Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

McpHttpServer.test.ts

874 lines34.0 KB

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