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

McpHttpServer.test.ts

770 lines29.9 KB

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