The best way to control Claude Code, Codex and more from any computer or phone

main
ts 493 lines 18.6 KB
Raw
1 // @effect-diagnostics nodeBuiltinImport:off globalTimers:off
2 import * as NodeStream from "node:stream";
3
4 import { describe, expect, it } from "@effect/vitest";
5 import * as Deferred from "effect/Deferred";
6 import * as Effect from "effect/Effect";
7 import * as Fiber from "effect/Fiber";
8 import { vi } from "vite-plus/test";
9
10 import { mcpToolSession, runAcpMcpCliFastPath, runAcpMcpStdioBridge } from "./AcpMcpStdioBridge.ts";
11
12 function makeHarness(
13 responder: (request: Request) => Promise<Response> | Response,
14 input = new NodeStream.PassThrough(),
15 ) {
16 const written: Array<string> = [];
17 const requests: Array<{ readonly headers: Headers; readonly body: string }> = [];
18 const bridge = runAcpMcpStdioBridge({
19 endpoint: "http://127.0.0.1:1/mcp",
20 authorization: "Bearer bridge-test",
21 input,
22 output: {
23 write: (chunk: string) => {
24 written.push(chunk);
25 },
26 },
27 fetchImplementation: async (_url, init) => {
28 const request = new Request("http://127.0.0.1:1/mcp", init);
29 requests.push({ headers: request.headers, body: String(init?.body ?? "") });
30 return responder(request);
31 },
32 });
33 return { input, written, requests, bridge };
34 }
35
36 function pendingFetch(started: Deferred.Deferred<AbortSignal | undefined>) {
37 return (_url: string, init?: RequestInit): Promise<Response> => {
38 Deferred.doneUnsafe(started, Effect.succeed(init?.signal ?? undefined));
39 return new Promise(() => {});
40 };
41 }
42
43 describe("AcpMcpStdioBridge", () => {
44 it("prints structured results once in the terminal while retaining other content and errors", async () => {
45 const originalEnvironment = process.env;
46 using _environment = {
47 [Symbol.dispose]: () => {
48 process.env = originalEnvironment;
49 },
50 };
51 process.env = {
52 ...originalEnvironment,
53 T3_ACP_MCP_ENDPOINT: "http://127.0.0.1:1/mcp",
54 T3_ACP_MCP_AUTHORIZATION: "Bearer bridge-test",
55 };
56 const structuredContent = { taskId: "task-1", status: "failed" };
57 const explanation = { type: "text", text: "The command failed." };
58 const image = { type: "image", data: "image-data", mimeType: "image/png" };
59 const result = {
60 structuredContent,
61 content: [{ type: "text", text: JSON.stringify(structuredContent) }, explanation, image],
62 isError: true,
63 };
64 using fetch = vi.spyOn(globalThis, "fetch").mockImplementation(async (_url, init) => {
65 if (init?.method === "DELETE") return new Response(null, { status: 204 });
66 const message = JSON.parse(String(init?.body)) as { id?: string; method: string };
67 if (message.method === "notifications/initialized") {
68 return new Response(null, { status: 202 });
69 }
70 return Response.json(
71 {
72 jsonrpc: "2.0",
73 id: message.id,
74 result: message.method === "initialize" ? { protocolVersion: "2025-06-18" } : result,
75 },
76 { headers: { "mcp-session-id": "session-42" } },
77 );
78 });
79 using output = vi.spyOn(process.stdout, "write").mockReturnValue(true);
80
81 await runAcpMcpCliFastPath("acp-mcp-call", ["task_status", '{"taskId":"task-1"}']);
82
83 expect(output).toHaveBeenCalledExactlyOnceWith(
84 `${JSON.stringify({ ...result, content: [explanation, image] })}\n`,
85 );
86 expect(fetch).toHaveBeenLastCalledWith(
87 "http://127.0.0.1:1/mcp",
88 expect.objectContaining({ method: "DELETE" }),
89 );
90 });
91
92 it("reads the arguments from stdin when given -", async () => {
93 const originalEnvironment = process.env;
94 using _environment = {
95 [Symbol.dispose]: () => {
96 process.env = originalEnvironment;
97 },
98 };
99 process.env = {
100 ...originalEnvironment,
101 T3_ACP_MCP_ENDPOINT: "http://127.0.0.1:1/mcp",
102 T3_ACP_MCP_AUTHORIZATION: "Bearer bridge-test",
103 };
104 const calls: Array<unknown> = [];
105 using _fetch = vi.spyOn(globalThis, "fetch").mockImplementation(async (_url, init) => {
106 if (init?.method === "DELETE") return new Response(null, { status: 204 });
107 const message = JSON.parse(String(init?.body)) as {
108 id?: string;
109 method: string;
110 params?: unknown;
111 };
112 if (message.method === "notifications/initialized") {
113 return new Response(null, { status: 202 });
114 }
115 if (message.method === "tools/call") calls.push(message.params);
116 return Response.json({
117 jsonrpc: "2.0",
118 id: message.id,
119 result:
120 message.method === "initialize" ? { protocolVersion: "2025-06-18" } : { content: [] },
121 });
122 });
123 using _output = vi.spyOn(process.stdout, "write").mockReturnValue(true);
124 using _stdin = vi
125 .spyOn(process, "stdin", "get")
126 .mockReturnValue(
127 NodeStream.Readable.from(['{"task":"say \\"hi\\"",', '"mode":"async"}\r\n']) as never,
128 );
129
130 await runAcpMcpCliFastPath("acp-mcp-call", ["delegate_task", "-"]);
131
132 expect(calls).toEqual([
133 { name: "delegate_task", arguments: { task: 'say "hi"', mode: "async" } },
134 ]);
135 });
136
137 it.effect("forwards requests and replays the session id and protocol version", () =>
138 Effect.gen(function* () {
139 const { input, written, requests, bridge } = makeHarness((request) => {
140 const body = JSON.parse(String(requests.at(-1)?.body ?? "{}")) as { id?: number };
141 void request;
142 return new Response(
143 JSON.stringify({
144 jsonrpc: "2.0",
145 id: body.id ?? null,
146 result: body.id === 1 ? { protocolVersion: "2025-06-18" } : { ok: true },
147 }),
148 {
149 status: 200,
150 headers: { "content-type": "application/json", "mcp-session-id": "session-42" },
151 },
152 );
153 });
154 const fiber = yield* Effect.forkChild(bridge);
155
156 input.write(`${JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize" })}\n`);
157 input.write(`${JSON.stringify({ jsonrpc: "2.0", id: 2, method: "tools/list" })}\n`);
158 input.end();
159 yield* Fiber.join(fiber);
160
161 expect(written).toHaveLength(2);
162 expect(JSON.parse(written[0]!)).toMatchObject({ id: 1 });
163 expect(JSON.parse(written[1]!)).toMatchObject({ id: 2, result: { ok: true } });
164 expect(requests[0]?.headers.get("authorization")).toBe("Bearer bridge-test");
165 expect(requests[1]?.headers.get("mcp-session-id")).toBe("session-42");
166 expect(requests[1]?.headers.get("mcp-protocol-version")).toBe("2025-06-18");
167 }),
168 );
169
170 it.effect("acknowledges notifications silently and synthesizes errors for failed requests", () =>
171 Effect.gen(function* () {
172 let call = 0;
173 const { input, written, bridge } = makeHarness(() => {
174 call += 1;
175 return call === 1
176 ? new Response(null, { status: 202 })
177 : new Response("upstream broke", { status: 500 });
178 });
179 const fiber = yield* Effect.forkChild(bridge);
180
181 input.write(`${JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" })}\n`);
182 input.write(`${JSON.stringify({ jsonrpc: "2.0", id: 3, method: "tools/list" })}\n`);
183 input.end();
184 yield* Fiber.join(fiber);
185
186 expect(written).toHaveLength(1);
187 expect(JSON.parse(written[0]!)).toMatchObject({
188 id: 3,
189 error: { code: -32603 },
190 });
191 }),
192 );
193
194 it.effect("emits parse errors for malformed JSON-RPC input", () =>
195 Effect.gen(function* () {
196 const { input, written, requests, bridge } = makeHarness(
197 () => new Response(null, { status: 202 }),
198 );
199 const fiber = yield* Effect.forkChild(bridge);
200
201 input.end("{not-json}\n");
202 yield* Fiber.join(fiber);
203
204 expect(requests).toHaveLength(0);
205 expect(JSON.parse(written[0]!)).toEqual({
206 jsonrpc: "2.0",
207 id: null,
208 error: { code: -32700, message: "Parse error" },
209 });
210 }),
211 );
212
213 it.effect("keeps U+2028 and U+2029 inside a message instead of splitting it", () =>
214 Effect.gen(function* () {
215 const { input, written, requests, bridge } = makeHarness(
216 () => Response.json({ jsonrpc: "2.0", id: 4, result: { ok: true } }),
217 // Object mode keeps the two writes as separate chunks instead of one buffered read.
218 new NodeStream.PassThrough({ objectMode: true }),
219 );
220 const fiber = yield* Effect.forkChild(bridge);
221 // JSON.stringify leaves both separators unescaped, as MCP stdio clients send them.
222 const message = JSON.stringify({
223 jsonrpc: "2.0",
224 id: 4,
225 method: "tools/call",
226 params: { name: "echo", arguments: { text: "a\u2028b\u2029c\u{1f30d}" } },
227 });
228
229 // Split inside the emoji's UTF-8 bytes and leave the last line unterminated, as stdin may.
230 const bytes = Buffer.from(message);
231 const split = bytes.indexOf(Buffer.from("\u{1f30d}")) + 2;
232 input.write(bytes.subarray(0, split));
233 input.end(bytes.subarray(split));
234 yield* Fiber.join(fiber);
235
236 expect(requests.map((request) => request.body)).toEqual([message]);
237 expect(written.map((chunk) => JSON.parse(chunk))).toEqual([
238 { jsonrpc: "2.0", id: 4, result: { ok: true } },
239 ]);
240 }),
241 );
242
243 it.effect("forwards SSE messages before the HTTP response closes", () =>
244 Effect.gen(function* () {
245 let resolveResponseController!: (
246 controller: ReadableStreamDefaultController<Uint8Array>,
247 ) => void;
248 const responseControllerReady = new Promise<ReadableStreamDefaultController<Uint8Array>>(
249 (resolve) => {
250 resolveResponseController = resolve;
251 },
252 );
253 let firstWrite: (() => void) | undefined;
254 const firstWritten = new Promise<void>((resolve) => {
255 firstWrite = resolve;
256 });
257 const input = new NodeStream.PassThrough();
258 const written: Array<string> = [];
259 const fiber = yield* Effect.forkChild(
260 runAcpMcpStdioBridge({
261 endpoint: "http://127.0.0.1:1/mcp",
262 authorization: "Bearer bridge-test",
263 input,
264 output: {
265 write: (chunk) => {
266 written.push(chunk);
267 firstWrite?.();
268 },
269 },
270 fetchImplementation: async () =>
271 new Response(
272 new ReadableStream<Uint8Array>({
273 start: (controller) => {
274 resolveResponseController(controller);
275 },
276 }),
277 { headers: { "content-type": "text/event-stream" } },
278 ),
279 }),
280 );
281
282 input.write(`${JSON.stringify({ jsonrpc: "2.0", id: 7, method: "tools/call" })}\n`);
283 const responseController = yield* Effect.promise(() => responseControllerReady);
284 responseController.enqueue(
285 new TextEncoder().encode(
286 'data: {"jsonrpc":"2.0","method":"notifications/progress","params":{}}\n\n',
287 ),
288 );
289 yield* Effect.promise(() => firstWritten);
290 expect(JSON.parse(written[0]!)).toMatchObject({ method: "notifications/progress" });
291
292 responseController.enqueue(
293 new TextEncoder().encode('data: {"jsonrpc":"2.0","id":7,"result":{}}\n\n'),
294 );
295 responseController.close();
296 input.end();
297 yield* Fiber.join(fiber);
298 expect(written).toHaveLength(2);
299 }),
300 );
301
302 it.effect("forwards client responses while an SSE request is still open", () =>
303 Effect.gen(function* () {
304 let responseController: ReadableStreamDefaultController<Uint8Array> | undefined;
305 let serverRequestWritten: (() => void) | undefined;
306 const serverRequestReachedClient = new Promise<void>((resolve) => {
307 serverRequestWritten = resolve;
308 });
309 const input = new NodeStream.PassThrough();
310 const written: Array<string> = [];
311 const fiber = yield* Effect.forkChild(
312 runAcpMcpStdioBridge({
313 endpoint: "http://127.0.0.1:1/mcp",
314 authorization: "Bearer bridge-test",
315 input,
316 output: {
317 write: (chunk) => {
318 written.push(chunk);
319 if (JSON.parse(chunk).id === "server-request-1") serverRequestWritten?.();
320 },
321 },
322 fetchImplementation: async (_url, init) => {
323 const body = JSON.parse(String(init?.body ?? "{}")) as {
324 readonly id?: unknown;
325 readonly method?: unknown;
326 readonly result?: unknown;
327 };
328 if (body.method === "tools/call") {
329 return new Response(
330 new ReadableStream<Uint8Array>({
331 start: (controller) => {
332 responseController = controller;
333 controller.enqueue(
334 new TextEncoder().encode(
335 'data: {"jsonrpc":"2.0","id":"server-request-1","method":"elicitation/create","params":{}}\n\n',
336 ),
337 );
338 },
339 }),
340 { headers: { "content-type": "text/event-stream" } },
341 );
342 }
343 expect(body).toMatchObject({ id: "server-request-1", result: { action: "accept" } });
344 responseController?.enqueue(
345 new TextEncoder().encode('data: {"jsonrpc":"2.0","id":7,"result":{}}\n\n'),
346 );
347 responseController?.close();
348 return new Response(null, { status: 202 });
349 },
350 }),
351 );
352
353 input.write(`${JSON.stringify({ jsonrpc: "2.0", id: 7, method: "tools/call" })}\n`);
354 yield* Effect.promise(() => serverRequestReachedClient);
355 input.write(
356 `${JSON.stringify({ jsonrpc: "2.0", id: "server-request-1", result: { action: "accept" } })}\n`,
357 );
358 input.end();
359 yield* Fiber.join(fiber);
360
361 expect(written.map((line) => JSON.parse(line).id)).toEqual(["server-request-1", 7]);
362 }),
363 );
364
365 it.effect("forwards cancellation while a tool SSE response is still open", () =>
366 Effect.gen(function* () {
367 let resolveResponseController!: (
368 controller: ReadableStreamDefaultController<Uint8Array>,
369 ) => void;
370 const responseControllerReady = new Promise<ReadableStreamDefaultController<Uint8Array>>(
371 (resolve) => {
372 resolveResponseController = resolve;
373 },
374 );
375 const methods: Array<string> = [];
376 const input = new NodeStream.PassThrough();
377 const written: Array<string> = [];
378 const fiber = yield* Effect.forkChild(
379 runAcpMcpStdioBridge({
380 endpoint: "http://127.0.0.1:1/mcp",
381 authorization: "Bearer bridge-test",
382 input,
383 output: { write: (chunk) => written.push(chunk) },
384 fetchImplementation: async (_url, init) => {
385 const body = JSON.parse(String(init?.body ?? "{}")) as {
386 readonly method?: string;
387 };
388 methods.push(body.method ?? "");
389 if (body.method === "tools/call") {
390 return new Response(
391 new ReadableStream<Uint8Array>({
392 start: resolveResponseController,
393 }),
394 { headers: { "content-type": "text/event-stream" } },
395 );
396 }
397 const controller = await responseControllerReady;
398 controller.enqueue(
399 new TextEncoder().encode('data: {"jsonrpc":"2.0","id":7,"result":{}}\n\n'),
400 );
401 controller.close();
402 return new Response(null, { status: 202 });
403 },
404 }),
405 );
406
407 input.write(`${JSON.stringify({ jsonrpc: "2.0", id: 7, method: "tools/call" })}\n`);
408 yield* Effect.promise(() => responseControllerReady);
409 input.write(
410 `${JSON.stringify({ jsonrpc: "2.0", method: "notifications/cancelled", params: { requestId: 7 } })}\n`,
411 );
412 input.end();
413 yield* Fiber.join(fiber);
414
415 expect(methods).toEqual(["tools/call", "notifications/cancelled"]);
416 expect(JSON.parse(written[0]!)).toMatchObject({ id: 7, result: {} });
417 }),
418 );
419
420 it.effect("aborts the pending fetch when a tool call is interrupted", () =>
421 Effect.gen(function* () {
422 const started = yield* Deferred.make<AbortSignal | undefined>();
423 const fiber = yield* mcpToolSession({
424 endpoint: "http://127.0.0.1:1/mcp",
425 authorization: "Bearer bridge-test",
426 clientName: "t3-code-acp-cli",
427 fetchImplementation: pendingFetch(started),
428 }).pipe(
429 Effect.flatMap((session) => session.call("orchestrator_capabilities", {})),
430 Effect.scoped,
431 Effect.forkChild,
432 );
433
434 const signal = yield* Deferred.await(started);
435 yield* Fiber.interrupt(fiber);
436 expect(signal?.aborted).toBe(true);
437 }),
438 );
439
440 it.effect("answers a server ping that arrives before the tool result on its SSE stream", () =>
441 Effect.gen(function* () {
442 const sent: Array<{ id?: unknown; method?: string; result?: unknown }> = [];
443 const result = yield* mcpToolSession({
444 endpoint: "http://127.0.0.1:1/mcp",
445 authorization: "Bearer bridge-test",
446 clientName: "t3-code-acp-cli",
447 fetchImplementation: async (_url, init) => {
448 if (init?.method === "DELETE") return new Response(null, { status: 204 });
449 const message = JSON.parse(String(init?.body)) as (typeof sent)[number];
450 sent.push(message);
451 if (message.method === "initialize") {
452 return Response.json(
453 { jsonrpc: "2.0", id: message.id, result: { protocolVersion: "2025-06-18" } },
454 { headers: { "mcp-session-id": "session-42" } },
455 );
456 }
457 if (message.method !== "tools/call") return new Response(null, { status: 202 });
458 const ping = { jsonrpc: "2.0", id: "server-ping", method: "ping" };
459 const reply = { jsonrpc: "2.0", id: message.id, result: { content: [] } };
460 return new Response(
461 `data: ${JSON.stringify(ping)}\n\ndata: ${JSON.stringify(reply)}\n\n`,
462 { headers: { "content-type": "text/event-stream" } },
463 );
464 },
465 }).pipe(
466 Effect.flatMap((session) => session.call("orchestrator_capabilities", {})),
467 Effect.scoped,
468 );
469
470 expect(result).toEqual({ content: [] });
471 expect(sent).toContainEqual({ jsonrpc: "2.0", id: "server-ping", result: {} });
472 }),
473 );
474
475 it.effect("aborts the pending fetch when the stdio bridge is interrupted", () =>
476 Effect.gen(function* () {
477 const started = yield* Deferred.make<AbortSignal | undefined>();
478 const input = new NodeStream.PassThrough();
479 const fiber = yield* runAcpMcpStdioBridge({
480 endpoint: "http://127.0.0.1:1/mcp",
481 authorization: "Bearer bridge-test",
482 input,
483 output: { write: () => undefined },
484 fetchImplementation: pendingFetch(started),
485 }).pipe(Effect.forkChild);
486
487 input.write(`${JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" })}\n`);
488 const signal = yield* Deferred.await(started);
489 yield* Fiber.interrupt(fiber);
490 expect(signal?.aborted).toBe(true);
491 }),
492 );
493 });