Open History to see the last commit
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)
14}
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
31}
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>
82}
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
87}
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
106}
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 toolName?: McpServerDescriptor['toolName']
134 requestOptions?: McpServerDescriptor['requestOptions']
135 }) => {
136 const descriptor: McpServerDescriptor = {
137 transport: info.transport,
138 prefix: info.prefix,
139 ...(info.clientOptions ? { clientOptions: info.clientOptions } : {}),
140 ...(info.toolFilter ? { toolFilter: info.toolFilter } : {}),
141 ...(info.needsApproval ? { needsApproval: info.needsApproval } : {}),
142 ...(info.toolName ? { toolName: info.toolName } : {}),
143 ...(info.requestOptions ? { requestOptions: info.requestOptions } : {}),
144 }
145 total += 1
146 const key = info.prefix
147 if (key === undefined || key === '') {
148 if (fallback !== null) {
149 throw new Error(
150 'createMcpAppCallHandler: multiple clients without a prefix; serverId routing is ambiguous',
151 )
152 }
153 fallback = descriptor
154 return
155 }
156 if (key in byServerId) {
157 throw new Error(`createMcpAppCallHandler: duplicate serverId "${key}"`)
158 }
159 byServerId[key] = descriptor
160 }
161
162 for (const entry of entries) {
163 if (isPool(entry)) {
164 for (const info of Object.values(entry.getServers())) {
165 add(info)
166 }
167 } else {
168 add(entry.getInfo())
169 }
170 }
171 return { byServerId, fallback, total }
172}
173
174/**
175 * Invoke an optional `onError` hook, absorbing BOTH synchronous and asynchronous
176 * throws from the hook itself. The hook runs inside the promise chain (not as a
177 * bare argument) so a sync `throw` becomes a rejection that `.catch` swallows —
178 * a host's observability callback must never break the handler's result or mask
179 * the real error.
180 */
181function reportError(
182 onError: McpAppCallHandlerOptions['onError'],
183 error: unknown,
184 info: { phase: 'call' | 'close'; req: McpAppCallRequest },
185): Promise<void> {
186 if (!onError) return Promise.resolve()
187 return Promise.resolve()
188 .then(() => onError(error, info))
189 .catch(() => undefined)
190}
191
192/**
193 * Creates a server-side handler that resolves an MCP server descriptor from the
194 * provided client(s), reconnects per-call (stateless/serverless-safe), enforces
195 * a same-server allowlist, and proxies `callTool` to the underlying MCP server.
196 *
197 * Always closes the per-call client in `finally`. Never returns transport config.
198 */
199export function createMcpAppCallHandler(opts: McpAppCallHandlerOptions) {
200 const registry = buildRegistry(opts.clients)
201
202 // Resolve a serverId against the static `clients` registry. When serverId is
203 // undefined and exactly one descriptor is registered, default to that sole
204 // descriptor; with zero or multiple, undefined stays unresolvable.
205 const resolveFromRegistry = (
206 serverId: string | undefined,
207 ): McpServerDescriptor | null => {
208 if (serverId !== undefined) {
209 return registry.byServerId[serverId] ?? null
210 }
211 if (registry.total !== 1) return null
212 return registry.fallback ?? Object.values(registry.byServerId)[0] ?? null
213 }
214
215 return async (
216 req: McpAppCallRequest,
217 ): Promise<{ ok: true; result: unknown } | { ok: false; error: string }> => {
218 // Resolve server descriptor. The store WINS when it has an entry; otherwise
219 // we fall back to the static `clients` registry (the base). A store miss
220 // (null) must not reject when the registry can serve the request.
221 const fromRegistry = resolveFromRegistry(req.serverId)
222 const descriptor =
223 (opts.store ? await opts.store.get(req.threadId, req.serverId) : null) ??
224 fromRegistry
225
226 if (!descriptor) {
227 // serverId omitted but resolution was ambiguous (zero or multiple
228 // servers configured) → clearer message than "Unknown serverId: undefined".
229 const error =
230 req.serverId === undefined
231 ? 'No serverId provided and zero or multiple servers configured; specify serverId'
232 : `Unknown serverId: ${req.serverId}`
233 return { ok: false, error }
234 }
235
236 if (descriptor.transport === undefined) {
237 // Client was built from a raw Transport instance (no reconnectable
238 // descriptor), so there is nothing to reconnect per-call.
239 return {
240 ok: false,
241 error: 'MCP client has no reconnectable transport descriptor',
242 }
243 }
244
245 // A persistent store cannot serialize a function, so a stored descriptor
246 // can come back without `toolFilter`, `needsApproval`, or `toolName`. Fall
247 // back to the options of the same server in `clients`, or a widget could
248 // call a tool the model cannot see, or run one the model can run only
249 // after approval. A stored descriptor can also lack `requestOptions` when
250 // the code that wrote it did not set it. Then the widget call uses the
251 // timeout of the same server in `clients`.
252 const toolFilter = descriptor.toolFilter ?? fromRegistry?.toolFilter
253 const needsApproval =
254 descriptor.needsApproval ?? fromRegistry?.needsApproval
255 const toolName = descriptor.toolName ?? fromRegistry?.toolName
256 const requestOptions =
257 descriptor.requestOptions ?? fromRegistry?.requestOptions
258 const client = await createMCPClient({
259 transport: descriptor.transport,
260 prefix: descriptor.prefix,
261 ...(descriptor.clientOptions
262 ? { clientOptions: descriptor.clientOptions }
263 : {}),
264 ...(toolFilter ? { toolFilter } : {}),
265 ...(needsApproval ? { needsApproval } : {}),
266 ...(toolName ? { toolName } : {}),
267 ...(requestOptions ? { requestOptions } : {}),
268 })
269
270 try {
271 // The widget sends the server-native (UNPREFIXED) tool name
272 // (`UIResourcePart.toolName` is the native name), so we match it directly
273 // against the native names the server exposes — carried on
274 // `metadata.mcp.serverToolName` (falling back to `name` for unprefixed
275 // clients) — and forward `req.toolName` unchanged to `client.callTool`.
276 const exposed: ServerTool | undefined = (await client.tools()).find(
277 (t) => serverToolNameOf(t) === req.toolName,
278 )
279 const customOk = opts.allowTool ? await opts.allowTool(req) : true
280
281 if (!exposed || !customOk) {
282 return { ok: false, error: `Tool not allowed: ${req.toolName}` }
283 }
284 // A widget call has no approval step. `tools()` marks the tools that the
285 // client's `needsApproval` selects, so refuse those here.
286 if (exposed.needsApproval) {
287 return { ok: false, error: `Tool needs approval: ${req.toolName}` }
288 }
289
290 // Reject a malformed args payload (array, primitive, null) rather than
291 // silently coercing it to {} — a bad widget request should fail loudly
292 // instead of executing the tool with defaults. Absent args is valid.
293 const args = req.args === undefined ? {} : req.args
294 if (!isArgsRecord(args)) {
295 return { ok: false, error: 'Invalid args: expected an object' }
296 }
297 const result = await client.callTool(req.toolName, args)
298 return { ok: true, result }
299 } catch (err) {
300 // Surface the failure for server-side observability before flattening it
301 // into the opaque wire error; never let the hook itself break the result.
302 await reportError(opts.onError, err, { phase: 'call', req })
303 return {
304 ok: false,
305 error: err instanceof Error ? err.message : 'MCP call failed',
306 }
307 } finally {
308 // Per-call reconnect handler closes its client every call; a consistently
309 // failing close leaks handles silently. Don't rethrow (it would mask the
310 // real result), but report it through the same hook.
311 await client
312 .close()
313 .catch((err: unknown) =>
314 reportError(opts.onError, err, { phase: 'close', req }),
315 )
316 }
317 }
318}