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

McpHttpServer.test.ts

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