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