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 Effect from "effect/Effect";
6import * as Layer from "effect/Layer";
7import * as Stream from "effect/Stream";
8import { McpSchema, McpServer } from "effect/unstable/ai";
9import { HttpBody, HttpClient, HttpRouter, HttpServerResponse } from "effect/unstable/http";
10
11import * as McpHttpServer from "./McpHttpServer.ts";
12import * as McpInvocationContext from "./McpInvocationContext.ts";
13import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
14
15const environmentId = EnvironmentId.make("environment-mcp-test");
16const threadId = ThreadId.make("thread-mcp-test");
17const tabId = PreviewTabId.make("tab-mcp-test");
18const alternateTabId = PreviewTabId.make("tab-mcp-alternate");
19const invocation = {
20 environmentId,
21 threadId,
22 providerSessionId: "provider-session-mcp-test",
23 providerInstanceId: ProviderInstanceId.make("codex"),
24 capabilities: new Set(["preview"] as const),
25 issuedAt: 1,
26 expiresAt: Number.MAX_SAFE_INTEGER,
27};
28const client = McpSchema.McpServerClient.of({
29 clientId: 1,
30 initializePayload: {
31 protocolVersion: "2025-03-26",
32 capabilities: {},
33 clientInfo: { name: "mcp-test", version: "1.0.0" },
34 },
35 getClient: Effect.die("unused"),
36});
37const TestLayer = McpHttpServer.PreviewToolkitRegistrationLive.pipe(
38 Layer.provideMerge(McpServer.McpServer.layer),
39 Layer.provideMerge(PreviewAutomationBroker.layer.pipe(Layer.provide(NodeServices.layer))),
40);
41
42it("normalizes empty successful notification responses to accepted", () => {
43 const notificationResponse = McpHttpServer.normalizeMcpHttpResponse(
44 HttpServerResponse.text("", { status: 200, contentType: "application/json" }),
45 );
46 expect(notificationResponse.status).toBe(202);
47
48 const resultResponse = McpHttpServer.normalizeMcpHttpResponse(
49 HttpServerResponse.jsonUnsafe({ jsonrpc: "2.0", id: 1, result: {} }),
50 );
51 expect(resultResponse.status).toBe(200);
52});
53
54it.effect("returns bounded structural preview snapshot failures", () =>
55 Effect.scoped(
56 Effect.gen(function* () {
57 const server = yield* McpServer.McpServer;
58 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
59 const events = yield* broker.connect({
60 clientId: "mcp-failure-client",
61 environmentId,
62 });
63 yield* Stream.runForEach(events, (event) =>
64 event.type === "connected"
65 ? Effect.void
66 : broker.respond({
67 clientId: "mcp-failure-client",
68 connectionId: event.connectionId,
69 requestId: event.request.requestId,
70 ok: false,
71 error: {
72 _tag: "PreviewAutomationExecutionError",
73 message: "sensitive renderer failure",
74 detail: { consoleOutput: "sensitive browser output" },
75 },
76 }),
77 ).pipe(Effect.forkScoped);
78 yield* Effect.yieldNow;
79
80 const snapshot = yield* server
81 .callTool({ name: "preview_snapshot", arguments: {} })
82 .pipe(
83 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
84 Effect.provideService(McpSchema.McpServerClient, client),
85 );
86
87 expect(snapshot.isError).toBe(true);
88 expect(snapshot.content).toEqual([{ type: "text", text: "Preview snapshot failed." }]);
89 expect(snapshot.structuredContent).toEqual({
90 error: {
91 _tag: "PreviewAutomationExecutionError",
92 operation: "snapshot",
93 failureCount: 1,
94 },
95 });
96 }),
97 ).pipe(Effect.provide(TestLayer)),
98);
99
100it.effect("terminates HTTP MCP sessions with DELETE", () =>
101 Effect.scoped(
102 Effect.gen(function* () {
103 const serverLayer = McpServer.layerHttp({
104 name: "MCP termination test",
105 version: "1.0.0",
106 path: "/mcp",
107 });
108 yield* HttpRouter.serve(serverLayer, {
109 disableListenLog: true,
110 disableLogger: true,
111 }).pipe(Layer.build);
112 const httpClient = yield* HttpClient.HttpClient;
113
114 const initializeResponse = yield* httpClient.post("/mcp", {
115 headers: { accept: "application/json, text/event-stream" },
116 body: HttpBody.text(
117 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"mcp-test","version":"1.0.0"}}}`,
118 "application/json",
119 ),
120 });
121 const sessionId = initializeResponse.headers["mcp-session-id"];
122 expect(initializeResponse.status).toBe(200);
123 expect(sessionId).not.toBeNull();
124
125 const missingSessionResponse = yield* httpClient.del("/mcp");
126 expect(missingSessionResponse.status).toBe(400);
127
128 const unknownSessionResponse = yield* httpClient.del("/mcp", {
129 headers: { "mcp-session-id": "unknown-session" },
130 });
131 expect(unknownSessionResponse.status).toBe(404);
132
133 const terminateResponse = yield* httpClient.del("/mcp", {
134 headers: { "mcp-session-id": sessionId! },
135 });
136 expect(terminateResponse.status).toBe(204);
137
138 const reusedSessionResponse = yield* httpClient.post("/mcp", {
139 headers: {
140 accept: "application/json, text/event-stream",
141 "mcp-session-id": sessionId!,
142 },
143 body: HttpBody.text(
144 `{"jsonrpc":"2.0","id":2,"method":"ping","params":{}}`,
145 "application/json",
146 ),
147 });
148 expect(reusedSessionResponse.status).toBe(404);
149 }),
150 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
151);
152
153it.effect("registers annotated tools and preserves authenticated request context", () =>
154 Effect.scoped(
155 Effect.gen(function* () {
156 const server = yield* McpServer.McpServer;
157 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
158 const routedRequests: Array<{
159 readonly operation: string;
160 readonly tabId?: string | undefined;
161 }> = [];
162 const events = yield* broker.connect({
163 clientId: "mcp-test-client",
164 environmentId,
165 });
166 yield* Stream.runForEach(events, (event) => {
167 if (event.type === "connected") return Effect.void;
168 routedRequests.push(event.request);
169 return broker.respond({
170 clientId: "mcp-test-client",
171 connectionId: event.connectionId,
172 requestId: event.request.requestId,
173 ok: true,
174 result:
175 event.request.operation === "snapshot"
176 ? {
177 url: "http://example.test/",
178 title: "Example",
179 loading: false,
180 visibleText: "Example",
181 interactiveElements: [],
182 accessibilityTree: {},
183 consoleEntries: [],
184 networkEntries: [],
185 actionTimeline: [],
186 screenshot: {
187 mimeType: "image/png",
188 data: Buffer.from("png").toString("base64"),
189 width: 10,
190 height: 5,
191 },
192 }
193 : event.request.operation === "press"
194 ? undefined
195 : {
196 available: true,
197 visible: true,
198 tabId,
199 url: "http://example.test/",
200 title: "Example",
201 loading: false,
202 },
203 });
204 }).pipe(Effect.forkScoped);
205 yield* Effect.yieldNow;
206
207 const statusTool = server.tools.find(({ tool }) => tool.name === "preview_status");
208 expect(statusTool?.tool.annotations?.readOnlyHint).toBe(true);
209 expect(statusTool?.tool.annotations?.idempotentHint).toBe(true);
210 expect(statusTool?.tool.annotations?.destructiveHint).toBe(false);
211
212 const snapshotTool = server.tools.find(({ tool }) => tool.name === "preview_snapshot");
213 expect(snapshotTool?.tool.annotations?.readOnlyHint).toBe(true);
214 expect(snapshotTool?.tool.annotations?.idempotentHint).toBe(true);
215 expect(snapshotTool?.tool.annotations?.openWorldHint).toBe(true);
216
217 const clickTool = server.tools.find(({ tool }) => tool.name === "preview_click");
218 expect(clickTool?.tool.annotations?.readOnlyHint).toBe(false);
219 expect(clickTool?.tool.annotations?.destructiveHint).toBe(true);
220 expect(clickTool?.tool.annotations?.openWorldHint).toBe(true);
221
222 const navigateTool = server.tools.find(({ tool }) => tool.name === "preview_navigate");
223 expect(navigateTool?.tool.annotations?.destructiveHint).toBe(false);
224 expect(navigateTool?.tool.annotations?.openWorldHint).toBe(true);
225
226 const status = yield* server
227 .callTool({ name: "preview_status", arguments: {} })
228 .pipe(
229 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
230 Effect.provideService(McpSchema.McpServerClient, client),
231 );
232 expect(status.isError).toBe(false);
233 expect(status.structuredContent).toMatchObject({
234 available: true,
235 tabId,
236 });
237
238 const malformed = yield* server
239 .callTool({ name: "preview_click", arguments: { selector: "" } })
240 .pipe(
241 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
242 Effect.provideService(McpSchema.McpServerClient, client),
243 );
244 expect(malformed.isError).toBe(true);
245
246 const snapshot = yield* server
247 .callTool({ name: "preview_snapshot", arguments: { tabId: alternateTabId } })
248 .pipe(
249 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
250 Effect.provideService(McpSchema.McpServerClient, client),
251 );
252 expect(snapshot.isError).toBe(false);
253 expect(snapshot.content.some((content) => content.type === "image")).toBe(true);
254 expect(snapshot.structuredContent).toMatchObject({
255 screenshot: { mimeType: "image/png", width: 10, height: 5 },
256 });
257 expect(routedRequests.find(({ operation }) => operation === "snapshot")?.tabId).toBe(
258 alternateTabId,
259 );
260
261 const press = yield* server
262 .callTool({ name: "preview_press", arguments: { key: "Enter" } })
263 .pipe(
264 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
265 Effect.provideService(McpSchema.McpServerClient, client),
266 );
267 expect(press.isError).toBe(false);
268 expect(press.structuredContent).toBeNull();
269 expect(press.content).toEqual([{ type: "text", text: "null" }]);
270 }),
271 ).pipe(Effect.provide(TestLayer)),
272);