Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AcpMcpStdioBridge.ts

350 lines12.2 KB

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