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

McpHttpServer.test.ts

283 lines10.5 KB

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