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

McpToolAccess.test.ts

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