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

McpInvocationContext.ts

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