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

McpHttpServer.test.ts

819 lines31.1 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("routes same-child follow-ups to t3_thread_send and independent reviews to delegate_task", () => {
424 const description = OrchestratorToolkit.tools.delegate_task.description ?? "";
425 expect(description).toContain(
426 "For independent T3 delegated review rounds, call delegate_task again",
427 );
428 expect(description).toContain(
429 "For a follow-up that needs the same child's conversation, use t3_thread_send on its childThreadId.",
430 );
431 expect(description).not.toContain("not the target for starting another");
432});
433​
434it.effect(
435 "registers the pull request toolkit and surfaces a missing capability as a tool error",
436 () =>
437 Effect.gen(function* () {
438 const server = yield* McpServer.McpServer;
439 const names = server.tools.map(({ tool }) => tool.name);
440 expect(names).toEqual(
441 expect.arrayContaining([
442 "link_pull_request",
443 "unlink_pull_request",
444 "list_thread_pull_requests",
445 ]),
446 );
447 const linkTool = server.tools.find(({ tool }) => tool.name === "link_pull_request");
448 expect(linkTool?.tool.annotations?.idempotentHint).toBe(true);
449 expect(linkTool?.tool.annotations?.openWorldHint).toBe(false);
450 expect(linkTool?.tool.description).toContain("Register every pull request you open");
451​
452 const denied = yield* server
453 .callTool({ name: "list_thread_pull_requests", arguments: {} })
454 .pipe(
455 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
456 Effect.provideService(McpSchema.McpServerClient, client),
457 );
458 expect(denied.isError).toBe(true);
459 expect(denied.content).toEqual([
460 { type: "text", text: "MCP credential does not grant the pull-requests capability." },
461 ]);
462 }).pipe(Effect.provide(layerPullRequestsTest)),
463);
464​
465it.effect("bounds large ARIA trees without dropping every server locator", () =>
466 Effect.scoped(
467 Effect.gen(function* () {
468 const accessibilityTree = Array.from(
469 { length: 2_000 },
470 (_, index) => `- button "删除 ${index}" [ref=t3-snapshot-e${index}]`,
471 ).join("\n");
472 yield* serveSnapshots("mcp-large-server-refs", { ...snapshotResult, accessibilityTree });
473 const result = yield* callSnapshot({ includeImage: false });
474 expect(result.isError).toBe(false);
475 const metadata = result.structuredContent as { accessibilityTree: string };
476 expect(metadata.accessibilityTree).toContain("[ref=t3-snapshot-e0]");
477 expect(metadata.accessibilityTree.length).toBeLessThan(accessibilityTree.length);
478 const body = result.content[1];
479 expect(Buffer.byteLength(body?.type === "text" ? body.text : "", "utf8")).toBeLessThanOrEqual(
480 McpHttpServer.MAX_SNAPSHOT_TEXT_BYTES,
481 );
482 }),
483 ).pipe(Effect.provide(layerTest)),
484);
485​
486it.effect("keeps the snapshot text under the agent's output ceiling", () =>
487 Effect.scoped(
488 Effect.gen(function* () {
489 const pageText = "/Users/theo/Code/project\nClaude, Codex · 79 threads\n".repeat(600);
490 const element = (name: string, index: number) => ({
491 tag: "div",
492 role: "presentation",
493 name,
494 selector: `div:nth-of-type(${index})`,
495 x: 0,
496 y: 0,
497 width: 10,
498 height: 10,
499 });
500 const oversized = {
501 ...snapshotResult,
502 visibleText: pageText,
503 interactiveElements: [
504 element(pageText, 1),
505 element(pageText, 2),
506 element(pageText, 3),
507 element("Continue", 4),
508 ],
509 accessibilityTree: { nodes: Array.from({ length: 2_000 }, (_, i) => ({ nodeId: `${i}` })) },
510 consoleEntries: Array.from({ length: 100 }, (_, i) => ({
511 level: "log",
512 text: `entry ${i}`,
513 timestamp: "t",
514 })),
515 };
516 yield* serveSnapshots("mcp-bounded-client", oversized);
517​
518 const snapshot = yield* callSnapshot({ includeImage: false });
519​
520 expect(snapshot.isError).toBe(false);
521 const [identity, text, notice] = snapshot.content;
522 expect(identity?.type === "text" ? decodeJsonText(identity.text) : null).toEqual({
523 url: oversized.url,
524 });
525 expect(text?.type).toBe("text");
526 const body = text?.type === "text" ? text.text : "";
527 expect(Buffer.byteLength(body, "utf8")).toBeLessThanOrEqual(
528 McpHttpServer.MAX_SNAPSHOT_TEXT_BYTES,
529 );
530 const parsed = decodeJsonText(body) as {
531 readonly accessibilityTree?: unknown;
532 readonly visibleText: string;
533 readonly interactiveElements: ReadonlyArray<{ readonly name: string }>;
534 readonly consoleEntries: ReadonlyArray<{ readonly text: string }>;
535 };
536 expect(parsed.accessibilityTree).toBeUndefined();
537 expect(parsed.visibleText.length).toBeLessThanOrEqual(8_001);
538 expect(parsed.interactiveElements).toHaveLength(4);
539 expect(parsed.interactiveElements[0]?.name.length).toBeLessThanOrEqual(201);
540 expect(parsed.interactiveElements[3]?.name).toBe("Continue");
541 expect(parsed.consoleEntries).toHaveLength(40);
542 expect(parsed.consoleEntries[0]?.text).toBe("entry 60");
543 expect(notice?.type === "text" ? notice.text : "").toContain("accessibilityTree");
544 expect(notice?.type === "text" ? notice.text : "").toContain("60 older console entries");
545 expect(snapshot.structuredContent).toEqual({
546 ...parsed,
547 omitted: expect.arrayContaining(["60 older console entries"]),
548 });
549 }),
550 ).pipe(Effect.provide(layerTest)),
551);
552​
553// regression: #10501 keep preview snapshots usable by the agent
554it.effect("bounds the snapshot text even when nothing but logs and the title are large", () =>
555 Effect.scoped(
556 Effect.gen(function* () {
557 const oversized = {
558 ...snapshotResult,
559 title: "t".repeat(70_000),
560 interactiveElements: [],
561 consoleEntries: [{ level: "log", text: "x".repeat(70_000), timestamp: "t" }],
562 };
563 yield* serveSnapshots("mcp-bounded-logs-client", oversized);
564​
565 const snapshot = yield* callSnapshot({ includeImage: false });
566​
567 const [, text] = snapshot.content;
568 const body = text?.type === "text" ? text.text : "";
569 expect(Buffer.byteLength(body, "utf8")).toBeLessThanOrEqual(
570 McpHttpServer.MAX_SNAPSHOT_TEXT_BYTES,
571 );
572 const parsed = decodeJsonText(body) as {
573 readonly title: string;
574 readonly consoleEntries: ReadonlyArray<{ readonly text: string }>;
575 };
576 expect(parsed.title.length).toBe(2_049);
577 expect(parsed.consoleEntries[0]?.text.length).toBe(501);
578 const notice = snapshot.content[2];
579 const noticeText = notice?.type === "text" ? notice.text : "";
580 expect(noticeText).toContain("url or title after 2048 characters");
581 expect(noticeText).toContain("console entries text after 500 characters");
582 }),
583 ).pipe(Effect.provide(layerTest)),
584);
585​
586// regression: #13558 preview snapshots overflowed the agent's tool output
587it.effect("bounds page text made of wide characters before dropping locators", () =>
588 Effect.scoped(
589 Effect.gen(function* () {
590 yield* serveSnapshots("mcp-wide-text-client", {
591 ...snapshotResult,
592 visibleText: "界".repeat(9_000),
593 interactiveElements: Array.from({ length: 20 }, (_, i) => ({
594 tag: "button",
595 role: "button",
596 name: `Button ${i}`,
597 selector: `#button-${i}`,
598 x: 0,
599 y: 0,
600 width: 10,
601 height: 10,
602 })),
603 });
604​
605 const snapshot = yield* callSnapshot({ includeImage: false });
606​
607 const [, text, notice] = snapshot.content;
608 const body = text?.type === "text" ? text.text : "";
609 expect(Buffer.byteLength(body, "utf8")).toBeLessThanOrEqual(
610 McpHttpServer.MAX_SNAPSHOT_TEXT_BYTES,
611 );
612 const parsed = decodeJsonText(body) as {
613 readonly visibleText: string;
614 readonly interactiveElements: ReadonlyArray<unknown>;
615 };
616 expect(parsed.visibleText).toMatch(/^界+…$/);
617 expect(parsed.interactiveElements).toHaveLength(20);
618 expect(notice?.type === "text" ? notice.text : "").toContain(
619 "visibleText after 4000 characters",
620 );
621 }),
622 ).pipe(Effect.provide(layerTest)),
623);
624​
625it.effect("terminates HTTP MCP sessions with DELETE", () =>
626 Effect.scoped(
627 Effect.gen(function* () {
628 const token = "providerTokenWithoutDots";
629 const scope: McpInvocationContext.McpInvocationScope = {
630 environmentId,
631 requestNamespace: "provider-session",
632 thread: {
633 threadId: ThreadId.make("thread-provider"),
634 providerSessionId: "provider-session",
635 providerInstanceId: ProviderInstanceId.make("codex"),
636 },
637 client: undefined,
638 capabilities: new Set(["orchestration"]),
639 issuedAt: 1,
640 };
641 const layerServer = McpHttpServer.layerMcpTransport.pipe(
642 Layer.provide(
643 Layer.mock(McpSessionRegistry.McpSessionRegistry)({
644 resolve: (presented) =>
645 Effect.succeed(
646 presented === token
647 ? (scope as McpInvocationContext.McpThreadInvocationScope)
648 : undefined,
649 ),
650 }),
651 ),
652 );
653 yield* HttpRouter.serve(layerServer, {
654 disableListenLog: true,
655 disableLogger: true,
656 }).pipe(Layer.build);
657 const httpClient = (yield* HttpClient.HttpClient).pipe(
658 HttpClient.mapRequest(HttpClientRequest.bearerToken(token)),
659 );
660​
661 const initializeResponse = yield* httpClient.post("/mcp", {
662 headers: { accept: "application/json, text/event-stream" },
663 body: HttpBody.text(
664 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"mcp-test","version":"1.0.0"}}}`,
665 "application/json",
666 ),
667 });
668 const sessionId = initializeResponse.headers["mcp-session-id"];
669 expect(initializeResponse.status).toBe(200);
670 expect(sessionId).not.toBeNull();
671​
672 const missingSessionResponse = yield* httpClient.del("/mcp");
673 expect(missingSessionResponse.status).toBe(400);
674​
675 const unknownSessionResponse = yield* httpClient.del("/mcp", {
676 headers: { "mcp-session-id": "unknown-session" },
677 });
678 expect(unknownSessionResponse.status).toBe(404);
679​
680 const terminateResponse = yield* httpClient.del("/mcp", {
681 headers: { "mcp-session-id": sessionId! },
682 });
683 expect(terminateResponse.status).toBe(204);
684​
685 const reusedSessionResponse = yield* httpClient.post("/mcp", {
686 headers: {
687 accept: "application/json, text/event-stream",
688 "mcp-session-id": sessionId!,
689 },
690 body: HttpBody.text(
691 `{"jsonrpc":"2.0","id":2,"method":"ping","params":{}}`,
692 "application/json",
693 ),
694 });
695 expect(reusedSessionResponse.status).toBe(404);
696 }),
697 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
698);
699​
700it.effect("admits provider and OAuth client credentials and points only clients at OAuth", () =>
701 Effect.scoped(
702 Effect.gen(function* () {
703 const providerToken = "providerTokenWithoutDots";
704 const clientToken = "client-payload.client-signature";
705 const providerScope: McpInvocationContext.McpInvocationScope = {
706 environmentId,
707 requestNamespace: "provider-session",
708 thread: {
709 threadId: ThreadId.make("thread-provider"),
710 providerSessionId: "provider-session",
711 providerInstanceId: ProviderInstanceId.make("codex"),
712 },
713 client: undefined,
714 capabilities: new Set(["orchestration"]),
715 issuedAt: 1,
716 };
717 const clientScope: McpInvocationContext.McpInvocationScope = {
718 environmentId,
719 requestNamespace: "client:session-1",
720 thread: undefined,
721 client: { sessionId: "session-1", label: "Claude Code", access: "auto" },
722 capabilities: new Set(["orchestration"]),
723 issuedAt: 1,
724 };
725 const seen: Array<McpInvocationContext.McpInvocationScope> = [];
726 const ProbeToolkit = Toolkit.make(
727 Tool.make("probe", {
728 description: "Reports the caller.",
729 success: Schema.Struct({ ok: Schema.Boolean }),
730 failure: OrchestratorMcpFailure,
731 failureMode: "return",
732 dependencies: [McpInvocationContext.McpInvocationContext],
733 }),
734 );
735 const serverLayer = McpHttpServer.toolkitRegistration(
736 ProbeToolkit,
737 McpToolAccess.toLayer(ProbeToolkit, {
738 probe: McpToolAccess.reads(() =>
739 McpInvocationContext.McpInvocationContext.pipe(
740 Effect.tap((scope) => Effect.sync(() => seen.push(scope))),
741 Effect.as({ ok: true }),
742 ),
743 ),
744 }),
745 ).pipe(
746 Layer.provideMerge(McpHttpServer.layerMcpTransport),
747 Layer.provide(
748 Layer.mock(McpSessionRegistry.McpSessionRegistry)({
749 resolve: (token) =>
750 Effect.succeed(
751 token === providerToken
752 ? (providerScope as McpInvocationContext.McpThreadInvocationScope)
753 : undefined,
754 ),
755 }),
756 ),
757 Layer.provide(
758 Layer.succeed(McpHttpServer.McpClientAuthenticator, {
759 authenticate: (request) =>
760 Effect.succeed(
761 request.headers.authorization === `Bearer ${clientToken}` ? clientScope : undefined,
762 ),
763 }),
764 ),
765 );
766 yield* HttpRouter.serve(serverLayer, { disableListenLog: true, disableLogger: true }).pipe(
767 Layer.build,
768 );
769 const httpClient = yield* HttpClient.HttpClient;
770 const call = (token: string | undefined) =>
771 Effect.gen(function* () {
772 const headers = {
773 accept: "application/json, text/event-stream",
774 ...(token === undefined ? {} : { authorization: `Bearer ${token}` }),
775 };
776 const initialize = yield* httpClient.post("/mcp", {
777 headers,
778 body: HttpBody.text(
779 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`,
780 "application/json",
781 ),
782 });
783 if (initialize.status !== 200) return initialize;
784 return yield* httpClient.post("/mcp", {
785 headers: {
786 ...headers,
787 "mcp-session-id": initialize.headers["mcp-session-id"]!,
788 "mcp-protocol-version": "2025-06-18",
789 },
790 body: HttpBody.text(
791 `{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"probe","arguments":{}}}`,
792 "application/json",
793 ),
794 });
795 });
796​
797 expect((yield* call(providerToken)).status).toBe(200);
798 expect((yield* call(clientToken)).status).toBe(200);
799 expect(seen.map((scope) => scope.requestNamespace)).toEqual([
800 "provider-session",
801 "client:session-1",
802 ]);
803​
804 const missing = yield* call(undefined);
805 expect(missing.status).toBe(401);
806 expect(missing.headers["www-authenticate"]).toMatch(
807 /^Bearer resource_metadata="http:\/\/[^"]+\/\.well-known\/oauth-protected-resource\/mcp"$/,
808 );
809​
810 const expiredClient = yield* call("stale-payload.stale-signature");
811 expect(expiredClient.headers["www-authenticate"]).toContain("resource_metadata=");
812 expect(expiredClient.headers["www-authenticate"]).toContain('error="invalid_token"');
813​
814 const deadProvider = yield* call("deadProviderToken");
815 expect(deadProvider.status).toBe(401);
816 expect(deadProvider.headers["www-authenticate"]).toBe('Bearer error="invalid_token"');
817 }),
818 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
819);