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

AcpMcpStdioBridge.test.ts

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