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

McpToolAccess.test.ts

341 lines13.0 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);
219const background = threadCaller(backgroundThreadId);
220const oldProviderBackground = threadCaller(oldProviderThreadId);
221const archivedBackground = threadCaller(archivedThreadId);
222const unknownOwnerBackground = threadCaller(unknownOwnerThreadId);
223const mismatchedProvider = {
224 ...background,
225 thread: { ...background.thread!, providerInstanceId: ProviderInstanceId.make("claude") },
226};
227const supervisedClient = clientCaller("approval-required");
228const fullAccessClient = clientCaller("full-access");
229const readOnlyClient = clientCaller("read-only");
230const previewOnly = { ...fullAccess, capabilities: new Set(["preview"] as const) };
231​
232it.effect.each([
233 ["reads", ended, {}, "ran"],
234 ["reads", supervisedClient, {}, "ran"],
235 ["reads", readOnlyClient, {}, "ran"],
236​
237 ["writes", readOnlyClient, {}, "capability_denied"],
238 ["writes_threads", readOnlyClient, { threadId: supervisedThreadId }, "capability_denied"],
239 ["starts_threads", readOnlyClient, {}, "capability_denied"],
240 ["writes_environment", readOnlyClient, {}, "capability_denied"],
241​
242 ["reads_as_caller", ended, {}, "ran"],
243 ["reads_as_caller", fullAccessClient, {}, "thread_credential_required"],
244 ["acts_as_caller", supervised, {}, "ran"],
245 ["acts_as_caller", ended, {}, "parent_not_active"],
246 ["acts_as_caller", background, {}, "ran"],
247 ["acts_as_caller", oldProviderBackground, {}, "parent_not_active"],
248 ["acts_as_caller", mismatchedProvider, {}, "parent_not_active"],
249 ["acts_as_caller", archivedBackground, {}, "parent_not_active"],
250 ["acts_as_caller", unknownOwnerBackground, {}, "parent_not_active"],
251 ["acts_as_caller", fullAccessClient, {}, "thread_credential_required"],
252​
253 ["writes", supervised, {}, "ran"],
254 ["writes", ended, {}, "parent_not_active"],
255 ["writes", background, {}, "ran"],
256 ["writes", oldProviderBackground, {}, "parent_not_active"],
257 ["writes", supervisedClient, {}, "ran"],
258 ["writes", previewOnly, {}, "capability_denied"],
259 ["writes_environment", previewOnly, {}, "capability_denied"],
260​
261 ["writes_with_capability", previewOnly, {}, "ran"],
262 ["writes_with_capability", readOnlyClient, {}, "capability_denied"],
263 ["writes_with_capability", ended, {}, "parent_not_active"],
264​
265 ["writes_threads", supervised, {}, "ran"],
266 ["writes_threads", supervised, { threadId: planThreadId }, "ran"],
267 [
268 "writes_threads",
269 supervised,
270 { threadId: fullAccessThreadId },
271 "runtime_mode_escalation_denied",
272 ],
273 ["writes_threads", plan, { threadId: supervisedThreadId }, "interaction_mode_escalation_denied"],
274 ["writes_threads", fullAccess, { threadId: supervisedThreadId }, "ran"],
275 ["writes_threads", ended, { threadId: supervisedThreadId }, "parent_not_active"],
276 ["writes_threads", supervisedClient, { threadId: supervisedThreadId }, "ran"],
277 [
278 "writes_threads",
279 supervisedClient,
280 { threadId: fullAccessThreadId },
281 "runtime_mode_escalation_denied",
282 ],
283 ["writes_threads", supervised, { threadId: "thread:missing" }, "ran"],
284​
285 ["starts_threads", supervised, {}, "approval-required/default"],
286 ["starts_threads", supervised, { runtimeMode: "full-access" }, "runtime_mode_escalation_denied"],
287 ["starts_threads", plan, {}, "approval-required/plan"],
288 ["starts_threads", plan, { interactionMode: "default" }, "interaction_mode_escalation_denied"],
289 ["starts_threads", fullAccess, { runtimeMode: "auto", interactionMode: "plan" }, "auto/plan"],
290 ["starts_threads", ended, {}, "parent_not_active"],
291 ["starts_threads", supervisedClient, {}, "approval-required/default"],
292 ["starts_threads", supervisedClient, { runtimeMode: "auto" }, "runtime_mode_escalation_denied"],
293 ["starts_threads", fullAccessClient, { runtimeMode: "full-access" }, "full-access/default"],
294​
295 ["writes_environment", fullAccess, {}, "ran"],
296 ["writes_environment", supervised, {}, "capability_denied"],
297 ["writes_environment", plan, {}, "capability_denied"],
298 ["writes_environment", fullAccessClient, {}, "ran"],
299 ["writes_environment", supervisedClient, {}, "capability_denied"],
300] as const)("%s from %o with %o: %s", ([tool, scope, args, expected]) =>
301 call(tool, scope, args).pipe(
302 Effect.map((outcome) => expect(outcome).toBe(expected)),
303 Effect.provide(
304 probeServer(
305 Layer.mock(ThreadManagement.ThreadManagementService)({
306 getThreadShell: (threadId) => Effect.succeed(shells.get(threadId) ?? null),
307 }),
308 ),
309 ),
310 ),
311);
312​
313it("refuses a declaration or handlers layer that only wears another's fields", () => {
314 const copiedDeclaration = Object.assign(
315 unchecked,
316 McpToolAccess.reads(() => ran),
317 );
318 expect(() =>
319 McpToolAccess.toLayer(ProbeToolkit, {
320 ...probeHandlers,
321 // @ts-expect-error a declaration's fields copied onto an unchecked handler
322 reads: copiedDeclaration,
323 }),
324 ).toThrow(TypeError);
325 const copiedLayer = Object.assign(Layer.empty, layerProbeHandlers);
326 expect(() => McpToolAccess.HandlersLayer.layer(copiedLayer)).toThrow(TypeError);
327});
328​
329it.effect("refuses a change when the calling thread cannot be read", () =>
330 call("writes", supervised).pipe(
331 Effect.map((outcome) => expect(outcome).toBe("orchestration_error")),
332 Effect.provide(
333 probeServer(
334 Layer.mock(ThreadManagement.ThreadManagementService)({
335 getThreadShell: (threadId) =>
336 Effect.fail(new OrchestratorProjectionError({ threadId, cause: "unreadable" })),
337 }),
338 ),
339 ),
340 ),
341);