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