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