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

AcpMcpStdioBridge.ts

444 lines15.5 KB

1// Relay JSON-RPC verbatim; schema decoding would reject foreign payloads.
2// @effect-diagnostics globalJsonInEffect:off
3import * as Cause from "effect/Cause";
4import * as Effect from "effect/Effect";
5import * as Option from "effect/Option";
6import * as Fiber from "effect/Fiber";
7import * as Schema from "effect/Schema";
8import * as Scope from "effect/Scope";
9import * as Stream from "effect/Stream";
10import { discardResponseBody, responsePayloads } from "@t3tools/shared/mcpResponsePayloads";
11​
12/** ACP mandates stdio MCP support; HTTP/SSE support varies. */
13​
14const JsonRpcError = Schema.Struct({ code: Schema.Number, message: Schema.String });
15​
16export class AcpMcpBridgeError extends Schema.TaggedError<AcpMcpBridgeError>()(
17 "AcpMcpBridgeError",
18 {
19 message: Schema.String,
20 cause: Schema.optional(Schema.Defect()),
21 /** The JSON-RPC error the server answered with, when it answered. */
22 rpcError: Schema.optional(JsonRpcError),
23 },
24) {}
25​
26const decodeRpcError = Schema.decodeUnknownOption(JsonRpcError);
27​
28const isAcpMcpBridgeError = Schema.is(AcpMcpBridgeError);
29​
30const bridgeError = (cause: unknown): AcpMcpBridgeError =>
31 isAcpMcpBridgeError(cause)
32 ? cause
33 : new AcpMcpBridgeError({
34 message: cause instanceof Error ? cause.message : String(cause),
35 cause,
36 });
37​
38const decodeJsonLine = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));
39​
40interface JsonRpcEnvelope {
41 readonly id?: unknown;
42 readonly method?: unknown;
43 readonly error?: unknown;
44 readonly result?: unknown;
46​
47const MCP_PROTOCOL_VERSION = "2025-06-18";
48​
49export interface AcpMcpStdioBridgeOptions {
50 readonly endpoint: string;
51 readonly authorization: string;
52 readonly input: NodeJS.ReadableStream;
53 readonly output: { write(chunk: string): unknown };
54 readonly fetchImplementation?: (url: string, init?: RequestInit) => Promise<Response>;
56​
57function asEnvelope(value: unknown): JsonRpcEnvelope | null {
58 return typeof value === "object" && value !== null ? (value as JsonRpcEnvelope) : null;
60​
61function protocolVersionOf(entry: unknown): string | null {
62 const result = asEnvelope(entry)?.result;
63 const version =
64 typeof result === "object" && result !== null
65 ? (result as { readonly protocolVersion?: unknown }).protocolVersion
66 : undefined;
67 return typeof version === "string" && version.length > 0 ? version : null;
69​
70function replyToServerRequest(envelope: JsonRpcEnvelope): unknown {
71 return envelope.method === "ping"
72 ? { jsonrpc: "2.0", id: envelope.id, result: {} }
73 : { jsonrpc: "2.0", id: envelope.id, error: { code: -32601, message: "Method not found" } };
75​
76export interface McpToolSessionOptions {
77 readonly endpoint: string;
78 readonly authorization: string;
79 readonly clientName: string;
80 readonly fetchImplementation?: (url: string, init?: RequestInit) => Promise<Response>;
82​
83export interface McpToolSession {
84 /** Resolves to the JSON-RPC `result` of `tools/call`, a `CallToolResult`. */
85 readonly call: (
86 tool: string,
87 args: Readonly<Record<string, unknown>>,
88 ) => Effect.Effect<unknown, AcpMcpBridgeError>;
90​
91/**
92 * One initialized MCP session over T3 Code's HTTP endpoint, terminated when
93 * the scope closes. Used by the ACP terminal fallback and `t3 thread`.
94 */
95export const mcpToolSession = (
96 options: McpToolSessionOptions,
97): Effect.Effect<McpToolSession, AcpMcpBridgeError, Scope.Scope> => {
98 const fetchImplementation = options.fetchImplementation ?? fetch;
99 let sessionId: string | null = null;
100 let protocolVersion: string | null = null;
101 let nextId = 0;
102​
103 const headers = () => ({
104 accept: "application/json, text/event-stream",
105 authorization: options.authorization,
106 ...(sessionId === null ? {} : { "mcp-session-id": sessionId }),
107 ...(protocolVersion === null ? {} : { "mcp-protocol-version": protocolVersion }),
108 });
109​
110 const send = Effect.fn("AcpMcpStdioBridge.send")(function* (
111 message: unknown,
112 ): Effect.fn.Return<ReadonlyArray<unknown>, AcpMcpBridgeError> {
113 const response = yield* Effect.tryPromise({
114 try: (signal) =>
115 fetchImplementation(options.endpoint, {
116 method: "POST",
117 headers: { "content-type": "application/json", ...headers() },
118 body: JSON.stringify(message),
119 signal,
120 }),
121 catch: bridgeError,
122 });
123 sessionId = response.headers.get("mcp-session-id") ?? sessionId;
124 if (!response.ok) {
125 yield* discardResponseBody(response);
126 return yield* new AcpMcpBridgeError({
127 message: `T3 Code MCP endpoint responded with HTTP ${response.status}.`,
128 });
129 }
130 const payloads: Array<unknown> = [];
131 yield* Stream.runForEach(responsePayloads(response, bridgeError), (payload) => {
132 protocolVersion = protocolVersionOf(payload) ?? protocolVersion;
133 const envelope = asEnvelope(payload);
134 if (envelope?.id !== undefined && typeof envelope.method === "string") {
135 return send(replyToServerRequest(envelope)).pipe(Effect.asVoid);
136 }
137 payloads.push(payload);
138 return Effect.void;
139 });
140 return payloads;
141 });
142​
143 const request = Effect.fn("AcpMcpStdioBridge.request")(function* (
144 method: string,
145 params: unknown,
146 ): Effect.fn.Return<JsonRpcEnvelope, AcpMcpBridgeError> {
147 const id = `t3-cli-${nextId++}`;
148 const responses = yield* send({ jsonrpc: "2.0", id, method, params });
149 const envelope = asEnvelope(responses.find((entry) => asEnvelope(entry)?.id === id));
150 if (envelope === null || envelope.error !== undefined) {
151 const rpcError = Option.getOrUndefined(decodeRpcError(envelope?.error));
152 return yield* new AcpMcpBridgeError({
153 message: `T3 Code MCP ${method} failed${envelope?.error === undefined ? "." : `: ${JSON.stringify(envelope.error)}`}`,
154 ...(rpcError === undefined ? {} : { rpcError }),
155 });
156 }
157 return envelope;
158 });
159​
160 const terminate = Effect.suspend(() =>
161 sessionId === null
162 ? Effect.void
163 : Effect.tryPromise({
164 try: () =>
165 fetchImplementation(options.endpoint, { method: "DELETE", headers: headers() }),
166 catch: bridgeError,
167 }).pipe(Effect.flatMap(discardResponseBody), Effect.ignore),
168 );
169​
170 // Registered before the handshake so a session the server opened is ended
171 // even when the handshake fails, and the handshake stays interruptible.
172 return Effect.gen(function* () {
173 yield* Effect.addFinalizer(() => terminate);
174 yield* request("initialize", {
175 protocolVersion: MCP_PROTOCOL_VERSION,
176 capabilities: {},
177 clientInfo: { name: options.clientName, version: "0.0.0" },
178 });
179 yield* send({ jsonrpc: "2.0", method: "notifications/initialized" });
180 return {
181 call: (tool, args) =>
182 request("tools/call", { name: tool, arguments: args }).pipe(
183 Effect.map((envelope) => envelope.result),
184 ),
185 } satisfies McpToolSession;
186 });
187};
188​
189/**
190 * This is the terminal fallback for ACP agents that accept `mcpServers` in
191 * `session/new` but fail to expose those tools to their model. Compliant ACP
192 * agents continue to use the stdio bridge above.
193 */
194function callAcpMcpTool(options: {
195 readonly endpoint: string;
196 readonly authorization: string;
197 readonly tool: string;
198 readonly arguments: Readonly<Record<string, unknown>>;
199}): Effect.Effect<unknown, AcpMcpBridgeError> {
200 return mcpToolSession({ ...options, clientName: "t3-code-acp-cli" }).pipe(
201 Effect.flatMap((session) => session.call(options.tool, options.arguments)),
202 Effect.scoped,
203 );
205​
206export function runAcpMcpStdioBridge(options: AcpMcpStdioBridgeOptions): Effect.Effect<void> {
207 const fetchImplementation = options.fetchImplementation ?? fetch;
208 return Effect.gen(function* () {
209 let sessionId: string | null = null;
210 let protocolVersion: string | null = null;
211 const running = new Set<Fiber.Fiber<void>>();
212​
213 const writeMessage = (message: unknown): Effect.Effect<void> =>
214 Effect.sync(() => {
215 options.output.write(`${JSON.stringify(message)}\n`);
216 });
217​
218 const handleServerPayload = Effect.fn("AcpMcpStdioBridge.handleServerPayload")(function* (
219 payload: unknown,
220 ): Effect.fn.Return<void> {
221 for (const entry of Array.isArray(payload) ? payload : [payload]) {
222 protocolVersion = protocolVersionOf(entry) ?? protocolVersion;
223 yield* writeMessage(entry);
224 }
225 });
226​
227 const respondWithError = (
228 requestId: unknown,
229 message: string,
230 code = -32603,
231 ): Effect.Effect<void> =>
232 writeMessage({
233 jsonrpc: "2.0",
234 id: requestId ?? null,
235 error: { code, message },
236 });
237​
238 const forward: (line: string, envelope: JsonRpcEnvelope) => Effect.Effect<void> = Effect.fn(
239 "AcpMcpStdioBridge.forward",
240 )(
241 function* (line: string, envelope: JsonRpcEnvelope) {
242 const response = yield* Effect.tryPromise({
243 try: (signal) =>
244 fetchImplementation(options.endpoint, {
245 method: "POST",
246 headers: {
247 "content-type": "application/json",
248 accept: "application/json, text/event-stream",
249 authorization: options.authorization,
250 ...(sessionId === null ? {} : { "mcp-session-id": sessionId }),
251 ...(protocolVersion === null ? {} : { "mcp-protocol-version": protocolVersion }),
252 },
253 body: line,
254 signal,
255 }),
256 catch: bridgeError,
257 });
258 sessionId = response.headers.get("mcp-session-id") ?? sessionId;
259 if (!response.ok) {
260 if (envelope.id !== undefined) {
261 yield* respondWithError(
262 envelope.id,
263 `T3 Code MCP endpoint responded with HTTP ${response.status}.`,
264 );
265 }
266 return yield* discardResponseBody(response);
267 }
268 yield* Stream.runForEach(responsePayloads(response, bridgeError), handleServerPayload);
269 },
270 (effect, _line, envelope) =>
271 effect.pipe(
272 Effect.catchCause((cause) => {
273 if (envelope.id === undefined) return Effect.void;
274 const error = Cause.squash(cause);
275 return respondWithError(
276 envelope.id,
277 `T3 Code MCP bridge request failed: ${error instanceof Error ? error.message : String(error)}`,
278 );
279 }),
280 ),
281 );
282​
283 // Order only session establishment; SSE responses must bypass it to avoid deadlock. Calls remain concurrent after initialization.
284 let sessionBarrier: Effect.Effect<void> = Effect.void;
285 let sessionBarrierPending = false;
286​
287 const launch = Effect.fn("AcpMcpStdioBridge.launch")(function* (
288 task: Effect.Effect<void>,
289 ): Effect.fn.Return<void> {
290 const fiber = yield* Effect.forkChild(task);
291 running.add(fiber);
292 yield* Effect.forkChild(
293 Fiber.await(fiber).pipe(
294 Effect.andThen(
295 Effect.sync(() => {
296 running.delete(fiber);
297 }),
298 ),
299 ),
300 );
301 });
302​
303 const dispatch = Effect.fn("AcpMcpStdioBridge.dispatch")(function* (
304 line: string,
305 ): Effect.fn.Return<void> {
306 if (line.trim().length === 0) return;
307 const parsed = decodeJsonLine(line);
308 if (Option.isNone(parsed)) {
309 return yield* respondWithError(null, "Parse error", -32700);
310 }
311 const envelope = asEnvelope(parsed.value);
312 if (envelope === null) return;
313 const isResponse = envelope.id !== undefined && ("result" in envelope || "error" in envelope);
314 const isSessionHandshake =
315 envelope.method === "initialize" || envelope.method === "notifications/initialized";
316 if (isResponse) {
317 return yield* launch(forward(line, envelope));
318 }
319 if (isSessionHandshake) {
320 const prior = sessionBarrier;
321 const fiber = yield* Effect.forkChild(prior.pipe(Effect.andThen(forward(line, envelope))));
322 running.add(fiber);
323 const barrier = Fiber.await(fiber).pipe(Effect.asVoid);
324 sessionBarrier = barrier;
325 sessionBarrierPending = true;
326 yield* Effect.forkChild(
327 Fiber.await(fiber).pipe(
328 Effect.andThen(
329 Effect.sync(() => {
330 running.delete(fiber);
331 if (sessionBarrier === barrier) sessionBarrierPending = false;
332 }),
333 ),
334 ),
335 );
336 return;
337 }
338 const task = sessionBarrierPending
339 ? sessionBarrier.pipe(Effect.andThen(forward(line, envelope)))
340 : forward(line, envelope);
341 return yield* launch(task);
342 });
343​
344 // node:readline also splits on U+2028/U+2029, which JSON.stringify leaves raw inside strings.
345 yield* Stream.fromAsyncIterable(options.input, bridgeError).pipe(
346 Stream.map((chunk) => (typeof chunk === "string" ? Buffer.from(chunk) : chunk)),
347 Stream.decodeText(),
348 Stream.splitLines,
349 Stream.runForEach(dispatch),
350 Effect.ignoreCause,
351 );
352 yield* Fiber.awaitAll(running);
353 });
355​
356async function readStdin(): Promise<string> {
357 const chunks: Array<Buffer> = [];
358 for await (const chunk of process.stdin) {
359 chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
360 }
361 return Buffer.concat(chunks).toString("utf8");
363​
364/** Avoid heavy imports on the ACP first-message path. */
365export async function runAcpMcpCliFastPath(
366 command: "acp-mcp-bridge" | "acp-mcp-call",
367 args: ReadonlyArray<string>,
368): Promise<void> {
369 const endpoint = process.env.T3_ACP_MCP_ENDPOINT;
370 const authorization = process.env.T3_ACP_MCP_AUTHORIZATION;
371 if (endpoint === undefined || authorization === undefined) {
372 process.stderr.write(`${command} requires T3_ACP_MCP_ENDPOINT and T3_ACP_MCP_AUTHORIZATION.\n`);
373 process.exitCode = 2;
374 return;
375 }
376 if (command === "acp-mcp-bridge") {
377 await Effect.runPromise(
378 runAcpMcpStdioBridge({
379 endpoint,
380 authorization,
381 input: process.stdin,
382 output: process.stdout,
383 }),
384 );
385 return;
386 }
387 const [tool, argumentsArg] = args;
388 if (tool === undefined || argumentsArg === undefined) {
389 process.stderr.write(
390 "acp-mcp-call requires <tool> and <arguments-json>, or - to read it from stdin.\n",
391 );
392 process.exitCode = 2;
393 return;
394 }
395 // Windows PowerShell 5.1 strips the quotes from JSON passed as an argument; stdin keeps them.
396 const argumentsJson = argumentsArg === "-" ? await readStdin() : argumentsArg;
397 let parsed: unknown;
398 try {
399 parsed = JSON.parse(argumentsJson);
400 } catch {
401 process.stderr.write("acp-mcp-call arguments must be valid JSON.\n");
402 process.exitCode = 2;
403 return;
404 }
405 if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
406 process.stderr.write("acp-mcp-call arguments must be a JSON object.\n");
407 process.exitCode = 2;
408 return;
409 }
410 let result = await Effect.runPromise(
411 callAcpMcpTool({
412 endpoint,
413 authorization,
414 tool,
415 arguments: parsed as Record<string, unknown>,
416 }),
417 );
418 // Terminal callers see both fields, unlike native MCP clients that choose one.
419 if (
420 typeof result === "object" &&
421 result !== null &&
422 "structuredContent" in result &&
423 result.structuredContent !== undefined &&
424 "content" in result &&
425 Array.isArray(result.content)
426 ) {
427 const encoded = JSON.stringify(result.structuredContent);
428 result = {
429 ...result,
430 content: result.content.filter(
431 (part: unknown) =>
432 !(
433 typeof part === "object" &&
434 part !== null &&
435 "type" in part &&
436 part.type === "text" &&
437 "text" in part &&
438 part.text === encoded
439 ),
440 ),
441 };
442 }
443 process.stdout.write(`${JSON.stringify(result)}\n`);