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

AcpMcpStdioBridge.test.ts

332 lines12.3 KB

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