Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

McpHttpServer.test.ts

1,478 lines57.5 KB

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