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