Open History to see the last commit
1import { expect, it } from "@effect/vitest";
2import {
3 EnvironmentId,
4 OrchestratorMcpEnvironmentTarget,
5 OrchestratorMcpFailure,
6 ProviderInstanceId,
7 ProviderInteractionMode,
8 RuntimeMode,
9 ThreadId,
10} from "@t3tools/contracts";
11import * as Cause from "effect/Cause";
12import * as Effect from "effect/Effect";
13import * as Exit from "effect/Exit";
14import * as Layer from "effect/Layer";
15import * as Schema from "effect/Schema";
16import * as Sink from "effect/Sink";
17import * as Stream from "effect/Stream";
18import { McpSchema, McpServer, Tool, Toolkit } from "effect/ai";
19
20import { OrchestratorProjectionError } from "../orchestration-v2/Orchestrator.ts";
21import * as PeerForwarding from "../peer/PeerForwarding.ts";
22import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
23import * as McpHttpServer from "./McpHttpServer.ts";
24import * as McpInvocationContext from "./McpInvocationContext.ts";
25import * as McpToolAccess from "./McpToolAccess.ts";
26import { liveThreadShell } from "./McpToolAccess.testkit.ts";
27
28const supervisedThreadId = ThreadId.make("thread:supervised");
29const planThreadId = ThreadId.make("thread:plan");
30const fullAccessThreadId = ThreadId.make("thread:full-access");
31const endedThreadId = ThreadId.make("thread:ended");
32const backgroundThreadId = ThreadId.make("thread:background");
33const oldProviderThreadId = ThreadId.make("thread:old-provider-background");
34const archivedThreadId = ThreadId.make("thread:archived-background");
35const unknownOwnerThreadId = ThreadId.make("thread:unknown-background-owner");
36
37const backgroundShell = (threadId: ThreadId, providerInstanceId: ProviderInstanceId) => ({
38 ...liveThreadShell(threadId, { activeRunId: null }),
39 pendingBackgroundTasks: [
40 { taskId: "task:background", kind: "subagent" as const, providerInstanceId },
41 ],
42});
43
44const shells = new Map([
45 [supervisedThreadId, liveThreadShell(supervisedThreadId, { runtimeMode: "approval-required" })],
46 [
47 planThreadId,
48 liveThreadShell(planThreadId, { runtimeMode: "approval-required", interactionMode: "plan" }),
49 ],
50 [fullAccessThreadId, liveThreadShell(fullAccessThreadId)],
51 [endedThreadId, liveThreadShell(endedThreadId, { activeRunId: null })],
52 [backgroundThreadId, backgroundShell(backgroundThreadId, ProviderInstanceId.make("codex"))],
53 [oldProviderThreadId, backgroundShell(oldProviderThreadId, ProviderInstanceId.make("claude"))],
54 [
55 archivedThreadId,
56 {
57 ...backgroundShell(archivedThreadId, ProviderInstanceId.make("codex")),
58 archivedAt: liveThreadShell(archivedThreadId).updatedAt,
59 },
60 ],
61 [
62 unknownOwnerThreadId,
63 {
64 ...liveThreadShell(unknownOwnerThreadId, { activeRunId: null }),
65 pendingBackgroundTasks: [{ taskId: "task:unknown", kind: "subagent" as const }],
66 },
67 ],
68]);
69
70const threadCaller = (threadId: ThreadId): McpInvocationContext.McpInvocationScope => ({
71 environmentId: EnvironmentId.make("environment"),
72 requestNamespace: `provider:${threadId}`,
73 thread: {
74 threadId,
75 providerSessionId: `provider:${threadId}`,
76 providerInstanceId: ProviderInstanceId.make("codex"),
77 },
78 client: undefined,
79 capabilities: new Set(["orchestration"]),
80 issuedAt: 0,
81});
82
83const clientCaller = (
84 access: McpInvocationContext.McpClientCaller["access"],
85): McpInvocationContext.McpInvocationScope => ({
86 environmentId: EnvironmentId.make("environment"),
87 requestNamespace: "client:session",
88 thread: undefined,
89 client: { sessionId: "session", label: "Claude Code", access },
90 capabilities: new Set(["orchestration"]),
91 issuedAt: 0,
92});
93
94const mcpClient = McpSchema.McpServerClient.of({
95 clientId: 1,
96 protocolVersion: "2025-06-18",
97 clientCapabilities: {},
98 clientInfo: { name: "mcp-test", version: "1" },
99 initializePayload: {
100 protocolVersion: "2025-06-18",
101 capabilities: {},
102 clientInfo: { name: "mcp-test", version: "1" },
103 },
104 getClient: Effect.die("unused"),
105});
106
107const probe = {
108 success: Schema.Struct({ ran: Schema.String }),
109 failure: OrchestratorMcpFailure,
110 failureMode: "return" as const,
111 dependencies: [
112 McpInvocationContext.McpInvocationContext,
113 ThreadManagement.ThreadManagementService,
114 ],
115};
116const ProbeToolkit = Toolkit.make(
117 Tool.make("reads", probe),
118 Tool.make("reads_as_caller", probe).annotate(
119 McpSchema.EnabledWhen,
120 McpInvocationContext.hiddenFromOutsideClients,
121 ),
122 Tool.make("acts_as_caller", probe).annotate(
123 McpSchema.EnabledWhen,
124 McpInvocationContext.hiddenFromOutsideClients,
125 ),
126 Tool.make("writes", probe),
127 Tool.make("writes_with_capability", probe),
128 Tool.make("writes_threads", {
129 ...probe,
130 parameters: Schema.Struct({ threadId: Schema.optional(ThreadId) }),
131 }),
132 Tool.make("starts_threads", {
133 ...probe,
134 parameters: Schema.Struct({
135 runtimeMode: Schema.optional(RuntimeMode),
136 interactionMode: Schema.optional(ProviderInteractionMode),
137 }),
138 }),
139 Tool.make("writes_environment", probe),
140 Tool.make("writes_owner_work", probe),
141);
142const ran = Effect.succeed({ ran: "ran" });
143const probeHandlers: McpToolAccess.Handlers<typeof ProbeToolkit.tools> = {
144 reads: McpToolAccess.reads(() => ran),
145 reads_as_caller: McpToolAccess.readsAsCaller(() => ran),
146 acts_as_caller: McpToolAccess.actsAsCaller(() => ran),
147 writes: McpToolAccess.writes(() => ran),
148 writes_with_capability: McpToolAccess.writesWithCapability(() => ran),
149 writes_threads: McpToolAccess.writesThreads(
150 (input) => [input.threadId],
151 () => ran,
152 ),
153 starts_threads: McpToolAccess.startsThreads(
154 (input) => input,
155 (_, modes) => Effect.succeed({ ran: `${modes.runtimeMode}/${modes.interactionMode}` }),
156 "stamped",
157 ),
158 writes_environment: McpToolAccess.writesEnvironment(() => ran),
159 writes_owner_work: McpToolAccess.writesOwnerWork("drive owner work", () => ran),
160};
161const layerProbeHandlers = McpToolAccess.toLayer(ProbeToolkit, probeHandlers);
162
163const unchecked = () => ran;
164
165// `@ts-expect-error` fails the build if one ever compiles. Never called.
166export const refusedAtCompileTime = () => {
167 McpToolAccess.toLayer(ProbeToolkit, {
168 ...probeHandlers,
169 // @ts-expect-error a handler that skips its declaration
170 reads: unchecked,
171 });
172 McpToolAccess.toLayer(ProbeToolkit, {
173 ...probeHandlers,
174 // @ts-expect-error a declaration's fields copied onto an unchecked handler
175 reads: Object.assign(
176 unchecked,
177 McpToolAccess.reads(() => ran),
178 ),
179 });
180 // @ts-expect-error a declaration built outside McpToolAccess
181 McpToolAccess.Declaration.make(unchecked);
182 // @ts-expect-error a declaration constructed directly
183 new McpToolAccess.Declaration(unchecked); // oxlint-disable-line eslint/no-new -- This type-contract test checks direct construction.
184 // @ts-expect-error a handlers layer built outside McpToolAccess
185 McpToolAccess.HandlersLayer.make(Layer.empty);
186 // @effect-diagnostics-next-line anyUnknownInErrorContext:off
187 McpHttpServer.toolkitRegistration(
188 ProbeToolkit,
189 // @ts-expect-error a handlers layer that skipped `McpToolAccess.toLayer`
190 ProbeToolkit.toLayer({
191 reads: unchecked,
192 reads_as_caller: unchecked,
193 acts_as_caller: unchecked,
194 writes: unchecked,
195 writes_with_capability: unchecked,
196 writes_threads: unchecked,
197 starts_threads: unchecked,
198 writes_environment: unchecked,
199 writes_owner_work: unchecked,
200 }),
201 );
202};
203
204const probeServer = (threads: Layer.Layer<ThreadManagement.ThreadManagementService>) =>
205 McpHttpServer.toolkitRegistration(ProbeToolkit, layerProbeHandlers).pipe(
206 Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
207 Layer.provideMerge(threads),
208 );
209
210const decodeOutcome = Schema.decodeUnknownEffect(
211 Schema.fromJsonString(
212 Schema.Union([Schema.Struct({ ran: Schema.String }), Schema.Struct({ code: Schema.String })]),
213 ),
214);
215
216const call = (
217 tool: string,
218 scope: McpInvocationContext.McpInvocationScope,
219 args: Record<string, unknown> = {},
220) =>
221 McpServer.McpServer.pipe(
222 Effect.flatMap((server) => server.callTool({ name: tool, arguments: args })),
223 Effect.flatMap(({ content }) =>
224 decodeOutcome(content.map((part) => (part.type === "text" ? part.text : "")).join("")),
225 ),
226 Effect.map((outcome) => ("code" in outcome ? outcome.code : outcome.ran)),
227 Effect.provideService(McpInvocationContext.McpInvocationContext, scope),
228 Effect.provideService(McpSchema.McpServerClient, mcpClient),
229 );
230
231const supervised = threadCaller(supervisedThreadId);
232const plan = threadCaller(planThreadId);
233const fullAccess = threadCaller(fullAccessThreadId);
234const ended = threadCaller(endedThreadId);
235const background = threadCaller(backgroundThreadId);
236const oldProviderBackground = threadCaller(oldProviderThreadId);
237const archivedBackground = threadCaller(archivedThreadId);
238const unknownOwnerBackground = threadCaller(unknownOwnerThreadId);
239const mismatchedProvider = {
240 ...background,
241 thread: { ...background.thread!, providerInstanceId: ProviderInstanceId.make("claude") },
242};
243const supervisedClient = clientCaller("approval-required");
244const fullAccessClient = clientCaller("full-access");
245const readOnlyClient = clientCaller("read-only");
246const linkedClient: McpInvocationContext.McpInvocationScope = {
247 ...supervisedClient,
248 client: { ...supervisedClient.client!, linked: true },
249};
250// A full-access link's agents can do anything this environment's user can.
251const fullAccessLinkedClient: McpInvocationContext.McpInvocationScope = {
252 ...fullAccessClient,
253 client: { ...fullAccessClient.client!, linked: true },
254};
255// An administrator's ceiling narrows every client to it.
256const atCeilingClient: McpInvocationContext.McpInvocationScope = {
257 ...fullAccessClient,
258 runtimeModeCeiling: "auto",
259 client: {
260 ...fullAccessClient.client!,
261 narrowedTo: { runtimeMode: "auto", interactionMode: "default" },
262 },
263};
264const previewOnly = { ...fullAccess, capabilities: new Set(["preview"] as const) };
265
266it.effect.each([
267 ["reads", ended, {}, "ran"],
268 ["reads", supervisedClient, {}, "ran"],
269 ["reads", readOnlyClient, {}, "ran"],
270
271 ["writes", readOnlyClient, {}, "capability_denied"],
272 ["writes_threads", readOnlyClient, { threadId: supervisedThreadId }, "capability_denied"],
273 ["starts_threads", readOnlyClient, {}, "capability_denied"],
274 ["writes_environment", readOnlyClient, {}, "capability_denied"],
275
276 ["reads_as_caller", ended, {}, "ran"],
277 ["acts_as_caller", supervised, {}, "ran"],
278 ["acts_as_caller", ended, {}, "parent_not_active"],
279 ["acts_as_caller", background, {}, "ran"],
280 ["acts_as_caller", oldProviderBackground, {}, "parent_not_active"],
281 ["acts_as_caller", mismatchedProvider, {}, "parent_not_active"],
282 ["acts_as_caller", archivedBackground, {}, "parent_not_active"],
283 ["acts_as_caller", unknownOwnerBackground, {}, "parent_not_active"],
284
285 ["writes", supervised, {}, "ran"],
286 ["writes", ended, {}, "parent_not_active"],
287 ["writes", background, {}, "ran"],
288 ["writes", oldProviderBackground, {}, "parent_not_active"],
289 ["writes", supervisedClient, {}, "ran"],
290 ["writes", previewOnly, {}, "capability_denied"],
291 ["writes_environment", previewOnly, {}, "capability_denied"],
292
293 ["writes_with_capability", previewOnly, {}, "ran"],
294 ["writes_with_capability", readOnlyClient, {}, "capability_denied"],
295 ["writes_with_capability", ended, {}, "parent_not_active"],
296 ["writes", linkedClient, {}, "capability_denied"],
297 ["writes_with_capability", linkedClient, {}, "capability_denied"],
298 ["writes", fullAccessLinkedClient, {}, "ran"],
299 ["writes_with_capability", fullAccessLinkedClient, {}, "ran"],
300
301 ["writes_threads", supervised, {}, "ran"],
302 ["writes_threads", supervised, { threadId: planThreadId }, "ran"],
303 [
304 "writes_threads",
305 supervised,
306 { threadId: fullAccessThreadId },
307 "runtime_mode_escalation_denied",
308 ],
309 ["writes_threads", plan, { threadId: supervisedThreadId }, "interaction_mode_escalation_denied"],
310 ["writes_threads", fullAccess, { threadId: supervisedThreadId }, "ran"],
311 ["writes_threads", ended, { threadId: supervisedThreadId }, "parent_not_active"],
312 ["writes_threads", supervisedClient, { threadId: supervisedThreadId }, "ran"],
313 [
314 "writes_threads",
315 supervisedClient,
316 { threadId: fullAccessThreadId },
317 "runtime_mode_escalation_denied",
318 ],
319 ["writes_threads", supervised, { threadId: "thread:missing" }, "ran"],
320
321 ["starts_threads", supervised, {}, "approval-required/default"],
322 ["starts_threads", supervised, { runtimeMode: "full-access" }, "runtime_mode_escalation_denied"],
323 ["starts_threads", plan, {}, "approval-required/plan"],
324 ["starts_threads", plan, { interactionMode: "default" }, "interaction_mode_escalation_denied"],
325 ["starts_threads", fullAccess, { runtimeMode: "auto", interactionMode: "plan" }, "auto/plan"],
326 ["starts_threads", ended, {}, "parent_not_active"],
327 ["starts_threads", supervisedClient, {}, "approval-required/default"],
328 ["starts_threads", supervisedClient, { runtimeMode: "auto" }, "runtime_mode_escalation_denied"],
329 ["starts_threads", fullAccessClient, { runtimeMode: "full-access" }, "full-access/default"],
330
331 ["writes_environment", fullAccess, {}, "ran"],
332 ["writes_environment", supervised, {}, "capability_denied"],
333 ["writes_environment", plan, {}, "capability_denied"],
334 ["writes_environment", fullAccessClient, {}, "ran"],
335 ["writes_environment", supervisedClient, {}, "capability_denied"],
336
337 ["writes_owner_work", fullAccess, {}, "ran"],
338 ["writes_owner_work", supervised, {}, "capability_denied"],
339 ["writes_owner_work", plan, {}, "capability_denied"],
340 ["writes_owner_work", ended, {}, "parent_not_active"],
341 ["writes_owner_work", fullAccessClient, {}, "ran"],
342 ["writes_owner_work", supervisedClient, {}, "capability_denied"],
343 ["writes_owner_work", readOnlyClient, {}, "capability_denied"],
344 ["writes_owner_work", linkedClient, {}, "capability_denied"],
345 ["writes_owner_work", fullAccessLinkedClient, {}, "ran"],
346 ["writes_owner_work", atCeilingClient, {}, "ran"],
347 ["writes_environment", atCeilingClient, {}, "capability_denied"],
348] as const)("%s from %o with %o: %s", ([tool, scope, args, expected]) =>
349 call(tool, scope, args).pipe(
350 Effect.map((outcome) => expect(outcome).toBe(expected)),
351 Effect.provide(
352 probeServer(
353 Layer.mock(ThreadManagement.ThreadManagementService)({
354 getThreadShell: (threadId) => Effect.succeed(shells.get(threadId) ?? null),
355 }),
356 ),
357 ),
358 ),
359);
360
361it("refuses a declaration or handlers layer that only wears another's fields", () => {
362 const copiedDeclaration = Object.assign(
363 unchecked,
364 McpToolAccess.reads(() => ran),
365 );
366 expect(() =>
367 McpToolAccess.toLayer(ProbeToolkit, {
368 ...probeHandlers,
369 // @ts-expect-error a declaration's fields copied onto an unchecked handler
370 reads: copiedDeclaration,
371 }),
372 ).toThrow(TypeError);
373 const copiedLayer = Object.assign(Layer.empty, layerProbeHandlers);
374 expect(() => McpToolAccess.HandlersLayer.layer(copiedLayer)).toThrow(TypeError);
375});
376
377it.effect("refuses a change when the calling thread cannot be read", () =>
378 call("writes", supervised).pipe(
379 Effect.map((outcome) => expect(outcome).toBe("orchestration_error")),
380 Effect.provide(
381 probeServer(
382 Layer.mock(ThreadManagement.ThreadManagementService)({
383 getThreadShell: (threadId) =>
384 Effect.fail(new OrchestratorProjectionError({ threadId, cause: "unreadable" })),
385 }),
386 ),
387 ),
388 ),
389);
390
391const box = EnvironmentId.make("environment-box");
392const here = EnvironmentId.make("environment");
393const linkedProbe = {
394 ...probe,
395 parameters: Schema.Struct({
396 environmentId: OrchestratorMcpEnvironmentTarget,
397 threadId: Schema.optional(ThreadId),
398 runtimeMode: Schema.optional(RuntimeMode),
399 interactionMode: Schema.optional(ProviderInteractionMode),
400 }),
401};
402const LinkedProbeToolkit = Toolkit.make(
403 Tool.make("reads", linkedProbe),
404 Tool.make("writes", linkedProbe),
405 Tool.make("writes_with_capability", linkedProbe),
406 Tool.make("writes_threads", linkedProbe),
407 Tool.make("starts_threads", linkedProbe),
408 Tool.make("writes_environment", linkedProbe),
409);
410/** Runs here, and tells whether `environmentId` reached the handler. */
411const ranHere = <P extends object>(params: P) =>
412 Effect.succeed({ ran: "environmentId" in params ? "saw environmentId" : "here" });
413
414const linkedProbeServer = McpHttpServer.toolkitRegistration(
415 LinkedProbeToolkit,
416 McpToolAccess.toLayer(LinkedProbeToolkit, {
417 reads: McpToolAccess.reads(ranHere),
418 writes: McpToolAccess.writes(ranHere),
419 writes_with_capability: McpToolAccess.writesWithCapability(ranHere),
420 writes_threads: McpToolAccess.writesThreads((input) => [input.threadId], ranHere),
421 starts_threads: McpToolAccess.startsThreads((input) => input, ranHere, "stamped"),
422 writes_environment: McpToolAccess.writesEnvironment(ranHere),
423 }),
424).pipe(
425 Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
426 Layer.provideMerge(
427 Layer.mock(ThreadManagement.ThreadManagementService)({
428 getThreadShell: (threadId) => Effect.succeed(shells.get(threadId) ?? null),
429 }),
430 ),
431 // Stands in for the linked environment, answering with where the call went.
432 Layer.provide(
433 Layer.mock(PeerForwarding.PeerForwarding)({
434 call: (_scope, tool, environmentId) =>
435 Effect.succeed({ ran: `${tool.name} in ${environmentId}` } as never),
436 }),
437 ),
438);
439
440it.effect.each([
441 ["reads", supervised, { environmentId: box }, "reads in environment-box"],
442 ["reads", supervised, { environmentId: here }, "here"],
443 ["reads", supervised, {}, "here"],
444
445 // The caller is checked here before anything goes.
446 ["writes", readOnlyClient, { environmentId: box }, "capability_denied"],
447 ["writes", ended, { environmentId: box }, "parent_not_active"],
448 ["writes", supervised, { environmentId: box }, "writes in environment-box"],
449 ["writes_with_capability", readOnlyClient, { environmentId: box }, "capability_denied"],
450 [
451 "starts_threads",
452 plan,
453 { environmentId: box, interactionMode: "default" },
454 "interaction_mode_escalation_denied",
455 ],
456 ["starts_threads", plan, { environmentId: box }, "starts_threads in environment-box"],
457 ["writes_environment", supervised, { environmentId: box }, "capability_denied"],
458 [
459 "writes_environment",
460 fullAccess,
461 { environmentId: box },
462 "writes_environment in environment-box",
463 ],
464 ["writes_environment", fullAccess, { environmentId: here }, "here"],
465
466 // A thread id names a thread where the call runs, and is checked there.
467 [
468 "writes_threads",
469 supervised,
470 { environmentId: box, threadId: fullAccessThreadId },
471 "writes_threads in environment-box",
472 ],
473 [
474 "writes_threads",
475 supervised,
476 { environmentId: here, threadId: fullAccessThreadId },
477 "runtime_mode_escalation_denied",
478 ],
479] as const)("a linked %s from %o with %o: %s", ([tool, scope, args, expected]) =>
480 call(tool, scope, args).pipe(
481 Effect.map((outcome) => expect(outcome).toBe(expected)),
482 Effect.provide(linkedProbeServer),
483 ),
484);
485
486it.effect("refuses a linked environment to a tool that acts as its calling thread", () =>
487 Effect.gen(function* () {
488 const CallerToolkit = Toolkit.make(
489 Tool.make("acts_as_caller", linkedProbe).annotate(
490 McpSchema.EnabledWhen,
491 McpInvocationContext.hiddenFromOutsideClients,
492 ),
493 );
494 const built = yield* Layer.build(
495 McpToolAccess.HandlersLayer.layer(
496 McpToolAccess.toLayer(CallerToolkit, {
497 acts_as_caller: McpToolAccess.actsAsCaller(ranHere),
498 }),
499 ),
500 ).pipe(Effect.scoped, Effect.exit);
501 expect(Exit.isFailure(built) && Cause.hasDies(built.cause)).toBe(true);
502 }),
503);
504
505// Discovery hides these tools. The handler must refuse on its own if that ever changes.
506it.effect.each(["reads_as_caller", "acts_as_caller"] as const)(
507 "%s refuses an outside client behind discovery",
508 (tool) =>
509 Effect.gen(function* () {
510 const built = yield* ProbeToolkit;
511 const { result } = yield* built
512 .handle(tool, {})
513 .pipe(Stream.unwrap, Stream.run(Sink.last()), Effect.flatMap(Effect.fromOption));
514 expect(result).toMatchObject({ code: "thread_credential_required" });
515 }).pipe(
516 Effect.provide(McpToolAccess.HandlersLayer.layer(layerProbeHandlers)),
517 Effect.provideService(McpInvocationContext.McpInvocationContext, fullAccessClient),
518 Effect.provide(Layer.mock(ThreadManagement.ThreadManagementService)({})),
519 ),
520);
521
522it.effect("refuses to build a thread-bound tool that outside clients would be offered", () =>
523 Effect.gen(function* () {
524 const CallerToolkit = Toolkit.make(Tool.make("reads_as_caller", probe));
525 const built = yield* Layer.build(
526 McpToolAccess.HandlersLayer.layer(
527 McpToolAccess.toLayer(CallerToolkit, {
528 reads_as_caller: McpToolAccess.readsAsCaller(() => ran),
529 }),
530 ),
531 ).pipe(Effect.scoped, Effect.exit);
532 expect(Exit.isFailure(built) && Cause.pretty(built.cause)).toContain(
533 "reads_as_caller acts as its calling thread",
534 );
535 }),
536);