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

McpHttpServer.test.ts

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