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 } 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 /** The origin an outside client reached; its thread links open the web app there. */
49 readonly webOrigin?: 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 a web URL on the origin they reached instead.
139 */
140export const threadLinkFor = (
141 scope: Pick<McpInvocationScope, "environmentId" | "client">,
142 threadId: ThreadId,
143): string => {
144 const origin = scope.client?.webOrigin;
145 return origin === undefined
146 ? formatThreadLink({ environmentId: scope.environmentId, threadId })
147 : `${origin}/${encodeURIComponent(scope.environmentId)}/${encodeURIComponent(threadId)}`;
148};
149
150export class McpInvocationContext extends Context.Service<
151 McpInvocationContext,
152 McpInvocationScope
153>()("t3/mcp/McpInvocationContext") {}
154
155/**
156 * `McpSchema.EnabledWhen` for tools a delegated child must not see or call.
157 * EnabledWhen only receives the MCP client profile, so read the T3 caller from the request fiber.
158 */
159export const hiddenFromSubagents = (): boolean => {
160 const fiber = Fiber.getCurrent();
161 const scope = fiber && Context.getOrUndefined(fiber.context, McpInvocationContext);
162 return scope?.thread?.subagent !== true;
163};
164
165/** `McpSchema.EnabledWhen` for tools that only serve links, hidden while the beta is off. */
166export const hiddenWhileLinksOff = (): boolean => {
167 const fiber = Fiber.getCurrent();
168 const scope = fiber && Context.getOrUndefined(fiber.context, McpInvocationContext);
169 return scope?.linkedEnvironments !== false;
170};
171
172export type McpCapabilityError<C extends McpCapability> = C extends "preview"
173 ? PreviewAutomationUnavailableError
174 : McpCapabilityUnavailableError;
175
176const missingCapability = (
177 invocation: McpInvocationScope,
178 capability: McpCapability,
179): PreviewAutomationUnavailableError | McpCapabilityUnavailableError => {
180 const fields = {
181 environmentId: invocation.environmentId,
182 ...(invocation.thread === undefined
183 ? {}
184 : {
185 threadId: invocation.thread.threadId,
186 providerSessionId: invocation.thread.providerSessionId,
187 providerInstanceId: invocation.thread.providerInstanceId,
188 }),
189 };
190 return capability === "preview"
191 ? new PreviewAutomationUnavailableError({ capability, ...fields })
192 : new McpCapabilityUnavailableError({ capability, ...fields });
193};
194
195export const requireMcpCapability = <const C extends McpCapability>(
196 capability: C,
197): Effect.Effect<McpInvocationScope, McpCapabilityError<C>, McpInvocationContext> =>
198 McpInvocationContext.pipe(
199 Effect.filterOrFail(
200 (invocation) => invocation.capabilities.has(capability),
201 (invocation) => missingCapability(invocation, capability) as McpCapabilityError<C>,
202 ),
203 Effect.withSpan("mcp.requireCapability"),
204 );
205
206export const requireThreadMcpCapability = <const C extends "preview" | "device">(
207 capability: C,
208): Effect.Effect<McpThreadInvocationScope, McpCapabilityError<C>, McpInvocationContext> =>
209 McpInvocationContext.pipe(
210 Effect.filterOrFail(
211 (invocation): invocation is McpThreadInvocationScope =>
212 invocation.capabilities.has(capability) && invocation.thread !== undefined,
213 (invocation) => missingCapability(invocation, capability) as McpCapabilityError<C>,
214 ),
215 Effect.withSpan("mcp.requireCapability"),
216 );
217
218const threadCallerRequired = (operation: string) =>
219 new OrchestratorMcpFailure({
220 code: "thread_credential_required",
221 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.`,
222 });
223
224export type McpThreadInvocationScope = McpInvocationScope & { readonly thread: McpThreadCaller };
225
226export const requireThreadScope = (scope: McpInvocationScope, operation: string) =>
227 scope.thread === undefined
228 ? Effect.fail(threadCallerRequired(operation))
229 : Effect.succeed(scope as McpThreadInvocationScope);