Open History to see the last commit
1// The bridge relays opaque JSON-RPC lines verbatim; schema-decoding foreign
2// payloads here would reject traffic it must pass through untouched.
3// @effect-diagnostics nodeBuiltinImport:off preferSchemaOverJson:off
4import * as NodeReadline from "node:readline";
5
6import * as Cause from "effect/Cause";
7import * as Effect from "effect/Effect";
8import * as Fiber from "effect/Fiber";
9import * as Stream from "effect/Stream";
10import { discardResponseBody, responsePayloads } from "@t3tools/shared/mcpResponsePayloads";
11
12/**
13 * ACP agents must support stdio MCP servers, while optional http/sse support is
14 * unevenly implemented.
15 */
16
17export class AcpMcpBridgeError extends Error {
18 readonly _tag = "AcpMcpBridgeError";
19}
20
21const bridgeError = (cause: unknown): AcpMcpBridgeError =>
22 cause instanceof AcpMcpBridgeError
23 ? cause
24 : new AcpMcpBridgeError(cause instanceof Error ? cause.message : String(cause), { cause });
25
26interface JsonRpcEnvelope {
27 readonly id?: unknown;
28 readonly method?: unknown;
29 readonly error?: unknown;
30 readonly result?: unknown;
31}
32
33const MCP_PROTOCOL_VERSION = "2025-06-18";
34
35export interface AcpMcpStdioBridgeOptions {
36 readonly endpoint: string;
37 readonly authorization: string;
38 readonly input: NodeJS.ReadableStream;
39 readonly output: { write(chunk: string): unknown };
40 readonly fetchImplementation?: (url: string, init?: RequestInit) => Promise<Response>;
41}
42
43function asEnvelope(value: unknown): JsonRpcEnvelope | null {
44 return typeof value === "object" && value !== null ? (value as JsonRpcEnvelope) : null;
45}
46
47function protocolVersionOf(entry: unknown): string | null {
48 const result = asEnvelope(entry)?.result;
49 const version =
50 typeof result === "object" && result !== null
51 ? (result as { readonly protocolVersion?: unknown }).protocolVersion
52 : undefined;
53 return typeof version === "string" && version.length > 0 ? version : null;
54}
55
56export interface AcpMcpToolCallOptions {
57 readonly endpoint: string;
58 readonly authorization: string;
59 readonly tool: string;
60 readonly arguments: Readonly<Record<string, unknown>>;
61 readonly fetchImplementation?: (url: string, init?: RequestInit) => Promise<Response>;
62}
63
64/**
65 * This is the terminal fallback for ACP agents that accept `mcpServers` in
66 * `session/new` but fail to expose those tools to their model. Compliant ACP
67 * agents continue to use the stdio bridge above.
68 */
69export function callAcpMcpTool(
70 options: AcpMcpToolCallOptions,
71): Effect.Effect<unknown, AcpMcpBridgeError> {
72 const fetchImplementation = options.fetchImplementation ?? fetch;
73 return Effect.gen(function* () {
74 let sessionId: string | null = null;
75 let protocolVersion: string | null = null;
76
77 const send = Effect.fn("AcpMcpStdioBridge.send")(function* (
78 message: unknown,
79 ): Effect.fn.Return<ReadonlyArray<unknown>, AcpMcpBridgeError> {
80 const response = yield* Effect.tryPromise({
81 try: () =>
82 fetchImplementation(options.endpoint, {
83 method: "POST",
84 headers: {
85 "content-type": "application/json",
86 accept: "application/json, text/event-stream",
87 authorization: options.authorization,
88 ...(sessionId === null ? {} : { "mcp-session-id": sessionId }),
89 ...(protocolVersion === null ? {} : { "mcp-protocol-version": protocolVersion }),
90 },
91 body: JSON.stringify(message),
92 }),
93 catch: bridgeError,
94 });
95 sessionId = response.headers.get("mcp-session-id") ?? sessionId;
96 if (!response.ok) {
97 yield* discardResponseBody(response);
98 return yield* Effect.fail(
99 new AcpMcpBridgeError(`T3 Code MCP endpoint responded with HTTP ${response.status}.`),
100 );
101 }
102 const payloads = yield* Stream.runCollect(responsePayloads(response, bridgeError));
103 for (const payload of payloads) {
104 protocolVersion = protocolVersionOf(payload) ?? protocolVersion;
105 }
106 return payloads;
107 });
108
109 const initializeId = "t3-acp-cli-initialize";
110 const initialized = yield* send({
111 jsonrpc: "2.0",
112 id: initializeId,
113 method: "initialize",
114 params: {
115 protocolVersion: MCP_PROTOCOL_VERSION,
116 capabilities: {},
117 clientInfo: { name: "t3-code-acp-cli", version: "0.0.0" },
118 },
119 });
120 const initializeResponse = initialized.find((entry) => asEnvelope(entry)?.id === initializeId);
121 if (initializeResponse === undefined || asEnvelope(initializeResponse)?.error !== undefined) {
122 return yield* Effect.fail(
123 new AcpMcpBridgeError("T3 Code MCP endpoint rejected initialization."),
124 );
125 }
126 yield* send({ jsonrpc: "2.0", method: "notifications/initialized" });
127
128 const callId = "t3-acp-cli-tool-call";
129 const responses = yield* send({
130 jsonrpc: "2.0",
131 id: callId,
132 method: "tools/call",
133 params: { name: options.tool, arguments: options.arguments },
134 });
135 const response = responses.find((entry) => asEnvelope(entry)?.id === callId);
136 const envelope = asEnvelope(response);
137 if (envelope === null || envelope.error !== undefined) {
138 return yield* Effect.fail(
139 new AcpMcpBridgeError(
140 `T3 Code MCP tool call failed${envelope?.error === undefined ? "." : `: ${JSON.stringify(envelope.error)}`}`,
141 ),
142 );
143 }
144 return envelope.result;
145 });
146}
147
148export function runAcpMcpStdioBridge(options: AcpMcpStdioBridgeOptions): Effect.Effect<void> {
149 const fetchImplementation = options.fetchImplementation ?? fetch;
150 return Effect.gen(function* () {
151 let sessionId: string | null = null;
152 let protocolVersion: string | null = null;
153 const running = new Set<Fiber.Fiber<void>>();
154
155 const writeMessage = (message: unknown): Effect.Effect<void> =>
156 Effect.sync(() => {
157 options.output.write(`${JSON.stringify(message)}\n`);
158 });
159
160 const handleServerPayload = Effect.fn("AcpMcpStdioBridge.handleServerPayload")(function* (
161 payload: unknown,
162 ): Effect.fn.Return<void> {
163 for (const entry of Array.isArray(payload) ? payload : [payload]) {
164 protocolVersion = protocolVersionOf(entry) ?? protocolVersion;
165 yield* writeMessage(entry);
166 }
167 });
168
169 const respondWithError = (
170 requestId: unknown,
171 message: string,
172 code = -32603,
173 ): Effect.Effect<void> =>
174 writeMessage({
175 jsonrpc: "2.0",
176 id: requestId ?? null,
177 error: { code, message },
178 });
179
180 const forward: (line: string, envelope: JsonRpcEnvelope) => Effect.Effect<void> = Effect.fn(
181 "AcpMcpStdioBridge.forward",
182 )(
183 function* (line: string, envelope: JsonRpcEnvelope) {
184 const response = yield* Effect.tryPromise({
185 try: () =>
186 fetchImplementation(options.endpoint, {
187 method: "POST",
188 headers: {
189 "content-type": "application/json",
190 accept: "application/json, text/event-stream",
191 authorization: options.authorization,
192 ...(sessionId === null ? {} : { "mcp-session-id": sessionId }),
193 ...(protocolVersion === null ? {} : { "mcp-protocol-version": protocolVersion }),
194 },
195 body: line,
196 }),
197 catch: bridgeError,
198 });
199 sessionId = response.headers.get("mcp-session-id") ?? sessionId;
200 if (!response.ok) {
201 if (envelope.id !== undefined) {
202 yield* respondWithError(
203 envelope.id,
204 `T3 Code MCP endpoint responded with HTTP ${response.status}.`,
205 );
206 }
207 return yield* discardResponseBody(response);
208 }
209 yield* Stream.runForEach(responsePayloads(response, bridgeError), handleServerPayload);
210 },
211 (effect, _line, envelope) =>
212 effect.pipe(
213 Effect.catchCause((cause) => {
214 if (envelope.id === undefined) return Effect.void;
215 const error = Cause.squash(cause);
216 return respondWithError(
217 envelope.id,
218 `T3 Code MCP bridge request failed: ${error instanceof Error ? error.message : String(error)}`,
219 );
220 }),
221 ),
222 );
223
224 // Only session establishment is ordered; client responses to
225 // server-initiated SSE requests must bypass the barrier or they would
226 // deadlock the still-open HTTP exchange, and normal MCP calls stay
227 // concurrent after initialization.
228 let sessionBarrier: Effect.Effect<void> = Effect.void;
229 let sessionBarrierPending = false;
230
231 const launch = Effect.fn("AcpMcpStdioBridge.launch")(function* (
232 task: Effect.Effect<void>,
233 ): Effect.fn.Return<void> {
234 const fiber = yield* Effect.forkChild(task);
235 running.add(fiber);
236 yield* Effect.forkChild(
237 Fiber.await(fiber).pipe(
238 Effect.andThen(
239 Effect.sync(() => {
240 running.delete(fiber);
241 }),
242 ),
243 ),
244 );
245 });
246
247 const dispatch = Effect.fn("AcpMcpStdioBridge.dispatch")(function* (
248 line: string,
249 ): Effect.fn.Return<void> {
250 if (line.trim().length === 0) return;
251 let parsed: unknown;
252 try {
253 parsed = JSON.parse(line);
254 } catch {
255 return yield* respondWithError(null, "Parse error", -32700);
256 }
257 const envelope = asEnvelope(parsed);
258 if (envelope === null) return;
259 const isResponse = envelope.id !== undefined && ("result" in envelope || "error" in envelope);
260 const isSessionHandshake =
261 envelope.method === "initialize" || envelope.method === "notifications/initialized";
262 if (isResponse) {
263 return yield* launch(forward(line, envelope));
264 }
265 if (isSessionHandshake) {
266 const prior = sessionBarrier;
267 const fiber = yield* Effect.forkChild(prior.pipe(Effect.andThen(forward(line, envelope))));
268 running.add(fiber);
269 const barrier = Fiber.await(fiber).pipe(Effect.asVoid);
270 sessionBarrier = barrier;
271 sessionBarrierPending = true;
272 yield* Effect.forkChild(
273 Fiber.await(fiber).pipe(
274 Effect.andThen(
275 Effect.sync(() => {
276 running.delete(fiber);
277 if (sessionBarrier === barrier) sessionBarrierPending = false;
278 }),
279 ),
280 ),
281 );
282 return;
283 }
284 const task = sessionBarrierPending
285 ? sessionBarrier.pipe(Effect.andThen(forward(line, envelope)))
286 : forward(line, envelope);
287 return yield* launch(task);
288 });
289
290 const reader = NodeReadline.createInterface({ input: options.input });
291 yield* Stream.runForEach(Stream.fromAsyncIterable(reader, bridgeError), dispatch).pipe(
292 Effect.catchCause(() => Effect.void),
293 );
294 yield* Fiber.awaitAll(running);
295 });
296}
297
298/**
299 * Kept free of heavy imports: these commands run on the ACP first-message
300 * critical path.
301 */
302export async function runAcpMcpCliFastPath(
303 command: "acp-mcp-bridge" | "acp-mcp-call",
304 args: ReadonlyArray<string>,
305): Promise<void> {
306 const endpoint = process.env.T3_ACP_MCP_ENDPOINT;
307 const authorization = process.env.T3_ACP_MCP_AUTHORIZATION;
308 if (endpoint === undefined || authorization === undefined) {
309 process.stderr.write(`${command} requires T3_ACP_MCP_ENDPOINT and T3_ACP_MCP_AUTHORIZATION.\n`);
310 process.exitCode = 2;
311 return;
312 }
313 if (command === "acp-mcp-bridge") {
314 await Effect.runPromise(
315 runAcpMcpStdioBridge({
316 endpoint,
317 authorization,
318 input: process.stdin,
319 output: process.stdout,
320 }),
321 );
322 return;
323 }
324 const [tool, argumentsJson] = args;
325 if (tool === undefined || argumentsJson === undefined) {
326 process.stderr.write("acp-mcp-call requires <tool> and <arguments-json>.\n");
327 process.exitCode = 2;
328 return;
329 }
330 let parsed: unknown;
331 try {
332 parsed = JSON.parse(argumentsJson);
333 } catch {
334 process.stderr.write("acp-mcp-call arguments must be valid JSON.\n");
335 process.exitCode = 2;
336 return;
337 }
338 if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
339 process.stderr.write("acp-mcp-call arguments must be a JSON object.\n");
340 process.exitCode = 2;
341 return;
342 }
343 const result = await Effect.runPromise(
344 callAcpMcpTool({
345 endpoint,
346 authorization,
347 tool,
348 arguments: parsed as Record<string, unknown>,
349 }),
350 );
351 process.stdout.write(`${JSON.stringify(result)}\n`);
352}