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 RuntimeMode,
10 type ThreadId,
11} from "@t3tools/contracts";
12import * as Context from "effect/Context";
13import * as Effect from "effect/Effect";
14import * as Fiber from "effect/Fiber";
15import { formatThreadLink, hostedThreadLink } from "@t3tools/shared/threadLinks";
16
17const ALL_MCP_CAPABILITIES = [
18 "preview",
19 "orchestration",
20 "worktree",
21 "device",
22 "pull-requests",
23] as const;
24export type McpCapability = (typeof ALL_MCP_CAPABILITIES)[number];
25
26export interface McpThreadCaller {
27 readonly threadId: ThreadId;
28 readonly providerSessionId: string;
29 readonly providerInstanceId: ProviderInstanceId;
30 /** A delegated child task; its parent owns the work it hands back. */
31 readonly subagent?: boolean;
32}
33
34export interface McpClientCaller {
35 readonly sessionId: string;
36 readonly label: string;
37 readonly access: AuthMcpClientAccess;
38 /**
39 * Another T3 Code environment's peer link. What it starts here carries its
40 * session as `linkOrigin`, and it changes only that work (`linkOrigin.ts`).
41 */
42 readonly linked?: boolean | undefined;
43 /**
44 * Narrower modes the client asked for on this request (`T3-Mode-Limit`):
45 * another environment passing on the limits of the agent it calls for.
46 */
47 readonly narrowedTo?: ClientModes | undefined;
48 /** An outside client's thread links go through this hosted app, as Copy thread's do. */
49 readonly hostedAppUrl?: string | undefined;
50}
51
52/**
53 * `T3-Mode-Limit: <runtimeMode>/<interactionMode>` lets an OAuth client cap
54 * a request below what it was approved with: another environment passes on
55 * the limits of the agent it calls for. It can only narrow (see
56 * `clientModeCeiling`), so a client gains nothing by sending a broad one.
57 */
58export const MODE_LIMIT_HEADER = "t3-mode-limit";
59
60export interface ClientModes {
61 readonly runtimeMode: RuntimeMode;
62 readonly interactionMode: ProviderInteractionMode;
63}
64
65const runtimeModeRank: Record<RuntimeMode, number> = {
66 "approval-required": 0,
67 "auto-accept-edits": 1,
68 auto: 2,
69 "full-access": 3,
70};
71const interactionModeRank: Record<ProviderInteractionMode, number> = { plan: 0, default: 1 };
72
73/**
74 * The modes a client caller's writes are capped at: what it was approved
75 * with, narrowed by what it asked for on this request. A read-only client
76 * never reaches a write (`McpToolAccess` refuses it first), so it maps to the
77 * lowest runtime mode rather than to nothing.
78 */
79export const clientModeCeiling = (client: McpClientCaller | undefined): ClientModes => {
80 const approved: ClientModes = {
81 runtimeMode:
82 client === undefined || client.access === "read-only" ? "approval-required" : client.access,
83 interactionMode: "default",
84 };
85 const asked = client?.narrowedTo;
86 if (asked === undefined) return approved;
87 return {
88 runtimeMode:
89 runtimeModeRank[asked.runtimeMode] < runtimeModeRank[approved.runtimeMode]
90 ? asked.runtimeMode
91 : approved.runtimeMode,
92 interactionMode:
93 interactionModeRank[asked.interactionMode] < interactionModeRank[approved.interactionMode]
94 ? asked.interactionMode
95 : approved.interactionMode,
96 };
97};
98
99/**
100 * A client approved above an administrator's runtime-mode ceiling acts as if it had narrowed
101 * itself to the ceiling, so what it starts and schedules is not refused for a mode it never chose.
102 */
103export const withRuntimeModeCeiling = (
104 scope: McpInvocationScope,
105 ceiling: RuntimeMode | undefined,
106): McpInvocationScope => {
107 if (ceiling === undefined || scope.client === undefined) return scope;
108 const asked = scope.client.narrowedTo;
109 return {
110 ...scope,
111 client: {
112 ...scope.client,
113 narrowedTo: {
114 runtimeMode:
115 asked !== undefined && runtimeModeRank[asked.runtimeMode] < runtimeModeRank[ceiling]
116 ? asked.runtimeMode
117 : ceiling,
118 interactionMode: asked?.interactionMode ?? "default",
119 },
120 },
121 };
122};
123
124/** Thread callers default to their own thread; client callers need thread for tools that act as the caller. */
125export interface McpInvocationScope {
126 readonly environmentId: EnvironmentId;
127 readonly capabilities: ReadonlySet<McpCapability>;
128 readonly issuedAt: number;
129 readonly requestNamespace: string;
130 readonly thread: McpThreadCaller | undefined;
131 readonly client: McpClientCaller | undefined;
132 /** False while the Linked environments beta is off here; `/mcp` reads it per request. */
133 readonly linkedEnvironments?: boolean;
134}
135
136/**
137 * T3 Code renders `t3-thread://` links as thread chips. Other MCP clients cannot open them, so
138 * they get the hosted link Copy thread copies, which opens the thread in either app or a browser.
139 * A known `title` labels the chip for clients that cannot load this environment's threads.
140 */
141export const threadLinkFor = (
142 scope: Pick<McpInvocationScope, "environmentId" | "client">,
143 threadId: ThreadId,
144 title?: string,
145): string => {
146 const hostedAppUrl = scope.client?.hostedAppUrl;
147 const ref = { environmentId: scope.environmentId, threadId };
148 return hostedAppUrl === undefined
149 ? formatThreadLink(ref, title)
150 : hostedThreadLink(ref, hostedAppUrl);
151};
152
153export class McpInvocationContext extends Context.Service<
154 McpInvocationContext,
155 McpInvocationScope
156>()("t3/mcp/McpInvocationContext") {}
157
158/**
159 * `McpSchema.EnabledWhen` for tools a delegated child must not see or call.
160 * EnabledWhen only receives the MCP client profile, so read the T3 caller from the request fiber.
161 */
162export const hiddenFromSubagents = (): boolean => {
163 const fiber = Fiber.getCurrent();
164 const scope = fiber && Context.getOrUndefined(fiber.context, McpInvocationContext);
165 return scope?.thread?.subagent !== true;
166};
167
168/** `McpSchema.EnabledWhen` for tools that only serve links, hidden while the beta is off. */
169export const hiddenWhileLinksOff = (): boolean => {
170 const fiber = Fiber.getCurrent();
171 const scope = fiber && Context.getOrUndefined(fiber.context, McpInvocationContext);
172 return scope?.linkedEnvironments !== false;
173};
174
175export type McpCapabilityError<C extends McpCapability> = C extends "preview"
176 ? PreviewAutomationUnavailableError
177 : McpCapabilityUnavailableError;
178
179const missingCapability = (
180 invocation: McpInvocationScope,
181 capability: McpCapability,
182): PreviewAutomationUnavailableError | McpCapabilityUnavailableError => {
183 const fields = {
184 environmentId: invocation.environmentId,
185 ...(invocation.thread === undefined
186 ? {}
187 : {
188 threadId: invocation.thread.threadId,
189 providerSessionId: invocation.thread.providerSessionId,
190 providerInstanceId: invocation.thread.providerInstanceId,
191 }),
192 };
193 return capability === "preview"
194 ? new PreviewAutomationUnavailableError({ capability, ...fields })
195 : new McpCapabilityUnavailableError({ capability, ...fields });
196};
197
198export const requireMcpCapability = <const C extends McpCapability>(
199 capability: C,
200): Effect.Effect<McpInvocationScope, McpCapabilityError<C>, McpInvocationContext> =>
201 McpInvocationContext.pipe(
202 Effect.filterOrFail(
203 (invocation) => invocation.capabilities.has(capability),
204 (invocation) => missingCapability(invocation, capability) as McpCapabilityError<C>,
205 ),
206 Effect.withSpan("mcp.requireCapability"),
207 );
208
209export const requireThreadMcpCapability = <const C extends "preview" | "device">(
210 capability: C,
211): Effect.Effect<McpThreadInvocationScope, McpCapabilityError<C>, McpInvocationContext> =>
212 McpInvocationContext.pipe(
213 Effect.filterOrFail(
214 (invocation): invocation is McpThreadInvocationScope =>
215 invocation.capabilities.has(capability) && invocation.thread !== undefined,
216 (invocation) => missingCapability(invocation, capability) as McpCapabilityError<C>,
217 ),
218 Effect.withSpan("mcp.requireCapability"),
219 );
220
221const threadCallerRequired = (operation: string) =>
222 new OrchestratorMcpFailure({
223 code: "thread_credential_required",
224 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.`,
225 });
226
227export type McpThreadInvocationScope = McpInvocationScope & { readonly thread: McpThreadCaller };
228
229export const requireThreadScope = (scope: McpInvocationScope, operation: string) =>
230 scope.thread === undefined
231 ? Effect.fail(threadCallerRequired(operation))
232 : Effect.succeed(scope as McpThreadInvocationScope);