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

McpHttpServer.test.ts

803 lines31.3 KB

1import { expect, it } from "@effect/vitest";
2import { NodeHttpServer } from "@effect/platform-node";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import { EnvironmentId, PreviewTabId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
5import * as Deferred from "effect/Deferred";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Option from "effect/Option";
10import * as Path from "effect/Path";
11import * as Schema from "effect/Schema";
12import * as Stream from "effect/Stream";
13import { McpProtocol, McpSchema, McpServer } from "effect/unstable/ai";
14import { HttpBody, HttpClient, HttpRouter, HttpServerResponse } from "effect/unstable/http";
15​
16import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts";
17import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts";
18import { ThreadBootstrap } from "../orchestration/Services/ThreadBootstrap.ts";
19import * as ServerConfig from "../config.ts";
20import * as McpHttpServer from "./McpHttpServer.ts";
21import * as McpInvocationContext from "./McpInvocationContext.ts";
22import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
23​
24const environmentId = EnvironmentId.make("environment-mcp-test");
25const threadId = ThreadId.make("thread-mcp-test");
26const tabId = PreviewTabId.make("tab-mcp-test");
27const alternateTabId = PreviewTabId.make("tab-mcp-alternate");
28const decodeJsonText = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
29const invocation = {
30 environmentId,
31 threadId,
32 providerSessionId: "provider-session-mcp-test",
33 providerInstanceId: ProviderInstanceId.make("codex"),
34 capabilities: new Set(["preview"] as const),
35 issuedAt: 1,
36};
37const client = McpSchema.McpServerClient.of({
38 clientId: 1,
39 clientCapabilities: {},
40 clientInfo: { name: "mcp-test", version: "1.0.0" },
41 protocolVersion: "2025-06-18",
42 initializePayload: {
43 protocolVersion: "2025-06-18",
44 capabilities: {},
45 clientInfo: { name: "mcp-test", version: "1.0.0" },
46 },
47 getClient: Effect.die("unused"),
48});
49const TestLayer = McpHttpServer.PreviewToolkitRegistrationLive.pipe(
50 Layer.provideMerge(McpServer.McpServer.layer),
51 Layer.provideMerge(PreviewAutomationBroker.layer),
52 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-http-server-test-" })),
53 Layer.provideMerge(NodeServices.layer),
54);
55const PullRequestsTestLayer = McpHttpServer.PullRequestsToolkitRegistrationLive.pipe(
56 Layer.provideMerge(McpServer.McpServer.layer),
57 Layer.provide(
58 Layer.mergeAll(
59 Layer.mock(ProjectionSnapshotQuery)({
60 getThreadShellById: () => Effect.succeed(Option.none()),
61 }),
62 Layer.mock(OrchestrationEngineService)({}),
63 NodeServices.layer,
64 ),
65 ),
66);
67​
68const ThreadsTestLayer = McpHttpServer.ThreadsToolkitRegistrationLive.pipe(
69 Layer.provideMerge(McpServer.McpServer.layer),
70 Layer.provide(
71 Layer.mergeAll(
72 Layer.mock(ProjectionSnapshotQuery)({
73 getThreadShellById: () => Effect.succeed(Option.none()),
74 }),
75 Layer.mock(ThreadBootstrap)({}),
76 NodeServices.layer,
77 ),
78 ),
79);
80​
81const snapshotResult = {
82 url: "http://example.test/",
83 title: "Example",
84 loading: false,
85 visibleText: "Example",
86 interactiveElements: [],
87 accessibilityTree: {},
88 consoleEntries: [],
89 networkEntries: [],
90 actionTimeline: [],
91 screenshot: {
92 mimeType: "image/png",
93 data: Buffer.from("png").toString("base64"),
94 width: 10,
95 height: 5,
96 },
97};
98​
99/** Answers every snapshot request on a fresh broker host with the given result. */
100const serveSnapshots = (clientId: string, result: unknown) =>
101 Effect.gen(function* () {
102 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
103 const connected = yield* Deferred.make<void>();
104 const inputs: Array<unknown> = [];
105 const events = yield* broker.connect({ clientId, environmentId });
106 yield* Stream.runForEach(events, (event) => {
107 if (event.type === "connected") return Deferred.succeed(connected, undefined);
108 inputs.push(event.request.input);
109 return broker.respond({
110 clientId,
111 connectionId: event.connectionId,
112 requestId: event.request.requestId,
113 ok: true,
114 result,
115 });
116 }).pipe(Effect.forkScoped);
117 yield* Deferred.await(connected);
118 return inputs;
119 });
120​
121const callSnapshot = (args: Record<string, unknown>) =>
122 Effect.gen(function* () {
123 const server = yield* McpServer.McpServer;
124 return yield* server
125 .callTool({ name: "preview_snapshot", arguments: args })
126 .pipe(
127 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
128 Effect.provideService(McpSchema.McpServerClient, client),
129 );
130 });
131​
132it("normalizes empty successful notification responses to accepted", () => {
133 const notificationResponse = McpHttpServer.normalizeMcpHttpResponse(
134 HttpServerResponse.text("", { status: 200, contentType: "application/json" }),
135 );
136 expect(notificationResponse.status).toBe(202);
137​
138 const resultResponse = McpHttpServer.normalizeMcpHttpResponse(
139 HttpServerResponse.jsonUnsafe({ jsonrpc: "2.0", id: 1, result: {} }),
140 );
141 expect(resultResponse.status).toBe(200);
142});
143​
144it.effect.each([{}, { includeImage: false }])(
145 "returns bounded structural preview snapshot failures %#",
146 (input) =>
147 Effect.scoped(
148 Effect.gen(function* () {
149 const server = yield* McpServer.McpServer;
150 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
151 const events = yield* broker.connect({
152 clientId: "mcp-failure-client",
153 environmentId,
154 });
155 yield* Stream.runForEach(events, (event) =>
156 event.type === "connected"
157 ? Effect.void
158 : broker.respond({
159 clientId: "mcp-failure-client",
160 connectionId: event.connectionId,
161 requestId: event.request.requestId,
162 ok: false,
163 error: {
164 _tag: "PreviewAutomationExecutionError",
165 message: "sensitive renderer failure",
166 detail: { consoleOutput: "sensitive browser output" },
167 },
168 }),
169 ).pipe(Effect.forkScoped);
170 yield* Effect.yieldNow;
171​
172 const snapshot = yield* server
173 .callTool({ name: "preview_snapshot", arguments: input })
174 .pipe(
175 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
176 Effect.provideService(McpSchema.McpServerClient, client),
177 );
178​
179 expect(snapshot.isError).toBe(true);
180 expect(snapshot.content).toEqual([
181 { type: "text", text: "Preview snapshot failed: PreviewAutomationExecutionError." },
182 ]);
183 expect(snapshot.structuredContent).toEqual({
184 error: {
185 _tag: "PreviewAutomationExecutionError",
186 operation: "snapshot",
187 failureCount: 1,
188 },
189 });
190 }),
191 ).pipe(Effect.provide(TestLayer)),
192);
193​
194it.effect.each([
195 { mode: "default", input: {}, images: true },
196 { mode: "explicit image", input: { includeImage: true }, images: true },
197 { mode: "text only", input: { includeImage: false }, images: false },
198])("returns fresh $mode snapshots on repeated MCP calls", ({ input, images }) =>
199 Effect.scoped(
200 Effect.gen(function* () {
201 const server = yield* McpServer.McpServer;
202 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
203 const connected = yield* Deferred.make<void>();
204 const png =
205 "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII=";
206 const page = {
207 url: "http://example.test/",
208 loading: false,
209 visibleText: "Save your changes",
210 interactiveElements: [
211 {
212 tag: "button",
213 role: "button",
214 name: "Save",
215 selector: "#save",
216 x: 0,
217 y: 0,
218 width: 20,
219 height: 10,
220 },
221 ],
222 accessibilityTree: { role: "document", name: "Example" },
223 consoleEntries: [],
224 networkEntries: [],
225 actionTimeline: [],
226 };
227 const screenshot = { mimeType: "image/png", width: 1, height: 1 };
228 let requests = 0;
229 const events = yield* broker.connect({ clientId: "mcp-image-option-client", environmentId });
230 yield* Stream.runForEach(events, (event) => {
231 if (event.type === "connected") return Deferred.succeed(connected, undefined);
232 requests += 1;
233 expect(event.request).toMatchObject({
234 operation: "snapshot",
235 tabId: alternateTabId,
236 threadId,
237 });
238 expect(event.request.input).toEqual({});
239 return broker.respond({
240 clientId: "mcp-image-option-client",
241 connectionId: event.connectionId,
242 requestId: event.request.requestId,
243 ok: true,
244 result: {
245 ...page,
246 title: `Snapshot ${requests}`,
247 screenshot: { ...screenshot, data: png },
248 },
249 });
250 }).pipe(Effect.forkScoped);
251 yield* Deferred.await(connected);
252​
253 for (const call of [1, 2, 3, 4, 5, 6]) {
254 const snapshot = yield* server
255 .callTool({
256 name: "preview_snapshot",
257 arguments: { ...input, tabId: alternateTabId },
258 })
259 .pipe(
260 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
261 Effect.provideService(McpSchema.McpServerClient, client),
262 );
263 const metadata = { ...page, title: `Snapshot ${call}`, screenshot };
264 const { accessibilityTree: _tree, ...boundedMetadata } = metadata;
265 expect(snapshot.isError).toBe(false);
266 expect(snapshot.structuredContent).toEqual(metadata);
267 const [identity, text, ...rest] = snapshot.content;
268 expect(identity?.type === "text" ? decodeJsonText(identity.text) : null).toEqual({
269 url: page.url,
270 });
271 expect(text?.type === "text" ? decodeJsonText(text.text) : null).toEqual(boundedMetadata);
272 expect(rest).toEqual([
273 {
274 type: "text",
275 text: "Snapshot text was bounded. Omitted: accessibilityTree (use interactiveElements locators or preview_evaluate).",
276 },
277 ...(images
278 ? [
279 {
280 type: "image",
281 mimeType: "image/png",
282 data: new Uint8Array(Buffer.from(png, "base64")),
283 },
284 ]
285 : []),
286 ]);
287 }
288​
289 // Output selection belongs to this call, not the MCP session's history.
290 const nextDefault = yield* server
291 .callTool({
292 name: "preview_snapshot",
293 arguments: { tabId: alternateTabId },
294 })
295 .pipe(
296 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
297 Effect.provideService(McpSchema.McpServerClient, client),
298 );
299 expect(nextDefault.content.map((content) => content.type)).toEqual([
300 "text",
301 "text",
302 "text",
303 "image",
304 ]);
305 expect(nextDefault.structuredContent).toEqual({ ...page, title: "Snapshot 7", screenshot });
306 expect(requests).toBe(7);
307 }),
308 ).pipe(Effect.provide(TestLayer)),
309);
310​
311it.effect("rejects non-boolean snapshot image options before selecting a browser host", () =>
312 Effect.gen(function* () {
313 const server = yield* McpServer.McpServer;
314 for (const includeImage of ["false", 0, null]) {
315 const result = yield* server
316 .callTool({
317 name: "preview_snapshot",
318 arguments: { includeImage },
319 })
320 .pipe(
321 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
322 Effect.provideService(McpSchema.McpServerClient, client),
323 );
324 expect(result.isError).toBe(true);
325 expect(result.content).toEqual([{ type: "text", text: "Preview snapshot failed: AiError." }]);
326 expect(result.structuredContent).toEqual({
327 error: { _tag: "AiError", operation: "snapshot", failureCount: 1 },
328 });
329 }
330 }).pipe(Effect.provide(TestLayer)),
331);
332​
333it.effect("saves the snapshot PNG on request and reports its path", () =>
334 Effect.scoped(
335 Effect.gen(function* () {
336 const config = yield* ServerConfig.ServerConfig;
337 const fileSystem = yield* FileSystem.FileSystem;
338 const path = yield* Path.Path;
339 const inputs = yield* serveSnapshots("mcp-save-client", snapshotResult);
340​
341 const snapshot = yield* callSnapshot({ save: true });
342​
343 expect(snapshot.isError).toBe(false);
344 // The browser never receives the server-only `save` flag.
345 expect(inputs).toEqual([{}]);
346 const structured = snapshot.structuredContent as { readonly screenshotPath?: string };
347 const screenshotPath = structured.screenshotPath;
348 expect(typeof screenshotPath).toBe("string");
349 expect(path.dirname(screenshotPath!)).toBe(config.browserArtifactsDir);
350 expect(path.basename(screenshotPath!)).toMatch(
351 /^browser-screenshot-example-test-[0-9a-z]+-[0-9a-f]{8}\.png$/,
352 );
353 expect(Buffer.from(yield* fileSystem.readFile(screenshotPath!)).toString()).toBe("png");
354 const [, text] = snapshot.content;
355 expect(text?.type === "text" ? text.text : "").toContain(screenshotPath);
356​
357 const unsaved = yield* callSnapshot({});
358 expect(unsaved.structuredContent).not.toHaveProperty("screenshotPath");
359 }),
360 ).pipe(Effect.provide(TestLayer)),
361);
362​
363it.effect("reports a tagged error when the screenshot cannot be saved", () =>
364 Effect.scoped(
365 Effect.gen(function* () {
366 const config = yield* ServerConfig.ServerConfig;
367 const fileSystem = yield* FileSystem.FileSystem;
368 // A regular file where the artifacts directory should be makes every write fail.
369 yield* fileSystem.writeFileString(config.browserArtifactsDir, "");
370 yield* serveSnapshots("mcp-save-failure-client", snapshotResult);
371​
372 const snapshot = yield* callSnapshot({ save: true });
373​
374 expect(snapshot.isError).toBe(true);
375 expect(snapshot.content).toEqual([
376 { type: "text", text: "Preview snapshot failed: PreviewScreenshotSaveError." },
377 ]);
378 expect(snapshot.structuredContent).toEqual({
379 error: { _tag: "PreviewScreenshotSaveError", operation: "snapshot", failureCount: 1 },
380 });
381 }),
382 ).pipe(Effect.provide(TestLayer)),
383);
384​
385it.effect(
386 "registers the pull request toolkit and surfaces a missing capability as a tool error",
387 () =>
388 Effect.gen(function* () {
389 const server = yield* McpServer.McpServer;
390 const names = server.tools.map(({ tool }) => tool.name);
391 expect(names).toEqual(
392 expect.arrayContaining([
393 "link_pull_request",
394 "unlink_pull_request",
395 "list_thread_pull_requests",
396 ]),
397 );
398 const linkTool = server.tools.find(({ tool }) => tool.name === "link_pull_request");
399 expect(linkTool?.tool.annotations?.idempotentHint).toBe(true);
400 expect(linkTool?.tool.annotations?.openWorldHint).toBe(false);
401 expect(linkTool?.tool.description).toContain("Register every pull request you open");
402​
403 const denied = yield* server
404 .callTool({ name: "list_thread_pull_requests", arguments: {} })
405 .pipe(
406 // A preview-only credential: the token predates the toolkit or was minted elsewhere.
407 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
408 Effect.provideService(McpSchema.McpServerClient, client),
409 );
410 expect(denied.isError).toBe(true);
411 expect(denied.content).toEqual([
412 { type: "text", text: "MCP credential does not grant the pull-requests capability." },
413 ]);
414 }).pipe(Effect.provide(PullRequestsTestLayer)),
415);
416​
417it.effect("registers the threads toolkit and surfaces a missing capability as a tool error", () =>
418 Effect.gen(function* () {
419 const server = yield* McpServer.McpServer;
420 const startTool = server.tools.find(({ tool }) => tool.name === "t3_thread_start");
421 expect(startTool?.tool.annotations?.destructiveHint).toBe(false);
422 expect(startTool?.tool.annotations?.openWorldHint).toBe(false);
423 expect(startTool?.tool.description).toContain("NEW top-level T3 Code thread");
424​
425 const denied = yield* server
426 .callTool({ name: "t3_thread_start", arguments: { prompt: "Continue the migration." } })
427 .pipe(
428 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
429 Effect.provideService(McpSchema.McpServerClient, client),
430 );
431 expect(denied.isError).toBe(true);
432 expect(denied.content).toEqual([
433 { type: "text", text: "MCP credential does not grant the threads capability." },
434 ]);
435 }).pipe(Effect.provide(ThreadsTestLayer)),
436);
437​
438it.effect("keeps the snapshot text under the agent's output ceiling", () =>
439 Effect.scoped(
440 Effect.gen(function* () {
441 // Mirrors the real failure: a [role] container whose innerText is the whole
442 // project list, repeated for several elements, plus a big AX tree.
443 const pageText = "/Users/theo/Code/project\nClaude, Codex · 79 threads\n".repeat(600);
444 const element = (name: string, index: number) => ({
445 tag: "div",
446 role: "presentation",
447 name,
448 selector: `div:nth-of-type(${index})`,
449 x: 0,
450 y: 0,
451 width: 10,
452 height: 10,
453 });
454 const oversized = {
455 ...snapshotResult,
456 visibleText: pageText,
457 interactiveElements: [
458 element(pageText, 1),
459 element(pageText, 2),
460 element(pageText, 3),
461 element("Continue", 4),
462 ],
463 accessibilityTree: { nodes: Array.from({ length: 2_000 }, (_, i) => ({ nodeId: `${i}` })) },
464 consoleEntries: Array.from({ length: 100 }, (_, i) => ({
465 level: "log",
466 text: `entry ${i}`,
467 timestamp: "t",
468 })),
469 };
470 yield* serveSnapshots("mcp-bounded-client", oversized);
471​
472 const snapshot = yield* callSnapshot({ includeImage: false });
473​
474 expect(snapshot.isError).toBe(false);
475 const [identity, text, notice] = snapshot.content;
476 expect(identity?.type === "text" ? decodeJsonText(identity.text) : null).toEqual({
477 url: oversized.url,
478 });
479 expect(text?.type).toBe("text");
480 const body = text?.type === "text" ? text.text : "";
481 expect(Buffer.byteLength(body, "utf8")).toBeLessThanOrEqual(
482 McpHttpServer.MAX_SNAPSHOT_TEXT_BYTES,
483 );
484 const parsed = decodeJsonText(body) as {
485 readonly accessibilityTree?: unknown;
486 readonly visibleText: string;
487 readonly interactiveElements: ReadonlyArray<{ readonly name: string }>;
488 readonly consoleEntries: ReadonlyArray<{ readonly text: string }>;
489 };
490 expect(parsed.accessibilityTree).toBeUndefined();
491 expect(parsed.visibleText.length).toBeLessThanOrEqual(8_001);
492 expect(parsed.interactiveElements).toHaveLength(4);
493 expect(parsed.interactiveElements[0]?.name.length).toBeLessThanOrEqual(201);
494 expect(parsed.interactiveElements[3]?.name).toBe("Continue");
495 expect(parsed.consoleEntries).toHaveLength(40);
496 expect(parsed.consoleEntries[0]?.text).toBe("entry 60");
497 expect(notice?.type === "text" ? notice.text : "").toContain("accessibilityTree");
498 expect(notice?.type === "text" ? notice.text : "").toContain("60 older console entries");
499 // The structured result is untouched; only the text the agent reads is bounded.
500 expect(snapshot.structuredContent).toMatchObject({
501 accessibilityTree: oversized.accessibilityTree,
502 });
503 }),
504 ).pipe(Effect.provide(TestLayer)),
505);
506​
507it.effect("bounds the snapshot text even when nothing but logs and the title are large", () =>
508 Effect.scoped(
509 Effect.gen(function* () {
510 const oversized = {
511 ...snapshotResult,
512 title: "t".repeat(70_000),
513 interactiveElements: [],
514 consoleEntries: [{ level: "log", text: "x".repeat(70_000), timestamp: "t" }],
515 };
516 yield* serveSnapshots("mcp-bounded-logs-client", oversized);
517​
518 const snapshot = yield* callSnapshot({ includeImage: false });
519​
520 const [, text] = snapshot.content;
521 const body = text?.type === "text" ? text.text : "";
522 expect(Buffer.byteLength(body, "utf8")).toBeLessThanOrEqual(
523 McpHttpServer.MAX_SNAPSHOT_TEXT_BYTES,
524 );
525 const parsed = decodeJsonText(body) as {
526 readonly title: string;
527 readonly consoleEntries: ReadonlyArray<{ readonly text: string }>;
528 };
529 expect(parsed.title.length).toBe(2_049);
530 expect(parsed.consoleEntries[0]?.text.length).toBe(501);
531 const notice = snapshot.content[2];
532 const noticeText = notice?.type === "text" ? notice.text : "";
533 expect(noticeText).toContain("url or title after 2048 characters");
534 expect(noticeText).toContain("console entries text after 500 characters");
535 }),
536 ).pipe(Effect.provide(TestLayer)),
537);
538​
539it.effect("sheds log entries before locators when every list is full", () =>
540 Effect.scoped(
541 Effect.gen(function* () {
542 const long = "x".repeat(2_000);
543 const oversized = {
544 ...snapshotResult,
545 interactiveElements: Array.from({ length: 20 }, (_, i) => ({
546 tag: "button",
547 role: "button",
548 name: `Button ${i}`,
549 selector: `#button-${i}`,
550 x: 0,
551 y: 0,
552 width: 10,
553 height: 10,
554 })),
555 consoleEntries: Array.from({ length: 200 }, () => ({
556 level: long,
557 text: long,
558 timestamp: long,
559 source: long,
560 })),
561 networkEntries: Array.from({ length: 200 }, () => ({
562 url: long,
563 method: long,
564 status: 200,
565 failed: false,
566 errorText: long,
567 timestamp: long,
568 })),
569 actionTimeline: Array.from({ length: 200 }, () => ({
570 id: long,
571 action: long,
572 status: "succeeded",
573 startedAt: long,
574 completedAt: long,
575 error: long,
576 })),
577 };
578 yield* serveSnapshots("mcp-full-logs-client", oversized);
579​
580 const snapshot = yield* callSnapshot({ includeImage: false });
581​
582 const [, text, notice] = snapshot.content;
583 const body = text?.type === "text" ? text.text : "";
584 expect(Buffer.byteLength(body, "utf8")).toBeLessThanOrEqual(
585 McpHttpServer.MAX_SNAPSHOT_TEXT_BYTES,
586 );
587 const parsed = decodeJsonText(body) as {
588 readonly interactiveElements: ReadonlyArray<unknown>;
589 readonly consoleEntries: ReadonlyArray<unknown>;
590 readonly networkEntries: ReadonlyArray<unknown>;
591 readonly actionTimeline: ReadonlyArray<unknown>;
592 };
593 // Locators survive; the log lists take the cut.
594 expect(parsed.interactiveElements).toHaveLength(20);
595 expect(
596 parsed.consoleEntries.length + parsed.networkEntries.length + parsed.actionTimeline.length,
597 ).toBeLessThan(120);
598 const noticeText = notice?.type === "text" ? notice.text : "";
599 expect(noticeText).toContain("40 of 40 actionTimeline");
600 expect(noticeText).not.toMatch(/\d+ of \d+ interactiveElements/);
601 }),
602 ).pipe(Effect.provide(TestLayer)),
603);
604​
605it.effect("terminates HTTP MCP sessions with DELETE", () =>
606 Effect.scoped(
607 Effect.gen(function* () {
608 const serverLayer = McpServer.layerHttp({
609 name: "MCP termination test",
610 version: "1.0.0",
611 path: "/mcp",
612 protocols: [McpProtocol.v2025_06_18],
613 });
614 yield* HttpRouter.serve(serverLayer, {
615 disableListenLog: true,
616 disableLogger: true,
617 }).pipe(Layer.build);
618 const httpClient = yield* HttpClient.HttpClient;
619​
620 const initializeResponse = yield* httpClient.post("/mcp", {
621 headers: { accept: "application/json, text/event-stream" },
622 body: HttpBody.text(
623 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"mcp-test","version":"1.0.0"}}}`,
624 "application/json",
625 ),
626 });
627 const sessionId = initializeResponse.headers["mcp-session-id"];
628 expect(initializeResponse.status).toBe(200);
629 expect(sessionId).not.toBeNull();
630​
631 const missingSessionResponse = yield* httpClient.del("/mcp");
632 expect(missingSessionResponse.status).toBe(400);
633​
634 const unknownSessionResponse = yield* httpClient.del("/mcp", {
635 headers: { "mcp-session-id": "unknown-session" },
636 });
637 expect(unknownSessionResponse.status).toBe(404);
638​
639 const terminateResponse = yield* httpClient.del("/mcp", {
640 headers: { "mcp-session-id": sessionId! },
641 });
642 expect(terminateResponse.status).toBe(204);
643​
644 const reusedSessionResponse = yield* httpClient.post("/mcp", {
645 headers: {
646 accept: "application/json, text/event-stream",
647 "mcp-session-id": sessionId!,
648 },
649 body: HttpBody.text(
650 `{"jsonrpc":"2.0","id":2,"method":"ping","params":{}}`,
651 "application/json",
652 ),
653 });
654 expect(reusedSessionResponse.status).toBe(404);
655 }),
656 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
657);
658​
659it.effect("registers annotated tools and preserves authenticated request context", () =>
660 Effect.scoped(
661 Effect.gen(function* () {
662 const server = yield* McpServer.McpServer;
663 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
664 const toolIcon = {
665 _tag: "website" as const,
666 pageUrl: "http://example.test/",
667 };
668 const routedRequests: Array<{
669 readonly operation: string;
670 readonly tabId?: string | undefined;
671 }> = [];
672 const events = yield* broker.connect({
673 clientId: "mcp-test-client",
674 environmentId,
675 });
676 yield* Stream.runForEach(events, (event) => {
677 if (event.type === "connected") return Effect.void;
678 routedRequests.push(event.request);
679 return broker.respond({
680 clientId: "mcp-test-client",
681 connectionId: event.connectionId,
682 requestId: event.request.requestId,
683 ok: true,
684 result:
685 event.request.operation === "snapshot"
686 ? snapshotResult
687 : event.request.operation === "evaluate"
688 ? ["Connect", "Continue"]
689 : event.request.operation === "press"
690 ? undefined
691 : {
692 available: true,
693 visible: true,
694 tabId,
695 url: "http://example.test/",
696 title: "Example",
697 loading: false,
698 },
699 });
700 }).pipe(Effect.forkScoped);
701 yield* Effect.yieldNow;
702​
703 const statusTool = server.tools.find(({ tool }) => tool.name === "preview_status");
704 expect(statusTool?.tool.annotations?.readOnlyHint).toBe(true);
705 expect(statusTool?.tool.annotations?.idempotentHint).toBe(true);
706 expect(statusTool?.tool.annotations?.destructiveHint).toBe(false);
707​
708 const snapshotTool = server.tools.find(({ tool }) => tool.name === "preview_snapshot");
709 expect(snapshotTool?.tool.annotations?.readOnlyHint).toBe(true);
710 expect(snapshotTool?.tool.annotations?.idempotentHint).toBe(true);
711 expect(snapshotTool?.tool.annotations?.openWorldHint).toBe(true);
712​
713 const clickTool = server.tools.find(({ tool }) => tool.name === "preview_click");
714 expect(clickTool?.tool.annotations?.readOnlyHint).toBe(false);
715 expect(clickTool?.tool.annotations?.destructiveHint).toBe(true);
716 expect(clickTool?.tool.annotations?.openWorldHint).toBe(true);
717 expect(clickTool?.tool.outputSchema).toMatchObject({
718 type: "object",
719 additionalProperties: false,
720 description: "The preview action completed successfully.",
721 });
722​
723 const navigateTool = server.tools.find(({ tool }) => tool.name === "preview_navigate");
724 expect(navigateTool?.tool.annotations?.destructiveHint).toBe(false);
725 expect(navigateTool?.tool.annotations?.openWorldHint).toBe(true);
726​
727 const status = yield* server
728 .callTool({ name: "preview_status", arguments: {} })
729 .pipe(
730 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
731 Effect.provideService(McpSchema.McpServerClient, client),
732 );
733 expect(status.isError).toBe(false);
734 expect(status.structuredContent).toMatchObject({
735 available: true,
736 tabId,
737 });
738​
739 const malformed = yield* server
740 .callTool({ name: "preview_click", arguments: { selector: "" } })
741 .pipe(
742 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
743 Effect.provideService(McpSchema.McpServerClient, client),
744 Effect.flip,
745 );
746 expect(malformed._tag).toBe("InvalidParams");
747​
748 const snapshot = yield* server
749 .callTool({ name: "preview_snapshot", arguments: { tabId: alternateTabId } })
750 .pipe(
751 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
752 Effect.provideService(McpSchema.McpServerClient, client),
753 );
754 expect(snapshot.isError).toBe(false);
755 expect(snapshot.content.some((content) => content.type === "image")).toBe(true);
756 expect(snapshot.structuredContent).toMatchObject({
757 screenshot: { mimeType: "image/png", width: 10, height: 5 },
758 });
759 expect(routedRequests.find(({ operation }) => operation === "snapshot")?.tabId).toBe(
760 alternateTabId,
761 );
762​
763 // Arrays and primitives are wrapped so structuredContent stays a JSON object.
764 // Claude Code rejects the whole result otherwise.
765 const evaluateTool = server.tools.find(({ tool }) => tool.name === "preview_evaluate");
766 expect(evaluateTool?.tool.outputSchema).toMatchObject({ type: "object" });
767 const evaluated = yield* server
768 .callTool({ name: "preview_evaluate", arguments: { expression: "buttons()" } })
769 .pipe(
770 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
771 Effect.provideService(McpSchema.McpServerClient, client),
772 );
773 expect(evaluated.isError).toBe(false);
774 expect(evaluated.structuredContent).toEqual({ value: ["Connect", "Continue"], toolIcon });
775 const evaluatedText = evaluated.content[0];
776 expect(evaluatedText?.type === "text" ? decodeJsonText(evaluatedText.text) : null).toEqual({
777 toolIcon,
778 value: ["Connect", "Continue"],
779 });
780​
781 const actionRequests = [
782 { name: "preview_click", arguments: { x: 10, y: 10 } },
783 { name: "preview_type", arguments: { text: "Hello" } },
784 { name: "preview_press", arguments: { key: "Enter" } },
785 { name: "preview_scroll", arguments: { deltaY: 100 } },
786 { name: "preview_wait_for", arguments: { text: "Example" } },
787 ];
788 for (const request of actionRequests) {
789 const result = yield* server
790 .callTool(request)
791 .pipe(
792 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
793 Effect.provideService(McpSchema.McpServerClient, client),
794 );
795 expect(result.isError).toBe(false);
796 expect(result.structuredContent).toEqual({ toolIcon });
797 expect(routedRequests.at(-1)?.operation).toBe("status");
798 const text = result.content[0];
799 expect(text?.type === "text" ? decodeJsonText(text.text) : null).toEqual({ toolIcon });
800 }
801 }),
802 ).pipe(Effect.provide(TestLayer)),
803);