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

McpHttpServer.test.ts

288 lines11.2 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 expect(clickTool?.tool.outputSchema).toEqual({
223 type: "object",
224 additionalProperties: false,
225 description: "The preview action completed successfully.",
226 });
227​
228 const navigateTool = server.tools.find(({ tool }) => tool.name === "preview_navigate");
229 expect(navigateTool?.tool.annotations?.destructiveHint).toBe(false);
230 expect(navigateTool?.tool.annotations?.openWorldHint).toBe(true);
231​
232 const status = yield* server
233 .callTool({ name: "preview_status", arguments: {} })
234 .pipe(
235 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
236 Effect.provideService(McpSchema.McpServerClient, client),
237 );
238 expect(status.isError).toBe(false);
239 expect(status.structuredContent).toMatchObject({
240 available: true,
241 tabId,
242 });
243​
244 const malformed = yield* server
245 .callTool({ name: "preview_click", arguments: { selector: "" } })
246 .pipe(
247 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
248 Effect.provideService(McpSchema.McpServerClient, client),
249 Effect.flip,
250 );
251 expect(malformed._tag).toBe("InvalidParams");
252​
253 const snapshot = yield* server
254 .callTool({ name: "preview_snapshot", arguments: { tabId: alternateTabId } })
255 .pipe(
256 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
257 Effect.provideService(McpSchema.McpServerClient, client),
258 );
259 expect(snapshot.isError).toBe(false);
260 expect(snapshot.content.some((content) => content.type === "image")).toBe(true);
261 expect(snapshot.structuredContent).toMatchObject({
262 screenshot: { mimeType: "image/png", width: 10, height: 5 },
263 });
264 expect(routedRequests.find(({ operation }) => operation === "snapshot")?.tabId).toBe(
265 alternateTabId,
266 );
267​
268 const actionRequests = [
269 { name: "preview_click", arguments: { x: 10, y: 10 } },
270 { name: "preview_type", arguments: { text: "Hello" } },
271 { name: "preview_press", arguments: { key: "Enter" } },
272 { name: "preview_scroll", arguments: { deltaY: 100 } },
273 { name: "preview_wait_for", arguments: { text: "Example" } },
274 ];
275 for (const request of actionRequests) {
276 const result = yield* server
277 .callTool(request)
278 .pipe(
279 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
280 Effect.provideService(McpSchema.McpServerClient, client),
281 );
282 expect(result.isError).toBe(false);
283 expect(result.structuredContent).toEqual({});
284 expect(result.content).toEqual([{ type: "text", text: "{}" }]);
285 }
286 }),
287 ).pipe(Effect.provide(TestLayer)),
288);