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