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