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

McpToolAccess.test.ts

314 lines12.3 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​
74// One tool per declaration, each answering with the modes it was handed, so
75// the table below reads what the gate let through.
76const probe = {
77 success: Schema.Struct({ ran: Schema.String }),
78 failure: OrchestratorMcpFailure,
79 failureMode: "return" as const,
80 dependencies: [
81 McpInvocationContext.McpInvocationContext,
82 ThreadManagement.ThreadManagementService,
83 ],
84};
85const ProbeToolkit = Toolkit.make(
86 Tool.make("reads", probe),
87 Tool.make("reads_as_caller", probe),
88 Tool.make("acts_as_caller", probe),
89 Tool.make("writes", probe),
90 Tool.make("writes_threads", {
91 ...probe,
92 parameters: Schema.Struct({ threadId: Schema.optional(ThreadId) }),
93 }),
94 Tool.make("starts_threads", {
95 ...probe,
96 parameters: Schema.Struct({
97 runtimeMode: Schema.optional(RuntimeMode),
98 interactionMode: Schema.optional(ProviderInteractionMode),
99 }),
100 }),
101 Tool.make("writes_environment", probe),
102);
103const ran = Effect.succeed({ ran: "ran" });
104const probeHandlers: McpToolAccess.Handlers<typeof ProbeToolkit.tools> = {
105 reads: McpToolAccess.reads(() => ran),
106 reads_as_caller: McpToolAccess.readsAsCaller(() => ran),
107 acts_as_caller: McpToolAccess.actsAsCaller(() => ran),
108 writes: McpToolAccess.writes(() => 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// What the compiler refuses: each line below must fail to typecheck, and its
124// `@ts-expect-error` fails the build if one ever compiles. Never called.
125export const refusedAtCompileTime = () => {
126 McpToolAccess.toLayer(ProbeToolkit, {
127 ...probeHandlers,
128 // @ts-expect-error a handler that skips its declaration
129 reads: unchecked,
130 });
131 McpToolAccess.toLayer(ProbeToolkit, {
132 ...probeHandlers,
133 // @ts-expect-error a declaration's fields copied onto an unchecked handler
134 reads: Object.assign(
135 unchecked,
136 McpToolAccess.reads(() => ran),
137 ),
138 });
139 // @ts-expect-error a declaration built outside McpToolAccess
140 McpToolAccess.Declaration.make(unchecked);
141 // @ts-expect-error a declaration constructed directly
142 new McpToolAccess.Declaration(unchecked);
143 // @ts-expect-error a handlers layer built outside McpToolAccess
144 McpToolAccess.HandlersLayer.make(Layer.empty);
145 // The refused layer below types its error and services as unknown, which is fine here.
146 // @effect-diagnostics-next-line anyUnknownInErrorContext:off
147 McpHttpServer.toolkitRegistration(
148 ProbeToolkit,
149 // @ts-expect-error a handlers layer that skipped `McpToolAccess.toLayer`
150 ProbeToolkit.toLayer({
151 reads: unchecked,
152 reads_as_caller: unchecked,
153 acts_as_caller: unchecked,
154 writes: unchecked,
155 writes_threads: unchecked,
156 starts_threads: unchecked,
157 writes_environment: unchecked,
158 }),
159 );
160};
161​
162const probeServer = (threads: Layer.Layer<ThreadManagement.ThreadManagementService>) =>
163 McpHttpServer.toolkitRegistration(ProbeToolkit, layerProbeHandlers).pipe(
164 Layer.provideMerge(McpServer.McpServer.layer),
165 Layer.provideMerge(threads),
166 );
167​
168/** A probe's answer, or the gate's refusal, as the result's JSON text. */
169const decodeOutcome = Schema.decodeUnknownEffect(
170 Schema.fromJsonString(
171 Schema.Union([Schema.Struct({ ran: Schema.String }), Schema.Struct({ code: Schema.String })]),
172 ),
173);
174​
175const call = (
176 tool: string,
177 scope: McpInvocationContext.McpInvocationScope,
178 args: Record<string, unknown> = {},
179) =>
180 McpServer.McpServer.pipe(
181 Effect.flatMap((server) => server.callTool({ name: tool, arguments: args })),
182 Effect.flatMap(({ content }) =>
183 decodeOutcome(content.map((part) => (part.type === "text" ? part.text : "")).join("")),
184 ),
185 Effect.map((outcome) => ("code" in outcome ? outcome.code : outcome.ran)),
186 Effect.provideService(McpInvocationContext.McpInvocationContext, scope),
187 Effect.provideService(McpSchema.McpServerClient, mcpClient),
188 );
189​
190const supervised = threadCaller(supervisedThreadId);
191const plan = threadCaller(planThreadId);
192const fullAccess = threadCaller(fullAccessThreadId);
193const ended = threadCaller(endedThreadId);
194const supervisedClient = clientCaller("approval-required");
195const fullAccessClient = clientCaller("full-access");
196const readOnlyClient = clientCaller("read-only");
197// A live full-access thread whose credential may use its browser but not control threads.
198const previewOnly = { ...fullAccess, capabilities: new Set(["preview"] as const) };
199​
200it.effect.each([
201 // Reads are open to every caller, even one whose turn ended.
202 ["reads", ended, {}, "ran"],
203 ["reads", supervisedClient, {}, "ran"],
204 ["reads", readOnlyClient, {}, "ran"],
205​
206 // A client approved for read-only access changes nothing.
207 ["writes", readOnlyClient, {}, "capability_denied"],
208 ["writes_threads", readOnlyClient, { threadId: supervisedThreadId }, "capability_denied"],
209 ["starts_threads", readOnlyClient, {}, "capability_denied"],
210 ["writes_environment", readOnlyClient, {}, "capability_denied"],
211​
212 // What belongs to the calling thread needs one; changing it needs its live turn.
213 ["reads_as_caller", ended, {}, "ran"],
214 ["reads_as_caller", fullAccessClient, {}, "thread_credential_required"],
215 ["acts_as_caller", supervised, {}, "ran"],
216 ["acts_as_caller", ended, {}, "parent_not_active"],
217 ["acts_as_caller", fullAccessClient, {}, "thread_credential_required"],
218​
219 // Any change needs a thread caller's live turn; a client has none to lose.
220 ["writes", supervised, {}, "ran"],
221 ["writes", ended, {}, "parent_not_active"],
222 ["writes", supervisedClient, {}, "ran"],
223 // Uploads, scheduled tasks, projects and settings need a credential that controls threads.
224 ["writes", previewOnly, {}, "capability_denied"],
225 ["writes_environment", previewOnly, {}, "capability_denied"],
226​
227 // Changing a thread: only one that runs within the caller's modes.
228 ["writes_threads", supervised, {}, "ran"],
229 ["writes_threads", supervised, { threadId: planThreadId }, "ran"],
230 [
231 "writes_threads",
232 supervised,
233 { threadId: fullAccessThreadId },
234 "runtime_mode_escalation_denied",
235 ],
236 ["writes_threads", plan, { threadId: supervisedThreadId }, "interaction_mode_escalation_denied"],
237 ["writes_threads", fullAccess, { threadId: supervisedThreadId }, "ran"],
238 ["writes_threads", ended, { threadId: supervisedThreadId }, "parent_not_active"],
239 ["writes_threads", supervisedClient, { threadId: supervisedThreadId }, "ran"],
240 [
241 "writes_threads",
242 supervisedClient,
243 { threadId: fullAccessThreadId },
244 "runtime_mode_escalation_denied",
245 ],
246 // A thread that does not exist is the tool's to report.
247 ["writes_threads", supervised, { threadId: "thread:missing" }, "ran"],
248​
249 // Starting a thread: the caller's own modes or narrower.
250 ["starts_threads", supervised, {}, "approval-required/default"],
251 ["starts_threads", supervised, { runtimeMode: "full-access" }, "runtime_mode_escalation_denied"],
252 ["starts_threads", plan, {}, "approval-required/plan"],
253 ["starts_threads", plan, { interactionMode: "default" }, "interaction_mode_escalation_denied"],
254 ["starts_threads", fullAccess, { runtimeMode: "auto", interactionMode: "plan" }, "auto/plan"],
255 ["starts_threads", ended, {}, "parent_not_active"],
256 ["starts_threads", supervisedClient, {}, "approval-required/default"],
257 ["starts_threads", supervisedClient, { runtimeMode: "auto" }, "runtime_mode_escalation_denied"],
258 ["starts_threads", fullAccessClient, { runtimeMode: "full-access" }, "full-access/default"],
259​
260 // Projects and environment settings need full access.
261 ["writes_environment", fullAccess, {}, "ran"],
262 ["writes_environment", supervised, {}, "capability_denied"],
263 ["writes_environment", plan, {}, "capability_denied"],
264 ["writes_environment", fullAccessClient, {}, "ran"],
265 ["writes_environment", supervisedClient, {}, "capability_denied"],
266] as const)("%s from %o with %o: %s", ([tool, scope, args, expected]) =>
267 call(tool, scope, args).pipe(
268 Effect.map((outcome) => expect(outcome).toBe(expected)),
269 Effect.provide(
270 probeServer(
271 Layer.mock(ThreadManagement.ThreadManagementService)({
272 getThreadShell: (threadId) => Effect.succeed(shells.get(threadId) ?? null),
273 }),
274 ),
275 ),
276 ),
277);
278​
279it("refuses a declaration or handlers layer built outside McpToolAccess", () => {
280 // Private constructors only bind the type checker; Reflect.construct reaches them anyway.
281 expect(() => Reflect.construct(McpToolAccess.Declaration, [unchecked])).toThrow(TypeError);
282 expect(() => Reflect.construct(McpToolAccess.HandlersLayer, [Layer.empty])).toThrow(TypeError);
283});
284​
285it("refuses a declaration or handlers layer that only wears another's fields", () => {
286 // The types already refuse these; at runtime the private fields are missing too.
287 const copiedDeclaration = Object.assign(
288 unchecked,
289 McpToolAccess.reads(() => ran),
290 );
291 expect(() =>
292 McpToolAccess.toLayer(ProbeToolkit, {
293 ...probeHandlers,
294 // @ts-expect-error a declaration's fields copied onto an unchecked handler
295 reads: copiedDeclaration,
296 }),
297 ).toThrow(TypeError);
298 const copiedLayer = Object.assign(Layer.empty, layerProbeHandlers);
299 expect(() => McpToolAccess.HandlersLayer.layer(copiedLayer)).toThrow(TypeError);
300});
301​
302it.effect("refuses a change when the calling thread cannot be read", () =>
303 call("writes", supervised).pipe(
304 Effect.map((outcome) => expect(outcome).toBe("orchestration_error")),
305 Effect.provide(
306 probeServer(
307 Layer.mock(ThreadManagement.ThreadManagementService)({
308 getThreadShell: (threadId) =>
309 Effect.fail(new OrchestratorProjectionError({ threadId, cause: "unreadable" })),
310 }),
311 ),
312 ),
313 ),
314);