Open History to see the last commit
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 * as ProviderRegistry from "../provider/Services/ProviderRegistry.ts";
18import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.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 OrchestratorTestLayer = McpHttpServer.OrchestratorToolkitRegistrationLive.pipe(
69 Layer.provideMerge(McpServer.McpServer.layer),
70 Layer.provide(
71 Layer.mergeAll(
72 Layer.mock(ProjectionSnapshotQuery)({}),
73 Layer.mock(OrchestrationEngineService)({}),
74 Layer.mock(ProviderRegistry.ProviderRegistry)({}),
75 NodeServices.layer,
76 ),
77 ),
78);
79
80const snapshotResult = {
81 url: "http://example.test/",
82 title: "Example",
83 loading: false,
84 visibleText: "Example",
85 interactiveElements: [],
86 accessibilityTree: {},
87 consoleEntries: [],
88 networkEntries: [],
89 actionTimeline: [],
90 screenshot: {
91 mimeType: "image/png",
92 data: Buffer.from("png").toString("base64"),
93 width: 10,
94 height: 5,
95 },
96};
97
98/** Answers every snapshot request on a fresh broker host with the given result. */
99const serveSnapshots = (clientId: string, result: unknown) =>
100 Effect.gen(function* () {
101 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
102 const connected = yield* Deferred.make<void>();
103 const inputs: Array<unknown> = [];
104 const events = yield* broker.connect({ clientId, environmentId });
105 yield* Stream.runForEach(events, (event) => {
106 if (event.type === "connected") return Deferred.succeed(connected, undefined);
107 inputs.push(event.request.input);
108 return broker.respond({
109 clientId,
110 connectionId: event.connectionId,
111 requestId: event.request.requestId,
112 ok: true,
113 result,
114 });
115 }).pipe(Effect.forkScoped);
116 yield* Deferred.await(connected);
117 return inputs;
118 });
119
120const callSnapshot = (args: Record<string, unknown>) =>
121 Effect.gen(function* () {
122 const server = yield* McpServer.McpServer;
123 return yield* server
124 .callTool({ name: "preview_snapshot", arguments: args })
125 .pipe(
126 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
127 Effect.provideService(McpSchema.McpServerClient, client),
128 );
129 });
130
131it("normalizes empty successful notification responses to accepted", () => {
132 const notificationResponse = McpHttpServer.normalizeMcpHttpResponse(
133 HttpServerResponse.text("", { status: 200, contentType: "application/json" }),
134 );
135 expect(notificationResponse.status).toBe(202);
136
137 const resultResponse = McpHttpServer.normalizeMcpHttpResponse(
138 HttpServerResponse.jsonUnsafe({ jsonrpc: "2.0", id: 1, result: {} }),
139 );
140 expect(resultResponse.status).toBe(200);
141});
142
143it.effect.each([{}, { includeImage: false }])(
144 "returns bounded structural preview snapshot failures %#",
145 (input) =>
146 Effect.scoped(
147 Effect.gen(function* () {
148 const server = yield* McpServer.McpServer;
149 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
150 const events = yield* broker.connect({
151 clientId: "mcp-failure-client",
152 environmentId,
153 });
154 yield* Stream.runForEach(events, (event) =>
155 event.type === "connected"
156 ? Effect.void
157 : broker.respond({
158 clientId: "mcp-failure-client",
159 connectionId: event.connectionId,
160 requestId: event.request.requestId,
161 ok: false,
162 error: {
163 _tag: "PreviewAutomationExecutionError",
164 message: "sensitive renderer failure",
165 detail: { consoleOutput: "sensitive browser output" },
166 },
167 }),
168 ).pipe(Effect.forkScoped);
169 yield* Effect.yieldNow;
170
171 const snapshot = yield* server
172 .callTool({ name: "preview_snapshot", arguments: input })
173 .pipe(
174 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
175 Effect.provideService(McpSchema.McpServerClient, client),
176 );
177
178 expect(snapshot.isError).toBe(true);
179 expect(snapshot.content).toEqual([
180 { type: "text", text: "Preview snapshot failed: PreviewAutomationExecutionError." },
181 ]);
182 expect(snapshot.structuredContent).toEqual({
183 error: {
184 _tag: "PreviewAutomationExecutionError",
185 operation: "snapshot",
186 failureCount: 1,
187 },
188 });
189 }),
190 ).pipe(Effect.provide(TestLayer)),
191);
192
193it.effect.each([
194 { mode: "default", input: {}, images: true },
195 { mode: "explicit image", input: { includeImage: true }, images: true },
196 { mode: "text only", input: { includeImage: false }, images: false },
197])("returns fresh $mode snapshots on repeated MCP calls", ({ input, images }) =>
198 Effect.scoped(
199 Effect.gen(function* () {
200 const server = yield* McpServer.McpServer;
201 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
202 const connected = yield* Deferred.make<void>();
203 const png =
204 "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII=";
205 const page = {
206 url: "http://example.test/",
207 loading: false,
208 visibleText: "Save your changes",
209 interactiveElements: [
210 {
211 tag: "button",
212 role: "button",
213 name: "Save",
214 selector: "#save",
215 x: 0,
216 y: 0,
217 width: 20,
218 height: 10,
219 },
220 ],
221 accessibilityTree: { role: "document", name: "Example" },
222 consoleEntries: [],
223 networkEntries: [],
224 actionTimeline: [],
225 };
226 const screenshot = { mimeType: "image/png", width: 1, height: 1 };
227 let requests = 0;
228 const events = yield* broker.connect({ clientId: "mcp-image-option-client", environmentId });
229 yield* Stream.runForEach(events, (event) => {
230 if (event.type === "connected") return Deferred.succeed(connected, undefined);
231 requests += 1;
232 expect(event.request).toMatchObject({
233 operation: "snapshot",
234 tabId: alternateTabId,
235 threadId,
236 });
237 expect(event.request.input).toEqual({});
238 return broker.respond({
239 clientId: "mcp-image-option-client",
240 connectionId: event.connectionId,
241 requestId: event.request.requestId,
242 ok: true,
243 result: {
244 ...page,
245 title: `Snapshot ${requests}`,
246 screenshot: { ...screenshot, data: png },
247 },
248 });
249 }).pipe(Effect.forkScoped);
250 yield* Deferred.await(connected);
251
252 for (const call of [1, 2, 3, 4, 5, 6]) {
253 const snapshot = yield* server
254 .callTool({
255 name: "preview_snapshot",
256 arguments: { ...input, tabId: alternateTabId },
257 })
258 .pipe(
259 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
260 Effect.provideService(McpSchema.McpServerClient, client),
261 );
262 const metadata = { ...page, title: `Snapshot ${call}`, screenshot };
263 const { accessibilityTree: _tree, ...boundedMetadata } = metadata;
264 expect(snapshot.isError).toBe(false);
265 expect(snapshot.structuredContent).toEqual(metadata);
266 const [identity, text, ...rest] = snapshot.content;
267 expect(identity?.type === "text" ? decodeJsonText(identity.text) : null).toEqual({
268 url: page.url,
269 });
270 expect(text?.type === "text" ? decodeJsonText(text.text) : null).toEqual(boundedMetadata);
271 expect(rest).toEqual([
272 {
273 type: "text",
274 text: "Snapshot text was bounded. Omitted: accessibilityTree (use interactiveElements locators or preview_evaluate).",
275 },
276 ...(images
277 ? [
278 {
279 type: "image",
280 mimeType: "image/png",
281 data: new Uint8Array(Buffer.from(png, "base64")),
282 },
283 ]
284 : []),
285 ]);
286 }
287
288 // Output selection belongs to this call, not the MCP session's history.
289 const nextDefault = yield* server
290 .callTool({
291 name: "preview_snapshot",
292 arguments: { tabId: alternateTabId },
293 })
294 .pipe(
295 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
296 Effect.provideService(McpSchema.McpServerClient, client),
297 );
298 expect(nextDefault.content.map((content) => content.type)).toEqual([
299 "text",
300 "text",
301 "text",
302 "image",
303 ]);
304 expect(nextDefault.structuredContent).toEqual({ ...page, title: "Snapshot 7", screenshot });
305 expect(requests).toBe(7);
306 }),
307 ).pipe(Effect.provide(TestLayer)),
308);
309
310it.effect("rejects non-boolean snapshot image options before selecting a browser host", () =>
311 Effect.gen(function* () {
312 const server = yield* McpServer.McpServer;
313 for (const includeImage of ["false", 0, null]) {
314 const result = yield* server
315 .callTool({
316 name: "preview_snapshot",
317 arguments: { includeImage },
318 })
319 .pipe(
320 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
321 Effect.provideService(McpSchema.McpServerClient, client),
322 );
323 expect(result.isError).toBe(true);
324 expect(result.content).toEqual([{ type: "text", text: "Preview snapshot failed: AiError." }]);
325 expect(result.structuredContent).toEqual({
326 error: { _tag: "AiError", operation: "snapshot", failureCount: 1 },
327 });
328 }
329 }).pipe(Effect.provide(TestLayer)),
330);
331
332it.effect("saves the snapshot PNG on request and reports its path", () =>
333 Effect.scoped(
334 Effect.gen(function* () {
335 const config = yield* ServerConfig.ServerConfig;
336 const fileSystem = yield* FileSystem.FileSystem;
337 const path = yield* Path.Path;
338 const inputs = yield* serveSnapshots("mcp-save-client", snapshotResult);
339
340 const snapshot = yield* callSnapshot({ save: true });
341
342 expect(snapshot.isError).toBe(false);
343 // The browser never receives the server-only `save` flag.
344 expect(inputs).toEqual([{}]);
345 const structured = snapshot.structuredContent as { readonly screenshotPath?: string };
346 const screenshotPath = structured.screenshotPath;
347 expect(typeof screenshotPath).toBe("string");
348 expect(path.dirname(screenshotPath!)).toBe(config.browserArtifactsDir);
349 expect(path.basename(screenshotPath!)).toMatch(
350 /^browser-screenshot-example-test-[0-9a-z]+-[0-9a-f]{8}\.png$/,
351 );
352 expect(Buffer.from(yield* fileSystem.readFile(screenshotPath!)).toString()).toBe("png");
353 const [, text] = snapshot.content;
354 expect(text?.type === "text" ? text.text : "").toContain(screenshotPath);
355
356 const unsaved = yield* callSnapshot({});
357 expect(unsaved.structuredContent).not.toHaveProperty("screenshotPath");
358 }),
359 ).pipe(Effect.provide(TestLayer)),
360);
361
362it.effect("reports a tagged error when the screenshot cannot be saved", () =>
363 Effect.scoped(
364 Effect.gen(function* () {
365 const config = yield* ServerConfig.ServerConfig;
366 const fileSystem = yield* FileSystem.FileSystem;
367 // A regular file where the artifacts directory should be makes every write fail.
368 yield* fileSystem.writeFileString(config.browserArtifactsDir, "");
369 yield* serveSnapshots("mcp-save-failure-client", snapshotResult);
370
371 const snapshot = yield* callSnapshot({ save: true });
372
373 expect(snapshot.isError).toBe(true);
374 expect(snapshot.content).toEqual([
375 { type: "text", text: "Preview snapshot failed: PreviewScreenshotSaveError." },
376 ]);
377 expect(snapshot.structuredContent).toEqual({
378 error: { _tag: "PreviewScreenshotSaveError", operation: "snapshot", failureCount: 1 },
379 });
380 }),
381 ).pipe(Effect.provide(TestLayer)),
382);
383
384it.effect(
385 "registers the pull request toolkit and surfaces a missing capability as a tool error",
386 () =>
387 Effect.gen(function* () {
388 const server = yield* McpServer.McpServer;
389 const names = server.tools.map(({ tool }) => tool.name);
390 expect(names).toEqual(
391 expect.arrayContaining([
392 "link_pull_request",
393 "unlink_pull_request",
394 "list_thread_pull_requests",
395 ]),
396 );
397 const linkTool = server.tools.find(({ tool }) => tool.name === "link_pull_request");
398 expect(linkTool?.tool.annotations?.idempotentHint).toBe(true);
399 expect(linkTool?.tool.annotations?.openWorldHint).toBe(false);
400 expect(linkTool?.tool.description).toContain("Register every pull request you open");
401
402 const denied = yield* server
403 .callTool({ name: "list_thread_pull_requests", arguments: {} })
404 .pipe(
405 // A preview-only credential: the token predates the toolkit or was minted elsewhere.
406 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
407 Effect.provideService(McpSchema.McpServerClient, client),
408 );
409 expect(denied.isError).toBe(true);
410 expect(denied.content).toEqual([
411 { type: "text", text: "MCP credential does not grant the pull-requests capability." },
412 ]);
413 }).pipe(Effect.provide(PullRequestsTestLayer)),
414);
415
416it.effect("registers the V2 orchestrator tools and returns a denied capability as a result", () =>
417 Effect.gen(function* () {
418 const server = yield* McpServer.McpServer;
419 const names = server.tools.map(({ tool }) => tool.name);
420 expect(names).toEqual(expect.arrayContaining(["orchestrator_capabilities", "create_threads"]));
421
422 // Same shape V2 returns: a declared failure is a result the agent can
423 // branch on by code, not a transport error.
424 const denied = yield* server
425 .callTool({ name: "create_threads", arguments: { threads: [{ prompt: "Do it" }] } })
426 .pipe(
427 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
428 Effect.provideService(McpSchema.McpServerClient, client),
429 );
430 expect(denied.isError).toBe(false);
431 expect(denied.structuredContent).toMatchObject({
432 _tag: "OrchestratorMcpFailure",
433 code: "capability_denied",
434 });
435 }).pipe(Effect.provide(OrchestratorTestLayer)),
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: true,
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);