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

tools.ts

729 lines21.8 KB

1import {
2 DEFAULT_REQUEST_TIMEOUT_MSEC,
3 ProtocolError,
4 ProtocolErrorCode,
5 SdkError,
6 SdkErrorCode,
7 isCallToolResult,
8 isInputRequiredResult,
9} from '@modelcontextprotocol/client'
10import type {
11 Client,
12 Request,
13 TaskStatus,
14 Tool as McpToolDef,
15 ToolAnnotations,
16 Transport,
17} from '@modelcontextprotocol/client'
18import type {
19 AnyServerTool,
20 ContentPart,
21 ToolInputResponse,
22} from '@tanstack/ai'
23import {
24 isMCPInputRequiredError,
25 MCPInputRequiredError,
26} from './input-required'
27import type { McpServerTool, McpToolMetadata } from './types'
28​
29interface ConvertOptions {
30 prefix?: string
31 lazy?: boolean
32 needsApproval?: (tool: McpToolDef) => boolean
34​
35/** Reads the MCP Apps `_meta.ui.resourceUri` link from a tool def, if present. */
36export function extractUiResourceUri(def: McpToolDef): string | undefined {
37 const meta = def._meta
38 if (!isRecord(meta)) return undefined
39 const ui = meta.ui
40 if (!isRecord(ui)) return undefined
41 return typeof ui.resourceUri === 'string' ? ui.resourceUri : undefined
43​
44/**
45 * The human-readable display name for a tool, following the MCP spec's
46 * precedence: the top-level `title` field wins, then the legacy
47 * `annotations.title`, and finally the programmatic `name`.
48 */
49function toolDisplayTitle(def: McpToolDef): string {
50 return def.title ?? def.annotations?.title ?? def.name
52​
53/**
54 * Build the `metadata.mcp` block stamped onto every discovered/bound tool.
55 * Shared by auto-discovery (`toServerTools`) and the explicit `tools(defs)`
56 * path in `client.ts` so the two cannot drift.
57 *
58 * `annotations` is the server's own object, forwarded verbatim. Per the MCP
59 * spec its fields (including `title`) are **hints** — a host may use them for
60 * display or to shape an approval UI, but never as a security boundary.
61 *
62 * Fields the server didn't declare are OMITTED rather than set to `undefined`:
63 * the explicit path merges this over any `mcp` block the caller already put on
64 * their tool definition, and an `undefined` value would blank out what they set.
65 */
66export function toolMcpMetadata(
67 def: McpToolDef,
68 serverId: string | undefined,
69): McpToolMetadata {
70 const uiResourceUri = extractUiResourceUri(def)
71 const annotations: ToolAnnotations | undefined = def.annotations
72 return {
73 serverToolName: def.name,
74 serverId,
75 title: toolDisplayTitle(def),
76 ...(uiResourceUri !== undefined ? { uiResourceUri } : {}),
77 ...(annotations !== undefined ? { annotations } : {}),
78 }
80​
81export function mcpContentToTanstack(
82 content: unknown,
83): string | Array<ContentPart> {
84 // A valid MCP result may carry only structuredContent (no content[]) → guard
85 // against undefined/non-array before reading length/map.
86 if (!Array.isArray(content)) return ''
87 // Single text block → plain string (most common, best for the model).
88 if (content.length === 1 && content[0]?.type === 'text')
89 return content[0].text
90 const parts = content
91 .map((c): ContentPart => {
92 switch (c.type) {
93 case 'text':
94 return { type: 'text', content: c.text }
95 case 'image':
96 return {
97 type: 'image',
98 source: { type: 'data', value: c.data, mimeType: c.mimeType },
99 }
100 case 'resource': {
101 const uri = c.resource?.uri
102 if (typeof uri === 'string' && uri.startsWith('ui://')) {
103 // ui:// resources are surfaced via readResource (MCP Apps); omit from model text.
104 return { type: 'text', content: '' }
105 }
106 return { type: 'text', content: JSON.stringify(c.resource) }
107 }
108 default:
109 return { type: 'text', content: JSON.stringify(c) }
110 }
111 })
112 .filter((p) => !(p.type === 'text' && p.content === ''))
113 return parts.length ? parts : ''
115​
116/**
117 * Calls one MCP tool and returns the tool result.
118 *
119 * A spec 2025 task waits on `tasks/get`, then reads `tasks/result`.
120 * Spec 2026-07-28 has no tasks, so a 2026 call returns the tool result.
121 * `chat()` receives the tool result after the task ends.
122 *
123 * `signal` stops the wait. This function then sends `tasks/cancel`.
124 * It does not wait for that cancel request.
125 *
126 * If the tool result asks for input, this function throws
127 * {@link MCPInputRequiredError}.
128 * `kind` is `form` for user input, or `sampling` for a model request.
129 * `request` is the input request body.
130 * This function does not catch that error.
131 *
132 * On spec 2026, pass `inputResponse` to answer an input request.
133 * The call gets the request again, then sends the answer at once
134 * with `inputResponses` and the server's `requestState`.
135 * If the server asks for input again after that answer, this throws an Error.
136 *
137 * @param client - Connected MCP client
138 * @param mcpName - Server tool name
139 * @param args - Tool arguments
140 * @param taskRequired - True when the tool requires a spec 2025 task
141 * @param signal - Stops the wait when the caller aborts
142 * @param inputResponse - The user's answer from an `mcp_input` interrupt
143 */
144export async function callMcpTool(
145 client: Client,
146 mcpName: string,
147 args: Record<string, unknown>,
148 taskRequired: boolean,
149 signal?: AbortSignal,
150 inputResponse?: ToolInputResponse,
151) {
152 signal?.throwIfAborted()
153 const isModern = client.getProtocolEra() === 'modern'
154 if (!taskRequired && !isModern) {
155 const result = await client.callTool(
156 { name: mcpName, arguments: args },
157 { signal, allowInputRequired: true },
158 )
159 throwIfInputRequired(result)
160 return result
161 }
162​
163 const params = { name: mcpName, arguments: args }
164 let raw = isModern
165 ? await rawRequest(client, 'tools/call', params, signal)
166 : await sdkRequest(
167 client,
168 'tools/call',
169 { name: mcpName, arguments: args, task: {} },
170 signal,
171 )
172 // ponytail: the answer is sent on the second call, so the server state never
173 // travels through the browser. The cost is one extra tools/call.
174 if (isModern && inputResponse !== undefined && isInputRequiredResult(raw)) {
175 raw = await rawRequest(
176 client,
177 'tools/call',
178 { ...params, ...retryParams(raw, inputResponse) },
179 signal,
180 )
181 // ponytail: one input round per call. The next resume starts with no
182 // requestState, so a second pause would ask round 1 again forever.
183 // Carry requestState through the interrupt if servers need more rounds.
184 if (isInputRequiredResult(raw)) {
185 throw new Error(
186 `The MCP tool "${mcpName}" asked for input a second time. ` +
187 'This client answers one input request per tool call.',
188 )
189 }
190 }
191 return finishToolCall(client, mcpName, raw, signal)
193​
194// Answers only the first input request. That is the one the interrupt shows.
195function retryParams(
196 result: { inputRequests?: unknown; requestState?: string },
197 response: ToolInputResponse,
198) {
199 const requests = isRecord(result.inputRequests) ? result.inputRequests : {}
200 const key = Object.keys(requests)[0]
201 const entry = key === undefined ? undefined : requests[key]
202 const method = isRecord(entry) ? entry.method : undefined
203 const requestState =
204 result.requestState === undefined
205 ? {}
206 : { requestState: result.requestState }
207 if (key === undefined) return requestState
208 return {
209 inputResponses: { [key]: inputAnswer(method, response) },
210 ...requestState,
211 }
213​
214function inputAnswer(method: unknown, response: ToolInputResponse) {
215 if (method === 'sampling/createMessage') {
216 if (response.status === 'cancelled') {
217 throw new Error('The user cancelled the MCP sampling request.')
218 }
219 const payload = response.payload
220 if (typeof payload !== 'string') return payload
221 return {
222 role: 'assistant',
223 content: { type: 'text', text: payload },
224 model: 'user',
225 }
226 }
227 if (response.status === 'cancelled') return { action: 'cancel' }
228 const payload = response.payload
229 // An ElicitResult passes as is. Any other value is the accepted content.
230 if (isRecord(payload) && typeof payload.action === 'string') return payload
231 return { action: 'accept', content: payload }
233​
234const schemaSlot: unknown = undefined
235​
236const passThroughResult = {
237 '~standard': {
238 version: 1 as const,
239 vendor: 'tanstack-ai-mcp',
240 types: {
241 input: schemaSlot,
242 output: schemaSlot,
243 },
244 validate(value: unknown) {
245 return { value }
246 },
247 },
249​
250/** The spec 2025-11-25 task fields this client reads. */
251type TaskState = {
252 taskId: string
253 status: TaskStatus
254 pollInterval: number | undefined
255 statusMessage: string | undefined
257​
258const defaultPollMs = 1000
259​
260let rawRequestId = 0
261​
262const transportTaps = new WeakMap<
263 Transport,
264 Set<(message: unknown) => boolean>
265>()
266​
267async function finishToolCall(
268 client: Client,
269 mcpName: string,
270 raw: unknown,
271 signal?: AbortSignal,
272) {
273 throwIfInputRequired(raw)
274 // A spec 2025 task body also carries `content`. Read the task first.
275 const task = readNestedTask(raw)
276 if (task !== undefined) {
277 return pollTask(client, mcpName, task, signal)
278 }
279 if (isCallToolResult(raw)) return raw
280 throw missingTaskResult(mcpName)
282​
283async function pollTask(
284 client: Client,
285 mcpName: string,
286 task: TaskState,
287 signal?: AbortSignal,
288) {
289 let current = task
290 try {
291 while (
292 current.status === 'working' ||
293 current.status === 'input_required'
294 ) {
295 if (current.status === 'input_required') {
296 // A spec 2025 task sends its input request on tasks/result, as a
297 // request to the client. This client does not answer those requests,
298 // so stop here. Polling again would never end.
299 void cancelTask(client, current.taskId)
300 throw new Error(
301 `MCP task "${current.taskId}" needs input. This client cannot answer a spec 2025 task input request.`,
302 )
303 }
304 const delay = current.pollInterval ?? defaultPollMs
305 await waitForPoll(delay, signal)
306 current = await readPolledTask(client, current.taskId, mcpName, signal)
307 }
308 } catch (error) {
309 if (isMCPInputRequiredError(error)) throw error
310 if (signal?.aborted) {
311 void cancelTask(client, task.taskId)
312 throw abortReason(signal)
313 }
314 throw error
315 }
316​
317 switch (current.status) {
318 case 'completed':
319 return taskResult(client, mcpName, current.taskId, signal)
320 case 'failed':
321 case 'cancelled':
322 throw terminalTaskError(current)
323 default: {
324 const unexpected: never = current.status
325 throw new Error(`Unknown MCP task status: ${String(unexpected)}`)
326 }
327 }
329​
330async function taskResult(
331 client: Client,
332 mcpName: string,
333 taskId: string,
334 signal?: AbortSignal,
335) {
336 const result = await taskRequest(client, 'tasks/result', { taskId }, signal)
337 throwIfInputRequired(result)
338 if (!isCallToolResult(result)) throw missingTaskResult(mcpName)
339 return result
341​
342async function readPolledTask(
343 client: Client,
344 taskId: string,
345 mcpName: string,
346 signal?: AbortSignal,
347) {
348 const body = await taskRequest(client, 'tasks/get', { taskId }, signal)
349 throwIfInputRequired(body)
350 const task = readTaskState(body)
351 if (task === undefined) throw missingTaskResult(mcpName)
352 return task
354​
355function taskRequest(
356 client: Client,
357 method: string,
358 params: Record<string, unknown>,
359 signal?: AbortSignal,
360) {
361 return sdkRequest(client, method, params, signal)
363​
364async function sdkRequest(
365 client: Client,
366 method: string,
367 params: Record<string, unknown>,
368 signal?: AbortSignal,
369) {
370 signal?.throwIfAborted()
371 const rpc: Request = { method, params }
372 try {
373 return await client.request(
374 rpc,
375 passThroughResult,
376 signal === undefined ? undefined : { signal },
377 )
378 } catch (error) {
379 if (signal?.aborted) throw abortReason(signal)
380 throw error
381 }
383​
384function rawRequest(
385 client: Client,
386 method: string,
387 params: Record<string, unknown>,
388 signal?: AbortSignal,
389) {
390 signal?.throwIfAborted()
391 const transport = client.transport
392 if (transport === undefined) {
393 throw new Error('The MCP client is not connected.')
394 }
395 rawRequestId += 1
396 const id = `tanstack-ai-mcp:${rawRequestId}`
397 const listeners = tapTransport(transport)
398 const body = withEnvelope(params, readEnvelope(client))
399 return new Promise<unknown>((resolve, reject) => {
400 let settled = false
401 // Same limit as an SDK request, so a lost response cannot hang the call.
402 const timer = setTimeout(() => {
403 finish(
404 new SdkError(
405 SdkErrorCode.RequestTimeout,
406 `The MCP request ${method} timed out after ${DEFAULT_REQUEST_TIMEOUT_MSEC} ms.`,
407 ),
408 )
409 }, DEFAULT_REQUEST_TIMEOUT_MSEC)
410 const finish = (error: unknown, result?: unknown) => {
411 if (settled) return
412 settled = true
413 clearTimeout(timer)
414 listeners.delete(accept)
415 if (signal !== undefined) {
416 signal.removeEventListener('abort', onAbort)
417 }
418 if (error !== undefined) {
419 reject(error)
420 return
421 }
422 resolve(result)
423 }
424 const accept = (message: unknown) => {
425 if (!isRecord(message) || message.id !== id) return false
426 if (isRecord(message.error)) {
427 const { code, message: text, data } = message.error
428 finish(
429 new ProtocolError(
430 typeof code === 'number' ? code : ProtocolErrorCode.InternalError,
431 typeof text === 'string' ? text : 'The MCP request failed.',
432 data,
433 ),
434 )
435 return true
436 }
437 finish(undefined, message.result)
438 return true
439 }
440 const activeSignal = signal
441 const onAbort = () => {
442 if (activeSignal === undefined) return
443 finish(abortReason(activeSignal))
444 }
445 listeners.add(accept)
446 if (activeSignal !== undefined) {
447 activeSignal.addEventListener('abort', onAbort, { once: true })
448 }
449 void transport
450 .send({
451 jsonrpc: '2.0',
452 id,
453 method,
454 params: body,
455 })
456 .catch((error: unknown) => {
457 finish(error)
458 })
459 })
461​
462function tapTransport(transport: Transport) {
463 const existing = transportTaps.get(transport)
464 if (existing !== undefined) return existing
465 const listeners = new Set<(message: unknown) => boolean>()
466 transportTaps.set(transport, listeners)
467 const previous = transport.onmessage
468 transport.onmessage = (message, extra) => {
469 const pending = [...listeners]
470 for (const listener of pending) {
471 if (listener(message)) return
472 }
473 previous?.(message, extra)
474 }
475 return listeners
477​
478function readEnvelope(client: Client) {
479 const value: unknown = client
480 if (!isRecord(value)) return undefined
481 const method = value._outboundMetaEnvelope
482 if (typeof method !== 'function') return undefined
483 const called: unknown = method.call(value)
484 if (!isRecord(called)) return undefined
485 return called
487​
488function withEnvelope(
489 params: Record<string, unknown>,
490 envelope: Record<string, unknown> | undefined,
491) {
492 if (envelope === undefined) return params
493 const meta = isRecord(params._meta) ? params._meta : {}
494 return {
495 ...params,
496 _meta: { ...envelope, ...meta },
497 }
499​
500function cancelTask(client: Client, taskId: string) {
501 return taskRequest(client, 'tasks/cancel', { taskId }).catch(() => undefined)
503​
504function throwIfInputRequired(value: unknown) {
505 if (!isRecord(value)) return
506 if (isInputRequiredResult(value)) {
507 throwInputRequired(value.inputRequests, value)
508 }
509 if (value.status !== 'input_required') return
510 if (!hasRequests(value.inputRequests)) return
511 throwInputRequired(value.inputRequests, value)
513​
514function throwInputRequired(requests: unknown, fallback: unknown) {
515 const entry = firstInputRequest(requests)
516 if (entry === undefined) {
517 throw new MCPInputRequiredError('form', fallback)
518 }
519 const body = isRecord(entry.params) ? entry.params : entry
520 if (entry.method === 'sampling/createMessage') {
521 throw new MCPInputRequiredError('sampling', body)
522 }
523 if (entry.method === 'elicitation/create') {
524 throw new MCPInputRequiredError('form', body)
525 }
526 throw new Error(`The MCP server asked for unsupported input: ${entry.method}`)
528​
529function firstInputRequest(requests: unknown) {
530 if (!isRecord(requests)) return undefined
531 const entries = Object.values(requests)
532 for (const entry of entries) {
533 if (!isRecord(entry) || typeof entry.method !== 'string') continue
534 return entry
535 }
536 return undefined
538​
539function hasRequests(requests: unknown) {
540 return isRecord(requests) && Object.keys(requests).length > 0
542​
543function readNestedTask(value: unknown) {
544 if (!isRecord(value)) return undefined
545 return readTaskState(value.task)
547​
548function readTaskState(value: unknown) {
549 if (!isRecord(value)) return undefined
550 if (typeof value.taskId !== 'string' || value.taskId.length === 0) {
551 return undefined
552 }
553 if (!isTaskStatus(value.status)) return undefined
554 const task: TaskState = {
555 taskId: value.taskId,
556 status: value.status,
557 pollInterval:
558 typeof value.pollInterval === 'number' ? value.pollInterval : undefined,
559 statusMessage:
560 typeof value.statusMessage === 'string' ? value.statusMessage : undefined,
561 }
562 return task
564​
565function isTaskStatus(value: unknown): value is TaskStatus {
566 switch (value) {
567 case 'working':
568 case 'input_required':
569 case 'completed':
570 case 'failed':
571 case 'cancelled':
572 return true
573 default:
574 return false
575 }
577​
578function terminalTaskError(task: TaskState) {
579 const detail = task.statusMessage
580 if (detail !== undefined && detail.length > 0) {
581 return new Error(`MCP task "${task.taskId}" ${task.status}: ${detail}`)
582 }
583 return new Error(`MCP task "${task.taskId}" ${task.status}.`)
585​
586function missingTaskResult(mcpName: string) {
587 return new Error(
588 `MCP task-required tool "${mcpName}" ended without a result or error`,
589 )
591​
592function waitForPoll(milliseconds: number, signal?: AbortSignal) {
593 signal?.throwIfAborted()
594 if (milliseconds <= 0) return Promise.resolve()
595 if (signal === undefined) {
596 return new Promise<void>((resolve) => {
597 setTimeout(resolve, milliseconds)
598 })
599 }
600 const active = signal
601 return new Promise<void>((resolve, reject) => {
602 const timer = setTimeout(() => {
603 active.removeEventListener('abort', onAbort)
604 resolve()
605 }, milliseconds)
606 const onAbort = () => {
607 clearTimeout(timer)
608 reject(abortReason(active))
609 }
610 active.addEventListener('abort', onAbort, { once: true })
611 })
613​
614function abortReason(signal: AbortSignal) {
615 return signal.reason instanceof Error
616 ? signal.reason
617 : new DOMException('Aborted', 'AbortError')
619​
620function isRecord(value: unknown): value is Record<string, unknown> {
621 return typeof value === 'object' && value !== null && !Array.isArray(value)
623​
624/**
625 * Build the execute body that proxies a TanStack tool call to an MCP server.
626 * Shared by auto-discovery and the definition path.
627 *
628 * @param preferStructured when true (i.e. the tool declares an outputSchema),
629 * return `result.structuredContent` if present so the existing output
630 * validation in `executeServerTool` validates MCP's typed payload rather than
631 * a JSON-in-text blob. Otherwise normalize `content[]` → string | ContentPart[].
632 */
633export function makeMcpExecute(
634 client: Client,
635 mcpName: string,
636 preferStructured: boolean,
637 taskRequired = false,
638) {
639 return async (
640 args: unknown,
641 ctx?: { abortSignal?: AbortSignal; inputResponse?: ToolInputResponse },
642 ) => {
643 const result = await callMcpTool(
644 client,
645 mcpName,
646 isRecord(args) ? args : {},
647 taskRequired,
648 ctx?.abortSignal,
649 ctx?.inputResponse,
650 )
651 if (result.isError) {
652 const text = Array.isArray(result.content)
653 ? mcpContentToTanstack(result.content)
654 : undefined
655 const detail =
656 typeof text === 'string'
657 ? text
658 : text === undefined
659 ? undefined
660 : JSON.stringify(text)
661 // An empty/absent detail (e.g. a ui://-only error body) would render a
662 // dangling colon — fall back to the bare message.
663 throw new Error(
664 !detail
665 ? `MCP tool "${mcpName}" returned an error`
666 : `MCP tool "${mcpName}" returned an error: ${detail}`,
667 )
668 }
669 if (preferStructured && result.structuredContent !== undefined) {
670 return result.structuredContent
671 }
672 return mcpContentToTanstack(result.content)
673 }
675​
676/** A tool that must run as a task. */
677export function requiresTaskExecution(def: McpToolDef): boolean {
678 return def.execution?.taskSupport === 'required'
680​
681/** The server declares task-based execution support for tools/call. */
682export function serverSupportsTaskCalls(client: Client): boolean {
683 return Boolean(client.getServerCapabilities()?.tasks?.requests?.tools?.call)
685​
686/**
687 * Auto-discovery path: turn raw MCP tool defs into ServerTools. Task-required
688 * tools are excluded when the server does not declare the tasks capability
689 * for tools/call — every invocation would fail, so they must not be offered
690 * to the model.
691 */
692export function toServerTools(
693 client: Client,
694 defs: Array<McpToolDef>,
695 options: ConvertOptions,
696): Array<McpServerTool> {
697 const supportsTasks = serverSupportsTaskCalls(client)
698 return defs
699 .filter((def) => !requiresTaskExecution(def) || supportsTasks)
700 .map((def) => {
701 const name = options.prefix ? `${options.prefix}_${def.name}` : def.name
702 const tool: McpServerTool = {
703 __toolSide: 'server',
704 name,
705 description: def.description ?? '',
706 inputSchema: (def.inputSchema as any) ?? {
707 type: 'object',
708 properties: {},
709 },
710 ...(def.outputSchema ? { outputSchema: def.outputSchema as any } : {}),
711 ...(options.lazy ? { lazy: true } : {}),
712 metadata: {
713 mcp: toolMcpMetadata(def, options.prefix),
714 },
715 execute: makeMcpExecute(
716 client,
717 def.name,
718 Boolean(def.outputSchema),
719 requiresTaskExecution(def),
720 ),
721 }
722 if (options.needsApproval?.(def)) {
723 // McpServerTool types needsApproval as false to stay a plain ServerTool.
724 const approvable: AnyServerTool = tool
725 approvable.needsApproval = true
726 }
727 return tool
728 })