Open History to see the last commit
1import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
2import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
3import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
4import { expect, it } from "@effect/vitest";
5import { NodeHttpServer } from "@effect/platform-node";
6import * as NodeServices from "@effect/platform-node/NodeServices";
7import {
8 DeviceId,
9 DeviceOperationError,
10 EnvironmentId,
11 OrchestratorMcpEnvironmentTarget,
12 OrchestratorMcpFailure,
13 PreviewTabId,
14 ProviderInstanceId,
15 ProviderInteractionMode,
16 RuntimeMode,
17 ThreadId,
18} from "@t3tools/contracts";
19import * as Context from "effect/Context";
20import * as Deferred from "effect/Deferred";
21import * as Effect from "effect/Effect";
22import * as Layer from "effect/Layer";
23import * as Schema from "effect/Schema";
24import * as Stream from "effect/Stream";
25import { McpSchema, McpServer, Tool, Toolkit } from "effect/ai";
26import { HttpBody, HttpClient, HttpClientRequest, HttpRouter } from "effect/http";
27
28import * as ProjectService from "../project/ProjectService.ts";
29import * as DeviceService from "../device/DeviceService.ts";
30import * as PullRequestReviewGuideService from "../pullRequest/PullRequestReviewGuideService.ts";
31import * as ServerConfig from "../config.ts";
32import * as ServerSettings from "../serverSettings.ts";
33import { advertisedJsonSchema } from "./advertisedJsonSchema.ts";
34import * as McpHttpServer from "./McpHttpServer.ts";
35import * as McpToolAccess from "./McpToolAccess.ts";
36import * as McpToolAccessTestkit from "./McpToolAccess.testkit.ts";
37import * as McpInvocationContext from "./McpInvocationContext.ts";
38import * as McpSessionRegistry from "./McpSessionRegistry.ts";
39import * as OrchestratorMcpService from "./OrchestratorMcpService.ts";
40import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
41import { OrchestratorToolkit } from "./toolkits/orchestrator/tools.ts";
42import { PreviewToolkit } from "./toolkits/preview/tools.ts";
43import { ProjectToolkit } from "./toolkits/project/tools.ts";
44
45const environmentId = EnvironmentId.make("environment-mcp-test");
46const threadId = ThreadId.make("thread-mcp-test");
47const alternateTabId = PreviewTabId.make("tab-mcp-alternate");
48const decodeJsonText = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
49const invocation = {
50 environmentId,
51 requestNamespace: "provider-session-mcp-test",
52 thread: {
53 threadId,
54 providerSessionId: "provider-session-mcp-test",
55 providerInstanceId: ProviderInstanceId.make("codex"),
56 },
57 client: undefined,
58 capabilities: new Set(["preview"] as const),
59 issuedAt: 1,
60};
61const client = McpSchema.McpServerClient.of({
62 clientId: 1,
63 clientCapabilities: {},
64 clientInfo: { name: "mcp-test", version: "1.0.0" },
65 protocolVersion: "2025-06-18",
66 initializePayload: {
67 protocolVersion: "2025-06-18",
68 capabilities: {},
69 clientInfo: { name: "mcp-test", version: "1.0.0" },
70 },
71 getClient: Effect.die("unused"),
72});
73const layerTest = McpHttpServer.layerPreviewToolkit.pipe(
74 Layer.provideMerge(McpServer.McpServer.layer),
75 Layer.provideMerge(McpToolAccessTestkit.liveThreadsLayer),
76 Layer.provideMerge(PreviewAutomationBroker.layer),
77 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-http-server-test-" })),
78 Layer.provideMerge(NodeServices.layer),
79);
80const layerPullRequestsTest = McpHttpServer.layerPullRequestsToolkit.pipe(
81 Layer.provideMerge(McpServer.McpServer.layer),
82 Layer.provideMerge(McpToolAccessTestkit.liveThreadsLayer),
83 Layer.provide(
84 Layer.mergeAll(
85 Layer.mock(ProjectService.ProjectService)({}),
86 Layer.mock(PullRequestReviewGuideService.PullRequestReviewGuideService)({}),
87 Layer.mock(Orchestrator.OrchestratorV2)({}),
88 Layer.mock(ProjectionStore.ProjectionStoreV2)({}),
89 NodeServices.layer,
90 ),
91 ),
92);
93
94const snapshotResult = {
95 url: "http://example.test/",
96 title: "Example",
97 loading: false,
98 visibleText: "Example",
99 interactiveElements: [],
100 accessibilityTree: {},
101 consoleEntries: [],
102 networkEntries: [],
103 actionTimeline: [],
104 screenshot: {
105 mimeType: "image/png",
106 data: Buffer.from("png").toString("base64"),
107 width: 10,
108 height: 5,
109 },
110};
111
112const serveSnapshots = (clientId: string, result: unknown) =>
113 Effect.gen(function* () {
114 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
115 const connected = yield* Deferred.make<void>();
116 const inputs: Array<unknown> = [];
117 const events = yield* broker.connect({ clientId, environmentId });
118 yield* Stream.runForEach(events, (event) => {
119 if (event.type === "connected") return Deferred.succeed(connected, undefined);
120 inputs.push(event.request.input);
121 return broker.respond({
122 clientId,
123 connectionId: event.connectionId,
124 requestId: event.request.requestId,
125 ok: true,
126 result,
127 });
128 }).pipe(Effect.forkScoped);
129 yield* Deferred.await(connected);
130 return inputs;
131 });
132
133const callTool = (name: string, args: Record<string, unknown>) =>
134 Effect.gen(function* () {
135 const server = yield* McpServer.McpServer;
136 return yield* server
137 .callTool({ name, arguments: args })
138 .pipe(
139 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
140 Effect.provideService(McpSchema.McpServerClient, client),
141 );
142 });
143
144const callSnapshot = (args: Record<string, unknown>) => callTool("preview_snapshot", args);
145
146it.effect.each([
147 { input: {}, open: false, message: "No device is open in this thread. Call device_open first." },
148 {
149 input: { deviceId: "missing", hostId: "local" },
150 open: false,
151 message: "Device missing is not open in this thread. Call device_open first.",
152 },
153 {
154 input: {},
155 open: true,
156 message:
157 "Device screenshot failed: Could not communicate with device support. Try refreshing devices.",
158 },
159 {
160 input: {},
161 open: true,
162 rejected: true,
163 message:
164 "Device screenshot failed: The device hub could not complete the request. Call device_list to check the device state, and device_open if it needs to be reopened.",
165 },
166])(
167 "preserves actionable screenshot failure text: $message",
168 ({ input, open, message, ...options }) =>
169 Effect.gen(function* () {
170 const server = yield* McpServer.McpServer;
171 const result = yield* server.callTool({ name: "device_screenshot", arguments: input }).pipe(
172 Effect.provideService(McpInvocationContext.McpInvocationContext, {
173 ...invocation,
174 capabilities: new Set(["device"] as const),
175 }),
176 Effect.provideService(McpSchema.McpServerClient, client),
177 );
178 expect(result.isError).toBe(true);
179 expect(result.content).toEqual([{ type: "text", text: message }]);
180 expect(result.structuredContent).toMatchObject({
181 error: { message, operation: "screenshot" },
182 });
183 expect(JSON.stringify(result)).not.toContain("private hub output");
184 }).pipe(
185 Effect.provide(
186 McpHttpServer.layerDeviceToolkit.pipe(
187 Layer.provideMerge(McpServer.McpServer.layer),
188 Layer.provide(McpToolAccessTestkit.liveThreadsLayer),
189 Layer.provide(
190 Layer.mock(DeviceService.DeviceService)({
191 locateSession: () => Effect.succeedNone,
192 sessionsForThread: () =>
193 Effect.succeed(
194 open
195 ? [
196 {
197 threadId,
198 hostId: "local",
199 deviceId: DeviceId.make("phone"),
200 platform: "ios",
201 openedAt: "2026-10-23T00:00:00Z",
202 },
203 ]
204 : [],
205 ),
206 screenshot: () =>
207 Effect.fail(
208 new DeviceOperationError({
209 operation: "screenshot",
210 reason:
211 "rejected" in options && options.rejected ? "hub_rejected" : "request_failed",
212 cause: new Error("private hub output"),
213 }),
214 ),
215 }),
216 ),
217 Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
218 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-device-mcp-test-" })),
219 Layer.provide(NodeServices.layer),
220 ),
221 ),
222 Effect.scoped,
223 ),
224);
225
226const layerRecordingTools = (calls: Array<unknown>) => {
227 const RecordingToolkit = Toolkit.make(
228 OrchestratorToolkit.tools.delegate_task,
229 OrchestratorToolkit.tools.t3_thread_read,
230 OrchestratorToolkit.tools.t3_thread_wait,
231 ProjectToolkit.tools.t3_project_update,
232 );
233 const record = McpToolAccess.reads((params: unknown) =>
234 Effect.sync(() => calls.push(params)).pipe(
235 Effect.andThen(
236 Effect.fail(new OrchestratorMcpFailure({ code: "thread_not_found", message: "Recorded." })),
237 ),
238 ),
239 );
240 return McpHttpServer.toolkitRegistration(
241 RecordingToolkit,
242 McpToolAccess.toLayer(RecordingToolkit, {
243 delegate_task: record,
244 t3_thread_read: record,
245 t3_thread_wait: record,
246 t3_project_update: record,
247 }),
248 ).pipe(
249 Layer.provideMerge(McpServer.McpServer.layer),
250 Layer.provide(
251 Layer.mergeAll(
252 McpToolAccessTestkit.liveThreadsLayer,
253 Layer.mock(OrchestratorMcpService.OrchestratorMcpService)({}),
254 Layer.mock(ProjectService.ProjectService)({}),
255 NodeServices.layer,
256 ),
257 ),
258 );
259};
260
261it.effect.each([{}, { includeImage: false }])(
262 "returns bounded structural preview snapshot failures %#",
263 (input) =>
264 Effect.scoped(
265 Effect.gen(function* () {
266 const server = yield* McpServer.McpServer;
267 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
268 const events = yield* broker.connect({
269 clientId: "mcp-failure-client",
270 environmentId,
271 });
272 yield* Stream.runForEach(events, (event) =>
273 event.type === "connected"
274 ? Effect.void
275 : broker.respond({
276 clientId: "mcp-failure-client",
277 connectionId: event.connectionId,
278 requestId: event.request.requestId,
279 ok: false,
280 error: {
281 _tag: "PreviewAutomationExecutionError",
282 message: "sensitive renderer failure",
283 detail: { consoleOutput: "sensitive browser output" },
284 },
285 }),
286 ).pipe(Effect.forkScoped);
287 yield* Effect.yieldNow;
288
289 const snapshot = yield* server
290 .callTool({ name: "preview_snapshot", arguments: input })
291 .pipe(
292 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
293 Effect.provideService(McpSchema.McpServerClient, client),
294 );
295
296 const message = "Preview automation snapshot failed on client mcp-failure-client.";
297 expect(snapshot.isError).toBe(true);
298 expect(snapshot.content).toEqual([
299 { type: "text", text: `Preview snapshot failed: ${message}` },
300 ]);
301 expect(snapshot.structuredContent).toEqual({
302 error: {
303 _tag: "PreviewAutomationExecutionError",
304 operation: "snapshot",
305 failureCount: 1,
306 message,
307 },
308 });
309 }),
310 ).pipe(Effect.provide(layerTest)),
311);
312
313it.effect.each([
314 { mode: "default", input: {}, images: false },
315 { mode: "explicit image", input: { includeImage: true }, images: true },
316 { mode: "text only", input: { includeImage: false }, images: false },
317])("returns fresh $mode snapshots on repeated MCP calls", ({ input, images }) =>
318 Effect.scoped(
319 Effect.gen(function* () {
320 const server = yield* McpServer.McpServer;
321 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
322 const connected = yield* Deferred.make<void>();
323 const png =
324 "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII=";
325 const page = {
326 url: "http://example.test/",
327 loading: false,
328 visibleText: "Save your changes",
329 interactiveElements: [
330 {
331 tag: "button",
332 role: "button",
333 name: "Save",
334 selector: "#save",
335 x: 0,
336 y: 0,
337 width: 20,
338 height: 10,
339 },
340 ],
341 accessibilityTree: { role: "document", name: "Example" },
342 consoleEntries: [],
343 networkEntries: [],
344 actionTimeline: [],
345 };
346 const screenshot = { mimeType: "image/png", width: 1, height: 1 };
347 let requests = 0;
348 const events = yield* broker.connect({ clientId: "mcp-image-option-client", environmentId });
349 yield* Stream.runForEach(events, (event) => {
350 if (event.type === "connected") return Deferred.succeed(connected, undefined);
351 requests += 1;
352 expect(event.request).toMatchObject({
353 operation: "snapshot",
354 tabId: alternateTabId,
355 threadId,
356 });
357 expect(event.request.input).toEqual({});
358 return broker.respond({
359 clientId: "mcp-image-option-client",
360 connectionId: event.connectionId,
361 requestId: event.request.requestId,
362 ok: true,
363 result: {
364 ...page,
365 title: `Snapshot ${requests}`,
366 screenshot: { ...screenshot, data: png },
367 },
368 });
369 }).pipe(Effect.forkScoped);
370 yield* Deferred.await(connected);
371
372 for (const call of [1, 2, 3, 4, 5, 6]) {
373 const snapshot = yield* server
374 .callTool({
375 name: "preview_snapshot",
376 arguments: { ...input, tabId: alternateTabId },
377 })
378 .pipe(
379 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
380 Effect.provideService(McpSchema.McpServerClient, client),
381 );
382 const metadata = { ...page, title: `Snapshot ${call}`, screenshot };
383 const { accessibilityTree: _tree, ...boundedMetadata } = metadata;
384 expect(snapshot.isError).toBe(false);
385 expect(snapshot.structuredContent).toEqual({
386 ...boundedMetadata,
387 omitted: ["accessibilityTree (use interactiveElements locators or preview_evaluate)"],
388 });
389 const [identity, text, ...rest] = snapshot.content;
390 expect(identity?.type === "text" ? decodeJsonText(identity.text) : null).toEqual({
391 url: page.url,
392 });
393 expect(text?.type === "text" ? decodeJsonText(text.text) : null).toEqual(boundedMetadata);
394 expect(rest).toEqual([
395 {
396 type: "text",
397 text: "Snapshot text was bounded. Omitted: accessibilityTree (use interactiveElements locators or preview_evaluate).",
398 },
399 ...(images
400 ? [
401 {
402 type: "image",
403 mimeType: "image/png",
404 data: new Uint8Array(Buffer.from(png, "base64")),
405 },
406 ]
407 : []),
408 ]);
409 }
410
411 const nextDefault = yield* server
412 .callTool({
413 name: "preview_snapshot",
414 arguments: { tabId: alternateTabId },
415 })
416 .pipe(
417 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
418 Effect.provideService(McpSchema.McpServerClient, client),
419 );
420 expect(nextDefault.content.map((content) => content.type)).toEqual(["text", "text", "text"]);
421 expect(nextDefault.structuredContent).toMatchObject({ title: "Snapshot 7", screenshot });
422 expect(nextDefault.structuredContent).not.toHaveProperty("accessibilityTree");
423 expect(requests).toBe(7);
424 }),
425 ).pipe(Effect.provide(layerTest)),
426);
427
428it.effect("refuses preview tools to a client outside a thread before they run", () =>
429 Effect.gen(function* () {
430 const server = yield* McpServer.McpServer;
431 const readOnly = {
432 ...invocation,
433 thread: undefined,
434 requestNamespace: "client:session-1",
435 client: { sessionId: "session-1", label: "Claude Code", access: "read-only" as const },
436 };
437 const click = yield* server
438 .callTool({ name: "preview_act", arguments: { action: "click", locator: "text=Send" } })
439 .pipe(
440 Effect.provideService(McpInvocationContext.McpInvocationContext, readOnly),
441 Effect.provideService(McpSchema.McpServerClient, client),
442 );
443 expect(click.isError).toBe(true);
444 expect(click.content).toEqual([
445 { type: "text", text: expect.stringContaining("needs an agent running inside T3 Code") },
446 ]);
447 }).pipe(Effect.provide(layerTest)),
448);
449
450it.effect("advertises the compact input schema for every registered tool", () =>
451 Effect.gen(function* () {
452 const server = yield* McpServer.McpServer;
453 const tools: Record<string, Tool.Any> = PreviewToolkit.tools;
454
455 expect(server.tools.length).toBe(Object.keys(tools).length);
456 for (const { tool } of server.tools) {
457 expect(tool.inputSchema, tool.name).toEqual(advertisedJsonSchema(tools[tool.name]!));
458 }
459 }).pipe(Effect.provide(layerTest)),
460);
461
462it.effect("checks each preview_act action against that action's own input", () =>
463 Effect.scoped(
464 Effect.gen(function* () {
465 const inputs = yield* serveSnapshots("mcp-act-client", {});
466
467 const missingKey = yield* callTool("preview_act", { action: "press" });
468 expect(missingKey.isError).toBe(true);
469 expect(inputs).toEqual([]);
470
471 const click = yield* callTool("preview_act", {
472 action: "click",
473 locator: "text=Send",
474 key: "Enter",
475 });
476 expect(click.isError).toBe(false);
477 expect(inputs[0]).toEqual({ locator: "text=Send" });
478
479 yield* callTool("preview_act", { action: "type", selector: "#name", text: "Ada" });
480 expect(inputs.at(-2)).toEqual({ selector: "#name", text: "Ada" });
481 }),
482 ).pipe(Effect.provide(layerTest)),
483);
484
485it.effect("decodes null optional arguments the way it decodes omitted ones", () => {
486 const calls: Array<unknown> = [];
487 return Effect.gen(function* () {
488 const thread = { threadId: "thread-null-arguments" };
489 yield* callTool("t3_thread_read", thread);
490 yield* callTool("t3_thread_read", { ...thread, afterPosition: null, view: null });
491 yield* callTool("delegate_task", { task: "Inspect", target: {} });
492 yield* callTool("delegate_task", { task: "Inspect", title: null, target: { model: null } });
493 yield* callTool("t3_project_update", { projectId: "project-1", projectIcon: null });
494
495 expect(calls).toHaveLength(5);
496 expect(calls[1]).toEqual(calls[0]);
497 expect(calls[3]).toEqual(calls[2]);
498 expect(calls[4]).toStrictEqual({ projectId: "project-1", projectIcon: null });
499 }).pipe(Effect.provide(layerRecordingTools(calls)));
500});
501
502it.effect(
503 "clamps t3_thread_read page sizes above their maximum instead of rejecting the call",
504 () => {
505 const calls: Array<unknown> = [];
506 return Effect.gen(function* () {
507 const thread = { threadId: "thread-clamped-arguments" };
508 // Codex never shows the model these bounds, so an over-large page must still read.
509 yield* callTool("t3_thread_read", {
510 ...thread,
511 limit: 150,
512 runLimit: 80,
513 maxCharsPerItem: 60_000,
514 });
515 yield* callTool("t3_thread_read", {
516 ...thread,
517 limit: 100,
518 runLimit: 50,
519 maxCharsPerItem: 50_000,
520 });
521 yield* callTool("t3_thread_read", { ...thread, limit: 7, runLimit: 1, maxCharsPerItem: 1 });
522
523 expect(calls).toEqual([
524 { ...thread, limit: 100, runLimit: 50, maxCharsPerItem: 50_000 },
525 { ...thread, limit: 100, runLimit: 50, maxCharsPerItem: 50_000 },
526 { ...thread, limit: 7, runLimit: 1, maxCharsPerItem: 1 },
527 ]);
528 }).pipe(Effect.provide(layerRecordingTools(calls)));
529 },
530);
531
532it.effect.each(["limit", "runLimit", "maxCharsPerItem"])(
533 "still rejects a t3_thread_read %s below its minimum",
534 (field) => {
535 const calls: Array<unknown> = [];
536 return Effect.gen(function* () {
537 // Zero is a different request than one item, so it fails rather than answering another question.
538 const rejected = yield* callTool("t3_thread_read", {
539 threadId: "thread-below-minimum",
540 [field]: 0,
541 }).pipe(Effect.flip);
542
543 expect(String(rejected)).toContain("greater than or equal to 1");
544 expect(calls).toEqual([]);
545 }).pipe(Effect.provide(layerRecordingTools(calls)));
546 },
547);
548
549it("keeps cross-tool routing out of the delegate_task description", () => {
550 const description = OrchestratorToolkit.tools.delegate_task.description ?? "";
551 expect(description).toContain("Start one child agent with only `task`");
552 // Review rounds, follow-ups, and polling are routed in the system text.
553 expect(description).not.toContain("t3_thread_send");
554 expect(description).not.toContain("Do not poll");
555 expect(description).not.toContain("Prefer native");
556});
557
558it.effect(
559 "registers the pull request toolkit and surfaces a missing capability as a tool error",
560 () =>
561 Effect.gen(function* () {
562 const server = yield* McpServer.McpServer;
563 const names = server.tools.map(({ tool }) => tool.name);
564 expect(names).toEqual(
565 expect.arrayContaining([
566 "link_pull_request",
567 "unlink_pull_request",
568 "list_thread_pull_requests",
569 ]),
570 );
571 const linkTool = server.tools.find(({ tool }) => tool.name === "link_pull_request");
572 expect(linkTool?.tool.annotations?.idempotentHint).toBe(true);
573 expect(linkTool?.tool.annotations?.openWorldHint).toBe(false);
574 expect(linkTool?.tool.description).toContain("Link a PR to this thread");
575 expect(linkTool?.tool.description).toContain("settles the thread on merge");
576
577 const denied = yield* server
578 .callTool({ name: "list_thread_pull_requests", arguments: {} })
579 .pipe(
580 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
581 Effect.provideService(McpSchema.McpServerClient, client),
582 );
583 expect(denied.isError).toBe(true);
584 expect(denied.content).toEqual([
585 { type: "text", text: "MCP credential does not grant the pull-requests capability." },
586 ]);
587 }).pipe(Effect.provide(layerPullRequestsTest)),
588);
589
590it.effect("bounds large ARIA trees without dropping every server locator", () =>
591 Effect.scoped(
592 Effect.gen(function* () {
593 const accessibilityTree = Array.from(
594 { length: 2_000 },
595 (_, index) => `- button "删除 ${index}" [ref=t3-snapshot-e${index}]`,
596 ).join("\n");
597 yield* serveSnapshots("mcp-large-server-refs", { ...snapshotResult, accessibilityTree });
598 const result = yield* callSnapshot({ includeImage: false });
599 expect(result.isError).toBe(false);
600 const metadata = result.structuredContent as { accessibilityTree: string };
601 expect(metadata.accessibilityTree).toContain("[ref=t3-snapshot-e0]");
602 expect(metadata.accessibilityTree.length).toBeLessThan(accessibilityTree.length);
603 const body = result.content[1];
604 expect(Buffer.byteLength(body?.type === "text" ? body.text : "", "utf8")).toBeLessThanOrEqual(
605 McpHttpServer.MAX_SNAPSHOT_TEXT_BYTES,
606 );
607 }),
608 ).pipe(Effect.provide(layerTest)),
609);
610
611it.effect("keeps the snapshot text under the agent's output ceiling", () =>
612 Effect.scoped(
613 Effect.gen(function* () {
614 const pageText = "/Users/theo/Code/project\nClaude, Codex · 79 threads\n".repeat(600);
615 const element = (name: string, index: number) => ({
616 tag: "div",
617 role: "presentation",
618 name,
619 selector: `div:nth-of-type(${index})`,
620 x: 0,
621 y: 0,
622 width: 10,
623 height: 10,
624 });
625 const oversized = {
626 ...snapshotResult,
627 visibleText: pageText,
628 interactiveElements: [
629 element(pageText, 1),
630 element(pageText, 2),
631 element(pageText, 3),
632 element("Continue", 4),
633 ],
634 accessibilityTree: { nodes: Array.from({ length: 2_000 }, (_, i) => ({ nodeId: `${i}` })) },
635 consoleEntries: Array.from({ length: 100 }, (_, i) => ({
636 level: "log",
637 text: `entry ${i}`,
638 timestamp: "t",
639 })),
640 };
641 yield* serveSnapshots("mcp-bounded-client", oversized);
642
643 const snapshot = yield* callSnapshot({ includeImage: false });
644
645 expect(snapshot.isError).toBe(false);
646 const [identity, text, notice] = snapshot.content;
647 expect(identity?.type === "text" ? decodeJsonText(identity.text) : null).toEqual({
648 url: oversized.url,
649 });
650 expect(text?.type).toBe("text");
651 const body = text?.type === "text" ? text.text : "";
652 expect(Buffer.byteLength(body, "utf8")).toBeLessThanOrEqual(
653 McpHttpServer.MAX_SNAPSHOT_TEXT_BYTES,
654 );
655 const parsed = decodeJsonText(body) as {
656 readonly accessibilityTree?: unknown;
657 readonly visibleText: string;
658 readonly interactiveElements: ReadonlyArray<{ readonly name: string }>;
659 readonly consoleEntries: ReadonlyArray<{ readonly text: string }>;
660 };
661 expect(parsed.accessibilityTree).toBeUndefined();
662 expect(parsed.visibleText.length).toBeLessThanOrEqual(8_001);
663 expect(parsed.interactiveElements).toHaveLength(4);
664 expect(parsed.interactiveElements[0]?.name.length).toBeLessThanOrEqual(201);
665 expect(parsed.interactiveElements[3]?.name).toBe("Continue");
666 expect(parsed.consoleEntries).toHaveLength(40);
667 expect(parsed.consoleEntries[0]?.text).toBe("entry 60");
668 expect(notice?.type === "text" ? notice.text : "").toContain("accessibilityTree");
669 expect(notice?.type === "text" ? notice.text : "").toContain("60 older console entries");
670 expect(snapshot.structuredContent).toEqual({
671 ...parsed,
672 omitted: expect.arrayContaining(["60 older console entries"]),
673 });
674 }),
675 ).pipe(Effect.provide(layerTest)),
676);
677
678// regression: #10501 keep preview snapshots usable by the agent
679it.effect("bounds the snapshot text even when nothing but logs and the title are large", () =>
680 Effect.scoped(
681 Effect.gen(function* () {
682 const oversized = {
683 ...snapshotResult,
684 title: "t".repeat(70_000),
685 interactiveElements: [],
686 consoleEntries: [{ level: "log", text: "x".repeat(70_000), timestamp: "t" }],
687 };
688 yield* serveSnapshots("mcp-bounded-logs-client", oversized);
689
690 const snapshot = yield* callSnapshot({ includeImage: false });
691
692 const [, text] = snapshot.content;
693 const body = text?.type === "text" ? text.text : "";
694 expect(Buffer.byteLength(body, "utf8")).toBeLessThanOrEqual(
695 McpHttpServer.MAX_SNAPSHOT_TEXT_BYTES,
696 );
697 const parsed = decodeJsonText(body) as {
698 readonly title: string;
699 readonly consoleEntries: ReadonlyArray<{ readonly text: string }>;
700 };
701 expect(parsed.title.length).toBe(2_049);
702 expect(parsed.consoleEntries[0]?.text.length).toBe(501);
703 const notice = snapshot.content[2];
704 const noticeText = notice?.type === "text" ? notice.text : "";
705 expect(noticeText).toContain("url or title after 2048 characters");
706 expect(noticeText).toContain("console entries text after 500 characters");
707 }),
708 ).pipe(Effect.provide(layerTest)),
709);
710
711// regression: #13558 preview snapshots overflowed the agent's tool output
712it.effect("bounds page text made of wide characters before dropping locators", () =>
713 Effect.scoped(
714 Effect.gen(function* () {
715 yield* serveSnapshots("mcp-wide-text-client", {
716 ...snapshotResult,
717 visibleText: "界".repeat(9_000),
718 interactiveElements: Array.from({ length: 20 }, (_, i) => ({
719 tag: "button",
720 role: "button",
721 name: `Button ${i}`,
722 selector: `#button-${i}`,
723 x: 0,
724 y: 0,
725 width: 10,
726 height: 10,
727 })),
728 });
729
730 const snapshot = yield* callSnapshot({ includeImage: false });
731
732 const [, text, notice] = snapshot.content;
733 const body = text?.type === "text" ? text.text : "";
734 expect(Buffer.byteLength(body, "utf8")).toBeLessThanOrEqual(
735 McpHttpServer.MAX_SNAPSHOT_TEXT_BYTES,
736 );
737 const parsed = decodeJsonText(body) as {
738 readonly visibleText: string;
739 readonly interactiveElements: ReadonlyArray<unknown>;
740 };
741 expect(parsed.visibleText).toMatch(/^界+…$/);
742 expect(parsed.interactiveElements).toHaveLength(20);
743 expect(notice?.type === "text" ? notice.text : "").toContain(
744 "visibleText after 4000 characters",
745 );
746 }),
747 ).pipe(Effect.provide(layerTest)),
748);
749
750it.effect("terminates HTTP MCP sessions with DELETE", () =>
751 Effect.scoped(
752 Effect.gen(function* () {
753 const token = "providerTokenWithoutDots";
754 const scope: McpInvocationContext.McpInvocationScope = {
755 environmentId,
756 requestNamespace: "provider-session",
757 thread: {
758 threadId: ThreadId.make("thread-provider"),
759 providerSessionId: "provider-session",
760 providerInstanceId: ProviderInstanceId.make("codex"),
761 },
762 client: undefined,
763 capabilities: new Set(["orchestration"]),
764 issuedAt: 1,
765 };
766 const layerServer = McpHttpServer.layerMcpTransport.pipe(
767 Layer.provide(ServerSettings.layerTest()),
768 Layer.provide(
769 Layer.mock(McpSessionRegistry.McpSessionRegistry)({
770 resolve: (presented) =>
771 Effect.succeed(
772 presented === token
773 ? (scope as McpInvocationContext.McpThreadInvocationScope)
774 : undefined,
775 ),
776 }),
777 ),
778 );
779 yield* HttpRouter.serve(layerServer, {
780 disableListenLog: true,
781 disableLogger: true,
782 }).pipe(Layer.build);
783 const httpClient = (yield* HttpClient.HttpClient).pipe(
784 HttpClient.mapRequest(HttpClientRequest.bearerToken(token)),
785 );
786
787 const initializeResponse = yield* httpClient.post("/mcp", {
788 headers: { accept: "application/json, text/event-stream" },
789 body: HttpBody.text(
790 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"mcp-test","version":"1.0.0"}}}`,
791 "application/json",
792 ),
793 });
794 const sessionId = initializeResponse.headers["mcp-session-id"];
795 expect(initializeResponse.status).toBe(200);
796 expect(sessionId).not.toBeNull();
797
798 const missingSessionResponse = yield* httpClient.del("/mcp");
799 expect(missingSessionResponse.status).toBe(400);
800
801 const unknownSessionResponse = yield* httpClient.del("/mcp", {
802 headers: { "mcp-session-id": "unknown-session" },
803 });
804 expect(unknownSessionResponse.status).toBe(404);
805
806 const terminateResponse = yield* httpClient.del("/mcp", {
807 headers: { "mcp-session-id": sessionId! },
808 });
809 expect(terminateResponse.status).toBe(204);
810
811 const reusedSessionResponse = yield* httpClient.post("/mcp", {
812 headers: {
813 accept: "application/json, text/event-stream",
814 "mcp-session-id": sessionId!,
815 },
816 body: HttpBody.text(
817 `{"jsonrpc":"2.0","id":2,"method":"ping","params":{}}`,
818 "application/json",
819 ),
820 });
821 expect(reusedSessionResponse.status).toBe(404);
822 }),
823 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
824);
825
826it.effect("admits provider and OAuth client credentials and points only clients at OAuth", () =>
827 Effect.scoped(
828 Effect.gen(function* () {
829 const providerToken = "providerTokenWithoutDots";
830 const clientToken = "client-payload.client-signature";
831 const providerScope: McpInvocationContext.McpInvocationScope = {
832 environmentId,
833 requestNamespace: "provider-session",
834 thread: {
835 threadId: ThreadId.make("thread-provider"),
836 providerSessionId: "provider-session",
837 providerInstanceId: ProviderInstanceId.make("codex"),
838 },
839 client: undefined,
840 capabilities: new Set(["orchestration"]),
841 issuedAt: 1,
842 };
843 const clientScope: McpInvocationContext.McpInvocationScope = {
844 environmentId,
845 requestNamespace: "client:session-1",
846 thread: undefined,
847 client: { sessionId: "session-1", label: "Claude Code", access: "auto" },
848 capabilities: new Set(["orchestration"]),
849 issuedAt: 1,
850 };
851 const seen: Array<McpInvocationContext.McpInvocationScope> = [];
852 const ProbeToolkit = Toolkit.make(
853 Tool.make("probe", {
854 description: "Reports the caller.",
855 success: Schema.Struct({ ok: Schema.Boolean }),
856 failure: OrchestratorMcpFailure,
857 failureMode: "return",
858 dependencies: [McpInvocationContext.McpInvocationContext],
859 }),
860 );
861 const serverLayer = McpHttpServer.toolkitRegistration(
862 ProbeToolkit,
863 McpToolAccess.toLayer(ProbeToolkit, {
864 probe: McpToolAccess.reads(() =>
865 McpInvocationContext.McpInvocationContext.pipe(
866 Effect.tap((scope) => Effect.sync(() => seen.push(scope))),
867 Effect.as({ ok: true }),
868 ),
869 ),
870 }),
871 ).pipe(
872 Layer.provideMerge(
873 McpHttpServer.layerMcpTransport.pipe(Layer.provide(ServerSettings.layerTest())),
874 ),
875 Layer.provide(
876 Layer.mock(McpSessionRegistry.McpSessionRegistry)({
877 resolve: (token) =>
878 Effect.succeed(
879 token === providerToken
880 ? (providerScope as McpInvocationContext.McpThreadInvocationScope)
881 : undefined,
882 ),
883 }),
884 ),
885 Layer.provide(
886 Layer.succeed(McpHttpServer.McpClientAuthenticator, {
887 authenticate: (request) =>
888 Effect.succeed(
889 request.headers.authorization === `Bearer ${clientToken}` ? clientScope : undefined,
890 ),
891 }),
892 ),
893 );
894 yield* HttpRouter.serve(serverLayer, { disableListenLog: true, disableLogger: true }).pipe(
895 Layer.build,
896 );
897 const httpClient = yield* HttpClient.HttpClient;
898 const call = (token: string | undefined) =>
899 Effect.gen(function* () {
900 const headers = {
901 accept: "application/json, text/event-stream",
902 ...(token === undefined ? {} : { authorization: `Bearer ${token}` }),
903 };
904 const initialize = yield* httpClient.post("/mcp", {
905 headers,
906 body: HttpBody.text(
907 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`,
908 "application/json",
909 ),
910 });
911 if (initialize.status !== 200) return initialize;
912 return yield* httpClient.post("/mcp", {
913 headers: {
914 ...headers,
915 "mcp-session-id": initialize.headers["mcp-session-id"]!,
916 "mcp-protocol-version": "2025-06-18",
917 },
918 body: HttpBody.text(
919 `{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"probe","arguments":{}}}`,
920 "application/json",
921 ),
922 });
923 });
924
925 expect((yield* call(providerToken)).status).toBe(200);
926 expect((yield* call(clientToken)).status).toBe(200);
927 expect(seen.map((scope) => scope.requestNamespace)).toEqual([
928 "provider-session",
929 "client:session-1",
930 ]);
931
932 const missing = yield* call(undefined);
933 expect(missing.status).toBe(401);
934 expect(missing.headers["www-authenticate"]).toMatch(
935 /^Bearer resource_metadata="http:\/\/[^"]+\/\.well-known\/oauth-protected-resource\/mcp"$/,
936 );
937
938 const expiredClient = yield* call("stale-payload.stale-signature");
939 expect(expiredClient.headers["www-authenticate"]).toContain("resource_metadata=");
940 expect(expiredClient.headers["www-authenticate"]).toContain('error="invalid_token"');
941
942 const deadProvider = yield* call("deadProviderToken");
943 expect(deadProvider.status).toBe(401);
944 expect(deadProvider.headers["www-authenticate"]).toBe('Bearer error="invalid_token"');
945 }),
946 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
947);
948
949it.effect("hides tools for links and refuses another environment while the beta is off", () =>
950 Effect.scoped(
951 Effect.gen(function* () {
952 const token = "linksToken";
953 const scope: McpInvocationContext.McpThreadInvocationScope = {
954 environmentId,
955 requestNamespace: token,
956 thread: {
957 threadId: ThreadId.make("thread-links"),
958 providerSessionId: token,
959 providerInstanceId: ProviderInstanceId.make("codex"),
960 },
961 client: undefined,
962 capabilities: new Set(["orchestration"]),
963 issuedAt: 1,
964 };
965 const LinksToolkit = Toolkit.make(
966 Tool.make("links", {
967 description: "Lists links.",
968 success: Schema.Struct({ links: Schema.Number }),
969 failure: OrchestratorMcpFailure,
970 failureMode: "return",
971 }).annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenWhileLinksOff),
972 Tool.make("where", {
973 description: "Says where it ran.",
974 parameters: Schema.Struct({ environmentId: OrchestratorMcpEnvironmentTarget }),
975 success: Schema.Struct({ ranIn: Schema.String }),
976 failure: OrchestratorMcpFailure,
977 failureMode: "return",
978 }),
979 );
980 const settingsContext = yield* Layer.build(ServerSettings.layerTest());
981 const settings = Context.get(settingsContext, ServerSettings.ServerSettingsService);
982 const serverLayer = McpHttpServer.toolkitRegistration(
983 LinksToolkit,
984 McpToolAccess.toLayer(LinksToolkit, {
985 links: McpToolAccess.reads(() => Effect.succeed({ links: 0 })),
986 where: McpToolAccess.reads(() => Effect.succeed({ ranIn: "here" })),
987 }),
988 ).pipe(
989 Layer.provideMerge(
990 McpHttpServer.layerMcpTransport.pipe(
991 Layer.provide(Layer.succeedContext(settingsContext)),
992 ),
993 ),
994 Layer.provide(McpToolAccessTestkit.liveThreadsLayer),
995 Layer.provide(
996 Layer.mock(McpSessionRegistry.McpSessionRegistry)({
997 resolve: (presented) => Effect.succeed(presented === token ? scope : undefined),
998 }),
999 ),
1000 );
1001 yield* HttpRouter.serve(serverLayer, { disableListenLog: true, disableLogger: true }).pipe(
1002 Layer.build,
1003 );
1004 const httpClient = yield* HttpClient.HttpClient;
1005 const headers = {
1006 accept: "application/json, text/event-stream",
1007 authorization: `Bearer ${token}`,
1008 };
1009 const initialize = yield* httpClient.post("/mcp", {
1010 headers,
1011 body: HttpBody.text(
1012 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`,
1013 "application/json",
1014 ),
1015 });
1016 const rpc = (method: string, params: object) =>
1017 httpClient
1018 .post("/mcp", {
1019 headers: {
1020 ...headers,
1021 "mcp-session-id": initialize.headers["mcp-session-id"]!,
1022 "mcp-protocol-version": "2025-06-18",
1023 },
1024 body: HttpBody.text(
1025 JSON.stringify({ jsonrpc: "2.0", id: 2, method, params }),
1026 "application/json",
1027 ),
1028 })
1029 .pipe(Effect.flatMap((response) => response.json));
1030 const listed = () =>
1031 rpc("tools/list", {}).pipe(
1032 Effect.map((body) =>
1033 (body as { result: { tools: ReadonlyArray<{ name: string }> } }).result.tools.map(
1034 (tool) => tool.name,
1035 ),
1036 ),
1037 );
1038 const ranIn = (where: EnvironmentId) =>
1039 rpc("tools/call", { name: "where", arguments: { environmentId: where } }).pipe(
1040 Effect.map(
1041 (body) =>
1042 (
1043 body as {
1044 result: {
1045 isError?: boolean;
1046 structuredContent?: unknown;
1047 content: ReadonlyArray<{ text: string }>;
1048 };
1049 }
1050 ).result,
1051 ),
1052 );
1053 const elsewhere = EnvironmentId.make("environment-elsewhere");
1054
1055 expect(yield* listed()).toEqual(["where"]);
1056 expect(yield* ranIn(elsewhere)).toMatchObject({
1057 isError: true,
1058 content: [{ text: expect.stringContaining("Linked environments is off on this machine") }],
1059 });
1060 expect((yield* ranIn(environmentId)).structuredContent).toEqual({ ranIn: "here" });
1061
1062 yield* settings.updateSettings({ linkedEnvironmentsEnabled: true });
1063 expect(yield* listed()).toEqual(["links", "where"]);
1064 // On, the call goes on to the forwarding, which this server lacks.
1065 expect(yield* ranIn(elsewhere)).toMatchObject({
1066 isError: true,
1067 content: [{ text: expect.stringContaining("cannot reach linked environments") }],
1068 });
1069 }),
1070 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
1071);
1072
1073it.effect("lists pull request watch tools only to threads that are not delegated children", () =>
1074 Effect.scoped(
1075 Effect.gen(function* () {
1076 const scopeFor = (
1077 token: string,
1078 subagent: boolean,
1079 ): McpInvocationContext.McpThreadInvocationScope => ({
1080 environmentId,
1081 requestNamespace: token,
1082 thread: {
1083 threadId: ThreadId.make(`thread-${token}`),
1084 providerSessionId: token,
1085 providerInstanceId: ProviderInstanceId.make("codex"),
1086 subagent,
1087 },
1088 client: undefined,
1089 capabilities: new Set(["pull-requests"]),
1090 issuedAt: 1,
1091 });
1092 const scopes = new Map([
1093 ["parentToken", scopeFor("parentToken", false)],
1094 ["childToken", scopeFor("childToken", true)],
1095 ]);
1096 const serverLayer = McpHttpServer.layerPullRequestsToolkit.pipe(
1097 Layer.provideMerge(
1098 McpHttpServer.layerMcpTransport.pipe(Layer.provide(ServerSettings.layerTest())),
1099 ),
1100 Layer.provide(
1101 Layer.mock(McpSessionRegistry.McpSessionRegistry)({
1102 resolve: (token) => Effect.succeed(scopes.get(token)),
1103 }),
1104 ),
1105 Layer.provide(
1106 Layer.mergeAll(
1107 McpToolAccessTestkit.liveThreadsLayer,
1108 Layer.mock(ProjectService.ProjectService)({}),
1109 Layer.mock(PullRequestReviewGuideService.PullRequestReviewGuideService)({}),
1110 Layer.mock(Orchestrator.OrchestratorV2)({}),
1111 Layer.mock(ProjectionStore.ProjectionStoreV2)({}),
1112 NodeServices.layer,
1113 ),
1114 ),
1115 );
1116 yield* HttpRouter.serve(serverLayer, { disableListenLog: true, disableLogger: true }).pipe(
1117 Layer.build,
1118 );
1119 const httpClient = yield* HttpClient.HttpClient;
1120 const listedTools = (token: string) =>
1121 Effect.gen(function* () {
1122 const headers = {
1123 accept: "application/json, text/event-stream",
1124 authorization: `Bearer ${token}`,
1125 };
1126 const initialize = yield* httpClient.post("/mcp", {
1127 headers,
1128 body: HttpBody.text(
1129 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`,
1130 "application/json",
1131 ),
1132 });
1133 const listed = yield* httpClient.post("/mcp", {
1134 headers: {
1135 ...headers,
1136 "mcp-session-id": initialize.headers["mcp-session-id"]!,
1137 "mcp-protocol-version": "2025-06-18",
1138 },
1139 body: HttpBody.text(
1140 `{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}`,
1141 "application/json",
1142 ),
1143 });
1144 const body = (yield* listed.json) as {
1145 readonly result: { readonly tools: ReadonlyArray<{ readonly name: string }> };
1146 };
1147 return body.result.tools.map((tool) => tool.name);
1148 });
1149
1150 const parentTools = yield* listedTools("parentToken");
1151 const childTools = yield* listedTools("childToken");
1152 expect(parentTools).toEqual(
1153 expect.arrayContaining(["link_pull_request", "watch_pull_request", "unwatch_pull_request"]),
1154 );
1155 expect(childTools).toContain("link_pull_request");
1156 expect(childTools).not.toContain("watch_pull_request");
1157 expect(childTools).not.toContain("unwatch_pull_request");
1158 }),
1159 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
1160);
1161
1162it.effect(
1163 "narrows an OAuth client's modes to the T3-Mode-Limit it sends, and never widens them",
1164 () =>
1165 Effect.scoped(
1166 Effect.gen(function* () {
1167 const clientToken = "client-payload.client-signature";
1168 const clientScope: McpInvocationContext.McpInvocationScope = {
1169 environmentId,
1170 requestNamespace: "client:linked",
1171 thread: undefined,
1172 client: { sessionId: "linked", label: "T3 Code · laptop", access: "auto" },
1173 capabilities: new Set(["orchestration"]),
1174 issuedAt: 1,
1175 };
1176 // Starts a thread at the modes the gate hands it, so the outcome is those modes.
1177 const StartsToolkit = Toolkit.make(
1178 Tool.make("starts", {
1179 description: "Reports the modes a started thread would run with.",
1180 parameters: Schema.Struct({
1181 runtimeMode: Schema.optional(RuntimeMode),
1182 interactionMode: Schema.optional(ProviderInteractionMode),
1183 }),
1184 success: Schema.Struct({ modes: Schema.String }),
1185 failure: OrchestratorMcpFailure,
1186 failureMode: "return",
1187 dependencies: [
1188 McpInvocationContext.McpInvocationContext,
1189 ThreadManagementService.ThreadManagementService,
1190 ],
1191 }),
1192 );
1193 const serverLayer = McpHttpServer.toolkitRegistration(
1194 StartsToolkit,
1195 McpToolAccess.toLayer(StartsToolkit, {
1196 starts: McpToolAccess.startsThreads(
1197 (input) => input,
1198 (_, modes) =>
1199 Effect.succeed({ modes: `${modes.runtimeMode}/${modes.interactionMode}` }),
1200 "stamped",
1201 ),
1202 }),
1203 ).pipe(
1204 Layer.provideMerge(
1205 McpHttpServer.layerMcpTransport.pipe(Layer.provide(ServerSettings.layerTest())),
1206 ),
1207 Layer.provide(McpToolAccessTestkit.liveThreadsLayer),
1208 Layer.provide(
1209 Layer.mock(McpSessionRegistry.McpSessionRegistry)({
1210 // @effect-diagnostics-next-line effectSucceedWithVoid:off - This optional result requires undefined, not the wider void type.
1211 resolve: () => Effect.succeed(undefined),
1212 }),
1213 ),
1214 Layer.provide(
1215 Layer.succeed(McpHttpServer.McpClientAuthenticator, {
1216 authenticate: (request) =>
1217 Effect.succeed(
1218 request.headers.authorization === `Bearer ${clientToken}`
1219 ? clientScope
1220 : undefined,
1221 ),
1222 }),
1223 ),
1224 );
1225 yield* HttpRouter.serve(serverLayer, { disableListenLog: true, disableLogger: true }).pipe(
1226 Layer.build,
1227 );
1228 const httpClient = yield* HttpClient.HttpClient;
1229 const decodeOutcome = Schema.decodeUnknownEffect(
1230 Schema.fromJsonString(
1231 Schema.Struct({
1232 result: Schema.Struct({
1233 content: Schema.Array(Schema.Struct({ text: Schema.String })),
1234 }),
1235 }),
1236 ),
1237 );
1238 const decodeText = Schema.decodeUnknownEffect(
1239 Schema.fromJsonString(
1240 Schema.Union([
1241 Schema.Struct({ modes: Schema.String }),
1242 Schema.Struct({ code: Schema.String }),
1243 ]),
1244 ),
1245 );
1246 /** Starts a thread as the client, with `limit` as T3-Mode-Limit; the HTTP status or the outcome. */
1247 const start = (limit: string | undefined, args: Record<string, string> = {}) =>
1248 Effect.gen(function* () {
1249 const headers = {
1250 accept: "application/json, text/event-stream",
1251 authorization: `Bearer ${clientToken}`,
1252 ...(limit === undefined ? {} : { "t3-mode-limit": limit }),
1253 };
1254 const initialize = yield* httpClient.post("/mcp", {
1255 headers,
1256 body: HttpBody.text(
1257 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`,
1258 "application/json",
1259 ),
1260 });
1261 if (initialize.status !== 200) return initialize.status;
1262 const response = yield* httpClient.post("/mcp", {
1263 headers: {
1264 ...headers,
1265 "mcp-session-id": initialize.headers["mcp-session-id"]!,
1266 "mcp-protocol-version": "2025-06-18",
1267 },
1268 body: HttpBody.text(
1269 JSON.stringify({
1270 jsonrpc: "2.0",
1271 id: 2,
1272 method: "tools/call",
1273 params: { name: "starts", arguments: args },
1274 }),
1275 "application/json",
1276 ),
1277 });
1278 const body = yield* decodeOutcome(yield* response.text);
1279 const outcome = yield* decodeText(
1280 body.result.content.map((part) => part.text).join(""),
1281 );
1282 return "code" in outcome ? outcome.code : outcome.modes;
1283 });
1284
1285 // Approved for auto: without the header the client keeps its ceiling.
1286 expect(yield* start(undefined)).toBe("auto/default");
1287 // The header narrows both modes, and asking above it is refused.
1288 expect(yield* start("approval-required/plan")).toBe("approval-required/plan");
1289 expect(yield* start("approval-required/plan", { runtimeMode: "auto" })).toBe(
1290 "runtime_mode_escalation_denied",
1291 );
1292 expect(yield* start("auto-accept-edits/plan", { interactionMode: "default" })).toBe(
1293 "interaction_mode_escalation_denied",
1294 );
1295 // A broader header changes nothing: the approved ceiling still holds.
1296 expect(yield* start("full-access/default")).toBe("auto/default");
1297 expect(yield* start("full-access/default", { runtimeMode: "full-access" })).toBe(
1298 "runtime_mode_escalation_denied",
1299 );
1300 // A malformed header is refused before anything runs.
1301 expect(yield* start("auto")).toBe(400);
1302 expect(yield* start("auto/default/extra")).toBe(400);
1303 expect(yield* start("root/default")).toBe(400);
1304 }),
1305 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
1306);