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