Open History to see the last commit
1import {
2 isCallToolResult,
3 isInputRequiredResult,
4} from '@modelcontextprotocol/client'
5import type {
6 Client,
7 Request,
8 RequestOptions,
9 TaskStatus,
10 Tool as McpToolDef,
11 ToolAnnotations,
12} from '@modelcontextprotocol/client'
13import type {
14 AnyServerTool,
15 ContentPart,
16 ToolInputResponse,
17} from '@tanstack/ai'
18import {
19 isMCPInputRequiredError,
20 MCPInputRequiredError,
21} from './input-required'
22import type { MCPClientOptions, McpServerTool, McpToolMetadata } from './types'
23
24interface ConvertOptions {
25 prefix?: string
26 toolName?: (tool: McpToolDef) => string
27 lazy?: boolean
28 needsApproval?: (tool: McpToolDef) => boolean
29 requestOptions?: MCPClientOptions['requestOptions']
30}
31
32/** Reads the MCP Apps `_meta.ui.resourceUri` link from a tool def, if present. */
33export function extractUiResourceUri(def: McpToolDef): string | undefined {
34 const meta = def._meta
35 if (!isRecord(meta)) return undefined
36 const ui = meta.ui
37 if (!isRecord(ui)) return undefined
38 return typeof ui.resourceUri === 'string' ? ui.resourceUri : undefined
39}
40
41/**
42 * The human-readable display name for a tool, following the MCP spec's
43 * precedence: the top-level `title` field wins, then the legacy
44 * `annotations.title`, and finally the programmatic `name`.
45 */
46function toolDisplayTitle(def: McpToolDef): string {
47 return def.title ?? def.annotations?.title ?? def.name
48}
49
50/**
51 * Build the `metadata.mcp` block stamped onto every discovered/bound tool.
52 * Shared by auto-discovery (`toServerTools`) and the explicit `tools(defs)`
53 * path in `client.ts` so the two cannot drift.
54 *
55 * `annotations` is a frozen copy of the server's object. A host cannot change
56 * the server's data through it. Per the MCP spec, its fields (including
57 * `title`) are hints. A host may use them for display or for an approval UI,
58 * but never as a security boundary.
59 *
60 * Fields the server didn't declare are OMITTED rather than set to `undefined`:
61 * the explicit path merges this over any `mcp` block the caller already put on
62 * their tool definition, and an `undefined` value would blank out what they set.
63 */
64export function toolMcpMetadata(
65 def: McpToolDef,
66 serverId: string | undefined,
67): McpToolMetadata {
68 const uiResourceUri = extractUiResourceUri(def)
69 const annotations: ToolAnnotations | undefined = def.annotations
70 return {
71 serverToolName: def.name,
72 serverId,
73 title: toolDisplayTitle(def),
74 ...(uiResourceUri !== undefined ? { uiResourceUri } : {}),
75 ...(annotations !== undefined
76 ? { annotations: Object.freeze({ ...annotations }) }
77 : {}),
78 }
79}
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 : ''
114}
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 * @param requestOptions - The client `requestOptions`, sent with tools/call
144 * @param inputSchema - The listed tool's input schema. On spec 2026 the SDK
145 * reads its `x-mcp-header` fields to send the `Mcp-Param-*` headers.
146 * @param askInput - Asks the user for each elicitation round on spec 2026.
147 * The harness sets it. Without it, a call answers one round.
148 */
149export async function callMcpTool(
150 client: Client,
151 mcpName: string,
152 args: Record<string, unknown>,
153 taskRequired: boolean,
154 signal?: AbortSignal,
155 inputResponse?: ToolInputResponse,
156 requestOptions?: MCPClientOptions['requestOptions'],
157 inputSchema?: McpToolDef['inputSchema'],
158 askInput?: AskInput,
159) {
160 signal?.throwIfAborted()
161 const isModern = client.getProtocolEra() === 'modern'
162 if (taskRequired && !isModern) {
163 const raw = await sdkRequest(
164 client,
165 'tools/call',
166 { name: mcpName, arguments: args, task: {} },
167 signal,
168 requestOptions,
169 )
170 return finishToolCall(client, mcpName, raw, signal)
171 }
172
173 const options = {
174 ...sdkRequestOptions(requestOptions, signal),
175 allowInputRequired: true,
176 // Only name and inputSchema. The SDK sends the Mcp-Param-* headers from
177 // the schema. With no outputSchema, it skips its output check, which
178 // would reject an input_required result.
179 ...(isModern && inputSchema !== undefined
180 ? { toolDefinition: { name: mcpName, inputSchema } }
181 : {}),
182 }
183 const params = { name: mcpName, arguments: args }
184 let result = await client.callTool(params, options)
185 // ponytail: the answer is sent on the second call, so the server state never
186 // travels through the browser. The cost is one extra tools/call.
187 if (inputResponse !== undefined && isInputRequiredResult(result)) {
188 result = await client.callTool(
189 { ...params, ...retryParams(result, inputResponse) },
190 options,
191 )
192 // ponytail: one input round per call. The next resume starts with no
193 // requestState, so a second pause would ask round 1 again forever.
194 // Carry requestState through the interrupt if servers need more rounds.
195 if (isInputRequiredResult(result) && askInput === undefined) {
196 throw new Error(
197 `The MCP tool "${mcpName}" asked for input a second time. ` +
198 'This client answers one input request per tool call.',
199 )
200 }
201 }
202 // The harness asks the user for each elicitation round, up to a cap.
203 for (
204 let round = 1;
205 isModern && askInput && isInputRequiredResult(result);
206 round++
207 ) {
208 const entry = firstInputRequest(result.inputRequests)
209 if (entry?.method !== 'elicitation/create') break
210 if (round > maxInputRounds) {
211 throw new Error(
212 `The MCP tool "${mcpName}" asked for input more than ` +
213 `${maxInputRounds} times in one call.`,
214 )
215 }
216 const answer = await askInput(isRecord(entry.params) ? entry.params : entry)
217 result = await client.callTool(
218 { ...params, ...retryParams(result, answer) },
219 options,
220 )
221 }
222 throwIfInputRequired(result)
223 return result
224}
225
226/** Asks the user for one MCP elicitation request body. */
227export type AskInput = (request: unknown) => Promise<ToolInputResponse>
228
229const maxInputRounds = 5
230
231// Answers only the first input request. That is the one the interrupt shows.
232function retryParams(
233 result: { inputRequests?: unknown; requestState?: string },
234 response: ToolInputResponse,
235) {
236 const requests = isRecord(result.inputRequests) ? result.inputRequests : {}
237 const key = Object.keys(requests)[0]
238 const entry = key === undefined ? undefined : requests[key]
239 const method = isRecord(entry) ? entry.method : undefined
240 const requestState =
241 result.requestState === undefined
242 ? {}
243 : { requestState: result.requestState }
244 if (key === undefined) return requestState
245 return {
246 inputResponses: { [key]: inputAnswer(method, response) },
247 ...requestState,
248 }
249}
250
251function inputAnswer(method: unknown, response: ToolInputResponse) {
252 if (method === 'sampling/createMessage') {
253 if (response.status === 'cancelled') {
254 throw new Error('The user cancelled the MCP sampling request.')
255 }
256 const payload = response.payload
257 if (typeof payload !== 'string') return payload
258 return {
259 role: 'assistant',
260 content: { type: 'text', text: payload },
261 model: 'user',
262 }
263 }
264 if (response.status === 'cancelled') return { action: 'cancel' }
265 const payload = response.payload
266 // An ElicitResult passes as is. Any other value is the accepted content.
267 if (isRecord(payload) && typeof payload.action === 'string') return payload
268 return { action: 'accept', content: payload }
269}
270
271const schemaSlot: unknown = undefined
272
273const passThroughResult = {
274 '~standard': {
275 version: 1 as const,
276 vendor: 'tanstack-ai-mcp',
277 types: {
278 input: schemaSlot,
279 output: schemaSlot,
280 },
281 validate(value: unknown) {
282 return { value }
283 },
284 },
285}
286
287/** The spec 2025-11-25 task fields this client reads. */
288type TaskState = {
289 taskId: string
290 status: TaskStatus
291 pollInterval: number | undefined
292 statusMessage: string | undefined
293}
294
295const defaultPollMs = 1000
296
297async function finishToolCall(
298 client: Client,
299 mcpName: string,
300 raw: unknown,
301 signal?: AbortSignal,
302) {
303 throwIfInputRequired(raw)
304 // A spec 2025 task body also carries `content`. Read the task first.
305 const task = readNestedTask(raw)
306 if (task !== undefined) {
307 return pollTask(client, mcpName, task, signal)
308 }
309 if (isCallToolResult(raw)) return raw
310 throw missingTaskResult(mcpName)
311}
312
313async function pollTask(
314 client: Client,
315 mcpName: string,
316 task: TaskState,
317 signal?: AbortSignal,
318) {
319 let current = task
320 try {
321 while (
322 current.status === 'working' ||
323 current.status === 'input_required'
324 ) {
325 if (current.status === 'input_required') {
326 // A spec 2025 task sends its input request on tasks/result, as a
327 // request to the client. This client does not answer those requests,
328 // so stop here. Polling again would never end.
329 void cancelTask(client, current.taskId)
330 throw new Error(
331 `MCP task "${current.taskId}" needs input. This client cannot answer a spec 2025 task input request.`,
332 )
333 }
334 const delay = current.pollInterval ?? defaultPollMs
335 await waitForPoll(delay, signal)
336 current = await readPolledTask(client, current.taskId, mcpName, signal)
337 }
338 } catch (error) {
339 if (isMCPInputRequiredError(error)) throw error
340 if (signal?.aborted) {
341 void cancelTask(client, task.taskId)
342 throw abortReason(signal)
343 }
344 throw error
345 }
346
347 switch (current.status) {
348 case 'completed':
349 return taskResult(client, mcpName, current.taskId, signal)
350 case 'failed':
351 case 'cancelled':
352 throw terminalTaskError(current)
353 default: {
354 const unexpected: never = current.status
355 throw new Error(`Unknown MCP task status: ${String(unexpected)}`)
356 }
357 }
358}
359
360async function taskResult(
361 client: Client,
362 mcpName: string,
363 taskId: string,
364 signal?: AbortSignal,
365) {
366 const result = await taskRequest(client, 'tasks/result', { taskId }, signal)
367 throwIfInputRequired(result)
368 if (!isCallToolResult(result)) throw missingTaskResult(mcpName)
369 return result
370}
371
372async function readPolledTask(
373 client: Client,
374 taskId: string,
375 mcpName: string,
376 signal?: AbortSignal,
377) {
378 const body = await taskRequest(client, 'tasks/get', { taskId }, signal)
379 throwIfInputRequired(body)
380 const task = readTaskState(body)
381 if (task === undefined) throw missingTaskResult(mcpName)
382 return task
383}
384
385// ponytail: task polls (tasks/get, tasks/result, tasks/cancel) keep the SDK
386// default timeout. Each poll is a short request. Pass the client
387// requestOptions here if a server is slow to answer a poll.
388function taskRequest(
389 client: Client,
390 method: string,
391 params: Record<string, unknown>,
392 signal?: AbortSignal,
393) {
394 return sdkRequest(client, method, params, signal)
395}
396
397/**
398 * The SDK options for one request: the client `requestOptions` plus the
399 * caller's `signal`. `undefined` when both are unset, so the SDK defaults
400 * apply.
401 *
402 * The SDK asks the server for progress only when `onprogress` is set. So a
403 * no-op `onprogress` comes with `resetTimeoutOnProgress`, or that option
404 * would never see a progress notification.
405 */
406export function sdkRequestOptions(
407 requestOptions: MCPClientOptions['requestOptions'],
408 signal?: AbortSignal,
409): RequestOptions | undefined {
410 if (requestOptions === undefined && signal === undefined) return undefined
411 return {
412 ...requestOptions,
413 ...(requestOptions?.resetTimeoutOnProgress ? { onprogress: () => {} } : {}),
414 ...(signal === undefined ? {} : { signal }),
415 }
416}
417
418async function sdkRequest(
419 client: Client,
420 method: string,
421 params: Record<string, unknown>,
422 signal?: AbortSignal,
423 requestOptions?: MCPClientOptions['requestOptions'],
424) {
425 signal?.throwIfAborted()
426 const rpc: Request = { method, params }
427 try {
428 return await client.request(
429 rpc,
430 passThroughResult,
431 sdkRequestOptions(requestOptions, signal),
432 )
433 } catch (error) {
434 if (signal?.aborted) throw abortReason(signal)
435 throw error
436 }
437}
438
439function cancelTask(client: Client, taskId: string) {
440 return taskRequest(client, 'tasks/cancel', { taskId }).catch(() => undefined)
441}
442
443function throwIfInputRequired(value: unknown) {
444 if (!isRecord(value)) return
445 if (isInputRequiredResult(value)) {
446 throwInputRequired(value.inputRequests, value)
447 }
448 if (value.status !== 'input_required') return
449 if (!hasRequests(value.inputRequests)) return
450 throwInputRequired(value.inputRequests, value)
451}
452
453function throwInputRequired(requests: unknown, fallback: unknown) {
454 const entry = firstInputRequest(requests)
455 if (entry === undefined) {
456 throw new MCPInputRequiredError('form', fallback)
457 }
458 const body = isRecord(entry.params) ? entry.params : entry
459 if (entry.method === 'sampling/createMessage') {
460 throw new MCPInputRequiredError('sampling', body)
461 }
462 if (entry.method === 'elicitation/create') {
463 throw new MCPInputRequiredError('form', body)
464 }
465 throw new Error(`The MCP server asked for unsupported input: ${entry.method}`)
466}
467
468function firstInputRequest(requests: unknown) {
469 if (!isRecord(requests)) return undefined
470 const entries = Object.values(requests)
471 for (const entry of entries) {
472 if (!isRecord(entry) || typeof entry.method !== 'string') continue
473 return entry
474 }
475 return undefined
476}
477
478function hasRequests(requests: unknown) {
479 return isRecord(requests) && Object.keys(requests).length > 0
480}
481
482function readNestedTask(value: unknown) {
483 if (!isRecord(value)) return undefined
484 return readTaskState(value.task)
485}
486
487function readTaskState(value: unknown) {
488 if (!isRecord(value)) return undefined
489 if (typeof value.taskId !== 'string' || value.taskId.length === 0) {
490 return undefined
491 }
492 if (!isTaskStatus(value.status)) return undefined
493 const task: TaskState = {
494 taskId: value.taskId,
495 status: value.status,
496 pollInterval:
497 typeof value.pollInterval === 'number' ? value.pollInterval : undefined,
498 statusMessage:
499 typeof value.statusMessage === 'string' ? value.statusMessage : undefined,
500 }
501 return task
502}
503
504function isTaskStatus(value: unknown): value is TaskStatus {
505 switch (value) {
506 case 'working':
507 case 'input_required':
508 case 'completed':
509 case 'failed':
510 case 'cancelled':
511 return true
512 default:
513 return false
514 }
515}
516
517function terminalTaskError(task: TaskState) {
518 const detail = task.statusMessage
519 if (detail !== undefined && detail.length > 0) {
520 return new Error(`MCP task "${task.taskId}" ${task.status}: ${detail}`)
521 }
522 return new Error(`MCP task "${task.taskId}" ${task.status}.`)
523}
524
525function missingTaskResult(mcpName: string) {
526 return new Error(
527 `MCP task-required tool "${mcpName}" ended without a result or error`,
528 )
529}
530
531function waitForPoll(milliseconds: number, signal?: AbortSignal) {
532 signal?.throwIfAborted()
533 if (milliseconds <= 0) return Promise.resolve()
534 if (signal === undefined) {
535 return new Promise<void>((resolve) => {
536 setTimeout(resolve, milliseconds)
537 })
538 }
539 const active = signal
540 return new Promise<void>((resolve, reject) => {
541 const timer = setTimeout(() => {
542 active.removeEventListener('abort', onAbort)
543 resolve()
544 }, milliseconds)
545 const onAbort = () => {
546 clearTimeout(timer)
547 reject(abortReason(active))
548 }
549 active.addEventListener('abort', onAbort, { once: true })
550 })
551}
552
553function abortReason(signal: AbortSignal) {
554 return signal.reason instanceof Error
555 ? signal.reason
556 : new DOMException('Aborted', 'AbortError')
557}
558
559function isRecord(value: unknown): value is Record<string, unknown> {
560 return typeof value === 'object' && value !== null && !Array.isArray(value)
561}
562
563/**
564 * Build the execute body that proxies a TanStack tool call to an MCP server.
565 * Shared by auto-discovery and the definition path.
566 *
567 * @param preferStructured when true (i.e. the tool declares an outputSchema),
568 * return `result.structuredContent` if present so the existing output
569 * validation in `executeServerTool` validates MCP's typed payload rather than
570 * a JSON-in-text blob. Otherwise normalize `content[]` → string | ContentPart[].
571 * @param requestOptions - The client `requestOptions`, sent with each call
572 * @param inputSchema - The listed tool's input schema, for the Mcp-Param-* headers
573 */
574export function makeMcpExecute(
575 client: Client,
576 mcpName: string,
577 preferStructured: boolean,
578 taskRequired = false,
579 requestOptions?: MCPClientOptions['requestOptions'],
580 inputSchema?: McpToolDef['inputSchema'],
581) {
582 return async (
583 args: unknown,
584 ctx?: {
585 abortSignal?: AbortSignal
586 inputResponse?: ToolInputResponse
587 askInput?: AskInput
588 },
589 ) => {
590 const result = await callMcpTool(
591 client,
592 mcpName,
593 isRecord(args) ? args : {},
594 taskRequired,
595 ctx?.abortSignal,
596 ctx?.inputResponse,
597 requestOptions,
598 inputSchema,
599 ctx?.askInput,
600 )
601 if (result.isError) {
602 const text = Array.isArray(result.content)
603 ? mcpContentToTanstack(result.content)
604 : undefined
605 const detail =
606 typeof text === 'string'
607 ? text
608 : text === undefined
609 ? undefined
610 : JSON.stringify(text)
611 // An empty/absent detail (e.g. a ui://-only error body) would render a
612 // dangling colon — fall back to the bare message.
613 throw new Error(
614 !detail
615 ? `MCP tool "${mcpName}" returned an error`
616 : `MCP tool "${mcpName}" returned an error: ${detail}`,
617 )
618 }
619 if (preferStructured && result.structuredContent !== undefined) {
620 return result.structuredContent
621 }
622 return mcpContentToTanstack(result.content)
623 }
624}
625
626/** A tool that must run as a task. */
627export function requiresTaskExecution(def: McpToolDef): boolean {
628 return def.execution?.taskSupport === 'required'
629}
630
631/** The server declares task-based execution support for tools/call. */
632export function serverSupportsTaskCalls(client: Client): boolean {
633 return Boolean(client.getServerCapabilities()?.tasks?.requests?.tools?.call)
634}
635
636/**
637 * Auto-discovery path: turn raw MCP tool defs into ServerTools. Task-required
638 * tools are excluded when the server does not declare the tasks capability
639 * for tools/call — every invocation would fail, so they must not be offered
640 * to the model.
641 */
642export function toServerTools(
643 client: Client,
644 defs: Array<McpToolDef>,
645 options: ConvertOptions,
646): Array<McpServerTool> {
647 const supportsTasks = serverSupportsTaskCalls(client)
648 return defs
649 .filter((def) => !requiresTaskExecution(def) || supportsTasks)
650 .map((def) => {
651 // `toolName` wins over the prefix. metadata.mcp keeps the server name.
652 const name =
653 options.toolName?.(def) ??
654 (options.prefix ? `${options.prefix}_${def.name}` : def.name)
655 // A server can leave out `type` or `properties`. Fill both, because
656 // some providers reject an object schema without `properties`.
657 const schema: Partial<McpToolDef['inputSchema']> = def.inputSchema ?? {}
658 const tool: McpServerTool = {
659 __toolSide: 'server',
660 name,
661 description: def.description ?? '',
662 inputSchema: {
663 ...schema,
664 type: schema.type ?? 'object',
665 properties: schema.properties ?? {},
666 } as any,
667 ...(def.outputSchema ? { outputSchema: def.outputSchema as any } : {}),
668 ...(options.lazy ? { lazy: true } : {}),
669 metadata: {
670 mcp: toolMcpMetadata(def, options.prefix),
671 },
672 execute: makeMcpExecute(
673 client,
674 def.name,
675 Boolean(def.outputSchema),
676 requiresTaskExecution(def),
677 options.requestOptions,
678 def.inputSchema,
679 ),
680 }
681 if (options.needsApproval?.(def)) {
682 // McpServerTool types needsApproval as false to stay a plain ServerTool.
683 const approvable: AnyServerTool = tool
684 approvable.needsApproval = true
685 }
686 return tool
687 })
688}