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

McpHttpServer.test.ts

764 lines29.2 KB

1import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
2import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
3import { expect, it } from "@effect/vitest";
4import { NodeHttpServer } from "@effect/platform-node";
5import * as NodeServices from "@effect/platform-node/NodeServices";
6import {
7 EnvironmentId,
8 OrchestratorMcpFailure,
9 PreviewTabId,
10 ProviderInstanceId,
11 ThreadId,
12} from "@t3tools/contracts";
13import * as Deferred from "effect/Deferred";
14import * as Effect from "effect/Effect";
15import * as Layer from "effect/Layer";
16import * as Schema from "effect/Schema";
17import * as Stream from "effect/Stream";
18import { McpSchema, McpServer, Tool, Toolkit } from "effect/ai";
19import { HttpBody, HttpClient, HttpClientRequest, HttpRouter } from "effect/http";
20​
21import * as ProjectService from "../project/ProjectService.ts";
22import * as PullRequestReviewGuideService from "../pullRequest/PullRequestReviewGuideService.ts";
23import * as ServerConfig from "../config.ts";
24import * as McpHttpServer from "./McpHttpServer.ts";
25import * as McpToolAccess from "./McpToolAccess.ts";
26import * as McpToolAccessTestkit from "./McpToolAccess.testkit.ts";
27import * as McpInvocationContext from "./McpInvocationContext.ts";
28import * as McpSessionRegistry from "./McpSessionRegistry.ts";
29import * as OrchestratorMcpService from "./OrchestratorMcpService.ts";
30import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
31import { OrchestratorToolkit } from "./toolkits/orchestrator/tools.ts";
32import { ProjectToolkit } from "./toolkits/project/tools.ts";
33​
34const environmentId = EnvironmentId.make("environment-mcp-test");
35const threadId = ThreadId.make("thread-mcp-test");
36const alternateTabId = PreviewTabId.make("tab-mcp-alternate");
37const decodeJsonText = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
38const invocation = {
39 environmentId,
40 requestNamespace: "provider-session-mcp-test",
41 thread: {
42 threadId,
43 providerSessionId: "provider-session-mcp-test",
44 providerInstanceId: ProviderInstanceId.make("codex"),
45 },
46 client: undefined,
47 capabilities: new Set(["preview"] as const),
48 issuedAt: 1,
49};
50const client = McpSchema.McpServerClient.of({
51 clientId: 1,
52 clientCapabilities: {},
53 clientInfo: { name: "mcp-test", version: "1.0.0" },
54 protocolVersion: "2025-06-18",
55 initializePayload: {
56 protocolVersion: "2025-06-18",
57 capabilities: {},
58 clientInfo: { name: "mcp-test", version: "1.0.0" },
59 },
60 getClient: Effect.die("unused"),
61});
62const layerTest = McpHttpServer.layerPreviewToolkit.pipe(
63 Layer.provideMerge(McpServer.McpServer.layer),
64 Layer.provideMerge(McpToolAccessTestkit.liveThreadsLayer),
65 Layer.provideMerge(PreviewAutomationBroker.layer),
66 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-http-server-test-" })),
67 Layer.provideMerge(NodeServices.layer),
68);
69const layerPullRequestsTest = McpHttpServer.layerPullRequestsToolkit.pipe(
70 Layer.provideMerge(McpServer.McpServer.layer),
71 Layer.provideMerge(McpToolAccessTestkit.liveThreadsLayer),
72 Layer.provide(
73 Layer.mergeAll(
74 Layer.mock(ProjectService.ProjectService)({}),
75 Layer.mock(PullRequestReviewGuideService.PullRequestReviewGuideService)({}),
76 Layer.mock(Orchestrator.OrchestratorV2)({}),
77 Layer.mock(ProjectionStore.ProjectionStoreV2)({}),
78 NodeServices.layer,
79 ),
80 ),
81);
82​
83const snapshotResult = {
84 url: "http://example.test/",
85 title: "Example",
86 loading: false,
87 visibleText: "Example",
88 interactiveElements: [],
89 accessibilityTree: {},
90 consoleEntries: [],
91 networkEntries: [],
92 actionTimeline: [],
93 screenshot: {
94 mimeType: "image/png",
95 data: Buffer.from("png").toString("base64"),
96 width: 10,
97 height: 5,
98 },
99};
100​
101const serveSnapshots = (clientId: string, result: unknown) =>
102 Effect.gen(function* () {
103 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
104 const connected = yield* Deferred.make<void>();
105 const inputs: Array<unknown> = [];
106 const events = yield* broker.connect({ clientId, environmentId });
107 yield* Stream.runForEach(events, (event) => {
108 if (event.type === "connected") return Deferred.succeed(connected, undefined);
109 inputs.push(event.request.input);
110 return broker.respond({
111 clientId,
112 connectionId: event.connectionId,
113 requestId: event.request.requestId,
114 ok: true,
115 result,
116 });
117 }).pipe(Effect.forkScoped);
118 yield* Deferred.await(connected);
119 return inputs;
120 });
121​
122const callTool = (name: string, args: Record<string, unknown>) =>
123 Effect.gen(function* () {
124 const server = yield* McpServer.McpServer;
125 return yield* server
126 .callTool({ name, arguments: args })
127 .pipe(
128 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
129 Effect.provideService(McpSchema.McpServerClient, client),
130 );
131 });
132​
133const callSnapshot = (args: Record<string, unknown>) => callTool("preview_snapshot", args);
134​
135// Real tool definitions with handlers that record what they decoded.
136const layerRecordingTools = (calls: Array<unknown>) => {
137 const RecordingToolkit = Toolkit.make(
138 OrchestratorToolkit.tools.delegate_task,
139 OrchestratorToolkit.tools.t3_thread_read,
140 OrchestratorToolkit.tools.t3_thread_wait,
141 ProjectToolkit.tools.t3_project_update,
142 );
143 const record = McpToolAccess.reads((params: unknown) =>
144 Effect.sync(() => calls.push(params)).pipe(
145 Effect.andThen(
146 Effect.fail(new OrchestratorMcpFailure({ code: "thread_not_found", message: "Recorded." })),
147 ),
148 ),
149 );
150 return McpHttpServer.toolkitRegistration(
151 RecordingToolkit,
152 McpToolAccess.toLayer(RecordingToolkit, {
153 delegate_task: record,
154 t3_thread_read: record,
155 t3_thread_wait: record,
156 t3_project_update: record,
157 }),
158 ).pipe(
159 Layer.provideMerge(McpServer.McpServer.layer),
160 Layer.provide(
161 Layer.mergeAll(
162 McpToolAccessTestkit.liveThreadsLayer,
163 Layer.mock(OrchestratorMcpService.OrchestratorMcpService)({}),
164 Layer.mock(ProjectService.ProjectService)({}),
165 NodeServices.layer,
166 ),
167 ),
168 );
169};
170​
171it.effect.each([{}, { includeImage: false }])(
172 "returns bounded structural preview snapshot failures %#",
173 (input) =>
174 Effect.scoped(
175 Effect.gen(function* () {
176 const server = yield* McpServer.McpServer;
177 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
178 const events = yield* broker.connect({
179 clientId: "mcp-failure-client",
180 environmentId,
181 });
182 yield* Stream.runForEach(events, (event) =>
183 event.type === "connected"
184 ? Effect.void
185 : broker.respond({
186 clientId: "mcp-failure-client",
187 connectionId: event.connectionId,
188 requestId: event.request.requestId,
189 ok: false,
190 error: {
191 _tag: "PreviewAutomationExecutionError",
192 message: "sensitive renderer failure",
193 detail: { consoleOutput: "sensitive browser output" },
194 },
195 }),
196 ).pipe(Effect.forkScoped);
197 yield* Effect.yieldNow;
198​
199 const snapshot = yield* server
200 .callTool({ name: "preview_snapshot", arguments: input })
201 .pipe(
202 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
203 Effect.provideService(McpSchema.McpServerClient, client),
204 );
205​
206 const message = "Preview automation snapshot failed on client mcp-failure-client.";
207 expect(snapshot.isError).toBe(true);
208 expect(snapshot.content).toEqual([
209 { type: "text", text: `Preview snapshot failed: ${message}` },
210 ]);
211 expect(snapshot.structuredContent).toEqual({
212 error: {
213 _tag: "PreviewAutomationExecutionError",
214 operation: "snapshot",
215 failureCount: 1,
216 message,
217 },
218 });
219 }),
220 ).pipe(Effect.provide(layerTest)),
221);
222​
223it.effect.each([
224 { mode: "default", input: {}, images: false },
225 { mode: "explicit image", input: { includeImage: true }, images: true },
226 { mode: "text only", input: { includeImage: false }, images: false },
227])("returns fresh $mode snapshots on repeated MCP calls", ({ input, images }) =>
228 Effect.scoped(
229 Effect.gen(function* () {
230 const server = yield* McpServer.McpServer;
231 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
232 const connected = yield* Deferred.make<void>();
233 const png =
234 "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII=";
235 const page = {
236 url: "http://example.test/",
237 loading: false,
238 visibleText: "Save your changes",
239 interactiveElements: [
240 {
241 tag: "button",
242 role: "button",
243 name: "Save",
244 selector: "#save",
245 x: 0,
246 y: 0,
247 width: 20,
248 height: 10,
249 },
250 ],
251 accessibilityTree: { role: "document", name: "Example" },
252 consoleEntries: [],
253 networkEntries: [],
254 actionTimeline: [],
255 };
256 const screenshot = { mimeType: "image/png", width: 1, height: 1 };
257 let requests = 0;
258 const events = yield* broker.connect({ clientId: "mcp-image-option-client", environmentId });
259 yield* Stream.runForEach(events, (event) => {
260 if (event.type === "connected") return Deferred.succeed(connected, undefined);
261 requests += 1;
262 expect(event.request).toMatchObject({
263 operation: "snapshot",
264 tabId: alternateTabId,
265 threadId,
266 });
267 expect(event.request.input).toEqual({});
268 return broker.respond({
269 clientId: "mcp-image-option-client",
270 connectionId: event.connectionId,
271 requestId: event.request.requestId,
272 ok: true,
273 result: {
274 ...page,
275 title: `Snapshot ${requests}`,
276 screenshot: { ...screenshot, data: png },
277 },
278 });
279 }).pipe(Effect.forkScoped);
280 yield* Deferred.await(connected);
281​
282 for (const call of [1, 2, 3, 4, 5, 6]) {
283 const snapshot = yield* server
284 .callTool({
285 name: "preview_snapshot",
286 arguments: { ...input, tabId: alternateTabId },
287 })
288 .pipe(
289 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
290 Effect.provideService(McpSchema.McpServerClient, client),
291 );
292 const metadata = { ...page, title: `Snapshot ${call}`, screenshot };
293 const { accessibilityTree: _tree, ...boundedMetadata } = metadata;
294 expect(snapshot.isError).toBe(false);
295 expect(snapshot.structuredContent).toEqual({
296 ...boundedMetadata,
297 omitted: ["accessibilityTree (use interactiveElements locators or preview_evaluate)"],
298 });
299 const [identity, text, ...rest] = snapshot.content;
300 expect(identity?.type === "text" ? decodeJsonText(identity.text) : null).toEqual({
301 url: page.url,
302 });
303 expect(text?.type === "text" ? decodeJsonText(text.text) : null).toEqual(boundedMetadata);
304 expect(rest).toEqual([
305 {
306 type: "text",
307 text: "Snapshot text was bounded. Omitted: accessibilityTree (use interactiveElements locators or preview_evaluate).",
308 },
309 ...(images
310 ? [
311 {
312 type: "image",
313 mimeType: "image/png",
314 data: new Uint8Array(Buffer.from(png, "base64")),
315 },
316 ]
317 : []),
318 ]);
319 }
320​
321 const nextDefault = yield* server
322 .callTool({
323 name: "preview_snapshot",
324 arguments: { tabId: alternateTabId },
325 })
326 .pipe(
327 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
328 Effect.provideService(McpSchema.McpServerClient, client),
329 );
330 expect(nextDefault.content.map((content) => content.type)).toEqual(["text", "text", "text"]);
331 expect(nextDefault.structuredContent).toMatchObject({ title: "Snapshot 7", screenshot });
332 expect(nextDefault.structuredContent).not.toHaveProperty("accessibilityTree");
333 expect(requests).toBe(7);
334 }),
335 ).pipe(Effect.provide(layerTest)),
336);
337​
338it.effect("refuses preview tools to a client outside a thread before they run", () =>
339 Effect.gen(function* () {
340 const server = yield* McpServer.McpServer;
341 const readOnly = {
342 ...invocation,
343 thread: undefined,
344 requestNamespace: "client:session-1",
345 client: { sessionId: "session-1", label: "Claude Code", access: "read-only" as const },
346 };
347 const click = yield* server
348 .callTool({ name: "preview_click", arguments: { locator: "text=Send" } })
349 .pipe(
350 Effect.provideService(McpInvocationContext.McpInvocationContext, readOnly),
351 Effect.provideService(McpSchema.McpServerClient, client),
352 );
353 expect(click.isError).toBe(true);
354 expect(click.content).toEqual([
355 { type: "text", text: expect.stringContaining("needs an agent running inside T3 Code") },
356 ]);
357 }).pipe(Effect.provide(layerTest)),
358);
359​
360it.effect("decodes null optional arguments the way it decodes omitted ones", () => {
361 const calls: Array<unknown> = [];
362 return Effect.gen(function* () {
363 const thread = { threadId: "thread-null-arguments" };
364 yield* callTool("t3_thread_read", thread);
365 yield* callTool("t3_thread_read", { ...thread, afterPosition: null, view: null });
366 yield* callTool("delegate_task", { task: "Inspect", target: {} });
367 yield* callTool("delegate_task", { task: "Inspect", title: null, target: { model: null } });
368 // A null the schema declares keeps its meaning: here it clears the project icon.
369 yield* callTool("t3_project_update", { projectId: "project-1", projectIcon: null });
370​
371 expect(calls).toHaveLength(5);
372 expect(calls[1]).toEqual(calls[0]);
373 expect(calls[3]).toEqual(calls[2]);
374 expect(calls[4]).toStrictEqual({ projectId: "project-1", projectIcon: null });
375 }).pipe(Effect.provide(layerRecordingTools(calls)));
376});
377​
378it.effect(
379 "registers the pull request toolkit and surfaces a missing capability as a tool error",
380 () =>
381 Effect.gen(function* () {
382 const server = yield* McpServer.McpServer;
383 const names = server.tools.map(({ tool }) => tool.name);
384 expect(names).toEqual(
385 expect.arrayContaining([
386 "link_pull_request",
387 "unlink_pull_request",
388 "list_thread_pull_requests",
389 ]),
390 );
391 const linkTool = server.tools.find(({ tool }) => tool.name === "link_pull_request");
392 expect(linkTool?.tool.annotations?.idempotentHint).toBe(true);
393 expect(linkTool?.tool.annotations?.openWorldHint).toBe(false);
394 expect(linkTool?.tool.description).toContain("Register every pull request you open");
395​
396 const denied = yield* server
397 .callTool({ name: "list_thread_pull_requests", arguments: {} })
398 .pipe(
399 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
400 Effect.provideService(McpSchema.McpServerClient, client),
401 );
402 expect(denied.isError).toBe(true);
403 expect(denied.content).toEqual([
404 { type: "text", text: "MCP credential does not grant the pull-requests capability." },
405 ]);
406 }).pipe(Effect.provide(layerPullRequestsTest)),
407);
408​
409it.effect("bounds large ARIA trees without dropping every server locator", () =>
410 Effect.scoped(
411 Effect.gen(function* () {
412 const accessibilityTree = Array.from(
413 { length: 2_000 },
414 (_, index) => `- button "删除 ${index}" [ref=t3-snapshot-e${index}]`,
415 ).join("\n");
416 yield* serveSnapshots("mcp-large-server-refs", { ...snapshotResult, accessibilityTree });
417 const result = yield* callSnapshot({ includeImage: false });
418 expect(result.isError).toBe(false);
419 const metadata = result.structuredContent as { accessibilityTree: string };
420 expect(metadata.accessibilityTree).toContain("[ref=t3-snapshot-e0]");
421 expect(metadata.accessibilityTree.length).toBeLessThan(accessibilityTree.length);
422 const body = result.content[1];
423 expect(Buffer.byteLength(body?.type === "text" ? body.text : "", "utf8")).toBeLessThanOrEqual(
424 McpHttpServer.MAX_SNAPSHOT_TEXT_BYTES,
425 );
426 }),
427 ).pipe(Effect.provide(layerTest)),
428);
429​
430it.effect("keeps the snapshot text under the agent's output ceiling", () =>
431 Effect.scoped(
432 Effect.gen(function* () {
433 const pageText = "/Users/theo/Code/project\nClaude, Codex · 79 threads\n".repeat(600);
434 const element = (name: string, index: number) => ({
435 tag: "div",
436 role: "presentation",
437 name,
438 selector: `div:nth-of-type(${index})`,
439 x: 0,
440 y: 0,
441 width: 10,
442 height: 10,
443 });
444 const oversized = {
445 ...snapshotResult,
446 visibleText: pageText,
447 interactiveElements: [
448 element(pageText, 1),
449 element(pageText, 2),
450 element(pageText, 3),
451 element("Continue", 4),
452 ],
453 accessibilityTree: { nodes: Array.from({ length: 2_000 }, (_, i) => ({ nodeId: `${i}` })) },
454 consoleEntries: Array.from({ length: 100 }, (_, i) => ({
455 level: "log",
456 text: `entry ${i}`,
457 timestamp: "t",
458 })),
459 };
460 yield* serveSnapshots("mcp-bounded-client", oversized);
461​
462 const snapshot = yield* callSnapshot({ includeImage: false });
463​
464 expect(snapshot.isError).toBe(false);
465 const [identity, text, notice] = snapshot.content;
466 expect(identity?.type === "text" ? decodeJsonText(identity.text) : null).toEqual({
467 url: oversized.url,
468 });
469 expect(text?.type).toBe("text");
470 const body = text?.type === "text" ? text.text : "";
471 expect(Buffer.byteLength(body, "utf8")).toBeLessThanOrEqual(
472 McpHttpServer.MAX_SNAPSHOT_TEXT_BYTES,
473 );
474 const parsed = decodeJsonText(body) as {
475 readonly accessibilityTree?: unknown;
476 readonly visibleText: string;
477 readonly interactiveElements: ReadonlyArray<{ readonly name: string }>;
478 readonly consoleEntries: ReadonlyArray<{ readonly text: string }>;
479 };
480 expect(parsed.accessibilityTree).toBeUndefined();
481 expect(parsed.visibleText.length).toBeLessThanOrEqual(8_001);
482 expect(parsed.interactiveElements).toHaveLength(4);
483 expect(parsed.interactiveElements[0]?.name.length).toBeLessThanOrEqual(201);
484 expect(parsed.interactiveElements[3]?.name).toBe("Continue");
485 expect(parsed.consoleEntries).toHaveLength(40);
486 expect(parsed.consoleEntries[0]?.text).toBe("entry 60");
487 expect(notice?.type === "text" ? notice.text : "").toContain("accessibilityTree");
488 expect(notice?.type === "text" ? notice.text : "").toContain("60 older console entries");
489 // Claude Code shows the model structuredContent instead of the text, so it is bounded too.
490 expect(snapshot.structuredContent).toEqual({
491 ...parsed,
492 omitted: expect.arrayContaining(["60 older console entries"]),
493 });
494 }),
495 ).pipe(Effect.provide(layerTest)),
496);
497​
498// regression: #10501 keep preview snapshots usable by the agent
499it.effect("bounds the snapshot text even when nothing but logs and the title are large", () =>
500 Effect.scoped(
501 Effect.gen(function* () {
502 const oversized = {
503 ...snapshotResult,
504 title: "t".repeat(70_000),
505 interactiveElements: [],
506 consoleEntries: [{ level: "log", text: "x".repeat(70_000), timestamp: "t" }],
507 };
508 yield* serveSnapshots("mcp-bounded-logs-client", oversized);
509​
510 const snapshot = yield* callSnapshot({ includeImage: false });
511​
512 const [, text] = snapshot.content;
513 const body = text?.type === "text" ? text.text : "";
514 expect(Buffer.byteLength(body, "utf8")).toBeLessThanOrEqual(
515 McpHttpServer.MAX_SNAPSHOT_TEXT_BYTES,
516 );
517 const parsed = decodeJsonText(body) as {
518 readonly title: string;
519 readonly consoleEntries: ReadonlyArray<{ readonly text: string }>;
520 };
521 expect(parsed.title.length).toBe(2_049);
522 expect(parsed.consoleEntries[0]?.text.length).toBe(501);
523 const notice = snapshot.content[2];
524 const noticeText = notice?.type === "text" ? notice.text : "";
525 expect(noticeText).toContain("url or title after 2048 characters");
526 expect(noticeText).toContain("console entries text after 500 characters");
527 }),
528 ).pipe(Effect.provide(layerTest)),
529);
530​
531// regression: #13558 preview snapshots overflowed the agent's tool output
532it.effect("bounds page text made of wide characters before dropping locators", () =>
533 Effect.scoped(
534 Effect.gen(function* () {
535 yield* serveSnapshots("mcp-wide-text-client", {
536 ...snapshotResult,
537 visibleText: "界".repeat(9_000),
538 interactiveElements: Array.from({ length: 20 }, (_, i) => ({
539 tag: "button",
540 role: "button",
541 name: `Button ${i}`,
542 selector: `#button-${i}`,
543 x: 0,
544 y: 0,
545 width: 10,
546 height: 10,
547 })),
548 });
549​
550 const snapshot = yield* callSnapshot({ includeImage: false });
551​
552 const [, text, notice] = snapshot.content;
553 const body = text?.type === "text" ? text.text : "";
554 expect(Buffer.byteLength(body, "utf8")).toBeLessThanOrEqual(
555 McpHttpServer.MAX_SNAPSHOT_TEXT_BYTES,
556 );
557 const parsed = decodeJsonText(body) as {
558 readonly visibleText: string;
559 readonly interactiveElements: ReadonlyArray<unknown>;
560 };
561 expect(parsed.visibleText).toMatch(/^界+…$/);
562 expect(parsed.interactiveElements).toHaveLength(20);
563 expect(notice?.type === "text" ? notice.text : "").toContain(
564 "visibleText after 4000 characters",
565 );
566 }),
567 ).pipe(Effect.provide(layerTest)),
568);
569​
570it.effect("terminates HTTP MCP sessions with DELETE", () =>
571 Effect.scoped(
572 Effect.gen(function* () {
573 const token = "providerTokenWithoutDots";
574 const scope: McpInvocationContext.McpInvocationScope = {
575 environmentId,
576 requestNamespace: "provider-session",
577 thread: {
578 threadId: ThreadId.make("thread-provider"),
579 providerSessionId: "provider-session",
580 providerInstanceId: ProviderInstanceId.make("codex"),
581 },
582 client: undefined,
583 capabilities: new Set(["orchestration"]),
584 issuedAt: 1,
585 };
586 const layerServer = McpHttpServer.layerMcpTransport.pipe(
587 Layer.provide(
588 Layer.mock(McpSessionRegistry.McpSessionRegistry)({
589 resolve: (presented) =>
590 Effect.succeed(
591 presented === token
592 ? (scope as McpInvocationContext.McpThreadInvocationScope)
593 : undefined,
594 ),
595 }),
596 ),
597 );
598 yield* HttpRouter.serve(layerServer, {
599 disableListenLog: true,
600 disableLogger: true,
601 }).pipe(Layer.build);
602 const httpClient = (yield* HttpClient.HttpClient).pipe(
603 HttpClient.mapRequest(HttpClientRequest.bearerToken(token)),
604 );
605​
606 const initializeResponse = yield* httpClient.post("/mcp", {
607 headers: { accept: "application/json, text/event-stream" },
608 body: HttpBody.text(
609 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"mcp-test","version":"1.0.0"}}}`,
610 "application/json",
611 ),
612 });
613 const sessionId = initializeResponse.headers["mcp-session-id"];
614 expect(initializeResponse.status).toBe(200);
615 expect(sessionId).not.toBeNull();
616​
617 const missingSessionResponse = yield* httpClient.del("/mcp");
618 expect(missingSessionResponse.status).toBe(400);
619​
620 const unknownSessionResponse = yield* httpClient.del("/mcp", {
621 headers: { "mcp-session-id": "unknown-session" },
622 });
623 expect(unknownSessionResponse.status).toBe(404);
624​
625 const terminateResponse = yield* httpClient.del("/mcp", {
626 headers: { "mcp-session-id": sessionId! },
627 });
628 expect(terminateResponse.status).toBe(204);
629​
630 const reusedSessionResponse = yield* httpClient.post("/mcp", {
631 headers: {
632 accept: "application/json, text/event-stream",
633 "mcp-session-id": sessionId!,
634 },
635 body: HttpBody.text(
636 `{"jsonrpc":"2.0","id":2,"method":"ping","params":{}}`,
637 "application/json",
638 ),
639 });
640 expect(reusedSessionResponse.status).toBe(404);
641 }),
642 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
643);
644​
645it.effect("admits provider and OAuth client credentials and points only clients at OAuth", () =>
646 Effect.scoped(
647 Effect.gen(function* () {
648 const providerToken = "providerTokenWithoutDots";
649 const clientToken = "client-payload.client-signature";
650 const providerScope: McpInvocationContext.McpInvocationScope = {
651 environmentId,
652 requestNamespace: "provider-session",
653 thread: {
654 threadId: ThreadId.make("thread-provider"),
655 providerSessionId: "provider-session",
656 providerInstanceId: ProviderInstanceId.make("codex"),
657 },
658 client: undefined,
659 capabilities: new Set(["orchestration"]),
660 issuedAt: 1,
661 };
662 const clientScope: McpInvocationContext.McpInvocationScope = {
663 environmentId,
664 requestNamespace: "client:session-1",
665 thread: undefined,
666 client: { sessionId: "session-1", label: "Claude Code", access: "auto" },
667 capabilities: new Set(["orchestration"]),
668 issuedAt: 1,
669 };
670 const seen: Array<McpInvocationContext.McpInvocationScope> = [];
671 const ProbeToolkit = Toolkit.make(
672 Tool.make("probe", {
673 description: "Reports the caller.",
674 success: Schema.Struct({ ok: Schema.Boolean }),
675 failure: OrchestratorMcpFailure,
676 failureMode: "return",
677 dependencies: [McpInvocationContext.McpInvocationContext],
678 }),
679 );
680 const serverLayer = McpHttpServer.toolkitRegistration(
681 ProbeToolkit,
682 McpToolAccess.toLayer(ProbeToolkit, {
683 probe: McpToolAccess.reads(() =>
684 McpInvocationContext.McpInvocationContext.pipe(
685 Effect.tap((scope) => Effect.sync(() => seen.push(scope))),
686 Effect.as({ ok: true }),
687 ),
688 ),
689 }),
690 ).pipe(
691 Layer.provideMerge(McpHttpServer.layerMcpTransport),
692 Layer.provide(
693 Layer.mock(McpSessionRegistry.McpSessionRegistry)({
694 resolve: (token) =>
695 Effect.succeed(
696 token === providerToken
697 ? (providerScope as McpInvocationContext.McpThreadInvocationScope)
698 : undefined,
699 ),
700 }),
701 ),
702 Layer.provide(
703 Layer.succeed(McpHttpServer.McpClientAuthenticator, {
704 authenticate: (request) =>
705 Effect.succeed(
706 request.headers.authorization === `Bearer ${clientToken}` ? clientScope : undefined,
707 ),
708 }),
709 ),
710 );
711 yield* HttpRouter.serve(serverLayer, { disableListenLog: true, disableLogger: true }).pipe(
712 Layer.build,
713 );
714 const httpClient = yield* HttpClient.HttpClient;
715 const call = (token: string | undefined) =>
716 Effect.gen(function* () {
717 const headers = {
718 accept: "application/json, text/event-stream",
719 ...(token === undefined ? {} : { authorization: `Bearer ${token}` }),
720 };
721 const initialize = yield* httpClient.post("/mcp", {
722 headers,
723 body: HttpBody.text(
724 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`,
725 "application/json",
726 ),
727 });
728 if (initialize.status !== 200) return initialize;
729 return yield* httpClient.post("/mcp", {
730 headers: {
731 ...headers,
732 "mcp-session-id": initialize.headers["mcp-session-id"]!,
733 "mcp-protocol-version": "2025-06-18",
734 },
735 body: HttpBody.text(
736 `{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"probe","arguments":{}}}`,
737 "application/json",
738 ),
739 });
740 });
741​
742 expect((yield* call(providerToken)).status).toBe(200);
743 expect((yield* call(clientToken)).status).toBe(200);
744 expect(seen.map((scope) => scope.requestNamespace)).toEqual([
745 "provider-session",
746 "client:session-1",
747 ]);
748​
749 const missing = yield* call(undefined);
750 expect(missing.status).toBe(401);
751 expect(missing.headers["www-authenticate"]).toMatch(
752 /^Bearer resource_metadata="http:\/\/[^"]+\/\.well-known\/oauth-protected-resource\/mcp"$/,
753 );
754​
755 const expiredClient = yield* call("stale-payload.stale-signature");
756 expect(expiredClient.headers["www-authenticate"]).toContain("resource_metadata=");
757 expect(expiredClient.headers["www-authenticate"]).toContain('error="invalid_token"');
758​
759 const deadProvider = yield* call("deadProviderToken");
760 expect(deadProvider.status).toBe(401);
761 expect(deadProvider.headers["www-authenticate"]).toBe('Bearer error="invalid_token"');
762 }),
763 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
764);