Open History to see the last commit
1import {
2 type EnvironmentId,
3 type OrchestrationV2LinkOrigin,
4 OrchestratorMcpEnvironmentTarget,
5 OrchestratorMcpFailure,
6 type ProviderInteractionMode,
7 type RuntimeMode,
8 type ThreadId,
9} from "@t3tools/contracts";
10import * as Context from "effect/Context";
11import * as Effect from "effect/Effect";
12import * as Option from "effect/Option";
13import * as Predicate from "effect/Predicate";
14import * as Ref from "effect/Ref";
15import * as Struct from "effect/Struct";
16import type * as Layer from "effect/Layer";
17import type * as Scope from "effect/Scope";
18import { McpSchema } from "effect/ai";
19import type { Tool, Toolkit } from "effect/ai";
20
21import {
22 DispatchModeLimit,
23 type DispatchModeRefusal,
24} from "../orchestration-v2/DispatchModeLimit.ts";
25import * as PeerForwarding from "../peer/PeerForwarding.ts";
26import { assertNotLinked, assertSameLink, callerLinkOrigin } from "./linkOrigin.ts";
27import * as McpInvocationContext from "./McpInvocationContext.ts";
28import { resolveInteractionMode, resolveRuntimeMode } from "./delegatedTaskModes.ts";
29import {
30 assertFullAccess,
31 assertLiveCaller,
32 assertTargetWithinLimits,
33 type Caller,
34 loadCaller,
35 readCaller,
36 unavailable,
37} from "./threadAccess.ts";
38
39/** Private constructors only enforce types; the token also blocks runtime construction. */
40const builtHere: unique symbol = Symbol("t3/mcp/McpToolAccess/builtHere");
41
42const refuseOutsideConstruction = (token: symbol) => {
43 if (token !== builtHere) {
44 throw new TypeError("Only McpToolAccess builds MCP tool declarations and handler layers.");
45 }
46};
47
48let declare: <P, A, E, R>(
49 handle: (params: P) => Effect.Effect<A, E, R>,
50 remote: RemoteCheck<P> | undefined,
51 forwarded?: Forwarded<P, A, E, R>,
52) => Declaration<(params: P) => Effect.Effect<A, E, R>>;
53
54/**
55 * What a call bound for a linked environment checks here before it goes: the
56 * caller, not the thread or project it names, which live there and are
57 * checked there. `undefined` for tools that act as the calling thread itself.
58 */
59type RemoteCheck<P> = (
60 params: P,
61) => Effect.Effect<unknown, OrchestratorMcpFailure, Effect.Services<typeof writingCaller>>;
62let remoteCheckOf: <Handler>(declaration: Declaration<Handler>) => RemoteCheck<never> | undefined;
63
64/** What a call answered in a linked environment does here before it returns. */
65type Forwarded<P, A, E, R> = (
66 params: P,
67 environmentId: EnvironmentId,
68 result: A,
69) => Effect.Effect<A, E, R>;
70let forwardedOf: <Handler>(
71 declaration: Declaration<Handler>,
72) => Forwarded<never, unknown, unknown, unknown> | undefined;
73
74type CheckedHandlerOf<D> = D extends Declaration<infer Handler> ? Handler : never;
75
76interface CheckedHandler extends Struct.Lambda {
77 <Handler>(declaration: Declaration<Handler>): Handler;
78 readonly "~lambda.out": CheckedHandlerOf<this["~lambda.in"]>;
79}
80let checkedHandler: CheckedHandler;
81
82let handlersLayer: <Tools extends Record<string, Tool.Any>, EX, RX>(
83 layer: Layer.Layer<Tool.HandlersFor<Tools>, EX, RX>,
84) => HandlersLayer<Tools, EX, RX>;
85
86/** t3code/no-raw-mcp-registration confines Effect's unchecked registration API to McpHttpServer. */
87export class Declaration<out Handler> {
88 readonly #handle: Handler;
89 readonly #remote: RemoteCheck<never> | undefined;
90 readonly #forwarded: Forwarded<never, unknown, unknown, unknown> | undefined;
91 private constructor(
92 token: typeof builtHere,
93 handle: Handler,
94 remote: RemoteCheck<never> | undefined,
95 forwarded: Forwarded<never, unknown, unknown, unknown> | undefined,
96 ) {
97 refuseOutsideConstruction(token);
98 this.#handle = handle;
99 this.#remote = remote;
100 this.#forwarded = forwarded;
101 }
102 static {
103 declare = (handle, remote, forwarded) =>
104 new Declaration(
105 builtHere,
106 handle,
107 remote,
108 forwarded as Forwarded<never, unknown, unknown, unknown> | undefined,
109 );
110 checkedHandler = Struct.lambda<CheckedHandler>((declaration) => declaration.#handle);
111 remoteCheckOf = (declaration) => declaration.#remote;
112 forwardedOf = (declaration) => declaration.#forwarded;
113 }
114}
115
116const refuseReadOnlyClient = McpInvocationContext.McpInvocationContext.pipe(
117 Effect.flatMap((scope) =>
118 scope.client?.access === "read-only"
119 ? Effect.fail(
120 new OrchestratorMcpFailure({
121 code: "capability_denied",
122 message:
123 "This tool changes the environment, and this MCP client was approved for read-only access.",
124 }),
125 )
126 : Effect.void,
127 ),
128);
129
130const writingCaller = refuseReadOnlyClient.pipe(
131 Effect.andThen(loadCaller()),
132 Effect.tap(assertLiveCaller),
133);
134
135const orchestratingCaller = refuseReadOnlyClient.pipe(
136 Effect.andThen(readCaller()),
137 Effect.tap(assertLiveCaller),
138);
139
140const requireThreadCaller = McpInvocationContext.McpInvocationContext.pipe(
141 Effect.flatMap((scope) => McpInvocationContext.requireThreadScope(scope, "This tool")),
142);
143
144export const reads = <P, A, E, R>(handle: (params: P) => Effect.Effect<A, E, R>) =>
145 declare(
146 (params: P) => handle(params),
147 () => Effect.void,
148 );
149
150export const readsAsCaller = <P, A, E, R>(handle: (params: P) => Effect.Effect<A, E, R>) =>
151 declare((params: P) => requireThreadCaller.pipe(Effect.flatMap(() => handle(params))), undefined);
152
153export const actsAsCaller = <P, A, E, R>(handle: (params: P) => Effect.Effect<A, E, R>) =>
154 declare(
155 (params: P) =>
156 requireThreadCaller.pipe(
157 Effect.andThen(writingCaller),
158 Effect.flatMap(() => handle(params)),
159 ),
160 undefined,
161 );
162
163/**
164 * Changes something that belongs to no thread, such as a pending upload or a
165 * scheduled task. Work a linked environment started may not: none of it
166 * carries the link's origin, so none of it is that link's.
167 */
168export const writes = <P, A, E, R>(
169 handle: (params: P) => Effect.Effect<A, E, R>,
170 options?: {
171 /** Whether a linked caller may make it, as for uploads its own sends need. */
172 readonly linkedCallers?: "allowed";
173 },
174) =>
175 declare(
176 (params: P) =>
177 orchestratingCaller.pipe(
178 Effect.tap((caller) =>
179 options?.linkedCallers === "allowed"
180 ? Effect.void
181 : assertNotLinked(caller, "change this environment's scheduled tasks"),
182 ),
183 Effect.flatMap(() => handle(params)),
184 ),
185 () => orchestratingCaller,
186 );
187
188/** Requires handler capability checks, not thread control; linked work is refused the same way. */
189export const writesWithCapability = <P, A, E, R>(handle: (params: P) => Effect.Effect<A, E, R>) =>
190 declare(
191 (params: P) =>
192 writingCaller.pipe(
193 Effect.tap((caller) => assertNotLinked(caller, "start work here that is not its link's")),
194 Effect.flatMap(() => handle(params)),
195 ),
196 () => writingCaller,
197 );
198
199export const writesThreads = <P, A, E, R>(
200 threads: (params: P) => ReadonlyArray<ThreadId | undefined>,
201 handle: (params: P) => Effect.Effect<A, E, R>,
202) =>
203 declare(
204 (params: P) =>
205 Effect.gen(function* () {
206 const caller = yield* writingCaller;
207 for (const threadId of threads(params)) {
208 if (threadId === undefined || threadId === caller.scope.thread?.threadId) continue;
209 const target = yield* caller.threads
210 .getThreadShell(threadId)
211 .pipe(Effect.mapError(unavailable));
212 if (target !== null && target.deletedAt === null) {
213 yield* assertTargetWithinLimits(caller.limits, target);
214 yield* assertSameLink(caller, target);
215 }
216 }
217 // Modes can rise after this check; the orchestrator rechecks under lock and records refusal before handlers wrap errors.
218 const refused = yield* Ref.make<DispatchModeRefusal | undefined>(undefined);
219 return yield* handle(params).pipe(
220 Effect.provideService(DispatchModeLimit, { ...caller.limits, refused }),
221 Effect.catch((error) =>
222 Effect.flatMap(Ref.get(refused), (refusal) =>
223 Effect.fail<E | OrchestratorMcpFailure>(
224 refusal === undefined ? error : escalationDenied(refusal),
225 ),
226 ),
227 ),
228 );
229 }),
230 () => writingCaller,
231 );
232
233const escalationDenied = (refusal: DispatchModeRefusal) =>
234 new OrchestratorMcpFailure({
235 code:
236 refusal.mode === "runtime"
237 ? "runtime_mode_escalation_denied"
238 : "interaction_mode_escalation_denied",
239 message: `Thread ${refusal.threadId} now runs in ${refusal.runtimeMode}/${refusal.interactionMode} mode, above this caller's. Its user changed it while this call ran.`,
240 });
241
242export interface StartedModes {
243 readonly runtimeMode: RuntimeMode;
244 readonly interactionMode: ProviderInteractionMode;
245 /** The linked environment the caller acts for. The thread must carry it. */
246 readonly linkOrigin: OrchestrationV2LinkOrigin | undefined;
247}
248
249/**
250 * Starts threads with the modes `modes` requests, which may not be broader
251 * than the caller's. `linked` says what a linked caller gets: threads stamped
252 * with its `linkOrigin`, or a refusal where the tool cannot carry one.
253 */
254export const startsThreads = <P, A, E, R>(
255 modes: (params: P) => {
256 readonly runtimeMode?: RuntimeMode | undefined;
257 readonly interactionMode?: ProviderInteractionMode | undefined;
258 },
259 handle: (params: P, modes: StartedModes) => Effect.Effect<A, E, R>,
260 linked: "stamped" | { readonly refused: string },
261) => {
262 const started = Effect.fn("McpToolAccess.started")(function* (caller: Caller, params: P) {
263 const requested = modes(params);
264 return {
265 runtimeMode: yield* resolveRuntimeMode(caller.limits.runtimeMode, requested.runtimeMode),
266 interactionMode: yield* resolveInteractionMode(
267 caller.limits.interactionMode,
268 requested.interactionMode,
269 ),
270 linkOrigin: callerLinkOrigin(caller),
271 } satisfies StartedModes;
272 });
273 return declare(
274 (params: P) =>
275 Effect.gen(function* () {
276 const caller = yield* writingCaller;
277 if (linked !== "stamped") yield* assertNotLinked(caller, linked.refused);
278 return yield* handle(params, yield* started(caller, params));
279 }),
280 (params: P) => Effect.flatMap(writingCaller, (caller) => started(caller, params)),
281 );
282};
283
284/** One tool with two access rules, picked per call, such as create versus update. */
285export const either = <P, A, E, R, A2, E2, R2>(
286 useFirst: (params: P) => boolean,
287 first: Declaration<(params: P) => Effect.Effect<A, E, R>>,
288 second: Declaration<(params: P) => Effect.Effect<A2, E2, R2>>,
289) => {
290 const remotes = [remoteCheckOf(first), remoteCheckOf(second)] as ReadonlyArray<
291 RemoteCheck<P> | undefined
292 >;
293 return declare(
294 (params: P): Effect.Effect<A | A2, E | E2, R | R2> =>
295 useFirst(params) ? checkedHandler(first)(params) : checkedHandler(second)(params),
296 (params) =>
297 remotes[useFirst(params) ? 0 : 1]?.(params) ??
298 Effect.fail(
299 new OrchestratorMcpFailure({
300 code: "invalid_request",
301 message: "This action acts as the calling thread, which is here. Omit environmentId.",
302 }),
303 ),
304 );
305};
306
307/**
308 * `declaration`, whose result from a linked environment then goes through
309 * `forwarded` here, for what this environment records about the call.
310 */
311export const afterForwarding = <P, A, E, R, E2, R2>(
312 declaration: Declaration<(params: P) => Effect.Effect<A, E, R>>,
313 forwarded: Forwarded<P, A, E2, R2>,
314) =>
315 declare(
316 checkedHandler(declaration) as (params: P) => Effect.Effect<A, E | E2, R | R2>,
317 remoteCheckOf(declaration) as RemoteCheck<P> | undefined,
318 forwarded,
319 );
320
321const fullAccessRequired =
322 "Changing projects or environment settings needs a live full-access/default calling thread or a full-access client.";
323
324/** Recheck after waits before writing; caller modes may have changed. */
325export const writesEnvironment = <P, A, E, R>(
326 handle: (
327 params: P,
328 check: Effect.Effect<Caller, OrchestratorMcpFailure, CheckServices>,
329 ) => Effect.Effect<A, E, R>,
330 options?: {
331 /**
332 * Whether a linked caller may make it, as for adding a project: it leaves
333 * everything already here as it was.
334 */
335 readonly linkedCallers?: "allowed";
336 },
337) => {
338 const check = orchestratingCaller.pipe(
339 Effect.tap((caller) =>
340 options?.linkedCallers === "allowed"
341 ? Effect.void
342 : assertNotLinked(caller, "change projects or environment settings"),
343 ),
344 Effect.tap((caller) => assertFullAccess(caller, fullAccessRequired)),
345 );
346 return declare(
347 (params: P) => check.pipe(Effect.flatMap(() => handle(params, check))),
348 // Linked work never reaches a link at all; that is checked as the call goes.
349 () =>
350 orchestratingCaller.pipe(
351 Effect.tap((caller) => assertFullAccess(caller, fullAccessRequired)),
352 ),
353 );
354};
355
356type CheckServices = Effect.Services<typeof orchestratingCaller>;
357
358type Declarations<Handlers> = {
359 readonly [Name in keyof Handlers]: Declaration<Handlers[Name]> & NotCallable;
360};
361
362type NotCallable = { readonly call?: never } & { readonly apply?: never };
363
364export type Handlers<Tools extends Record<string, Tool.Any>> = Declarations<
365 Toolkit.HandlersFrom<Tools>
366>;
367
368export class HandlersLayer<Tools extends Record<string, Tool.Any>, EX = never, RX = never> {
369 readonly #layer: Layer.Layer<Tool.HandlersFor<Tools>, EX, RX>;
370 private constructor(
371 token: typeof builtHere,
372 layer: Layer.Layer<Tool.HandlersFor<Tools>, EX, RX>,
373 ) {
374 refuseOutsideConstruction(token);
375 this.#layer = layer;
376 }
377 static {
378 handlersLayer = (layer) => new HandlersLayer(builtHere, layer);
379 }
380 static layer<Tools extends Record<string, Tool.Any>, EX, RX>(
381 handlers: HandlersLayer<Tools, EX, RX>,
382 ) {
383 return handlers.#layer;
384 }
385}
386
387const checkedHandlers = <Handlers>(declarations: Declarations<Handlers>): Handlers =>
388 Struct.map(declarations, checkedHandler);
389
390/**
391 * A tool runs in a linked environment when its parameters take this target
392 * as `environmentId`. Other tools may name an environment for their own
393 * reasons, such as the one to link or to move a thread to.
394 */
395const takesLinkedEnvironment = (tool: Tool.Any) => {
396 const parameters: unknown = tool.parametersSchema;
397 return (
398 Predicate.hasProperty(parameters, "fields") &&
399 Predicate.hasProperty(parameters.fields, "environmentId") &&
400 parameters.fields.environmentId === OrchestratorMcpEnvironmentTarget
401 );
402};
403
404const linksUnavailable = new OrchestratorMcpFailure({
405 code: "orchestration_error",
406 message: "This environment cannot reach linked environments.",
407});
408
409/**
410 * Every tool that takes a linked environment runs there the same way: its
411 * declaration checks the caller here, and the same call goes to the other
412 * environment, which checks the rest. The handler here never sees
413 * `environmentId`, so it cannot leak into what it writes.
414 */
415const routed = Effect.fn("McpToolAccess.routed")(function* <Tools extends Record<string, Tool.Any>>(
416 toolkit: Toolkit.Toolkit<Tools>,
417 declarations: Handlers<Tools>,
418 checked: Toolkit.HandlersFrom<Tools>,
419) {
420 // Optional so toolkits that never leave this environment build without it.
421 const forwarding = yield* Effect.serviceOption(PeerForwarding.PeerForwarding);
422 const handlers: Record<string, unknown> = { ...checked };
423 for (const [name, declaration] of Object.entries<Declaration<unknown>>(declarations)) {
424 const tool = toolkit.tools[name];
425 if (tool === undefined) continue;
426 const remote = remoteCheckOf(declaration);
427 if (
428 remote === undefined &&
429 Context.getOrUndefined(tool.annotations, McpSchema.EnabledWhen) !==
430 McpInvocationContext.hiddenFromOutsideClients
431 )
432 return yield* Effect.die(
433 `${name} acts as its calling thread, so outside clients must not be offered it.`,
434 );
435 if (!takesLinkedEnvironment(tool)) continue;
436 const forwarded = forwardedOf(declaration) as
437 | Forwarded<object, unknown, Tool.Failure<Tools[keyof Tools]>, never>
438 | undefined;
439 if (remote === undefined)
440 return yield* Effect.die(
441 `${name} takes a linked environment, but it acts as its calling thread, which is here.`,
442 );
443 const here = handlers[name] as (
444 params: object,
445 ) => Effect.Effect<unknown, Tool.Failure<Tools[keyof Tools]>>;
446 handlers[name] = ({ environmentId, ...params }: { readonly environmentId?: EnvironmentId }) =>
447 Effect.gen(function* () {
448 const scope = yield* McpInvocationContext.McpInvocationContext;
449 const target = PeerForwarding.remoteTarget(scope, environmentId);
450 if (target === undefined) return yield* here(params);
451 if (scope.linkedEnvironments === false) return yield* PeerForwarding.linkedEnvironmentsOff;
452 yield* (remote as RemoteCheck<typeof params>)(params);
453 if (Option.isNone(forwarding)) return yield* linksUnavailable;
454 const result = yield* forwarding.value.call(scope, tool, target, {
455 ...params,
456 environmentId,
457 });
458 return forwarded === undefined ? result : yield* forwarded(params, target, result);
459 });
460 }
461 return handlers as Toolkit.HandlersFrom<Tools>;
462});
463
464export const toLayer = <Tools extends Record<string, Tool.Any>, EX = never, RX = never>(
465 toolkit: Toolkit.Toolkit<Tools>,
466 build: Handlers<Tools> | Effect.Effect<Handlers<Tools>, EX, RX>,
467): HandlersLayer<Tools, EX, Exclude<RX, Scope.Scope>> => {
468 // Checked as soon as they are given, so a forged declaration fails here.
469 const withDeclarations = (declarations: Handlers<Tools>) =>
470 routed(toolkit, declarations, checkedHandlers(declarations));
471 return handlersLayer(
472 toolkit.toLayer(
473 Effect.isEffect(build) ? Effect.flatMap(build, withDeclarations) : withDeclarations(build),
474 ),
475 );
476};