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

McpToolAccess.ts

523 lines18.9 KB

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