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

McpToolAccess.ts

316 lines12.1 KB

1import {
2 OrchestratorMcpFailure,
3 type ProviderInteractionMode,
4 type RuntimeMode,
5 type ThreadId,
6} from "@t3tools/contracts";
7import * as Effect from "effect/Effect";
8import * as Ref from "effect/Ref";
9import * as Struct from "effect/Struct";
10import type * as Layer from "effect/Layer";
11import type * as Scope from "effect/Scope";
12import type { Tool, Toolkit } from "effect/ai";
13​
14import {
15 DispatchModeLimit,
16 type DispatchModeRefusal,
17} from "../orchestration-v2/DispatchModeLimit.ts";
18import * as McpInvocationContext from "./McpInvocationContext.ts";
19import { resolveInteractionMode, resolveRuntimeMode } from "./OrchestratorMcpService.ts";
20import {
21 assertFullAccess,
22 assertLiveCaller,
23 assertTargetWithinLimits,
24 type Caller,
25 loadCaller,
26 readCaller,
27 unavailable,
28} from "./threadAccess.ts";
29​
30// Only the classes below assign these, from their static blocks, so nothing
31// outside this module can build a declaration or a handlers layer.
32​
33/**
34 * Both constructors demand this. Their private constructors only stop the type
35 * checker; this also stops `Reflect.construct` and friends at runtime.
36 */
37const builtHere: unique symbol = Symbol("t3/mcp/McpToolAccess/builtHere");
38​
39const refuseOutsideConstruction = (token: symbol) => {
40 if (token !== builtHere) {
41 throw new TypeError("Only McpToolAccess builds MCP tool declarations and handler layers.");
42 }
43};
44​
45/** Builds a declaration; only the declaration functions below call it. */
46let declare: <P, A, E, R>(
47 handle: (params: P) => Effect.Effect<A, E, R>,
48) => Declaration<(params: P) => Effect.Effect<A, E, R>>;
49​
50type CheckedHandlerOf<D> = D extends Declaration<infer Handler> ? Handler : never;
51​
52/** Turns each declaration back into the handler it checks, keeping its type. */
53interface CheckedHandler extends Struct.Lambda {
54 <Handler>(declaration: Declaration<Handler>): Handler;
55 readonly "~lambda.out": CheckedHandlerOf<this["~lambda.in"]>;
57let checkedHandler: CheckedHandler;
58​
59/** Only `toLayer` below builds one. */
60let handlersLayer: <Tools extends Record<string, Tool.Any>, EX, RX>(
61 layer: Layer.Layer<Tool.HandlersFor<Tools>, EX, RX>,
62) => HandlersLayer<Tools, EX, RX>;
63​
64/**
65 * Who may call a T3 MCP tool. Every handler is built by one of the
66 * declarations below, which say what the tool does. `toLayer` accepts only
67 * declarations, and `/mcp` registers only layers `toLayer` built, so a tool
68 * without a decision here does not compile. Both are nominal classes, so a
69 * handler or layer cannot pass for one by copying its fields. Effect's own
70 * registration functions accept any handler, so the
71 * `t3code/no-raw-mcp-registration` lint rule keeps Effect's `McpServer` inside
72 * McpHttpServer.
73 *
74 * Parameters choose the target; the caller sets the limits: a thread caller
75 * its own runtime and interaction modes, an outside client the ceiling it was
76 * approved with. Nothing a caller starts or changes may run with broader
77 * modes, and a thread caller changes things only while its own run is live.
78 * A refusal is an `OrchestratorMcpFailure`, so the compiler requires it in the
79 * tool's failure schema, and `ThreadManagementService` in its dependencies.
80 *
81 * The declaration checks the caller before the handler runs. Handlers still
82 * check what only they can see, such as a queued run belonging to its thread.
83 */
84export class Declaration<out Handler> {
85 // A private field makes the class nominal, and only this module can build
86 // one: its constructor is private and the static block hands the only way
87 // in to module-scoped functions. Copying a declaration's fields onto
88 // anything else fails to typecheck and, at runtime, to run.
89 readonly #handle: Handler;
90 private constructor(token: typeof builtHere, handle: Handler) {
91 refuseOutsideConstruction(token);
92 this.#handle = handle;
93 }
94 static {
95 declare = (handle) => new Declaration(builtHere, handle);
96 checkedHandler = Struct.lambda<CheckedHandler>((declaration) => declaration.#handle);
97 }
99​
100/** A client approved for read-only access changes nothing. */
101const refuseReadOnlyClient = McpInvocationContext.McpInvocationContext.pipe(
102 Effect.flatMap((scope) =>
103 scope.client?.access === "read-only"
104 ? Effect.fail(
105 new OrchestratorMcpFailure({
106 code: "capability_denied",
107 message:
108 "This tool changes the environment, and this MCP client was approved for read-only access.",
109 }),
110 )
111 : Effect.void,
112 ),
113);
114​
115/**
116 * The caller of a tool that changes something. Tools that act for a
117 * capability of their own (preview, device, worktree, pull requests) check it
118 * themselves.
119 */
120const writingCaller = refuseReadOnlyClient.pipe(
121 Effect.andThen(loadCaller()),
122 Effect.tap(assertLiveCaller),
123);
124​
125/** The same, for tools whose only capability is controlling threads. */
126const orchestratingCaller = refuseReadOnlyClient.pipe(
127 Effect.andThen(readCaller()),
128 Effect.tap(assertLiveCaller),
129);
130​
131const requireThreadCaller = McpInvocationContext.McpInvocationContext.pipe(
132 Effect.flatMap((scope) => McpInvocationContext.requireThreadScope(scope, "This tool")),
133);
134​
135/** Changes nothing, so every caller may call it. */
136export const reads = <P, A, E, R>(handle: (params: P) => Effect.Effect<A, E, R>) =>
137 declare((params: P) => handle(params));
138​
139/** Reads what belongs to the calling T3 thread, such as its preview tabs or devices. */
140export const readsAsCaller = <P, A, E, R>(handle: (params: P) => Effect.Effect<A, E, R>) =>
141 declare((params: P) => requireThreadCaller.pipe(Effect.flatMap(() => handle(params))));
142​
143/**
144 * Acts as the calling T3 thread (its subagents, preview tabs, devices,
145 * worktree) while that thread's run is live. Only an agent running inside a
146 * T3 thread has one.
147 */
148export const actsAsCaller = <P, A, E, R>(handle: (params: P) => Effect.Effect<A, E, R>) =>
149 declare((params: P) =>
150 requireThreadCaller.pipe(
151 Effect.flatMap(() => writingCaller),
152 Effect.flatMap(() => handle(params)),
153 ),
154 );
155​
156/** Changes something that belongs to no thread, such as a pending upload or a scheduled task. */
157export const writes = <P, A, E, R>(handle: (params: P) => Effect.Effect<A, E, R>) =>
158 declare((params: P) => orchestratingCaller.pipe(Effect.flatMap(() => handle(params))));
159​
160/**
161 * Changes the threads `threads` names. An omitted id is the caller's own
162 * thread; any other thread must run within the caller's modes, checked here
163 * and again by the orchestrator when it applies each command. A thread that
164 * does not exist is the handler's to report.
165 */
166export const writesThreads = <P, A, E, R>(
167 threads: (params: P) => ReadonlyArray<ThreadId | undefined>,
168 handle: (params: P) => Effect.Effect<A, E, R>,
169) =>
170 declare((params: P) =>
171 Effect.gen(function* () {
172 const caller = yield* writingCaller;
173 for (const threadId of threads(params)) {
174 if (threadId === undefined || threadId === caller.scope.thread?.threadId) continue;
175 const target = yield* caller.threads
176 .getThreadShell(threadId)
177 .pipe(Effect.mapError(unavailable));
178 if (target !== null && target.deletedAt === null) {
179 yield* assertTargetWithinLimits(caller.limits, target);
180 }
181 }
182 // The target's user can raise its modes after the check above; the
183 // orchestrator checks again under the thread's lock and records its
184 // refusal here, since handlers wrap dispatch errors their own way.
185 const refused = yield* Ref.make<DispatchModeRefusal | undefined>(undefined);
186 return yield* handle(params).pipe(
187 Effect.provideService(DispatchModeLimit, { ...caller.limits, refused }),
188 Effect.catch((error) =>
189 Effect.flatMap(Ref.get(refused), (refusal) =>
190 Effect.fail<E | OrchestratorMcpFailure>(
191 refusal === undefined ? error : escalationDenied(refusal),
192 ),
193 ),
194 ),
195 );
196 }),
197 );
198​
199/** How an agent hears that a thread it targets was raised above its modes mid-call. */
200const escalationDenied = (refusal: DispatchModeRefusal) =>
201 new OrchestratorMcpFailure({
202 code:
203 refusal.mode === "runtime"
204 ? "runtime_mode_escalation_denied"
205 : "interaction_mode_escalation_denied",
206 message: `Thread ${refusal.threadId} now runs in ${refusal.runtimeMode}/${refusal.interactionMode} mode, above this caller's. Its user changed it while this call ran.`,
207 });
208​
209/** The modes a started thread runs with: those requested, else the caller's own. */
210export interface StartedModes {
211 readonly runtimeMode: RuntimeMode;
212 readonly interactionMode: ProviderInteractionMode;
214​
215/** Starts threads with the modes `modes` requests, which may not be broader than the caller's. */
216export const startsThreads = <P, A, E, R>(
217 modes: (params: P) => {
218 readonly runtimeMode?: RuntimeMode | undefined;
219 readonly interactionMode?: ProviderInteractionMode | undefined;
220 },
221 handle: (params: P, modes: StartedModes) => Effect.Effect<A, E, R>,
222) =>
223 declare((params: P) =>
224 Effect.gen(function* () {
225 const { limits } = yield* writingCaller;
226 const requested = modes(params);
227 const started: StartedModes = {
228 runtimeMode: yield* resolveRuntimeMode(limits.runtimeMode, requested.runtimeMode),
229 interactionMode: yield* resolveInteractionMode(
230 limits.interactionMode,
231 requested.interactionMode,
232 ),
233 };
234 return yield* handle(params, started);
235 }),
236 );
237​
238const fullAccessRequired =
239 "Changing projects or environment settings needs a live full-access/default calling thread or a full-access client.";
240​
241/**
242 * Changes projects or environment settings, which needs a full-access/default
243 * caller. `check` re-checks the caller wherever the handler waits before
244 * writing, such as for a lock, since the caller's modes can change meanwhile.
245 */
246export const writesEnvironment = <P, A, E, R>(
247 handle: (
248 params: P,
249 check: Effect.Effect<Caller, OrchestratorMcpFailure, CheckServices>,
250 ) => Effect.Effect<A, E, R>,
251) => {
252 const check = orchestratingCaller.pipe(
253 Effect.tap((caller) => assertFullAccess(caller, fullAccessRequired)),
254 );
255 return declare((params: P) => check.pipe(Effect.flatMap(() => handle(params, check))));
256};
257​
258/** What a declaration's own check needs. */
259type CheckServices = Effect.Services<typeof orchestratingCaller>;
260​
261/**
262 * Each handler of `Handlers`, built by one of the declarations above. A
263 * declaration is never callable, which rules out a handler function wearing a
264 * declaration's fields.
265 */
266type Declarations<Handlers> = {
267 readonly [Name in keyof Handlers]: Declaration<Handlers[Name]> & NotCallable;
268};
269​
270/** Anything but a function. */
271type NotCallable = { readonly call?: never } & { readonly apply?: never };
272​
273/** A toolkit's handlers, each built by one of the declarations above. */
274export type Handlers<Tools extends Record<string, Tool.Any>> = Declarations<
275 Toolkit.HandlersFrom<Tools>
276>;
277​
278/**
279 * A toolkit's handler layer built by `toLayer`, the only kind `/mcp`
280 * registers. Like a declaration it is nominal, so nothing else passes for one.
281 */
282export class HandlersLayer<Tools extends Record<string, Tool.Any>, EX = never, RX = never> {
283 readonly #layer: Layer.Layer<Tool.HandlersFor<Tools>, EX, RX>;
284 private constructor(
285 token: typeof builtHere,
286 layer: Layer.Layer<Tool.HandlersFor<Tools>, EX, RX>,
287 ) {
288 refuseOutsideConstruction(token);
289 this.#layer = layer;
290 }
291 static {
292 handlersLayer = (layer) => new HandlersLayer(builtHere, layer);
293 }
294 /** The handlers, for registering this toolkit on the MCP server. */
295 static layer<Tools extends Record<string, Tool.Any>, EX, RX>(
296 handlers: HandlersLayer<Tools, EX, RX>,
297 ) {
298 return handlers.#layer;
299 }
301​
302const checkedHandlers = <Handlers>(declarations: Declarations<Handlers>): Handlers =>
303 Struct.map(declarations, checkedHandler);
304​
305/** `Toolkit.toLayer` for handlers that all declare their access. */
306export const toLayer = <Tools extends Record<string, Tool.Any>, EX = never, RX = never>(
307 toolkit: Toolkit.Toolkit<Tools>,
308 build: Handlers<Tools> | Effect.Effect<Handlers<Tools>, EX, RX>,
309): HandlersLayer<Tools, EX, Exclude<RX, Scope.Scope>> =>
310 handlersLayer(
311 toolkit.toLayer(
312 Effect.isEffect(build)
313 ? Effect.map(build, checkedHandlers<Toolkit.HandlersFrom<Tools>>)
314 : checkedHandlers(build),
315 ),
316 );