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 = (message: unknown): Effect.Effect<ReadonlyArray<unknown>, AcpMcpBridgeError> =>
78 Effect.gen(function* () {
79 const response = yield* Effect.tryPromise({
80 try: () =>
81 fetchImplementation(options.endpoint, {
82 method: "POST",
83 headers: {
84 "content-type": "application/json",
85 accept: "application/json, text/event-stream",
86 authorization: options.authorization,
87 ...(sessionId === null ? {} : { "mcp-session-id": sessionId }),
88 ...(protocolVersion === null ? {} : { "mcp-protocol-version": protocolVersion }),
89 },
90 body: JSON.stringify(message),
91 }),
92 catch: bridgeError,
93 });
94 sessionId = response.headers.get("mcp-session-id") ?? sessionId;
95 if (!response.ok) {
96 yield* discardResponseBody(response);
97 return yield* Effect.fail(
98 new AcpMcpBridgeError(`T3 Code MCP endpoint responded with HTTP ${response.status}.`),
99 );
100 }
101 const payloads = yield* Stream.runCollect(responsePayloads(response, bridgeError));
102 for (const payload of payloads) {
103 protocolVersion = protocolVersionOf(payload) ?? protocolVersion;
104 }
105 return payloads;
106 });
107
108 const initializeId = "t3-acp-cli-initialize";
109 const initialized = yield* send({
110 jsonrpc: "2.0",
111 id: initializeId,
112 method: "initialize",
113 params: {
114 protocolVersion: MCP_PROTOCOL_VERSION,
115 capabilities: {},
116 clientInfo: { name: "t3-code-acp-cli", version: "0.0.0" },
117 },
118 });
119 const initializeResponse = initialized.find((entry) => asEnvelope(entry)?.id === initializeId);
120 if (initializeResponse === undefined || asEnvelope(initializeResponse)?.error !== undefined) {
121 return yield* Effect.fail(
122 new AcpMcpBridgeError("T3 Code MCP endpoint rejected initialization."),
123 );
124 }
125 yield* send({ jsonrpc: "2.0", method: "notifications/initialized" });
126
127 const callId = "t3-acp-cli-tool-call";
128 const responses = yield* send({
129 jsonrpc: "2.0",
130 id: callId,
131 method: "tools/call",
132 params: { name: options.tool, arguments: options.arguments },
133 });
134 const response = responses.find((entry) => asEnvelope(entry)?.id === callId);
135 const envelope = asEnvelope(response);
136 if (envelope === null || envelope.error !== undefined) {
137 return yield* Effect.fail(
138 new AcpMcpBridgeError(
139 `T3 Code MCP tool call failed${envelope?.error === undefined ? "." : `: ${JSON.stringify(envelope.error)}`}`,
140 ),
141 );
142 }
143 return envelope.result;
144 });
145}
146
147export function runAcpMcpStdioBridge(options: AcpMcpStdioBridgeOptions): Effect.Effect<void> {
148 const fetchImplementation = options.fetchImplementation ?? fetch;
149 return Effect.gen(function* () {
150 let sessionId: string | null = null;
151 let protocolVersion: string | null = null;
152 const running = new Set<Fiber.Fiber<void>>();
153
154 const writeMessage = (message: unknown): Effect.Effect<void> =>
155 Effect.sync(() => {
156 options.output.write(`${JSON.stringify(message)}\n`);
157 });
158
159 const handleServerPayload = (payload: unknown): Effect.Effect<void> =>
160 Effect.gen(function* () {
161 for (const entry of Array.isArray(payload) ? payload : [payload]) {
162 protocolVersion = protocolVersionOf(entry) ?? protocolVersion;
163 yield* writeMessage(entry);
164 }
165 });
166
167 const respondWithError = (
168 requestId: unknown,
169 message: string,
170 code = -32603,
171 ): Effect.Effect<void> =>
172 writeMessage({
173 jsonrpc: "2.0",
174 id: requestId ?? null,
175 error: { code, message },
176 });
177
178 const forward = (line: string, envelope: JsonRpcEnvelope): Effect.Effect<void> =>
179 Effect.gen(function* () {
180 const response = yield* Effect.tryPromise({
181 try: () =>
182 fetchImplementation(options.endpoint, {
183 method: "POST",
184 headers: {
185 "content-type": "application/json",
186 accept: "application/json, text/event-stream",
187 authorization: options.authorization,
188 ...(sessionId === null ? {} : { "mcp-session-id": sessionId }),
189 ...(protocolVersion === null ? {} : { "mcp-protocol-version": protocolVersion }),
190 },
191 body: line,
192 }),
193 catch: bridgeError,
194 });
195 sessionId = response.headers.get("mcp-session-id") ?? sessionId;
196 if (!response.ok) {
197 if (envelope.id !== undefined) {
198 yield* respondWithError(
199 envelope.id,
200 `T3 Code MCP endpoint responded with HTTP ${response.status}.`,
201 );
202 }
203 return yield* discardResponseBody(response);
204 }
205 yield* Stream.runForEach(responsePayloads(response, bridgeError), handleServerPayload);
206 }).pipe(
207 Effect.catchCause((cause) => {
208 if (envelope.id === undefined) return Effect.void;
209 const error = Cause.squash(cause);
210 return respondWithError(
211 envelope.id,
212 `T3 Code MCP bridge request failed: ${error instanceof Error ? error.message : String(error)}`,
213 );
214 }),
215 );
216
217 // Only session establishment is ordered; client responses to
218 // server-initiated SSE requests must bypass the barrier or they would
219 // deadlock the still-open HTTP exchange, and normal MCP calls stay
220 // concurrent after initialization.
221 let sessionBarrier: Effect.Effect<void> = Effect.void;
222 let sessionBarrierPending = false;
223
224 const launch = (task: Effect.Effect<void>): Effect.Effect<void> =>
225 Effect.gen(function* () {
226 const fiber = yield* Effect.forkChild(task);
227 running.add(fiber);
228 yield* Effect.forkChild(
229 Fiber.await(fiber).pipe(
230 Effect.andThen(
231 Effect.sync(() => {
232 running.delete(fiber);
233 }),
234 ),
235 ),
236 );
237 });
238
239 const dispatch = (line: string): Effect.Effect<void> =>
240 Effect.gen(function* () {
241 if (line.trim().length === 0) return;
242 let parsed: unknown;
243 try {
244 parsed = JSON.parse(line);
245 } catch {
246 return yield* respondWithError(null, "Parse error", -32700);
247 }
248 const envelope = asEnvelope(parsed);
249 if (envelope === null) return;
250 const isResponse =
251 envelope.id !== undefined && ("result" in envelope || "error" in envelope);
252 const isSessionHandshake =
253 envelope.method === "initialize" || envelope.method === "notifications/initialized";
254 if (isResponse) {
255 return yield* launch(forward(line, envelope));
256 }
257 if (isSessionHandshake) {
258 const prior = sessionBarrier;
259 const fiber = yield* Effect.forkChild(
260 prior.pipe(Effect.andThen(forward(line, envelope))),
261 );
262 running.add(fiber);
263 const barrier = Fiber.await(fiber).pipe(Effect.asVoid);
264 sessionBarrier = barrier;
265 sessionBarrierPending = true;
266 yield* Effect.forkChild(
267 Fiber.await(fiber).pipe(
268 Effect.andThen(
269 Effect.sync(() => {
270 running.delete(fiber);
271 if (sessionBarrier === barrier) sessionBarrierPending = false;
272 }),
273 ),
274 ),
275 );
276 return;
277 }
278 const task = sessionBarrierPending
279 ? sessionBarrier.pipe(Effect.andThen(forward(line, envelope)))
280 : forward(line, envelope);
281 return yield* launch(task);
282 });
283
284 const reader = NodeReadline.createInterface({ input: options.input });
285 yield* Stream.runForEach(Stream.fromAsyncIterable(reader, bridgeError), dispatch).pipe(
286 Effect.catchCause(() => Effect.void),
287 );
288 yield* Fiber.awaitAll(running);
289 });
290}
291
292/**
293 * Kept free of heavy imports: these commands run on the ACP first-message
294 * critical path.
295 */
296export async function runAcpMcpCliFastPath(
297 command: "acp-mcp-bridge" | "acp-mcp-call",
298 args: ReadonlyArray<string>,
299): Promise<void> {
300 const endpoint = process.env.T3_ACP_MCP_ENDPOINT;
301 const authorization = process.env.T3_ACP_MCP_AUTHORIZATION;
302 if (endpoint === undefined || authorization === undefined) {
303 process.stderr.write(`${command} requires T3_ACP_MCP_ENDPOINT and T3_ACP_MCP_AUTHORIZATION.\n`);
304 process.exitCode = 2;
305 return;
306 }
307 if (command === "acp-mcp-bridge") {
308 await Effect.runPromise(
309 runAcpMcpStdioBridge({
310 endpoint,
311 authorization,
312 input: process.stdin,
313 output: process.stdout,
314 }),
315 );
316 return;
317 }
318 const [tool, argumentsJson] = args;
319 if (tool === undefined || argumentsJson === undefined) {
320 process.stderr.write("acp-mcp-call requires <tool> and <arguments-json>.\n");
321 process.exitCode = 2;
322 return;
323 }
324 let parsed: unknown;
325 try {
326 parsed = JSON.parse(argumentsJson);
327 } catch {
328 process.stderr.write("acp-mcp-call arguments must be valid JSON.\n");
329 process.exitCode = 2;
330 return;
331 }
332 if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
333 process.stderr.write("acp-mcp-call arguments must be a JSON object.\n");
334 process.exitCode = 2;
335 return;
336 }
337 const result = await Effect.runPromise(
338 callAcpMcpTool({
339 endpoint,
340 authorization,
341 tool,
342 arguments: parsed as Record<string, unknown>,
343 }),
344 );
345 process.stdout.write(`${JSON.stringify(result)}\n`);
346}