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

McpHttpServer.test.ts

872 lines33.9 KB

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