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

McpHttpServer.test.ts

915 lines35.7 KB

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