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

McpToolAccess.test.ts

347 lines13.4 KB

1import { expect, it } from "@effect/vitest";
2import {
3 EnvironmentId,
4 OrchestratorMcpFailure,
5 ProviderInstanceId,
6 ProviderInteractionMode,
7 RuntimeMode,
8 ThreadId,
9} from "@t3tools/contracts";
10import * as Effect from "effect/Effect";
11import * as Layer from "effect/Layer";
12import * as Schema from "effect/Schema";
13import { McpSchema, McpServer, Tool, Toolkit } from "effect/ai";
14​
15import { OrchestratorProjectionError } from "../orchestration-v2/Orchestrator.ts";
16import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
17import * as McpHttpServer from "./McpHttpServer.ts";
18import * as McpInvocationContext from "./McpInvocationContext.ts";
19import * as McpToolAccess from "./McpToolAccess.ts";
20import { liveThreadShell } from "./McpToolAccess.testkit.ts";
21​
22const supervisedThreadId = ThreadId.make("thread:supervised");
23const planThreadId = ThreadId.make("thread:plan");
24const fullAccessThreadId = ThreadId.make("thread:full-access");
25const endedThreadId = ThreadId.make("thread:ended");
26const backgroundThreadId = ThreadId.make("thread:background");
27const oldProviderThreadId = ThreadId.make("thread:old-provider-background");
28const archivedThreadId = ThreadId.make("thread:archived-background");
29const unknownOwnerThreadId = ThreadId.make("thread:unknown-background-owner");
30​
31const backgroundShell = (threadId: ThreadId, providerInstanceId: ProviderInstanceId) => ({
32 ...liveThreadShell(threadId, { activeRunId: null }),
33 pendingBackgroundTasks: [
34 { taskId: "task:background", kind: "subagent" as const, providerInstanceId },
35 ],
36});
37​
38const shells = new Map([
39 [supervisedThreadId, liveThreadShell(supervisedThreadId, { runtimeMode: "approval-required" })],
40 [
41 planThreadId,
42 liveThreadShell(planThreadId, { runtimeMode: "approval-required", interactionMode: "plan" }),
43 ],
44 [fullAccessThreadId, liveThreadShell(fullAccessThreadId)],
45 [endedThreadId, liveThreadShell(endedThreadId, { activeRunId: null })],
46 [backgroundThreadId, backgroundShell(backgroundThreadId, ProviderInstanceId.make("codex"))],
47 [oldProviderThreadId, backgroundShell(oldProviderThreadId, ProviderInstanceId.make("claude"))],
48 [
49 archivedThreadId,
50 {
51 ...backgroundShell(archivedThreadId, ProviderInstanceId.make("codex")),
52 archivedAt: liveThreadShell(archivedThreadId).updatedAt,
53 },
54 ],
55 [
56 unknownOwnerThreadId,
57 {
58 ...liveThreadShell(unknownOwnerThreadId, { activeRunId: null }),
59 pendingBackgroundTasks: [{ taskId: "task:unknown", kind: "subagent" as const }],
60 },
61 ],
62]);
63​
64const threadCaller = (threadId: ThreadId): McpInvocationContext.McpInvocationScope => ({
65 environmentId: EnvironmentId.make("environment"),
66 requestNamespace: `provider:${threadId}`,
67 thread: {
68 threadId,
69 providerSessionId: `provider:${threadId}`,
70 providerInstanceId: ProviderInstanceId.make("codex"),
71 },
72 client: undefined,
73 capabilities: new Set(["orchestration"]),
74 issuedAt: 0,
75});
76​
77const clientCaller = (
78 access: McpInvocationContext.McpClientCaller["access"],
79): McpInvocationContext.McpInvocationScope => ({
80 environmentId: EnvironmentId.make("environment"),
81 requestNamespace: "client:session",
82 thread: undefined,
83 client: { sessionId: "session", label: "Claude Code", access },
84 capabilities: new Set(["orchestration"]),
85 issuedAt: 0,
86});
87​
88const mcpClient = McpSchema.McpServerClient.of({
89 clientId: 1,
90 protocolVersion: "2025-06-18",
91 clientCapabilities: {},
92 clientInfo: { name: "mcp-test", version: "1" },
93 initializePayload: {
94 protocolVersion: "2025-06-18",
95 capabilities: {},
96 clientInfo: { name: "mcp-test", version: "1" },
97 },
98 getClient: Effect.die("unused"),
99});
100​
101const probe = {
102 success: Schema.Struct({ ran: Schema.String }),
103 failure: OrchestratorMcpFailure,
104 failureMode: "return" as const,
105 dependencies: [
106 McpInvocationContext.McpInvocationContext,
107 ThreadManagement.ThreadManagementService,
108 ],
109};
110const ProbeToolkit = Toolkit.make(
111 Tool.make("reads", probe),
112 Tool.make("reads_as_caller", probe),
113 Tool.make("acts_as_caller", probe),
114 Tool.make("writes", probe),
115 Tool.make("writes_with_capability", probe),
116 Tool.make("writes_threads", {
117 ...probe,
118 parameters: Schema.Struct({ threadId: Schema.optional(ThreadId) }),
119 }),
120 Tool.make("starts_threads", {
121 ...probe,
122 parameters: Schema.Struct({
123 runtimeMode: Schema.optional(RuntimeMode),
124 interactionMode: Schema.optional(ProviderInteractionMode),
125 }),
126 }),
127 Tool.make("writes_environment", probe),
128);
129const ran = Effect.succeed({ ran: "ran" });
130const probeHandlers: McpToolAccess.Handlers<typeof ProbeToolkit.tools> = {
131 reads: McpToolAccess.reads(() => ran),
132 reads_as_caller: McpToolAccess.readsAsCaller(() => ran),
133 acts_as_caller: McpToolAccess.actsAsCaller(() => ran),
134 writes: McpToolAccess.writes(() => ran),
135 writes_with_capability: McpToolAccess.writesWithCapability(() => ran),
136 writes_threads: McpToolAccess.writesThreads(
137 (input) => [input.threadId],
138 () => ran,
139 ),
140 starts_threads: McpToolAccess.startsThreads(
141 (input) => input,
142 (_, modes) => Effect.succeed({ ran: `${modes.runtimeMode}/${modes.interactionMode}` }),
143 ),
144 writes_environment: McpToolAccess.writesEnvironment(() => ran),
145};
146const layerProbeHandlers = McpToolAccess.toLayer(ProbeToolkit, probeHandlers);
147​
148const unchecked = () => ran;
149​
150// `@ts-expect-error` fails the build if one ever compiles. Never called.
151export const refusedAtCompileTime = () => {
152 McpToolAccess.toLayer(ProbeToolkit, {
153 ...probeHandlers,
154 // @ts-expect-error a handler that skips its declaration
155 reads: unchecked,
156 });
157 McpToolAccess.toLayer(ProbeToolkit, {
158 ...probeHandlers,
159 // @ts-expect-error a declaration's fields copied onto an unchecked handler
160 reads: Object.assign(
161 unchecked,
162 McpToolAccess.reads(() => ran),
163 ),
164 });
165 // @ts-expect-error a declaration built outside McpToolAccess
166 McpToolAccess.Declaration.make(unchecked);
167 // @ts-expect-error a declaration constructed directly
168 new McpToolAccess.Declaration(unchecked);
169 // @ts-expect-error a handlers layer built outside McpToolAccess
170 McpToolAccess.HandlersLayer.make(Layer.empty);
171 // @effect-diagnostics-next-line anyUnknownInErrorContext:off
172 McpHttpServer.toolkitRegistration(
173 ProbeToolkit,
174 // @ts-expect-error a handlers layer that skipped `McpToolAccess.toLayer`
175 ProbeToolkit.toLayer({
176 reads: unchecked,
177 reads_as_caller: unchecked,
178 acts_as_caller: unchecked,
179 writes: unchecked,
180 writes_with_capability: unchecked,
181 writes_threads: unchecked,
182 starts_threads: unchecked,
183 writes_environment: unchecked,
184 }),
185 );
186};
187​
188const probeServer = (threads: Layer.Layer<ThreadManagement.ThreadManagementService>) =>
189 McpHttpServer.toolkitRegistration(ProbeToolkit, layerProbeHandlers).pipe(
190 Layer.provideMerge(McpServer.McpServer.layer),
191 Layer.provideMerge(threads),
192 );
193​
194const decodeOutcome = Schema.decodeUnknownEffect(
195 Schema.fromJsonString(
196 Schema.Union([Schema.Struct({ ran: Schema.String }), Schema.Struct({ code: Schema.String })]),
197 ),
198);
199​
200const call = (
201 tool: string,
202 scope: McpInvocationContext.McpInvocationScope,
203 args: Record<string, unknown> = {},
204) =>
205 McpServer.McpServer.pipe(
206 Effect.flatMap((server) => server.callTool({ name: tool, arguments: args })),
207 Effect.flatMap(({ content }) =>
208 decodeOutcome(content.map((part) => (part.type === "text" ? part.text : "")).join("")),
209 ),
210 Effect.map((outcome) => ("code" in outcome ? outcome.code : outcome.ran)),
211 Effect.provideService(McpInvocationContext.McpInvocationContext, scope),
212 Effect.provideService(McpSchema.McpServerClient, mcpClient),
213 );
214​
215const supervised = threadCaller(supervisedThreadId);
216const plan = threadCaller(planThreadId);
217const fullAccess = threadCaller(fullAccessThreadId);
218const ended = threadCaller(endedThreadId);
219// Its turn ended, but a background subagent it started still runs.
220const background = threadCaller(backgroundThreadId);
221const oldProviderBackground = threadCaller(oldProviderThreadId);
222const archivedBackground = threadCaller(archivedThreadId);
223const unknownOwnerBackground = threadCaller(unknownOwnerThreadId);
224const mismatchedProvider = {
225 ...background,
226 thread: { ...background.thread!, providerInstanceId: ProviderInstanceId.make("claude") },
227};
228const supervisedClient = clientCaller("approval-required");
229const fullAccessClient = clientCaller("full-access");
230const readOnlyClient = clientCaller("read-only");
231const previewOnly = { ...fullAccess, capabilities: new Set(["preview"] as const) };
232​
233it.effect.each([
234 ["reads", ended, {}, "ran"],
235 ["reads", supervisedClient, {}, "ran"],
236 ["reads", readOnlyClient, {}, "ran"],
237​
238 ["writes", readOnlyClient, {}, "capability_denied"],
239 ["writes_threads", readOnlyClient, { threadId: supervisedThreadId }, "capability_denied"],
240 ["starts_threads", readOnlyClient, {}, "capability_denied"],
241 ["writes_environment", readOnlyClient, {}, "capability_denied"],
242​
243 ["reads_as_caller", ended, {}, "ran"],
244 ["reads_as_caller", fullAccessClient, {}, "thread_credential_required"],
245 ["acts_as_caller", supervised, {}, "ran"],
246 ["acts_as_caller", ended, {}, "parent_not_active"],
247 ["acts_as_caller", background, {}, "ran"],
248 ["acts_as_caller", oldProviderBackground, {}, "parent_not_active"],
249 ["acts_as_caller", mismatchedProvider, {}, "parent_not_active"],
250 ["acts_as_caller", archivedBackground, {}, "parent_not_active"],
251 ["acts_as_caller", unknownOwnerBackground, {}, "parent_not_active"],
252 ["acts_as_caller", fullAccessClient, {}, "thread_credential_required"],
253​
254 ["writes", supervised, {}, "ran"],
255 ["writes", ended, {}, "parent_not_active"],
256 ["writes", background, {}, "ran"],
257 ["writes", oldProviderBackground, {}, "parent_not_active"],
258 ["writes", supervisedClient, {}, "ran"],
259 ["writes", previewOnly, {}, "capability_denied"],
260 ["writes_environment", previewOnly, {}, "capability_denied"],
261​
262 ["writes_with_capability", previewOnly, {}, "ran"],
263 ["writes_with_capability", readOnlyClient, {}, "capability_denied"],
264 ["writes_with_capability", ended, {}, "parent_not_active"],
265​
266 ["writes_threads", supervised, {}, "ran"],
267 ["writes_threads", supervised, { threadId: planThreadId }, "ran"],
268 [
269 "writes_threads",
270 supervised,
271 { threadId: fullAccessThreadId },
272 "runtime_mode_escalation_denied",
273 ],
274 ["writes_threads", plan, { threadId: supervisedThreadId }, "interaction_mode_escalation_denied"],
275 ["writes_threads", fullAccess, { threadId: supervisedThreadId }, "ran"],
276 ["writes_threads", ended, { threadId: supervisedThreadId }, "parent_not_active"],
277 ["writes_threads", supervisedClient, { threadId: supervisedThreadId }, "ran"],
278 [
279 "writes_threads",
280 supervisedClient,
281 { threadId: fullAccessThreadId },
282 "runtime_mode_escalation_denied",
283 ],
284 ["writes_threads", supervised, { threadId: "thread:missing" }, "ran"],
285​
286 ["starts_threads", supervised, {}, "approval-required/default"],
287 ["starts_threads", supervised, { runtimeMode: "full-access" }, "runtime_mode_escalation_denied"],
288 ["starts_threads", plan, {}, "approval-required/plan"],
289 ["starts_threads", plan, { interactionMode: "default" }, "interaction_mode_escalation_denied"],
290 ["starts_threads", fullAccess, { runtimeMode: "auto", interactionMode: "plan" }, "auto/plan"],
291 ["starts_threads", ended, {}, "parent_not_active"],
292 ["starts_threads", supervisedClient, {}, "approval-required/default"],
293 ["starts_threads", supervisedClient, { runtimeMode: "auto" }, "runtime_mode_escalation_denied"],
294 ["starts_threads", fullAccessClient, { runtimeMode: "full-access" }, "full-access/default"],
295​
296 ["writes_environment", fullAccess, {}, "ran"],
297 ["writes_environment", supervised, {}, "capability_denied"],
298 ["writes_environment", plan, {}, "capability_denied"],
299 ["writes_environment", fullAccessClient, {}, "ran"],
300 ["writes_environment", supervisedClient, {}, "capability_denied"],
301] as const)("%s from %o with %o: %s", ([tool, scope, args, expected]) =>
302 call(tool, scope, args).pipe(
303 Effect.map((outcome) => expect(outcome).toBe(expected)),
304 Effect.provide(
305 probeServer(
306 Layer.mock(ThreadManagement.ThreadManagementService)({
307 getThreadShell: (threadId) => Effect.succeed(shells.get(threadId) ?? null),
308 }),
309 ),
310 ),
311 ),
312);
313​
314it("refuses a declaration or handlers layer built outside McpToolAccess", () => {
315 expect(() => Reflect.construct(McpToolAccess.Declaration, [unchecked])).toThrow(TypeError);
316 expect(() => Reflect.construct(McpToolAccess.HandlersLayer, [Layer.empty])).toThrow(TypeError);
317});
318​
319it("refuses a declaration or handlers layer that only wears another's fields", () => {
320 const copiedDeclaration = Object.assign(
321 unchecked,
322 McpToolAccess.reads(() => ran),
323 );
324 expect(() =>
325 McpToolAccess.toLayer(ProbeToolkit, {
326 ...probeHandlers,
327 // @ts-expect-error a declaration's fields copied onto an unchecked handler
328 reads: copiedDeclaration,
329 }),
330 ).toThrow(TypeError);
331 const copiedLayer = Object.assign(Layer.empty, layerProbeHandlers);
332 expect(() => McpToolAccess.HandlersLayer.layer(copiedLayer)).toThrow(TypeError);
333});
334​
335it.effect("refuses a change when the calling thread cannot be read", () =>
336 call("writes", supervised).pipe(
337 Effect.map((outcome) => expect(outcome).toBe("orchestration_error")),
338 Effect.provide(
339 probeServer(
340 Layer.mock(ThreadManagement.ThreadManagementService)({
341 getThreadShell: (threadId) =>
342 Effect.fail(new OrchestratorProjectionError({ threadId, cause: "unreadable" })),
343 }),
344 ),
345 ),
346 ),
347);