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