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 NodeCrypto from "@effect/platform-node/NodeCrypto";
7import * as NodeServices from "@effect/platform-node/NodeServices";
8import {
9 DeviceId,
10 DeviceOperationError,
11 EnvironmentId,
12 OrchestratorMcpEnvironmentTarget,
13 OrchestratorMcpFailure,
14 PreviewTabId,
15 ProviderInstanceId,
16 ProviderInteractionMode,
17 RuntimeMode,
18 ThreadId,
19} from "@t3tools/contracts";
20import * as Context from "effect/Context";
21import * as Deferred from "effect/Deferred";
22import * as Effect from "effect/Effect";
23import * as Layer from "effect/Layer";
24import * as Logger from "effect/Logger";
25import * as Schema from "effect/Schema";
26import * as Stream from "effect/Stream";
27import { McpSchema, McpServer, Tool, Toolkit } from "effect/ai";
28import { HttpBody, HttpClient, HttpClientRequest, HttpRouter } from "effect/http";
29
30import * as ProjectService from "../project/ProjectService.ts";
31import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
32import * as McpOAuth from "../auth/McpOAuth.ts";
33import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
34import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
35import * as Sqlite from "../persistence/Sqlite.ts";
36import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
37
38import * as DeviceService from "../device/DeviceService.ts";
39import * as PullRequestReviewGuideService from "../pullRequest/PullRequestReviewGuideService.ts";
40import * as ServerConfig from "../config.ts";
41import * as ServerSettings from "../serverSettings.ts";
42import { advertisedJsonSchema } from "./advertisedJsonSchema.ts";
43import * as McpHttpServer from "./McpHttpServer.ts";
44import * as McpToolAccess from "./McpToolAccess.ts";
45import * as McpToolAccessTestkit from "./McpToolAccess.testkit.ts";
46import * as McpInvocationContext from "./McpInvocationContext.ts";
47import * as McpSessionRegistry from "./McpSessionRegistry.ts";
48import * as OrchestratorMcpService from "./OrchestratorMcpService.ts";
49import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
50import { OrchestratorToolkit } from "./toolkits/orchestrator/tools.ts";
51import { PreviewToolkit } from "./toolkits/preview/tools.ts";
52import { ProjectToolkit } from "./toolkits/project/tools.ts";
53
54const environmentId = EnvironmentId.make("environment-mcp-test");
55const threadId = ThreadId.make("thread-mcp-test");
56const alternateTabId = PreviewTabId.make("tab-mcp-alternate");
57const decodeJsonText = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
58const invocation = {
59 environmentId,
60 requestNamespace: "provider-session-mcp-test",
61 thread: {
62 threadId,
63 providerSessionId: "provider-session-mcp-test",
64 providerInstanceId: ProviderInstanceId.make("codex"),
65 },
66 client: undefined,
67 capabilities: new Set(["preview"] as const),
68 issuedAt: 1,
69};
70const client = McpSchema.McpServerClient.of({
71 clientId: 1,
72 clientCapabilities: {},
73 clientInfo: { name: "mcp-test", version: "1.0.0" },
74 protocolVersion: "2025-06-18",
75 initializePayload: {
76 protocolVersion: "2025-06-18",
77 capabilities: {},
78 clientInfo: { name: "mcp-test", version: "1.0.0" },
79 },
80 getClient: Effect.die("unused"),
81});
82const layerTest = McpHttpServer.layerPreviewToolkit.pipe(
83 Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
84 Layer.provideMerge(McpToolAccessTestkit.liveThreadsLayer),
85 Layer.provideMerge(PreviewAutomationBroker.layer),
86 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-http-server-test-" })),
87 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
88);
89const layerPullRequestsTest = McpHttpServer.layerPullRequestsToolkit.pipe(
90 Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
91 Layer.provideMerge(McpToolAccessTestkit.liveThreadsLayer),
92 Layer.provide(
93 Layer.mergeAll(
94 Layer.mock(ProjectService.ProjectService)({}),
95 Layer.mock(PullRequestReviewGuideService.PullRequestReviewGuideService)({}),
96 Layer.mock(Orchestrator.OrchestratorV2)({}),
97 Layer.mock(ProjectionStore.ProjectionStoreV2)({}),
98 NodeServices.layer,
99 NodeCrypto.layer,
100 ),
101 ),
102);
103
104const snapshotResult = {
105 url: "http://example.test/",
106 title: "Example",
107 loading: false,
108 visibleText: "Example",
109 interactiveElements: [],
110 accessibilityTree: {},
111 consoleEntries: [],
112 networkEntries: [],
113 actionTimeline: [],
114 screenshot: {
115 mimeType: "image/png",
116 data: Buffer.from("png").toString("base64"),
117 width: 10,
118 height: 5,
119 },
120};
121
122const serveSnapshots = (clientId: string, result: unknown) =>
123 Effect.gen(function* () {
124 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
125 const connected = yield* Deferred.make<void>();
126 const inputs: Array<unknown> = [];
127 const events = yield* broker.connect({ clientId, environmentId });
128 yield* Stream.runForEach(events, (event) => {
129 if (event.type === "connected") return Deferred.succeed(connected, undefined);
130 inputs.push(event.request.input);
131 return broker.respond({
132 clientId,
133 connectionId: event.connectionId,
134 requestId: event.request.requestId,
135 ok: true,
136 result,
137 });
138 }).pipe(Effect.forkScoped);
139 yield* Deferred.await(connected);
140 return inputs;
141 });
142
143const callTool = (name: string, args: Record<string, unknown>) =>
144 Effect.gen(function* () {
145 const server = yield* McpServer.McpServer;
146 return yield* server
147 .callTool({ name, arguments: args })
148 .pipe(
149 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
150 Effect.provideService(McpSchema.McpServerClient, client),
151 );
152 });
153
154const callSnapshot = (args: Record<string, unknown>) => callTool("preview_snapshot", args);
155
156it.effect.each([
157 { input: {}, open: false, message: "No device is open in this thread. Call device_open first." },
158 {
159 input: { deviceId: "missing" },
160 open: false,
161 message: "Device missing is not open in this thread. Call device_open first.",
162 },
163 {
164 input: {},
165 open: true,
166 message:
167 "Device screenshot failed: Could not communicate with device support. Try refreshing devices.",
168 },
169 {
170 input: {},
171 open: true,
172 rejected: true,
173 message:
174 "Device screenshot failed: The device hub could not complete the request. Call device_list to check the device state, and device_open if it needs to be reopened.",
175 },
176])(
177 "preserves actionable screenshot failure text: $message",
178 ({ input, open, message, ...options }) =>
179 Effect.gen(function* () {
180 const server = yield* McpServer.McpServer;
181 const result = yield* server.callTool({ name: "device_screenshot", arguments: input }).pipe(
182 Effect.provideService(McpInvocationContext.McpInvocationContext, {
183 ...invocation,
184 capabilities: new Set(["device"] as const),
185 }),
186 Effect.provideService(McpSchema.McpServerClient, client),
187 );
188 expect(result.isError).toBe(true);
189 expect(result.content).toEqual([{ type: "text", text: message }]);
190 expect(result.structuredContent).toMatchObject({
191 error: { message, operation: "screenshot" },
192 });
193 expect(JSON.stringify(result)).not.toContain("private hub output");
194 }).pipe(
195 Effect.provide(
196 McpHttpServer.layerDeviceToolkit.pipe(
197 Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
198 Layer.provide(McpToolAccessTestkit.liveThreadsLayer),
199 Layer.provide(
200 Layer.mock(DeviceService.DeviceService)({
201 locateSession: () => Effect.succeedNone,
202 sessionsForThread: () =>
203 Effect.succeed(
204 open
205 ? [
206 {
207 threadId,
208 hostId: "local",
209 deviceId: DeviceId.make("phone"),
210 platform: "ios",
211 openedAt: "2026-10-23T00:00:00Z",
212 },
213 ]
214 : [],
215 ),
216 screenshot: () =>
217 Effect.fail(
218 new DeviceOperationError({
219 operation: "screenshot",
220 reason:
221 "rejected" in options && options.rejected ? "hub_rejected" : "request_failed",
222 cause: new Error("private hub output"),
223 }),
224 ),
225 }),
226 ),
227 Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
228 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-device-mcp-test-" })),
229 Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
230 ),
231 ),
232 Effect.scoped,
233 ),
234);
235
236const layerRecordingTools = (calls: Array<unknown>) => {
237 const RecordingToolkit = Toolkit.make(
238 OrchestratorToolkit.tools.delegate_task,
239 OrchestratorToolkit.tools.t3_thread_read,
240 OrchestratorToolkit.tools.t3_thread_wait,
241 ProjectToolkit.tools.t3_project_update,
242 );
243 const record = McpToolAccess.reads((params: unknown) =>
244 Effect.sync(() => calls.push(params)).pipe(
245 Effect.andThen(
246 Effect.fail(new OrchestratorMcpFailure({ code: "thread_not_found", message: "Recorded." })),
247 ),
248 ),
249 );
250 return McpHttpServer.toolkitRegistration(
251 RecordingToolkit,
252 McpToolAccess.toLayer(RecordingToolkit, {
253 delegate_task: record,
254 t3_thread_read: record,
255 t3_thread_wait: record,
256 t3_project_update: record,
257 }),
258 ).pipe(
259 Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
260 Layer.provide(
261 Layer.mergeAll(
262 McpToolAccessTestkit.liveThreadsLayer,
263 Layer.mock(OrchestratorMcpService.OrchestratorMcpService)({}),
264 Layer.mock(ProjectService.ProjectService)({}),
265 NodeServices.layer,
266 NodeCrypto.layer,
267 ),
268 ),
269 );
270};
271
272it.effect.each([{}, { includeImage: false }])(
273 "returns bounded structural preview snapshot failures %#",
274 (input) =>
275 Effect.scoped(
276 Effect.gen(function* () {
277 const server = yield* McpServer.McpServer;
278 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
279 const events = yield* broker.connect({
280 clientId: "mcp-failure-client",
281 environmentId,
282 });
283 yield* Stream.runForEach(events, (event) =>
284 event.type === "connected"
285 ? Effect.void
286 : broker.respond({
287 clientId: "mcp-failure-client",
288 connectionId: event.connectionId,
289 requestId: event.request.requestId,
290 ok: false,
291 error: {
292 _tag: "PreviewAutomationExecutionError",
293 message: "sensitive renderer failure",
294 detail: { consoleOutput: "sensitive browser output" },
295 },
296 }),
297 ).pipe(Effect.forkScoped);
298 yield* Effect.yieldNow;
299
300 const snapshot = yield* server
301 .callTool({ name: "preview_snapshot", arguments: input })
302 .pipe(
303 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
304 Effect.provideService(McpSchema.McpServerClient, client),
305 );
306
307 const message = "Preview automation snapshot failed on client mcp-failure-client.";
308 expect(snapshot.isError).toBe(true);
309 expect(snapshot.content).toEqual([
310 { type: "text", text: `Preview snapshot failed: ${message}` },
311 ]);
312 expect(snapshot.structuredContent).toEqual({
313 error: {
314 _tag: "PreviewAutomationExecutionError",
315 operation: "snapshot",
316 failureCount: 1,
317 message,
318 },
319 });
320 }),
321 ).pipe(Effect.provide(layerTest)),
322);
323
324it.effect.each([
325 { mode: "default", input: {}, images: false },
326 { mode: "explicit image", input: { includeImage: true }, images: true },
327 { mode: "text only", input: { includeImage: false }, images: false },
328])("returns fresh $mode snapshots on repeated MCP calls", ({ input, images }) =>
329 Effect.scoped(
330 Effect.gen(function* () {
331 const server = yield* McpServer.McpServer;
332 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
333 const connected = yield* Deferred.make<void>();
334 const png =
335 "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII=";
336 const page = {
337 url: "http://example.test/",
338 loading: false,
339 visibleText: "Save your changes",
340 interactiveElements: [
341 {
342 tag: "button",
343 role: "button",
344 name: "Save",
345 selector: "#save",
346 x: 0,
347 y: 0,
348 width: 20,
349 height: 10,
350 },
351 ],
352 accessibilityTree: { role: "document", name: "Example" },
353 consoleEntries: [],
354 networkEntries: [],
355 actionTimeline: [],
356 };
357 const screenshot = { mimeType: "image/png", width: 1, height: 1 };
358 let requests = 0;
359 const events = yield* broker.connect({ clientId: "mcp-image-option-client", environmentId });
360 yield* Stream.runForEach(events, (event) => {
361 if (event.type === "connected") return Deferred.succeed(connected, undefined);
362 requests += 1;
363 expect(event.request).toMatchObject({
364 operation: "snapshot",
365 tabId: alternateTabId,
366 threadId,
367 });
368 expect(event.request.input).toEqual({});
369 return broker.respond({
370 clientId: "mcp-image-option-client",
371 connectionId: event.connectionId,
372 requestId: event.request.requestId,
373 ok: true,
374 result: {
375 ...page,
376 title: `Snapshot ${requests}`,
377 screenshot: { ...screenshot, data: png },
378 },
379 });
380 }).pipe(Effect.forkScoped);
381 yield* Deferred.await(connected);
382
383 for (const call of [1, 2, 3, 4, 5, 6]) {
384 const snapshot = yield* server
385 .callTool({
386 name: "preview_snapshot",
387 arguments: { ...input, tabId: alternateTabId },
388 })
389 .pipe(
390 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
391 Effect.provideService(McpSchema.McpServerClient, client),
392 );
393 const metadata = { ...page, title: `Snapshot ${call}`, screenshot };
394 const { accessibilityTree: _tree, ...boundedMetadata } = metadata;
395 expect(snapshot.isError).toBe(false);
396 expect(snapshot.structuredContent).toEqual({
397 ...boundedMetadata,
398 omitted: ["accessibilityTree (use interactiveElements locators or preview_evaluate)"],
399 });
400 const [identity, text, ...rest] = snapshot.content;
401 expect(identity?.type === "text" ? decodeJsonText(identity.text) : null).toEqual({
402 url: page.url,
403 });
404 expect(text?.type === "text" ? decodeJsonText(text.text) : null).toEqual(boundedMetadata);
405 expect(rest).toEqual([
406 {
407 type: "text",
408 text: "Snapshot text was bounded. Omitted: accessibilityTree (use interactiveElements locators or preview_evaluate).",
409 },
410 ...(images
411 ? [
412 {
413 type: "image",
414 mimeType: "image/png",
415 data: new Uint8Array(Buffer.from(png, "base64")),
416 },
417 ]
418 : []),
419 ]);
420 }
421
422 const nextDefault = yield* server
423 .callTool({
424 name: "preview_snapshot",
425 arguments: { tabId: alternateTabId },
426 })
427 .pipe(
428 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
429 Effect.provideService(McpSchema.McpServerClient, client),
430 );
431 expect(nextDefault.content.map((content) => content.type)).toEqual(["text", "text", "text"]);
432 expect(nextDefault.structuredContent).toMatchObject({ title: "Snapshot 7", screenshot });
433 expect(nextDefault.structuredContent).not.toHaveProperty("accessibilityTree");
434 expect(requests).toBe(7);
435 }),
436 ).pipe(Effect.provide(layerTest)),
437);
438
439it.effect("refuses preview tools to a client outside a thread before they run", () =>
440 Effect.gen(function* () {
441 const server = yield* McpServer.McpServer;
442 const readOnly = {
443 ...invocation,
444 thread: undefined,
445 requestNamespace: "client:session-1",
446 client: { sessionId: "session-1", label: "Claude Code", access: "read-only" as const },
447 };
448 const click = yield* server
449 .callTool({ name: "preview_act", arguments: { action: "click", locator: "text=Send" } })
450 .pipe(
451 Effect.provideService(McpInvocationContext.McpInvocationContext, readOnly),
452 Effect.provideService(McpSchema.McpServerClient, client),
453 );
454 expect(click.isError).toBe(true);
455 expect(click.content).toEqual([
456 { type: "text", text: expect.stringContaining("needs an agent running inside T3 Code") },
457 ]);
458 }).pipe(Effect.provide(layerTest)),
459);
460
461it.effect("advertises the compact input schema for every registered tool", () =>
462 Effect.gen(function* () {
463 const server = yield* McpServer.McpServer;
464 const tools: Record<string, Tool.Any> = PreviewToolkit.tools;
465
466 expect(server.tools.length).toBe(Object.keys(tools).length);
467 for (const { tool } of server.tools) {
468 expect(tool.inputSchema, tool.name).toEqual(advertisedJsonSchema(tools[tool.name]!));
469 }
470 }).pipe(Effect.provide(layerTest)),
471);
472
473it.effect("checks each preview_act action against that action's own input", () =>
474 Effect.scoped(
475 Effect.gen(function* () {
476 const inputs = yield* serveSnapshots("mcp-act-client", {});
477
478 const missingKey = yield* callTool("preview_act", { action: "press" });
479 expect(missingKey.isError).toBe(true);
480 expect(inputs).toEqual([]);
481
482 const click = yield* callTool("preview_act", {
483 action: "click",
484 locator: "text=Send",
485 key: "Enter",
486 });
487 expect(click.isError).toBe(false);
488 expect(inputs[0]).toEqual({ locator: "text=Send" });
489
490 yield* callTool("preview_act", { action: "type", selector: "#name", text: "Ada" });
491 expect(inputs.at(-2)).toEqual({ selector: "#name", text: "Ada" });
492 }),
493 ).pipe(Effect.provide(layerTest)),
494);
495
496it.effect("decodes null optional arguments the way it decodes omitted ones", () => {
497 const calls: Array<unknown> = [];
498 return Effect.gen(function* () {
499 const thread = { threadId: "thread-null-arguments" };
500 yield* callTool("t3_thread_read", thread);
501 yield* callTool("t3_thread_read", { ...thread, afterPosition: null, view: null });
502 yield* callTool("delegate_task", { task: "Inspect", target: {} });
503 yield* callTool("delegate_task", { task: "Inspect", title: null, target: { model: null } });
504 yield* callTool("t3_project_update", { projectId: "project-1", projectIcon: null });
505
506 expect(calls).toHaveLength(5);
507 expect(calls[1]).toEqual(calls[0]);
508 expect(calls[3]).toEqual(calls[2]);
509 expect(calls[4]).toStrictEqual({ projectId: "project-1", projectIcon: null });
510 }).pipe(Effect.provide(layerRecordingTools(calls)));
511});
512
513it.effect(
514 "clamps t3_thread_read page sizes above their maximum instead of rejecting the call",
515 () => {
516 const calls: Array<unknown> = [];
517 return Effect.gen(function* () {
518 const thread = { threadId: "thread-clamped-arguments" };
519 // Codex never shows the model these bounds, so an over-large page must still read.
520 yield* callTool("t3_thread_read", {
521 ...thread,
522 limit: 150,
523 runLimit: 80,
524 maxCharsPerItem: 60_000,
525 });
526 yield* callTool("t3_thread_read", {
527 ...thread,
528 limit: 100,
529 runLimit: 50,
530 maxCharsPerItem: 50_000,
531 });
532 yield* callTool("t3_thread_read", { ...thread, limit: 7, runLimit: 1, maxCharsPerItem: 1 });
533
534 expect(calls).toEqual([
535 { ...thread, limit: 100, runLimit: 50, maxCharsPerItem: 50_000 },
536 { ...thread, limit: 100, runLimit: 50, maxCharsPerItem: 50_000 },
537 { ...thread, limit: 7, runLimit: 1, maxCharsPerItem: 1 },
538 ]);
539 }).pipe(Effect.provide(layerRecordingTools(calls)));
540 },
541);
542
543it.effect.each(["limit", "runLimit", "maxCharsPerItem"])(
544 "still rejects a t3_thread_read %s below its minimum",
545 (field) => {
546 const calls: Array<unknown> = [];
547 return Effect.gen(function* () {
548 // Zero is a different request than one item, so it fails rather than answering another question.
549 const rejected = yield* callTool("t3_thread_read", {
550 threadId: "thread-below-minimum",
551 [field]: 0,
552 }).pipe(Effect.flip);
553
554 expect(String(rejected)).toContain("greater than or equal to 1");
555 expect(calls).toEqual([]);
556 }).pipe(Effect.provide(layerRecordingTools(calls)));
557 },
558);
559
560it("keeps cross-tool routing out of the delegate_task description", () => {
561 const description = OrchestratorToolkit.tools.delegate_task.description ?? "";
562 expect(description).toContain("Start one child agent with only `task`");
563 // Review rounds, follow-ups, and polling are routed in the system text.
564 expect(description).not.toContain("t3_thread_send");
565 expect(description).not.toContain("Do not poll");
566 expect(description).not.toContain("Prefer native");
567});
568
569it.effect(
570 "registers the pull request toolkit and surfaces a missing capability as a tool error",
571 () =>
572 Effect.gen(function* () {
573 const server = yield* McpServer.McpServer;
574 const names = server.tools.map(({ tool }) => tool.name);
575 expect(names).toEqual(
576 expect.arrayContaining([
577 "link_pull_request",
578 "unlink_pull_request",
579 "list_thread_pull_requests",
580 ]),
581 );
582 const linkTool = server.tools.find(({ tool }) => tool.name === "link_pull_request");
583 expect(linkTool?.tool.annotations?.idempotentHint).toBe(true);
584 expect(linkTool?.tool.annotations?.openWorldHint).toBe(false);
585 expect(linkTool?.tool.description).toContain("Link a PR to this thread");
586 expect(linkTool?.tool.description).toContain("settles the thread on merge");
587
588 const denied = yield* server
589 .callTool({ name: "list_thread_pull_requests", arguments: {} })
590 .pipe(
591 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
592 Effect.provideService(McpSchema.McpServerClient, client),
593 );
594 expect(denied.isError).toBe(true);
595 expect(denied.content).toEqual([
596 { type: "text", text: "MCP credential does not grant the pull-requests capability." },
597 ]);
598 }).pipe(Effect.provide(layerPullRequestsTest)),
599);
600
601it.effect("bounds large ARIA trees without dropping every server locator", () =>
602 Effect.scoped(
603 Effect.gen(function* () {
604 const accessibilityTree = Array.from(
605 { length: 2_000 },
606 (_, index) => `- button "删除 ${index}" [ref=t3-snapshot-e${index}]`,
607 ).join("\n");
608 yield* serveSnapshots("mcp-large-server-refs", { ...snapshotResult, accessibilityTree });
609 const result = yield* callSnapshot({ includeImage: false });
610 expect(result.isError).toBe(false);
611 const metadata = result.structuredContent as { accessibilityTree: string };
612 expect(metadata.accessibilityTree).toContain("[ref=t3-snapshot-e0]");
613 expect(metadata.accessibilityTree.length).toBeLessThan(accessibilityTree.length);
614 const body = result.content[1];
615 expect(Buffer.byteLength(body?.type === "text" ? body.text : "", "utf8")).toBeLessThanOrEqual(
616 McpHttpServer.MAX_SNAPSHOT_TEXT_BYTES,
617 );
618 }),
619 ).pipe(Effect.provide(layerTest)),
620);
621
622it.effect("keeps the snapshot text under the agent's output ceiling", () =>
623 Effect.scoped(
624 Effect.gen(function* () {
625 const pageText = "/Users/theo/Code/project\nClaude, Codex · 79 threads\n".repeat(600);
626 const element = (name: string, index: number) => ({
627 tag: "div",
628 role: "presentation",
629 name,
630 selector: `div:nth-of-type(${index})`,
631 x: 0,
632 y: 0,
633 width: 10,
634 height: 10,
635 });
636 const oversized = {
637 ...snapshotResult,
638 visibleText: pageText,
639 interactiveElements: [
640 element(pageText, 1),
641 element(pageText, 2),
642 element(pageText, 3),
643 element("Continue", 4),
644 ],
645 accessibilityTree: { nodes: Array.from({ length: 2_000 }, (_, i) => ({ nodeId: `${i}` })) },
646 consoleEntries: Array.from({ length: 100 }, (_, i) => ({
647 level: "log",
648 text: `entry ${i}`,
649 timestamp: "t",
650 })),
651 };
652 yield* serveSnapshots("mcp-bounded-client", oversized);
653
654 const snapshot = yield* callSnapshot({ includeImage: false });
655
656 expect(snapshot.isError).toBe(false);
657 const [identity, text, notice] = snapshot.content;
658 expect(identity?.type === "text" ? decodeJsonText(identity.text) : null).toEqual({
659 url: oversized.url,
660 });
661 expect(text?.type).toBe("text");
662 const body = text?.type === "text" ? text.text : "";
663 expect(Buffer.byteLength(body, "utf8")).toBeLessThanOrEqual(
664 McpHttpServer.MAX_SNAPSHOT_TEXT_BYTES,
665 );
666 const parsed = decodeJsonText(body) as {
667 readonly accessibilityTree?: unknown;
668 readonly visibleText: string;
669 readonly interactiveElements: ReadonlyArray<{ readonly name: string }>;
670 readonly consoleEntries: ReadonlyArray<{ readonly text: string }>;
671 };
672 expect(parsed.accessibilityTree).toBeUndefined();
673 expect(parsed.visibleText.length).toBeLessThanOrEqual(8_001);
674 expect(parsed.interactiveElements).toHaveLength(4);
675 expect(parsed.interactiveElements[0]?.name.length).toBeLessThanOrEqual(201);
676 expect(parsed.interactiveElements[3]?.name).toBe("Continue");
677 expect(parsed.consoleEntries).toHaveLength(40);
678 expect(parsed.consoleEntries[0]?.text).toBe("entry 60");
679 expect(notice?.type === "text" ? notice.text : "").toContain("accessibilityTree");
680 expect(notice?.type === "text" ? notice.text : "").toContain("60 older console entries");
681 expect(snapshot.structuredContent).toEqual({
682 ...parsed,
683 omitted: expect.arrayContaining(["60 older console entries"]),
684 });
685 }),
686 ).pipe(Effect.provide(layerTest)),
687);
688
689// regression: #10501 keep preview snapshots usable by the agent
690it.effect("bounds the snapshot text even when nothing but logs and the title are large", () =>
691 Effect.scoped(
692 Effect.gen(function* () {
693 const oversized = {
694 ...snapshotResult,
695 title: `t${"😀".repeat(35_000)}`,
696 interactiveElements: [],
697 consoleEntries: [{ level: "log", text: `x${"😀".repeat(35_000)}`, timestamp: "t" }],
698 };
699 yield* serveSnapshots("mcp-bounded-logs-client", oversized);
700
701 const snapshot = yield* callSnapshot({ includeImage: false });
702
703 const [, text] = snapshot.content;
704 const body = text?.type === "text" ? text.text : "";
705 expect(Buffer.byteLength(body, "utf8")).toBeLessThanOrEqual(
706 McpHttpServer.MAX_SNAPSHOT_TEXT_BYTES,
707 );
708 const parsed = decodeJsonText(body) as {
709 readonly title: string;
710 readonly consoleEntries: ReadonlyArray<{ readonly text: string }>;
711 };
712 expect(parsed.title.isWellFormed()).toBe(true);
713 expect(parsed.title.length).toBe(2_048);
714 expect(parsed.consoleEntries[0]?.text.isWellFormed()).toBe(true);
715 expect(parsed.consoleEntries[0]?.text.length).toBe(500);
716 const notice = snapshot.content[2];
717 const noticeText = notice?.type === "text" ? notice.text : "";
718 expect(noticeText).toContain("url or title after 2048 characters");
719 expect(noticeText).toContain("console entries text after 500 characters");
720 }),
721 ).pipe(Effect.provide(layerTest)),
722);
723
724// regression: #13558 preview snapshots overflowed the agent's tool output
725it.effect("bounds page text made of wide characters before dropping locators", () =>
726 Effect.scoped(
727 Effect.gen(function* () {
728 yield* serveSnapshots("mcp-wide-text-client", {
729 ...snapshotResult,
730 visibleText: "界".repeat(9_000),
731 interactiveElements: Array.from({ length: 20 }, (_, i) => ({
732 tag: "button",
733 role: "button",
734 name: `Button ${i}`,
735 selector: `#button-${i}`,
736 x: 0,
737 y: 0,
738 width: 10,
739 height: 10,
740 })),
741 });
742
743 const snapshot = yield* callSnapshot({ includeImage: false });
744
745 const [, text, notice] = snapshot.content;
746 const body = text?.type === "text" ? text.text : "";
747 expect(Buffer.byteLength(body, "utf8")).toBeLessThanOrEqual(
748 McpHttpServer.MAX_SNAPSHOT_TEXT_BYTES,
749 );
750 const parsed = decodeJsonText(body) as {
751 readonly visibleText: string;
752 readonly interactiveElements: ReadonlyArray<unknown>;
753 };
754 expect(parsed.visibleText).toMatch(/^界+…$/);
755 expect(parsed.interactiveElements).toHaveLength(20);
756 expect(notice?.type === "text" ? notice.text : "").toContain(
757 "visibleText after 4000 characters",
758 );
759 }),
760 ).pipe(Effect.provide(layerTest)),
761);
762
763it.effect("terminates HTTP MCP sessions with DELETE", () =>
764 Effect.scoped(
765 Effect.gen(function* () {
766 const token = "providerTokenWithoutDots";
767 const scope: McpInvocationContext.McpInvocationScope = {
768 environmentId,
769 requestNamespace: "provider-session",
770 thread: {
771 threadId: ThreadId.make("thread-provider"),
772 providerSessionId: "provider-session",
773 providerInstanceId: ProviderInstanceId.make("codex"),
774 },
775 client: undefined,
776 capabilities: new Set(["orchestration"]),
777 issuedAt: 1,
778 };
779 const layerServer = McpHttpServer.layerMcpTransport(Layer.empty).pipe(
780 Layer.provide(ServerSettings.layerTest()),
781 Layer.provide(
782 Layer.mock(McpSessionRegistry.McpSessionRegistry)({
783 resolve: (presented) =>
784 Effect.succeed(
785 presented === token
786 ? (scope as McpInvocationContext.McpThreadInvocationScope)
787 : undefined,
788 ),
789 }),
790 ),
791 );
792 yield* HttpRouter.serve(layerServer, {
793 disableListenLog: true,
794 disableLogger: true,
795 }).pipe(Layer.build);
796 const httpClient = (yield* HttpClient.HttpClient).pipe(
797 HttpClient.mapRequest(HttpClientRequest.bearerToken(token)),
798 );
799
800 const initializeResponse = yield* httpClient.post("/mcp", {
801 headers: { accept: "application/json, text/event-stream" },
802 body: HttpBody.text(
803 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"mcp-test","version":"1.0.0"}}}`,
804 "application/json",
805 ),
806 });
807 const sessionId = initializeResponse.headers["mcp-session-id"];
808 expect(initializeResponse.status).toBe(200);
809 expect(sessionId).not.toBeNull();
810
811 const missingSessionResponse = yield* httpClient.del("/mcp");
812 expect(missingSessionResponse.status).toBe(400);
813
814 const unknownSessionResponse = yield* httpClient.del("/mcp", {
815 headers: { "mcp-session-id": "unknown-session" },
816 });
817 expect(unknownSessionResponse.status).toBe(404);
818
819 const terminateResponse = yield* httpClient.del("/mcp", {
820 headers: { "mcp-session-id": sessionId! },
821 });
822 expect(terminateResponse.status).toBe(204);
823
824 const reusedSessionResponse = yield* httpClient.post("/mcp", {
825 headers: {
826 accept: "application/json, text/event-stream",
827 "mcp-session-id": sessionId!,
828 },
829 body: HttpBody.text(
830 `{"jsonrpc":"2.0","id":2,"method":"ping","params":{}}`,
831 "application/json",
832 ),
833 });
834 expect(reusedSessionResponse.status).toBe(404);
835 }),
836 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
837);
838
839it.effect("admits provider and OAuth client credentials and points only clients at OAuth", () =>
840 Effect.scoped(
841 Effect.gen(function* () {
842 const providerToken = "providerTokenWithoutDots";
843 const clientToken = "client-payload.client-signature";
844 const providerScope: McpInvocationContext.McpInvocationScope = {
845 environmentId,
846 requestNamespace: "provider-session",
847 thread: {
848 threadId: ThreadId.make("thread-provider"),
849 providerSessionId: "provider-session",
850 providerInstanceId: ProviderInstanceId.make("codex"),
851 },
852 client: undefined,
853 capabilities: new Set(["orchestration"]),
854 issuedAt: 1,
855 };
856 const clientScope: McpInvocationContext.McpInvocationScope = {
857 environmentId,
858 requestNamespace: "client:session-1",
859 thread: undefined,
860 client: { sessionId: "session-1", label: "Claude Code", access: "auto" },
861 capabilities: new Set(["orchestration"]),
862 issuedAt: 1,
863 };
864 const seen: Array<McpInvocationContext.McpInvocationScope> = [];
865 const ProbeToolkit = Toolkit.make(
866 Tool.make("probe", {
867 description: "Reports the caller.",
868 success: Schema.Struct({ ok: Schema.Boolean }),
869 failure: OrchestratorMcpFailure,
870 failureMode: "return",
871 dependencies: [McpInvocationContext.McpInvocationContext],
872 }),
873 );
874 const serverLayer = McpHttpServer.layerMcpTransport(
875 McpHttpServer.toolkitRegistration(
876 ProbeToolkit,
877 McpToolAccess.toLayer(ProbeToolkit, {
878 probe: McpToolAccess.reads(() =>
879 McpInvocationContext.McpInvocationContext.pipe(
880 Effect.tap((scope) => Effect.sync(() => seen.push(scope))),
881 Effect.as({ ok: true }),
882 ),
883 ),
884 }),
885 ),
886 ).pipe(
887 Layer.provide(ServerSettings.layerTest()),
888 Layer.provide(
889 Layer.mock(McpSessionRegistry.McpSessionRegistry)({
890 resolve: (token) =>
891 Effect.succeed(
892 token === providerToken
893 ? (providerScope as McpInvocationContext.McpThreadInvocationScope)
894 : undefined,
895 ),
896 }),
897 ),
898 Layer.provide(
899 Layer.succeed(McpHttpServer.McpClientAuthenticator, {
900 authenticate: (request) =>
901 Effect.succeed(
902 request.headers.authorization === `Bearer ${clientToken}` ? clientScope : undefined,
903 ),
904 }),
905 ),
906 );
907 yield* HttpRouter.serve(serverLayer, { disableListenLog: true, disableLogger: true }).pipe(
908 Layer.build,
909 );
910 const httpClient = yield* HttpClient.HttpClient;
911 const call = (token: string | undefined) =>
912 Effect.gen(function* () {
913 const headers = {
914 accept: "application/json, text/event-stream",
915 ...(token === undefined ? {} : { authorization: `Bearer ${token}` }),
916 };
917 const initialize = yield* httpClient.post("/mcp", {
918 headers,
919 body: HttpBody.text(
920 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`,
921 "application/json",
922 ),
923 });
924 if (initialize.status !== 200) return initialize;
925 return yield* httpClient.post("/mcp", {
926 headers: {
927 ...headers,
928 "mcp-session-id": initialize.headers["mcp-session-id"]!,
929 "mcp-protocol-version": "2025-06-18",
930 },
931 body: HttpBody.text(
932 `{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"probe","arguments":{}}}`,
933 "application/json",
934 ),
935 });
936 });
937
938 expect((yield* call(providerToken)).status).toBe(200);
939 expect((yield* call(clientToken)).status).toBe(200);
940 expect(seen.map((scope) => scope.requestNamespace)).toEqual([
941 "provider-session",
942 "client:session-1",
943 ]);
944
945 const missing = yield* call(undefined);
946 expect(missing.status).toBe(401);
947 expect(missing.headers["www-authenticate"]).toMatch(
948 /^Bearer resource_metadata="http:\/\/[^"]+\/\.well-known\/oauth-protected-resource\/mcp"$/,
949 );
950
951 const expiredClient = yield* call("stale-payload.stale-signature");
952 expect(expiredClient.headers["www-authenticate"]).toContain("resource_metadata=");
953 expect(expiredClient.headers["www-authenticate"]).toContain('error="invalid_token"');
954
955 const deadProvider = yield* call("deadProviderToken");
956 expect(deadProvider.status).toBe(401);
957 expect(deadProvider.headers["www-authenticate"]).toBe('Bearer error="invalid_token"');
958 }),
959 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
960);
961
962it.effect("accepts case-insensitive MCP bearer schemes and diagnoses rejected credentials", () => {
963 const messages: Array<unknown> = [];
964 const logger = Logger.make(({ message }) => messages.push(message));
965 const layerAuth = Layer.mergeAll(EnvironmentAuth.layer, McpSessionRegistry.layer).pipe(
966 Layer.provideMerge(
967 Layer.mock(ServerEnvironment.ServerEnvironment)({
968 getEnvironmentId: Effect.succeed(environmentId),
969 }),
970 ),
971 Layer.provideMerge(Sqlite.layerMemory),
972 Layer.provide(ServerSecretStore.layer),
973 Layer.provide(ManagedPolicy.layerTest()),
974 Layer.provideMerge(ServerEnvironment.layerIdentity),
975 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-auth-header-test-" })),
976 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
977 );
978 return Effect.scoped(
979 Effect.gen(function* () {
980 const auth = yield* EnvironmentAuth.EnvironmentAuth;
981 const registry = yield* McpSessionRegistry.McpSessionRegistry;
982 const issued = yield* registry.issue({
983 threadId,
984 providerInstanceId: ProviderInstanceId.make("codex"),
985 });
986 const providerToken = issued.config.authorizationHeader.slice("Bearer ".length);
987 const oauth = yield* auth.issueMcpClientSession({
988 label: "MCP header test",
989 access: "read-only",
990 peerLink: false,
991 client: { deviceType: "bot" },
992 });
993 yield* HttpRouter.serve(
994 McpHttpServer.layerMcpTransport(Layer.empty).pipe(
995 Layer.provide(McpOAuth.layerMcpClientAuthenticator),
996 Layer.provide(ServerSettings.layerTest()),
997 ),
998 { disableListenLog: true, disableLogger: true },
999 ).pipe(Layer.build);
1000 const httpClient = yield* HttpClient.HttpClient;
1001 const initialize = (authorization?: string) =>
1002 httpClient.post("/mcp", {
1003 headers: {
1004 accept: "application/json, text/event-stream",
1005 ...(authorization === undefined ? {} : { authorization }),
1006 },
1007 body: HttpBody.text(
1008 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"mcp-header-test","version":"1.0.0"}}}`,
1009 "application/json",
1010 ),
1011 });
1012
1013 for (const scheme of ["Bearer", "bearer", "bEaReR"]) {
1014 for (const [kind, token] of [
1015 ["provider", providerToken],
1016 ["OAuth", oauth.token],
1017 ]) {
1018 const response = yield* initialize(`${scheme} ${token}`);
1019 expect.soft(response.status, `${kind} ${scheme}`).toBe(200);
1020 }
1021 }
1022 messages.length = 0;
1023 for (const [authorization, reason] of [
1024 [undefined, "missing_authorization_header"],
1025 [`Basic ${providerToken}`, "unsupported_scheme"],
1026 ["Bearer", "missing_bearer_token"],
1027 ["bEaReR ", "missing_bearer_token"],
1028 [`bearer ${providerToken.toUpperCase()}`, "unknown_or_expired_token"],
1029 [`bEaReR ${oauth.token.toUpperCase()}`, "unknown_or_expired_token"],
1030 ] as const) {
1031 const response = yield* initialize(authorization);
1032 expect(response.status).toBe(401);
1033 expect
1034 .soft(messages.at(-1))
1035 .toEqual(["rejected MCP request with an unusable credential", { reason }]);
1036 const body = yield* response.text;
1037 expect(body).not.toContain(providerToken);
1038 expect(body).not.toContain(oauth.token);
1039 expect(JSON.stringify(response.headers)).not.toContain(providerToken);
1040 expect(JSON.stringify(response.headers)).not.toContain(oauth.token);
1041 }
1042 yield* registry.revokeThread(threadId);
1043 yield* auth.revokeSession(oauth.sessionId);
1044 for (const token of [providerToken, oauth.token]) {
1045 expect((yield* initialize(`bearer ${token}`)).status).toBe(401);
1046 }
1047 expect(JSON.stringify(messages)).not.toContain(providerToken);
1048 expect(JSON.stringify(messages)).not.toContain(oauth.token);
1049 expect(JSON.stringify(messages)).not.toContain(providerToken.toUpperCase());
1050 expect(JSON.stringify(messages)).not.toContain(oauth.token.toUpperCase());
1051 }),
1052 ).pipe(
1053 Effect.provide(
1054 layerAuth.pipe(
1055 Layer.provideMerge(NodeHttpServer.layerTest),
1056 Layer.provideMerge(Logger.layer([logger], { mergeWithExisting: false })),
1057 ),
1058 ),
1059 );
1060});
1061
1062it.effect("hides tools for links and refuses another environment while the beta is off", () =>
1063 Effect.scoped(
1064 Effect.gen(function* () {
1065 const token = "linksToken";
1066 const scope: McpInvocationContext.McpThreadInvocationScope = {
1067 environmentId,
1068 requestNamespace: token,
1069 thread: {
1070 threadId: ThreadId.make("thread-links"),
1071 providerSessionId: token,
1072 providerInstanceId: ProviderInstanceId.make("codex"),
1073 },
1074 client: undefined,
1075 capabilities: new Set(["orchestration"]),
1076 issuedAt: 1,
1077 };
1078 const LinksToolkit = Toolkit.make(
1079 Tool.make("links", {
1080 description: "Lists links.",
1081 success: Schema.Struct({ links: Schema.Number }),
1082 failure: OrchestratorMcpFailure,
1083 failureMode: "return",
1084 }).annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenWhileLinksOff),
1085 Tool.make("where", {
1086 description: "Says where it ran.",
1087 parameters: Schema.Struct({ environmentId: OrchestratorMcpEnvironmentTarget }),
1088 success: Schema.Struct({ ranIn: Schema.String }),
1089 failure: OrchestratorMcpFailure,
1090 failureMode: "return",
1091 }),
1092 );
1093 const settingsContext = yield* Layer.build(ServerSettings.layerTest());
1094 const settings = Context.get(settingsContext, ServerSettings.ServerSettingsService);
1095 const serverLayer = McpHttpServer.layerMcpTransport(
1096 McpHttpServer.toolkitRegistration(
1097 LinksToolkit,
1098 McpToolAccess.toLayer(LinksToolkit, {
1099 links: McpToolAccess.reads(() => Effect.succeed({ links: 0 })),
1100 where: McpToolAccess.reads(() => Effect.succeed({ ranIn: "here" })),
1101 }),
1102 ),
1103 ).pipe(
1104 Layer.provide(Layer.succeedContext(settingsContext)),
1105 Layer.provide(McpToolAccessTestkit.liveThreadsLayer),
1106 Layer.provide(
1107 Layer.mock(McpSessionRegistry.McpSessionRegistry)({
1108 resolve: (presented) => Effect.succeed(presented === token ? scope : undefined),
1109 }),
1110 ),
1111 );
1112 yield* HttpRouter.serve(serverLayer, { disableListenLog: true, disableLogger: true }).pipe(
1113 Layer.build,
1114 );
1115 const httpClient = yield* HttpClient.HttpClient;
1116 const headers = {
1117 accept: "application/json, text/event-stream",
1118 authorization: `Bearer ${token}`,
1119 };
1120 const initialize = yield* httpClient.post("/mcp", {
1121 headers,
1122 body: HttpBody.text(
1123 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`,
1124 "application/json",
1125 ),
1126 });
1127 const rpc = (method: string, params: object) =>
1128 httpClient
1129 .post("/mcp", {
1130 headers: {
1131 ...headers,
1132 "mcp-session-id": initialize.headers["mcp-session-id"]!,
1133 "mcp-protocol-version": "2025-06-18",
1134 },
1135 body: HttpBody.text(
1136 JSON.stringify({ jsonrpc: "2.0", id: 2, method, params }),
1137 "application/json",
1138 ),
1139 })
1140 .pipe(Effect.flatMap((response) => response.json));
1141 const listed = () =>
1142 rpc("tools/list", {}).pipe(
1143 Effect.map((body) =>
1144 (body as { result: { tools: ReadonlyArray<{ name: string }> } }).result.tools.map(
1145 (tool) => tool.name,
1146 ),
1147 ),
1148 );
1149 const ranIn = (where: EnvironmentId) =>
1150 rpc("tools/call", { name: "where", arguments: { environmentId: where } }).pipe(
1151 Effect.map(
1152 (body) =>
1153 (
1154 body as {
1155 result: {
1156 isError?: boolean;
1157 structuredContent?: unknown;
1158 content: ReadonlyArray<{ text: string }>;
1159 };
1160 }
1161 ).result,
1162 ),
1163 );
1164 const elsewhere = EnvironmentId.make("environment-elsewhere");
1165
1166 expect(yield* listed()).toEqual(["where"]);
1167 expect(yield* ranIn(elsewhere)).toMatchObject({
1168 isError: true,
1169 content: [{ text: expect.stringContaining("Linked environments is off on this machine") }],
1170 });
1171 expect((yield* ranIn(environmentId)).structuredContent).toEqual({ ranIn: "here" });
1172
1173 yield* settings.updateSettings({ linkedEnvironmentsEnabled: true });
1174 expect(yield* listed()).toEqual(["links", "where"]);
1175 // On, the call goes on to the forwarding, which this server lacks.
1176 expect(yield* ranIn(elsewhere)).toMatchObject({
1177 isError: true,
1178 content: [{ text: expect.stringContaining("cannot reach linked environments") }],
1179 });
1180 }),
1181 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
1182);
1183
1184it.effect("lists pull request watch tools only to threads that are not delegated children", () =>
1185 Effect.scoped(
1186 Effect.gen(function* () {
1187 const scopeFor = (
1188 token: string,
1189 subagent: boolean,
1190 ): McpInvocationContext.McpThreadInvocationScope => ({
1191 environmentId,
1192 requestNamespace: token,
1193 thread: {
1194 threadId: ThreadId.make(`thread-${token}`),
1195 providerSessionId: token,
1196 providerInstanceId: ProviderInstanceId.make("codex"),
1197 subagent,
1198 },
1199 client: undefined,
1200 capabilities: new Set(["pull-requests"]),
1201 issuedAt: 1,
1202 });
1203 const scopes = new Map([
1204 ["parentToken", scopeFor("parentToken", false)],
1205 ["childToken", scopeFor("childToken", true)],
1206 ]);
1207 const serverLayer = McpHttpServer.layerMcpTransport(
1208 McpHttpServer.layerPullRequestsToolkit,
1209 ).pipe(
1210 Layer.provide(ServerSettings.layerTest()),
1211 Layer.provide(
1212 Layer.mock(McpSessionRegistry.McpSessionRegistry)({
1213 resolve: (token) => Effect.succeed(scopes.get(token)),
1214 }),
1215 ),
1216 Layer.provide(
1217 Layer.mergeAll(
1218 McpToolAccessTestkit.liveThreadsLayer,
1219 Layer.mock(ProjectService.ProjectService)({}),
1220 Layer.mock(PullRequestReviewGuideService.PullRequestReviewGuideService)({}),
1221 Layer.mock(Orchestrator.OrchestratorV2)({}),
1222 Layer.mock(ProjectionStore.ProjectionStoreV2)({}),
1223 NodeServices.layer,
1224 NodeCrypto.layer,
1225 ),
1226 ),
1227 );
1228 yield* HttpRouter.serve(serverLayer, { disableListenLog: true, disableLogger: true }).pipe(
1229 Layer.build,
1230 );
1231 const httpClient = yield* HttpClient.HttpClient;
1232 const listedTools = (token: string) =>
1233 Effect.gen(function* () {
1234 const headers = {
1235 accept: "application/json, text/event-stream",
1236 authorization: `Bearer ${token}`,
1237 };
1238 const initialize = yield* httpClient.post("/mcp", {
1239 headers,
1240 body: HttpBody.text(
1241 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`,
1242 "application/json",
1243 ),
1244 });
1245 const listed = yield* httpClient.post("/mcp", {
1246 headers: {
1247 ...headers,
1248 "mcp-session-id": initialize.headers["mcp-session-id"]!,
1249 "mcp-protocol-version": "2025-06-18",
1250 },
1251 body: HttpBody.text(
1252 `{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}`,
1253 "application/json",
1254 ),
1255 });
1256 const body = (yield* listed.json) as {
1257 readonly result: { readonly tools: ReadonlyArray<{ readonly name: string }> };
1258 };
1259 return body.result.tools.map((tool) => tool.name);
1260 });
1261
1262 const parentTools = yield* listedTools("parentToken");
1263 const childTools = yield* listedTools("childToken");
1264 expect(parentTools).toEqual(
1265 expect.arrayContaining(["link_pull_request", "watch_pull_request", "unwatch_pull_request"]),
1266 );
1267 expect(childTools).toContain("link_pull_request");
1268 expect(childTools).not.toContain("watch_pull_request");
1269 expect(childTools).not.toContain("unwatch_pull_request");
1270 }),
1271 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
1272);
1273
1274it.effect(
1275 "narrows an OAuth client's modes to the T3-Mode-Limit it sends, and never widens them",
1276 () =>
1277 Effect.scoped(
1278 Effect.gen(function* () {
1279 const clientToken = "client-payload.client-signature";
1280 const clientScope: McpInvocationContext.McpInvocationScope = {
1281 environmentId,
1282 requestNamespace: "client:linked",
1283 thread: undefined,
1284 client: { sessionId: "linked", label: "T3 Code · laptop", access: "auto" },
1285 capabilities: new Set(["orchestration"]),
1286 issuedAt: 1,
1287 };
1288 // Starts a thread at the modes the gate hands it, so the outcome is those modes.
1289 const StartsToolkit = Toolkit.make(
1290 Tool.make("starts", {
1291 description: "Reports the modes a started thread would run with.",
1292 parameters: Schema.Struct({
1293 runtimeMode: Schema.optional(RuntimeMode),
1294 interactionMode: Schema.optional(ProviderInteractionMode),
1295 }),
1296 success: Schema.Struct({ modes: Schema.String }),
1297 failure: OrchestratorMcpFailure,
1298 failureMode: "return",
1299 dependencies: [
1300 McpInvocationContext.McpInvocationContext,
1301 ThreadManagementService.ThreadManagementService,
1302 ],
1303 }),
1304 );
1305 const serverLayer = McpHttpServer.layerMcpTransport(
1306 McpHttpServer.toolkitRegistration(
1307 StartsToolkit,
1308 McpToolAccess.toLayer(StartsToolkit, {
1309 starts: McpToolAccess.startsThreads(
1310 (input) => input,
1311 (_, modes) =>
1312 Effect.succeed({ modes: `${modes.runtimeMode}/${modes.interactionMode}` }),
1313 "stamped",
1314 ),
1315 }),
1316 ),
1317 ).pipe(
1318 Layer.provide(ServerSettings.layerTest()),
1319 Layer.provide(McpToolAccessTestkit.liveThreadsLayer),
1320 Layer.provide(
1321 Layer.mock(McpSessionRegistry.McpSessionRegistry)({
1322 resolve: () => Effect.undefined,
1323 }),
1324 ),
1325 Layer.provide(
1326 Layer.succeed(McpHttpServer.McpClientAuthenticator, {
1327 authenticate: (request) =>
1328 Effect.succeed(
1329 request.headers.authorization === `Bearer ${clientToken}`
1330 ? clientScope
1331 : undefined,
1332 ),
1333 }),
1334 ),
1335 );
1336 yield* HttpRouter.serve(serverLayer, { disableListenLog: true, disableLogger: true }).pipe(
1337 Layer.build,
1338 );
1339 const httpClient = yield* HttpClient.HttpClient;
1340 const decodeOutcome = Schema.decodeUnknownEffect(
1341 Schema.fromJsonString(
1342 Schema.Struct({
1343 result: Schema.Struct({
1344 content: Schema.Array(Schema.Struct({ text: Schema.String })),
1345 }),
1346 }),
1347 ),
1348 );
1349 const decodeText = Schema.decodeUnknownEffect(
1350 Schema.fromJsonString(
1351 Schema.Union([
1352 Schema.Struct({ modes: Schema.String }),
1353 Schema.Struct({ code: Schema.String }),
1354 ]),
1355 ),
1356 );
1357 /** Starts a thread as the client, with `limit` as T3-Mode-Limit; the HTTP status or the outcome. */
1358 const start = (limit: string | undefined, args: Record<string, string> = {}) =>
1359 Effect.gen(function* () {
1360 const headers = {
1361 accept: "application/json, text/event-stream",
1362 authorization: `Bearer ${clientToken}`,
1363 ...(limit === undefined ? {} : { "t3-mode-limit": limit }),
1364 };
1365 const initialize = yield* httpClient.post("/mcp", {
1366 headers,
1367 body: HttpBody.text(
1368 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`,
1369 "application/json",
1370 ),
1371 });
1372 if (initialize.status !== 200) return initialize.status;
1373 const response = yield* httpClient.post("/mcp", {
1374 headers: {
1375 ...headers,
1376 "mcp-session-id": initialize.headers["mcp-session-id"]!,
1377 "mcp-protocol-version": "2025-06-18",
1378 },
1379 body: HttpBody.text(
1380 JSON.stringify({
1381 jsonrpc: "2.0",
1382 id: 2,
1383 method: "tools/call",
1384 params: { name: "starts", arguments: args },
1385 }),
1386 "application/json",
1387 ),
1388 });
1389 const body = yield* decodeOutcome(yield* response.text);
1390 const outcome = yield* decodeText(
1391 body.result.content.map((part) => part.text).join(""),
1392 );
1393 return "code" in outcome ? outcome.code : outcome.modes;
1394 });
1395
1396 // Approved for auto: without the header the client keeps its ceiling.
1397 expect(yield* start(undefined)).toBe("auto/default");
1398 // The header narrows both modes, and asking above it is refused.
1399 expect(yield* start("approval-required/plan")).toBe("approval-required/plan");
1400 expect(yield* start("approval-required/plan", { runtimeMode: "auto" })).toBe(
1401 "runtime_mode_escalation_denied",
1402 );
1403 expect(yield* start("auto-accept-edits/plan", { interactionMode: "default" })).toBe(
1404 "interaction_mode_escalation_denied",
1405 );
1406 // A broader header changes nothing: the approved ceiling still holds.
1407 expect(yield* start("full-access/default")).toBe("auto/default");
1408 expect(yield* start("full-access/default", { runtimeMode: "full-access" })).toBe(
1409 "runtime_mode_escalation_denied",
1410 );
1411 // A malformed header is refused before anything runs.
1412 expect(yield* start("auto")).toBe(400);
1413 expect(yield* start("auto/default/extra")).toBe(400);
1414 expect(yield* start("root/default")).toBe(400);
1415 }),
1416 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
1417);