Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

McpInvocationContext.ts

187 lines6.8 KB

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;
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;
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;
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 /** False while the Linked environments beta is off here; `/mcp` reads it per request. */
105 readonly linkedEnvironments?: boolean;
107​
108export class McpInvocationContext extends Context.Service<
109 McpInvocationContext,
110 McpInvocationScope
111>()("t3/mcp/McpInvocationContext") {}
112​
113/**
114 * `McpSchema.EnabledWhen` for tools a delegated child must not see or call.
115 * EnabledWhen only receives the MCP client profile, so read the T3 caller from the request fiber.
116 */
117export const hiddenFromSubagents = (): boolean => {
118 const fiber = Fiber.getCurrent();
119 const scope = fiber && Context.getOrUndefined(fiber.context, McpInvocationContext);
120 return scope?.thread?.subagent !== true;
121};
122​
123/** `McpSchema.EnabledWhen` for tools that only serve links, hidden while the beta is off. */
124export const hiddenWhileLinksOff = (): boolean => {
125 const fiber = Fiber.getCurrent();
126 const scope = fiber && Context.getOrUndefined(fiber.context, McpInvocationContext);
127 return scope?.linkedEnvironments !== false;
128};
129​
130export type McpCapabilityError<C extends McpCapability> = C extends "preview"
131 ? PreviewAutomationUnavailableError
132 : McpCapabilityUnavailableError;
133​
134const missingCapability = (
135 invocation: McpInvocationScope,
136 capability: McpCapability,
137): PreviewAutomationUnavailableError | McpCapabilityUnavailableError => {
138 const fields = {
139 environmentId: invocation.environmentId,
140 ...(invocation.thread === undefined
141 ? {}
142 : {
143 threadId: invocation.thread.threadId,
144 providerSessionId: invocation.thread.providerSessionId,
145 providerInstanceId: invocation.thread.providerInstanceId,
146 }),
147 };
148 return capability === "preview"
149 ? new PreviewAutomationUnavailableError({ capability, ...fields })
150 : new McpCapabilityUnavailableError({ capability, ...fields });
151};
152​
153export const requireMcpCapability = <const C extends McpCapability>(
154 capability: C,
155): Effect.Effect<McpInvocationScope, McpCapabilityError<C>, McpInvocationContext> =>
156 McpInvocationContext.pipe(
157 Effect.filterOrFail(
158 (invocation) => invocation.capabilities.has(capability),
159 (invocation) => missingCapability(invocation, capability) as McpCapabilityError<C>,
160 ),
161 Effect.withSpan("mcp.requireCapability"),
162 );
163​
164export const requireThreadMcpCapability = <const C extends "preview" | "device">(
165 capability: C,
166): Effect.Effect<McpThreadInvocationScope, McpCapabilityError<C>, McpInvocationContext> =>
167 McpInvocationContext.pipe(
168 Effect.filterOrFail(
169 (invocation): invocation is McpThreadInvocationScope =>
170 invocation.capabilities.has(capability) && invocation.thread !== undefined,
171 (invocation) => missingCapability(invocation, capability) as McpCapabilityError<C>,
172 ),
173 Effect.withSpan("mcp.requireCapability"),
174 );
175​
176const threadCallerRequired = (operation: string) =>
177 new OrchestratorMcpFailure({
178 code: "thread_credential_required",
179 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.`,
180 });
181​
182export type McpThreadInvocationScope = McpInvocationScope & { readonly thread: McpThreadCaller };
183​
184export const requireThreadScope = (scope: McpInvocationScope, operation: string) =>
185 scope.thread === undefined
186 ? Effect.fail(threadCallerRequired(operation))
187 : Effect.succeed(scope as McpThreadInvocationScope);