Open History to see the last commit
1import {
2 type AuthMcpClientAccess,
3 type EnvironmentId,
4 McpCapabilityUnavailableError,
5 OrchestratorMcpFailure,
6 PreviewAutomationUnavailableError,
7 type ProviderInstanceId,
8 type ProviderInteractionMode,
9 type OrchestrationV2LinkedSender,
10 type RuntimeMode,
11 type ThreadId,
12} from "@t3tools/contracts";
13import * as Context from "effect/Context";
14import type * as DateTime from "effect/DateTime";
15import * as Effect from "effect/Effect";
16import * as Fiber from "effect/Fiber";
17import { formatThreadLink, hostedThreadLink } from "@t3tools/shared/threadLinks";
18
19const ALL_MCP_CAPABILITIES = [
20 "preview",
21 "orchestration",
22 "worktree",
23 "device",
24 "pull-requests",
25 "issues",
26 "background-wait",
27] as const;
28export type McpCapability = (typeof ALL_MCP_CAPABILITIES)[number];
29
30export interface McpThreadCaller {
31 readonly threadId: ThreadId;
32 readonly providerSessionId: string;
33 readonly providerInstanceId: ProviderInstanceId;
34 /** A delegated child task; its parent owns the work it hands back. */
35 readonly subagent?: boolean;
36}
37
38export interface McpClientCaller {
39 readonly sessionId: string;
40 readonly label: string;
41 readonly access: AuthMcpClientAccess;
42 /**
43 * Another T3 Code environment's peer link. What it starts here carries its
44 * session as `linkOrigin`, and it changes only that work (`linkOrigin.ts`).
45 */
46 readonly linked?: boolean | undefined;
47 /** When a peer link's session ends unless it is used again, answered as `T3-Link-Expires-At`. */
48 readonly linkExpiresAt?: DateTime.Utc | undefined;
49 /**
50 * Narrower modes the client asked for on this request (`T3-Mode-Limit`):
51 * another environment passing on the limits of the agent it calls for.
52 */
53 readonly narrowedTo?: ClientModes | undefined;
54 /** A linked environment's thread this request is made for (`T3-Sender-Thread`). */
55 readonly senderThread?: OrchestrationV2LinkedSender | undefined;
56 /** An outside client's thread links go through this hosted app, as Copy thread's do. */
57 readonly hostedAppUrl?: string | undefined;
58}
59
60/**
61 * `T3-Mode-Limit: <runtimeMode>/<interactionMode>` lets an OAuth client cap
62 * a request below what it was approved with: another environment passes on
63 * the limits of the agent it calls for. It can only narrow (see
64 * `clientModeCeiling`), so a client gains nothing by sending a broad one.
65 */
66export const MODE_LIMIT_HEADER = "t3-mode-limit";
67
68/**
69 * `T3-Link-Expires-At: <ISO time>` answers a peer link's request with when its
70 * session now ends. Using a link renews it, so the linking side keeps this.
71 */
72export const LINK_EXPIRES_AT_HEADER = "t3-link-expires-at";
73
74/**
75 * `T3-Sender-Thread: <environmentId>/<threadId>/<title>`, each URI-encoded: the
76 * thread another environment makes a request for, so what it sends here can name
77 * it. Read only from a linked client.
78 */
79export const SENDER_THREAD_HEADER = "t3-sender-thread";
80
81export interface ClientModes {
82 readonly runtimeMode: RuntimeMode;
83 readonly interactionMode: ProviderInteractionMode;
84}
85
86const runtimeModeRank: Record<RuntimeMode, number> = {
87 "approval-required": 0,
88 "auto-accept-edits": 1,
89 auto: 2,
90 "full-access": 3,
91};
92const interactionModeRank: Record<ProviderInteractionMode, number> = { plan: 0, default: 1 };
93
94/**
95 * The modes a client caller's writes are capped at: what it was approved
96 * with, narrowed by what it asked for on this request. A read-only client
97 * never reaches a write (`McpToolAccess` refuses it first), so it maps to the
98 * lowest runtime mode rather than to nothing.
99 */
100export const clientModeCeiling = (client: McpClientCaller | undefined): ClientModes => {
101 const approved: ClientModes = {
102 runtimeMode:
103 client === undefined || client.access === "read-only" ? "approval-required" : client.access,
104 interactionMode: "default",
105 };
106 const asked = client?.narrowedTo;
107 if (asked === undefined) return approved;
108 return {
109 runtimeMode:
110 runtimeModeRank[asked.runtimeMode] < runtimeModeRank[approved.runtimeMode]
111 ? asked.runtimeMode
112 : approved.runtimeMode,
113 interactionMode:
114 interactionModeRank[asked.interactionMode] < interactionModeRank[approved.interactionMode]
115 ? asked.interactionMode
116 : approved.interactionMode,
117 };
118};
119
120/**
121 * A client approved above an administrator's runtime-mode ceiling acts as if it had narrowed
122 * itself to the ceiling, so what it starts and schedules is not refused for a mode it never chose.
123 */
124export const withRuntimeModeCeiling = (
125 scope: McpInvocationScope,
126 ceiling: RuntimeMode | undefined,
127): McpInvocationScope => {
128 if (ceiling === undefined || scope.client === undefined) return scope;
129 const asked = scope.client.narrowedTo;
130 return {
131 ...scope,
132 client: {
133 ...scope.client,
134 narrowedTo: {
135 runtimeMode:
136 asked !== undefined && runtimeModeRank[asked.runtimeMode] < runtimeModeRank[ceiling]
137 ? asked.runtimeMode
138 : ceiling,
139 interactionMode: asked?.interactionMode ?? "default",
140 },
141 },
142 };
143};
144
145/** Thread callers default to their own thread; client callers need thread for tools that act as the caller. */
146export interface McpInvocationScope {
147 readonly environmentId: EnvironmentId;
148 readonly capabilities: ReadonlySet<McpCapability>;
149 readonly issuedAt: number;
150 readonly requestNamespace: string;
151 readonly thread: McpThreadCaller | undefined;
152 readonly client: McpClientCaller | undefined;
153 /** False while the Linked environments beta is off here; `/mcp` reads it per request. */
154 readonly linkedEnvironments?: boolean;
155 /**
156 * The origin this `/mcp` request reached, e.g. a T3 Connect tunnel. Hosted clients cannot
157 * see the URL they were configured with, so links they must fetch carry it. Unset in-process.
158 */
159 readonly origin?: string | undefined;
160 /** False when the calling thread's project is on no forge T3 reads; `/mcp` reads it per request. */
161 readonly forge?: boolean;
162}
163
164/**
165 * T3 Code renders `t3-thread://` links as thread chips. Other MCP clients cannot open them, so
166 * they get the hosted link Copy thread copies, which opens the thread in either app or a browser.
167 * A known `title` labels the chip for clients that cannot load this environment's threads.
168 */
169export const threadLinkFor = (
170 scope: Pick<McpInvocationScope, "environmentId" | "client">,
171 threadId: ThreadId,
172 title?: string,
173): string => {
174 const hostedAppUrl = scope.client?.hostedAppUrl;
175 const ref = { environmentId: scope.environmentId, threadId };
176 return hostedAppUrl === undefined
177 ? formatThreadLink(ref, title)
178 : hostedThreadLink(ref, hostedAppUrl);
179};
180
181export class McpInvocationContext extends Context.Service<
182 McpInvocationContext,
183 McpInvocationScope
184>()("t3/mcp/McpInvocationContext") {}
185
186/**
187 * `McpSchema.EnabledWhen` for tools a delegated child must not see or call.
188 * EnabledWhen only receives the MCP client profile, so read the T3 caller from the request fiber.
189 */
190export const hiddenFromSubagents = (): boolean => {
191 const fiber = Fiber.getCurrent();
192 const scope = fiber && Context.getOrUndefined(fiber.context, McpInvocationContext);
193 return scope?.thread?.subagent !== true;
194};
195
196/**
197 * `McpSchema.EnabledWhen` for tools that act as the calling thread: a client
198 * from outside has none. Discovery only; `McpToolAccess` still refuses the
199 * call, and `toLayer` requires this on every thread-bound declaration.
200 */
201export const hiddenFromOutsideClients = (): boolean => {
202 const fiber = Fiber.getCurrent();
203 const scope = fiber && Context.getOrUndefined(fiber.context, McpInvocationContext);
204 return scope === undefined || scope.thread !== undefined;
205};
206
207/** `hiddenFromOutsideClients`, and hidden from a thread whose provider cannot hold for background work. */
208export const hiddenWithoutBackgroundWait = (): boolean => {
209 const fiber = Fiber.getCurrent();
210 const scope = fiber && Context.getOrUndefined(fiber.context, McpInvocationContext);
211 return (
212 scope === undefined || (scope.thread !== undefined && scope.capabilities.has("background-wait"))
213 );
214};
215
216/** `McpSchema.EnabledWhen` for tools that only serve links, hidden while the beta is off. */
217export const hiddenWhileLinksOff = (): boolean => {
218 const fiber = Fiber.getCurrent();
219 const scope = fiber && Context.getOrUndefined(fiber.context, McpInvocationContext);
220 return scope?.linkedEnvironments !== false;
221};
222
223/** `McpSchema.EnabledWhen` for tools that act on the thread's forge, hidden where it has none. */
224export const hiddenWithoutForge = (): boolean => {
225 const fiber = Fiber.getCurrent();
226 const scope = fiber && Context.getOrUndefined(fiber.context, McpInvocationContext);
227 return scope?.forge !== false;
228};
229
230export type McpCapabilityError<C extends McpCapability> = C extends "preview"
231 ? PreviewAutomationUnavailableError
232 : McpCapabilityUnavailableError;
233
234const missingCapability = (
235 invocation: McpInvocationScope,
236 capability: McpCapability,
237): PreviewAutomationUnavailableError | McpCapabilityUnavailableError => {
238 const fields = {
239 environmentId: invocation.environmentId,
240 ...(invocation.thread === undefined
241 ? {}
242 : {
243 threadId: invocation.thread.threadId,
244 providerSessionId: invocation.thread.providerSessionId,
245 providerInstanceId: invocation.thread.providerInstanceId,
246 }),
247 };
248 return capability === "preview"
249 ? new PreviewAutomationUnavailableError({ capability, ...fields })
250 : new McpCapabilityUnavailableError({ capability, ...fields });
251};
252
253export const requireMcpCapability = <const C extends McpCapability>(
254 capability: C,
255): Effect.Effect<McpInvocationScope, McpCapabilityError<C>, McpInvocationContext> =>
256 McpInvocationContext.pipe(
257 Effect.filterOrFail(
258 (invocation) => invocation.capabilities.has(capability),
259 (invocation) => missingCapability(invocation, capability) as McpCapabilityError<C>,
260 ),
261 Effect.withSpan("mcp.requireCapability"),
262 );
263
264export const requireThreadMcpCapability = <const C extends "preview" | "device">(
265 capability: C,
266): Effect.Effect<McpThreadInvocationScope, McpCapabilityError<C>, McpInvocationContext> =>
267 McpInvocationContext.pipe(
268 Effect.filterOrFail(
269 (invocation): invocation is McpThreadInvocationScope =>
270 invocation.capabilities.has(capability) && invocation.thread !== undefined,
271 (invocation) => missingCapability(invocation, capability) as McpCapabilityError<C>,
272 ),
273 Effect.withSpan("mcp.requireCapability"),
274 );
275
276const threadCallerRequired = (operation: string) =>
277 new OrchestratorMcpFailure({
278 code: "thread_credential_required",
279 message: `${operation} acts as the calling T3 thread, so it needs an agent running inside T3 Code. This MCP client signed in from outside a thread.`,
280 });
281
282export type McpThreadInvocationScope = McpInvocationScope & { readonly thread: McpThreadCaller };
283
284export const requireThreadScope = (scope: McpInvocationScope, operation: string) =>
285 scope.thread === undefined
286 ? Effect.fail(threadCallerRequired(operation))
287 : Effect.succeed(scope as McpThreadInvocationScope);