The best way to control Claude Code, Codex and more from any computer or phone

main
ts 2,152 lines 84.3 KB
Raw
1 import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
2 import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
3 import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
4 import { expect, it } from "@effect/vitest";
5 import { NodeHttpServer } from "@effect/platform-node";
6 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
7 import * as NodeServices from "@effect/platform-node/NodeServices";
8 import {
9 DeviceId,
10 DeviceOperationError,
11 EnvironmentId,
12 OrchestratorMcpEnvironmentTarget,
13 OrchestratorMcpFailure,
14 PreviewTabId,
15 ProjectId,
16 ProviderInstanceId,
17 ProviderInteractionMode,
18 RuntimeMode,
19 ThreadId,
20 } from "@t3tools/contracts";
21 import * as Context from "effect/Context";
22 import * as Deferred from "effect/Deferred";
23 import * as Effect from "effect/Effect";
24 import * as FileSystem from "effect/FileSystem";
25 import * as Layer from "effect/Layer";
26 import * as Logger from "effect/Logger";
27 import * as Schema from "effect/Schema";
28 import * as Stream from "effect/Stream";
29 import * as Tracer from "effect/Tracer";
30 import { McpSchema, McpServer, Tool, Toolkit } from "effect/ai";
31 import { HttpBody, HttpClient, HttpClientRequest, HttpRouter, HttpServer } from "effect/http";
32 import * as NetAddress from "effect/net/NetAddress";
33
34 import * as ProjectService from "../project/ProjectService.ts";
35 import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
36 import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts";
37 import * as AssetSigner from "../assets/AssetSigner.ts";
38 import * as DocumentText from "../provider/DocumentText.ts";
39 import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
40 import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
41 import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
42 import * as McpOAuth from "../auth/McpOAuth.ts";
43 import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
44 import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
45 import * as Sqlite from "../persistence/Sqlite.ts";
46 import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
47 import * as PreviewManager from "../preview/Manager.ts";
48
49 import * as DeviceService from "../device/DeviceService.ts";
50 import * as GitManager from "../git/GitManager.ts";
51 import * as PullRequestReviewGuideService from "../pullRequest/PullRequestReviewGuideService.ts";
52 import * as PullRequestService from "../pullRequest/PullRequestService.ts";
53 import * as ServerConfig from "../config.ts";
54 import * as ServerHttp from "../http.ts";
55 import * as ServerSettings from "../serverSettings.ts";
56 import { advertisedJsonSchema } from "./advertisedJsonSchema.ts";
57 import * as McpHttpServer from "./McpHttpServer.ts";
58 import * as McpToolAccess from "./McpToolAccess.ts";
59 import * as McpToolAccessTestkit from "./McpToolAccess.testkit.ts";
60 import * as McpInvocationContext from "./McpInvocationContext.ts";
61 import * as McpSessionRegistry from "./McpSessionRegistry.ts";
62 import * as OrchestratorMcpService from "./OrchestratorMcpService.ts";
63 import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
64 import { OrchestratorToolkit } from "./toolkits/orchestrator/tools.ts";
65 import { PreviewToolkit } from "./toolkits/preview/tools.ts";
66 import { PreviewControlsToolkit } from "./toolkits/previewControls/tools.ts";
67 import { ProjectToolkit } from "./toolkits/project/tools.ts";
68 import { ThreadToolkit } from "./toolkits/thread/tools.ts";
69
70 const environmentId = EnvironmentId.make("environment-mcp-test");
71 const threadId = ThreadId.make("thread-mcp-test");
72 const alternateTabId = PreviewTabId.make("tab-mcp-alternate");
73 const decodeJsonText = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
74 const invocation = {
75 environmentId,
76 requestNamespace: "provider-session-mcp-test",
77 thread: {
78 threadId,
79 providerSessionId: "provider-session-mcp-test",
80 providerInstanceId: ProviderInstanceId.make("codex"),
81 },
82 client: undefined,
83 capabilities: new Set(["preview"] as const),
84 issuedAt: 1,
85 };
86 const client = McpSchema.McpServerClient.of({
87 clientId: 1,
88 clientCapabilities: {},
89 clientInfo: { name: "mcp-test", version: "1.0.0" },
90 protocolVersion: "2025-06-18",
91 initializePayload: {
92 protocolVersion: "2025-06-18",
93 capabilities: {},
94 clientInfo: { name: "mcp-test", version: "1.0.0" },
95 },
96 getClient: Effect.die("unused"),
97 });
98 const layerTest = McpHttpServer.layerPreviewToolkit.pipe(
99 Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
100 Layer.provideMerge(McpToolAccessTestkit.liveThreadsLayer),
101 Layer.provideMerge(PreviewAutomationBroker.layer),
102 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-http-server-test-" })),
103 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
104 );
105 const layerPullRequestsTest = McpHttpServer.layerPullRequestsToolkit.pipe(
106 Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
107 Layer.provideMerge(McpToolAccessTestkit.liveThreadsLayer),
108 Layer.provide(
109 Layer.mergeAll(
110 Layer.mock(ProjectService.ProjectService)({}),
111 Layer.mock(PullRequestReviewGuideService.PullRequestReviewGuideService)({}),
112 Layer.mock(PullRequestService.PullRequestService)({}),
113 Layer.mock(GitManager.GitManager)({}),
114 Layer.mock(Orchestrator.OrchestratorV2)({}),
115 Layer.mock(ProjectionStore.ProjectionStoreV2)({}),
116 NodeServices.layer,
117 NodeCrypto.layer,
118 ),
119 ),
120 );
121
122 const snapshotResult = {
123 url: "http://example.test/",
124 title: "Example",
125 loading: false,
126 visibleText: "Example",
127 interactiveElements: [],
128 accessibilityTree: {},
129 consoleEntries: [],
130 networkEntries: [],
131 actionTimeline: [],
132 screenshot: {
133 mimeType: "image/png",
134 data: Buffer.from("png").toString("base64"),
135 width: 10,
136 height: 5,
137 },
138 };
139
140 const serveSnapshots = (clientId: string, result: unknown) =>
141 Effect.gen(function* () {
142 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
143 const connected = yield* Deferred.make<void>();
144 const inputs: Array<unknown> = [];
145 const events = yield* broker.connect({ clientId, environmentId });
146 yield* Stream.runForEach(events, (event) => {
147 if (event.type === "connected") return Deferred.succeed(connected, undefined);
148 inputs.push(event.request.input);
149 return broker.respond({
150 clientId,
151 connectionId: event.connectionId,
152 requestId: event.request.requestId,
153 ok: true,
154 result,
155 });
156 }).pipe(Effect.forkScoped);
157 yield* Deferred.await(connected);
158 return inputs;
159 });
160
161 /** Records every span and the order spans start and end in, by span ID. */
162 const recordSpans = () => {
163 const spans: Array<Tracer.NativeSpan> = [];
164 const order: Array<string> = [];
165 const tracer = Tracer.make({
166 span: (options) => {
167 const span = new Tracer.NativeSpan(options);
168 spans.push(span);
169 order.push(`start ${span.spanId}`);
170 const end = span.end.bind(span);
171 span.end = (endTime, exit) => {
172 end(endTime, exit);
173 order.push(`end ${span.spanId}`);
174 };
175 return span;
176 },
177 });
178 return { tracer, spans, order };
179 };
180
181 const callTool = (name: string, args: Record<string, unknown>) =>
182 Effect.gen(function* () {
183 const server = yield* McpServer.McpServer;
184 return yield* server
185 .callTool({ name, arguments: args })
186 .pipe(
187 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
188 Effect.provideService(McpSchema.McpServerClient, client),
189 );
190 });
191
192 const callSnapshot = (args: Record<string, unknown>) => callTool("preview_snapshot", args);
193
194 it.effect.each([
195 { input: {}, open: false, message: "No device is open in this thread. Call device_open first." },
196 {
197 input: { deviceId: "missing" },
198 open: false,
199 message: "Device missing is not open in this thread. Call device_open first.",
200 },
201 {
202 input: {},
203 open: true,
204 message:
205 "Device screenshot failed: Could not communicate with device support. Try refreshing devices.",
206 },
207 {
208 input: {},
209 open: true,
210 rejected: true,
211 message:
212 "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.",
213 },
214 ])(
215 "preserves actionable screenshot failure text: $message",
216 ({ input, open, message, ...options }) =>
217 Effect.gen(function* () {
218 const server = yield* McpServer.McpServer;
219 const traced = recordSpans();
220 const result = yield* server.callTool({ name: "device_screenshot", arguments: input }).pipe(
221 Effect.provideService(McpInvocationContext.McpInvocationContext, {
222 ...invocation,
223 capabilities: new Set(["device"] as const),
224 }),
225 Effect.provideService(McpSchema.McpServerClient, client),
226 Effect.withTracer(traced.tracer),
227 );
228 expect(result.isError).toBe(true);
229 expect(result.content).toEqual([{ type: "text", text: message }]);
230 expect(result.structuredContent).toMatchObject({
231 error: { message, operation: "screenshot" },
232 });
233 expect(JSON.stringify(result)).not.toContain("private hub output");
234 // The tool's span names it, never its arguments.
235 expect(
236 traced.spans
237 .filter((span) => span.name.startsWith("mcp.tool."))
238 .map((span) => Object.fromEntries(span.attributes)),
239 ).toEqual([
240 { "rpc.system": "mcp", "rpc.method": "tools/call", "mcp.tool.name": "device_screenshot" },
241 ]);
242 }).pipe(
243 Effect.provide(
244 McpHttpServer.layerDeviceToolkit.pipe(
245 Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
246 Layer.provide(McpToolAccessTestkit.liveThreadsLayer),
247 Layer.provide(
248 Layer.mock(DeviceService.DeviceService)({
249 locateSession: () => Effect.succeedNone,
250 sessionsForThread: () =>
251 Effect.succeed(
252 open
253 ? [
254 {
255 threadId,
256 hostId: "local",
257 deviceId: DeviceId.make("phone"),
258 platform: "ios",
259 openedAt: "2026-10-23T00:00:00Z",
260 },
261 ]
262 : [],
263 ),
264 screenshot: () =>
265 Effect.fail(
266 new DeviceOperationError({
267 operation: "screenshot",
268 reason:
269 "rejected" in options && options.rejected ? "hub_rejected" : "request_failed",
270 cause: new Error("private hub output"),
271 }),
272 ),
273 }),
274 ),
275 Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
276 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-device-mcp-test-" })),
277 Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
278 ),
279 ),
280 ),
281 );
282
283 it.effect("rejects a metadata-only response when the screenshot is saved", () =>
284 Effect.scoped(
285 Effect.gen(function* () {
286 yield* serveSnapshots("mcp-missing-pixels", {
287 ...snapshotResult,
288 screenshot: { width: 10, height: 5 },
289 });
290 const result = yield* callSnapshot({ save: true });
291 expect(result.isError).toBe(true);
292 expect(result.content).toEqual([
293 { type: "text", text: expect.stringContaining("did not contain requested PNG pixels") },
294 ]);
295 }),
296 ).pipe(Effect.provide(layerTest)),
297 );
298
299 const layerRecordingTools = (calls: Array<unknown>) => {
300 const RecordingToolkit = Toolkit.make(
301 OrchestratorToolkit.tools.delegate_task,
302 OrchestratorToolkit.tools.t3_thread_list,
303 OrchestratorToolkit.tools.t3_thread_read,
304 OrchestratorToolkit.tools.t3_thread_wait,
305 ProjectToolkit.tools.t3_project_list,
306 ProjectToolkit.tools.t3_project_update,
307 ThreadToolkit.tools.t3_queue,
308 PreviewControlsToolkit.tools.t3_preview_list,
309 ProjectToolkit.tools.t3_thread_launch,
310 );
311 const record = McpToolAccess.reads((params: unknown) =>
312 Effect.sync(() => calls.push(params)).pipe(
313 Effect.andThen(
314 Effect.fail(new OrchestratorMcpFailure({ code: "thread_not_found", message: "Recorded." })),
315 ),
316 ),
317 );
318 return McpHttpServer.toolkitRegistration(
319 RecordingToolkit,
320 McpToolAccess.toLayer(RecordingToolkit, {
321 delegate_task: record,
322 t3_thread_list: record,
323 t3_thread_read: record,
324 t3_thread_wait: record,
325 t3_project_list: record,
326 t3_project_update: record,
327 t3_queue: record,
328 t3_preview_list: record,
329 t3_thread_launch: record,
330 }),
331 ).pipe(
332 Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
333 Layer.provide(
334 Layer.mergeAll(
335 McpToolAccessTestkit.liveThreadsLayer,
336 Layer.mock(OrchestratorMcpService.OrchestratorMcpService)({}),
337 Layer.mock(ProjectService.ProjectService)({}),
338 Layer.mock(PreviewManager.PreviewManager)({}),
339 Layer.mock(PreviewAutomationBroker.PreviewAutomationBroker)({}),
340 Layer.mock(ThreadLaunchService.ThreadLaunchService)({}),
341 Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
342 namedProjectsRoot: process.cwd(),
343 }),
344 Layer.mock(GitVcsDriver.GitVcsDriver)({}),
345 Layer.mock(ServerSettings.ServerSettingsService)({}),
346 Layer.mock(DocumentText.DocumentText)({}),
347 Layer.mock(ProviderRegistry.ProviderRegistry)({}),
348 ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-http-server-test-" }),
349 NodeCrypto.layer,
350 ),
351 ),
352 Layer.provideMerge(NodeServices.layer),
353 );
354 };
355
356 it.effect.each([{}, { includeImage: false }])(
357 "returns bounded structural preview snapshot failures %#",
358 (input) =>
359 Effect.scoped(
360 Effect.gen(function* () {
361 const server = yield* McpServer.McpServer;
362 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
363 const events = yield* broker.connect({
364 clientId: "mcp-failure-client",
365 environmentId,
366 });
367 yield* Stream.runForEach(events, (event) =>
368 event.type === "connected"
369 ? Effect.void
370 : broker.respond({
371 clientId: "mcp-failure-client",
372 connectionId: event.connectionId,
373 requestId: event.request.requestId,
374 ok: false,
375 error: {
376 _tag: "PreviewAutomationExecutionError",
377 message: "sensitive renderer failure",
378 detail: { consoleOutput: "sensitive browser output" },
379 },
380 }),
381 ).pipe(Effect.forkScoped);
382 yield* Effect.yieldNow;
383
384 const snapshot = yield* server
385 .callTool({ name: "preview_snapshot", arguments: input })
386 .pipe(
387 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
388 Effect.provideService(McpSchema.McpServerClient, client),
389 );
390
391 const message = "Preview automation snapshot failed on client mcp-failure-client.";
392 expect(snapshot.isError).toBe(true);
393 expect(snapshot.content).toEqual([
394 { type: "text", text: `Preview snapshot failed: ${message}` },
395 ]);
396 expect(snapshot.structuredContent).toEqual({
397 error: {
398 _tag: "PreviewAutomationExecutionError",
399 operation: "snapshot",
400 failureCount: 1,
401 message,
402 },
403 });
404 }),
405 ).pipe(Effect.provide(layerTest)),
406 );
407
408 it.effect.each([
409 { mode: "default", input: {}, images: false },
410 { mode: "explicit image", input: { includeImage: true }, images: true },
411 { mode: "text only", input: { includeImage: false }, images: false },
412 ])("returns fresh $mode snapshots on repeated MCP calls", ({ input, images }) =>
413 Effect.scoped(
414 Effect.gen(function* () {
415 const server = yield* McpServer.McpServer;
416 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
417 const connected = yield* Deferred.make<void>();
418 const png =
419 "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII=";
420 const page = {
421 url: "http://example.test/",
422 loading: false,
423 visibleText: "Save your changes",
424 interactiveElements: [
425 {
426 tag: "button",
427 role: "button",
428 name: "Save",
429 selector: "#save",
430 x: 0,
431 y: 0,
432 width: 20,
433 height: 10,
434 },
435 ],
436 accessibilityTree: { role: "document", name: "Example" },
437 consoleEntries: [],
438 networkEntries: [],
439 actionTimeline: [],
440 };
441 const screenshot = { mimeType: "image/png", width: 1, height: 1 };
442 let requests = 0;
443 const events = yield* broker.connect({ clientId: "mcp-image-option-client", environmentId });
444 yield* Stream.runForEach(events, (event) => {
445 if (event.type === "connected") return Deferred.succeed(connected, undefined);
446 requests += 1;
447 expect(event.request).toMatchObject({
448 operation: "snapshot",
449 tabId: alternateTabId,
450 threadId,
451 });
452 expect(event.request.input).toEqual(
453 images && requests !== 7 ? {} : { pixelsRequired: false },
454 );
455 return broker.respond({
456 clientId: "mcp-image-option-client",
457 connectionId: event.connectionId,
458 requestId: event.request.requestId,
459 ok: true,
460 result: {
461 ...page,
462 title: `Snapshot ${requests}`,
463 screenshot:
464 images || requests === 7 ? { ...screenshot, data: png } : { width: 1, height: 1 },
465 },
466 });
467 }).pipe(Effect.forkScoped);
468 yield* Deferred.await(connected);
469
470 for (const call of [1, 2, 3, 4, 5, 6]) {
471 const snapshot = yield* server
472 .callTool({
473 name: "preview_snapshot",
474 arguments: { ...input, tabId: alternateTabId },
475 })
476 .pipe(
477 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
478 Effect.provideService(McpSchema.McpServerClient, client),
479 );
480 const metadata = { ...page, title: `Snapshot ${call}`, screenshot };
481 const { accessibilityTree: _tree, ...boundedMetadata } = metadata;
482 expect(snapshot.isError).toBe(false);
483 expect(snapshot.structuredContent).toEqual({
484 ...boundedMetadata,
485 omitted: ["accessibilityTree (use interactiveElements locators or preview_evaluate)"],
486 });
487 const [identity, text, ...rest] = snapshot.content;
488 expect(identity?.type === "text" ? decodeJsonText(identity.text) : null).toEqual({
489 url: page.url,
490 });
491 expect(text?.type === "text" ? decodeJsonText(text.text) : null).toEqual(boundedMetadata);
492 expect(rest).toEqual([
493 {
494 type: "text",
495 text: "Snapshot text was bounded. Omitted: accessibilityTree (use interactiveElements locators or preview_evaluate).",
496 },
497 ...(images
498 ? [
499 {
500 type: "image",
501 mimeType: "image/png",
502 data: new Uint8Array(Buffer.from(png, "base64")),
503 },
504 ]
505 : []),
506 ]);
507 }
508
509 const nextDefault = yield* server
510 .callTool({
511 name: "preview_snapshot",
512 arguments: { tabId: alternateTabId },
513 })
514 .pipe(
515 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
516 Effect.provideService(McpSchema.McpServerClient, client),
517 );
518 expect(nextDefault.content.map((content) => content.type)).toEqual(["text", "text", "text"]);
519 expect(nextDefault.structuredContent).toMatchObject({ title: "Snapshot 7", screenshot });
520 expect(nextDefault.structuredContent).not.toHaveProperty("accessibilityTree");
521 expect(requests).toBe(7);
522 }),
523 ).pipe(Effect.provide(layerTest)),
524 );
525
526 it.effect("saves the uncapped screenshot while the agent sees the capped one", () =>
527 Effect.scoped(
528 Effect.gen(function* () {
529 const server = yield* McpServer.McpServer;
530 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
531 const connected = yield* Deferred.make<void>();
532 const capped =
533 "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII=";
534 const full =
535 "iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAAAAABX3VL4AAAADklEQVR4nGNgYGBgYAAAAAYAAXKCmeoAAAAASUVORK5CYII=";
536 const events = yield* broker.connect({ clientId: "mcp-save-client", environmentId });
537 yield* Stream.runForEach(events, (event) => {
538 if (event.type === "connected") return Deferred.succeed(connected, undefined);
539 expect(event.request.input).toEqual({ fullScreenshot: true });
540 return broker.respond({
541 clientId: "mcp-save-client",
542 connectionId: event.connectionId,
543 requestId: event.request.requestId,
544 ok: true,
545 result: {
546 ...snapshotResult,
547 screenshot: { mimeType: "image/png", data: capped, width: 1, height: 1 },
548 fullScreenshot: { data: full, width: 2, height: 2 },
549 },
550 });
551 }).pipe(Effect.forkScoped);
552 yield* Deferred.await(connected);
553
554 const snapshot = yield* server
555 .callTool({
556 name: "preview_snapshot",
557 arguments: { tabId: alternateTabId, save: true, includeImage: true },
558 })
559 .pipe(
560 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
561 Effect.provideService(McpSchema.McpServerClient, client),
562 );
563 const { screenshotPath } = snapshot.structuredContent as { readonly screenshotPath: string };
564 const saved = yield* (yield* FileSystem.FileSystem).readFile(screenshotPath);
565
566 expect(Buffer.from(saved).toString("base64")).toBe(full);
567 expect(snapshot.structuredContent).not.toHaveProperty("fullScreenshot");
568 expect(snapshot.content.at(-1)).toEqual({
569 type: "image",
570 mimeType: "image/png",
571 data: new Uint8Array(Buffer.from(capped, "base64")),
572 });
573 }),
574 ).pipe(Effect.provide(layerTest)),
575 );
576
577 it.effect("names the screenshot destination when saving it fails", () =>
578 Effect.scoped(
579 Effect.gen(function* () {
580 const config = yield* ServerConfig.ServerConfig;
581 yield* (yield* FileSystem.FileSystem).writeFileString(config.browserArtifactsDir, "occupied");
582 const inputs = yield* serveSnapshots("mcp-save-failure-client", snapshotResult);
583
584 const snapshot = yield* callSnapshot({ tabId: alternateTabId, save: true });
585 const text = snapshot.content[0]?.type === "text" ? snapshot.content[0].text : "";
586
587 expect(inputs).toEqual([{ fullScreenshot: true }]);
588 expect(snapshot.isError).toBe(true);
589 expect(text).toMatch(/^Preview snapshot failed: Could not save preview screenshot to /);
590 expect(text).toContain(config.browserArtifactsDir);
591 expect(snapshot.structuredContent).toMatchObject({
592 error: { _tag: "PreviewScreenshotSaveError", message: text.slice(25) },
593 });
594 }),
595 ).pipe(Effect.provide(layerTest)),
596 );
597
598 it.effect("refuses preview tools to a client outside a thread before they run", () =>
599 Effect.gen(function* () {
600 const server = yield* McpServer.McpServer;
601 const readOnly = {
602 ...invocation,
603 thread: undefined,
604 requestNamespace: "client:session-1",
605 client: { sessionId: "session-1", label: "Claude Code", access: "read-only" as const },
606 };
607 const click = yield* server
608 .callTool({ name: "preview_act", arguments: { action: "click", locator: "text=Send" } })
609 .pipe(
610 Effect.flip,
611 Effect.provideService(McpInvocationContext.McpInvocationContext, readOnly),
612 Effect.provideService(McpSchema.McpServerClient, client),
613 );
614 expect(click.message).toContain("Tool 'preview_act' not found");
615 }).pipe(Effect.provide(layerTest)),
616 );
617
618 it.effect("advertises the compact input schema for every registered tool", () =>
619 Effect.gen(function* () {
620 const server = yield* McpServer.McpServer;
621 const tools: Record<string, Tool.Any> = PreviewToolkit.tools;
622
623 expect(server.tools.length).toBe(Object.keys(tools).length);
624 for (const { tool } of server.tools) {
625 expect(tool.inputSchema, tool.name).toEqual(advertisedJsonSchema(tools[tool.name]!));
626 }
627 }).pipe(Effect.provide(layerTest)),
628 );
629
630 it.effect("checks each preview_act action against that action's own input", () =>
631 Effect.scoped(
632 Effect.gen(function* () {
633 const inputs = yield* serveSnapshots("mcp-act-client", {});
634
635 const missingKey = yield* callTool("preview_act", { action: "press" });
636 expect(missingKey.isError).toBe(true);
637 expect(inputs).toEqual([]);
638
639 const click = yield* callTool("preview_act", {
640 action: "click",
641 locator: "text=Send",
642 key: "Enter",
643 });
644 expect(click.isError).toBe(false);
645 expect(inputs[0]).toEqual({ locator: "text=Send" });
646
647 yield* callTool("preview_act", { action: "type", selector: "#name", text: "Ada" });
648 expect(inputs.at(-2)).toEqual({ selector: "#name", text: "Ada" });
649 }),
650 ).pipe(Effect.provide(layerTest)),
651 );
652
653 it.effect("rejects a hand-registered tool's undeclared argument before asking the browser", () =>
654 Effect.scoped(
655 Effect.gen(function* () {
656 const inputs = yield* serveSnapshots("mcp-excess-argument-client", snapshotResult);
657
658 const snapshot = yield* callSnapshot({ includeImages: true });
659
660 expect(inputs).toEqual([]);
661 expect(snapshot.isError).toBe(true);
662 expect(snapshot.content).toEqual([
663 { type: "text", text: expect.stringContaining('Unknown argument "includeImages"') },
664 ]);
665 }),
666 ).pipe(Effect.provide(layerTest)),
667 );
668
669 it.effect("decodes null optional arguments the way it decodes omitted ones", () => {
670 const calls: Array<unknown> = [];
671 return Effect.gen(function* () {
672 const thread = { threadId: "thread-null-arguments" };
673 yield* callTool("t3_thread_read", thread);
674 yield* callTool("t3_thread_read", { ...thread, afterPosition: null, view: null });
675 yield* callTool("delegate_task", { task: "Inspect", target: {} });
676 yield* callTool("delegate_task", { task: "Inspect", title: null, target: { model: null } });
677 yield* callTool("t3_project_update", { projectId: "project-1", projectIcon: null });
678
679 expect(calls).toHaveLength(5);
680 expect(calls[1]).toEqual(calls[0]);
681 expect(calls[3]).toEqual(calls[2]);
682 expect(calls[4]).toStrictEqual({ projectId: "project-1", projectIcon: null });
683 }).pipe(Effect.provide(layerRecordingTools(calls)));
684 });
685
686 it.effect("decodes a JSON-stringified delegate target as the same object", () => {
687 const calls: Array<unknown> = [];
688 return Effect.gen(function* () {
689 const task = "Inspect";
690 const target = {
691 providerInstanceId: "codex",
692 model: "gpt-6.2-sol",
693 options: { reasoningEffort: "medium" },
694 };
695 yield* callTool("delegate_task", { task, target });
696 yield* callTool("delegate_task", { task, target: JSON.stringify(target) });
697
698 for (const invalidTarget of ["{model:", '{"model":42}']) {
699 const error = yield* Effect.flip(callTool("delegate_task", { task, target: invalidTarget }));
700 expect(error).toBeInstanceOf(McpSchema.InvalidParams);
701 }
702 expect(calls).toHaveLength(2);
703 expect(calls[0]).toEqual({
704 task,
705 target: {
706 ...target,
707 options: [{ id: "reasoningEffort", value: "medium" }],
708 },
709 });
710 expect(calls[1]).toEqual(calls[0]);
711 }).pipe(Effect.provide(layerRecordingTools(calls)));
712 });
713
714 it.effect("rejects arguments a tool does not declare instead of dropping them", () => {
715 const calls: Array<unknown> = [];
716 return Effect.gen(function* () {
717 const launch = yield* Effect.flip(
718 callTool("t3_thread_launch", { title: "Repro", scratch: true, prompt: "say hi" }),
719 );
720 const wait = yield* Effect.flip(
721 callTool("t3_thread_wait", { threadId: "thread-excess-arguments", timeout: 5_000 }),
722 );
723
724 expect(calls).toEqual([]);
725 expect(launch.message).toContain('Unknown argument "prompt"');
726 expect(wait.message).toContain('Unknown argument "timeout"');
727 }).pipe(Effect.provide(layerRecordingTools(calls)));
728 });
729
730 it.effect("accepts a nested key the merged advertised schema shows", () => {
731 const calls: Array<unknown> = [];
732 return Effect.gen(function* () {
733 yield* Effect.exit(
734 callTool("t3_thread_launch", {
735 title: "Root",
736 projectId: "project-1",
737 message: "say hi",
738 workspaceStrategy: { type: "root", baseRef: "main" },
739 }),
740 );
741
742 expect(calls).toHaveLength(1);
743 }).pipe(Effect.provide(layerRecordingTools(calls)));
744 });
745
746 it.effect(
747 "clamps t3_thread_read page sizes above their maximum instead of rejecting the call",
748 () => {
749 const calls: Array<unknown> = [];
750 return Effect.gen(function* () {
751 const thread = { threadId: "thread-clamped-arguments" };
752 // Codex never shows the model these bounds, so an over-large page must still read.
753 yield* callTool("t3_thread_read", {
754 ...thread,
755 limit: 150,
756 runLimit: 80,
757 maxCharsPerItem: 60_000,
758 });
759 yield* callTool("t3_thread_read", {
760 ...thread,
761 limit: 100,
762 runLimit: 50,
763 maxCharsPerItem: 20_000,
764 });
765 yield* callTool("t3_thread_read", { ...thread, limit: 7, runLimit: 1, maxCharsPerItem: 1 });
766
767 expect(calls).toEqual([
768 { ...thread, limit: 100, runLimit: 50, maxCharsPerItem: 20_000 },
769 { ...thread, limit: 100, runLimit: 50, maxCharsPerItem: 20_000 },
770 { ...thread, limit: 7, runLimit: 1, maxCharsPerItem: 1 },
771 ]);
772 }).pipe(Effect.provide(layerRecordingTools(calls)));
773 },
774 );
775
776 it.effect.each(["limit", "runLimit", "maxCharsPerItem"])(
777 "still rejects a t3_thread_read %s below its minimum",
778 (field) => {
779 const calls: Array<unknown> = [];
780 return Effect.gen(function* () {
781 // Zero is a different request than one item, so it fails rather than answering another question.
782 const rejected = yield* callTool("t3_thread_read", {
783 threadId: "thread-below-minimum",
784 [field]: 0,
785 }).pipe(Effect.flip);
786
787 expect(String(rejected)).toContain("greater than or equal to 1");
788 expect(calls).toEqual([]);
789 }).pipe(Effect.provide(layerRecordingTools(calls)));
790 },
791 );
792
793 const clampedListLimits = [
794 { tool: "t3_thread_list", input: { allProjects: true }, maximum: 100 },
795 { tool: "t3_project_list", input: {}, maximum: 100 },
796 { tool: "t3_queue", input: { action: "list" }, maximum: 100 },
797 { tool: "t3_preview_list", input: {}, maximum: 50 },
798 ];
799
800 it.effect.each(clampedListLimits)(
801 "clamps a $tool limit above its maximum instead of rejecting the call",
802 ({ tool, input, maximum }) => {
803 const calls: Array<unknown> = [];
804 return Effect.gen(function* () {
805 yield* callTool(tool, { ...input, limit: maximum * 2 });
806 yield* callTool(tool, { ...input, limit: 7 });
807
808 expect(calls).toEqual([
809 { ...input, limit: maximum },
810 { ...input, limit: 7 },
811 ]);
812 }).pipe(Effect.provide(layerRecordingTools(calls)));
813 },
814 );
815
816 it("keeps cross-tool routing out of the delegate_task description", () => {
817 const description = OrchestratorToolkit.tools.delegate_task.description ?? "";
818 expect(description).toContain("Start one child agent with only `task`");
819 // Review rounds, follow-ups, and polling are routed in the system text.
820 expect(description).not.toContain("t3_thread_send");
821 expect(description).not.toContain("Do not poll");
822 expect(description).not.toContain("Prefer native");
823 });
824
825 it.effect(
826 "registers the pull request toolkit and surfaces a missing capability as a tool error",
827 () =>
828 Effect.gen(function* () {
829 const server = yield* McpServer.McpServer;
830 const names = server.tools.map(({ tool }) => tool.name);
831 expect(names).toEqual(
832 expect.arrayContaining([
833 "link_pull_request",
834 "unlink_pull_request",
835 "list_thread_pull_requests",
836 ]),
837 );
838 const linkTool = server.tools.find(({ tool }) => tool.name === "link_pull_request");
839 expect(linkTool?.tool.annotations?.idempotentHint).toBe(true);
840 expect(linkTool?.tool.annotations?.openWorldHint).toBe(false);
841 expect(linkTool?.tool.description).toContain("Link a PR to this thread");
842 expect(linkTool?.tool.description).toContain("settles the thread on merge");
843
844 const denied = yield* server
845 .callTool({ name: "list_thread_pull_requests", arguments: {} })
846 .pipe(
847 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
848 Effect.provideService(McpSchema.McpServerClient, client),
849 );
850 expect(denied.isError).toBe(true);
851 expect(denied.content).toEqual([
852 { type: "text", text: "MCP credential does not grant the pull-requests capability." },
853 ]);
854 }).pipe(Effect.provide(layerPullRequestsTest)),
855 );
856
857 it.effect("bounds large ARIA trees without dropping every server locator", () =>
858 Effect.scoped(
859 Effect.gen(function* () {
860 const accessibilityTree = Array.from(
861 { length: 2_000 },
862 (_, index) => `- button "删除 ${index}" [ref=t3-snapshot-e${index}]`,
863 ).join("\n");
864 const visibleText = Array.from({ length: 700 }, (_, index) => `Row ${index} value`).join(
865 "\n",
866 );
867 yield* serveSnapshots("mcp-large-server-refs", {
868 ...snapshotResult,
869 visibleText,
870 accessibilityTree,
871 });
872 const result = yield* callSnapshot({ includeImage: false });
873 expect(result.isError).toBe(false);
874 const metadata = result.structuredContent as {
875 accessibilityTree: string;
876 visibleText: string;
877 };
878 expect(metadata.visibleText.slice(0, 1_000)).toBe(visibleText.slice(0, 1_000));
879 expect(metadata.accessibilityTree).toContain("[ref=t3-snapshot-e0]");
880 expect(metadata.accessibilityTree.length).toBeLessThan(accessibilityTree.length);
881 const body = result.content[1];
882 expect(Buffer.byteLength(body?.type === "text" ? body.text : "", "utf8")).toBeLessThanOrEqual(
883 McpHttpServer.MAX_SNAPSHOT_TEXT_BYTES,
884 );
885 }),
886 ).pipe(Effect.provide(layerTest)),
887 );
888
889 it.effect("keeps the snapshot text under the agent's output ceiling", () =>
890 Effect.scoped(
891 Effect.gen(function* () {
892 const pageText = "/Users/theo/Code/project\nClaude, Codex · 79 threads\n".repeat(600);
893 const element = (name: string, index: number) => ({
894 tag: "div",
895 role: "presentation",
896 name,
897 selector: `div:nth-of-type(${index})`,
898 x: 0,
899 y: 0,
900 width: 10,
901 height: 10,
902 });
903 const oversized = {
904 ...snapshotResult,
905 visibleText: pageText,
906 interactiveElements: [
907 element(pageText, 1),
908 element(pageText, 2),
909 element(pageText, 3),
910 element("Continue", 4),
911 ],
912 accessibilityTree: { nodes: Array.from({ length: 2_000 }, (_, i) => ({ nodeId: `${i}` })) },
913 consoleEntries: Array.from({ length: 100 }, (_, i) => ({
914 level: "log",
915 text: `entry ${i}`,
916 timestamp: "t",
917 })),
918 };
919 yield* serveSnapshots("mcp-bounded-client", oversized);
920
921 const snapshot = yield* callSnapshot({ includeImage: false });
922
923 expect(snapshot.isError).toBe(false);
924 const [identity, text, notice] = snapshot.content;
925 expect(identity?.type === "text" ? decodeJsonText(identity.text) : null).toEqual({
926 url: oversized.url,
927 });
928 expect(text?.type).toBe("text");
929 const body = text?.type === "text" ? text.text : "";
930 expect(Buffer.byteLength(body, "utf8")).toBeLessThanOrEqual(
931 McpHttpServer.MAX_SNAPSHOT_TEXT_BYTES,
932 );
933 const parsed = decodeJsonText(body) as {
934 readonly accessibilityTree?: unknown;
935 readonly visibleText: string;
936 readonly interactiveElements: ReadonlyArray<{ readonly name: string }>;
937 readonly consoleEntries: ReadonlyArray<{ readonly text: string }>;
938 };
939 expect(parsed.accessibilityTree).toBeUndefined();
940 expect(parsed.visibleText.length).toBeLessThanOrEqual(8_001);
941 expect(parsed.interactiveElements).toHaveLength(4);
942 expect(parsed.interactiveElements[0]?.name.length).toBeLessThanOrEqual(201);
943 expect(parsed.interactiveElements[3]?.name).toBe("Continue");
944 expect(parsed.consoleEntries).toHaveLength(40);
945 expect(parsed.consoleEntries[0]?.text).toBe("entry 60");
946 expect(notice?.type === "text" ? notice.text : "").toContain("accessibilityTree");
947 expect(notice?.type === "text" ? notice.text : "").toContain("60 older console entries");
948 expect(snapshot.structuredContent).toEqual({
949 ...parsed,
950 omitted: expect.arrayContaining(["60 older console entries"]),
951 });
952 }),
953 ).pipe(Effect.provide(layerTest)),
954 );
955
956 // regression: #10501 keep preview snapshots usable by the agent
957 it.effect("bounds the snapshot text even when nothing but logs and the title are large", () =>
958 Effect.scoped(
959 Effect.gen(function* () {
960 const oversized = {
961 ...snapshotResult,
962 title: `t${"😀".repeat(35_000)}`,
963 interactiveElements: [],
964 consoleEntries: [{ level: "log", text: `x${"😀".repeat(35_000)}`, timestamp: "t" }],
965 };
966 yield* serveSnapshots("mcp-bounded-logs-client", oversized);
967
968 const snapshot = yield* callSnapshot({ includeImage: false });
969
970 const [, text] = snapshot.content;
971 const body = text?.type === "text" ? text.text : "";
972 expect(Buffer.byteLength(body, "utf8")).toBeLessThanOrEqual(
973 McpHttpServer.MAX_SNAPSHOT_TEXT_BYTES,
974 );
975 const parsed = decodeJsonText(body) as {
976 readonly title: string;
977 readonly consoleEntries: ReadonlyArray<{ readonly text: string }>;
978 };
979 expect(parsed.title.isWellFormed()).toBe(true);
980 expect(parsed.title.length).toBe(2_048);
981 expect(parsed.consoleEntries[0]?.text.isWellFormed()).toBe(true);
982 expect(parsed.consoleEntries[0]?.text.length).toBe(500);
983 const notice = snapshot.content[2];
984 const noticeText = notice?.type === "text" ? notice.text : "";
985 expect(noticeText).toContain("url or title after 2048 characters");
986 expect(noticeText).toContain("console entries text after 500 characters");
987 }),
988 ).pipe(Effect.provide(layerTest)),
989 );
990
991 // regression: #13558 preview snapshots overflowed the agent's tool output
992 it.effect("bounds page text made of wide characters before dropping locators", () =>
993 Effect.scoped(
994 Effect.gen(function* () {
995 yield* serveSnapshots("mcp-wide-text-client", {
996 ...snapshotResult,
997 visibleText: "界".repeat(9_000),
998 interactiveElements: Array.from({ length: 20 }, (_, i) => ({
999 tag: "button",
1000 role: "button",
1001 name: `Button ${i}`,
1002 selector: `#button-${i}`,
1003 x: 0,
1004 y: 0,
1005 width: 10,
1006 height: 10,
1007 })),
1008 });
1009
1010 const snapshot = yield* callSnapshot({ includeImage: false });
1011
1012 const [, text, notice] = snapshot.content;
1013 const body = text?.type === "text" ? text.text : "";
1014 expect(Buffer.byteLength(body, "utf8")).toBeLessThanOrEqual(
1015 McpHttpServer.MAX_SNAPSHOT_TEXT_BYTES,
1016 );
1017 const parsed = decodeJsonText(body) as {
1018 readonly visibleText: string;
1019 readonly interactiveElements: ReadonlyArray<unknown>;
1020 };
1021 expect(parsed.visibleText).toMatch(/^界+…$/);
1022 expect(parsed.interactiveElements).toHaveLength(20);
1023 expect(notice?.type === "text" ? notice.text : "").toContain(
1024 "visibleText after 4000 characters",
1025 );
1026 }),
1027 ).pipe(Effect.provide(layerTest)),
1028 );
1029
1030 it.effect("terminates HTTP MCP sessions with DELETE", () =>
1031 Effect.scoped(
1032 Effect.gen(function* () {
1033 const token = "providerTokenWithoutDots";
1034 const scope: McpInvocationContext.McpInvocationScope = {
1035 environmentId,
1036 requestNamespace: "provider-session",
1037 thread: {
1038 threadId: ThreadId.make("thread-provider"),
1039 providerSessionId: "provider-session",
1040 providerInstanceId: ProviderInstanceId.make("codex"),
1041 },
1042 client: undefined,
1043 capabilities: new Set(["orchestration"]),
1044 issuedAt: 1,
1045 };
1046 const layerServer = McpHttpServer.layerMcpTransport(Layer.empty).pipe(
1047 Layer.provide(ServerSettings.layerTest()),
1048 Layer.provide(
1049 Layer.mock(McpSessionRegistry.McpSessionRegistry)({
1050 resolve: (presented) =>
1051 Effect.succeed(
1052 presented === token
1053 ? (scope as McpInvocationContext.McpThreadInvocationScope)
1054 : undefined,
1055 ),
1056 }),
1057 ),
1058 );
1059 yield* HttpRouter.serve(layerServer, {
1060 disableListenLog: true,
1061 disableLogger: true,
1062 }).pipe(Layer.build);
1063 const httpClient = (yield* HttpClient.HttpClient).pipe(
1064 HttpClient.mapRequest(HttpClientRequest.bearerToken(token)),
1065 );
1066
1067 const initializeResponse = yield* httpClient.post("/mcp", {
1068 headers: { accept: "application/json, text/event-stream" },
1069 body: HttpBody.text(
1070 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"mcp-test","version":"1.0.0"}}}`,
1071 "application/json",
1072 ),
1073 });
1074 const sessionId = initializeResponse.headers["mcp-session-id"];
1075 expect(initializeResponse.status).toBe(200);
1076 expect(sessionId).not.toBeNull();
1077
1078 const missingSessionResponse = yield* httpClient.del("/mcp");
1079 expect(missingSessionResponse.status).toBe(400);
1080
1081 const unknownSessionResponse = yield* httpClient.del("/mcp", {
1082 headers: { "mcp-session-id": "unknown-session" },
1083 });
1084 expect(unknownSessionResponse.status).toBe(404);
1085
1086 const terminateResponse = yield* httpClient.del("/mcp", {
1087 headers: { "mcp-session-id": sessionId! },
1088 });
1089 expect(terminateResponse.status).toBe(204);
1090
1091 const reusedSessionResponse = yield* httpClient.post("/mcp", {
1092 headers: {
1093 accept: "application/json, text/event-stream",
1094 "mcp-session-id": sessionId!,
1095 },
1096 body: HttpBody.text(
1097 `{"jsonrpc":"2.0","id":2,"method":"ping","params":{}}`,
1098 "application/json",
1099 ),
1100 });
1101 expect(reusedSessionResponse.status).toBe(404);
1102 }),
1103 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
1104 );
1105
1106 it.effect("answers 2026-07-28 discovery and keeps 2025-06-18 as the initialize fallback", () =>
1107 Effect.scoped(
1108 Effect.gen(function* () {
1109 const token = "providerTokenWithoutDots";
1110 const scope: McpInvocationContext.McpInvocationScope = {
1111 environmentId,
1112 requestNamespace: "provider-session",
1113 thread: {
1114 threadId: ThreadId.make("thread-provider"),
1115 providerSessionId: "provider-session",
1116 providerInstanceId: ProviderInstanceId.make("codex"),
1117 },
1118 client: undefined,
1119 capabilities: new Set(["orchestration"]),
1120 issuedAt: 1,
1121 };
1122 const ProbeToolkit = Toolkit.make(
1123 Tool.make("probe", {
1124 description: "Reports success.",
1125 success: Schema.Struct({ ok: Schema.Boolean }),
1126 }),
1127 );
1128 const layerServer = McpHttpServer.layerMcpTransport(
1129 McpHttpServer.toolkitRegistration(
1130 ProbeToolkit,
1131 McpToolAccess.toLayer(ProbeToolkit, {
1132 probe: McpToolAccess.reads(() => Effect.succeed({ ok: true })),
1133 }),
1134 ),
1135 ).pipe(
1136 Layer.provide(ServerSettings.layerTest()),
1137 Layer.provide(
1138 Layer.mock(McpSessionRegistry.McpSessionRegistry)({
1139 resolve: (presented) =>
1140 Effect.succeed(
1141 presented === token
1142 ? (scope as McpInvocationContext.McpThreadInvocationScope)
1143 : undefined,
1144 ),
1145 }),
1146 ),
1147 );
1148 yield* HttpRouter.serve(layerServer, {
1149 disableListenLog: true,
1150 disableLogger: true,
1151 }).pipe(Layer.build);
1152 const httpClient = (yield* HttpClient.HttpClient).pipe(
1153 HttpClient.mapRequest(HttpClientRequest.bearerToken(token)),
1154 );
1155
1156 const discoverResponse = yield* httpClient.post("/mcp", {
1157 headers: {
1158 accept: "application/json, text/event-stream",
1159 "mcp-method": "server/discover",
1160 "mcp-protocol-version": "2026-07-28",
1161 },
1162 body: HttpBody.text(
1163 `{"jsonrpc":"2.0","id":1,"method":"server/discover","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{},"io.modelcontextprotocol/clientInfo":{"name":"mcp-test","version":"1.0.0"}}}}`,
1164 "application/json",
1165 ),
1166 });
1167 expect(discoverResponse.status).toBe(200);
1168 const discovered = (yield* discoverResponse.json) as {
1169 result: { supportedVersions: ReadonlyArray<string> };
1170 };
1171 expect(discovered.result.supportedVersions).toEqual(
1172 expect.arrayContaining(["2026-07-28", "2025-06-18"]),
1173 );
1174
1175 const toolsResponse = yield* httpClient.post("/mcp", {
1176 headers: {
1177 accept: "application/json, text/event-stream",
1178 "mcp-method": "tools/list",
1179 "mcp-protocol-version": "2026-07-28",
1180 },
1181 body: HttpBody.text(
1182 JSON.stringify({
1183 jsonrpc: "2.0",
1184 id: 3,
1185 method: "tools/list",
1186 params: {
1187 _meta: {
1188 "io.modelcontextprotocol/protocolVersion": "2026-07-28",
1189 "io.modelcontextprotocol/clientCapabilities": {},
1190 "io.modelcontextprotocol/clientInfo": { name: "mcp-test", version: "1.0.0" },
1191 },
1192 },
1193 }),
1194 "application/json",
1195 ),
1196 });
1197 expect(toolsResponse.status).toBe(200);
1198 const tools = (yield* toolsResponse.json) as {
1199 error?: unknown;
1200 result: { tools: ReadonlyArray<{ name: string }> };
1201 };
1202 expect(tools.error).toBeUndefined();
1203 expect(tools.result.tools).toEqual(
1204 expect.arrayContaining([expect.objectContaining({ name: "probe" })]),
1205 );
1206
1207 // The Go MCP SDK sends this without request metadata, though 2026-07-28 does not define it.
1208 const rootsChanged = (
1209 client: HttpClient.HttpClient,
1210 message: object = {},
1211 headers: Record<string, string> = {},
1212 ) =>
1213 client.post("/mcp", {
1214 headers: {
1215 accept: "application/json, text/event-stream",
1216 "mcp-method": "notifications/roots/list_changed",
1217 "mcp-protocol-version": "2026-07-28",
1218 ...headers,
1219 },
1220 body: HttpBody.text(
1221 JSON.stringify({
1222 jsonrpc: "2.0",
1223 method: "notifications/roots/list_changed",
1224 params: {},
1225 ...message,
1226 }),
1227 "application/json",
1228 ),
1229 });
1230 const acknowledged = yield* rootsChanged(httpClient);
1231 expect(acknowledged.status).toBe(202);
1232 expect(yield* acknowledged.text).toBe("");
1233 expect((yield* rootsChanged(yield* HttpClient.HttpClient)).status).toBe(401);
1234 expect((yield* rootsChanged(httpClient, { id: 7 })).status).toBe(400);
1235 expect((yield* rootsChanged(httpClient, {}, { origin: "https://example.com" })).status).toBe(
1236 403,
1237 );
1238
1239 const initializeResponse = yield* httpClient.post("/mcp", {
1240 headers: { accept: "application/json, text/event-stream" },
1241 body: HttpBody.text(
1242 `{"jsonrpc":"2.0","id":2,"method":"initialize","params":{"protocolVersion":"2099-01-01","capabilities":{},"clientInfo":{"name":"mcp-test","version":"1.0.0"}}}`,
1243 "application/json",
1244 ),
1245 });
1246 expect(initializeResponse.status).toBe(200);
1247 const initialized = (yield* initializeResponse.json) as {
1248 result: { protocolVersion: string };
1249 };
1250 expect(initialized.result.protocolVersion).toBe("2025-06-18");
1251 }),
1252 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
1253 );
1254
1255 it.effect("admits provider and OAuth client credentials and points only clients at OAuth", () =>
1256 Effect.scoped(
1257 Effect.gen(function* () {
1258 const providerToken = "providerTokenWithoutDots";
1259 const clientToken = "client-payload.client-signature";
1260 const providerScope: McpInvocationContext.McpInvocationScope = {
1261 environmentId,
1262 requestNamespace: "provider-session",
1263 thread: {
1264 threadId: ThreadId.make("thread-provider"),
1265 providerSessionId: "provider-session",
1266 providerInstanceId: ProviderInstanceId.make("codex"),
1267 },
1268 client: undefined,
1269 capabilities: new Set(["orchestration"]),
1270 issuedAt: 1,
1271 };
1272 const clientScope: McpInvocationContext.McpInvocationScope = {
1273 environmentId,
1274 requestNamespace: "client:session-1",
1275 thread: undefined,
1276 client: { sessionId: "session-1", label: "Claude Code", access: "auto" },
1277 capabilities: new Set(["orchestration"]),
1278 issuedAt: 1,
1279 };
1280 const seen: Array<McpInvocationContext.McpInvocationScope> = [];
1281 const ProbeToolkit = Toolkit.make(
1282 Tool.make("probe", {
1283 description: "Reports the caller.",
1284 success: Schema.Struct({ ok: Schema.Boolean }),
1285 failure: OrchestratorMcpFailure,
1286 failureMode: "return",
1287 dependencies: [McpInvocationContext.McpInvocationContext],
1288 }),
1289 );
1290 const serverLayer = McpHttpServer.layerMcpTransport(
1291 McpHttpServer.toolkitRegistration(
1292 ProbeToolkit,
1293 McpToolAccess.toLayer(ProbeToolkit, {
1294 probe: McpToolAccess.reads(() =>
1295 McpInvocationContext.McpInvocationContext.pipe(
1296 Effect.tap((scope) => Effect.sync(() => seen.push(scope))),
1297 Effect.as({ ok: true }),
1298 ),
1299 ),
1300 }),
1301 ),
1302 ).pipe(
1303 Layer.provide(ServerSettings.layerTest()),
1304 Layer.provide(
1305 Layer.mock(McpSessionRegistry.McpSessionRegistry)({
1306 resolve: (token) =>
1307 Effect.succeed(
1308 token === providerToken
1309 ? (providerScope as McpInvocationContext.McpThreadInvocationScope)
1310 : undefined,
1311 ),
1312 }),
1313 ),
1314 Layer.provide(
1315 Layer.succeed(McpHttpServer.McpClientAuthenticator, {
1316 authenticate: (request) =>
1317 Effect.succeed(
1318 request.headers.authorization === `Bearer ${clientToken}` ? clientScope : undefined,
1319 ),
1320 }),
1321 ),
1322 Layer.provide(ServerHttp.layerBrowserApiCors),
1323 Layer.provide(
1324 ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-origin-test-" }).pipe(
1325 Layer.provide(NodeServices.layer),
1326 ),
1327 ),
1328 );
1329 const traced = recordSpans();
1330 yield* HttpRouter.serve(serverLayer, { disableListenLog: true, disableLogger: true }).pipe(
1331 Layer.build,
1332 Effect.withTracer(traced.tracer),
1333 );
1334 const httpClient = yield* HttpClient.HttpClient;
1335 const call = (token: string | undefined) =>
1336 Effect.gen(function* () {
1337 const headers = {
1338 accept: "application/json, text/event-stream",
1339 ...(token === undefined ? {} : { authorization: `Bearer ${token}` }),
1340 };
1341 const initialize = yield* httpClient.post("/mcp", {
1342 headers,
1343 body: HttpBody.text(
1344 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`,
1345 "application/json",
1346 ),
1347 });
1348 if (initialize.status !== 200) return initialize;
1349 return yield* httpClient.post("/mcp", {
1350 headers: {
1351 ...headers,
1352 "mcp-session-id": initialize.headers["mcp-session-id"]!,
1353 "mcp-protocol-version": "2025-06-18",
1354 },
1355 body: HttpBody.text(
1356 `{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"probe","arguments":{}}}`,
1357 "application/json",
1358 ),
1359 });
1360 });
1361
1362 expect((yield* call(providerToken)).status).toBe(200);
1363 // The tool gets its own span, without its arguments, which starts once authentication has ended.
1364 const toolSpan = traced.spans.find((span) => span.name === "mcp.tool.probe");
1365 expect(Object.fromEntries(toolSpan?.attributes ?? [])).toEqual({
1366 "rpc.system": "mcp",
1367 "rpc.method": "tools/call",
1368 "mcp.tool.name": "probe",
1369 });
1370 const authSpan = traced.spans.find(
1371 (span) =>
1372 span.name === "McpHttpServer.authenticateRequest" && span.traceId === toolSpan?.traceId,
1373 );
1374 expect(authSpan).toBeDefined();
1375 expect(traced.order.slice(0, traced.order.indexOf(`start ${toolSpan?.spanId}`))).toContain(
1376 `end ${authSpan?.spanId}`,
1377 );
1378 expect((yield* call(clientToken)).status).toBe(200);
1379 expect(seen.map((scope) => scope.requestNamespace)).toEqual([
1380 "provider-session",
1381 "client:session-1",
1382 ]);
1383
1384 const missing = yield* call(undefined);
1385 expect(missing.status).toBe(401);
1386 expect(missing.headers["www-authenticate"]).toMatch(
1387 /^Bearer resource_metadata="http:\/\/[^"]+\/\.well-known\/oauth-protected-resource\/mcp"$/,
1388 );
1389
1390 const expiredClient = yield* call("stale-payload.stale-signature");
1391 expect(expiredClient.headers["www-authenticate"]).toContain("resource_metadata=");
1392 expect(expiredClient.headers["www-authenticate"]).toContain('error="invalid_token"');
1393
1394 const spansBeforeRejection = traced.spans.length;
1395 const deadProvider = yield* call("deadProviderToken");
1396 expect(deadProvider.status).toBe(401);
1397 expect(deadProvider.headers["www-authenticate"]).toBe('Bearer error="invalid_token"');
1398 // A rejected credential is recorded on the auth span, and nothing is handled.
1399 const rejectedSpans = traced.spans.slice(spansBeforeRejection);
1400 expect(
1401 rejectedSpans
1402 .filter((span) => span.name === "McpHttpServer.authenticateRequest")
1403 .map((span) => span.events.map(([name]) => name)),
1404 ).toEqual([[expect.stringContaining("unknown_or_expired_token")]]);
1405 expect(
1406 rejectedSpans.filter(
1407 (span) => span.name.startsWith("mcp.tool.") || span.name.startsWith("McpServer."),
1408 ),
1409 ).toEqual([]);
1410
1411 // A present, disallowed Origin is refused with 403 before credentials or CORS answer.
1412 const foreignOrigin = (method: "POST" | "OPTIONS", token: string | undefined) =>
1413 httpClient.execute(
1414 HttpClientRequest.make(method)("/mcp", {
1415 headers: {
1416 origin: "https://untrusted.invalid",
1417 accept: "application/json, text/event-stream",
1418 "access-control-request-method": "POST",
1419 ...(token === undefined ? {} : { authorization: `Bearer ${token}` }),
1420 },
1421 ...(method === "POST"
1422 ? {
1423 body: HttpBody.text(
1424 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`,
1425 "application/json",
1426 ),
1427 }
1428 : {}),
1429 }),
1430 );
1431 expect((yield* foreignOrigin("POST", providerToken)).status).toBe(403);
1432 expect((yield* foreignOrigin("POST", undefined)).status).toBe(403);
1433 expect((yield* foreignOrigin("OPTIONS", undefined)).status).toBe(403);
1434 }),
1435 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
1436 );
1437
1438 it.effect("accepts case-insensitive MCP bearer schemes and diagnoses rejected credentials", () => {
1439 const messages: Array<unknown> = [];
1440 const logger = Logger.make(({ message }) => messages.push(message));
1441 const layerAuth = Layer.mergeAll(EnvironmentAuth.layer, McpSessionRegistry.layer).pipe(
1442 Layer.provideMerge(
1443 Layer.mock(ServerEnvironment.ServerEnvironment)({
1444 getEnvironmentId: Effect.succeed(environmentId),
1445 }),
1446 ),
1447 Layer.provideMerge(Sqlite.layerMemory),
1448 Layer.provide(ServerSecretStore.layer),
1449 Layer.provide(ManagedPolicy.layerTest()),
1450 Layer.provideMerge(ServerEnvironment.layerIdentity),
1451 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-auth-header-test-" })),
1452 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
1453 );
1454 return Effect.scoped(
1455 Effect.gen(function* () {
1456 const auth = yield* EnvironmentAuth.EnvironmentAuth;
1457 const registry = yield* McpSessionRegistry.McpSessionRegistry;
1458 const issued = yield* registry.issue({
1459 threadId,
1460 providerInstanceId: ProviderInstanceId.make("codex"),
1461 });
1462 const providerToken = issued.config.authorizationHeader.slice("Bearer ".length);
1463 const oauth = yield* auth.issueMcpClientSession({
1464 label: "MCP header test",
1465 access: "read-only",
1466 peerLink: false,
1467 client: { deviceType: "bot" },
1468 });
1469 yield* HttpRouter.serve(
1470 McpHttpServer.layerMcpTransport(Layer.empty).pipe(
1471 Layer.provide(McpOAuth.layerMcpClientAuthenticator),
1472 Layer.provide(ServerSettings.layerTest()),
1473 ),
1474 { disableListenLog: true, disableLogger: true },
1475 ).pipe(Layer.build);
1476 const httpClient = yield* HttpClient.HttpClient;
1477 const initialize = (authorization?: string) =>
1478 httpClient.post("/mcp", {
1479 headers: {
1480 accept: "application/json, text/event-stream",
1481 ...(authorization === undefined ? {} : { authorization }),
1482 },
1483 body: HttpBody.text(
1484 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"mcp-header-test","version":"1.0.0"}}}`,
1485 "application/json",
1486 ),
1487 });
1488
1489 for (const scheme of ["Bearer", "bearer", "bEaReR"]) {
1490 for (const [kind, token] of [
1491 ["provider", providerToken],
1492 ["OAuth", oauth.token],
1493 ]) {
1494 const response = yield* initialize(`${scheme} ${token}`);
1495 expect.soft(response.status, `${kind} ${scheme}`).toBe(200);
1496 }
1497 }
1498 messages.length = 0;
1499 for (const [authorization, reason] of [
1500 [undefined, "missing_authorization_header"],
1501 [`Basic ${providerToken}`, "unsupported_scheme"],
1502 ["Bearer", "missing_bearer_token"],
1503 ["bEaReR ", "missing_bearer_token"],
1504 [`bearer ${providerToken.toUpperCase()}`, "unknown_or_expired_token"],
1505 [`bEaReR ${oauth.token.toUpperCase()}`, "unknown_or_expired_token"],
1506 ] as const) {
1507 const response = yield* initialize(authorization);
1508 expect(response.status).toBe(401);
1509 expect
1510 .soft(messages.at(-1))
1511 .toEqual(["rejected MCP request with an unusable credential", { reason }]);
1512 const body = yield* response.text;
1513 expect(body).not.toContain(providerToken);
1514 expect(body).not.toContain(oauth.token);
1515 expect(JSON.stringify(response.headers)).not.toContain(providerToken);
1516 expect(JSON.stringify(response.headers)).not.toContain(oauth.token);
1517 }
1518 yield* registry.revokeThread(threadId);
1519 yield* auth.revokeSession(oauth.sessionId);
1520 for (const token of [providerToken, oauth.token]) {
1521 expect((yield* initialize(`bearer ${token}`)).status).toBe(401);
1522 }
1523 expect(JSON.stringify(messages)).not.toContain(providerToken);
1524 expect(JSON.stringify(messages)).not.toContain(oauth.token);
1525 expect(JSON.stringify(messages)).not.toContain(providerToken.toUpperCase());
1526 expect(JSON.stringify(messages)).not.toContain(oauth.token.toUpperCase());
1527 }),
1528 ).pipe(
1529 Effect.provide(
1530 layerAuth.pipe(
1531 Layer.provideMerge(NodeHttpServer.layerTest),
1532 Layer.provideMerge(Logger.layer([logger], { mergeWithExisting: false })),
1533 ),
1534 ),
1535 );
1536 });
1537
1538 it.effect("gives outside clients an upload URL on the origin their request reached", () =>
1539 Effect.scoped(
1540 Effect.gen(function* () {
1541 const token = "outsideClientToken";
1542 const scope: McpInvocationContext.McpInvocationScope = {
1543 environmentId,
1544 requestNamespace: `client:${token}`,
1545 thread: undefined,
1546 client: { sessionId: token, label: "Hosted agent", access: "full-access" },
1547 capabilities: new Set(["orchestration"]),
1548 issuedAt: 1,
1549 };
1550 const serverLayer = McpHttpServer.layerMcpTransport(
1551 McpHttpServer.layerAttachmentToolkit,
1552 ).pipe(
1553 Layer.provide(ServerSettings.layerTest()),
1554 Layer.provide(McpToolAccessTestkit.liveThreadsLayer),
1555 Layer.provide(
1556 Layer.mock(McpSessionRegistry.McpSessionRegistry)({
1557 resolve: () => Effect.undefined,
1558 }),
1559 ),
1560 // Signs in the way an OAuth client such as a hosted ChatGPT app does.
1561 Layer.provide(
1562 Layer.succeed(McpHttpServer.McpClientAuthenticator)({
1563 authenticate: (request) =>
1564 Effect.succeed(
1565 request.headers.authorization === `Bearer ${token}` ? scope : undefined,
1566 ),
1567 }),
1568 ),
1569 Layer.provide(
1570 AssetSigner.layer.pipe(
1571 Layer.provideMerge(ServerSecretStore.layer),
1572 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-upload-" })),
1573 Layer.provideMerge(DocumentText.layer),
1574 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
1575 ),
1576 ),
1577 );
1578 yield* HttpRouter.serve(serverLayer, { disableListenLog: true, disableLogger: true }).pipe(
1579 Layer.build,
1580 );
1581 const httpClient = yield* HttpClient.HttpClient;
1582 const prepareUpload = (proxyHeaders: Record<string, string>) =>
1583 Effect.gen(function* () {
1584 const headers = {
1585 accept: "application/json, text/event-stream",
1586 authorization: `Bearer ${token}`,
1587 ...proxyHeaders,
1588 };
1589 const initialize = yield* httpClient.post("/mcp", {
1590 headers,
1591 body: HttpBody.text(
1592 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`,
1593 "application/json",
1594 ),
1595 });
1596 const response = yield* httpClient.post("/mcp", {
1597 headers: {
1598 ...headers,
1599 "mcp-session-id": initialize.headers["mcp-session-id"]!,
1600 "mcp-protocol-version": "2025-06-18",
1601 },
1602 body: HttpBody.text(
1603 JSON.stringify({
1604 jsonrpc: "2.0",
1605 id: 2,
1606 method: "tools/call",
1607 params: {
1608 name: "t3_attachment_prepare_upload",
1609 arguments: {
1610 upload: {
1611 type: "image",
1612 name: "shot.png",
1613 mimeType: "image/png",
1614 sizeBytes: 6,
1615 },
1616 },
1617 },
1618 }),
1619 "application/json",
1620 ),
1621 });
1622 const body = (yield* response.json) as {
1623 result: { structuredContent: { uploadUrl: string } };
1624 };
1625 return body.result.structuredContent;
1626 });
1627
1628 const direct = yield* prepareUpload({});
1629 const { address } = yield* HttpServer.HttpServer;
1630 if (!NetAddress.isInetAddress(address)) throw new Error("Expected a TCP test server");
1631 expect(new URL(direct.uploadUrl).origin).toBe(`http://127.0.0.1:${address.port}`);
1632
1633 const proxied = yield* prepareUpload({ "x-forwarded-proto": "https" });
1634 expect(new URL(proxied.uploadUrl).protocol).toBe("https:");
1635 }),
1636 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
1637 );
1638
1639 it.effect("hides tools for links and refuses another environment while the beta is off", () =>
1640 Effect.scoped(
1641 Effect.gen(function* () {
1642 const token = "linksToken";
1643 const scope: McpInvocationContext.McpThreadInvocationScope = {
1644 environmentId,
1645 requestNamespace: token,
1646 thread: {
1647 threadId: ThreadId.make("thread-links"),
1648 providerSessionId: token,
1649 providerInstanceId: ProviderInstanceId.make("codex"),
1650 },
1651 client: undefined,
1652 capabilities: new Set(["orchestration"]),
1653 issuedAt: 1,
1654 };
1655 const LinksToolkit = Toolkit.make(
1656 Tool.make("links", {
1657 description: "Lists links.",
1658 success: Schema.Struct({ links: Schema.Number }),
1659 failure: OrchestratorMcpFailure,
1660 failureMode: "return",
1661 }).annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenWhileLinksOff),
1662 Tool.make("where", {
1663 description: "Says where it ran.",
1664 parameters: Schema.Struct({ environmentId: OrchestratorMcpEnvironmentTarget }),
1665 success: Schema.Struct({ ranIn: Schema.String }),
1666 failure: OrchestratorMcpFailure,
1667 failureMode: "return",
1668 }),
1669 );
1670 const settingsContext = yield* Layer.build(ServerSettings.layerTest());
1671 const settings = Context.get(settingsContext, ServerSettings.ServerSettingsService);
1672 const serverLayer = McpHttpServer.layerMcpTransport(
1673 McpHttpServer.toolkitRegistration(
1674 LinksToolkit,
1675 McpToolAccess.toLayer(LinksToolkit, {
1676 links: McpToolAccess.reads(() => Effect.succeed({ links: 0 })),
1677 where: McpToolAccess.reads(() => Effect.succeed({ ranIn: "here" })),
1678 }),
1679 ),
1680 ).pipe(
1681 Layer.provide(Layer.succeedContext(settingsContext)),
1682 Layer.provide(McpToolAccessTestkit.liveThreadsLayer),
1683 Layer.provide(
1684 Layer.mock(McpSessionRegistry.McpSessionRegistry)({
1685 resolve: (presented) => Effect.succeed(presented === token ? scope : undefined),
1686 }),
1687 ),
1688 );
1689 yield* HttpRouter.serve(serverLayer, { disableListenLog: true, disableLogger: true }).pipe(
1690 Layer.build,
1691 );
1692 const httpClient = yield* HttpClient.HttpClient;
1693 const headers = {
1694 accept: "application/json, text/event-stream",
1695 authorization: `Bearer ${token}`,
1696 };
1697 const initialize = yield* httpClient.post("/mcp", {
1698 headers,
1699 body: HttpBody.text(
1700 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`,
1701 "application/json",
1702 ),
1703 });
1704 const rpc = (method: string, params: object) =>
1705 httpClient
1706 .post("/mcp", {
1707 headers: {
1708 ...headers,
1709 "mcp-session-id": initialize.headers["mcp-session-id"]!,
1710 "mcp-protocol-version": "2025-06-18",
1711 },
1712 body: HttpBody.text(
1713 JSON.stringify({ jsonrpc: "2.0", id: 2, method, params }),
1714 "application/json",
1715 ),
1716 })
1717 .pipe(Effect.flatMap((response) => response.json));
1718 const listed = () =>
1719 rpc("tools/list", {}).pipe(
1720 Effect.map((body) =>
1721 (body as { result: { tools: ReadonlyArray<{ name: string }> } }).result.tools.map(
1722 (tool) => tool.name,
1723 ),
1724 ),
1725 );
1726 const ranIn = (where: EnvironmentId) =>
1727 rpc("tools/call", { name: "where", arguments: { environmentId: where } }).pipe(
1728 Effect.map(
1729 (body) =>
1730 (
1731 body as {
1732 result: {
1733 isError?: boolean;
1734 structuredContent?: unknown;
1735 content: ReadonlyArray<{ text: string }>;
1736 };
1737 }
1738 ).result,
1739 ),
1740 );
1741 const elsewhere = EnvironmentId.make("environment-elsewhere");
1742
1743 expect(yield* listed()).toEqual(["where"]);
1744 expect(yield* ranIn(elsewhere)).toMatchObject({
1745 isError: true,
1746 content: [{ text: expect.stringContaining("Linked environments is off on this machine") }],
1747 });
1748 expect((yield* ranIn(environmentId)).structuredContent).toEqual({ ranIn: "here" });
1749
1750 yield* settings.updateSettings({ linkedEnvironmentsEnabled: true });
1751 expect(yield* listed()).toEqual(["links", "where"]);
1752 // On, the call goes on to the forwarding, which this server lacks.
1753 expect(yield* ranIn(elsewhere)).toMatchObject({
1754 isError: true,
1755 content: [{ text: expect.stringContaining("cannot reach linked environments") }],
1756 });
1757 }),
1758 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
1759 );
1760
1761 it.effect(
1762 "lists watch tools only to threads that are not delegated children, and forge tools only where the project has a forge",
1763 () =>
1764 Effect.scoped(
1765 Effect.gen(function* () {
1766 const scopeFor = (
1767 token: string,
1768 subagent: boolean,
1769 ): McpInvocationContext.McpThreadInvocationScope => ({
1770 environmentId,
1771 requestNamespace: token,
1772 thread: {
1773 threadId: ThreadId.make(`thread-${token}`),
1774 providerSessionId: token,
1775 providerInstanceId: ProviderInstanceId.make("codex"),
1776 subagent,
1777 },
1778 client: undefined,
1779 capabilities: new Set(["pull-requests"]),
1780 issuedAt: 1,
1781 });
1782 const scopes = new Map([
1783 ["parentToken", scopeFor("parentToken", false)],
1784 ["childToken", scopeFor("childToken", true)],
1785 ["noForgeToken", scopeFor("noForgeToken", false)],
1786 ]);
1787 const serverLayer = McpHttpServer.layerMcpTransport(
1788 McpHttpServer.layerPullRequestsToolkit,
1789 ).pipe(
1790 Layer.provide(ServerSettings.layerTest()),
1791 Layer.provide(
1792 Layer.mock(McpSessionRegistry.McpSessionRegistry)({
1793 resolve: (token) => Effect.succeed(scopes.get(token)),
1794 }),
1795 ),
1796 Layer.provide(
1797 Layer.mergeAll(
1798 McpToolAccessTestkit.liveThreadsLayer,
1799 Layer.mock(ProjectService.ProjectService)({}),
1800 Layer.mock(PullRequestReviewGuideService.PullRequestReviewGuideService)({}),
1801 Layer.mock(PullRequestService.PullRequestService)({
1802 servesProject: (projectId) => Effect.succeed(projectId !== "project-noForgeToken"),
1803 }),
1804 Layer.mock(GitManager.GitManager)({}),
1805 Layer.mock(Orchestrator.OrchestratorV2)({}),
1806 Layer.mock(ProjectionStore.ProjectionStoreV2)({
1807 getThreadShell: (threadId) =>
1808 Effect.succeed({
1809 projectId: ProjectId.make(threadId.replace("thread-", "project-")),
1810 } as never),
1811 }),
1812 NodeServices.layer,
1813 NodeCrypto.layer,
1814 ),
1815 ),
1816 );
1817 yield* HttpRouter.serve(serverLayer, { disableListenLog: true, disableLogger: true }).pipe(
1818 Layer.build,
1819 );
1820 const httpClient = yield* HttpClient.HttpClient;
1821 const listedTools = (token: string) =>
1822 Effect.gen(function* () {
1823 const headers = {
1824 accept: "application/json, text/event-stream",
1825 authorization: `Bearer ${token}`,
1826 };
1827 const initialize = yield* httpClient.post("/mcp", {
1828 headers,
1829 body: HttpBody.text(
1830 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`,
1831 "application/json",
1832 ),
1833 });
1834 const listed = yield* httpClient.post("/mcp", {
1835 headers: {
1836 ...headers,
1837 "mcp-session-id": initialize.headers["mcp-session-id"]!,
1838 "mcp-protocol-version": "2025-06-18",
1839 },
1840 body: HttpBody.text(
1841 `{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}`,
1842 "application/json",
1843 ),
1844 });
1845 const body = (yield* listed.json) as {
1846 readonly result: { readonly tools: ReadonlyArray<{ readonly name: string }> };
1847 };
1848 return body.result.tools.map((tool) => tool.name);
1849 });
1850
1851 const parentTools = yield* listedTools("parentToken");
1852 const childTools = yield* listedTools("childToken");
1853 expect(parentTools).toEqual(
1854 expect.arrayContaining([
1855 "link_pull_request",
1856 "watch_pull_request",
1857 "unwatch_pull_request",
1858 ]),
1859 );
1860 expect(childTools).toContain("link_pull_request");
1861 expect(childTools).not.toContain("watch_pull_request");
1862 expect(childTools).not.toContain("unwatch_pull_request");
1863 expect(parentTools).toEqual(
1864 expect.arrayContaining([
1865 "pull_request_read",
1866 "pull_request_review",
1867 "pull_request_merge",
1868 "ci_logs",
1869 "ci_rerun",
1870 ]),
1871 );
1872 const noForgeTools = yield* listedTools("noForgeToken");
1873 expect(noForgeTools).toEqual(
1874 expect.arrayContaining(["link_pull_request", "watch_pull_request"]),
1875 );
1876 expect(
1877 noForgeTools.filter((name) => name.startsWith("pull_request_") || name.startsWith("ci_")),
1878 ).toEqual([]);
1879 }),
1880 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
1881 );
1882
1883 it.effect(
1884 "narrows an OAuth client's modes to the T3-Mode-Limit it sends, and never widens them",
1885 () =>
1886 Effect.scoped(
1887 Effect.gen(function* () {
1888 const clientToken = "client-payload.client-signature";
1889 const clientScope: McpInvocationContext.McpInvocationScope = {
1890 environmentId,
1891 requestNamespace: "client:linked",
1892 thread: undefined,
1893 client: { sessionId: "linked", label: "T3 Code · laptop", access: "auto" },
1894 capabilities: new Set(["orchestration"]),
1895 issuedAt: 1,
1896 };
1897 // Starts a thread at the modes the gate hands it, so the outcome is those modes.
1898 const StartsToolkit = Toolkit.make(
1899 Tool.make("starts", {
1900 description: "Reports the modes a started thread would run with.",
1901 parameters: Schema.Struct({
1902 runtimeMode: Schema.optional(RuntimeMode),
1903 interactionMode: Schema.optional(ProviderInteractionMode),
1904 }),
1905 success: Schema.Struct({ modes: Schema.String }),
1906 failure: OrchestratorMcpFailure,
1907 failureMode: "return",
1908 dependencies: [
1909 McpInvocationContext.McpInvocationContext,
1910 ThreadManagementService.ThreadManagementService,
1911 ],
1912 }),
1913 );
1914 const serverLayer = McpHttpServer.layerMcpTransport(
1915 McpHttpServer.toolkitRegistration(
1916 StartsToolkit,
1917 McpToolAccess.toLayer(StartsToolkit, {
1918 starts: McpToolAccess.startsThreads(
1919 (input) => input,
1920 (_, modes) =>
1921 Effect.succeed({ modes: `${modes.runtimeMode}/${modes.interactionMode}` }),
1922 "stamped",
1923 ),
1924 }),
1925 ),
1926 ).pipe(
1927 Layer.provide(ServerSettings.layerTest()),
1928 Layer.provide(McpToolAccessTestkit.liveThreadsLayer),
1929 Layer.provide(
1930 Layer.mock(McpSessionRegistry.McpSessionRegistry)({
1931 resolve: () => Effect.undefined,
1932 }),
1933 ),
1934 Layer.provide(
1935 Layer.succeed(McpHttpServer.McpClientAuthenticator, {
1936 authenticate: (request) =>
1937 Effect.succeed(
1938 request.headers.authorization === `Bearer ${clientToken}`
1939 ? clientScope
1940 : undefined,
1941 ),
1942 }),
1943 ),
1944 );
1945 yield* HttpRouter.serve(serverLayer, { disableListenLog: true, disableLogger: true }).pipe(
1946 Layer.build,
1947 );
1948 const httpClient = yield* HttpClient.HttpClient;
1949 const decodeOutcome = Schema.decodeUnknownEffect(
1950 Schema.fromJsonString(
1951 Schema.Struct({
1952 result: Schema.Struct({
1953 content: Schema.Array(Schema.Struct({ text: Schema.String })),
1954 }),
1955 }),
1956 ),
1957 );
1958 const decodeText = Schema.decodeUnknownEffect(
1959 Schema.fromJsonString(
1960 Schema.Union([
1961 Schema.Struct({ modes: Schema.String }),
1962 Schema.Struct({ code: Schema.String }),
1963 ]),
1964 ),
1965 );
1966 /** Starts a thread as the client, with `limit` as T3-Mode-Limit; the HTTP status or the outcome. */
1967 const start = (limit: string | undefined, args: Record<string, string> = {}) =>
1968 Effect.gen(function* () {
1969 const headers = {
1970 accept: "application/json, text/event-stream",
1971 authorization: `Bearer ${clientToken}`,
1972 ...(limit === undefined ? {} : { "t3-mode-limit": limit }),
1973 };
1974 const initialize = yield* httpClient.post("/mcp", {
1975 headers,
1976 body: HttpBody.text(
1977 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`,
1978 "application/json",
1979 ),
1980 });
1981 if (initialize.status !== 200) return initialize.status;
1982 const response = yield* httpClient.post("/mcp", {
1983 headers: {
1984 ...headers,
1985 "mcp-session-id": initialize.headers["mcp-session-id"]!,
1986 "mcp-protocol-version": "2025-06-18",
1987 },
1988 body: HttpBody.text(
1989 JSON.stringify({
1990 jsonrpc: "2.0",
1991 id: 2,
1992 method: "tools/call",
1993 params: { name: "starts", arguments: args },
1994 }),
1995 "application/json",
1996 ),
1997 });
1998 const body = yield* decodeOutcome(yield* response.text);
1999 const outcome = yield* decodeText(
2000 body.result.content.map((part) => part.text).join(""),
2001 );
2002 return "code" in outcome ? outcome.code : outcome.modes;
2003 });
2004
2005 // Approved for auto: without the header the client keeps its ceiling.
2006 expect(yield* start(undefined)).toBe("auto/default");
2007 // The header narrows both modes, and asking above it is refused.
2008 expect(yield* start("approval-required/plan")).toBe("approval-required/plan");
2009 expect(yield* start("approval-required/plan", { runtimeMode: "auto" })).toBe(
2010 "runtime_mode_escalation_denied",
2011 );
2012 expect(yield* start("auto-accept-edits/plan", { interactionMode: "default" })).toBe(
2013 "interaction_mode_escalation_denied",
2014 );
2015 // A broader header changes nothing: the approved ceiling still holds.
2016 expect(yield* start("full-access/default")).toBe("auto/default");
2017 expect(yield* start("full-access/default", { runtimeMode: "full-access" })).toBe(
2018 "runtime_mode_escalation_denied",
2019 );
2020 // A malformed header is refused before anything runs.
2021 expect(yield* start("auto")).toBe(400);
2022 expect(yield* start("auto/default/extra")).toBe(400);
2023 expect(yield* start("root/default")).toBe(400);
2024 }),
2025 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
2026 );
2027
2028 it.effect("lists optional tools to a deferring client only after tool_search loads them", () =>
2029 Effect.scoped(
2030 Effect.gen(function* () {
2031 const scopeFor = (token: string): McpInvocationContext.McpThreadInvocationScope => ({
2032 environmentId,
2033 requestNamespace: token,
2034 thread: {
2035 threadId: ThreadId.make(`thread-${token}`),
2036 providerSessionId: token,
2037 providerInstanceId: ProviderInstanceId.make("copilot"),
2038 },
2039 client: undefined,
2040 capabilities: new Set(["orchestration"]),
2041 issuedAt: 1,
2042 });
2043 const scopes = new Map([
2044 ["deferringToken", scopeFor("deferringToken")],
2045 ["otherToken", scopeFor("otherToken")],
2046 ]);
2047 const tool = (name: string, description: string) =>
2048 Tool.make(name, {
2049 description,
2050 success: Schema.Struct({}),
2051 failure: OrchestratorMcpFailure,
2052 failureMode: "return",
2053 });
2054 const OptionalToolkit = Toolkit.make(
2055 tool("delegate_task", "Delegates a task."),
2056 tool("preview_open", "Opens a browser preview."),
2057 tool("schedule_task", "Schedules a task."),
2058 );
2059 const reads = McpToolAccess.reads(() => Effect.succeed({}));
2060 const serverLayer = McpHttpServer.layerMcpTransport(
2061 Layer.mergeAll(
2062 McpHttpServer.toolkitRegistration(
2063 OptionalToolkit,
2064 McpToolAccess.toLayer(OptionalToolkit, {
2065 delegate_task: reads,
2066 preview_open: reads,
2067 schedule_task: reads,
2068 }),
2069 ),
2070 McpHttpServer.layerToolSearch,
2071 ),
2072 ).pipe(
2073 Layer.provide(ServerSettings.layerTest()),
2074 Layer.provide(McpToolAccessTestkit.liveThreadsLayer),
2075 Layer.provide(
2076 Layer.mock(McpSessionRegistry.McpSessionRegistry)({
2077 resolve: (token) => Effect.succeed(scopes.get(token)),
2078 }),
2079 ),
2080 );
2081 yield* HttpRouter.serve(serverLayer, { disableListenLog: true, disableLogger: true }).pipe(
2082 Layer.build,
2083 );
2084 const httpClient = yield* HttpClient.HttpClient;
2085 const session = (token: string, deferred: boolean) =>
2086 Effect.gen(function* () {
2087 const headers = {
2088 accept: "application/json, text/event-stream",
2089 authorization: `Bearer ${token}`,
2090 ...(deferred ? { "t3-tool-exposure": "deferred" } : {}),
2091 };
2092 const initialize = yield* httpClient.post("/mcp", {
2093 headers,
2094 body: HttpBody.text(
2095 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`,
2096 "application/json",
2097 ),
2098 });
2099 const rpc = (method: string, params: object) =>
2100 httpClient
2101 .post("/mcp", {
2102 headers: {
2103 ...headers,
2104 "mcp-session-id": initialize.headers["mcp-session-id"]!,
2105 "mcp-protocol-version": "2025-06-18",
2106 },
2107 body: HttpBody.text(
2108 JSON.stringify({ jsonrpc: "2.0", id: 2, method, params }),
2109 "application/json",
2110 ),
2111 })
2112 .pipe(
2113 Effect.flatMap((response) => response.text),
2114 // tool_search answers over SSE, after its list_changed notification.
2115 Effect.map((text): unknown =>
2116 text
2117 .split("\n")
2118 .filter((line) => line.startsWith("data: ") || line.startsWith("{"))
2119 .map((line) => JSON.parse(line.replace(/^data: /u, "")) as { id?: number })
2120 .find((message) => message.id === 2),
2121 ),
2122 );
2123 return {
2124 listed: rpc("tools/list", {}).pipe(
2125 Effect.map((body) =>
2126 (body as { result: { tools: ReadonlyArray<{ name: string }> } }).result.tools
2127 .map((listed) => listed.name)
2128 .sort(),
2129 ),
2130 ),
2131 call: (name: string, args: object) =>
2132 rpc("tools/call", { name, arguments: args }).pipe(
2133 Effect.map((body) => (body as { result: { structuredContent?: unknown } }).result),
2134 ),
2135 };
2136 });
2137
2138 const deferring = yield* session("deferringToken", true);
2139 const other = yield* session("otherToken", false);
2140 expect(yield* deferring.listed).toEqual(["delegate_task", "tool_search"]);
2141 expect(yield* other.listed).toEqual(["delegate_task", "preview_open", "schedule_task"]);
2142 // Unlisted tools stay callable.
2143 expect((yield* deferring.call("schedule_task", {})).structuredContent).toEqual({});
2144
2145 expect(
2146 (yield* deferring.call("tool_search", { query: "browser" })).structuredContent,
2147 ).toEqual({ tools: [{ name: "preview_open", description: "Opens a browser preview." }] });
2148 expect(yield* deferring.listed).toEqual(["delegate_task", "preview_open", "tool_search"]);
2149 expect(yield* other.listed).toEqual(["delegate_task", "preview_open", "schedule_task"]);
2150 }),
2151 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
2152 );