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