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

AcpMcpStdioBridge.test.ts

285 lines10.5 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 { 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("forwards requests and replays the session id and protocol version", () =>
34 Effect.gen(function* () {
35 const { input, written, requests, bridge } = makeHarness((request) => {
36 const body = JSON.parse(String(requests.at(-1)?.body ?? "{}")) as { id?: number };
37 void request;
38 return new Response(
39 JSON.stringify({
40 jsonrpc: "2.0",
41 id: body.id ?? null,
42 result: body.id === 1 ? { protocolVersion: "2025-06-18" } : { ok: true },
43 }),
44 {
45 status: 200,
46 headers: { "content-type": "application/json", "mcp-session-id": "session-42" },
47 },
48 );
49 });
50 const fiber = yield* Effect.forkChild(bridge);
51​
52 input.write(`${JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize" })}\n`);
53 input.write(`${JSON.stringify({ jsonrpc: "2.0", id: 2, method: "tools/list" })}\n`);
54 input.end();
55 yield* Fiber.join(fiber);
56​
57 expect(written).toHaveLength(2);
58 expect(JSON.parse(written[0]!)).toMatchObject({ id: 1 });
59 expect(JSON.parse(written[1]!)).toMatchObject({ id: 2, result: { ok: true } });
60 expect(requests[0]?.headers.get("authorization")).toBe("Bearer bridge-test");
61 expect(requests[1]?.headers.get("mcp-session-id")).toBe("session-42");
62 expect(requests[1]?.headers.get("mcp-protocol-version")).toBe("2025-06-18");
63 }),
64 );
65​
66 it.effect("acknowledges notifications silently and synthesizes errors for failed requests", () =>
67 Effect.gen(function* () {
68 let call = 0;
69 const { input, written, bridge } = makeHarness(() => {
70 call += 1;
71 return call === 1
72 ? new Response(null, { status: 202 })
73 : new Response("upstream broke", { status: 500 });
74 });
75 const fiber = yield* Effect.forkChild(bridge);
76​
77 input.write(`${JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" })}\n`);
78 input.write(`${JSON.stringify({ jsonrpc: "2.0", id: 3, method: "tools/list" })}\n`);
79 input.end();
80 yield* Fiber.join(fiber);
81​
82 expect(written).toHaveLength(1);
83 expect(JSON.parse(written[0]!)).toMatchObject({
84 id: 3,
85 error: { code: -32603 },
86 });
87 }),
88 );
89​
90 it.effect("emits parse errors for malformed JSON-RPC input", () =>
91 Effect.gen(function* () {
92 const { input, written, requests, bridge } = makeHarness(
93 () => new Response(null, { status: 202 }),
94 );
95 const fiber = yield* Effect.forkChild(bridge);
96​
97 input.end("{not-json}\n");
98 yield* Fiber.join(fiber);
99​
100 expect(requests).toHaveLength(0);
101 expect(JSON.parse(written[0]!)).toEqual({
102 jsonrpc: "2.0",
103 id: null,
104 error: { code: -32700, message: "Parse error" },
105 });
106 }),
107 );
108​
109 it.effect("forwards SSE messages before the HTTP response closes", () =>
110 Effect.gen(function* () {
111 let resolveResponseController!: (
112 controller: ReadableStreamDefaultController<Uint8Array>,
113 ) => void;
114 const responseControllerReady = new Promise<ReadableStreamDefaultController<Uint8Array>>(
115 (resolve) => {
116 resolveResponseController = resolve;
117 },
118 );
119 let firstWrite: (() => void) | undefined;
120 const firstWritten = new Promise<void>((resolve) => {
121 firstWrite = resolve;
122 });
123 const input = new NodeStream.PassThrough();
124 const written: Array<string> = [];
125 const fiber = yield* Effect.forkChild(
126 runAcpMcpStdioBridge({
127 endpoint: "http://127.0.0.1:1/mcp",
128 authorization: "Bearer bridge-test",
129 input,
130 output: {
131 write: (chunk) => {
132 written.push(chunk);
133 firstWrite?.();
134 },
135 },
136 fetchImplementation: async () =>
137 new Response(
138 new ReadableStream<Uint8Array>({
139 start: (controller) => {
140 resolveResponseController(controller);
141 },
142 }),
143 { headers: { "content-type": "text/event-stream" } },
144 ),
145 }),
146 );
147​
148 input.write(`${JSON.stringify({ jsonrpc: "2.0", id: 7, method: "tools/call" })}\n`);
149 const responseController = yield* Effect.promise(() => responseControllerReady);
150 responseController.enqueue(
151 new TextEncoder().encode(
152 'data: {"jsonrpc":"2.0","method":"notifications/progress","params":{}}\n\n',
153 ),
154 );
155 yield* Effect.promise(() => firstWritten);
156 expect(JSON.parse(written[0]!)).toMatchObject({ method: "notifications/progress" });
157​
158 responseController.enqueue(
159 new TextEncoder().encode('data: {"jsonrpc":"2.0","id":7,"result":{}}\n\n'),
160 );
161 responseController.close();
162 input.end();
163 yield* Fiber.join(fiber);
164 expect(written).toHaveLength(2);
165 }),
166 );
167​
168 it.effect("forwards client responses while an SSE request is still open", () =>
169 Effect.gen(function* () {
170 let responseController: ReadableStreamDefaultController<Uint8Array> | undefined;
171 let serverRequestWritten: (() => void) | undefined;
172 const serverRequestReachedClient = new Promise<void>((resolve) => {
173 serverRequestWritten = resolve;
174 });
175 const input = new NodeStream.PassThrough();
176 const written: Array<string> = [];
177 const fiber = yield* Effect.forkChild(
178 runAcpMcpStdioBridge({
179 endpoint: "http://127.0.0.1:1/mcp",
180 authorization: "Bearer bridge-test",
181 input,
182 output: {
183 write: (chunk) => {
184 written.push(chunk);
185 if (JSON.parse(chunk).id === "server-request-1") serverRequestWritten?.();
186 },
187 },
188 fetchImplementation: async (_url, init) => {
189 const body = JSON.parse(String(init?.body ?? "{}")) as {
190 readonly id?: unknown;
191 readonly method?: unknown;
192 readonly result?: unknown;
193 };
194 if (body.method === "tools/call") {
195 return new Response(
196 new ReadableStream<Uint8Array>({
197 start: (controller) => {
198 responseController = controller;
199 controller.enqueue(
200 new TextEncoder().encode(
201 'data: {"jsonrpc":"2.0","id":"server-request-1","method":"elicitation/create","params":{}}\n\n',
202 ),
203 );
204 },
205 }),
206 { headers: { "content-type": "text/event-stream" } },
207 );
208 }
209 expect(body).toMatchObject({ id: "server-request-1", result: { action: "accept" } });
210 responseController?.enqueue(
211 new TextEncoder().encode('data: {"jsonrpc":"2.0","id":7,"result":{}}\n\n'),
212 );
213 responseController?.close();
214 return new Response(null, { status: 202 });
215 },
216 }),
217 );
218​
219 input.write(`${JSON.stringify({ jsonrpc: "2.0", id: 7, method: "tools/call" })}\n`);
220 yield* Effect.promise(() => serverRequestReachedClient);
221 input.write(
222 `${JSON.stringify({ jsonrpc: "2.0", id: "server-request-1", result: { action: "accept" } })}\n`,
223 );
224 input.end();
225 yield* Fiber.join(fiber);
226​
227 expect(written.map((line) => JSON.parse(line).id)).toEqual(["server-request-1", 7]);
228 }),
229 );
230​
231 it.effect("forwards cancellation while a tool SSE response is still open", () =>
232 Effect.gen(function* () {
233 let resolveResponseController!: (
234 controller: ReadableStreamDefaultController<Uint8Array>,
235 ) => void;
236 const responseControllerReady = new Promise<ReadableStreamDefaultController<Uint8Array>>(
237 (resolve) => {
238 resolveResponseController = resolve;
239 },
240 );
241 const methods: Array<string> = [];
242 const input = new NodeStream.PassThrough();
243 const written: Array<string> = [];
244 const fiber = yield* Effect.forkChild(
245 runAcpMcpStdioBridge({
246 endpoint: "http://127.0.0.1:1/mcp",
247 authorization: "Bearer bridge-test",
248 input,
249 output: { write: (chunk) => written.push(chunk) },
250 fetchImplementation: async (_url, init) => {
251 const body = JSON.parse(String(init?.body ?? "{}")) as {
252 readonly method?: string;
253 };
254 methods.push(body.method ?? "");
255 if (body.method === "tools/call") {
256 return new Response(
257 new ReadableStream<Uint8Array>({
258 start: resolveResponseController,
259 }),
260 { headers: { "content-type": "text/event-stream" } },
261 );
262 }
263 const controller = await responseControllerReady;
264 controller.enqueue(
265 new TextEncoder().encode('data: {"jsonrpc":"2.0","id":7,"result":{}}\n\n'),
266 );
267 controller.close();
268 return new Response(null, { status: 202 });
269 },
270 }),
271 );
272​
273 input.write(`${JSON.stringify({ jsonrpc: "2.0", id: 7, method: "tools/call" })}\n`);
274 yield* Effect.promise(() => responseControllerReady);
275 input.write(
276 `${JSON.stringify({ jsonrpc: "2.0", method: "notifications/cancelled", params: { requestId: 7 } })}\n`,
277 );
278 input.end();
279 yield* Fiber.join(fiber);
280​
281 expect(methods).toEqual(["tools/call", "notifications/cancelled"]);
282 expect(JSON.parse(written[0]!)).toMatchObject({ id: 7, result: {} });
283 }),
284 );
285});