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