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