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

McpHttpServer.test.ts

274 lines10.6 KB

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 { McpProtocol, 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 protocolVersion: "2025-06-18",
30 initializePayload: {
31 protocolVersion: "2025-06-18",
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 protocols: [McpProtocol.v2025_06_18],
108 });
109 yield* HttpRouter.serve(serverLayer, {
110 disableListenLog: true,
111 disableLogger: true,
112 }).pipe(Layer.build);
113 const httpClient = yield* HttpClient.HttpClient;
114​
115 const initializeResponse = yield* httpClient.post("/mcp", {
116 headers: { accept: "application/json, text/event-stream" },
117 body: HttpBody.text(
118 `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"mcp-test","version":"1.0.0"}}}`,
119 "application/json",
120 ),
121 });
122 const sessionId = initializeResponse.headers["mcp-session-id"];
123 expect(initializeResponse.status).toBe(200);
124 expect(sessionId).not.toBeNull();
125​
126 const missingSessionResponse = yield* httpClient.del("/mcp");
127 expect(missingSessionResponse.status).toBe(400);
128​
129 const unknownSessionResponse = yield* httpClient.del("/mcp", {
130 headers: { "mcp-session-id": "unknown-session" },
131 });
132 expect(unknownSessionResponse.status).toBe(404);
133​
134 const terminateResponse = yield* httpClient.del("/mcp", {
135 headers: { "mcp-session-id": sessionId! },
136 });
137 expect(terminateResponse.status).toBe(204);
138​
139 const reusedSessionResponse = yield* httpClient.post("/mcp", {
140 headers: {
141 accept: "application/json, text/event-stream",
142 "mcp-session-id": sessionId!,
143 },
144 body: HttpBody.text(
145 `{"jsonrpc":"2.0","id":2,"method":"ping","params":{}}`,
146 "application/json",
147 ),
148 });
149 expect(reusedSessionResponse.status).toBe(404);
150 }),
151 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
152);
153​
154it.effect("registers annotated tools and preserves authenticated request context", () =>
155 Effect.scoped(
156 Effect.gen(function* () {
157 const server = yield* McpServer.McpServer;
158 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
159 const routedRequests: Array<{
160 readonly operation: string;
161 readonly tabId?: string | undefined;
162 }> = [];
163 const events = yield* broker.connect({
164 clientId: "mcp-test-client",
165 environmentId,
166 });
167 yield* Stream.runForEach(events, (event) => {
168 if (event.type === "connected") return Effect.void;
169 routedRequests.push(event.request);
170 return broker.respond({
171 clientId: "mcp-test-client",
172 connectionId: event.connectionId,
173 requestId: event.request.requestId,
174 ok: true,
175 result:
176 event.request.operation === "snapshot"
177 ? {
178 url: "http://example.test/",
179 title: "Example",
180 loading: false,
181 visibleText: "Example",
182 interactiveElements: [],
183 accessibilityTree: {},
184 consoleEntries: [],
185 networkEntries: [],
186 actionTimeline: [],
187 screenshot: {
188 mimeType: "image/png",
189 data: Buffer.from("png").toString("base64"),
190 width: 10,
191 height: 5,
192 },
193 }
194 : event.request.operation === "press"
195 ? undefined
196 : {
197 available: true,
198 visible: true,
199 tabId,
200 url: "http://example.test/",
201 title: "Example",
202 loading: false,
203 },
204 });
205 }).pipe(Effect.forkScoped);
206 yield* Effect.yieldNow;
207​
208 const statusTool = server.tools.find(({ tool }) => tool.name === "preview_status");
209 expect(statusTool?.tool.annotations?.readOnlyHint).toBe(true);
210 expect(statusTool?.tool.annotations?.idempotentHint).toBe(true);
211 expect(statusTool?.tool.annotations?.destructiveHint).toBe(false);
212​
213 const snapshotTool = server.tools.find(({ tool }) => tool.name === "preview_snapshot");
214 expect(snapshotTool?.tool.annotations?.readOnlyHint).toBe(true);
215 expect(snapshotTool?.tool.annotations?.idempotentHint).toBe(true);
216 expect(snapshotTool?.tool.annotations?.openWorldHint).toBe(true);
217​
218 const clickTool = server.tools.find(({ tool }) => tool.name === "preview_click");
219 expect(clickTool?.tool.annotations?.readOnlyHint).toBe(false);
220 expect(clickTool?.tool.annotations?.destructiveHint).toBe(true);
221 expect(clickTool?.tool.annotations?.openWorldHint).toBe(true);
222​
223 const navigateTool = server.tools.find(({ tool }) => tool.name === "preview_navigate");
224 expect(navigateTool?.tool.annotations?.destructiveHint).toBe(false);
225 expect(navigateTool?.tool.annotations?.openWorldHint).toBe(true);
226​
227 const status = yield* server
228 .callTool({ name: "preview_status", arguments: {} })
229 .pipe(
230 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
231 Effect.provideService(McpSchema.McpServerClient, client),
232 );
233 expect(status.isError).toBe(false);
234 expect(status.structuredContent).toMatchObject({
235 available: true,
236 tabId,
237 });
238​
239 const malformed = yield* server
240 .callTool({ name: "preview_click", arguments: { selector: "" } })
241 .pipe(
242 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
243 Effect.provideService(McpSchema.McpServerClient, client),
244 Effect.flip,
245 );
246 expect(malformed._tag).toBe("InvalidParams");
247​
248 const snapshot = yield* server
249 .callTool({ name: "preview_snapshot", arguments: { tabId: alternateTabId } })
250 .pipe(
251 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
252 Effect.provideService(McpSchema.McpServerClient, client),
253 );
254 expect(snapshot.isError).toBe(false);
255 expect(snapshot.content.some((content) => content.type === "image")).toBe(true);
256 expect(snapshot.structuredContent).toMatchObject({
257 screenshot: { mimeType: "image/png", width: 10, height: 5 },
258 });
259 expect(routedRequests.find(({ operation }) => operation === "snapshot")?.tabId).toBe(
260 alternateTabId,
261 );
262​
263 const press = yield* server
264 .callTool({ name: "preview_press", arguments: { key: "Enter" } })
265 .pipe(
266 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
267 Effect.provideService(McpSchema.McpServerClient, client),
268 );
269 expect(press.isError).toBe(false);
270 expect(press.structuredContent).toBeNull();
271 expect(press.content).toEqual([{ type: "text", text: "null" }]);
272 }),
273 ).pipe(Effect.provide(TestLayer)),
274);