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