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(70_000),
696 interactiveElements: [],
697 consoleEntries: [{ level: "log", text: "x".repeat(70_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.length).toBe(2_049);
713 expect(parsed.consoleEntries[0]?.text.length).toBe(501);
714 const notice = snapshot.content[2];
715 const noticeText = notice?.type === "text" ? notice.text : "";
716 expect(noticeText).toContain("url or title after 2048 characters");
717 expect(noticeText).toContain("console entries text after 500 characters");
718 }),
719 ).pipe(Effect.provide(layerTest)),
720);
721
722// regression: #13558 preview snapshots overflowed the agent's tool output
723it.effect("bounds page text made of wide characters before dropping locators", () =>
724 Effect.scoped(
725 Effect.gen(function* () {
726 yield* serveSnapshots("mcp-wide-text-client", {
727 ...snapshotResult,
728 visibleText: "界".repeat(9_000),
729 interactiveElements: Array.from({ length: 20 }, (_, i) => ({
730 tag: "button",
731 role: "button",
732 name: `Button ${i}`,
733 selector: `#button-${i}`,
734 x: 0,
735 y: 0,
736 width: 10,
737 height: 10,
738 })),
739 });
740
741 const snapshot = yield* callSnapshot({ includeImage: false });
742
743 const [, text, notice] = snapshot.content;
744 const body = text?.type === "text" ? text.text : "";
745 expect(Buffer.byteLength(body, "utf8")).toBeLessThanOrEqual(
746 McpHttpServer.MAX_SNAPSHOT_TEXT_BYTES,
747 );
748 const parsed = decodeJsonText(body) as {
749 readonly visibleText: string;
750 readonly interactiveElements: ReadonlyArray<unknown>;
751 };
752 expect(parsed.visibleText).toMatch(/^界+…$/);
753 expect(parsed.interactiveElements).toHaveLength(20);
754 expect(notice?.type === "text" ? notice.text : "").toContain(
755 "visibleText after 4000 characters",
756 );
757 }),
758 ).pipe(Effect.provide(layerTest)),
759);
760
761it.effect("terminates HTTP MCP sessions with DELETE", () =>
762 Effect.scoped(
763 Effect.gen(function* () {
764 const token = "providerTokenWithoutDots";
765 const scope: McpInvocationContext.McpInvocationScope = {
766 environmentId,
767 requestNamespace: "provider-session",
768 thread: {
769 threadId: ThreadId.make("thread-provider"),
770 providerSessionId: "provider-session",
771 providerInstanceId: ProviderInstanceId.make("codex"),
772 },
773 client: undefined,
774 capabilities: new Set(["orchestration"]),
775 issuedAt: 1,
776 };
777 const layerServer = McpHttpServer.layerMcpTransport(Layer.empty).pipe(
778 Layer.provide(ServerSettings.layerTest()),
779 Layer.provide(
780 Layer.mock(McpSessionRegistry.McpSessionRegistry)({
781 resolve: (presented) =>
782 Effect.succeed(
783 presented === token
784 ? (scope as McpInvocationContext.McpThreadInvocationScope)
785 : undefined,
786 ),
787 }),
788 ),
789 );
790 yield* HttpRouter.serve(layerServer, {
791 disableListenLog: true,
792 disableLogger: true,
793 }).pipe(Layer.build);
794 const httpClient = (yield* HttpClient.HttpClient).pipe(
795 HttpClient.mapRequest(HttpClientRequest.bearerToken(token)),
796 );
797
798 const initializeResponse = yield* httpClient.post("/mcp", {
799 headers: { accept: "application/json, text/event-stream" },
800 body: HttpBody.text(
801 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"mcp-test","version":"1.0.0"}}}`,
802 "application/json",
803 ),
804 });
805 const sessionId = initializeResponse.headers["mcp-session-id"];
806 expect(initializeResponse.status).toBe(200);
807 expect(sessionId).not.toBeNull();
808
809 const missingSessionResponse = yield* httpClient.del("/mcp");
810 expect(missingSessionResponse.status).toBe(400);
811
812 const unknownSessionResponse = yield* httpClient.del("/mcp", {
813 headers: { "mcp-session-id": "unknown-session" },
814 });
815 expect(unknownSessionResponse.status).toBe(404);
816
817 const terminateResponse = yield* httpClient.del("/mcp", {
818 headers: { "mcp-session-id": sessionId! },
819 });
820 expect(terminateResponse.status).toBe(204);
821
822 const reusedSessionResponse = yield* httpClient.post("/mcp", {
823 headers: {
824 accept: "application/json, text/event-stream",
825 "mcp-session-id": sessionId!,
826 },
827 body: HttpBody.text(
828 `{"jsonrpc":"2.0","id":2,"method":"ping","params":{}}`,
829 "application/json",
830 ),
831 });
832 expect(reusedSessionResponse.status).toBe(404);
833 }),
834 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
835);
836
837it.effect("admits provider and OAuth client credentials and points only clients at OAuth", () =>
838 Effect.scoped(
839 Effect.gen(function* () {
840 const providerToken = "providerTokenWithoutDots";
841 const clientToken = "client-payload.client-signature";
842 const providerScope: McpInvocationContext.McpInvocationScope = {
843 environmentId,
844 requestNamespace: "provider-session",
845 thread: {
846 threadId: ThreadId.make("thread-provider"),
847 providerSessionId: "provider-session",
848 providerInstanceId: ProviderInstanceId.make("codex"),
849 },
850 client: undefined,
851 capabilities: new Set(["orchestration"]),
852 issuedAt: 1,
853 };
854 const clientScope: McpInvocationContext.McpInvocationScope = {
855 environmentId,
856 requestNamespace: "client:session-1",
857 thread: undefined,
858 client: { sessionId: "session-1", label: "Claude Code", access: "auto" },
859 capabilities: new Set(["orchestration"]),
860 issuedAt: 1,
861 };
862 const seen: Array<McpInvocationContext.McpInvocationScope> = [];
863 const ProbeToolkit = Toolkit.make(
864 Tool.make("probe", {
865 description: "Reports the caller.",
866 success: Schema.Struct({ ok: Schema.Boolean }),
867 failure: OrchestratorMcpFailure,
868 failureMode: "return",
869 dependencies: [McpInvocationContext.McpInvocationContext],
870 }),
871 );
872 const serverLayer = McpHttpServer.layerMcpTransport(
873 McpHttpServer.toolkitRegistration(
874 ProbeToolkit,
875 McpToolAccess.toLayer(ProbeToolkit, {
876 probe: McpToolAccess.reads(() =>
877 McpInvocationContext.McpInvocationContext.pipe(
878 Effect.tap((scope) => Effect.sync(() => seen.push(scope))),
879 Effect.as({ ok: true }),
880 ),
881 ),
882 }),
883 ),
884 ).pipe(
885 Layer.provide(ServerSettings.layerTest()),
886 Layer.provide(
887 Layer.mock(McpSessionRegistry.McpSessionRegistry)({
888 resolve: (token) =>
889 Effect.succeed(
890 token === providerToken
891 ? (providerScope as McpInvocationContext.McpThreadInvocationScope)
892 : undefined,
893 ),
894 }),
895 ),
896 Layer.provide(
897 Layer.succeed(McpHttpServer.McpClientAuthenticator, {
898 authenticate: (request) =>
899 Effect.succeed(
900 request.headers.authorization === `Bearer ${clientToken}` ? clientScope : undefined,
901 ),
902 }),
903 ),
904 );
905 yield* HttpRouter.serve(serverLayer, { disableListenLog: true, disableLogger: true }).pipe(
906 Layer.build,
907 );
908 const httpClient = yield* HttpClient.HttpClient;
909 const call = (token: string | undefined) =>
910 Effect.gen(function* () {
911 const headers = {
912 accept: "application/json, text/event-stream",
913 ...(token === undefined ? {} : { authorization: `Bearer ${token}` }),
914 };
915 const initialize = yield* httpClient.post("/mcp", {
916 headers,
917 body: HttpBody.text(
918 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`,
919 "application/json",
920 ),
921 });
922 if (initialize.status !== 200) return initialize;
923 return yield* httpClient.post("/mcp", {
924 headers: {
925 ...headers,
926 "mcp-session-id": initialize.headers["mcp-session-id"]!,
927 "mcp-protocol-version": "2025-06-18",
928 },
929 body: HttpBody.text(
930 `{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"probe","arguments":{}}}`,
931 "application/json",
932 ),
933 });
934 });
935
936 expect((yield* call(providerToken)).status).toBe(200);
937 expect((yield* call(clientToken)).status).toBe(200);
938 expect(seen.map((scope) => scope.requestNamespace)).toEqual([
939 "provider-session",
940 "client:session-1",
941 ]);
942
943 const missing = yield* call(undefined);
944 expect(missing.status).toBe(401);
945 expect(missing.headers["www-authenticate"]).toMatch(
946 /^Bearer resource_metadata="http:\/\/[^"]+\/\.well-known\/oauth-protected-resource\/mcp"$/,
947 );
948
949 const expiredClient = yield* call("stale-payload.stale-signature");
950 expect(expiredClient.headers["www-authenticate"]).toContain("resource_metadata=");
951 expect(expiredClient.headers["www-authenticate"]).toContain('error="invalid_token"');
952
953 const deadProvider = yield* call("deadProviderToken");
954 expect(deadProvider.status).toBe(401);
955 expect(deadProvider.headers["www-authenticate"]).toBe('Bearer error="invalid_token"');
956 }),
957 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
958);
959
960it.effect("accepts case-insensitive MCP bearer schemes and diagnoses rejected credentials", () => {
961 const messages: Array<unknown> = [];
962 const logger = Logger.make(({ message }) => messages.push(message));
963 const layerAuth = Layer.mergeAll(EnvironmentAuth.layer, McpSessionRegistry.layer).pipe(
964 Layer.provideMerge(
965 Layer.mock(ServerEnvironment.ServerEnvironment)({
966 getEnvironmentId: Effect.succeed(environmentId),
967 }),
968 ),
969 Layer.provideMerge(Sqlite.layerMemory),
970 Layer.provide(ServerSecretStore.layer),
971 Layer.provide(ManagedPolicy.layerTest()),
972 Layer.provideMerge(ServerEnvironment.layerIdentity),
973 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-auth-header-test-" })),
974 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
975 );
976 return Effect.scoped(
977 Effect.gen(function* () {
978 const auth = yield* EnvironmentAuth.EnvironmentAuth;
979 const registry = yield* McpSessionRegistry.McpSessionRegistry;
980 const issued = yield* registry.issue({
981 threadId,
982 providerInstanceId: ProviderInstanceId.make("codex"),
983 });
984 const providerToken = issued.config.authorizationHeader.slice("Bearer ".length);
985 const oauth = yield* auth.issueMcpClientSession({
986 label: "MCP header test",
987 access: "read-only",
988 peerLink: false,
989 client: { deviceType: "bot" },
990 });
991 yield* HttpRouter.serve(
992 McpHttpServer.layerMcpTransport(Layer.empty).pipe(
993 Layer.provide(McpOAuth.layerMcpClientAuthenticator),
994 Layer.provide(ServerSettings.layerTest()),
995 ),
996 { disableListenLog: true, disableLogger: true },
997 ).pipe(Layer.build);
998 const httpClient = yield* HttpClient.HttpClient;
999 const initialize = (authorization?: string) =>
1000 httpClient.post("/mcp", {
1001 headers: {
1002 accept: "application/json, text/event-stream",
1003 ...(authorization === undefined ? {} : { authorization }),
1004 },
1005 body: HttpBody.text(
1006 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"mcp-header-test","version":"1.0.0"}}}`,
1007 "application/json",
1008 ),
1009 });
1010
1011 for (const scheme of ["Bearer", "bearer", "bEaReR"]) {
1012 for (const [kind, token] of [
1013 ["provider", providerToken],
1014 ["OAuth", oauth.token],
1015 ]) {
1016 const response = yield* initialize(`${scheme} ${token}`);
1017 expect.soft(response.status, `${kind} ${scheme}`).toBe(200);
1018 }
1019 }
1020 messages.length = 0;
1021 for (const [authorization, reason] of [
1022 [undefined, "missing_authorization_header"],
1023 [`Basic ${providerToken}`, "unsupported_scheme"],
1024 ["Bearer", "missing_bearer_token"],
1025 ["bEaReR ", "missing_bearer_token"],
1026 [`bearer ${providerToken.toUpperCase()}`, "unknown_or_expired_token"],
1027 [`bEaReR ${oauth.token.toUpperCase()}`, "unknown_or_expired_token"],
1028 ] as const) {
1029 const response = yield* initialize(authorization);
1030 expect(response.status).toBe(401);
1031 expect
1032 .soft(messages.at(-1))
1033 .toEqual(["rejected MCP request with an unusable credential", { reason }]);
1034 const body = yield* response.text;
1035 expect(body).not.toContain(providerToken);
1036 expect(body).not.toContain(oauth.token);
1037 expect(JSON.stringify(response.headers)).not.toContain(providerToken);
1038 expect(JSON.stringify(response.headers)).not.toContain(oauth.token);
1039 }
1040 yield* registry.revokeThread(threadId);
1041 yield* auth.revokeSession(oauth.sessionId);
1042 for (const token of [providerToken, oauth.token]) {
1043 expect((yield* initialize(`bearer ${token}`)).status).toBe(401);
1044 }
1045 expect(JSON.stringify(messages)).not.toContain(providerToken);
1046 expect(JSON.stringify(messages)).not.toContain(oauth.token);
1047 expect(JSON.stringify(messages)).not.toContain(providerToken.toUpperCase());
1048 expect(JSON.stringify(messages)).not.toContain(oauth.token.toUpperCase());
1049 }),
1050 ).pipe(
1051 Effect.provide(
1052 layerAuth.pipe(
1053 Layer.provideMerge(NodeHttpServer.layerTest),
1054 Layer.provideMerge(Logger.layer([logger], { mergeWithExisting: false })),
1055 ),
1056 ),
1057 );
1058});
1059
1060it.effect("hides tools for links and refuses another environment while the beta is off", () =>
1061 Effect.scoped(
1062 Effect.gen(function* () {
1063 const token = "linksToken";
1064 const scope: McpInvocationContext.McpThreadInvocationScope = {
1065 environmentId,
1066 requestNamespace: token,
1067 thread: {
1068 threadId: ThreadId.make("thread-links"),
1069 providerSessionId: token,
1070 providerInstanceId: ProviderInstanceId.make("codex"),
1071 },
1072 client: undefined,
1073 capabilities: new Set(["orchestration"]),
1074 issuedAt: 1,
1075 };
1076 const LinksToolkit = Toolkit.make(
1077 Tool.make("links", {
1078 description: "Lists links.",
1079 success: Schema.Struct({ links: Schema.Number }),
1080 failure: OrchestratorMcpFailure,
1081 failureMode: "return",
1082 }).annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenWhileLinksOff),
1083 Tool.make("where", {
1084 description: "Says where it ran.",
1085 parameters: Schema.Struct({ environmentId: OrchestratorMcpEnvironmentTarget }),
1086 success: Schema.Struct({ ranIn: Schema.String }),
1087 failure: OrchestratorMcpFailure,
1088 failureMode: "return",
1089 }),
1090 );
1091 const settingsContext = yield* Layer.build(ServerSettings.layerTest());
1092 const settings = Context.get(settingsContext, ServerSettings.ServerSettingsService);
1093 const serverLayer = McpHttpServer.layerMcpTransport(
1094 McpHttpServer.toolkitRegistration(
1095 LinksToolkit,
1096 McpToolAccess.toLayer(LinksToolkit, {
1097 links: McpToolAccess.reads(() => Effect.succeed({ links: 0 })),
1098 where: McpToolAccess.reads(() => Effect.succeed({ ranIn: "here" })),
1099 }),
1100 ),
1101 ).pipe(
1102 Layer.provide(Layer.succeedContext(settingsContext)),
1103 Layer.provide(McpToolAccessTestkit.liveThreadsLayer),
1104 Layer.provide(
1105 Layer.mock(McpSessionRegistry.McpSessionRegistry)({
1106 resolve: (presented) => Effect.succeed(presented === token ? scope : undefined),
1107 }),
1108 ),
1109 );
1110 yield* HttpRouter.serve(serverLayer, { disableListenLog: true, disableLogger: true }).pipe(
1111 Layer.build,
1112 );
1113 const httpClient = yield* HttpClient.HttpClient;
1114 const headers = {
1115 accept: "application/json, text/event-stream",
1116 authorization: `Bearer ${token}`,
1117 };
1118 const initialize = yield* httpClient.post("/mcp", {
1119 headers,
1120 body: HttpBody.text(
1121 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`,
1122 "application/json",
1123 ),
1124 });
1125 const rpc = (method: string, params: object) =>
1126 httpClient
1127 .post("/mcp", {
1128 headers: {
1129 ...headers,
1130 "mcp-session-id": initialize.headers["mcp-session-id"]!,
1131 "mcp-protocol-version": "2025-06-18",
1132 },
1133 body: HttpBody.text(
1134 JSON.stringify({ jsonrpc: "2.0", id: 2, method, params }),
1135 "application/json",
1136 ),
1137 })
1138 .pipe(Effect.flatMap((response) => response.json));
1139 const listed = () =>
1140 rpc("tools/list", {}).pipe(
1141 Effect.map((body) =>
1142 (body as { result: { tools: ReadonlyArray<{ name: string }> } }).result.tools.map(
1143 (tool) => tool.name,
1144 ),
1145 ),
1146 );
1147 const ranIn = (where: EnvironmentId) =>
1148 rpc("tools/call", { name: "where", arguments: { environmentId: where } }).pipe(
1149 Effect.map(
1150 (body) =>
1151 (
1152 body as {
1153 result: {
1154 isError?: boolean;
1155 structuredContent?: unknown;
1156 content: ReadonlyArray<{ text: string }>;
1157 };
1158 }
1159 ).result,
1160 ),
1161 );
1162 const elsewhere = EnvironmentId.make("environment-elsewhere");
1163
1164 expect(yield* listed()).toEqual(["where"]);
1165 expect(yield* ranIn(elsewhere)).toMatchObject({
1166 isError: true,
1167 content: [{ text: expect.stringContaining("Linked environments is off on this machine") }],
1168 });
1169 expect((yield* ranIn(environmentId)).structuredContent).toEqual({ ranIn: "here" });
1170
1171 yield* settings.updateSettings({ linkedEnvironmentsEnabled: true });
1172 expect(yield* listed()).toEqual(["links", "where"]);
1173 // On, the call goes on to the forwarding, which this server lacks.
1174 expect(yield* ranIn(elsewhere)).toMatchObject({
1175 isError: true,
1176 content: [{ text: expect.stringContaining("cannot reach linked environments") }],
1177 });
1178 }),
1179 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
1180);
1181
1182it.effect("lists pull request watch tools only to threads that are not delegated children", () =>
1183 Effect.scoped(
1184 Effect.gen(function* () {
1185 const scopeFor = (
1186 token: string,
1187 subagent: boolean,
1188 ): McpInvocationContext.McpThreadInvocationScope => ({
1189 environmentId,
1190 requestNamespace: token,
1191 thread: {
1192 threadId: ThreadId.make(`thread-${token}`),
1193 providerSessionId: token,
1194 providerInstanceId: ProviderInstanceId.make("codex"),
1195 subagent,
1196 },
1197 client: undefined,
1198 capabilities: new Set(["pull-requests"]),
1199 issuedAt: 1,
1200 });
1201 const scopes = new Map([
1202 ["parentToken", scopeFor("parentToken", false)],
1203 ["childToken", scopeFor("childToken", true)],
1204 ]);
1205 const serverLayer = McpHttpServer.layerMcpTransport(
1206 McpHttpServer.layerPullRequestsToolkit,
1207 ).pipe(
1208 Layer.provide(ServerSettings.layerTest()),
1209 Layer.provide(
1210 Layer.mock(McpSessionRegistry.McpSessionRegistry)({
1211 resolve: (token) => Effect.succeed(scopes.get(token)),
1212 }),
1213 ),
1214 Layer.provide(
1215 Layer.mergeAll(
1216 McpToolAccessTestkit.liveThreadsLayer,
1217 Layer.mock(ProjectService.ProjectService)({}),
1218 Layer.mock(PullRequestReviewGuideService.PullRequestReviewGuideService)({}),
1219 Layer.mock(Orchestrator.OrchestratorV2)({}),
1220 Layer.mock(ProjectionStore.ProjectionStoreV2)({}),
1221 NodeServices.layer,
1222 NodeCrypto.layer,
1223 ),
1224 ),
1225 );
1226 yield* HttpRouter.serve(serverLayer, { disableListenLog: true, disableLogger: true }).pipe(
1227 Layer.build,
1228 );
1229 const httpClient = yield* HttpClient.HttpClient;
1230 const listedTools = (token: string) =>
1231 Effect.gen(function* () {
1232 const headers = {
1233 accept: "application/json, text/event-stream",
1234 authorization: `Bearer ${token}`,
1235 };
1236 const initialize = yield* httpClient.post("/mcp", {
1237 headers,
1238 body: HttpBody.text(
1239 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`,
1240 "application/json",
1241 ),
1242 });
1243 const listed = yield* httpClient.post("/mcp", {
1244 headers: {
1245 ...headers,
1246 "mcp-session-id": initialize.headers["mcp-session-id"]!,
1247 "mcp-protocol-version": "2025-06-18",
1248 },
1249 body: HttpBody.text(
1250 `{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}`,
1251 "application/json",
1252 ),
1253 });
1254 const body = (yield* listed.json) as {
1255 readonly result: { readonly tools: ReadonlyArray<{ readonly name: string }> };
1256 };
1257 return body.result.tools.map((tool) => tool.name);
1258 });
1259
1260 const parentTools = yield* listedTools("parentToken");
1261 const childTools = yield* listedTools("childToken");
1262 expect(parentTools).toEqual(
1263 expect.arrayContaining(["link_pull_request", "watch_pull_request", "unwatch_pull_request"]),
1264 );
1265 expect(childTools).toContain("link_pull_request");
1266 expect(childTools).not.toContain("watch_pull_request");
1267 expect(childTools).not.toContain("unwatch_pull_request");
1268 }),
1269 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
1270);
1271
1272it.effect(
1273 "narrows an OAuth client's modes to the T3-Mode-Limit it sends, and never widens them",
1274 () =>
1275 Effect.scoped(
1276 Effect.gen(function* () {
1277 const clientToken = "client-payload.client-signature";
1278 const clientScope: McpInvocationContext.McpInvocationScope = {
1279 environmentId,
1280 requestNamespace: "client:linked",
1281 thread: undefined,
1282 client: { sessionId: "linked", label: "T3 Code · laptop", access: "auto" },
1283 capabilities: new Set(["orchestration"]),
1284 issuedAt: 1,
1285 };
1286 // Starts a thread at the modes the gate hands it, so the outcome is those modes.
1287 const StartsToolkit = Toolkit.make(
1288 Tool.make("starts", {
1289 description: "Reports the modes a started thread would run with.",
1290 parameters: Schema.Struct({
1291 runtimeMode: Schema.optional(RuntimeMode),
1292 interactionMode: Schema.optional(ProviderInteractionMode),
1293 }),
1294 success: Schema.Struct({ modes: Schema.String }),
1295 failure: OrchestratorMcpFailure,
1296 failureMode: "return",
1297 dependencies: [
1298 McpInvocationContext.McpInvocationContext,
1299 ThreadManagementService.ThreadManagementService,
1300 ],
1301 }),
1302 );
1303 const serverLayer = McpHttpServer.layerMcpTransport(
1304 McpHttpServer.toolkitRegistration(
1305 StartsToolkit,
1306 McpToolAccess.toLayer(StartsToolkit, {
1307 starts: McpToolAccess.startsThreads(
1308 (input) => input,
1309 (_, modes) =>
1310 Effect.succeed({ modes: `${modes.runtimeMode}/${modes.interactionMode}` }),
1311 "stamped",
1312 ),
1313 }),
1314 ),
1315 ).pipe(
1316 Layer.provide(ServerSettings.layerTest()),
1317 Layer.provide(McpToolAccessTestkit.liveThreadsLayer),
1318 Layer.provide(
1319 Layer.mock(McpSessionRegistry.McpSessionRegistry)({
1320 // @effect-diagnostics-next-line effectSucceedWithVoid:off - This optional result requires undefined, not the wider void type.
1321 resolve: () => Effect.succeed(undefined),
1322 }),
1323 ),
1324 Layer.provide(
1325 Layer.succeed(McpHttpServer.McpClientAuthenticator, {
1326 authenticate: (request) =>
1327 Effect.succeed(
1328 request.headers.authorization === `Bearer ${clientToken}`
1329 ? clientScope
1330 : undefined,
1331 ),
1332 }),
1333 ),
1334 );
1335 yield* HttpRouter.serve(serverLayer, { disableListenLog: true, disableLogger: true }).pipe(
1336 Layer.build,
1337 );
1338 const httpClient = yield* HttpClient.HttpClient;
1339 const decodeOutcome = Schema.decodeUnknownEffect(
1340 Schema.fromJsonString(
1341 Schema.Struct({
1342 result: Schema.Struct({
1343 content: Schema.Array(Schema.Struct({ text: Schema.String })),
1344 }),
1345 }),
1346 ),
1347 );
1348 const decodeText = Schema.decodeUnknownEffect(
1349 Schema.fromJsonString(
1350 Schema.Union([
1351 Schema.Struct({ modes: Schema.String }),
1352 Schema.Struct({ code: Schema.String }),
1353 ]),
1354 ),
1355 );
1356 /** Starts a thread as the client, with `limit` as T3-Mode-Limit; the HTTP status or the outcome. */
1357 const start = (limit: string | undefined, args: Record<string, string> = {}) =>
1358 Effect.gen(function* () {
1359 const headers = {
1360 accept: "application/json, text/event-stream",
1361 authorization: `Bearer ${clientToken}`,
1362 ...(limit === undefined ? {} : { "t3-mode-limit": limit }),
1363 };
1364 const initialize = yield* httpClient.post("/mcp", {
1365 headers,
1366 body: HttpBody.text(
1367 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`,
1368 "application/json",
1369 ),
1370 });
1371 if (initialize.status !== 200) return initialize.status;
1372 const response = yield* httpClient.post("/mcp", {
1373 headers: {
1374 ...headers,
1375 "mcp-session-id": initialize.headers["mcp-session-id"]!,
1376 "mcp-protocol-version": "2025-06-18",
1377 },
1378 body: HttpBody.text(
1379 JSON.stringify({
1380 jsonrpc: "2.0",
1381 id: 2,
1382 method: "tools/call",
1383 params: { name: "starts", arguments: args },
1384 }),
1385 "application/json",
1386 ),
1387 });
1388 const body = yield* decodeOutcome(yield* response.text);
1389 const outcome = yield* decodeText(
1390 body.result.content.map((part) => part.text).join(""),
1391 );
1392 return "code" in outcome ? outcome.code : outcome.modes;
1393 });
1394
1395 // Approved for auto: without the header the client keeps its ceiling.
1396 expect(yield* start(undefined)).toBe("auto/default");
1397 // The header narrows both modes, and asking above it is refused.
1398 expect(yield* start("approval-required/plan")).toBe("approval-required/plan");
1399 expect(yield* start("approval-required/plan", { runtimeMode: "auto" })).toBe(
1400 "runtime_mode_escalation_denied",
1401 );
1402 expect(yield* start("auto-accept-edits/plan", { interactionMode: "default" })).toBe(
1403 "interaction_mode_escalation_denied",
1404 );
1405 // A broader header changes nothing: the approved ceiling still holds.
1406 expect(yield* start("full-access/default")).toBe("auto/default");
1407 expect(yield* start("full-access/default", { runtimeMode: "full-access" })).toBe(
1408 "runtime_mode_escalation_denied",
1409 );
1410 // A malformed header is refused before anything runs.
1411 expect(yield* start("auto")).toBe(400);
1412 expect(yield* start("auto/default/extra")).toBe(400);
1413 expect(yield* start("root/default")).toBe(400);
1414 }),
1415 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
1416);