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

McpHttpServer.test.ts

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