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