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/** Thread callers default to their own thread; client callers need thread for tools that act as the caller. */
100export interface McpInvocationScope {
101 readonly environmentId: EnvironmentId;
102 readonly capabilities: ReadonlySet<McpCapability>;
103 readonly issuedAt: number;
104 readonly requestNamespace: string;
105 readonly thread: McpThreadCaller | undefined;
106 readonly client: McpClientCaller | undefined;
107 /** False while the Linked environments beta is off here; `/mcp` reads it per request. */
108 readonly linkedEnvironments?: boolean;
109}
110
111/**
112 * T3 Code renders `t3-thread://` links as thread chips. Other MCP clients cannot open them, so
113 * they get a web URL on the origin they reached instead.
114 */
115export const threadLinkFor = (
116 scope: Pick<McpInvocationScope, "environmentId" | "client">,
117 threadId: ThreadId,
118): string => {
119 const origin = scope.client?.webOrigin;
120 return origin === undefined
121 ? formatThreadLink({ environmentId: scope.environmentId, threadId })
122 : `${origin}/${encodeURIComponent(scope.environmentId)}/${encodeURIComponent(threadId)}`;
123};
124
125export class McpInvocationContext extends Context.Service<
126 McpInvocationContext,
127 McpInvocationScope
128>()("t3/mcp/McpInvocationContext") {}
129
130/**
131 * `McpSchema.EnabledWhen` for tools a delegated child must not see or call.
132 * EnabledWhen only receives the MCP client profile, so read the T3 caller from the request fiber.
133 */
134export const hiddenFromSubagents = (): boolean => {
135 const fiber = Fiber.getCurrent();
136 const scope = fiber && Context.getOrUndefined(fiber.context, McpInvocationContext);
137 return scope?.thread?.subagent !== true;
138};
139
140/** `McpSchema.EnabledWhen` for tools that only serve links, hidden while the beta is off. */
141export const hiddenWhileLinksOff = (): boolean => {
142 const fiber = Fiber.getCurrent();
143 const scope = fiber && Context.getOrUndefined(fiber.context, McpInvocationContext);
144 return scope?.linkedEnvironments !== false;
145};
146
147export type McpCapabilityError<C extends McpCapability> = C extends "preview"
148 ? PreviewAutomationUnavailableError
149 : McpCapabilityUnavailableError;
150
151const missingCapability = (
152 invocation: McpInvocationScope,
153 capability: McpCapability,
154): PreviewAutomationUnavailableError | McpCapabilityUnavailableError => {
155 const fields = {
156 environmentId: invocation.environmentId,
157 ...(invocation.thread === undefined
158 ? {}
159 : {
160 threadId: invocation.thread.threadId,
161 providerSessionId: invocation.thread.providerSessionId,
162 providerInstanceId: invocation.thread.providerInstanceId,
163 }),
164 };
165 return capability === "preview"
166 ? new PreviewAutomationUnavailableError({ capability, ...fields })
167 : new McpCapabilityUnavailableError({ capability, ...fields });
168};
169
170export const requireMcpCapability = <const C extends McpCapability>(
171 capability: C,
172): Effect.Effect<McpInvocationScope, McpCapabilityError<C>, McpInvocationContext> =>
173 McpInvocationContext.pipe(
174 Effect.filterOrFail(
175 (invocation) => invocation.capabilities.has(capability),
176 (invocation) => missingCapability(invocation, capability) as McpCapabilityError<C>,
177 ),
178 Effect.withSpan("mcp.requireCapability"),
179 );
180
181export const requireThreadMcpCapability = <const C extends "preview" | "device">(
182 capability: C,
183): Effect.Effect<McpThreadInvocationScope, McpCapabilityError<C>, McpInvocationContext> =>
184 McpInvocationContext.pipe(
185 Effect.filterOrFail(
186 (invocation): invocation is McpThreadInvocationScope =>
187 invocation.capabilities.has(capability) && invocation.thread !== undefined,
188 (invocation) => missingCapability(invocation, capability) as McpCapabilityError<C>,
189 ),
190 Effect.withSpan("mcp.requireCapability"),
191 );
192
193const threadCallerRequired = (operation: string) =>
194 new OrchestratorMcpFailure({
195 code: "thread_credential_required",
196 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.`,
197 });
198
199export type McpThreadInvocationScope = McpInvocationScope & { readonly thread: McpThreadCaller };
200
201export const requireThreadScope = (scope: McpInvocationScope, operation: string) =>
202 scope.thread === undefined
203 ? Effect.fail(threadCallerRequired(operation))
204 : Effect.succeed(scope as McpThreadInvocationScope);