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