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