Open History to see the last commit
1import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
2import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
3import { expect, it } from "@effect/vitest";
4import { NodeHttpServer } from "@effect/platform-node";
5import * as NodeServices from "@effect/platform-node/NodeServices";
6import {
7 EnvironmentId,
8 OrchestratorMcpFailure,
9 PreviewTabId,
10 ProviderInstanceId,
11 ThreadId,
12} from "@t3tools/contracts";
13import * as Deferred from "effect/Deferred";
14import * as Effect from "effect/Effect";
15import * as FileSystem from "effect/FileSystem";
16import * as Layer from "effect/Layer";
17import * as Path from "effect/Path";
18import * as Schema from "effect/Schema";
19import * as Stream from "effect/Stream";
20import { McpSchema, McpServer, Tool, Toolkit } from "effect/ai";
21import {
22 HttpBody,
23 HttpClient,
24 HttpClientRequest,
25 HttpRouter,
26 HttpServerResponse,
27} from "effect/http";
28
29import * as ProjectService from "../project/ProjectService.ts";
30import * as PullRequestReviewGuideService from "../pullRequest/PullRequestReviewGuideService.ts";
31import * as ServerConfig from "../config.ts";
32import * as McpHttpServer from "./McpHttpServer.ts";
33import * as McpToolAccess from "./McpToolAccess.ts";
34import * as McpToolAccessTestkit from "./McpToolAccess.testkit.ts";
35import * as McpInvocationContext from "./McpInvocationContext.ts";
36import * as McpSessionRegistry from "./McpSessionRegistry.ts";
37import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
38
39const environmentId = EnvironmentId.make("environment-mcp-test");
40const threadId = ThreadId.make("thread-mcp-test");
41const tabId = PreviewTabId.make("tab-mcp-test");
42const alternateTabId = PreviewTabId.make("tab-mcp-alternate");
43const decodeJsonText = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
44const invocation = {
45 environmentId,
46 requestNamespace: "provider-session-mcp-test",
47 thread: {
48 threadId,
49 providerSessionId: "provider-session-mcp-test",
50 providerInstanceId: ProviderInstanceId.make("codex"),
51 },
52 client: undefined,
53 capabilities: new Set(["preview"] as const),
54 issuedAt: 1,
55};
56const client = McpSchema.McpServerClient.of({
57 clientId: 1,
58 clientCapabilities: {},
59 clientInfo: { name: "mcp-test", version: "1.0.0" },
60 protocolVersion: "2025-06-18",
61 initializePayload: {
62 protocolVersion: "2025-06-18",
63 capabilities: {},
64 clientInfo: { name: "mcp-test", version: "1.0.0" },
65 },
66 getClient: Effect.die("unused"),
67});
68const layerTest = McpHttpServer.layerPreviewToolkit.pipe(
69 Layer.provideMerge(McpServer.McpServer.layer),
70 Layer.provideMerge(McpToolAccessTestkit.liveThreadsLayer),
71 Layer.provideMerge(PreviewAutomationBroker.layer),
72 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-http-server-test-" })),
73 Layer.provideMerge(NodeServices.layer),
74);
75const layerPullRequestsTest = McpHttpServer.layerPullRequestsToolkit.pipe(
76 Layer.provideMerge(McpServer.McpServer.layer),
77 Layer.provideMerge(McpToolAccessTestkit.liveThreadsLayer),
78 Layer.provide(
79 Layer.mergeAll(
80 Layer.mock(ProjectService.ProjectService)({}),
81 Layer.mock(PullRequestReviewGuideService.PullRequestReviewGuideService)({}),
82 Layer.mock(Orchestrator.OrchestratorV2)({}),
83 Layer.mock(ProjectionStore.ProjectionStoreV2)({}),
84 NodeServices.layer,
85 ),
86 ),
87);
88
89const snapshotResult = {
90 url: "http://example.test/",
91 title: "Example",
92 loading: false,
93 visibleText: "Example",
94 interactiveElements: [],
95 accessibilityTree: {},
96 consoleEntries: [],
97 networkEntries: [],
98 actionTimeline: [],
99 screenshot: {
100 mimeType: "image/png",
101 data: Buffer.from("png").toString("base64"),
102 width: 10,
103 height: 5,
104 },
105};
106
107const serveSnapshots = (clientId: string, result: unknown) =>
108 Effect.gen(function* () {
109 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
110 const connected = yield* Deferred.make<void>();
111 const inputs: Array<unknown> = [];
112 const events = yield* broker.connect({ clientId, environmentId });
113 yield* Stream.runForEach(events, (event) => {
114 if (event.type === "connected") return Deferred.succeed(connected, undefined);
115 inputs.push(event.request.input);
116 return broker.respond({
117 clientId,
118 connectionId: event.connectionId,
119 requestId: event.request.requestId,
120 ok: true,
121 result,
122 });
123 }).pipe(Effect.forkScoped);
124 yield* Deferred.await(connected);
125 return inputs;
126 });
127
128const callSnapshot = (args: Record<string, unknown>) =>
129 Effect.gen(function* () {
130 const server = yield* McpServer.McpServer;
131 return yield* server
132 .callTool({ name: "preview_snapshot", arguments: args })
133 .pipe(
134 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
135 Effect.provideService(McpSchema.McpServerClient, client),
136 );
137 });
138
139it("normalizes empty successful notification responses to accepted", () => {
140 const notificationResponse = McpHttpServer.normalizeMcpHttpResponse(
141 HttpServerResponse.text("", { status: 200, contentType: "application/json" }),
142 );
143 expect(notificationResponse.status).toBe(202);
144
145 const resultResponse = McpHttpServer.normalizeMcpHttpResponse(
146 HttpServerResponse.jsonUnsafe({ jsonrpc: "2.0", id: 1, result: {} }),
147 );
148 expect(resultResponse.status).toBe(200);
149});
150
151it.effect.each([{}, { includeImage: false }])(
152 "returns bounded structural preview snapshot failures %#",
153 (input) =>
154 Effect.scoped(
155 Effect.gen(function* () {
156 const server = yield* McpServer.McpServer;
157 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
158 const events = yield* broker.connect({
159 clientId: "mcp-failure-client",
160 environmentId,
161 });
162 yield* Stream.runForEach(events, (event) =>
163 event.type === "connected"
164 ? Effect.void
165 : broker.respond({
166 clientId: "mcp-failure-client",
167 connectionId: event.connectionId,
168 requestId: event.request.requestId,
169 ok: false,
170 error: {
171 _tag: "PreviewAutomationExecutionError",
172 message: "sensitive renderer failure",
173 detail: { consoleOutput: "sensitive browser output" },
174 },
175 }),
176 ).pipe(Effect.forkScoped);
177 yield* Effect.yieldNow;
178
179 const snapshot = yield* server
180 .callTool({ name: "preview_snapshot", arguments: input })
181 .pipe(
182 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
183 Effect.provideService(McpSchema.McpServerClient, client),
184 );
185
186 const message = "Preview automation snapshot failed on client mcp-failure-client.";
187 expect(snapshot.isError).toBe(true);
188 expect(snapshot.content).toEqual([
189 { type: "text", text: `Preview snapshot failed: ${message}` },
190 ]);
191 expect(snapshot.structuredContent).toEqual({
192 error: {
193 _tag: "PreviewAutomationExecutionError",
194 operation: "snapshot",
195 failureCount: 1,
196 message,
197 },
198 });
199 }),
200 ).pipe(Effect.provide(layerTest)),
201);
202
203it.effect.each([
204 { args: {}, advice: "No active preview tab was found for snapshot. Call preview_open first." },
205 {
206 args: { tabId: alternateTabId },
207 advice: `Preview tab ${alternateTabId} was not found for snapshot. Omit tabId to use the current tab, or call preview_open.`,
208 },
209])("tells the agent to open a tab when the snapshot has none $args", ({ args, advice }) =>
210 Effect.scoped(
211 Effect.gen(function* () {
212 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
213 const connected = yield* Deferred.make<void>();
214 const events = yield* broker.connect({ clientId: "mcp-no-tab-client", environmentId });
215 yield* Stream.runForEach(events, (event) =>
216 event.type === "connected"
217 ? Deferred.succeed(connected, undefined)
218 : broker.respond({
219 clientId: "mcp-no-tab-client",
220 connectionId: event.connectionId,
221 requestId: event.request.requestId,
222 ok: false,
223 error: { _tag: "PreviewAutomationTabNotFoundError", message: "no tab" },
224 }),
225 ).pipe(Effect.forkScoped);
226 yield* Deferred.await(connected);
227
228 const snapshot = yield* callSnapshot(args);
229
230 expect(snapshot.isError).toBe(true);
231 expect(snapshot.content).toEqual([
232 { type: "text", text: `Preview snapshot failed: ${advice}` },
233 ]);
234 }),
235 ).pipe(Effect.provide(layerTest)),
236);
237
238it.effect("tells the agent how to recover when no preview host can run the snapshot", () =>
239 Effect.gen(function* () {
240 const snapshot = yield* callSnapshot({});
241
242 expect(snapshot.isError).toBe(true);
243 const [text] = snapshot.content;
244 expect(text?.type === "text" ? text.text : "").toContain(
245 "Retry preview_status, then call preview_open",
246 );
247 expect(snapshot.structuredContent).toMatchObject({
248 error: { _tag: "PreviewAutomationNoAvailableHostError" },
249 });
250 }).pipe(Effect.provide(layerTest)),
251);
252
253it.effect.each([
254 { mode: "default", input: {}, images: false },
255 { mode: "explicit image", input: { includeImage: true }, images: true },
256 { mode: "text only", input: { includeImage: false }, images: false },
257])("returns fresh $mode snapshots on repeated MCP calls", ({ input, images }) =>
258 Effect.scoped(
259 Effect.gen(function* () {
260 const server = yield* McpServer.McpServer;
261 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
262 const connected = yield* Deferred.make<void>();
263 const png =
264 "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII=";
265 const page = {
266 url: "http://example.test/",
267 loading: false,
268 visibleText: "Save your changes",
269 interactiveElements: [
270 {
271 tag: "button",
272 role: "button",
273 name: "Save",
274 selector: "#save",
275 x: 0,
276 y: 0,
277 width: 20,
278 height: 10,
279 },
280 ],
281 accessibilityTree: { role: "document", name: "Example" },
282 consoleEntries: [],
283 networkEntries: [],
284 actionTimeline: [],
285 };
286 const screenshot = { mimeType: "image/png", width: 1, height: 1 };
287 let requests = 0;
288 const events = yield* broker.connect({ clientId: "mcp-image-option-client", environmentId });
289 yield* Stream.runForEach(events, (event) => {
290 if (event.type === "connected") return Deferred.succeed(connected, undefined);
291 requests += 1;
292 expect(event.request).toMatchObject({
293 operation: "snapshot",
294 tabId: alternateTabId,
295 threadId,
296 });
297 expect(event.request.input).toEqual({});
298 return broker.respond({
299 clientId: "mcp-image-option-client",
300 connectionId: event.connectionId,
301 requestId: event.request.requestId,
302 ok: true,
303 result: {
304 ...page,
305 title: `Snapshot ${requests}`,
306 screenshot: { ...screenshot, data: png },
307 },
308 });
309 }).pipe(Effect.forkScoped);
310 yield* Deferred.await(connected);
311
312 for (const call of [1, 2, 3, 4, 5, 6]) {
313 const snapshot = yield* server
314 .callTool({
315 name: "preview_snapshot",
316 arguments: { ...input, tabId: alternateTabId },
317 })
318 .pipe(
319 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
320 Effect.provideService(McpSchema.McpServerClient, client),
321 );
322 const metadata = { ...page, title: `Snapshot ${call}`, screenshot };
323 const { accessibilityTree: _tree, ...boundedMetadata } = metadata;
324 expect(snapshot.isError).toBe(false);
325 expect(snapshot.structuredContent).toEqual({
326 ...boundedMetadata,
327 omitted: ["accessibilityTree (use interactiveElements locators or preview_evaluate)"],
328 });
329 const [identity, text, ...rest] = snapshot.content;
330 expect(identity?.type === "text" ? decodeJsonText(identity.text) : null).toEqual({
331 url: page.url,
332 });
333 expect(text?.type === "text" ? decodeJsonText(text.text) : null).toEqual(boundedMetadata);
334 expect(rest).toEqual([
335 {
336 type: "text",
337 text: "Snapshot text was bounded. Omitted: accessibilityTree (use interactiveElements locators or preview_evaluate).",
338 },
339 ...(images
340 ? [
341 {
342 type: "image",
343 mimeType: "image/png",
344 data: new Uint8Array(Buffer.from(png, "base64")),
345 },
346 ]
347 : []),
348 ]);
349 }
350
351 const nextDefault = yield* server
352 .callTool({
353 name: "preview_snapshot",
354 arguments: { tabId: alternateTabId },
355 })
356 .pipe(
357 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
358 Effect.provideService(McpSchema.McpServerClient, client),
359 );
360 expect(nextDefault.content.map((content) => content.type)).toEqual(["text", "text", "text"]);
361 expect(nextDefault.structuredContent).toMatchObject({ title: "Snapshot 7", screenshot });
362 expect(nextDefault.structuredContent).not.toHaveProperty("accessibilityTree");
363 expect(requests).toBe(7);
364 }),
365 ).pipe(Effect.provide(layerTest)),
366);
367
368it.effect("refuses preview tools to a client outside a thread before they run", () =>
369 Effect.gen(function* () {
370 const server = yield* McpServer.McpServer;
371 const readOnly = {
372 ...invocation,
373 thread: undefined,
374 requestNamespace: "client:session-1",
375 client: { sessionId: "session-1", label: "Claude Code", access: "read-only" as const },
376 };
377 const click = yield* server
378 .callTool({ name: "preview_click", arguments: { locator: "text=Send" } })
379 .pipe(
380 Effect.provideService(McpInvocationContext.McpInvocationContext, readOnly),
381 Effect.provideService(McpSchema.McpServerClient, client),
382 );
383 expect(click.isError).toBe(true);
384 expect(click.content).toEqual([
385 { type: "text", text: expect.stringContaining("needs an agent running inside T3 Code") },
386 ]);
387 }).pipe(Effect.provide(layerTest)),
388);
389
390it.effect("rejects non-boolean snapshot image options before selecting a browser host", () =>
391 Effect.gen(function* () {
392 const server = yield* McpServer.McpServer;
393 for (const includeImage of ["false", 0, null]) {
394 const result = yield* server
395 .callTool({
396 name: "preview_snapshot",
397 arguments: { includeImage },
398 })
399 .pipe(
400 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
401 Effect.provideService(McpSchema.McpServerClient, client),
402 );
403 expect(result.isError).toBe(true);
404 expect(result.content).toEqual([{ type: "text", text: "Preview snapshot failed: AiError." }]);
405 expect(result.structuredContent).toEqual({
406 error: { _tag: "AiError", operation: "snapshot", failureCount: 1 },
407 });
408 }
409 }).pipe(Effect.provide(layerTest)),
410);
411
412it.effect("saves the snapshot PNG on request and reports its path", () =>
413 Effect.scoped(
414 Effect.gen(function* () {
415 const config = yield* ServerConfig.ServerConfig;
416 const fileSystem = yield* FileSystem.FileSystem;
417 const path = yield* Path.Path;
418 const inputs = yield* serveSnapshots("mcp-save-client", snapshotResult);
419
420 const snapshot = yield* callSnapshot({ save: true, includeImage: true });
421
422 expect(snapshot.isError).toBe(false);
423 expect(inputs).toEqual([{}]);
424 expect(snapshot.content.map((content) => content.type)).toContain("image");
425 const structured = snapshot.structuredContent as { readonly screenshotPath?: string };
426 const screenshotPath = structured.screenshotPath;
427 expect(typeof screenshotPath).toBe("string");
428 expect(path.dirname(screenshotPath!)).toBe(config.browserArtifactsDir);
429 expect(path.basename(screenshotPath!)).toMatch(
430 /^browser-screenshot-example-test-[0-9a-z]+-[0-9a-f]{8}\.png$/,
431 );
432 expect(Buffer.from(yield* fileSystem.readFile(screenshotPath!)).toString()).toBe("png");
433 const [, text] = snapshot.content;
434 expect(text?.type === "text" ? text.text : "").toContain(screenshotPath);
435
436 const unsaved = yield* callSnapshot({});
437 expect(unsaved.structuredContent).not.toHaveProperty("screenshotPath");
438
439 const pathOnly = yield* callSnapshot({ save: true });
440 const saved = pathOnly.structuredContent as { readonly screenshotPath: string };
441 expect(saved).toEqual({ url: snapshotResult.url, screenshotPath: expect.any(String) });
442 expect(Buffer.from(yield* fileSystem.readFile(saved.screenshotPath)).toString()).toBe("png");
443 const [only, ...others] = pathOnly.content;
444 expect(others).toEqual([]);
445 expect(only?.type === "text" ? decodeJsonText(only.text) : null).toEqual(saved);
446 }),
447 ).pipe(Effect.provide(layerTest)),
448);
449
450it.effect("reports a tagged error when the screenshot cannot be saved", () =>
451 Effect.scoped(
452 Effect.gen(function* () {
453 const config = yield* ServerConfig.ServerConfig;
454 const fileSystem = yield* FileSystem.FileSystem;
455 yield* fileSystem.writeFileString(config.browserArtifactsDir, "");
456 yield* serveSnapshots("mcp-save-failure-client", snapshotResult);
457
458 const snapshot = yield* callSnapshot({ save: true });
459
460 expect(snapshot.isError).toBe(true);
461 expect(snapshot.content).toEqual([
462 { type: "text", text: "Preview snapshot failed: PreviewScreenshotSaveError." },
463 ]);
464 expect(snapshot.structuredContent).toEqual({
465 error: { _tag: "PreviewScreenshotSaveError", operation: "snapshot", failureCount: 1 },
466 });
467 }),
468 ).pipe(Effect.provide(layerTest)),
469);
470
471it.effect(
472 "registers the pull request toolkit and surfaces a missing capability as a tool error",
473 () =>
474 Effect.gen(function* () {
475 const server = yield* McpServer.McpServer;
476 const names = server.tools.map(({ tool }) => tool.name);
477 expect(names).toEqual(
478 expect.arrayContaining([
479 "link_pull_request",
480 "unlink_pull_request",
481 "list_thread_pull_requests",
482 ]),
483 );
484 const linkTool = server.tools.find(({ tool }) => tool.name === "link_pull_request");
485 expect(linkTool?.tool.annotations?.idempotentHint).toBe(true);
486 expect(linkTool?.tool.annotations?.openWorldHint).toBe(false);
487 expect(linkTool?.tool.description).toContain("Register every pull request you open");
488
489 const denied = yield* server
490 .callTool({ name: "list_thread_pull_requests", arguments: {} })
491 .pipe(
492 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
493 Effect.provideService(McpSchema.McpServerClient, client),
494 );
495 expect(denied.isError).toBe(true);
496 expect(denied.content).toEqual([
497 { type: "text", text: "MCP credential does not grant the pull-requests capability." },
498 ]);
499 }).pipe(Effect.provide(layerPullRequestsTest)),
500);
501
502it.effect("returns server ARIA refs to agents in text and structured results", () =>
503 Effect.scoped(
504 Effect.gen(function* () {
505 const accessibilityTree =
506 '- button "delete" [ref=t3-snapshot-e1]\n- iframe [ref=t3-snapshot-e2]:\n - textbox "child" [ref=t3-snapshot-f1e1]';
507 yield* serveSnapshots("mcp-server-refs", { ...snapshotResult, accessibilityTree });
508 const result = yield* callSnapshot({ includeImage: false });
509 expect(result.isError).toBe(false);
510 expect(result.structuredContent).toMatchObject({ accessibilityTree });
511 expect(
512 result.content.some(
513 (entry) => entry.type === "text" && entry.text.includes("t3-snapshot-f1e1"),
514 ),
515 ).toBe(true);
516 }),
517 ).pipe(Effect.provide(layerTest)),
518);
519
520it.effect("bounds large ARIA trees without dropping every server locator", () =>
521 Effect.scoped(
522 Effect.gen(function* () {
523 const accessibilityTree = Array.from(
524 { length: 2_000 },
525 (_, index) => `- button "删除 ${index}" [ref=t3-snapshot-e${index}]`,
526 ).join("\n");
527 yield* serveSnapshots("mcp-large-server-refs", { ...snapshotResult, accessibilityTree });
528 const result = yield* callSnapshot({ includeImage: false });
529 expect(result.isError).toBe(false);
530 const metadata = result.structuredContent as { accessibilityTree: string };
531 expect(metadata.accessibilityTree).toContain("[ref=t3-snapshot-e0]");
532 expect(metadata.accessibilityTree.length).toBeLessThan(accessibilityTree.length);
533 const body = result.content[1];
534 expect(Buffer.byteLength(body?.type === "text" ? body.text : "", "utf8")).toBeLessThanOrEqual(
535 McpHttpServer.MAX_SNAPSHOT_TEXT_BYTES,
536 );
537 }),
538 ).pipe(Effect.provide(layerTest)),
539);
540
541it.effect("keeps the snapshot text under the agent's output ceiling", () =>
542 Effect.scoped(
543 Effect.gen(function* () {
544 const pageText = "/Users/theo/Code/project\nClaude, Codex · 79 threads\n".repeat(600);
545 const element = (name: string, index: number) => ({
546 tag: "div",
547 role: "presentation",
548 name,
549 selector: `div:nth-of-type(${index})`,
550 x: 0,
551 y: 0,
552 width: 10,
553 height: 10,
554 });
555 const oversized = {
556 ...snapshotResult,
557 visibleText: pageText,
558 interactiveElements: [
559 element(pageText, 1),
560 element(pageText, 2),
561 element(pageText, 3),
562 element("Continue", 4),
563 ],
564 accessibilityTree: { nodes: Array.from({ length: 2_000 }, (_, i) => ({ nodeId: `${i}` })) },
565 consoleEntries: Array.from({ length: 100 }, (_, i) => ({
566 level: "log",
567 text: `entry ${i}`,
568 timestamp: "t",
569 })),
570 };
571 yield* serveSnapshots("mcp-bounded-client", oversized);
572
573 const snapshot = yield* callSnapshot({ includeImage: false });
574
575 expect(snapshot.isError).toBe(false);
576 const [identity, text, notice] = snapshot.content;
577 expect(identity?.type === "text" ? decodeJsonText(identity.text) : null).toEqual({
578 url: oversized.url,
579 });
580 expect(text?.type).toBe("text");
581 const body = text?.type === "text" ? text.text : "";
582 expect(Buffer.byteLength(body, "utf8")).toBeLessThanOrEqual(
583 McpHttpServer.MAX_SNAPSHOT_TEXT_BYTES,
584 );
585 const parsed = decodeJsonText(body) as {
586 readonly accessibilityTree?: unknown;
587 readonly visibleText: string;
588 readonly interactiveElements: ReadonlyArray<{ readonly name: string }>;
589 readonly consoleEntries: ReadonlyArray<{ readonly text: string }>;
590 };
591 expect(parsed.accessibilityTree).toBeUndefined();
592 expect(parsed.visibleText.length).toBeLessThanOrEqual(8_001);
593 expect(parsed.interactiveElements).toHaveLength(4);
594 expect(parsed.interactiveElements[0]?.name.length).toBeLessThanOrEqual(201);
595 expect(parsed.interactiveElements[3]?.name).toBe("Continue");
596 expect(parsed.consoleEntries).toHaveLength(40);
597 expect(parsed.consoleEntries[0]?.text).toBe("entry 60");
598 expect(notice?.type === "text" ? notice.text : "").toContain("accessibilityTree");
599 expect(notice?.type === "text" ? notice.text : "").toContain("60 older console entries");
600 // Claude Code shows the model structuredContent instead of the text, so it is bounded too.
601 expect(snapshot.structuredContent).toEqual({
602 ...parsed,
603 omitted: expect.arrayContaining(["60 older console entries"]),
604 });
605 }),
606 ).pipe(Effect.provide(layerTest)),
607);
608
609it.effect("bounds the snapshot text even when nothing but logs and the title are large", () =>
610 Effect.scoped(
611 Effect.gen(function* () {
612 const oversized = {
613 ...snapshotResult,
614 title: "t".repeat(70_000),
615 interactiveElements: [],
616 consoleEntries: [{ level: "log", text: "x".repeat(70_000), timestamp: "t" }],
617 };
618 yield* serveSnapshots("mcp-bounded-logs-client", oversized);
619
620 const snapshot = yield* callSnapshot({ includeImage: false });
621
622 const [, text] = snapshot.content;
623 const body = text?.type === "text" ? text.text : "";
624 expect(Buffer.byteLength(body, "utf8")).toBeLessThanOrEqual(
625 McpHttpServer.MAX_SNAPSHOT_TEXT_BYTES,
626 );
627 const parsed = decodeJsonText(body) as {
628 readonly title: string;
629 readonly consoleEntries: ReadonlyArray<{ readonly text: string }>;
630 };
631 expect(parsed.title.length).toBe(2_049);
632 expect(parsed.consoleEntries[0]?.text.length).toBe(501);
633 const notice = snapshot.content[2];
634 const noticeText = notice?.type === "text" ? notice.text : "";
635 expect(noticeText).toContain("url or title after 2048 characters");
636 expect(noticeText).toContain("console entries text after 500 characters");
637 }),
638 ).pipe(Effect.provide(layerTest)),
639);
640
641it.effect("bounds page text made of wide characters before dropping locators", () =>
642 Effect.scoped(
643 Effect.gen(function* () {
644 yield* serveSnapshots("mcp-wide-text-client", {
645 ...snapshotResult,
646 visibleText: "界".repeat(9_000),
647 interactiveElements: Array.from({ length: 20 }, (_, i) => ({
648 tag: "button",
649 role: "button",
650 name: `Button ${i}`,
651 selector: `#button-${i}`,
652 x: 0,
653 y: 0,
654 width: 10,
655 height: 10,
656 })),
657 });
658
659 const snapshot = yield* callSnapshot({ includeImage: false });
660
661 const [, text, notice] = snapshot.content;
662 const body = text?.type === "text" ? text.text : "";
663 expect(Buffer.byteLength(body, "utf8")).toBeLessThanOrEqual(
664 McpHttpServer.MAX_SNAPSHOT_TEXT_BYTES,
665 );
666 const parsed = decodeJsonText(body) as {
667 readonly visibleText: string;
668 readonly interactiveElements: ReadonlyArray<unknown>;
669 };
670 expect(parsed.visibleText).toMatch(/^界+…$/);
671 expect(parsed.interactiveElements).toHaveLength(20);
672 expect(notice?.type === "text" ? notice.text : "").toContain(
673 "visibleText after 4000 characters",
674 );
675 }),
676 ).pipe(Effect.provide(layerTest)),
677);
678
679it.effect("sheds log entries before locators when every list is full", () =>
680 Effect.scoped(
681 Effect.gen(function* () {
682 const long = "x".repeat(2_000);
683 const oversized = {
684 ...snapshotResult,
685 interactiveElements: Array.from({ length: 20 }, (_, i) => ({
686 tag: "button",
687 role: "button",
688 name: `Button ${i}`,
689 selector: `#button-${i}`,
690 x: 0,
691 y: 0,
692 width: 10,
693 height: 10,
694 })),
695 consoleEntries: Array.from({ length: 200 }, () => ({
696 level: long,
697 text: long,
698 timestamp: long,
699 source: long,
700 })),
701 networkEntries: Array.from({ length: 200 }, () => ({
702 url: long,
703 method: long,
704 status: 200,
705 failed: false,
706 errorText: long,
707 timestamp: long,
708 })),
709 actionTimeline: Array.from({ length: 200 }, () => ({
710 id: long,
711 action: long,
712 status: "succeeded",
713 startedAt: long,
714 completedAt: long,
715 error: long,
716 })),
717 };
718 yield* serveSnapshots("mcp-full-logs-client", oversized);
719
720 const snapshot = yield* callSnapshot({ includeImage: false });
721
722 const [, text, notice] = snapshot.content;
723 const body = text?.type === "text" ? text.text : "";
724 expect(Buffer.byteLength(body, "utf8")).toBeLessThanOrEqual(
725 McpHttpServer.MAX_SNAPSHOT_TEXT_BYTES,
726 );
727 const parsed = decodeJsonText(body) as {
728 readonly interactiveElements: ReadonlyArray<unknown>;
729 readonly consoleEntries: ReadonlyArray<unknown>;
730 readonly networkEntries: ReadonlyArray<unknown>;
731 readonly actionTimeline: ReadonlyArray<unknown>;
732 };
733 expect(parsed.interactiveElements).toHaveLength(20);
734 expect(
735 parsed.consoleEntries.length + parsed.networkEntries.length + parsed.actionTimeline.length,
736 ).toBeLessThan(120);
737 const noticeText = notice?.type === "text" ? notice.text : "";
738 expect(noticeText).toContain("40 of 40 actionTimeline");
739 expect(noticeText).not.toMatch(/\d+ of \d+ interactiveElements/);
740 }),
741 ).pipe(Effect.provide(layerTest)),
742);
743
744it.effect("terminates HTTP MCP sessions with DELETE", () =>
745 Effect.scoped(
746 Effect.gen(function* () {
747 const token = "providerTokenWithoutDots";
748 const scope: McpInvocationContext.McpInvocationScope = {
749 environmentId,
750 requestNamespace: "provider-session",
751 thread: {
752 threadId: ThreadId.make("thread-provider"),
753 providerSessionId: "provider-session",
754 providerInstanceId: ProviderInstanceId.make("codex"),
755 },
756 client: undefined,
757 capabilities: new Set(["orchestration"]),
758 issuedAt: 1,
759 };
760 const layerServer = McpHttpServer.layerMcpTransport.pipe(
761 Layer.provide(
762 Layer.mock(McpSessionRegistry.McpSessionRegistry)({
763 resolve: (presented) =>
764 Effect.succeed(
765 presented === token
766 ? (scope as McpInvocationContext.McpThreadInvocationScope)
767 : undefined,
768 ),
769 }),
770 ),
771 );
772 yield* HttpRouter.serve(layerServer, {
773 disableListenLog: true,
774 disableLogger: true,
775 }).pipe(Layer.build);
776 const httpClient = (yield* HttpClient.HttpClient).pipe(
777 HttpClient.mapRequest(HttpClientRequest.bearerToken(token)),
778 );
779
780 const initializeResponse = yield* httpClient.post("/mcp", {
781 headers: { accept: "application/json, text/event-stream" },
782 body: HttpBody.text(
783 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"mcp-test","version":"1.0.0"}}}`,
784 "application/json",
785 ),
786 });
787 const sessionId = initializeResponse.headers["mcp-session-id"];
788 expect(initializeResponse.status).toBe(200);
789 expect(sessionId).not.toBeNull();
790
791 const missingSessionResponse = yield* httpClient.del("/mcp");
792 expect(missingSessionResponse.status).toBe(400);
793
794 const unknownSessionResponse = yield* httpClient.del("/mcp", {
795 headers: { "mcp-session-id": "unknown-session" },
796 });
797 expect(unknownSessionResponse.status).toBe(404);
798
799 const terminateResponse = yield* httpClient.del("/mcp", {
800 headers: { "mcp-session-id": sessionId! },
801 });
802 expect(terminateResponse.status).toBe(204);
803
804 const reusedSessionResponse = yield* httpClient.post("/mcp", {
805 headers: {
806 accept: "application/json, text/event-stream",
807 "mcp-session-id": sessionId!,
808 },
809 body: HttpBody.text(
810 `{"jsonrpc":"2.0","id":2,"method":"ping","params":{}}`,
811 "application/json",
812 ),
813 });
814 expect(reusedSessionResponse.status).toBe(404);
815 }),
816 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
817);
818
819it.effect("registers annotated tools and preserves authenticated request context", () =>
820 Effect.scoped(
821 Effect.gen(function* () {
822 const server = yield* McpServer.McpServer;
823 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
824 const toolIcon = {
825 _tag: "website" as const,
826 pageUrl: "http://example.test/",
827 };
828 const routedRequests: Array<{
829 readonly operation: string;
830 readonly tabId?: string | undefined;
831 }> = [];
832 const events = yield* broker.connect({
833 clientId: "mcp-test-client",
834 environmentId,
835 });
836 yield* Stream.runForEach(events, (event) => {
837 if (event.type === "connected") return Effect.void;
838 routedRequests.push(event.request);
839 return broker.respond({
840 clientId: "mcp-test-client",
841 connectionId: event.connectionId,
842 requestId: event.request.requestId,
843 ok: true,
844 result:
845 event.request.operation === "snapshot"
846 ? snapshotResult
847 : event.request.operation === "evaluate"
848 ? ["Connect", "Continue"]
849 : event.request.operation === "press"
850 ? undefined
851 : {
852 available: true,
853 visible: true,
854 tabId,
855 url: "http://example.test/",
856 title: "Example",
857 loading: false,
858 },
859 });
860 }).pipe(Effect.forkScoped);
861 yield* Effect.yieldNow;
862
863 const statusTool = server.tools.find(({ tool }) => tool.name === "preview_status");
864 expect(statusTool?.tool.annotations?.readOnlyHint).toBe(true);
865 expect(statusTool?.tool.annotations?.idempotentHint).toBe(true);
866 expect(statusTool?.tool.annotations?.destructiveHint).toBe(false);
867
868 const snapshotTool = server.tools.find(({ tool }) => tool.name === "preview_snapshot");
869 expect(snapshotTool?.tool.annotations?.readOnlyHint).toBe(false);
870 expect(snapshotTool?.tool.annotations?.idempotentHint).toBe(false);
871 expect(snapshotTool?.tool.annotations?.openWorldHint).toBe(true);
872
873 const clickTool = server.tools.find(({ tool }) => tool.name === "preview_click");
874 expect(clickTool?.tool.annotations?.readOnlyHint).toBe(false);
875 expect(clickTool?.tool.annotations?.destructiveHint).toBe(true);
876 expect(clickTool?.tool.annotations?.openWorldHint).toBe(true);
877 expect(clickTool?.tool.outputSchema).toMatchObject({
878 type: "object",
879 additionalProperties: true,
880 description: "The preview action completed successfully.",
881 });
882
883 const navigateTool = server.tools.find(({ tool }) => tool.name === "preview_navigate");
884 expect(navigateTool?.tool.annotations?.destructiveHint).toBe(false);
885 expect(navigateTool?.tool.annotations?.openWorldHint).toBe(true);
886
887 const status = yield* server
888 .callTool({ name: "preview_status", arguments: {} })
889 .pipe(
890 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
891 Effect.provideService(McpSchema.McpServerClient, client),
892 );
893 expect(status.isError).toBe(false);
894 expect(status.structuredContent).toMatchObject({
895 available: true,
896 tabId,
897 });
898
899 const malformed = yield* server
900 .callTool({ name: "preview_click", arguments: { selector: "" } })
901 .pipe(
902 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
903 Effect.provideService(McpSchema.McpServerClient, client),
904 Effect.flip,
905 );
906 expect(malformed._tag).toBe("InvalidParams");
907
908 const snapshot = yield* server
909 .callTool({
910 name: "preview_snapshot",
911 arguments: { tabId: alternateTabId, includeImage: true },
912 })
913 .pipe(
914 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
915 Effect.provideService(McpSchema.McpServerClient, client),
916 );
917 expect(snapshot.isError).toBe(false);
918 expect(snapshot.content.some((content) => content.type === "image")).toBe(true);
919 expect(snapshot.structuredContent).toMatchObject({
920 screenshot: { mimeType: "image/png", width: 10, height: 5 },
921 });
922 expect(routedRequests.find(({ operation }) => operation === "snapshot")?.tabId).toBe(
923 alternateTabId,
924 );
925
926 // Arrays and primitives are wrapped so structuredContent stays a JSON object.
927 // Claude Code rejects the whole result otherwise.
928 const evaluateTool = server.tools.find(({ tool }) => tool.name === "preview_evaluate");
929 expect(evaluateTool?.tool.outputSchema).toMatchObject({ type: "object" });
930 const evaluated = yield* server
931 .callTool({ name: "preview_evaluate", arguments: { expression: "buttons()" } })
932 .pipe(
933 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
934 Effect.provideService(McpSchema.McpServerClient, client),
935 );
936 expect(evaluated.isError).toBe(false);
937 expect(evaluated.structuredContent).toEqual({ value: ["Connect", "Continue"], toolIcon });
938 const evaluatedText = evaluated.content[0];
939 expect(evaluatedText?.type === "text" ? decodeJsonText(evaluatedText.text) : null).toEqual({
940 toolIcon,
941 value: ["Connect", "Continue"],
942 });
943
944 const actionRequests = [
945 { name: "preview_click", arguments: { x: 10, y: 10 } },
946 { name: "preview_type", arguments: { text: "Hello" } },
947 { name: "preview_press", arguments: { key: "Enter" } },
948 { name: "preview_scroll", arguments: { deltaY: 100 } },
949 { name: "preview_wait_for", arguments: { text: "Example" } },
950 ];
951 for (const request of actionRequests) {
952 const result = yield* server
953 .callTool(request)
954 .pipe(
955 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
956 Effect.provideService(McpSchema.McpServerClient, client),
957 );
958 expect(result.isError).toBe(false);
959 expect(result.structuredContent).toEqual({ toolIcon });
960 expect(routedRequests.at(-1)?.operation).toBe("status");
961 const text = result.content[0];
962 expect(text?.type === "text" ? decodeJsonText(text.text) : null).toEqual({ toolIcon });
963 }
964 }),
965 ).pipe(Effect.provide(layerTest)),
966);
967
968it.effect("admits provider and OAuth client credentials and points only clients at OAuth", () =>
969 Effect.scoped(
970 Effect.gen(function* () {
971 const providerToken = "providerTokenWithoutDots";
972 const clientToken = "client-payload.client-signature";
973 const providerScope: McpInvocationContext.McpInvocationScope = {
974 environmentId,
975 requestNamespace: "provider-session",
976 thread: {
977 threadId: ThreadId.make("thread-provider"),
978 providerSessionId: "provider-session",
979 providerInstanceId: ProviderInstanceId.make("codex"),
980 },
981 client: undefined,
982 capabilities: new Set(["orchestration"]),
983 issuedAt: 1,
984 };
985 const clientScope: McpInvocationContext.McpInvocationScope = {
986 environmentId,
987 requestNamespace: "client:session-1",
988 thread: undefined,
989 client: { sessionId: "session-1", label: "Claude Code", access: "auto" },
990 capabilities: new Set(["orchestration"]),
991 issuedAt: 1,
992 };
993 const seen: Array<McpInvocationContext.McpInvocationScope> = [];
994 const ProbeToolkit = Toolkit.make(
995 Tool.make("probe", {
996 description: "Reports the caller.",
997 success: Schema.Struct({ ok: Schema.Boolean }),
998 failure: OrchestratorMcpFailure,
999 failureMode: "return",
1000 dependencies: [McpInvocationContext.McpInvocationContext],
1001 }),
1002 );
1003 const serverLayer = McpHttpServer.toolkitRegistration(
1004 ProbeToolkit,
1005 McpToolAccess.toLayer(ProbeToolkit, {
1006 probe: McpToolAccess.reads(() =>
1007 McpInvocationContext.McpInvocationContext.pipe(
1008 Effect.tap((scope) => Effect.sync(() => seen.push(scope))),
1009 Effect.as({ ok: true }),
1010 ),
1011 ),
1012 }),
1013 ).pipe(
1014 Layer.provideMerge(McpHttpServer.layerMcpTransport),
1015 Layer.provide(
1016 Layer.mock(McpSessionRegistry.McpSessionRegistry)({
1017 resolve: (token) =>
1018 Effect.succeed(
1019 token === providerToken
1020 ? (providerScope as McpInvocationContext.McpThreadInvocationScope)
1021 : undefined,
1022 ),
1023 }),
1024 ),
1025 Layer.provide(
1026 Layer.succeed(McpHttpServer.McpClientAuthenticator, {
1027 authenticate: (request) =>
1028 Effect.succeed(
1029 request.headers.authorization === `Bearer ${clientToken}` ? clientScope : undefined,
1030 ),
1031 }),
1032 ),
1033 );
1034 yield* HttpRouter.serve(serverLayer, { disableListenLog: true, disableLogger: true }).pipe(
1035 Layer.build,
1036 );
1037 const httpClient = yield* HttpClient.HttpClient;
1038 const call = (token: string | undefined) =>
1039 Effect.gen(function* () {
1040 const headers = {
1041 accept: "application/json, text/event-stream",
1042 ...(token === undefined ? {} : { authorization: `Bearer ${token}` }),
1043 };
1044 const initialize = yield* httpClient.post("/mcp", {
1045 headers,
1046 body: HttpBody.text(
1047 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`,
1048 "application/json",
1049 ),
1050 });
1051 if (initialize.status !== 200) return initialize;
1052 return yield* httpClient.post("/mcp", {
1053 headers: {
1054 ...headers,
1055 "mcp-session-id": initialize.headers["mcp-session-id"]!,
1056 "mcp-protocol-version": "2025-06-18",
1057 },
1058 body: HttpBody.text(
1059 `{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"probe","arguments":{}}}`,
1060 "application/json",
1061 ),
1062 });
1063 });
1064
1065 expect((yield* call(providerToken)).status).toBe(200);
1066 expect((yield* call(clientToken)).status).toBe(200);
1067 expect(seen.map((scope) => scope.requestNamespace)).toEqual([
1068 "provider-session",
1069 "client:session-1",
1070 ]);
1071
1072 const missing = yield* call(undefined);
1073 expect(missing.status).toBe(401);
1074 expect(missing.headers["www-authenticate"]).toMatch(
1075 /^Bearer resource_metadata="http:\/\/[^"]+\/\.well-known\/oauth-protected-resource\/mcp"$/,
1076 );
1077
1078 const expiredClient = yield* call("stale-payload.stale-signature");
1079 expect(expiredClient.headers["www-authenticate"]).toContain("resource_metadata=");
1080 expect(expiredClient.headers["www-authenticate"]).toContain('error="invalid_token"');
1081
1082 const deadProvider = yield* call("deadProviderToken");
1083 expect(deadProvider.status).toBe(401);
1084 expect(deadProvider.headers["www-authenticate"]).toBe('Bearer error="invalid_token"');
1085 }),
1086 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
1087);