|
| 1 | +export type ClientMcpOptions = { |
| 2 | + /** Base URL of the opencode server, for example `http://127.0.0.1:4096`. Its query params are kept. */ |
| 3 | + readonly url: string |
| 4 | + /** Client name, `[a-zA-Z0-9_-]+`. Tools are exposed to the model as `<name>_<tool>`. */ |
| 5 | + readonly name: string |
| 6 | + /** Sent as `location[directory]`. */ |
| 7 | + readonly directory?: string |
| 8 | + /** Handshake headers, such as `authorization`. Browsers cannot send them; use a ticket in `url` instead. */ |
| 9 | + readonly headers?: Record<string, string> |
| 10 | + readonly tools: ReadonlyArray<ClientMcpTool> |
| 11 | + readonly WebSocket?: typeof WebSocket |
| 12 | +} |
| 13 | + |
| 14 | +export type ClientMcpTool = { |
| 15 | + /** `[a-zA-Z0-9_-]+` */ |
| 16 | + readonly name: string |
| 17 | + readonly description?: string |
| 18 | + /** JSON Schema for the arguments; `type: "object"` is always set. Arguments are not validated here. */ |
| 19 | + readonly inputSchema?: Record<string, unknown> |
| 20 | + readonly handler: ( |
| 21 | + args: Record<string, unknown>, |
| 22 | + ctx: ClientMcpToolContext, |
| 23 | + ) => ClientMcpToolResult | Promise<ClientMcpToolResult> |
| 24 | +} |
| 25 | + |
| 26 | +export type ClientMcpToolContext = { |
| 27 | + /** The opencode session that issued the call. */ |
| 28 | + readonly sessionID?: string |
| 29 | +} |
| 30 | + |
| 31 | +export type ClientMcpToolResult = { |
| 32 | + readonly content: ReadonlyArray< |
| 33 | + | { readonly type: "text"; readonly text: string } |
| 34 | + | { readonly type: "image"; readonly data: string; readonly mimeType: string } |
| 35 | + > |
| 36 | + readonly isError?: boolean |
| 37 | +} |
| 38 | + |
| 39 | +export type ClientMcpConnection = { |
| 40 | + close(): Promise<void> |
| 41 | +} |
| 42 | + |
| 43 | +type Message = { |
| 44 | + readonly id?: unknown |
| 45 | + readonly method?: unknown |
| 46 | + readonly params?: { |
| 47 | + readonly protocolVersion?: unknown |
| 48 | + readonly name?: unknown |
| 49 | + readonly arguments?: Record<string, unknown> |
| 50 | + readonly _meta?: Record<string, unknown> |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +const SESSION_ID_META_KEY = "ai.opencode/sessionID" |
| 55 | +const PROTOCOL_VERSION = "2025-11-25" |
| 56 | +const RECONNECT_MIN = 500 |
| 57 | +const RECONNECT_MAX = 10_000 |
| 58 | + |
| 59 | +/** |
| 60 | + * Exposes tools to the opencode server: opens a WebSocket to `/api/experimental/client-mcp` and answers MCP |
| 61 | + * JSON-RPC over it (one message per text frame), so the opencode server is the MCP client. Reconnects with |
| 62 | + * backoff until `close()`. |
| 63 | + */ |
| 64 | +export function connectClientMcp(options: ClientMcpOptions): ClientMcpConnection { |
| 65 | + const state: { disposed: boolean; delay: number; timer?: ReturnType<typeof setTimeout>; socket?: WebSocket } = { |
| 66 | + disposed: false, |
| 67 | + delay: RECONNECT_MIN, |
| 68 | + } |
| 69 | + |
| 70 | + const connect = () => { |
| 71 | + if (state.disposed) return |
| 72 | + const Socket = options.WebSocket ?? WebSocket |
| 73 | + const socket = options.headers |
| 74 | + ? // Bun and Node accept a `{ headers }` init as the second argument; the DOM typings only know protocols. |
| 75 | + new Socket(endpoint(options), { headers: options.headers } as unknown as string[]) |
| 76 | + : new Socket(endpoint(options)) |
| 77 | + state.socket = socket |
| 78 | + socket.addEventListener("message", (event) => { |
| 79 | + if (state.disposed || typeof event.data !== "string") return |
| 80 | + const message = parse(event.data) |
| 81 | + if (!message) return |
| 82 | + // Reset backoff only once the opencode server finished initializing, so a failed attach keeps backing off. |
| 83 | + if (message.method === "notifications/initialized") state.delay = RECONNECT_MIN |
| 84 | + // Notifications and responses need no reply. |
| 85 | + if ((typeof message.id !== "string" && typeof message.id !== "number") || typeof message.method !== "string") |
| 86 | + return |
| 87 | + void respond(options, message.method, message.params).then((reply) => |
| 88 | + send(socket, { jsonrpc: "2.0", id: message.id, ...reply }), |
| 89 | + ) |
| 90 | + }) |
| 91 | + socket.addEventListener("close", () => { |
| 92 | + if (state.socket === socket) state.socket = undefined |
| 93 | + if (state.disposed) return |
| 94 | + state.timer = setTimeout(connect, state.delay) |
| 95 | + state.delay = Math.min(state.delay * 2, RECONNECT_MAX) |
| 96 | + }) |
| 97 | + } |
| 98 | + |
| 99 | + connect() |
| 100 | + |
| 101 | + return { |
| 102 | + async close() { |
| 103 | + state.disposed = true |
| 104 | + clearTimeout(state.timer) |
| 105 | + state.socket?.close(1000) |
| 106 | + }, |
| 107 | + } |
| 108 | +} |
| 109 | + |
| 110 | +async function respond(options: ClientMcpOptions, method: string, params: Message["params"]) { |
| 111 | + switch (method) { |
| 112 | + case "initialize": |
| 113 | + return { |
| 114 | + result: { |
| 115 | + // The opencode server only offers versions it supports, so echo its choice. |
| 116 | + protocolVersion: typeof params?.protocolVersion === "string" ? params.protocolVersion : PROTOCOL_VERSION, |
| 117 | + capabilities: { tools: {} }, |
| 118 | + serverInfo: { name: options.name, version: "1.0.0" }, |
| 119 | + }, |
| 120 | + } |
| 121 | + case "ping": |
| 122 | + return { result: {} } |
| 123 | + case "tools/list": |
| 124 | + return { |
| 125 | + result: { |
| 126 | + tools: options.tools.map((tool) => ({ |
| 127 | + name: tool.name, |
| 128 | + description: tool.description, |
| 129 | + inputSchema: { type: "object", ...tool.inputSchema }, |
| 130 | + })), |
| 131 | + }, |
| 132 | + } |
| 133 | + case "tools/call": { |
| 134 | + const tool = options.tools.find((tool) => tool.name === params?.name) |
| 135 | + if (!tool) return { error: { code: -32602, message: `Unknown tool: ${String(params?.name)}` } } |
| 136 | + const meta = params?._meta?.[SESSION_ID_META_KEY] |
| 137 | + return Promise.resolve() |
| 138 | + .then(() => tool.handler(params?.arguments ?? {}, { sessionID: typeof meta === "string" ? meta : undefined })) |
| 139 | + .then( |
| 140 | + (result) => ({ result }), |
| 141 | + (error) => ({ |
| 142 | + result: { |
| 143 | + content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], |
| 144 | + isError: true, |
| 145 | + }, |
| 146 | + }), |
| 147 | + ) |
| 148 | + } |
| 149 | + } |
| 150 | + return { error: { code: -32601, message: `Method not found: ${method}` } } |
| 151 | +} |
| 152 | + |
| 153 | +function send(socket: WebSocket, message: object) { |
| 154 | + if (socket.readyState === socket.OPEN) socket.send(JSON.stringify(message)) |
| 155 | +} |
| 156 | + |
| 157 | +function parse(text: string): Message | undefined { |
| 158 | + try { |
| 159 | + const value: unknown = JSON.parse(text) |
| 160 | + return typeof value === "object" && value !== null && !Array.isArray(value) ? value : undefined |
| 161 | + } catch { |
| 162 | + return undefined |
| 163 | + } |
| 164 | +} |
| 165 | + |
| 166 | +function endpoint(options: ClientMcpOptions) { |
| 167 | + const base = new URL(options.url) |
| 168 | + if (!base.pathname.endsWith("/")) base.pathname += "/" |
| 169 | + const url = new URL("api/experimental/client-mcp", base) |
| 170 | + url.search = base.search |
| 171 | + if (options.directory) url.searchParams.set("location[directory]", options.directory) |
| 172 | + url.searchParams.set("name", options.name) |
| 173 | + url.protocol = url.protocol === "https:" || url.protocol === "wss:" ? "wss:" : "ws:" |
| 174 | + return url |
| 175 | +} |
0 commit comments