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

call-handler.ts

306 lines12.5 KB

1import { createMCPClient } from '../client'
2import type { MCPClient } from '../client'
3import type { MCPClients } from '../pool'
4import type {
5 McpAppCallRequest,
6 McpServerDescriptor,
7 McpSessionStore,
8} from './session-store'
9import type { ServerTool } from '@tanstack/ai'
10​
11/** Type guard: a plain (non-array) object usable as a tool-args record. */
12function isArgsRecord(value: unknown): value is Record<string, unknown> {
13 return value !== null && typeof value === 'object' && !Array.isArray(value)
15​
16/**
17 * The UNPREFIXED, server-native tool name for an exposed ServerTool.
18 * ai-mcp stamps it on `metadata.mcp.serverToolName`; the `name` fallback is a
19 * defensive last resort — auto-discovery (`toServerTools`) and the explicit
20 * `tools(defs)` path both always stamp `serverToolName`, so this fallback is
21 * only reached for hand-built ServerTools. `metadata` is
22 * `Record<string, unknown>`, so narrow each hop instead of asserting a shape.
23 */
24function serverToolNameOf(tool: ServerTool): string {
25 const mcp = tool.metadata?.mcp
26 if (mcp !== null && typeof mcp === 'object' && 'serverToolName' in mcp) {
27 const native: unknown = mcp.serverToolName
28 if (typeof native === 'string') return native
29 }
30 return tool.name
32​
33/**
34 * A single MCP client or a pool of clients (or an array of either). These are
35 * the same client/pool instances created with `createMCPClient` /
36 * `createMCPClients` and passed to `chat({ mcp: { clients: [...] } })`. The
37 * handler reads each client's connection descriptor via `getInfo()` /
38 * `getServers()` so it can reconnect per-call without a separate config map.
39 */
40export type McpAppClientsInput =
41 | MCPClient
42 | MCPClients
43 | Array<MCPClient | MCPClients>
44​
45export interface McpAppCallHandlerOptions {
46 /**
47 * The MCP client(s) to serve widget tool calls for — the same instances you
48 * pass to `chat({ mcp: { clients } })`. Accepts a single client, a pool, or
49 * an array of either. The handler reads each one's connection descriptor and
50 * reconnects per-call (stateless/serverless-safe).
51 */
52 clients: McpAppClientsInput
53 /**
54 * Opt-in dynamic/stateful resolution (e.g. inMemoryMcpSessionStore). When
55 * provided, the store WINS for any thread+serverId it has an entry for; on a
56 * store miss (null) the handler falls back to the static `clients` registry.
57 * So `clients` is always the base and the store is an override on top.
58 */
59 store?: McpSessionStore
60 /**
61 * Additional per-call authorizer. The server-exposure check is ALWAYS
62 * enforced first (any tool the server does not expose is rejected). When
63 * `allowTool` is provided, a request must satisfy BOTH — it is AND-ed on
64 * top of the server-exposure check, not a replacement for it.
65 */
66 allowTool?: (req: McpAppCallRequest) => boolean | Promise<boolean>
67 /**
68 * Optional server-side observability hook. The handler is otherwise opaque on
69 * failure — it returns a fail-soft `{ ok: false, error }` to the (untrusted)
70 * widget and logs nothing, so on a serverless backend there is no trace of
71 * WHY a proxied call failed. `onError` is invoked (and awaited if async) with
72 * the caught error and the originating request before that result is
73 * returned. `phase` distinguishes a `'call'` failure (connect/exposure
74 * lookup/execution/serialization) from a `'close'` failure (per-call client
75 * cleanup, which is swallowed and never affects the result). This library
76 * never writes to `console`; wire your logger here to capture failures.
77 */
78 onError?: (
79 error: unknown,
80 info: { phase: 'call' | 'close'; req: McpAppCallRequest },
81 ) => void | Promise<void>
83​
84/** Structurally distinguish a pool (has getServers) from a single client. */
85function isPool(entry: MCPClient | MCPClients): entry is MCPClients {
86 return 'getServers' in entry
88​
89/**
90 * The flattened view of the `clients` input used to resolve a `serverId` to a
91 * descriptor.
92 *
93 * - `byServerId` keys every addressable descriptor by its `prefix` — the exact
94 * value the widget sends as `serverId` (the client/pool stamps it on
95 * `metadata.mcp.serverId`, which equals `prefix`).
96 * - `fallback` holds the single descriptor that has no addressable prefix
97 * (undefined/empty). It is reachable ONLY via the sole-server default path
98 * (serverId omitted + exactly one descriptor in total).
99 * - `total` is the count of all descriptors across both, used to decide the
100 * sole-server default.
101 */
102interface AppRegistry {
103 byServerId: Record<string, McpServerDescriptor>
104 fallback: McpServerDescriptor | null
105 total: number
107​
108/**
109 * Flatten the `clients` input into a registry keyed UNIFORMLY by `prefix` (the
110 * value the widget sends as `serverId`). A pool contributes one entry per
111 * configured server (keyed by that server's `prefix`, NOT its config key); a
112 * single client is keyed by `getInfo().prefix`. Entries whose `prefix` is
113 * undefined/empty have no addressable serverId and go in the `fallback` slot
114 * (reachable only by the sole-server default).
115 *
116 * Throws at handler-construction time if two entries resolve to the same
117 * non-empty prefix, or if more than one entry has an undefined/empty prefix —
118 * either case makes `serverId` routing ambiguous, so it must not silently
119 * overwrite.
120 */
121function buildRegistry(clients: McpAppClientsInput): AppRegistry {
122 const entries = Array.isArray(clients) ? clients : [clients]
123 const byServerId: Record<string, McpServerDescriptor> = {}
124 let fallback: McpServerDescriptor | null = null
125 let total = 0
126​
127 const add = (info: {
128 transport: McpServerDescriptor['transport']
129 prefix: string | undefined
130 clientOptions?: McpServerDescriptor['clientOptions']
131 toolFilter?: McpServerDescriptor['toolFilter']
132 needsApproval?: McpServerDescriptor['needsApproval']
133 }) => {
134 const descriptor: McpServerDescriptor = {
135 transport: info.transport,
136 prefix: info.prefix,
137 ...(info.clientOptions ? { clientOptions: info.clientOptions } : {}),
138 ...(info.toolFilter ? { toolFilter: info.toolFilter } : {}),
139 ...(info.needsApproval ? { needsApproval: info.needsApproval } : {}),
140 }
141 total += 1
142 const key = info.prefix
143 if (key === undefined || key === '') {
144 if (fallback !== null) {
145 throw new Error(
146 'createMcpAppCallHandler: multiple clients without a prefix; serverId routing is ambiguous',
147 )
148 }
149 fallback = descriptor
150 return
151 }
152 if (key in byServerId) {
153 throw new Error(`createMcpAppCallHandler: duplicate serverId "${key}"`)
154 }
155 byServerId[key] = descriptor
156 }
157​
158 for (const entry of entries) {
159 if (isPool(entry)) {
160 for (const info of Object.values(entry.getServers())) {
161 add(info)
162 }
163 } else {
164 add(entry.getInfo())
165 }
166 }
167 return { byServerId, fallback, total }
169​
170/**
171 * Invoke an optional `onError` hook, absorbing BOTH synchronous and asynchronous
172 * throws from the hook itself. The hook runs inside the promise chain (not as a
173 * bare argument) so a sync `throw` becomes a rejection that `.catch` swallows —
174 * a host's observability callback must never break the handler's result or mask
175 * the real error.
176 */
177function reportError(
178 onError: McpAppCallHandlerOptions['onError'],
179 error: unknown,
180 info: { phase: 'call' | 'close'; req: McpAppCallRequest },
181): Promise<void> {
182 if (!onError) return Promise.resolve()
183 return Promise.resolve()
184 .then(() => onError(error, info))
185 .catch(() => undefined)
187​
188/**
189 * Creates a server-side handler that resolves an MCP server descriptor from the
190 * provided client(s), reconnects per-call (stateless/serverless-safe), enforces
191 * a same-server allowlist, and proxies `callTool` to the underlying MCP server.
192 *
193 * Always closes the per-call client in `finally`. Never returns transport config.
194 */
195export function createMcpAppCallHandler(opts: McpAppCallHandlerOptions) {
196 const registry = buildRegistry(opts.clients)
197​
198 // Resolve a serverId against the static `clients` registry. When serverId is
199 // undefined and exactly one descriptor is registered, default to that sole
200 // descriptor; with zero or multiple, undefined stays unresolvable.
201 const resolveFromRegistry = (
202 serverId: string | undefined,
203 ): McpServerDescriptor | null => {
204 if (serverId !== undefined) {
205 return registry.byServerId[serverId] ?? null
206 }
207 if (registry.total !== 1) return null
208 return registry.fallback ?? Object.values(registry.byServerId)[0] ?? null
209 }
210​
211 return async (
212 req: McpAppCallRequest,
213 ): Promise<{ ok: true; result: unknown } | { ok: false; error: string }> => {
214 // Resolve server descriptor. The store WINS when it has an entry; otherwise
215 // we fall back to the static `clients` registry (the base). A store miss
216 // (null) must not reject when the registry can serve the request.
217 const fromRegistry = resolveFromRegistry(req.serverId)
218 const descriptor =
219 (opts.store ? await opts.store.get(req.threadId, req.serverId) : null) ??
220 fromRegistry
221​
222 if (!descriptor) {
223 // serverId omitted but resolution was ambiguous (zero or multiple
224 // servers configured) → clearer message than "Unknown serverId: undefined".
225 const error =
226 req.serverId === undefined
227 ? 'No serverId provided and zero or multiple servers configured; specify serverId'
228 : `Unknown serverId: ${req.serverId}`
229 return { ok: false, error }
230 }
231​
232 if (descriptor.transport === undefined) {
233 // Client was built from a raw Transport instance (no reconnectable
234 // descriptor), so there is nothing to reconnect per-call.
235 return {
236 ok: false,
237 error: 'MCP client has no reconnectable transport descriptor',
238 }
239 }
240​
241 // A persistent store cannot serialize a function, so a stored descriptor
242 // can come back without `toolFilter` or `needsApproval`. Fall back to the
243 // policy of the same server in `clients`, or a widget could call a tool the
244 // model cannot see, or run one the model can run only after approval.
245 const toolFilter = descriptor.toolFilter ?? fromRegistry?.toolFilter
246 const needsApproval =
247 descriptor.needsApproval ?? fromRegistry?.needsApproval
248 const client = await createMCPClient({
249 transport: descriptor.transport,
250 prefix: descriptor.prefix,
251 ...(descriptor.clientOptions
252 ? { clientOptions: descriptor.clientOptions }
253 : {}),
254 ...(toolFilter ? { toolFilter } : {}),
255 ...(needsApproval ? { needsApproval } : {}),
256 })
257​
258 try {
259 // The widget sends the server-native (UNPREFIXED) tool name
260 // (`UIResourcePart.toolName` is the native name), so we match it directly
261 // against the native names the server exposes — carried on
262 // `metadata.mcp.serverToolName` (falling back to `name` for unprefixed
263 // clients) — and forward `req.toolName` unchanged to `client.callTool`.
264 const exposed: ServerTool | undefined = (await client.tools()).find(
265 (t) => serverToolNameOf(t) === req.toolName,
266 )
267 const customOk = opts.allowTool ? await opts.allowTool(req) : true
268​
269 if (!exposed || !customOk) {
270 return { ok: false, error: `Tool not allowed: ${req.toolName}` }
271 }
272 // A widget call has no approval step. `tools()` marks the tools that the
273 // client's `needsApproval` selects, so refuse those here.
274 if (exposed.needsApproval) {
275 return { ok: false, error: `Tool needs approval: ${req.toolName}` }
276 }
277​
278 // Reject a malformed args payload (array, primitive, null) rather than
279 // silently coercing it to {} — a bad widget request should fail loudly
280 // instead of executing the tool with defaults. Absent args is valid.
281 const args = req.args === undefined ? {} : req.args
282 if (!isArgsRecord(args)) {
283 return { ok: false, error: 'Invalid args: expected an object' }
284 }
285 const result = await client.callTool(req.toolName, args)
286 return { ok: true, result }
287 } catch (err) {
288 // Surface the failure for server-side observability before flattening it
289 // into the opaque wire error; never let the hook itself break the result.
290 await reportError(opts.onError, err, { phase: 'call', req })
291 return {
292 ok: false,
293 error: err instanceof Error ? err.message : 'MCP call failed',
294 }
295 } finally {
296 // Per-call reconnect handler closes its client every call; a consistently
297 // failing close leaks handles silently. Don't rethrow (it would mask the
298 // real result), but report it through the same hook.
299 await client
300 .close()
301 .catch((err: unknown) =>
302 reportError(opts.onError, err, { phase: 'close', req }),
303 )
304 }
305 }