Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

tool-bridge.ts

404 lines13.7 KB

1/**
2 * MCP tool-proxy bridge, shared by all harness adapters.
3 *
4 * Exposes chat()-provided server tools to an in-sandbox agent as an MCP server.
5 * The agent (inside the sandbox) calls `mcp__tanstack__<tool>`; the call is
6 * proxied OUT to a bridge endpoint, where the tool's `execute()` runs in the
7 * orchestrator process (with its closures / DB / secrets), and the result is
8 * returned into the sandbox.
9 *
10 * The bridge is split into a transport-agnostic CORE and a TRANSPORT:
11 * - {@link createToolBridgeCore} owns tool dispatch + the permission resolver
12 * (no I/O). It is what makes the bridge portable.
13 * - {@link startHostToolBridge} is the `node:http` transport for a long-running
14 * host (laptop / CI / Docker orchestrator). It binds loopback unless the
15 * sandbox must reach it via `host.docker.internal`, and authenticates with a
16 * constant-time bearer check.
17 * - A serverless/edge orchestrator (e.g. a Durable Object) instead serves the
18 * SAME core from its own `fetch` handler — no raw TCP listener — see
19 * {@link handleBridgeJsonRpc} and the Cloudflare example.
20 */
21import { createServer } from 'node:http'
22import { randomBytes, timingSafeEqual } from 'node:crypto'
23import { once } from 'node:events'
24import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
25import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'
26import {
27 CallToolRequestSchema,
28 ListToolsRequestSchema,
29} from '@modelcontextprotocol/sdk/types.js'
30import type { AddressInfo } from 'node:net'
31import type { AnyTool, EmitCustomEventOptions } from '@tanstack/ai'
32​
33/**
34 * Name of the bridged MCP server. The agent sees tools as
35 * `mcp__tanstack__<tool>`; each adapter's stream translator strips this prefix
36 * so tool-call events match the names the application registered.
37 */
38export const BRIDGED_MCP_SERVER_NAME = 'tanstack'
39​
40/** Hostname the sandbox uses to reach the bridge endpoint, per provider. */
41export function hostForSandbox(provider: string): string {
42 return provider === 'docker' || provider === 'sbx'
43 ? 'host.docker.internal'
44 : '127.0.0.1'
46​
47/** Result of a permission decision returned to the harness's prompt tool. */
48export interface PermissionToolResult {
49 behavior: 'allow' | 'deny'
50 message?: string
51 updatedInput?: unknown
53​
54export interface BridgePermission {
55 toolName: string
56 resolve: (input: {
57 tool_name?: string
58 input?: unknown
59 }) => PermissionToolResult | Promise<PermissionToolResult>
61​
62export interface ToolBridgeCoreOptions {
63 /** Runtime context forwarded to each tool's `execute()`. */
64 context?: unknown
65 /** Abort signal forwarded to each tool's `execute()`. */
66 signal?: AbortSignal
67 /**
68 * Forwarded to each tool's `execute()` so a bridged tool can stream progress /
69 * custom events back to the client mid-execution (e.g. code mode's
70 * `code_mode:console` logs). Without it those events are silently dropped — the
71 * bridge runs out-of-band from the main tool executor, so the executor's own
72 * `emitCustomEvent` never reaches a bridged tool. The harness adapter supplies
73 * one that injects a CUSTOM chunk into its live output stream.
74 */
75 emitCustomEvent?: (
76 eventName: string,
77 value: Record<string, unknown>,
78 options?: EmitCustomEventOptions,
79 ) => void
80 /**
81 * Optional permission-prompt tool (e.g. for Claude Code's
82 * `--permission-prompt-tool`). When set, the bridge exposes an extra MCP tool
83 * `<name>` whose handler returns the orchestrator's allow/deny decision.
84 */
85 permission?: BridgePermission
87​
88/** An MCP tool descriptor as advertised to the in-sandbox agent. */
89export interface ToolDescriptor {
90 name: string
91 description?: string
92 inputSchema: { type: 'object'; [key: string]: unknown }
94​
95/**
96 * Coerce a tool's `inputSchema` into the object-schema shape MCP advertises,
97 * substituting an empty object schema when it isn't already a JSON-schema object
98 * (project rule: a guard, not an `as` cast).
99 */
100function toObjectSchema(schema: unknown): {
101 type: 'object'
102 [key: string]: unknown
103} {
104 if (
105 schema !== null &&
106 typeof schema === 'object' &&
107 'type' in schema &&
108 schema.type === 'object'
109 ) {
110 return { ...schema, type: 'object' }
111 }
112 return { type: 'object', properties: {} }
114​
115/** MCP `tools/call` result shape. */
116export interface ToolCallResult {
117 content: Array<{ type: 'text'; text: string }>
118 isError?: boolean
120​
121/**
122 * Transport-agnostic bridge logic: list tools, and dispatch a tool/permission
123 * call. No sockets, no auth — a transport ({@link startHostToolBridge} or a
124 * `fetch` handler) wraps this and owns I/O + the bearer check.
125 */
126export interface ToolBridgeCore {
127 listTools: () => Array<ToolDescriptor>
128 callTool: (name: string, args: unknown) => Promise<ToolCallResult>
130​
131/** Build the transport-agnostic bridge core for the given tools. */
132export function createToolBridgeCore(
133 tools: Array<AnyTool>,
134 options: ToolBridgeCoreOptions = {},
135): ToolBridgeCore {
136 const toolsByName = new Map(tools.map((tool) => [tool.name, tool]))
137 const permission = options.permission
138​
139 const permissionDescriptor: ToolDescriptor | undefined = permission
140 ? {
141 name: permission.toolName,
142 description:
143 'Permission prompt: returns {behavior:"allow"|"deny"} for a requested action.',
144 inputSchema: { type: 'object', properties: {} },
145 }
146 : undefined
147​
148 return {
149 listTools() {
150 return [
151 ...tools.map((tool) => ({
152 name: tool.name,
153 description: tool.description,
154 inputSchema: toObjectSchema(tool.inputSchema),
155 })),
156 ...(permissionDescriptor ? [permissionDescriptor] : []),
157 ]
158 },
159​
160 async callTool(name, args) {
161 if (permission && name === permission.toolName) {
162 const result = await permission.resolve(args ?? {})
163 return { content: [{ type: 'text', text: JSON.stringify(result) }] }
164 }
165 const tool = toolsByName.get(name)
166 if (!tool?.execute) throw new Error(`Unknown tool: ${name}`)
167 try {
168 const result: unknown = await tool.execute(args ?? {}, {
169 context: options.context,
170 abortSignal: options.signal,
171 // No-op default so tools that always call it (e.g. code mode) don't
172 // crash when the transport didn't wire a sink.
173 emitCustomEvent: options.emitCustomEvent ?? (() => {}),
174 })
175 const text =
176 typeof result === 'string' ? result : JSON.stringify(result)
177 return { content: [{ type: 'text', text }] }
178 } catch (error) {
179 const message = error instanceof Error ? error.message : String(error)
180 return {
181 isError: true,
182 content: [
183 { type: 'text', text: `Tool execution failed: ${message}` },
184 ],
185 }
186 }
187 },
188 }
190​
191/**
192 * Minimal JSON-RPC dispatcher over a {@link ToolBridgeCore}, so a `fetch`-based
193 * transport (Worker / Durable Object) can serve MCP `initialize` / `tools/list`
194 * / `tools/call` without the node-specific HTTP transport. Returns the JSON-RPC
195 * response object, or `null` for a notification (no `id`).
196 */
197export async function handleBridgeJsonRpc(
198 core: ToolBridgeCore,
199 message: unknown,
200): Promise<unknown> {
201 if (message === null || typeof message !== 'object') {
202 return {
203 jsonrpc: '2.0',
204 id: null,
205 error: { code: -32600, message: 'Invalid Request' },
206 }
207 }
208 const rpc = message as { id?: unknown; method?: unknown; params?: unknown }
209 const id = rpc.id ?? null
210 const respond = (result: unknown): unknown => ({ jsonrpc: '2.0', id, result })
211 switch (rpc.method) {
212 case 'initialize':
213 return respond({
214 protocolVersion: '2024-11-05',
215 capabilities: { tools: {} },
216 serverInfo: { name: BRIDGED_MCP_SERVER_NAME, version: '1.0.0' },
217 })
218 case 'notifications/initialized':
219 return null
220 case 'tools/list':
221 return respond({ tools: core.listTools() })
222 case 'tools/call': {
223 const params = (rpc.params ?? {}) as {
224 name?: unknown
225 arguments?: unknown
226 }
227 if (typeof params.name !== 'string') {
228 return {
229 jsonrpc: '2.0',
230 id,
231 error: { code: -32602, message: 'Invalid params: name' },
232 }
233 }
234 return respond(await core.callTool(params.name, params.arguments ?? {}))
235 }
236 default:
237 return {
238 jsonrpc: '2.0',
239 id,
240 error: { code: -32601, message: 'Method not found' },
241 }
242 }
244​
245/**
246 * Constant-time check of an `Authorization: Bearer <token>` header against the
247 * expected token. Length mismatch returns false early (token length is not
248 * secret); equal-length comparison is timing-safe.
249 */
250export function timingSafeBearerEqual(
251 header: string | undefined,
252 token: string,
253): boolean {
254 if (header === undefined) return false
255 const a = Buffer.from(header)
256 const b = Buffer.from(`Bearer ${token}`)
257 if (a.length !== b.length) return false
258 return timingSafeEqual(a, b)
260​
261export interface HostToolBridge {
262 /** MCP server name; tools appear to the agent as `mcp__<name>__<tool>`. */
263 name: string
264 /** URL the SANDBOX uses to reach this bridge. */
265 url: string
266 /** Per-run bearer token gating the endpoint. */
267 token: string
268 close: () => Promise<void>
270​
271export interface StartBridgeOptions extends ToolBridgeCoreOptions {
272 /** Hostname the sandbox uses to reach the host (e.g. `host.docker.internal`). */
273 hostForSandbox: string
274 /**
275 * Address to bind the listener to. Defaults to `127.0.0.1` (loopback) and is
276 * widened to `0.0.0.0` only when the sandbox reaches the host via
277 * `host.docker.internal` (a container can't reach the host's loopback).
278 */
279 bindAddress?: string
281​
282function buildMcpServer(core: ToolBridgeCore): McpServer {
283 const server = new McpServer(
284 { name: BRIDGED_MCP_SERVER_NAME, version: '1.0.0' },
285 { capabilities: { tools: {} } },
286 )
287 server.server.setRequestHandler(ListToolsRequestSchema, () => ({
288 tools: core.listTools(),
289 }))
290 server.server.setRequestHandler(CallToolRequestSchema, async (request) => {
291 const result = await core.callTool(
292 request.params.name,
293 request.params.arguments ?? {},
294 )
295 return {
296 content: result.content,
297 ...(result.isError ? { isError: true } : {}),
298 }
299 })
300 return server
302​
303/**
304 * Start the `node:http` MCP tool-proxy bridge for the given tools. For a
305 * long-running host (laptop / CI / Docker orchestrator). Serverless/edge
306 * orchestrators serve {@link createToolBridgeCore} from their own `fetch`
307 * handler instead.
308 */
309export async function startHostToolBridge(
310 tools: Array<AnyTool>,
311 options: StartBridgeOptions,
312): Promise<HostToolBridge> {
313 const token = randomBytes(24).toString('hex')
314 const core = createToolBridgeCore(tools, options)
315 // Loopback by default; widen to all interfaces only for the Docker bridge,
316 // which a container reaches via host.docker.internal (host gateway).
317 const bindAddress =
318 options.bindAddress ??
319 (options.hostForSandbox === 'host.docker.internal'
320 ? '0.0.0.0'
321 : '127.0.0.1')
322​
323 const httpServer = createServer((req, res) => {
324 void (async () => {
325 if (!timingSafeBearerEqual(req.headers['authorization'], token)) {
326 res.writeHead(401).end('unauthorized')
327 return
328 }
329 const server = buildMcpServer(core)
330 const transport = new StreamableHTTPServerTransport({
331 sessionIdGenerator: undefined,
332 })
333 res.on('close', () => {
334 void transport.close()
335 void server.close()
336 })
337 await server.connect(transport)
338​
339 let body = ''
340 for await (const chunk of req) body += chunk
341 let parsed: unknown
342 try {
343 parsed = body ? JSON.parse(body) : undefined
344 } catch {
345 // Malformed agent request → 400, distinct from an internal 500.
346 if (!res.headersSent) res.writeHead(400).end('invalid JSON body')
347 return
348 }
349 await transport.handleRequest(req, res, parsed)
350 })().catch((error: unknown) => {
351 // Log the underlying fault — on the host/Docker path there is no run-log
352 // capturing it, so swallowing it leaves an operator with nothing.
353 console.error('[tool-bridge] request handler failed:', error)
354 if (!res.headersSent) res.writeHead(500).end('bridge error')
355 })
356 })
357​
358 await once(httpServer.listen(0, bindAddress), 'listening')
359 const port = (httpServer.address() as AddressInfo).port
360 const url = `http://${options.hostForSandbox}:${port}/mcp`
361​
362 return {
363 name: BRIDGED_MCP_SERVER_NAME,
364 url,
365 token,
366 close: () =>
367 new Promise<void>((resolve) => httpServer.close(() => resolve())),
368 }
370​
371/** A provisioned, reachable bridge endpoint (same shape as {@link HostToolBridge}). */
372export type ProvisionedBridge = HostToolBridge
373​
374export interface ToolBridgeProvisionOptions extends ToolBridgeCoreOptions {
375 /** Sandbox provider name, to derive how the sandbox reaches the bridge. */
376 provider: string
378​
379/**
380 * Stands up the tool-bridge endpoint for a run. The seam that makes the bridge
381 * portable across runtimes: a harness adapter asks its capability context for a
382 * provisioner and uses {@link nodeHttpBridgeProvisioner} as the default (host /
383 * Docker). A serverless/edge orchestrator PROVIDES its own — e.g. a Durable
384 * Object that mounts {@link createToolBridgeCore} / {@link handleBridgeJsonRpc}
385 * on its `fetch` handler and returns a sandbox-reachable URL — so no raw TCP
386 * listener is needed.
387 */
388export interface ToolBridgeProvisioner {
389 provision: (
390 tools: Array<AnyTool>,
391 options: ToolBridgeProvisionOptions,
392 ) => Promise<ProvisionedBridge>
394​
395/** Default provisioner: a `node:http` listener on the host. */
396export const nodeHttpBridgeProvisioner: ToolBridgeProvisioner = {
397 provision(tools, options) {
398 const { provider, ...core } = options
399 return startHostToolBridge(tools, {
400 hostForSandbox: hostForSandbox(provider),
401 ...core,
402 })
403 },