Skip to content

Commit 4535146

Browse files
authored
feat(client): add connectClientMcp helper for client-hosted MCP tools (#57504)
1 parent 76fd05f commit 4535146

5 files changed

Lines changed: 438 additions & 1 deletion

File tree

‎bun.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎packages/client/package.json‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,8 @@
2323
"./solid": "./src/solid/index.ts",
2424
"./effect": "./src/effect/index.ts",
2525
"./effect/api": "./src/effect/api.ts",
26-
"./effect/service": "./src/effect/service.ts"
26+
"./effect/service": "./src/effect/service.ts",
27+
"./mcp": "./src/mcp.ts"
2728
},
2829
"scripts": {
2930
"build": "bun run script/build-package.ts",
@@ -50,6 +51,7 @@
5051
},
5152
"devDependencies": {
5253
"@effect/platform-node": "catalog:",
54+
"@modelcontextprotocol/client": "2.0.0",
5355
"@opencode/httpapi-codegen": "workspace:*",
5456
"@tsconfig/bun": "catalog:",
5557
"@types/bun": "catalog:",

‎packages/client/src/mcp.ts‎

Lines changed: 175 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,175 @@
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+
}

‎packages/client/test/import-boundaries.test.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,11 @@ describe("public import boundaries", () => {
4141
expect(within(effectService.eager, effect).length).toBeGreaterThan(0)
4242
expect(within(effectService.all, core)).toEqual([])
4343
expect(within(effectService.all, server)).toEqual([])
44+
45+
const mcp = await bundleInputs("@opencode/client/mcp", "browser")
46+
47+
// The MCP entrypoint is dependency-free: only the generated entry and mcp.ts itself.
48+
expect(mcp.all.filter((file) => !file.endsWith("index.ts"))).toEqual([resolve(directory, "src/mcp.ts")])
4449
})
4550
})
4651

0 commit comments

Comments
 (0)