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