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";
15
16const ALL_MCP_CAPABILITIES = [
17 "preview",
18 "orchestration",
19 "worktree",
20 "device",
21 "pull-requests",
22] as const;
23export type McpCapability = (typeof ALL_MCP_CAPABILITIES)[number];
24
25export interface McpThreadCaller {
26 readonly threadId: ThreadId;
27 readonly providerSessionId: string;
28 readonly providerInstanceId: ProviderInstanceId;
29 /** A delegated child task; its parent owns the work it hands back. */
30 readonly subagent?: boolean;
31}
32
33export interface McpClientCaller {
34 readonly sessionId: string;
35 readonly label: string;
36 readonly access: AuthMcpClientAccess;
37 /**
38 * Another T3 Code environment's peer link. What it starts here carries its
39 * session as `linkOrigin`, and it changes only that work (`linkOrigin.ts`).
40 */
41 readonly linked?: boolean | undefined;
42 /**
43 * Narrower modes the client asked for on this request (`T3-Mode-Limit`):
44 * another environment passing on the limits of the agent it calls for.
45 */
46 readonly narrowedTo?: ClientModes | undefined;
47}
48
49/**
50 * `T3-Mode-Limit: <runtimeMode>/<interactionMode>` lets an OAuth client cap
51 * a request below what it was approved with: another environment passes on
52 * the limits of the agent it calls for. It can only narrow (see
53 * `clientModeCeiling`), so a client gains nothing by sending a broad one.
54 */
55export const MODE_LIMIT_HEADER = "t3-mode-limit";
56
57export interface ClientModes {
58 readonly runtimeMode: RuntimeMode;
59 readonly interactionMode: ProviderInteractionMode;
60}
61
62const runtimeModeRank: Record<RuntimeMode, number> = {
63 "approval-required": 0,
64 "auto-accept-edits": 1,
65 auto: 2,
66 "full-access": 3,
67};
68const interactionModeRank: Record<ProviderInteractionMode, number> = { plan: 0, default: 1 };
69
70/**
71 * The modes a client caller's writes are capped at: what it was approved
72 * with, narrowed by what it asked for on this request. A read-only client
73 * never reaches a write (`McpToolAccess` refuses it first), so it maps to the
74 * lowest runtime mode rather than to nothing.
75 */
76export const clientModeCeiling = (client: McpClientCaller | undefined): ClientModes => {
77 const approved: ClientModes = {
78 runtimeMode:
79 client === undefined || client.access === "read-only" ? "approval-required" : client.access,
80 interactionMode: "default",
81 };
82 const asked = client?.narrowedTo;
83 if (asked === undefined) return approved;
84 return {
85 runtimeMode:
86 runtimeModeRank[asked.runtimeMode] < runtimeModeRank[approved.runtimeMode]
87 ? asked.runtimeMode
88 : approved.runtimeMode,
89 interactionMode:
90 interactionModeRank[asked.interactionMode] < interactionModeRank[approved.interactionMode]
91 ? asked.interactionMode
92 : approved.interactionMode,
93 };
94};
95
96/** Thread callers default to their own thread; client callers need thread for tools that act as the caller. */
97export interface McpInvocationScope {
98 readonly environmentId: EnvironmentId;
99 readonly capabilities: ReadonlySet<McpCapability>;
100 readonly issuedAt: number;
101 readonly requestNamespace: string;
102 readonly thread: McpThreadCaller | undefined;
103 readonly client: McpClientCaller | undefined;
104}
105
106export class McpInvocationContext extends Context.Service<
107 McpInvocationContext,
108 McpInvocationScope
109>()("t3/mcp/McpInvocationContext") {}
110
111/**
112 * `McpSchema.EnabledWhen` for tools a delegated child must not see or call.
113 * EnabledWhen only receives the MCP client profile, so read the T3 caller from the request fiber.
114 */
115export const hiddenFromSubagents = (): boolean => {
116 const fiber = Fiber.getCurrent();
117 const scope = fiber && Context.getOrUndefined(fiber.context, McpInvocationContext);
118 return scope?.thread?.subagent !== true;
119};
120
121export type McpCapabilityError<C extends McpCapability> = C extends "preview"
122 ? PreviewAutomationUnavailableError
123 : McpCapabilityUnavailableError;
124
125const missingCapability = (
126 invocation: McpInvocationScope,
127 capability: McpCapability,
128): PreviewAutomationUnavailableError | McpCapabilityUnavailableError => {
129 const fields = {
130 environmentId: invocation.environmentId,
131 ...(invocation.thread === undefined
132 ? {}
133 : {
134 threadId: invocation.thread.threadId,
135 providerSessionId: invocation.thread.providerSessionId,
136 providerInstanceId: invocation.thread.providerInstanceId,
137 }),
138 };
139 return capability === "preview"
140 ? new PreviewAutomationUnavailableError({ capability, ...fields })
141 : new McpCapabilityUnavailableError({ capability, ...fields });
142};
143
144export const requireMcpCapability = <const C extends McpCapability>(
145 capability: C,
146): Effect.Effect<McpInvocationScope, McpCapabilityError<C>, McpInvocationContext> =>
147 McpInvocationContext.pipe(
148 Effect.filterOrFail(
149 (invocation) => invocation.capabilities.has(capability),
150 (invocation) => missingCapability(invocation, capability) as McpCapabilityError<C>,
151 ),
152 Effect.withSpan("mcp.requireCapability"),
153 );
154
155export const requireThreadMcpCapability = <const C extends "preview" | "device">(
156 capability: C,
157): Effect.Effect<McpThreadInvocationScope, McpCapabilityError<C>, McpInvocationContext> =>
158 McpInvocationContext.pipe(
159 Effect.filterOrFail(
160 (invocation): invocation is McpThreadInvocationScope =>
161 invocation.capabilities.has(capability) && invocation.thread !== undefined,
162 (invocation) => missingCapability(invocation, capability) as McpCapabilityError<C>,
163 ),
164 Effect.withSpan("mcp.requireCapability"),
165 );
166
167const threadCallerRequired = (operation: string) =>
168 new OrchestratorMcpFailure({
169 code: "thread_credential_required",
170 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.`,
171 });
172
173export type McpThreadInvocationScope = McpInvocationScope & { readonly thread: McpThreadCaller };
174
175export const requireThreadScope = (scope: McpInvocationScope, operation: string) =>
176 scope.thread === undefined
177 ? Effect.fail(threadCallerRequired(operation))
178 : Effect.succeed(scope as McpThreadInvocationScope);