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

McpHttpServer.test.ts

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