The best way to control Claude Code, Codex and more from any computer or phone
| 1 | // @effect-diagnostics globalJsonInEffect:off |
| 2 | import * as Deferred from "effect/Deferred"; |
| 3 | import * as Effect from "effect/Effect"; |
| 4 | import * as Schema from "effect/Schema"; |
| 5 | import * as Semaphore from "effect/Semaphore"; |
| 6 | import * as Stream from "effect/Stream"; |
| 7 | import type * as AcpSchema from "effect-acp/compat"; |
| 8 | |
| 9 | import { responsePayloads } from "@t3tools/shared/mcpResponsePayloads"; |
| 10 | |
| 11 | const MAX_CONNECTIONS = 16; |
| 12 | const MAX_MESSAGE_BYTES = 8 * 1024 * 1024; |
| 13 | // Runtime teardown waits on disconnect, so an endpoint that never answers must not hold it. |
| 14 | const DISCONNECT_TIMEOUT = "5 seconds"; |
| 15 | |
| 16 | interface JsonRpcEnvelope { |
| 17 | readonly id?: unknown; |
| 18 | readonly method?: unknown; |
| 19 | readonly error?: unknown; |
| 20 | readonly result?: unknown; |
| 21 | } |
| 22 | |
| 23 | interface Connection { |
| 24 | readonly mutex: Semaphore.Semaphore; |
| 25 | sessionId: string | null; |
| 26 | protocolVersion: string | null; |
| 27 | nextRequestId: number; |
| 28 | } |
| 29 | |
| 30 | export class AcpMcpOverAcpError extends Schema.TaggedError<AcpMcpOverAcpError>()( |
| 31 | "AcpMcpOverAcpError", |
| 32 | { message: Schema.String, cause: Schema.optional(Schema.Defect()) }, |
| 33 | ) {} |
| 34 | |
| 35 | const isAcpMcpOverAcpError = Schema.is(AcpMcpOverAcpError); |
| 36 | |
| 37 | const bridgeError = (cause: unknown): AcpMcpOverAcpError => |
| 38 | isAcpMcpOverAcpError(cause) |
| 39 | ? cause |
| 40 | : new AcpMcpOverAcpError({ |
| 41 | message: cause instanceof Error ? cause.message : String(cause), |
| 42 | cause, |
| 43 | }); |
| 44 | |
| 45 | const asEnvelope = (value: unknown): JsonRpcEnvelope | null => |
| 46 | typeof value === "object" && value !== null && !Array.isArray(value) |
| 47 | ? (value as JsonRpcEnvelope) |
| 48 | : null; |
| 49 | |
| 50 | function protocolVersionOf(payload: unknown): string | null { |
| 51 | const result = asEnvelope(payload)?.result; |
| 52 | if (typeof result !== "object" || result === null || Array.isArray(result)) return null; |
| 53 | const protocolVersion = (result as { readonly protocolVersion?: unknown }).protocolVersion; |
| 54 | return typeof protocolVersion === "string" && protocolVersion.length > 0 ? protocolVersion : null; |
| 55 | } |
| 56 | |
| 57 | function errorMessage(error: unknown): string { |
| 58 | if (typeof error !== "object" || error === null || Array.isArray(error)) { |
| 59 | return "The MCP server returned an error."; |
| 60 | } |
| 61 | const message = (error as { readonly message?: unknown }).message; |
| 62 | return typeof message === "string" && message.length > 0 |
| 63 | ? message |
| 64 | : "The MCP server returned an error."; |
| 65 | } |
| 66 | |
| 67 | export interface AcpMcpOverAcpBridgeOptions { |
| 68 | readonly endpoint: string; |
| 69 | readonly authorization: string; |
| 70 | readonly allocateConnectionId: Effect.Effect<string>; |
| 71 | readonly fetchImplementation?: (url: string, init?: RequestInit) => Promise<Response>; |
| 72 | } |
| 73 | |
| 74 | export interface AcpMcpOverAcpBridge { |
| 75 | readonly connect: ( |
| 76 | request: AcpSchema.ConnectMcpRequest, |
| 77 | ) => Effect.Effect<AcpSchema.ConnectMcpResponse, AcpMcpOverAcpError>; |
| 78 | readonly message: ( |
| 79 | request: AcpSchema.MessageMcpRequest, |
| 80 | ) => Effect.Effect<AcpSchema.MessageMcpResponse, AcpMcpOverAcpError>; |
| 81 | readonly notification: ( |
| 82 | request: AcpSchema.MessageMcpNotification, |
| 83 | ) => Effect.Effect<void, AcpMcpOverAcpError>; |
| 84 | readonly disconnect: ( |
| 85 | request: AcpSchema.DisconnectMcpRequest, |
| 86 | ) => Effect.Effect<AcpSchema.DisconnectMcpResponse, AcpMcpOverAcpError>; |
| 87 | /** Fails every call in flight, so Stop releases their HTTP responses. */ |
| 88 | readonly stopCalls: Effect.Effect<void>; |
| 89 | readonly dispose: Effect.Effect<void>; |
| 90 | } |
| 91 | |
| 92 | export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(function* ( |
| 93 | options: AcpMcpOverAcpBridgeOptions, |
| 94 | ): Effect.fn.Return<AcpMcpOverAcpBridge> { |
| 95 | const fetchImplementation = options.fetchImplementation ?? fetch; |
| 96 | const connections = yield* Effect.sync(() => new Map<string, Connection>()); |
| 97 | let callsStopped = yield* Deferred.make<void>(); |
| 98 | |
| 99 | const connectionFor = (connectionId: string): Effect.Effect<Connection, AcpMcpOverAcpError> => |
| 100 | Effect.suspend(() => { |
| 101 | const connection = connections.get(connectionId); |
| 102 | return connection === undefined |
| 103 | ? Effect.fail( |
| 104 | new AcpMcpOverAcpError({ |
| 105 | message: `Unknown MCP-over-ACP connection "${connectionId}".`, |
| 106 | }), |
| 107 | ) |
| 108 | : Effect.succeed(connection); |
| 109 | }); |
| 110 | |
| 111 | // Only initialization needs ordering; negotiated calls may wait independently. |
| 112 | const untilNegotiated = <A, E>(connection: Connection, effect: Effect.Effect<A, E>) => |
| 113 | Effect.suspend(() => |
| 114 | connection.protocolVersion === null ? connection.mutex.withPermits(1)(effect) : effect, |
| 115 | ); |
| 116 | |
| 117 | const sendNow = ( |
| 118 | connection: Connection, |
| 119 | message: unknown, |
| 120 | ): Effect.Effect<ReadonlyArray<unknown>, AcpMcpOverAcpError> => |
| 121 | untilNegotiated( |
| 122 | connection, |
| 123 | Effect.gen(function* () { |
| 124 | const body = JSON.stringify(message); |
| 125 | if (Buffer.byteLength(body) > MAX_MESSAGE_BYTES) { |
| 126 | return yield* new AcpMcpOverAcpError({ message: "MCP-over-ACP message exceeds 8 MiB." }); |
| 127 | } |
| 128 | const response = yield* Effect.tryPromise({ |
| 129 | try: (signal) => |
| 130 | fetchImplementation(options.endpoint, { |
| 131 | method: "POST", |
| 132 | signal, |
| 133 | headers: { |
| 134 | "content-type": "application/json", |
| 135 | accept: "application/json, text/event-stream", |
| 136 | authorization: options.authorization, |
| 137 | ...(connection.sessionId === null |
| 138 | ? {} |
| 139 | : { "mcp-session-id": connection.sessionId }), |
| 140 | ...(connection.protocolVersion === null |
| 141 | ? {} |
| 142 | : { "mcp-protocol-version": connection.protocolVersion }), |
| 143 | }, |
| 144 | body, |
| 145 | }), |
| 146 | catch: bridgeError, |
| 147 | }); |
| 148 | connection.sessionId = response.headers.get("mcp-session-id") ?? connection.sessionId; |
| 149 | if (!response.ok) { |
| 150 | yield* Effect.promise( |
| 151 | () => response.body?.cancel().catch(() => undefined) ?? Promise.resolve(), |
| 152 | ); |
| 153 | return yield* new AcpMcpOverAcpError({ |
| 154 | message: `T3 Code MCP endpoint responded with HTTP ${response.status}.`, |
| 155 | }); |
| 156 | } |
| 157 | const payloads = [...(yield* Stream.runCollect(responsePayloads(response, bridgeError)))]; |
| 158 | for (const payload of payloads) { |
| 159 | connection.protocolVersion = protocolVersionOf(payload) ?? connection.protocolVersion; |
| 160 | } |
| 161 | return payloads; |
| 162 | }).pipe(Effect.mapError(bridgeError)), |
| 163 | ); |
| 164 | |
| 165 | const send = ( |
| 166 | connection: Connection, |
| 167 | message: unknown, |
| 168 | ): Effect.Effect<ReadonlyArray<unknown>, AcpMcpOverAcpError> => |
| 169 | Effect.suspend(() => |
| 170 | Effect.raceFirst( |
| 171 | sendNow(connection, message), |
| 172 | Deferred.await(callsStopped).pipe( |
| 173 | Effect.andThen( |
| 174 | Effect.fail(new AcpMcpOverAcpError({ message: "The MCP call was stopped." })), |
| 175 | ), |
| 176 | ), |
| 177 | ), |
| 178 | ); |
| 179 | |
| 180 | const disconnect = Effect.fn("mcpOverAcpBridge.disconnect")(function* ( |
| 181 | request: AcpSchema.DisconnectMcpRequest, |
| 182 | ): Effect.fn.Return<AcpSchema.DisconnectMcpResponse, AcpMcpOverAcpError> { |
| 183 | const connection = yield* connectionFor(request.connectionId); |
| 184 | connections.delete(request.connectionId); |
| 185 | const sessionId = connection.sessionId; |
| 186 | if (sessionId !== null) { |
| 187 | yield* Effect.gen(function* () { |
| 188 | const response = yield* Effect.tryPromise({ |
| 189 | try: (signal) => |
| 190 | fetchImplementation(options.endpoint, { |
| 191 | method: "DELETE", |
| 192 | signal, |
| 193 | headers: { |
| 194 | authorization: options.authorization, |
| 195 | "mcp-session-id": sessionId, |
| 196 | ...(connection.protocolVersion === null |
| 197 | ? {} |
| 198 | : { "mcp-protocol-version": connection.protocolVersion }), |
| 199 | }, |
| 200 | }), |
| 201 | catch: bridgeError, |
| 202 | }); |
| 203 | if (!response.ok && response.status !== 404) { |
| 204 | return yield* new AcpMcpOverAcpError({ |
| 205 | message: `T3 Code MCP endpoint rejected disconnect with HTTP ${response.status}.`, |
| 206 | }); |
| 207 | } |
| 208 | yield* Effect.promise( |
| 209 | () => response.body?.cancel().catch(() => undefined) ?? Promise.resolve(), |
| 210 | ); |
| 211 | }).pipe( |
| 212 | Effect.timeoutOrElse({ |
| 213 | duration: DISCONNECT_TIMEOUT, |
| 214 | orElse: () => |
| 215 | Effect.fail( |
| 216 | new AcpMcpOverAcpError({ |
| 217 | message: "T3 Code MCP endpoint did not answer disconnect.", |
| 218 | }), |
| 219 | ), |
| 220 | }), |
| 221 | // Restore a session that failed to close, so a retry or dispose can close it. |
| 222 | Effect.onError(() => Effect.sync(() => connections.set(request.connectionId, connection))), |
| 223 | ); |
| 224 | } |
| 225 | return {}; |
| 226 | }); |
| 227 | |
| 228 | return { |
| 229 | connect: Effect.fn("mcpOverAcpBridge.connect")(function* (request) { |
| 230 | if (request.serverId !== "t3-code") { |
| 231 | return yield* new AcpMcpOverAcpError({ |
| 232 | message: `Unknown ACP MCP server "${request.serverId}".`, |
| 233 | }); |
| 234 | } |
| 235 | if (connections.size >= MAX_CONNECTIONS) { |
| 236 | return yield* new AcpMcpOverAcpError({ message: "Too many MCP-over-ACP connections." }); |
| 237 | } |
| 238 | const connectionId = yield* options.allocateConnectionId; |
| 239 | connections.set(connectionId, { |
| 240 | mutex: yield* Semaphore.make(1), |
| 241 | sessionId: null, |
| 242 | protocolVersion: null, |
| 243 | nextRequestId: 0, |
| 244 | }); |
| 245 | return { connectionId }; |
| 246 | }), |
| 247 | message: Effect.fn("mcpOverAcpBridge.message")(function* (request) { |
| 248 | const connection = yield* connectionFor(request.connectionId); |
| 249 | const id = ++connection.nextRequestId; |
| 250 | const payloads = yield* send(connection, { |
| 251 | jsonrpc: "2.0", |
| 252 | id, |
| 253 | method: request.method, |
| 254 | ...(request.params == null ? {} : { params: request.params }), |
| 255 | }); |
| 256 | const response = payloads.find((payload) => asEnvelope(payload)?.id === id); |
| 257 | const envelope = asEnvelope(response); |
| 258 | if (envelope === null) { |
| 259 | return yield* new AcpMcpOverAcpError({ |
| 260 | message: "MCP server did not return a matching response.", |
| 261 | }); |
| 262 | } |
| 263 | if (envelope.error !== undefined) { |
| 264 | return yield* new AcpMcpOverAcpError({ message: errorMessage(envelope.error) }); |
| 265 | } |
| 266 | return (envelope.result ?? null) as AcpSchema.MessageMcpResponse; |
| 267 | }), |
| 268 | notification: Effect.fn("mcpOverAcpBridge.notification")(function* (request) { |
| 269 | const connection = yield* connectionFor(request.connectionId); |
| 270 | yield* send(connection, { |
| 271 | jsonrpc: "2.0", |
| 272 | method: request.method, |
| 273 | ...(request.params == null ? {} : { params: request.params }), |
| 274 | }); |
| 275 | }), |
| 276 | disconnect, |
| 277 | stopCalls: Effect.suspend(() => { |
| 278 | const stopped = callsStopped; |
| 279 | callsStopped = Deferred.makeUnsafe(); |
| 280 | return Deferred.succeed(stopped, undefined); |
| 281 | }).pipe(Effect.asVoid), |
| 282 | dispose: Effect.suspend(() => |
| 283 | Effect.forEach( |
| 284 | [...connections.keys()], |
| 285 | (connectionId) => disconnect({ connectionId }).pipe(Effect.ignore), |
| 286 | { concurrency: "unbounded", discard: true }, |
| 287 | ), |
| 288 | ), |
| 289 | }; |
| 290 | }); |