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

AcpMcpStdioBridge.ts

416 lines15.3 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";
10​
11/**
12 * Stdio-to-HTTP bridge for T3's MCP endpoint.
13 *
14 * ACP agents must support stdio MCP servers, while optional http/sse support
15 * is unevenly implemented. `t3 acp-mcp-bridge` runs as the stdio MCP server an
16 * ACP agent spawns and forwards each JSON-RPC line to T3's authenticated
17 * streamable-HTTP endpoint: single JSON responses and SSE streams are written
18 * back as newline-delimited JSON-RPC, notification acknowledgements (202/204)
19 * produce no output, and the `mcp-session-id` / negotiated protocol version
20 * are replayed on subsequent requests.
21 *
22 * This entry sits on the ACP first-message critical path (bin.ts fast-paths
23 * it before the CLI graph), so it imports only effect core modules; keep the
24 * import list lean when changing it.
25 */
26​
27export class AcpMcpBridgeError extends Error {
28 readonly _tag = "AcpMcpBridgeError";
30​
31const bridgeError = (cause: unknown): AcpMcpBridgeError =>
32 cause instanceof AcpMcpBridgeError
33 ? cause
34 : new AcpMcpBridgeError(cause instanceof Error ? cause.message : String(cause), { cause });
35​
36interface JsonRpcEnvelope {
37 readonly id?: unknown;
38 readonly method?: unknown;
39 readonly error?: unknown;
40 readonly result?: unknown;
42​
43const MCP_PROTOCOL_VERSION = "2025-06-18";
44​
45export interface AcpMcpStdioBridgeOptions {
46 readonly endpoint: string;
47 readonly authorization: string;
48 readonly input: NodeJS.ReadableStream;
49 readonly output: { write(chunk: string): unknown };
50 readonly fetchImplementation?: (url: string, init?: RequestInit) => Promise<Response>;
52​
53function asEnvelope(value: unknown): JsonRpcEnvelope | null {
54 return typeof value === "object" && value !== null ? (value as JsonRpcEnvelope) : null;
56​
57function protocolVersionOf(entry: unknown): string | null {
58 const result = asEnvelope(entry)?.result;
59 const version =
60 typeof result === "object" && result !== null
61 ? (result as { readonly protocolVersion?: unknown }).protocolVersion
62 : undefined;
63 return typeof version === "string" && version.length > 0 ? version : null;
65​
66async function* sseDataLines(response: Response): AsyncGenerator<string> {
67 if (response.body === null) return;
68 const decoder = new TextDecoder();
69 let buffered = "";
70 for await (const chunk of response.body) {
71 buffered += decoder.decode(chunk as Uint8Array, { stream: true });
72 let separatorIndex = buffered.search(/\n\n|\r\n\r\n/u);
73 while (separatorIndex !== -1) {
74 const rawEvent = buffered.slice(0, separatorIndex);
75 buffered = buffered.slice(separatorIndex).replace(/^(?:\r?\n){2}/u, "");
76 const data = rawEvent
77 .split(/\r?\n/u)
78 .filter((line) => line.startsWith("data:"))
79 .map((line) => line.slice("data:".length).trimStart())
80 .join("\n");
81 if (data.length > 0) yield data;
82 separatorIndex = buffered.search(/\n\n|\r\n\r\n/u);
83 }
84 }
86​
87const discardResponseBody = (response: Response): Effect.Effect<void> =>
88 Effect.promise(() => response.body?.cancel().catch(() => undefined) ?? Promise.resolve());
89​
90/**
91 * Every JSON-RPC payload carried by a response, in arrival order: nothing for
92 * notification acknowledgements, each SSE `data:` event as it streams in, or
93 * the single JSON body.
94 */
95export function responsePayloads(response: Response): Stream.Stream<unknown, AcpMcpBridgeError> {
96 if (response.status === 202 || response.status === 204) {
97 return Stream.unwrap(discardResponseBody(response).pipe(Effect.as(Stream.empty)));
98 }
99 const contentType = response.headers.get("content-type") ?? "";
100 if (contentType.includes("text/event-stream")) {
101 return Stream.fromAsyncIterable(sseDataLines(response), bridgeError).pipe(
102 Stream.mapEffect((data) => Effect.try({ try: () => JSON.parse(data), catch: bridgeError })),
103 );
104 }
105 return Stream.unwrap(
106 Effect.tryPromise({ try: () => response.text(), catch: bridgeError }).pipe(
107 Effect.flatMap((text) =>
108 text.trim().length === 0
109 ? Effect.succeed(Stream.empty)
110 : Effect.try({ try: () => JSON.parse(text) as unknown, catch: bridgeError }).pipe(
111 Effect.map((payload) => Stream.fromIterable([payload])),
112 ),
113 ),
114 ),
115 );
117​
118export interface AcpMcpToolCallOptions {
119 readonly endpoint: string;
120 readonly authorization: string;
121 readonly tool: string;
122 readonly arguments: Readonly<Record<string, unknown>>;
123 readonly fetchImplementation?: (url: string, init?: RequestInit) => Promise<Response>;
125​
126/**
127 * Call one MCP tool through a fresh authenticated HTTP session.
128 *
129 * This is the terminal fallback for ACP agents that accept `mcpServers` in
130 * `session/new` but fail to expose those tools to their model. Compliant ACP
131 * agents continue to use the stdio bridge above.
132 */
133export function callAcpMcpTool(
134 options: AcpMcpToolCallOptions,
135): Effect.Effect<unknown, AcpMcpBridgeError> {
136 const fetchImplementation = options.fetchImplementation ?? fetch;
137 return Effect.gen(function* () {
138 // The bridge is single-fibered at creation time; concurrent sends only
139 // read these after the sequential handshake, so plain locals suffice.
140 let sessionId: string | null = null;
141 let protocolVersion: string | null = null;
142​
143 const send = (message: unknown): Effect.Effect<ReadonlyArray<unknown>, AcpMcpBridgeError> =>
144 Effect.gen(function* () {
145 const response = yield* Effect.tryPromise({
146 try: () =>
147 fetchImplementation(options.endpoint, {
148 method: "POST",
149 headers: {
150 "content-type": "application/json",
151 accept: "application/json, text/event-stream",
152 authorization: options.authorization,
153 ...(sessionId === null ? {} : { "mcp-session-id": sessionId }),
154 ...(protocolVersion === null ? {} : { "mcp-protocol-version": protocolVersion }),
155 },
156 body: JSON.stringify(message),
157 }),
158 catch: bridgeError,
159 });
160 sessionId = response.headers.get("mcp-session-id") ?? sessionId;
161 if (!response.ok) {
162 yield* discardResponseBody(response);
163 return yield* Effect.fail(
164 new AcpMcpBridgeError(`T3 Code MCP endpoint responded with HTTP ${response.status}.`),
165 );
166 }
167 const payloads = yield* Stream.runCollect(responsePayloads(response));
168 for (const payload of payloads) {
169 protocolVersion = protocolVersionOf(payload) ?? protocolVersion;
170 }
171 return payloads;
172 });
173​
174 const initializeId = "t3-acp-cli-initialize";
175 const initialized = yield* send({
176 jsonrpc: "2.0",
177 id: initializeId,
178 method: "initialize",
179 params: {
180 protocolVersion: MCP_PROTOCOL_VERSION,
181 capabilities: {},
182 clientInfo: { name: "t3-code-acp-cli", version: "0.0.0" },
183 },
184 });
185 const initializeResponse = initialized.find((entry) => asEnvelope(entry)?.id === initializeId);
186 if (initializeResponse === undefined || asEnvelope(initializeResponse)?.error !== undefined) {
187 return yield* Effect.fail(
188 new AcpMcpBridgeError("T3 Code MCP endpoint rejected initialization."),
189 );
190 }
191 yield* send({ jsonrpc: "2.0", method: "notifications/initialized" });
192​
193 const callId = "t3-acp-cli-tool-call";
194 const responses = yield* send({
195 jsonrpc: "2.0",
196 id: callId,
197 method: "tools/call",
198 params: { name: options.tool, arguments: options.arguments },
199 });
200 const response = responses.find((entry) => asEnvelope(entry)?.id === callId);
201 const envelope = asEnvelope(response);
202 if (envelope === null || envelope.error !== undefined) {
203 return yield* Effect.fail(
204 new AcpMcpBridgeError(
205 `T3 Code MCP tool call failed${envelope?.error === undefined ? "." : `: ${JSON.stringify(envelope.error)}`}`,
206 ),
207 );
208 }
209 return envelope.result;
210 });
212​
213export function runAcpMcpStdioBridge(options: AcpMcpStdioBridgeOptions): Effect.Effect<void> {
214 const fetchImplementation = options.fetchImplementation ?? fetch;
215 return Effect.gen(function* () {
216 // Dispatch happens synchronously on the single stream fiber, so plain
217 // locals carry the shared session state; forwards mutate them in
218 // completion order exactly like the wire does.
219 let sessionId: string | null = null;
220 let protocolVersion: string | null = null;
221 const running = new Set<Fiber.Fiber<void>>();
222​
223 const writeMessage = (message: unknown): Effect.Effect<void> =>
224 Effect.sync(() => {
225 options.output.write(`${JSON.stringify(message)}\n`);
226 });
227​
228 const handleServerPayload = (payload: unknown): Effect.Effect<void> =>
229 Effect.gen(function* () {
230 for (const entry of Array.isArray(payload) ? payload : [payload]) {
231 protocolVersion = protocolVersionOf(entry) ?? protocolVersion;
232 yield* writeMessage(entry);
233 }
234 });
235​
236 const respondWithError = (
237 requestId: unknown,
238 message: string,
239 code = -32603,
240 ): Effect.Effect<void> =>
241 writeMessage({
242 jsonrpc: "2.0",
243 id: requestId ?? null,
244 error: { code, message },
245 });
246​
247 const forward = (line: string, envelope: JsonRpcEnvelope): Effect.Effect<void> =>
248 Effect.gen(function* () {
249 const response = yield* Effect.tryPromise({
250 try: () =>
251 fetchImplementation(options.endpoint, {
252 method: "POST",
253 headers: {
254 "content-type": "application/json",
255 accept: "application/json, text/event-stream",
256 authorization: options.authorization,
257 ...(sessionId === null ? {} : { "mcp-session-id": sessionId }),
258 ...(protocolVersion === null ? {} : { "mcp-protocol-version": protocolVersion }),
259 },
260 body: line,
261 }),
262 catch: bridgeError,
263 });
264 sessionId = response.headers.get("mcp-session-id") ?? sessionId;
265 if (!response.ok) {
266 if (envelope.id !== undefined) {
267 yield* respondWithError(
268 envelope.id,
269 `T3 Code MCP endpoint responded with HTTP ${response.status}.`,
270 );
271 }
272 return yield* discardResponseBody(response);
273 }
274 yield* Stream.runForEach(responsePayloads(response), handleServerPayload);
275 }).pipe(
276 Effect.catchCause((cause) => {
277 if (envelope.id === undefined) return Effect.void;
278 const error = Cause.squash(cause);
279 return respondWithError(
280 envelope.id,
281 `T3 Code MCP bridge request failed: ${error instanceof Error ? error.message : String(error)}`,
282 );
283 }),
284 );
285​
286 // Only session establishment is ordered; client responses to
287 // server-initiated SSE requests must bypass the barrier or they would
288 // deadlock the still-open HTTP exchange, and normal MCP calls stay
289 // concurrent after initialization.
290 let sessionBarrier: Effect.Effect<void> = Effect.void;
291 let sessionBarrierPending = false;
292​
293 const launch = (task: Effect.Effect<void>): Effect.Effect<void> =>
294 Effect.gen(function* () {
295 const fiber = yield* Effect.forkChild(task);
296 running.add(fiber);
297 yield* Effect.forkChild(
298 Fiber.await(fiber).pipe(
299 Effect.andThen(
300 Effect.sync(() => {
301 running.delete(fiber);
302 }),
303 ),
304 ),
305 );
306 });
307​
308 const dispatch = (line: string): Effect.Effect<void> =>
309 Effect.gen(function* () {
310 if (line.trim().length === 0) return;
311 let parsed: unknown;
312 try {
313 parsed = JSON.parse(line);
314 } catch {
315 return yield* respondWithError(null, "Parse error", -32700);
316 }
317 const envelope = asEnvelope(parsed);
318 if (envelope === null) return;
319 const isResponse =
320 envelope.id !== undefined && ("result" in envelope || "error" in envelope);
321 const isSessionHandshake =
322 envelope.method === "initialize" || envelope.method === "notifications/initialized";
323 if (isResponse) {
324 return yield* launch(forward(line, envelope));
325 }
326 if (isSessionHandshake) {
327 const prior = sessionBarrier;
328 const fiber = yield* Effect.forkChild(
329 prior.pipe(Effect.andThen(forward(line, envelope))),
330 );
331 running.add(fiber);
332 const barrier = Fiber.await(fiber).pipe(Effect.asVoid);
333 sessionBarrier = barrier;
334 sessionBarrierPending = true;
335 yield* Effect.forkChild(
336 Fiber.await(fiber).pipe(
337 Effect.andThen(
338 Effect.sync(() => {
339 running.delete(fiber);
340 if (sessionBarrier === barrier) sessionBarrierPending = false;
341 }),
342 ),
343 ),
344 );
345 return;
346 }
347 const task = sessionBarrierPending
348 ? sessionBarrier.pipe(Effect.andThen(forward(line, envelope)))
349 : forward(line, envelope);
350 return yield* launch(task);
351 });
352​
353 const reader = NodeReadline.createInterface({ input: options.input });
354 yield* Stream.runForEach(Stream.fromAsyncIterable(reader, bridgeError), dispatch).pipe(
355 Effect.catchCause(() => Effect.void),
356 );
357 yield* Fiber.awaitAll(running);
358 });
360​
361/**
362 * Argv runner for `t3 acp-mcp-bridge` and `t3 acp-mcp-call`, shared by the
363 * fast-path dispatch in bin.ts and the full CLI's command handlers. Kept free
364 * of heavy imports: these commands run on the ACP first-message critical path.
365 */
366export async function runAcpMcpCliFastPath(
367 command: "acp-mcp-bridge" | "acp-mcp-call",
368 args: ReadonlyArray<string>,
369): Promise<void> {
370 const endpoint = process.env.T3_ACP_MCP_ENDPOINT;
371 const authorization = process.env.T3_ACP_MCP_AUTHORIZATION;
372 if (endpoint === undefined || authorization === undefined) {
373 process.stderr.write(`${command} requires T3_ACP_MCP_ENDPOINT and T3_ACP_MCP_AUTHORIZATION.\n`);
374 process.exitCode = 2;
375 return;
376 }
377 if (command === "acp-mcp-bridge") {
378 await Effect.runPromise(
379 runAcpMcpStdioBridge({
380 endpoint,
381 authorization,
382 input: process.stdin,
383 output: process.stdout,
384 }),
385 );
386 return;
387 }
388 const [tool, argumentsJson] = args;
389 if (tool === undefined || argumentsJson === undefined) {
390 process.stderr.write("acp-mcp-call requires <tool> and <arguments-json>.\n");
391 process.exitCode = 2;
392 return;
393 }
394 let parsed: unknown;
395 try {
396 parsed = JSON.parse(argumentsJson);
397 } catch {
398 process.stderr.write("acp-mcp-call arguments must be valid JSON.\n");
399 process.exitCode = 2;
400 return;
401 }
402 if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
403 process.stderr.write("acp-mcp-call arguments must be a JSON object.\n");
404 process.exitCode = 2;
405 return;
406 }
407 const result = await Effect.runPromise(
408 callAcpMcpTool({
409 endpoint,
410 authorization,
411 tool,
412 arguments: parsed as Record<string, unknown>,
413 }),
414 );
415 process.stdout.write(`${JSON.stringify(result)}\n`);