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

McpInvocationContext.ts

268 lines10.0 KB

1import {
2 type AuthMcpClientAccess,
3 type EnvironmentId,
4 McpCapabilityUnavailableError,
5 OrchestratorMcpFailure,
6 PreviewAutomationUnavailableError,
7 type ProviderInstanceId,
8 type ProviderInteractionMode,
9 type OrchestrationV2LinkedSender,
10 type RuntimeMode,
11 type ThreadId,
12} from "@t3tools/contracts";
13import * as Context from "effect/Context";
14import * as Effect from "effect/Effect";
15import * as Fiber from "effect/Fiber";
16import { formatThreadLink, hostedThreadLink } from "@t3tools/shared/threadLinks";
17​
18const ALL_MCP_CAPABILITIES = [
19 "preview",
20 "orchestration",
21 "worktree",
22 "device",
23 "pull-requests",
24 "issues",
25] as const;
26export type McpCapability = (typeof ALL_MCP_CAPABILITIES)[number];
27​
28export interface McpThreadCaller {
29 readonly threadId: ThreadId;
30 readonly providerSessionId: string;
31 readonly providerInstanceId: ProviderInstanceId;
32 /** A delegated child task; its parent owns the work it hands back. */
33 readonly subagent?: boolean;
35​
36export interface McpClientCaller {
37 readonly sessionId: string;
38 readonly label: string;
39 readonly access: AuthMcpClientAccess;
40 /**
41 * Another T3 Code environment's peer link. What it starts here carries its
42 * session as `linkOrigin`, and it changes only that work (`linkOrigin.ts`).
43 */
44 readonly linked?: boolean | undefined;
45 /**
46 * Narrower modes the client asked for on this request (`T3-Mode-Limit`):
47 * another environment passing on the limits of the agent it calls for.
48 */
49 readonly narrowedTo?: ClientModes | undefined;
50 /** A linked environment's thread this request is made for (`T3-Sender-Thread`). */
51 readonly senderThread?: OrchestrationV2LinkedSender | undefined;
52 /** An outside client's thread links go through this hosted app, as Copy thread's do. */
53 readonly hostedAppUrl?: string | undefined;
55​
56/**
57 * `T3-Mode-Limit: <runtimeMode>/<interactionMode>` lets an OAuth client cap
58 * a request below what it was approved with: another environment passes on
59 * the limits of the agent it calls for. It can only narrow (see
60 * `clientModeCeiling`), so a client gains nothing by sending a broad one.
61 */
62export const MODE_LIMIT_HEADER = "t3-mode-limit";
63​
64/**
65 * `T3-Sender-Thread: <environmentId>/<threadId>/<title>`, each URI-encoded: the
66 * thread another environment makes a request for, so what it sends here can name
67 * it. Read only from a linked client.
68 */
69export const SENDER_THREAD_HEADER = "t3-sender-thread";
70​
71export interface ClientModes {
72 readonly runtimeMode: RuntimeMode;
73 readonly interactionMode: ProviderInteractionMode;
75​
76const runtimeModeRank: Record<RuntimeMode, number> = {
77 "approval-required": 0,
78 "auto-accept-edits": 1,
79 auto: 2,
80 "full-access": 3,
81};
82const interactionModeRank: Record<ProviderInteractionMode, number> = { plan: 0, default: 1 };
83​
84/**
85 * The modes a client caller's writes are capped at: what it was approved
86 * with, narrowed by what it asked for on this request. A read-only client
87 * never reaches a write (`McpToolAccess` refuses it first), so it maps to the
88 * lowest runtime mode rather than to nothing.
89 */
90export const clientModeCeiling = (client: McpClientCaller | undefined): ClientModes => {
91 const approved: ClientModes = {
92 runtimeMode:
93 client === undefined || client.access === "read-only" ? "approval-required" : client.access,
94 interactionMode: "default",
95 };
96 const asked = client?.narrowedTo;
97 if (asked === undefined) return approved;
98 return {
99 runtimeMode:
100 runtimeModeRank[asked.runtimeMode] < runtimeModeRank[approved.runtimeMode]
101 ? asked.runtimeMode
102 : approved.runtimeMode,
103 interactionMode:
104 interactionModeRank[asked.interactionMode] < interactionModeRank[approved.interactionMode]
105 ? asked.interactionMode
106 : approved.interactionMode,
107 };
108};
109​
110/**
111 * A client approved above an administrator's runtime-mode ceiling acts as if it had narrowed
112 * itself to the ceiling, so what it starts and schedules is not refused for a mode it never chose.
113 */
114export const withRuntimeModeCeiling = (
115 scope: McpInvocationScope,
116 ceiling: RuntimeMode | undefined,
117): McpInvocationScope => {
118 if (ceiling === undefined || scope.client === undefined) return scope;
119 const asked = scope.client.narrowedTo;
120 return {
121 ...scope,
122 client: {
123 ...scope.client,
124 narrowedTo: {
125 runtimeMode:
126 asked !== undefined && runtimeModeRank[asked.runtimeMode] < runtimeModeRank[ceiling]
127 ? asked.runtimeMode
128 : ceiling,
129 interactionMode: asked?.interactionMode ?? "default",
130 },
131 },
132 };
133};
134​
135/** Thread callers default to their own thread; client callers need thread for tools that act as the caller. */
136export interface McpInvocationScope {
137 readonly environmentId: EnvironmentId;
138 readonly capabilities: ReadonlySet<McpCapability>;
139 readonly issuedAt: number;
140 readonly requestNamespace: string;
141 readonly thread: McpThreadCaller | undefined;
142 readonly client: McpClientCaller | undefined;
143 /** False while the Linked environments beta is off here; `/mcp` reads it per request. */
144 readonly linkedEnvironments?: boolean;
145 /**
146 * The origin this `/mcp` request reached, e.g. a T3 Connect tunnel. Hosted clients cannot
147 * see the URL they were configured with, so links they must fetch carry it. Unset in-process.
148 */
149 readonly origin?: string | undefined;
150 /** False when the calling thread's project is on no forge T3 reads; `/mcp` reads it per request. */
151 readonly forge?: boolean;
153​
154/**
155 * T3 Code renders `t3-thread://` links as thread chips. Other MCP clients cannot open them, so
156 * they get the hosted link Copy thread copies, which opens the thread in either app or a browser.
157 * A known `title` labels the chip for clients that cannot load this environment's threads.
158 */
159export const threadLinkFor = (
160 scope: Pick<McpInvocationScope, "environmentId" | "client">,
161 threadId: ThreadId,
162 title?: string,
163): string => {
164 const hostedAppUrl = scope.client?.hostedAppUrl;
165 const ref = { environmentId: scope.environmentId, threadId };
166 return hostedAppUrl === undefined
167 ? formatThreadLink(ref, title)
168 : hostedThreadLink(ref, hostedAppUrl);
169};
170​
171export class McpInvocationContext extends Context.Service<
172 McpInvocationContext,
173 McpInvocationScope
174>()("t3/mcp/McpInvocationContext") {}
175​
176/**
177 * `McpSchema.EnabledWhen` for tools a delegated child must not see or call.
178 * EnabledWhen only receives the MCP client profile, so read the T3 caller from the request fiber.
179 */
180export const hiddenFromSubagents = (): boolean => {
181 const fiber = Fiber.getCurrent();
182 const scope = fiber && Context.getOrUndefined(fiber.context, McpInvocationContext);
183 return scope?.thread?.subagent !== true;
184};
185​
186/**
187 * `McpSchema.EnabledWhen` for tools that act as the calling thread: a client
188 * from outside has none. Discovery only; `McpToolAccess` still refuses the
189 * call, and `toLayer` requires this on every thread-bound declaration.
190 */
191export const hiddenFromOutsideClients = (): boolean => {
192 const fiber = Fiber.getCurrent();
193 const scope = fiber && Context.getOrUndefined(fiber.context, McpInvocationContext);
194 return scope === undefined || scope.thread !== undefined;
195};
196​
197/** `McpSchema.EnabledWhen` for tools that only serve links, hidden while the beta is off. */
198export const hiddenWhileLinksOff = (): boolean => {
199 const fiber = Fiber.getCurrent();
200 const scope = fiber && Context.getOrUndefined(fiber.context, McpInvocationContext);
201 return scope?.linkedEnvironments !== false;
202};
203​
204/** `McpSchema.EnabledWhen` for tools that act on the thread's forge, hidden where it has none. */
205export const hiddenWithoutForge = (): boolean => {
206 const fiber = Fiber.getCurrent();
207 const scope = fiber && Context.getOrUndefined(fiber.context, McpInvocationContext);
208 return scope?.forge !== false;
209};
210​
211export type McpCapabilityError<C extends McpCapability> = C extends "preview"
212 ? PreviewAutomationUnavailableError
213 : McpCapabilityUnavailableError;
214​
215const missingCapability = (
216 invocation: McpInvocationScope,
217 capability: McpCapability,
218): PreviewAutomationUnavailableError | McpCapabilityUnavailableError => {
219 const fields = {
220 environmentId: invocation.environmentId,
221 ...(invocation.thread === undefined
222 ? {}
223 : {
224 threadId: invocation.thread.threadId,
225 providerSessionId: invocation.thread.providerSessionId,
226 providerInstanceId: invocation.thread.providerInstanceId,
227 }),
228 };
229 return capability === "preview"
230 ? new PreviewAutomationUnavailableError({ capability, ...fields })
231 : new McpCapabilityUnavailableError({ capability, ...fields });
232};
233​
234export const requireMcpCapability = <const C extends McpCapability>(
235 capability: C,
236): Effect.Effect<McpInvocationScope, McpCapabilityError<C>, McpInvocationContext> =>
237 McpInvocationContext.pipe(
238 Effect.filterOrFail(
239 (invocation) => invocation.capabilities.has(capability),
240 (invocation) => missingCapability(invocation, capability) as McpCapabilityError<C>,
241 ),
242 Effect.withSpan("mcp.requireCapability"),
243 );
244​
245export const requireThreadMcpCapability = <const C extends "preview" | "device">(
246 capability: C,
247): Effect.Effect<McpThreadInvocationScope, McpCapabilityError<C>, McpInvocationContext> =>
248 McpInvocationContext.pipe(
249 Effect.filterOrFail(
250 (invocation): invocation is McpThreadInvocationScope =>
251 invocation.capabilities.has(capability) && invocation.thread !== undefined,
252 (invocation) => missingCapability(invocation, capability) as McpCapabilityError<C>,
253 ),
254 Effect.withSpan("mcp.requireCapability"),
255 );
256​
257const threadCallerRequired = (operation: string) =>
258 new OrchestratorMcpFailure({
259 code: "thread_credential_required",
260 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.`,
261 });
262​
263export type McpThreadInvocationScope = McpInvocationScope & { readonly thread: McpThreadCaller };
264​
265export const requireThreadScope = (scope: McpInvocationScope, operation: string) =>
266 scope.thread === undefined
267 ? Effect.fail(threadCallerRequired(operation))
268 : Effect.succeed(scope as McpThreadInvocationScope);