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 Layer from "effect/Layer";
8import * as Schema from "effect/Schema";
9import * as Stream from "effect/Stream";
10import { McpProtocol, McpSchema, McpServer } from "effect/unstable/ai";
11import { HttpBody, HttpClient, HttpRouter, HttpServerResponse } from "effect/unstable/http";
12
13import * as McpHttpServer from "./McpHttpServer.ts";
14import * as McpInvocationContext from "./McpInvocationContext.ts";
15import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
16
17const environmentId = EnvironmentId.make("environment-mcp-test");
18const threadId = ThreadId.make("thread-mcp-test");
19const tabId = PreviewTabId.make("tab-mcp-test");
20const alternateTabId = PreviewTabId.make("tab-mcp-alternate");
21const encodeJsonText = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
22const invocation = {
23 environmentId,
24 threadId,
25 providerSessionId: "provider-session-mcp-test",
26 providerInstanceId: ProviderInstanceId.make("codex"),
27 capabilities: new Set(["preview"] as const),
28 issuedAt: 1,
29};
30const client = McpSchema.McpServerClient.of({
31 clientId: 1,
32 protocolVersion: "2025-06-18",
33 initializePayload: {
34 protocolVersion: "2025-06-18",
35 capabilities: {},
36 clientInfo: { name: "mcp-test", version: "1.0.0" },
37 },
38 getClient: Effect.die("unused"),
39});
40const TestLayer = McpHttpServer.PreviewToolkitRegistrationLive.pipe(
41 Layer.provideMerge(McpServer.McpServer.layer),
42 Layer.provideMerge(PreviewAutomationBroker.layer.pipe(Layer.provide(NodeServices.layer))),
43);
44
45it("normalizes empty successful notification responses to accepted", () => {
46 const notificationResponse = McpHttpServer.normalizeMcpHttpResponse(
47 HttpServerResponse.text("", { status: 200, contentType: "application/json" }),
48 );
49 expect(notificationResponse.status).toBe(202);
50
51 const resultResponse = McpHttpServer.normalizeMcpHttpResponse(
52 HttpServerResponse.jsonUnsafe({ jsonrpc: "2.0", id: 1, result: {} }),
53 );
54 expect(resultResponse.status).toBe(200);
55});
56
57it.effect.each([{}, { includeImage: false }])(
58 "returns bounded structural preview snapshot failures %#",
59 (input) =>
60 Effect.scoped(
61 Effect.gen(function* () {
62 const server = yield* McpServer.McpServer;
63 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
64 const events = yield* broker.connect({
65 clientId: "mcp-failure-client",
66 environmentId,
67 });
68 yield* Stream.runForEach(events, (event) =>
69 event.type === "connected"
70 ? Effect.void
71 : broker.respond({
72 clientId: "mcp-failure-client",
73 connectionId: event.connectionId,
74 requestId: event.request.requestId,
75 ok: false,
76 error: {
77 _tag: "PreviewAutomationExecutionError",
78 message: "sensitive renderer failure",
79 detail: { consoleOutput: "sensitive browser output" },
80 },
81 }),
82 ).pipe(Effect.forkScoped);
83 yield* Effect.yieldNow;
84
85 const snapshot = yield* server
86 .callTool({ name: "preview_snapshot", arguments: input })
87 .pipe(
88 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
89 Effect.provideService(McpSchema.McpServerClient, client),
90 );
91
92 expect(snapshot.isError).toBe(true);
93 expect(snapshot.content).toEqual([{ type: "text", text: "Preview snapshot failed." }]);
94 expect(snapshot.structuredContent).toEqual({
95 error: {
96 _tag: "PreviewAutomationExecutionError",
97 operation: "snapshot",
98 failureCount: 1,
99 },
100 });
101 }),
102 ).pipe(Effect.provide(TestLayer)),
103);
104
105it.effect.each([
106 { mode: "default", input: {}, images: true },
107 { mode: "explicit image", input: { includeImage: true }, images: true },
108 { mode: "text only", input: { includeImage: false }, images: false },
109])("returns fresh $mode snapshots on repeated MCP calls", ({ input, images }) =>
110 Effect.scoped(
111 Effect.gen(function* () {
112 const server = yield* McpServer.McpServer;
113 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
114 const connected = yield* Deferred.make<void>();
115 const png =
116 "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII=";
117 const page = {
118 url: "http://example.test/",
119 loading: false,
120 visibleText: "Save your changes",
121 interactiveElements: [
122 {
123 tag: "button",
124 role: "button",
125 name: "Save",
126 selector: "#save",
127 x: 0,
128 y: 0,
129 width: 20,
130 height: 10,
131 },
132 ],
133 accessibilityTree: { role: "document", name: "Example" },
134 consoleEntries: [],
135 networkEntries: [],
136 actionTimeline: [],
137 };
138 const screenshot = { mimeType: "image/png", width: 1, height: 1 };
139 let requests = 0;
140 const events = yield* broker.connect({ clientId: "mcp-image-option-client", environmentId });
141 yield* Stream.runForEach(events, (event) => {
142 if (event.type === "connected") return Deferred.succeed(connected, undefined);
143 requests += 1;
144 expect(event.request).toMatchObject({
145 operation: "snapshot",
146 tabId: alternateTabId,
147 threadId,
148 });
149 expect(event.request.input).toEqual({});
150 return broker.respond({
151 clientId: "mcp-image-option-client",
152 connectionId: event.connectionId,
153 requestId: event.request.requestId,
154 ok: true,
155 result: {
156 ...page,
157 title: `Snapshot ${requests}`,
158 screenshot: { ...screenshot, data: png },
159 },
160 });
161 }).pipe(Effect.forkScoped);
162 yield* Deferred.await(connected);
163
164 for (const call of [1, 2, 3, 4, 5, 6]) {
165 const snapshot = yield* server
166 .callTool({
167 name: "preview_snapshot",
168 arguments: { ...input, tabId: alternateTabId },
169 })
170 .pipe(
171 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
172 Effect.provideService(McpSchema.McpServerClient, client),
173 );
174 const metadata = { ...page, title: `Snapshot ${call}`, screenshot };
175 expect(snapshot.isError).toBe(false);
176 expect(snapshot.structuredContent).toEqual(metadata);
177 expect(snapshot.content).toEqual([
178 { type: "text", text: encodeJsonText(snapshot.structuredContent) },
179 ...(images
180 ? [
181 {
182 type: "image",
183 mimeType: "image/png",
184 data: new Uint8Array(Buffer.from(png, "base64")),
185 },
186 ]
187 : []),
188 ]);
189 }
190
191 // Output selection belongs to this call, not the MCP session's history.
192 const nextDefault = yield* server
193 .callTool({
194 name: "preview_snapshot",
195 arguments: { tabId: alternateTabId },
196 })
197 .pipe(
198 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
199 Effect.provideService(McpSchema.McpServerClient, client),
200 );
201 expect(nextDefault.content.map((content) => content.type)).toEqual(["text", "image"]);
202 expect(nextDefault.structuredContent).toEqual({ ...page, title: "Snapshot 7", screenshot });
203 expect(requests).toBe(7);
204 }),
205 ).pipe(Effect.provide(TestLayer)),
206);
207
208it.effect("rejects non-boolean snapshot image options before selecting a browser host", () =>
209 Effect.gen(function* () {
210 const server = yield* McpServer.McpServer;
211 for (const includeImage of ["false", 0, null]) {
212 const result = yield* server
213 .callTool({
214 name: "preview_snapshot",
215 arguments: { includeImage },
216 })
217 .pipe(
218 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
219 Effect.provideService(McpSchema.McpServerClient, client),
220 );
221 expect(result.isError).toBe(true);
222 expect(result.content).toEqual([{ type: "text", text: "Preview snapshot failed." }]);
223 expect(result.structuredContent).toEqual({
224 error: { _tag: "AiError", operation: "snapshot", failureCount: 1 },
225 });
226 }
227 }).pipe(Effect.provide(TestLayer)),
228);
229
230it.effect("terminates HTTP MCP sessions with DELETE", () =>
231 Effect.scoped(
232 Effect.gen(function* () {
233 const serverLayer = McpServer.layerHttp({
234 name: "MCP termination test",
235 version: "1.0.0",
236 path: "/mcp",
237 protocols: [McpProtocol.v2025_06_18],
238 });
239 yield* HttpRouter.serve(serverLayer, {
240 disableListenLog: true,
241 disableLogger: true,
242 }).pipe(Layer.build);
243 const httpClient = yield* HttpClient.HttpClient;
244
245 const initializeResponse = yield* httpClient.post("/mcp", {
246 headers: { accept: "application/json, text/event-stream" },
247 body: HttpBody.text(
248 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"mcp-test","version":"1.0.0"}}}`,
249 "application/json",
250 ),
251 });
252 const sessionId = initializeResponse.headers["mcp-session-id"];
253 expect(initializeResponse.status).toBe(200);
254 expect(sessionId).not.toBeNull();
255
256 const missingSessionResponse = yield* httpClient.del("/mcp");
257 expect(missingSessionResponse.status).toBe(400);
258
259 const unknownSessionResponse = yield* httpClient.del("/mcp", {
260 headers: { "mcp-session-id": "unknown-session" },
261 });
262 expect(unknownSessionResponse.status).toBe(404);
263
264 const terminateResponse = yield* httpClient.del("/mcp", {
265 headers: { "mcp-session-id": sessionId! },
266 });
267 expect(terminateResponse.status).toBe(204);
268
269 const reusedSessionResponse = yield* httpClient.post("/mcp", {
270 headers: {
271 accept: "application/json, text/event-stream",
272 "mcp-session-id": sessionId!,
273 },
274 body: HttpBody.text(
275 `{"jsonrpc":"2.0","id":2,"method":"ping","params":{}}`,
276 "application/json",
277 ),
278 });
279 expect(reusedSessionResponse.status).toBe(404);
280 }),
281 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
282);
283
284it.effect("registers annotated tools and preserves authenticated request context", () =>
285 Effect.scoped(
286 Effect.gen(function* () {
287 const server = yield* McpServer.McpServer;
288 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
289 const routedRequests: Array<{
290 readonly operation: string;
291 readonly tabId?: string | undefined;
292 }> = [];
293 const events = yield* broker.connect({
294 clientId: "mcp-test-client",
295 environmentId,
296 });
297 yield* Stream.runForEach(events, (event) => {
298 if (event.type === "connected") return Effect.void;
299 routedRequests.push(event.request);
300 return broker.respond({
301 clientId: "mcp-test-client",
302 connectionId: event.connectionId,
303 requestId: event.request.requestId,
304 ok: true,
305 result:
306 event.request.operation === "snapshot"
307 ? {
308 url: "http://example.test/",
309 title: "Example",
310 loading: false,
311 visibleText: "Example",
312 interactiveElements: [],
313 accessibilityTree: {},
314 consoleEntries: [],
315 networkEntries: [],
316 actionTimeline: [],
317 screenshot: {
318 mimeType: "image/png",
319 data: Buffer.from("png").toString("base64"),
320 width: 10,
321 height: 5,
322 },
323 }
324 : event.request.operation === "press"
325 ? undefined
326 : {
327 available: true,
328 visible: true,
329 tabId,
330 url: "http://example.test/",
331 title: "Example",
332 loading: false,
333 },
334 });
335 }).pipe(Effect.forkScoped);
336 yield* Effect.yieldNow;
337
338 const statusTool = server.tools.find(({ tool }) => tool.name === "preview_status");
339 expect(statusTool?.tool.annotations?.readOnlyHint).toBe(true);
340 expect(statusTool?.tool.annotations?.idempotentHint).toBe(true);
341 expect(statusTool?.tool.annotations?.destructiveHint).toBe(false);
342
343 const snapshotTool = server.tools.find(({ tool }) => tool.name === "preview_snapshot");
344 expect(snapshotTool?.tool.annotations?.readOnlyHint).toBe(true);
345 expect(snapshotTool?.tool.annotations?.idempotentHint).toBe(true);
346 expect(snapshotTool?.tool.annotations?.openWorldHint).toBe(true);
347
348 const clickTool = server.tools.find(({ tool }) => tool.name === "preview_click");
349 expect(clickTool?.tool.annotations?.readOnlyHint).toBe(false);
350 expect(clickTool?.tool.annotations?.destructiveHint).toBe(true);
351 expect(clickTool?.tool.annotations?.openWorldHint).toBe(true);
352 expect(clickTool?.tool.outputSchema).toEqual({
353 type: "object",
354 additionalProperties: false,
355 description: "The preview action completed successfully.",
356 });
357
358 const navigateTool = server.tools.find(({ tool }) => tool.name === "preview_navigate");
359 expect(navigateTool?.tool.annotations?.destructiveHint).toBe(false);
360 expect(navigateTool?.tool.annotations?.openWorldHint).toBe(true);
361
362 const status = yield* server
363 .callTool({ name: "preview_status", arguments: {} })
364 .pipe(
365 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
366 Effect.provideService(McpSchema.McpServerClient, client),
367 );
368 expect(status.isError).toBe(false);
369 expect(status.structuredContent).toMatchObject({
370 available: true,
371 tabId,
372 });
373
374 const malformed = yield* server
375 .callTool({ name: "preview_click", arguments: { selector: "" } })
376 .pipe(
377 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
378 Effect.provideService(McpSchema.McpServerClient, client),
379 Effect.flip,
380 );
381 expect(malformed._tag).toBe("InvalidParams");
382
383 const snapshot = yield* server
384 .callTool({ name: "preview_snapshot", arguments: { tabId: alternateTabId } })
385 .pipe(
386 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
387 Effect.provideService(McpSchema.McpServerClient, client),
388 );
389 expect(snapshot.isError).toBe(false);
390 expect(snapshot.content.some((content) => content.type === "image")).toBe(true);
391 expect(snapshot.structuredContent).toMatchObject({
392 screenshot: { mimeType: "image/png", width: 10, height: 5 },
393 });
394 expect(routedRequests.find(({ operation }) => operation === "snapshot")?.tabId).toBe(
395 alternateTabId,
396 );
397
398 const actionRequests = [
399 { name: "preview_click", arguments: { x: 10, y: 10 } },
400 { name: "preview_type", arguments: { text: "Hello" } },
401 { name: "preview_press", arguments: { key: "Enter" } },
402 { name: "preview_scroll", arguments: { deltaY: 100 } },
403 { name: "preview_wait_for", arguments: { text: "Example" } },
404 ];
405 for (const request of actionRequests) {
406 const result = yield* server
407 .callTool(request)
408 .pipe(
409 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
410 Effect.provideService(McpSchema.McpServerClient, client),
411 );
412 expect(result.isError).toBe(false);
413 expect(result.structuredContent).toEqual({});
414 expect(result.content).toEqual([{ type: "text", text: "{}" }]);
415 }
416 }),
417 ).pipe(Effect.provide(TestLayer)),
418);