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