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

tools.ts

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