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

McpHttpServer.test.ts

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