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

McpHttpServer.test.ts

905 lines34.5 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 Layer from "effect/Layer";
16import * as Schema from "effect/Schema";
17import * as Stream from "effect/Stream";
18import { McpSchema, McpServer, Tool, Toolkit } from "effect/ai";
19import { HttpBody, HttpClient, HttpClientRequest, HttpRouter } from "effect/http";
20​
21import * as ProjectService from "../project/ProjectService.ts";
22import * as PullRequestReviewGuideService from "../pullRequest/PullRequestReviewGuideService.ts";
23import * as ServerConfig from "../config.ts";
24import * as McpHttpServer from "./McpHttpServer.ts";
25import * as McpToolAccess from "./McpToolAccess.ts";
26import * as McpToolAccessTestkit from "./McpToolAccess.testkit.ts";
27import * as McpInvocationContext from "./McpInvocationContext.ts";
28import * as McpSessionRegistry from "./McpSessionRegistry.ts";
29import * as OrchestratorMcpService from "./OrchestratorMcpService.ts";
30import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
31import { OrchestratorToolkit } from "./toolkits/orchestrator/tools.ts";
32import { ProjectToolkit } from "./toolkits/project/tools.ts";
33​
34const environmentId = EnvironmentId.make("environment-mcp-test");
35const threadId = ThreadId.make("thread-mcp-test");
36const alternateTabId = PreviewTabId.make("tab-mcp-alternate");
37const decodeJsonText = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
38const invocation = {
39 environmentId,
40 requestNamespace: "provider-session-mcp-test",
41 thread: {
42 threadId,
43 providerSessionId: "provider-session-mcp-test",
44 providerInstanceId: ProviderInstanceId.make("codex"),
45 },
46 client: undefined,
47 capabilities: new Set(["preview"] as const),
48 issuedAt: 1,
49};
50const client = McpSchema.McpServerClient.of({
51 clientId: 1,
52 clientCapabilities: {},
53 clientInfo: { name: "mcp-test", version: "1.0.0" },
54 protocolVersion: "2025-06-18",
55 initializePayload: {
56 protocolVersion: "2025-06-18",
57 capabilities: {},
58 clientInfo: { name: "mcp-test", version: "1.0.0" },
59 },
60 getClient: Effect.die("unused"),
61});
62const layerTest = McpHttpServer.layerPreviewToolkit.pipe(
63 Layer.provideMerge(McpServer.McpServer.layer),
64 Layer.provideMerge(McpToolAccessTestkit.liveThreadsLayer),
65 Layer.provideMerge(PreviewAutomationBroker.layer),
66 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-http-server-test-" })),
67 Layer.provideMerge(NodeServices.layer),
68);
69const layerPullRequestsTest = McpHttpServer.layerPullRequestsToolkit.pipe(
70 Layer.provideMerge(McpServer.McpServer.layer),
71 Layer.provideMerge(McpToolAccessTestkit.liveThreadsLayer),
72 Layer.provide(
73 Layer.mergeAll(
74 Layer.mock(ProjectService.ProjectService)({}),
75 Layer.mock(PullRequestReviewGuideService.PullRequestReviewGuideService)({}),
76 Layer.mock(Orchestrator.OrchestratorV2)({}),
77 Layer.mock(ProjectionStore.ProjectionStoreV2)({}),
78 NodeServices.layer,
79 ),
80 ),
81);
82​
83const snapshotResult = {
84 url: "http://example.test/",
85 title: "Example",
86 loading: false,
87 visibleText: "Example",
88 interactiveElements: [],
89 accessibilityTree: {},
90 consoleEntries: [],
91 networkEntries: [],
92 actionTimeline: [],
93 screenshot: {
94 mimeType: "image/png",
95 data: Buffer.from("png").toString("base64"),
96 width: 10,
97 height: 5,
98 },
99};
100​
101const serveSnapshots = (clientId: string, result: unknown) =>
102 Effect.gen(function* () {
103 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
104 const connected = yield* Deferred.make<void>();
105 const inputs: Array<unknown> = [];
106 const events = yield* broker.connect({ clientId, environmentId });
107 yield* Stream.runForEach(events, (event) => {
108 if (event.type === "connected") return Deferred.succeed(connected, undefined);
109 inputs.push(event.request.input);
110 return broker.respond({
111 clientId,
112 connectionId: event.connectionId,
113 requestId: event.request.requestId,
114 ok: true,
115 result,
116 });
117 }).pipe(Effect.forkScoped);
118 yield* Deferred.await(connected);
119 return inputs;
120 });
121​
122const callTool = (name: string, args: Record<string, unknown>) =>
123 Effect.gen(function* () {
124 const server = yield* McpServer.McpServer;
125 return yield* server
126 .callTool({ name, arguments: args })
127 .pipe(
128 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
129 Effect.provideService(McpSchema.McpServerClient, client),
130 );
131 });
132​
133const callSnapshot = (args: Record<string, unknown>) => callTool("preview_snapshot", args);
134​
135const layerRecordingTools = (calls: Array<unknown>) => {
136 const RecordingToolkit = Toolkit.make(
137 OrchestratorToolkit.tools.delegate_task,
138 OrchestratorToolkit.tools.t3_thread_read,
139 OrchestratorToolkit.tools.t3_thread_wait,
140 ProjectToolkit.tools.t3_project_update,
141 );
142 const record = McpToolAccess.reads((params: unknown) =>
143 Effect.sync(() => calls.push(params)).pipe(
144 Effect.andThen(
145 Effect.fail(new OrchestratorMcpFailure({ code: "thread_not_found", message: "Recorded." })),
146 ),
147 ),
148 );
149 return McpHttpServer.toolkitRegistration(
150 RecordingToolkit,
151 McpToolAccess.toLayer(RecordingToolkit, {
152 delegate_task: record,
153 t3_thread_read: record,
154 t3_thread_wait: record,
155 t3_project_update: record,
156 }),
157 ).pipe(
158 Layer.provideMerge(McpServer.McpServer.layer),
159 Layer.provide(
160 Layer.mergeAll(
161 McpToolAccessTestkit.liveThreadsLayer,
162 Layer.mock(OrchestratorMcpService.OrchestratorMcpService)({}),
163 Layer.mock(ProjectService.ProjectService)({}),
164 NodeServices.layer,
165 ),
166 ),
167 );
168};
169​
170it.effect.each([{}, { includeImage: false }])(
171 "returns bounded structural preview snapshot failures %#",
172 (input) =>
173 Effect.scoped(
174 Effect.gen(function* () {
175 const server = yield* McpServer.McpServer;
176 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
177 const events = yield* broker.connect({
178 clientId: "mcp-failure-client",
179 environmentId,
180 });
181 yield* Stream.runForEach(events, (event) =>
182 event.type === "connected"
183 ? Effect.void
184 : broker.respond({
185 clientId: "mcp-failure-client",
186 connectionId: event.connectionId,
187 requestId: event.request.requestId,
188 ok: false,
189 error: {
190 _tag: "PreviewAutomationExecutionError",
191 message: "sensitive renderer failure",
192 detail: { consoleOutput: "sensitive browser output" },
193 },
194 }),
195 ).pipe(Effect.forkScoped);
196 yield* Effect.yieldNow;
197​
198 const snapshot = yield* server
199 .callTool({ name: "preview_snapshot", arguments: input })
200 .pipe(
201 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
202 Effect.provideService(McpSchema.McpServerClient, client),
203 );
204​
205 const message = "Preview automation snapshot failed on client mcp-failure-client.";
206 expect(snapshot.isError).toBe(true);
207 expect(snapshot.content).toEqual([
208 { type: "text", text: `Preview snapshot failed: ${message}` },
209 ]);
210 expect(snapshot.structuredContent).toEqual({
211 error: {
212 _tag: "PreviewAutomationExecutionError",
213 operation: "snapshot",
214 failureCount: 1,
215 message,
216 },
217 });
218 }),
219 ).pipe(Effect.provide(layerTest)),
220);
221​
222it.effect.each([
223 { mode: "default", input: {}, images: false },
224 { mode: "explicit image", input: { includeImage: true }, images: true },
225 { mode: "text only", input: { includeImage: false }, images: false },
226])("returns fresh $mode snapshots on repeated MCP calls", ({ input, images }) =>
227 Effect.scoped(
228 Effect.gen(function* () {
229 const server = yield* McpServer.McpServer;
230 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
231 const connected = yield* Deferred.make<void>();
232 const png =
233 "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII=";
234 const page = {
235 url: "http://example.test/",
236 loading: false,
237 visibleText: "Save your changes",
238 interactiveElements: [
239 {
240 tag: "button",
241 role: "button",
242 name: "Save",
243 selector: "#save",
244 x: 0,
245 y: 0,
246 width: 20,
247 height: 10,
248 },
249 ],
250 accessibilityTree: { role: "document", name: "Example" },
251 consoleEntries: [],
252 networkEntries: [],
253 actionTimeline: [],
254 };
255 const screenshot = { mimeType: "image/png", width: 1, height: 1 };
256 let requests = 0;
257 const events = yield* broker.connect({ clientId: "mcp-image-option-client", environmentId });
258 yield* Stream.runForEach(events, (event) => {
259 if (event.type === "connected") return Deferred.succeed(connected, undefined);
260 requests += 1;
261 expect(event.request).toMatchObject({
262 operation: "snapshot",
263 tabId: alternateTabId,
264 threadId,
265 });
266 expect(event.request.input).toEqual({});
267 return broker.respond({
268 clientId: "mcp-image-option-client",
269 connectionId: event.connectionId,
270 requestId: event.request.requestId,
271 ok: true,
272 result: {
273 ...page,
274 title: `Snapshot ${requests}`,
275 screenshot: { ...screenshot, data: png },
276 },
277 });
278 }).pipe(Effect.forkScoped);
279 yield* Deferred.await(connected);
280​
281 for (const call of [1, 2, 3, 4, 5, 6]) {
282 const snapshot = yield* server
283 .callTool({
284 name: "preview_snapshot",
285 arguments: { ...input, tabId: alternateTabId },
286 })
287 .pipe(
288 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
289 Effect.provideService(McpSchema.McpServerClient, client),
290 );
291 const metadata = { ...page, title: `Snapshot ${call}`, screenshot };
292 const { accessibilityTree: _tree, ...boundedMetadata } = metadata;
293 expect(snapshot.isError).toBe(false);
294 expect(snapshot.structuredContent).toEqual({
295 ...boundedMetadata,
296 omitted: ["accessibilityTree (use interactiveElements locators or preview_evaluate)"],
297 });
298 const [identity, text, ...rest] = snapshot.content;
299 expect(identity?.type === "text" ? decodeJsonText(identity.text) : null).toEqual({
300 url: page.url,
301 });
302 expect(text?.type === "text" ? decodeJsonText(text.text) : null).toEqual(boundedMetadata);
303 expect(rest).toEqual([
304 {
305 type: "text",
306 text: "Snapshot text was bounded. Omitted: accessibilityTree (use interactiveElements locators or preview_evaluate).",
307 },
308 ...(images
309 ? [
310 {
311 type: "image",
312 mimeType: "image/png",
313 data: new Uint8Array(Buffer.from(png, "base64")),
314 },
315 ]
316 : []),
317 ]);
318 }
319​
320 const nextDefault = yield* server
321 .callTool({
322 name: "preview_snapshot",
323 arguments: { tabId: alternateTabId },
324 })
325 .pipe(
326 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
327 Effect.provideService(McpSchema.McpServerClient, client),
328 );
329 expect(nextDefault.content.map((content) => content.type)).toEqual(["text", "text", "text"]);
330 expect(nextDefault.structuredContent).toMatchObject({ title: "Snapshot 7", screenshot });
331 expect(nextDefault.structuredContent).not.toHaveProperty("accessibilityTree");
332 expect(requests).toBe(7);
333 }),
334 ).pipe(Effect.provide(layerTest)),
335);
336​
337it.effect("refuses preview tools to a client outside a thread before they run", () =>
338 Effect.gen(function* () {
339 const server = yield* McpServer.McpServer;
340 const readOnly = {
341 ...invocation,
342 thread: undefined,
343 requestNamespace: "client:session-1",
344 client: { sessionId: "session-1", label: "Claude Code", access: "read-only" as const },
345 };
346 const click = yield* server
347 .callTool({ name: "preview_click", arguments: { locator: "text=Send" } })
348 .pipe(
349 Effect.provideService(McpInvocationContext.McpInvocationContext, readOnly),
350 Effect.provideService(McpSchema.McpServerClient, client),
351 );
352 expect(click.isError).toBe(true);
353 expect(click.content).toEqual([
354 { type: "text", text: expect.stringContaining("needs an agent running inside T3 Code") },
355 ]);
356 }).pipe(Effect.provide(layerTest)),
357);
358​
359it.effect("decodes null optional arguments the way it decodes omitted ones", () => {
360 const calls: Array<unknown> = [];
361 return Effect.gen(function* () {
362 const thread = { threadId: "thread-null-arguments" };
363 yield* callTool("t3_thread_read", thread);
364 yield* callTool("t3_thread_read", { ...thread, afterPosition: null, view: null });
365 yield* callTool("delegate_task", { task: "Inspect", target: {} });
366 yield* callTool("delegate_task", { task: "Inspect", title: null, target: { model: null } });
367 yield* callTool("t3_project_update", { projectId: "project-1", projectIcon: null });
368​
369 expect(calls).toHaveLength(5);
370 expect(calls[1]).toEqual(calls[0]);
371 expect(calls[3]).toEqual(calls[2]);
372 expect(calls[4]).toStrictEqual({ projectId: "project-1", projectIcon: null });
373 }).pipe(Effect.provide(layerRecordingTools(calls)));
374});
375​
376it.effect(
377 "clamps t3_thread_read page sizes above their maximum instead of rejecting the call",
378 () => {
379 const calls: Array<unknown> = [];
380 return Effect.gen(function* () {
381 const thread = { threadId: "thread-clamped-arguments" };
382 // Codex never shows the model these bounds, so an over-large page must still read.
383 yield* callTool("t3_thread_read", {
384 ...thread,
385 limit: 150,
386 runLimit: 80,
387 maxCharsPerItem: 60_000,
388 });
389 yield* callTool("t3_thread_read", {
390 ...thread,
391 limit: 100,
392 runLimit: 50,
393 maxCharsPerItem: 50_000,
394 });
395 yield* callTool("t3_thread_read", { ...thread, limit: 7, runLimit: 1, maxCharsPerItem: 1 });
396​
397 expect(calls).toEqual([
398 { ...thread, limit: 100, runLimit: 50, maxCharsPerItem: 50_000 },
399 { ...thread, limit: 100, runLimit: 50, maxCharsPerItem: 50_000 },
400 { ...thread, limit: 7, runLimit: 1, maxCharsPerItem: 1 },
401 ]);
402 }).pipe(Effect.provide(layerRecordingTools(calls)));
403 },
404);
405​
406it.effect.each(["limit", "runLimit", "maxCharsPerItem"])(
407 "still rejects a t3_thread_read %s below its minimum",
408 (field) => {
409 const calls: Array<unknown> = [];
410 return Effect.gen(function* () {
411 // Zero is a different request than one item, so it fails rather than answering another question.
412 const rejected = yield* callTool("t3_thread_read", {
413 threadId: "thread-below-minimum",
414 [field]: 0,
415 }).pipe(Effect.flip);
416​
417 expect(String(rejected)).toContain("greater than or equal to 1");
418 expect(calls).toEqual([]);
419 }).pipe(Effect.provide(layerRecordingTools(calls)));
420 },
421);
422​
423it("keeps cross-tool routing out of the delegate_task description", () => {
424 const description = OrchestratorToolkit.tools.delegate_task.description ?? "";
425 expect(description).toContain("Start one child agent with only `task`");
426 // Review rounds, follow-ups, and polling are routed in the system text.
427 expect(description).not.toContain("t3_thread_send");
428 expect(description).not.toContain("Do not poll");
429 expect(description).not.toContain("Prefer native");
430});
431​
432it.effect(
433 "registers the pull request toolkit and surfaces a missing capability as a tool error",
434 () =>
435 Effect.gen(function* () {
436 const server = yield* McpServer.McpServer;
437 const names = server.tools.map(({ tool }) => tool.name);
438 expect(names).toEqual(
439 expect.arrayContaining([
440 "link_pull_request",
441 "unlink_pull_request",
442 "list_thread_pull_requests",
443 ]),
444 );
445 const linkTool = server.tools.find(({ tool }) => tool.name === "link_pull_request");
446 expect(linkTool?.tool.annotations?.idempotentHint).toBe(true);
447 expect(linkTool?.tool.annotations?.openWorldHint).toBe(false);
448 expect(linkTool?.tool.description).toContain("Link a PR to this thread");
449 expect(linkTool?.tool.description).toContain("settles the thread on merge");
450​
451 const denied = yield* server
452 .callTool({ name: "list_thread_pull_requests", arguments: {} })
453 .pipe(
454 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
455 Effect.provideService(McpSchema.McpServerClient, client),
456 );
457 expect(denied.isError).toBe(true);
458 expect(denied.content).toEqual([
459 { type: "text", text: "MCP credential does not grant the pull-requests capability." },
460 ]);
461 }).pipe(Effect.provide(layerPullRequestsTest)),
462);
463​
464it.effect("bounds large ARIA trees without dropping every server locator", () =>
465 Effect.scoped(
466 Effect.gen(function* () {
467 const accessibilityTree = Array.from(
468 { length: 2_000 },
469 (_, index) => `- button "删除 ${index}" [ref=t3-snapshot-e${index}]`,
470 ).join("\n");
471 yield* serveSnapshots("mcp-large-server-refs", { ...snapshotResult, accessibilityTree });
472 const result = yield* callSnapshot({ includeImage: false });
473 expect(result.isError).toBe(false);
474 const metadata = result.structuredContent as { accessibilityTree: string };
475 expect(metadata.accessibilityTree).toContain("[ref=t3-snapshot-e0]");
476 expect(metadata.accessibilityTree.length).toBeLessThan(accessibilityTree.length);
477 const body = result.content[1];
478 expect(Buffer.byteLength(body?.type === "text" ? body.text : "", "utf8")).toBeLessThanOrEqual(
479 McpHttpServer.MAX_SNAPSHOT_TEXT_BYTES,
480 );
481 }),
482 ).pipe(Effect.provide(layerTest)),
483);
484​
485it.effect("keeps the snapshot text under the agent's output ceiling", () =>
486 Effect.scoped(
487 Effect.gen(function* () {
488 const pageText = "/Users/theo/Code/project\nClaude, Codex · 79 threads\n".repeat(600);
489 const element = (name: string, index: number) => ({
490 tag: "div",
491 role: "presentation",
492 name,
493 selector: `div:nth-of-type(${index})`,
494 x: 0,
495 y: 0,
496 width: 10,
497 height: 10,
498 });
499 const oversized = {
500 ...snapshotResult,
501 visibleText: pageText,
502 interactiveElements: [
503 element(pageText, 1),
504 element(pageText, 2),
505 element(pageText, 3),
506 element("Continue", 4),
507 ],
508 accessibilityTree: { nodes: Array.from({ length: 2_000 }, (_, i) => ({ nodeId: `${i}` })) },
509 consoleEntries: Array.from({ length: 100 }, (_, i) => ({
510 level: "log",
511 text: `entry ${i}`,
512 timestamp: "t",
513 })),
514 };
515 yield* serveSnapshots("mcp-bounded-client", oversized);
516​
517 const snapshot = yield* callSnapshot({ includeImage: false });
518​
519 expect(snapshot.isError).toBe(false);
520 const [identity, text, notice] = snapshot.content;
521 expect(identity?.type === "text" ? decodeJsonText(identity.text) : null).toEqual({
522 url: oversized.url,
523 });
524 expect(text?.type).toBe("text");
525 const body = text?.type === "text" ? text.text : "";
526 expect(Buffer.byteLength(body, "utf8")).toBeLessThanOrEqual(
527 McpHttpServer.MAX_SNAPSHOT_TEXT_BYTES,
528 );
529 const parsed = decodeJsonText(body) as {
530 readonly accessibilityTree?: unknown;
531 readonly visibleText: string;
532 readonly interactiveElements: ReadonlyArray<{ readonly name: string }>;
533 readonly consoleEntries: ReadonlyArray<{ readonly text: string }>;
534 };
535 expect(parsed.accessibilityTree).toBeUndefined();
536 expect(parsed.visibleText.length).toBeLessThanOrEqual(8_001);
537 expect(parsed.interactiveElements).toHaveLength(4);
538 expect(parsed.interactiveElements[0]?.name.length).toBeLessThanOrEqual(201);
539 expect(parsed.interactiveElements[3]?.name).toBe("Continue");
540 expect(parsed.consoleEntries).toHaveLength(40);
541 expect(parsed.consoleEntries[0]?.text).toBe("entry 60");
542 expect(notice?.type === "text" ? notice.text : "").toContain("accessibilityTree");
543 expect(notice?.type === "text" ? notice.text : "").toContain("60 older console entries");
544 expect(snapshot.structuredContent).toEqual({
545 ...parsed,
546 omitted: expect.arrayContaining(["60 older console entries"]),
547 });
548 }),
549 ).pipe(Effect.provide(layerTest)),
550);
551​
552// regression: #10501 keep preview snapshots usable by the agent
553it.effect("bounds the snapshot text even when nothing but logs and the title are large", () =>
554 Effect.scoped(
555 Effect.gen(function* () {
556 const oversized = {
557 ...snapshotResult,
558 title: "t".repeat(70_000),
559 interactiveElements: [],
560 consoleEntries: [{ level: "log", text: "x".repeat(70_000), timestamp: "t" }],
561 };
562 yield* serveSnapshots("mcp-bounded-logs-client", oversized);
563​
564 const snapshot = yield* callSnapshot({ includeImage: false });
565​
566 const [, text] = snapshot.content;
567 const body = text?.type === "text" ? text.text : "";
568 expect(Buffer.byteLength(body, "utf8")).toBeLessThanOrEqual(
569 McpHttpServer.MAX_SNAPSHOT_TEXT_BYTES,
570 );
571 const parsed = decodeJsonText(body) as {
572 readonly title: string;
573 readonly consoleEntries: ReadonlyArray<{ readonly text: string }>;
574 };
575 expect(parsed.title.length).toBe(2_049);
576 expect(parsed.consoleEntries[0]?.text.length).toBe(501);
577 const notice = snapshot.content[2];
578 const noticeText = notice?.type === "text" ? notice.text : "";
579 expect(noticeText).toContain("url or title after 2048 characters");
580 expect(noticeText).toContain("console entries text after 500 characters");
581 }),
582 ).pipe(Effect.provide(layerTest)),
583);
584​
585// regression: #13558 preview snapshots overflowed the agent's tool output
586it.effect("bounds page text made of wide characters before dropping locators", () =>
587 Effect.scoped(
588 Effect.gen(function* () {
589 yield* serveSnapshots("mcp-wide-text-client", {
590 ...snapshotResult,
591 visibleText: "界".repeat(9_000),
592 interactiveElements: Array.from({ length: 20 }, (_, i) => ({
593 tag: "button",
594 role: "button",
595 name: `Button ${i}`,
596 selector: `#button-${i}`,
597 x: 0,
598 y: 0,
599 width: 10,
600 height: 10,
601 })),
602 });
603​
604 const snapshot = yield* callSnapshot({ includeImage: false });
605​
606 const [, text, notice] = snapshot.content;
607 const body = text?.type === "text" ? text.text : "";
608 expect(Buffer.byteLength(body, "utf8")).toBeLessThanOrEqual(
609 McpHttpServer.MAX_SNAPSHOT_TEXT_BYTES,
610 );
611 const parsed = decodeJsonText(body) as {
612 readonly visibleText: string;
613 readonly interactiveElements: ReadonlyArray<unknown>;
614 };
615 expect(parsed.visibleText).toMatch(/^界+…$/);
616 expect(parsed.interactiveElements).toHaveLength(20);
617 expect(notice?.type === "text" ? notice.text : "").toContain(
618 "visibleText after 4000 characters",
619 );
620 }),
621 ).pipe(Effect.provide(layerTest)),
622);
623​
624it.effect("terminates HTTP MCP sessions with DELETE", () =>
625 Effect.scoped(
626 Effect.gen(function* () {
627 const token = "providerTokenWithoutDots";
628 const scope: McpInvocationContext.McpInvocationScope = {
629 environmentId,
630 requestNamespace: "provider-session",
631 thread: {
632 threadId: ThreadId.make("thread-provider"),
633 providerSessionId: "provider-session",
634 providerInstanceId: ProviderInstanceId.make("codex"),
635 },
636 client: undefined,
637 capabilities: new Set(["orchestration"]),
638 issuedAt: 1,
639 };
640 const layerServer = McpHttpServer.layerMcpTransport.pipe(
641 Layer.provide(
642 Layer.mock(McpSessionRegistry.McpSessionRegistry)({
643 resolve: (presented) =>
644 Effect.succeed(
645 presented === token
646 ? (scope as McpInvocationContext.McpThreadInvocationScope)
647 : undefined,
648 ),
649 }),
650 ),
651 );
652 yield* HttpRouter.serve(layerServer, {
653 disableListenLog: true,
654 disableLogger: true,
655 }).pipe(Layer.build);
656 const httpClient = (yield* HttpClient.HttpClient).pipe(
657 HttpClient.mapRequest(HttpClientRequest.bearerToken(token)),
658 );
659​
660 const initializeResponse = yield* httpClient.post("/mcp", {
661 headers: { accept: "application/json, text/event-stream" },
662 body: HttpBody.text(
663 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"mcp-test","version":"1.0.0"}}}`,
664 "application/json",
665 ),
666 });
667 const sessionId = initializeResponse.headers["mcp-session-id"];
668 expect(initializeResponse.status).toBe(200);
669 expect(sessionId).not.toBeNull();
670​
671 const missingSessionResponse = yield* httpClient.del("/mcp");
672 expect(missingSessionResponse.status).toBe(400);
673​
674 const unknownSessionResponse = yield* httpClient.del("/mcp", {
675 headers: { "mcp-session-id": "unknown-session" },
676 });
677 expect(unknownSessionResponse.status).toBe(404);
678​
679 const terminateResponse = yield* httpClient.del("/mcp", {
680 headers: { "mcp-session-id": sessionId! },
681 });
682 expect(terminateResponse.status).toBe(204);
683​
684 const reusedSessionResponse = yield* httpClient.post("/mcp", {
685 headers: {
686 accept: "application/json, text/event-stream",
687 "mcp-session-id": sessionId!,
688 },
689 body: HttpBody.text(
690 `{"jsonrpc":"2.0","id":2,"method":"ping","params":{}}`,
691 "application/json",
692 ),
693 });
694 expect(reusedSessionResponse.status).toBe(404);
695 }),
696 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
697);
698​
699it.effect("admits provider and OAuth client credentials and points only clients at OAuth", () =>
700 Effect.scoped(
701 Effect.gen(function* () {
702 const providerToken = "providerTokenWithoutDots";
703 const clientToken = "client-payload.client-signature";
704 const providerScope: McpInvocationContext.McpInvocationScope = {
705 environmentId,
706 requestNamespace: "provider-session",
707 thread: {
708 threadId: ThreadId.make("thread-provider"),
709 providerSessionId: "provider-session",
710 providerInstanceId: ProviderInstanceId.make("codex"),
711 },
712 client: undefined,
713 capabilities: new Set(["orchestration"]),
714 issuedAt: 1,
715 };
716 const clientScope: McpInvocationContext.McpInvocationScope = {
717 environmentId,
718 requestNamespace: "client:session-1",
719 thread: undefined,
720 client: { sessionId: "session-1", label: "Claude Code", access: "auto" },
721 capabilities: new Set(["orchestration"]),
722 issuedAt: 1,
723 };
724 const seen: Array<McpInvocationContext.McpInvocationScope> = [];
725 const ProbeToolkit = Toolkit.make(
726 Tool.make("probe", {
727 description: "Reports the caller.",
728 success: Schema.Struct({ ok: Schema.Boolean }),
729 failure: OrchestratorMcpFailure,
730 failureMode: "return",
731 dependencies: [McpInvocationContext.McpInvocationContext],
732 }),
733 );
734 const serverLayer = McpHttpServer.toolkitRegistration(
735 ProbeToolkit,
736 McpToolAccess.toLayer(ProbeToolkit, {
737 probe: McpToolAccess.reads(() =>
738 McpInvocationContext.McpInvocationContext.pipe(
739 Effect.tap((scope) => Effect.sync(() => seen.push(scope))),
740 Effect.as({ ok: true }),
741 ),
742 ),
743 }),
744 ).pipe(
745 Layer.provideMerge(McpHttpServer.layerMcpTransport),
746 Layer.provide(
747 Layer.mock(McpSessionRegistry.McpSessionRegistry)({
748 resolve: (token) =>
749 Effect.succeed(
750 token === providerToken
751 ? (providerScope as McpInvocationContext.McpThreadInvocationScope)
752 : undefined,
753 ),
754 }),
755 ),
756 Layer.provide(
757 Layer.succeed(McpHttpServer.McpClientAuthenticator, {
758 authenticate: (request) =>
759 Effect.succeed(
760 request.headers.authorization === `Bearer ${clientToken}` ? clientScope : undefined,
761 ),
762 }),
763 ),
764 );
765 yield* HttpRouter.serve(serverLayer, { disableListenLog: true, disableLogger: true }).pipe(
766 Layer.build,
767 );
768 const httpClient = yield* HttpClient.HttpClient;
769 const call = (token: string | undefined) =>
770 Effect.gen(function* () {
771 const headers = {
772 accept: "application/json, text/event-stream",
773 ...(token === undefined ? {} : { authorization: `Bearer ${token}` }),
774 };
775 const initialize = yield* httpClient.post("/mcp", {
776 headers,
777 body: HttpBody.text(
778 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`,
779 "application/json",
780 ),
781 });
782 if (initialize.status !== 200) return initialize;
783 return yield* httpClient.post("/mcp", {
784 headers: {
785 ...headers,
786 "mcp-session-id": initialize.headers["mcp-session-id"]!,
787 "mcp-protocol-version": "2025-06-18",
788 },
789 body: HttpBody.text(
790 `{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"probe","arguments":{}}}`,
791 "application/json",
792 ),
793 });
794 });
795​
796 expect((yield* call(providerToken)).status).toBe(200);
797 expect((yield* call(clientToken)).status).toBe(200);
798 expect(seen.map((scope) => scope.requestNamespace)).toEqual([
799 "provider-session",
800 "client:session-1",
801 ]);
802​
803 const missing = yield* call(undefined);
804 expect(missing.status).toBe(401);
805 expect(missing.headers["www-authenticate"]).toMatch(
806 /^Bearer resource_metadata="http:\/\/[^"]+\/\.well-known\/oauth-protected-resource\/mcp"$/,
807 );
808​
809 const expiredClient = yield* call("stale-payload.stale-signature");
810 expect(expiredClient.headers["www-authenticate"]).toContain("resource_metadata=");
811 expect(expiredClient.headers["www-authenticate"]).toContain('error="invalid_token"');
812​
813 const deadProvider = yield* call("deadProviderToken");
814 expect(deadProvider.status).toBe(401);
815 expect(deadProvider.headers["www-authenticate"]).toBe('Bearer error="invalid_token"');
816 }),
817 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
818);
819​
820it.effect("lists pull request watch tools only to threads that are not delegated children", () =>
821 Effect.scoped(
822 Effect.gen(function* () {
823 const scopeFor = (
824 token: string,
825 subagent: boolean,
826 ): McpInvocationContext.McpThreadInvocationScope => ({
827 environmentId,
828 requestNamespace: token,
829 thread: {
830 threadId: ThreadId.make(`thread-${token}`),
831 providerSessionId: token,
832 providerInstanceId: ProviderInstanceId.make("codex"),
833 subagent,
834 },
835 client: undefined,
836 capabilities: new Set(["pull-requests"]),
837 issuedAt: 1,
838 });
839 const scopes = new Map([
840 ["parentToken", scopeFor("parentToken", false)],
841 ["childToken", scopeFor("childToken", true)],
842 ]);
843 const serverLayer = McpHttpServer.layerPullRequestsToolkit.pipe(
844 Layer.provideMerge(McpHttpServer.layerMcpTransport),
845 Layer.provide(
846 Layer.mock(McpSessionRegistry.McpSessionRegistry)({
847 resolve: (token) => Effect.succeed(scopes.get(token)),
848 }),
849 ),
850 Layer.provide(
851 Layer.mergeAll(
852 McpToolAccessTestkit.liveThreadsLayer,
853 Layer.mock(ProjectService.ProjectService)({}),
854 Layer.mock(PullRequestReviewGuideService.PullRequestReviewGuideService)({}),
855 Layer.mock(Orchestrator.OrchestratorV2)({}),
856 Layer.mock(ProjectionStore.ProjectionStoreV2)({}),
857 NodeServices.layer,
858 ),
859 ),
860 );
861 yield* HttpRouter.serve(serverLayer, { disableListenLog: true, disableLogger: true }).pipe(
862 Layer.build,
863 );
864 const httpClient = yield* HttpClient.HttpClient;
865 const listedTools = (token: string) =>
866 Effect.gen(function* () {
867 const headers = {
868 accept: "application/json, text/event-stream",
869 authorization: `Bearer ${token}`,
870 };
871 const initialize = yield* httpClient.post("/mcp", {
872 headers,
873 body: HttpBody.text(
874 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`,
875 "application/json",
876 ),
877 });
878 const listed = yield* httpClient.post("/mcp", {
879 headers: {
880 ...headers,
881 "mcp-session-id": initialize.headers["mcp-session-id"]!,
882 "mcp-protocol-version": "2025-06-18",
883 },
884 body: HttpBody.text(
885 `{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}`,
886 "application/json",
887 ),
888 });
889 const body = (yield* listed.json) as {
890 readonly result: { readonly tools: ReadonlyArray<{ readonly name: string }> };
891 };
892 return body.result.tools.map((tool) => tool.name);
893 });
894​
895 const parentTools = yield* listedTools("parentToken");
896 const childTools = yield* listedTools("childToken");
897 expect(parentTools).toEqual(
898 expect.arrayContaining(["link_pull_request", "watch_pull_request", "unwatch_pull_request"]),
899 );
900 expect(childTools).toContain("link_pull_request");
901 expect(childTools).not.toContain("watch_pull_request");
902 expect(childTools).not.toContain("unwatch_pull_request");
903 }),
904 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
905);