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

AcpMcpStdioBridge.test.ts

345 lines13.0 KB

1// @effect-diagnostics nodeBuiltinImport:off globalTimers:off
2import * as NodeStream from "node:stream";
3​
4import { describe, expect, it } from "@effect/vitest";
5import * as Effect from "effect/Effect";
6import * as Fiber from "effect/Fiber";
7​
8import { AcpMcpBridgeError, callAcpMcpTool, runAcpMcpStdioBridge } from "./AcpMcpStdioBridge.ts";
9​
10function makeHarness(responder: (request: Request) => Promise<Response> | Response) {
11 const input = new NodeStream.PassThrough();
12 const written: Array<string> = [];
13 const requests: Array<{ readonly headers: Headers; readonly body: string }> = [];
14 const bridge = runAcpMcpStdioBridge({
15 endpoint: "http://127.0.0.1:1/mcp",
16 authorization: "Bearer bridge-test",
17 input,
18 output: {
19 write: (chunk: string) => {
20 written.push(chunk);
21 },
22 },
23 fetchImplementation: async (_url, init) => {
24 const request = new Request("http://127.0.0.1:1/mcp", init);
25 requests.push({ headers: request.headers, body: String(init?.body ?? "") });
26 return responder(request);
27 },
28 });
29 return { input, written, requests, bridge };
31​
32describe("AcpMcpStdioBridge", () => {
33 it.effect("preserves the original transport failure as the typed error cause", () =>
34 Effect.gen(function* () {
35 const source = new Error("fetch failed");
36 const failure = yield* callAcpMcpTool({
37 endpoint: "http://127.0.0.1:1/mcp",
38 authorization: "Bearer bridge-test",
39 tool: "orchestrator_capabilities",
40 arguments: {},
41 fetchImplementation: () => Promise.reject(source),
42 }).pipe(Effect.asVoid, Effect.flip);
43​
44 expect(failure).toBeInstanceOf(AcpMcpBridgeError);
45 expect(failure.cause).toBe(source);
46 }),
47 );
48​
49 it.effect("calls one tool through a fresh authenticated MCP session", () =>
50 Effect.gen(function* () {
51 const requests: Array<{ readonly body: unknown; readonly headers: Headers }> = [];
52 const result = yield* callAcpMcpTool({
53 endpoint: "http://127.0.0.1:1/mcp",
54 authorization: "Bearer bridge-test",
55 tool: "orchestrator_capabilities",
56 arguments: {},
57 fetchImplementation: async (_url, init) => {
58 const headers = new Headers(init?.headers);
59 const body: unknown = JSON.parse(String(init?.body ?? "{}"));
60 requests.push({ body, headers });
61 const request = body as { readonly id?: unknown; readonly method?: unknown };
62 if (request.method === "notifications/initialized") {
63 return new Response(null, { status: 202 });
64 }
65 return new Response(
66 JSON.stringify({
67 jsonrpc: "2.0",
68 id: request.id,
69 result:
70 request.method === "initialize"
71 ? { protocolVersion: "2025-06-18", capabilities: {}, serverInfo: {} }
72 : { structuredContent: { providers: ["codex"] } },
73 }),
74 {
75 headers: { "content-type": "application/json", "mcp-session-id": "session-42" },
76 },
77 );
78 },
79 });
80​
81 expect(result).toEqual({ structuredContent: { providers: ["codex"] } });
82 expect(requests).toHaveLength(3);
83 expect(requests[0]?.headers.get("authorization")).toBe("Bearer bridge-test");
84 expect(requests[1]?.headers.get("mcp-session-id")).toBe("session-42");
85 expect(requests[2]?.headers.get("mcp-protocol-version")).toBe("2025-06-18");
86 expect(requests[2]?.body).toMatchObject({
87 method: "tools/call",
88 params: { name: "orchestrator_capabilities", arguments: {} },
89 });
90 }),
91 );
92​
93 it.effect("forwards requests and replays the session id and protocol version", () =>
94 Effect.gen(function* () {
95 const { input, written, requests, bridge } = makeHarness((request) => {
96 const body = JSON.parse(String(requests.at(-1)?.body ?? "{}")) as { id?: number };
97 void request;
98 return new Response(
99 JSON.stringify({
100 jsonrpc: "2.0",
101 id: body.id ?? null,
102 result: body.id === 1 ? { protocolVersion: "2025-06-18" } : { ok: true },
103 }),
104 {
105 status: 200,
106 headers: { "content-type": "application/json", "mcp-session-id": "session-42" },
107 },
108 );
109 });
110 const fiber = yield* Effect.forkChild(bridge);
111​
112 input.write(`${JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize" })}\n`);
113 input.write(`${JSON.stringify({ jsonrpc: "2.0", id: 2, method: "tools/list" })}\n`);
114 input.end();
115 yield* Fiber.join(fiber);
116​
117 expect(written).toHaveLength(2);
118 expect(JSON.parse(written[0]!)).toMatchObject({ id: 1 });
119 expect(JSON.parse(written[1]!)).toMatchObject({ id: 2, result: { ok: true } });
120 expect(requests[0]?.headers.get("authorization")).toBe("Bearer bridge-test");
121 expect(requests[1]?.headers.get("mcp-session-id")).toBe("session-42");
122 expect(requests[1]?.headers.get("mcp-protocol-version")).toBe("2025-06-18");
123 }),
124 );
125​
126 it.effect("acknowledges notifications silently and synthesizes errors for failed requests", () =>
127 Effect.gen(function* () {
128 let call = 0;
129 const { input, written, bridge } = makeHarness(() => {
130 call += 1;
131 return call === 1
132 ? new Response(null, { status: 202 })
133 : new Response("upstream broke", { status: 500 });
134 });
135 const fiber = yield* Effect.forkChild(bridge);
136​
137 input.write(`${JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" })}\n`);
138 input.write(`${JSON.stringify({ jsonrpc: "2.0", id: 3, method: "tools/list" })}\n`);
139 input.end();
140 yield* Fiber.join(fiber);
141​
142 expect(written).toHaveLength(1);
143 expect(JSON.parse(written[0]!)).toMatchObject({
144 id: 3,
145 error: { code: -32603 },
146 });
147 }),
148 );
149​
150 it.effect("emits parse errors for malformed JSON-RPC input", () =>
151 Effect.gen(function* () {
152 const { input, written, requests, bridge } = makeHarness(
153 () => new Response(null, { status: 202 }),
154 );
155 const fiber = yield* Effect.forkChild(bridge);
156​
157 input.end("{not-json}\n");
158 yield* Fiber.join(fiber);
159​
160 expect(requests).toHaveLength(0);
161 expect(JSON.parse(written[0]!)).toEqual({
162 jsonrpc: "2.0",
163 id: null,
164 error: { code: -32700, message: "Parse error" },
165 });
166 }),
167 );
168​
169 it.effect("forwards SSE messages before the HTTP response closes", () =>
170 Effect.gen(function* () {
171 let resolveResponseController!: (
172 controller: ReadableStreamDefaultController<Uint8Array>,
173 ) => void;
174 const responseControllerReady = new Promise<ReadableStreamDefaultController<Uint8Array>>(
175 (resolve) => {
176 resolveResponseController = resolve;
177 },
178 );
179 let firstWrite: (() => void) | undefined;
180 const firstWritten = new Promise<void>((resolve) => {
181 firstWrite = resolve;
182 });
183 const input = new NodeStream.PassThrough();
184 const written: Array<string> = [];
185 const fiber = yield* Effect.forkChild(
186 runAcpMcpStdioBridge({
187 endpoint: "http://127.0.0.1:1/mcp",
188 authorization: "Bearer bridge-test",
189 input,
190 output: {
191 write: (chunk) => {
192 written.push(chunk);
193 firstWrite?.();
194 },
195 },
196 fetchImplementation: async () =>
197 new Response(
198 new ReadableStream<Uint8Array>({
199 start: (controller) => {
200 resolveResponseController(controller);
201 },
202 }),
203 { headers: { "content-type": "text/event-stream" } },
204 ),
205 }),
206 );
207​
208 input.write(`${JSON.stringify({ jsonrpc: "2.0", id: 7, method: "tools/call" })}\n`);
209 const responseController = yield* Effect.promise(() => responseControllerReady);
210 responseController.enqueue(
211 new TextEncoder().encode(
212 'data: {"jsonrpc":"2.0","method":"notifications/progress","params":{}}\n\n',
213 ),
214 );
215 yield* Effect.promise(() => firstWritten);
216 expect(JSON.parse(written[0]!)).toMatchObject({ method: "notifications/progress" });
217​
218 responseController.enqueue(
219 new TextEncoder().encode('data: {"jsonrpc":"2.0","id":7,"result":{}}\n\n'),
220 );
221 responseController.close();
222 input.end();
223 yield* Fiber.join(fiber);
224 expect(written).toHaveLength(2);
225 }),
226 );
227​
228 it.effect("forwards client responses while an SSE request is still open", () =>
229 Effect.gen(function* () {
230 let responseController: ReadableStreamDefaultController<Uint8Array> | undefined;
231 let serverRequestWritten: (() => void) | undefined;
232 const serverRequestReachedClient = new Promise<void>((resolve) => {
233 serverRequestWritten = resolve;
234 });
235 const input = new NodeStream.PassThrough();
236 const written: Array<string> = [];
237 const fiber = yield* Effect.forkChild(
238 runAcpMcpStdioBridge({
239 endpoint: "http://127.0.0.1:1/mcp",
240 authorization: "Bearer bridge-test",
241 input,
242 output: {
243 write: (chunk) => {
244 written.push(chunk);
245 if (JSON.parse(chunk).id === "server-request-1") serverRequestWritten?.();
246 },
247 },
248 fetchImplementation: async (_url, init) => {
249 const body = JSON.parse(String(init?.body ?? "{}")) as {
250 readonly id?: unknown;
251 readonly method?: unknown;
252 readonly result?: unknown;
253 };
254 if (body.method === "tools/call") {
255 return new Response(
256 new ReadableStream<Uint8Array>({
257 start: (controller) => {
258 responseController = controller;
259 controller.enqueue(
260 new TextEncoder().encode(
261 'data: {"jsonrpc":"2.0","id":"server-request-1","method":"elicitation/create","params":{}}\n\n',
262 ),
263 );
264 },
265 }),
266 { headers: { "content-type": "text/event-stream" } },
267 );
268 }
269 expect(body).toMatchObject({ id: "server-request-1", result: { action: "accept" } });
270 responseController?.enqueue(
271 new TextEncoder().encode('data: {"jsonrpc":"2.0","id":7,"result":{}}\n\n'),
272 );
273 responseController?.close();
274 return new Response(null, { status: 202 });
275 },
276 }),
277 );
278​
279 input.write(`${JSON.stringify({ jsonrpc: "2.0", id: 7, method: "tools/call" })}\n`);
280 yield* Effect.promise(() => serverRequestReachedClient);
281 input.write(
282 `${JSON.stringify({ jsonrpc: "2.0", id: "server-request-1", result: { action: "accept" } })}\n`,
283 );
284 input.end();
285 yield* Fiber.join(fiber);
286​
287 expect(written.map((line) => JSON.parse(line).id)).toEqual(["server-request-1", 7]);
288 }),
289 );
290​
291 it.effect("forwards cancellation while a tool SSE response is still open", () =>
292 Effect.gen(function* () {
293 let resolveResponseController!: (
294 controller: ReadableStreamDefaultController<Uint8Array>,
295 ) => void;
296 const responseControllerReady = new Promise<ReadableStreamDefaultController<Uint8Array>>(
297 (resolve) => {
298 resolveResponseController = resolve;
299 },
300 );
301 const methods: Array<string> = [];
302 const input = new NodeStream.PassThrough();
303 const written: Array<string> = [];
304 const fiber = yield* Effect.forkChild(
305 runAcpMcpStdioBridge({
306 endpoint: "http://127.0.0.1:1/mcp",
307 authorization: "Bearer bridge-test",
308 input,
309 output: { write: (chunk) => written.push(chunk) },
310 fetchImplementation: async (_url, init) => {
311 const body = JSON.parse(String(init?.body ?? "{}")) as {
312 readonly method?: string;
313 };
314 methods.push(body.method ?? "");
315 if (body.method === "tools/call") {
316 return new Response(
317 new ReadableStream<Uint8Array>({
318 start: resolveResponseController,
319 }),
320 { headers: { "content-type": "text/event-stream" } },
321 );
322 }
323 const controller = await responseControllerReady;
324 controller.enqueue(
325 new TextEncoder().encode('data: {"jsonrpc":"2.0","id":7,"result":{}}\n\n'),
326 );
327 controller.close();
328 return new Response(null, { status: 202 });
329 },
330 }),
331 );
332​
333 input.write(`${JSON.stringify({ jsonrpc: "2.0", id: 7, method: "tools/call" })}\n`);
334 yield* Effect.promise(() => responseControllerReady);
335 input.write(
336 `${JSON.stringify({ jsonrpc: "2.0", method: "notifications/cancelled", params: { requestId: 7 } })}\n`,
337 );
338 input.end();
339 yield* Fiber.join(fiber);
340​
341 expect(methods).toEqual(["tools/call", "notifications/cancelled"]);
342 expect(JSON.parse(written[0]!)).toMatchObject({ id: 7, result: {} });
343 }),
344 );
345});