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