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

McpHttpServer.test.ts

264 lines10.3 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 { 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 invocation = {
19 environmentId,
20 threadId,
21 providerSessionId: "provider-session-mcp-test",
22 providerInstanceId: ProviderInstanceId.make("codex"),
23 capabilities: new Set(["preview"] as const),
24 issuedAt: 1,
25 expiresAt: Number.MAX_SAFE_INTEGER,
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 events = yield* broker.connect({
158 clientId: "mcp-test-client",
159 environmentId,
160 });
161 yield* Stream.runForEach(events, (event) =>
162 event.type === "connected"
163 ? Effect.void
164 : broker.respond({
165 clientId: "mcp-test-client",
166 connectionId: event.connectionId,
167 requestId: event.request.requestId,
168 ok: true,
169 result:
170 event.request.operation === "snapshot"
171 ? {
172 url: "http://example.test/",
173 title: "Example",
174 loading: false,
175 visibleText: "Example",
176 interactiveElements: [],
177 accessibilityTree: {},
178 consoleEntries: [],
179 networkEntries: [],
180 actionTimeline: [],
181 screenshot: {
182 mimeType: "image/png",
183 data: Buffer.from("png").toString("base64"),
184 width: 10,
185 height: 5,
186 },
187 }
188 : event.request.operation === "press"
189 ? undefined
190 : {
191 available: true,
192 visible: true,
193 tabId,
194 url: "http://example.test/",
195 title: "Example",
196 loading: false,
197 },
198 }),
199 ).pipe(Effect.forkScoped);
200 yield* Effect.yieldNow;
201​
202 const statusTool = server.tools.find(({ tool }) => tool.name === "preview_status");
203 expect(statusTool?.tool.annotations?.readOnlyHint).toBe(true);
204 expect(statusTool?.tool.annotations?.idempotentHint).toBe(true);
205 expect(statusTool?.tool.annotations?.destructiveHint).toBe(false);
206​
207 const snapshotTool = server.tools.find(({ tool }) => tool.name === "preview_snapshot");
208 expect(snapshotTool?.tool.annotations?.readOnlyHint).toBe(true);
209 expect(snapshotTool?.tool.annotations?.idempotentHint).toBe(true);
210 expect(snapshotTool?.tool.annotations?.openWorldHint).toBe(true);
211​
212 const clickTool = server.tools.find(({ tool }) => tool.name === "preview_click");
213 expect(clickTool?.tool.annotations?.readOnlyHint).toBe(false);
214 expect(clickTool?.tool.annotations?.destructiveHint).toBe(true);
215 expect(clickTool?.tool.annotations?.openWorldHint).toBe(true);
216​
217 const navigateTool = server.tools.find(({ tool }) => tool.name === "preview_navigate");
218 expect(navigateTool?.tool.annotations?.destructiveHint).toBe(false);
219 expect(navigateTool?.tool.annotations?.openWorldHint).toBe(true);
220​
221 const status = yield* server
222 .callTool({ name: "preview_status", arguments: {} })
223 .pipe(
224 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
225 Effect.provideService(McpSchema.McpServerClient, client),
226 );
227 expect(status.isError).toBe(false);
228 expect(status.structuredContent).toMatchObject({
229 available: true,
230 tabId,
231 });
232​
233 const malformed = yield* server
234 .callTool({ name: "preview_click", arguments: { selector: "" } })
235 .pipe(
236 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
237 Effect.provideService(McpSchema.McpServerClient, client),
238 );
239 expect(malformed.isError).toBe(true);
240​
241 const snapshot = yield* server
242 .callTool({ name: "preview_snapshot", arguments: {} })
243 .pipe(
244 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
245 Effect.provideService(McpSchema.McpServerClient, client),
246 );
247 expect(snapshot.isError).toBe(false);
248 expect(snapshot.content.some((content) => content.type === "image")).toBe(true);
249 expect(snapshot.structuredContent).toMatchObject({
250 screenshot: { mimeType: "image/png", width: 10, height: 5 },
251 });
252​
253 const press = yield* server
254 .callTool({ name: "preview_press", arguments: { key: "Enter" } })
255 .pipe(
256 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
257 Effect.provideService(McpSchema.McpServerClient, client),
258 );
259 expect(press.isError).toBe(false);
260 expect(press.structuredContent).toBeNull();
261 expect(press.content).toEqual([{ type: "text", text: "null" }]);
262 }),
263 ).pipe(Effect.provide(TestLayer)),
264);