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