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

tool-bridge.ts

424 lines14.5 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 /** The thread id of the run, forwarded to each tool's `execute()`. */
64 threadId: string
65 /** Runtime context forwarded to each tool's `execute()`. */
66 context?: unknown
67 /** Abort signal forwarded to each tool's `execute()`. */
68 signal?: AbortSignal
69 /**
70 * Forwarded to each tool's `execute()` so a bridged tool can stream progress /
71 * custom events back to the client mid-execution (e.g. code mode's
72 * `code_mode:console` logs). Without it those events are silently dropped — the
73 * bridge runs out-of-band from the main tool executor, so the executor's own
74 * `emitCustomEvent` never reaches a bridged tool. The harness adapter supplies
75 * one that injects a CUSTOM chunk into its live output stream.
76 */
77 emitCustomEvent?: (
78 eventName: string,
79 value: Record<string, unknown>,
80 options?: EmitCustomEventOptions,
81 ) => void
82 /**
83 * Optional permission-prompt tool (e.g. for Claude Code's
84 * `--permission-prompt-tool`). When set, the bridge exposes an extra MCP tool
85 * `<name>` whose handler returns the orchestrator's allow/deny decision.
86 */
87 permission?: BridgePermission
89​
90/** An MCP tool descriptor as advertised to the in-sandbox agent. */
91export interface ToolDescriptor {
92 name: string
93 description?: string
94 inputSchema: { type: 'object'; [key: string]: unknown }
96​
97/**
98 * Coerce a tool's `inputSchema` into the object-schema shape MCP advertises,
99 * substituting an empty object schema when it isn't already a JSON-schema object
100 * (project rule: a guard, not an `as` cast).
101 */
102function toObjectSchema(schema: unknown): {
103 type: 'object'
104 [key: string]: unknown
105} {
106 if (
107 schema !== null &&
108 typeof schema === 'object' &&
109 'type' in schema &&
110 schema.type === 'object'
111 ) {
112 return { ...schema, type: 'object' }
113 }
114 return { type: 'object', properties: {} }
116​
117/** MCP `tools/call` result shape. */
118export interface ToolCallResult {
119 content: Array<{ type: 'text'; text: string }>
120 isError?: boolean
122​
123/**
124 * Transport-agnostic bridge logic: list tools, and dispatch a tool/permission
125 * call. No sockets, no auth — a transport ({@link startHostToolBridge} or a
126 * `fetch` handler) wraps this and owns I/O + the bearer check.
127 */
128export interface ToolBridgeCore {
129 listTools: () => Array<ToolDescriptor>
130 callTool: (name: string, args: unknown) => Promise<ToolCallResult>
132​
133/**
134 * Build the transport-agnostic bridge core for the given tools. Throws if a
135 * tool has `needsApproval`: the bridge runs tools out-of-band and cannot pause
136 * the run for an approval round-trip.
137 */
138export function createToolBridgeCore(
139 tools: Array<AnyTool>,
140 options: ToolBridgeCoreOptions,
141): ToolBridgeCore {
142 const gated = tools.find((tool) => tool.needsApproval)
143 if (gated) {
144 throw new Error(
145 `Tool "${gated.name}" has needsApproval, which harness adapters do not support. Remove needsApproval or use an HTTP adapter.`,
146 )
147 }
148 const toolsByName = new Map(tools.map((tool) => [tool.name, tool]))
149 const permission = options.permission
150​
151 const permissionDescriptor: ToolDescriptor | undefined = permission
152 ? {
153 name: permission.toolName,
154 description:
155 'Permission prompt: returns {behavior:"allow"|"deny"} for a requested action.',
156 inputSchema: { type: 'object', properties: {} },
157 }
158 : undefined
159​
160 return {
161 listTools() {
162 return [
163 ...tools.map((tool) => ({
164 name: tool.name,
165 description: tool.description,
166 inputSchema: toObjectSchema(tool.inputSchema),
167 })),
168 ...(permissionDescriptor ? [permissionDescriptor] : []),
169 ]
170 },
171​
172 async callTool(name, args) {
173 if (permission && name === permission.toolName) {
174 const result = await permission.resolve(args ?? {})
175 return { content: [{ type: 'text', text: JSON.stringify(result) }] }
176 }
177 const tool = toolsByName.get(name)
178 if (!tool?.execute) throw new Error(`Unknown tool: ${name}`)
179 try {
180 const result: unknown = await tool.execute(args ?? {}, {
181 threadId: options.threadId,
182 context: options.context,
183 abortSignal: options.signal,
184 // No-op default so tools that always call it (e.g. code mode) don't
185 // crash when the transport didn't wire a sink.
186 emitCustomEvent: options.emitCustomEvent ?? (() => {}),
187 })
188 const text =
189 typeof result === 'string' ? result : JSON.stringify(result)
190 return { content: [{ type: 'text', text }] }
191 } catch (error) {
192 const message = error instanceof Error ? error.message : String(error)
193 return {
194 isError: true,
195 content: [
196 { type: 'text', text: `Tool execution failed: ${message}` },
197 ],
198 }
199 }
200 },
201 }
203​
204/**
205 * Minimal JSON-RPC dispatcher over a {@link ToolBridgeCore}, so a `fetch`-based
206 * transport (Worker / Durable Object) can serve MCP `initialize` / `tools/list`
207 * / `tools/call` without the node-specific HTTP transport. Returns the JSON-RPC
208 * response object, or `null` for a notification (no `id`).
209 */
210export async function handleBridgeJsonRpc(
211 core: ToolBridgeCore,
212 message: unknown,
213): Promise<unknown> {
214 if (message === null || typeof message !== 'object') {
215 return {
216 jsonrpc: '2.0',
217 id: null,
218 error: { code: -32600, message: 'Invalid Request' },
219 }
220 }
221 const rpc = message as { id?: unknown; method?: unknown; params?: unknown }
222 const id = rpc.id ?? null
223 const respond = (result: unknown): unknown => ({ jsonrpc: '2.0', id, result })
224 switch (rpc.method) {
225 case 'initialize':
226 return respond({
227 protocolVersion: '2024-11-05',
228 capabilities: { tools: {} },
229 serverInfo: { name: BRIDGED_MCP_SERVER_NAME, version: '1.0.0' },
230 })
231 case 'notifications/initialized':
232 return null
233 case 'tools/list':
234 return respond({ tools: core.listTools() })
235 case 'tools/call': {
236 const params = (rpc.params ?? {}) as {
237 name?: unknown
238 arguments?: unknown
239 }
240 if (typeof params.name !== 'string') {
241 return {
242 jsonrpc: '2.0',
243 id,
244 error: { code: -32602, message: 'Invalid params: name' },
245 }
246 }
247 return respond(await core.callTool(params.name, params.arguments ?? {}))
248 }
249 default:
250 return {
251 jsonrpc: '2.0',
252 id,
253 error: { code: -32601, message: 'Method not found' },
254 }
255 }
257​
258/**
259 * Constant-time check of an `Authorization: Bearer <token>` header against the
260 * expected token. Length mismatch returns false early (token length is not
261 * secret); equal-length comparison is timing-safe.
262 */
263export function timingSafeBearerEqual(
264 header: string | undefined,
265 token: string,
266): boolean {
267 if (header === undefined) return false
268 const a = Buffer.from(header)
269 const b = Buffer.from(`Bearer ${token}`)
270 if (a.length !== b.length) return false
271 return timingSafeEqual(a, b)
273​
274export interface HostToolBridge {
275 /** MCP server name; tools appear to the agent as `mcp__<name>__<tool>`. */
276 name: string
277 /** URL the SANDBOX uses to reach this bridge. */
278 url: string
279 /** Per-run bearer token gating the endpoint. */
280 token: string
281 close: () => Promise<void>
283​
284export interface StartBridgeOptions extends ToolBridgeCoreOptions {
285 /** Hostname the sandbox uses to reach the host (e.g. `host.docker.internal`). */
286 hostForSandbox: string
287 /**
288 * Address to bind the listener to. Defaults to `127.0.0.1` (loopback) and is
289 * widened to `0.0.0.0` only when the sandbox reaches the host via
290 * `host.docker.internal` (a container can't reach the host's loopback).
291 */
292 bindAddress?: string
294​
295function buildMcpServer(core: ToolBridgeCore): McpServer {
296 const server = new McpServer(
297 { name: BRIDGED_MCP_SERVER_NAME, version: '1.0.0' },
298 { capabilities: { tools: {} } },
299 )
300 server.server.setRequestHandler(ListToolsRequestSchema, () => ({
301 tools: core.listTools(),
302 }))
303 server.server.setRequestHandler(CallToolRequestSchema, async (request) => {
304 const result = await core.callTool(
305 request.params.name,
306 request.params.arguments ?? {},
307 )
308 return {
309 content: result.content,
310 ...(result.isError ? { isError: true } : {}),
311 }
312 })
313 return server
315​
316/**
317 * Start the `node:http` MCP tool-proxy bridge for the given tools. For a
318 * long-running host (laptop / CI / Docker orchestrator). Serverless/edge
319 * orchestrators serve {@link createToolBridgeCore} from their own `fetch`
320 * handler instead.
321 */
322export async function startHostToolBridge(
323 tools: Array<AnyTool>,
324 options: StartBridgeOptions,
325): Promise<HostToolBridge> {
326 const token = randomBytes(24).toString('hex')
327 const core = createToolBridgeCore(tools, options)
328 // Loopback by default; widen to all interfaces only for the Docker bridge,
329 // which a container reaches via host.docker.internal (host gateway).
330 const bindAddress =
331 options.bindAddress ??
332 (options.hostForSandbox === 'host.docker.internal'
333 ? '0.0.0.0'
334 : '127.0.0.1')
335​
336 const httpServer = createServer((req, res) => {
337 void (async () => {
338 if (!timingSafeBearerEqual(req.headers['authorization'], token)) {
339 res.writeHead(401).end('unauthorized')
340 return
341 }
342 const server = buildMcpServer(core)
343 const transport = new StreamableHTTPServerTransport({
344 sessionIdGenerator: undefined,
345 })
346 res.on('close', () => {
347 void transport.close()
348 void server.close()
349 })
350 await server.connect(transport)
351​
352 let body = ''
353 for await (const chunk of req) body += chunk
354 let parsed: unknown
355 try {
356 parsed = body ? JSON.parse(body) : undefined
357 } catch {
358 // Malformed agent request → 400, distinct from an internal 500.
359 if (!res.headersSent) res.writeHead(400).end('invalid JSON body')
360 return
361 }
362 await transport.handleRequest(req, res, parsed)
363 })().catch((error: unknown) => {
364 // Log the underlying fault — on the host/Docker path there is no run-log
365 // capturing it, so swallowing it leaves an operator with nothing.
366 console.error('[tool-bridge] request handler failed:', error)
367 if (!res.headersSent) res.writeHead(500).end('bridge error')
368 })
369 })
370​
371 await once(httpServer.listen(0, bindAddress), 'listening')
372 const port = (httpServer.address() as AddressInfo).port
373 const url = `http://${options.hostForSandbox}:${port}/mcp`
374​
375 return {
376 name: BRIDGED_MCP_SERVER_NAME,
377 url,
378 token,
379 close: () => {
380 const closed = new Promise<void>((resolve) =>
381 httpServer.close(() => resolve()),
382 )
383 // `close()` alone waits for every open connection. An agent that keeps
384 // a request or a keep-alive socket open would hold the run's teardown.
385 httpServer.closeAllConnections()
386 return closed
387 },
388 }
390​
391/** A provisioned, reachable bridge endpoint (same shape as {@link HostToolBridge}). */
392export type ProvisionedBridge = HostToolBridge
393​
394export interface ToolBridgeProvisionOptions extends ToolBridgeCoreOptions {
395 /** Sandbox provider name, to derive how the sandbox reaches the bridge. */
396 provider: string
398​
399/**
400 * Stands up the tool-bridge endpoint for a run. The seam that makes the bridge
401 * portable across runtimes: a harness adapter asks its capability context for a
402 * provisioner and uses {@link nodeHttpBridgeProvisioner} as the default (host /
403 * Docker). A serverless/edge orchestrator PROVIDES its own — e.g. a Durable
404 * Object that mounts {@link createToolBridgeCore} / {@link handleBridgeJsonRpc}
405 * on its `fetch` handler and returns a sandbox-reachable URL — so no raw TCP
406 * listener is needed.
407 */
408export interface ToolBridgeProvisioner {
409 provision: (
410 tools: Array<AnyTool>,
411 options: ToolBridgeProvisionOptions,
412 ) => Promise<ProvisionedBridge>
414​
415/** Default provisioner: a `node:http` listener on the host. */
416export const nodeHttpBridgeProvisioner: ToolBridgeProvisioner = {
417 provision(tools, options) {
418 const { provider, ...core } = options
419 return startHostToolBridge(tools, {
420 hostForSandbox: hostForSandbox(provider),
421 ...core,
422 })
423 },