Open History to see the last commit
1import { Client } from '@modelcontextprotocol/client'
2import {
3 DuplicateToolNameError,
4 MCPConnectionError,
5 MCPTaskRequiredToolError,
6 MCPToolNotFoundError,
7} from './errors'
8import { listPages } from './list-pages'
9import {
10 callMcpTool,
11 makeMcpExecute,
12 requiresTaskExecution,
13 serverSupportsTaskCalls,
14 toolMcpMetadata,
15 toServerTools,
16} from './tools'
17import { directMCPClient } from './direct-client'
18import { isTransportInstance, resolveTransport } from './transport'
19import type {
20 DescriptorFromServer,
21 DirectClientOptions,
22 DirectMCPClient,
23} from './direct-client'
24import type { MCPServer } from './server/create-server'
25import type { TransportConfig } from './transport'
26import type {
27 AnyToolDefinition,
28 AutomaticDescriptor,
29 DescriptorTools,
30 MCPClientOptions,
31 MappedServerTools,
32 McpServerTool,
33 ServerDescriptor,
34 ToolsOptions,
35} from './types'
36import type {
37 ClientOptions,
38 GetPromptResult,
39 McpSubscription,
40 Prompt,
41 ReadResourceResult,
42 Resource,
43 ResourceTemplateType,
44 Tool as McpToolDef,
45 Transport,
46} from '@modelcontextprotocol/client'
47import type { ServerTool } from '@tanstack/ai'
48
49type CallToolResult = Awaited<ReturnType<Client['callTool']>>
50
51/**
52 * The raw MCP result of `callTool`. When the tool output type is known,
53 * `structuredContent` has that type. An untyped tool keeps the SDK type.
54 */
55export type TypedCallToolResult<TOutput> = unknown extends TOutput
56 ? CallToolResult
57 : Omit<CallToolResult, 'structuredContent'> & { structuredContent?: TOutput }
58
59type ToolPolicy = Pick<MCPClientOptions, 'toolFilter' | 'needsApproval'>
60
61export interface MCPClient<
62 TServer extends ServerDescriptor = AutomaticDescriptor,
63> {
64 readonly capabilities: TServer['capabilities']
65 /**
66 * Auto-discovery: every server tool as a ServerTool. With a generated
67 * descriptor, tool names are typed as the descriptor's name literals;
68 * args/results stay untyped — use the `tools(defs)` overload for typed args.
69 *
70 * Both overloads yield {@link McpServerTool}s, so `tool.metadata.mcp` (the
71 * server's title / annotations) is typed without an annotation or a cast.
72 */
73 tools: {
74 (options?: ToolsOptions): Promise<DescriptorTools<TServer>>
75 /**
76 * Explicit: bind these TanStack toolDefinitions to the server (typed +
77 * validated, allowlist). Note: when the client has a `prefix`, the
78 * runtime tool name is `${prefix}_${def.name}` while the static `TName`
79 * stays the unprefixed definition name.
80 */
81 <const TDefs extends ReadonlyArray<AnyToolDefinition>>(
82 defs: TDefs,
83 options?: ToolsOptions,
84 ): Promise<MappedServerTools<TDefs>>
85 }
86 resources: () => Promise<Array<Resource>>
87 /**
88 * Reads one resource. With a typed server, `uri` is one of its resource URIs.
89 */
90 readResource: (
91 uri: TServer['resources'][keyof TServer['resources']]['uri'],
92 ) => Promise<ReadResourceResult>
93 resourceTemplates: () => Promise<Array<ResourceTemplateType>>
94 prompts: () => Promise<Array<Prompt>>
95 /**
96 * Renders one prompt. With a typed server, `name` is one of its prompt
97 * names and `args` has that prompt's argument type. MCP sends each
98 * argument as a string.
99 */
100 getPrompt: <TName extends keyof TServer['prompts'] & string>(
101 name: TName,
102 args?: TServer['prompts'][TName]['args'],
103 ) => Promise<GetPromptResult>
104 /**
105 * Call a tool directly and return its raw MCP result. Tools declaring
106 * `execution.taskSupport: 'required'` automatically use task execution when
107 * the server declares the tasks capability for tools/call. Pass
108 * `options.signal` to abort — an in-flight task is best-effort cancelled on
109 * the server.
110 *
111 * With a typed server, `name` is one of its tool names and `args` has
112 * that tool's input type. The result is the raw MCP result. For a tool
113 * with an output schema, `structuredContent` has the tool output type.
114 */
115 callTool: <TName extends keyof TServer['tools'] & string>(
116 name: TName,
117 args?: TServer['tools'][TName]['input'],
118 options?: { signal?: AbortSignal },
119 ) => Promise<TypedCallToolResult<TServer['tools'][TName]['output']>>
120 /**
121 * The ORIGINAL connection descriptor this client was created from — the
122 * `transport` input and `prefix` passed to `createMCPClient`. Used by
123 * `createMcpAppCallHandler` to reconnect per-call (serverless-safe) without
124 * a separate transport-config map.
125 *
126 * `transport` is `undefined` when the client was built from a ready-made
127 * `Transport` instance rather than a serializable config — either via
128 * `createMCPClientFromTransport` (test-only) or `createMCPClient({ transport:
129 * <instance> })`. A live `Transport` instance is single-use and cannot be
130 * reconnected, so only serializable `TransportConfig`s are retained here.
131 */
132 getInfo: () => {
133 transport: TransportConfig | undefined
134 prefix: string | undefined
135 /**
136 * The options this client was built with, so a caller that reconstructs it
137 * from this descriptor keeps them. Without it a rebuilt client silently
138 * reverts to the SDK defaults — including the AJV validator that edge
139 * runtimes cannot compile.
140 *
141 * Optional so an existing hand-rolled `MCPClient` keeps compiling.
142 */
143 clientOptions?: ClientOptions
144 toolFilter?: MCPClientOptions['toolFilter']
145 needsApproval?: MCPClientOptions['needsApproval']
146 }
147 close: () => Promise<void>
148 [Symbol.asyncDispose]: () => Promise<void>
149}
150
151class MCPClientImpl<
152 TServer extends ServerDescriptor,
153> implements MCPClient<TServer> {
154 capabilities: TServer['capabilities'] = {}
155 readonly #client: Client
156 #closed = false
157 #toolDefinitions?: Map<string, McpToolDef>
158 // Open only after a spec 2026 connect when the server can report tool changes.
159 #toolListSubscription?: McpSubscription
160 private readonly prefix?: string
161 // The ORIGINAL serializable transport config (undefined for clients built
162 // from a ready-made Transport instance, which is single-use / not reconnectable).
163 readonly #transport: TransportConfig | undefined
164 // Retained for the same reason as #transport: the MCP Apps call handler
165 // rebuilds a client per call from getInfo(), and a rebuilt client that lost
166 // `jsonSchemaValidator` falls straight back to AJV.
167 readonly #clientOptions: ClientOptions | undefined
168 readonly #policy: ToolPolicy
169
170 constructor(
171 prefix?: string,
172 name = 'tanstack-ai-mcp',
173 version = '0.0.1',
174 transport?: TransportConfig,
175 clientOptions?: ClientOptions,
176 policy: ToolPolicy = {},
177 ) {
178 this.prefix = prefix
179 this.#transport = transport
180 this.#clientOptions = clientOptions
181 this.#policy = policy
182 // Try spec 2026-07-28 first. If the server does not support it, the
183 // client uses the 2025 initialize handshake. Caller options still apply.
184 // `mode` stays `auto` even when `clientOptions` sets another mode.
185 // A spec 2026 server returns `input_required` only to a client that
186 // declares elicitation and sampling. `chat()` turns that result into an
187 // `mcp_input` interrupt, so the client declares both by default.
188 this.#client = new Client(
189 { name, version },
190 {
191 ...clientOptions,
192 capabilities: {
193 elicitation: { form: {} },
194 sampling: {},
195 ...clientOptions?.capabilities,
196 },
197 versionNegotiation: {
198 ...clientOptions?.versionNegotiation,
199 mode: 'auto',
200 },
201 },
202 )
203 }
204
205 getInfo(): {
206 transport: TransportConfig | undefined
207 prefix: string | undefined
208 clientOptions?: ClientOptions
209 toolFilter?: MCPClientOptions['toolFilter']
210 needsApproval?: MCPClientOptions['needsApproval']
211 } {
212 const { toolFilter, needsApproval } = this.#policy
213 return {
214 transport: this.#transport,
215 prefix: this.prefix,
216 ...(this.#clientOptions ? { clientOptions: this.#clientOptions } : {}),
217 ...(toolFilter ? { toolFilter } : {}),
218 ...(needsApproval ? { needsApproval } : {}),
219 }
220 }
221
222 async connect(transport: Transport): Promise<void> {
223 try {
224 // A tools/list_changed notice drops the cached definitions so the next
225 // callTool reads each tool's execution mode again.
226 this.#client.setNotificationHandler(
227 'notifications/tools/list_changed',
228 () => {
229 this.#toolDefinitions = undefined
230 },
231 )
232 await this.#client.connect(transport)
233 this.capabilities = this.#client.getServerCapabilities() ?? {}
234 // A failed listen only means that tool changes are not pushed.
235 // The connection still works, so the error does not fail connect.
236 await this.#listenForToolListChanges().catch(() => undefined)
237 } catch (err) {
238 await this.#toolListSubscription?.close().catch(() => undefined)
239 await this.#client.close().catch(() => undefined)
240 throw new MCPConnectionError('Failed to connect to MCP server', err)
241 }
242 }
243
244 // Spec 2026 does not push tool-list changes. Open subscriptions/listen when
245 // the server says it can report them. The notice handler above drops the cache.
246 async #listenForToolListChanges() {
247 if (this.#client.getProtocolEra() !== 'modern') return
248 const tools = this.#client.getServerCapabilities()?.tools
249 if (tools?.listChanged !== true) return
250 this.#toolListSubscription = await this.#client.listen({
251 toolsListChanged: true,
252 })
253 }
254
255 // Read every tools/list page into the definition cache.
256 // listPages throws when a cursor repeats or the page cap is passed.
257 // A raw list does not compile `jsonSchemaValidator`. On spec 2025, SDK
258 // `callTool` then skips output checks. So `tools()` follows the raw walk
259 // with `listTools()` to fill the SDK cache and run the validator.
260 // Spec 2026 calls use a raw tools/call, which never reads that cache,
261 // so the second walk is skipped there.
262 // `raw: true` is the lazy `callTool` path. It must stay free of that cache.
263 async #listTools(options?: { raw?: boolean }) {
264 const client = this.#client
265 const defs = await listPages(async (cursor) => {
266 const page =
267 cursor === undefined
268 ? await client.request({ method: 'tools/list' })
269 : await client.request({
270 method: 'tools/list',
271 params: { cursor },
272 })
273 return { items: page.tools, nextCursor: page.nextCursor }
274 })
275 this.#toolDefinitions = new Map(defs.map((def) => [def.name, def]))
276 if (options?.raw !== true && client.getProtocolEra() !== 'modern') {
277 await client.listTools()
278 }
279 return defs
280 }
281
282 async tools(
283 defsOrOptions?: ReadonlyArray<AnyToolDefinition> | ToolsOptions,
284 maybeOptions: ToolsOptions = {},
285 ): Promise<Array<McpServerTool>> {
286 if (this.#closed) throw new MCPConnectionError('MCP client is closed')
287
288 const isDefs = Array.isArray(defsOrOptions)
289 const options: ToolsOptions = isDefs
290 ? maybeOptions
291 : // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
292 ((defsOrOptions as ToolsOptions) ?? {}) // SDK interop: defsOrOptions may be undefined at runtime even though TS types it as ToolsOptions here
293
294 const { toolFilter, needsApproval } = this.#policy
295 const listed = await this.#listTools()
296 const defs = toolFilter ? listed.filter((def) => toolFilter(def)) : listed
297
298 let tools: Array<McpServerTool>
299 if (isDefs) {
300 // Explicit path: bind each TanStack toolDefinition to the server by name.
301 const available = new Map(defs.map((tool) => [tool.name, tool]))
302 tools = (defsOrOptions as ReadonlyArray<AnyToolDefinition>).map((def) => {
303 const serverTool = available.get(def.name)
304 if (!serverTool) throw new MCPToolNotFoundError(def.name)
305 // A task-required tool on a server without the tasks capability for
306 // tools/call cannot be invoked (every call fails) — refuse the binding.
307 if (
308 requiresTaskExecution(serverTool) &&
309 !serverSupportsTaskCalls(this.#client)
310 ) {
311 throw new MCPTaskRequiredToolError(def.name)
312 }
313 const bound = def.server(
314 makeMcpExecute(
315 this.#client,
316 def.name,
317 Boolean(def.outputSchema),
318 requiresTaskExecution(serverTool),
319 ),
320 ) as ServerTool
321 // A caller-supplied definition may already carry its own `mcp` block,
322 // and `metadata.mcp` is untyped there — only spread it when it really
323 // is a plain object.
324 const existingMcp: unknown = bound.metadata?.mcp
325 const mcpBase =
326 existingMcp !== null && typeof existingMcp === 'object'
327 ? existingMcp
328 : {}
329 // Rebuilt rather than mutated in place: assigning `metadata` on a
330 // `ServerTool` can't narrow its declared `Record<string, any> |
331 // undefined` type, so a fresh literal is what lets the return value be
332 // an `McpServerTool` (typed `metadata.mcp`) without a cast.
333 //
334 // Stamping MCP metadata lets `serverToolNameOf` (and the call handler)
335 // recover the UNPREFIXED native name + serverId, and carries the
336 // server's display title / annotations to the host — mirrors
337 // toServerTools.
338 const tool: McpServerTool = {
339 ...bound,
340 ...(this.prefix ? { name: `${this.prefix}_${def.name}` } : {}),
341 ...(options.lazy ? { lazy: true } : {}),
342 metadata: {
343 ...bound.metadata,
344 mcp: { ...mcpBase, ...toolMcpMetadata(serverTool, this.prefix) },
345 },
346 }
347 return tool
348 })
349 } else {
350 // Auto-discovery path.
351 tools = toServerTools(this.#client, defs, {
352 prefix: this.prefix,
353 lazy: options.lazy,
354 needsApproval,
355 })
356 }
357
358 // Local duplicate guard (within one client's own list — applies to both branches).
359 const seen = new Set<string>()
360 for (const t of tools) {
361 if (seen.has(t.name)) throw new DuplicateToolNameError(t.name)
362 seen.add(t.name)
363 }
364 return tools
365 }
366
367 async resources(): Promise<Array<Resource>> {
368 if (this.#closed) throw new MCPConnectionError('MCP client is closed')
369 return (await this.#client.listResources()).resources
370 }
371
372 async readResource(uri: string): Promise<ReadResourceResult> {
373 if (this.#closed) throw new MCPConnectionError('MCP client is closed')
374 return this.#client.readResource({ uri })
375 }
376
377 async resourceTemplates(): Promise<Array<ResourceTemplateType>> {
378 if (this.#closed) throw new MCPConnectionError('MCP client is closed')
379 return (await this.#client.listResourceTemplates()).resourceTemplates
380 }
381
382 async prompts(): Promise<Array<Prompt>> {
383 if (this.#closed) throw new MCPConnectionError('MCP client is closed')
384 return (await this.#client.listPrompts()).prompts
385 }
386
387 async getPrompt(name: string, args?: unknown): Promise<GetPromptResult> {
388 if (this.#closed) throw new MCPConnectionError('MCP client is closed')
389 // MCP prompt arguments are strings.
390 const promptArgs = isArgs(args)
391 ? Object.fromEntries(
392 Object.entries(args).map(([key, value]) => [key, String(value)]),
393 )
394 : undefined
395 return this.#client.getPrompt({ name, arguments: promptArgs })
396 }
397
398 async callTool<TName extends keyof TServer['tools'] & string>(
399 name: TName,
400 args?: TServer['tools'][TName]['input'],
401 options?: { signal?: AbortSignal },
402 ): Promise<TypedCallToolResult<TServer['tools'][TName]['output']>> {
403 if (this.#closed) throw new MCPConnectionError('MCP client is closed')
404 if (!this.#toolDefinitions) {
405 // Lazy discovery so task-required tools work without a prior tools()
406 // call. Best-effort: a server whose tools/list fails (or omits the
407 // tool) still gets the plain tools/call it would have received before
408 // task support existed. See #listTools.
409 try {
410 await this.#listTools({ raw: true })
411 } catch {
412 // fall through to a plain tools/call
413 }
414 }
415 const definition = this.#toolDefinitions?.get(name)
416 const taskRequired =
417 definition !== undefined && requiresTaskExecution(definition)
418 // A known task-required tool on a server without the tasks capability can
419 // never execute — fail with the clear local error rather than the server's
420 // opaque -32600 (mirrors the tools([...defs]) binding guard).
421 if (taskRequired && !serverSupportsTaskCalls(this.#client)) {
422 throw new MCPTaskRequiredToolError(name)
423 }
424 const result = await callMcpTool(
425 this.#client,
426 name,
427 isArgs(args) ? args : {},
428 taskRequired,
429 options?.signal,
430 )
431 // Trust boundary: the server type says what `structuredContent` holds.
432 // The client does not check the wire value against that type.
433 return result as TypedCallToolResult<TServer['tools'][TName]['output']>
434 }
435
436 async close(): Promise<void> {
437 if (this.#closed) return
438 this.#closed = true
439 const subscription = this.#toolListSubscription
440 this.#toolListSubscription = undefined
441 try {
442 await subscription?.close()
443 } finally {
444 await this.#client.close()
445 }
446 }
447
448 async [Symbol.asyncDispose](): Promise<void> {
449 await this.close()
450 }
451}
452
453function isArgs(value: unknown): value is Record<string, unknown> {
454 return typeof value === 'object' && value !== null && !Array.isArray(value)
455}
456
457/**
458 * Connects to an MCP server.
459 *
460 * Pass `transport` for a server at a URL, on SSE, or on stdio.
461 * The client speaks MCP over that transport, so server auth applies.
462 *
463 * To type a transport client from a TanStack server, pass `typeof server`
464 * as the type argument. Import the server with `import type`.
465 *
466 * Pass `server` to call a `createMCPServer` result in this process.
467 * That client calls the tool functions directly. It opens no connection,
468 * and the server `auth` option does not run.
469 *
470 * @param options - A transport, or a TanStack MCP server in this process
471 *
472 * @example
473 * ```ts
474 * const remote = await createMCPClient<typeof server>({
475 * transport: { type: 'http', url: 'https://mcp.example.com/mcp' },
476 * })
477 * await remote.callTool('get_weather', { city: 'Paris' })
478 *
479 * const local = await createMCPClient({ server })
480 * await local.callTool('get_weather', { city: 'Paris' })
481 * ```
482 */
483export async function createMCPClient<
484 TDescriptor extends ServerDescriptor = AutomaticDescriptor,
485>(options: MCPClientOptions): Promise<MCPClient<TDescriptor>>
486export async function createMCPClient<TServer extends MCPServer>(
487 options: MCPClientOptions,
488): Promise<MCPClient<DescriptorFromServer<TServer>>>
489export async function createMCPClient<TServer extends MCPServer>(
490 options: DirectClientOptions<TServer>,
491): Promise<DirectMCPClient<TServer>>
492export async function createMCPClient(
493 options: MCPClientOptions | DirectClientOptions<MCPServer>,
494): Promise<MCPClient | DirectMCPClient<MCPServer>> {
495 if ('server' in options) {
496 return directMCPClient(options.server)
497 }
498 return connectTransport(options)
499}
500
501async function connectTransport<
502 TServer extends ServerDescriptor = AutomaticDescriptor,
503>(options: MCPClientOptions) {
504 const transport = await resolveTransport(options.transport)
505 const impl = new MCPClientImpl<TServer>(
506 options.prefix,
507 options.name,
508 options.version,
509 // Only a serializable config is reconnectable; a ready-made Transport
510 // instance is single-use, so it is not retained as a descriptor.
511 isTransportInstance(options.transport) ? undefined : options.transport,
512 options.clientOptions,
513 { toolFilter: options.toolFilter, needsApproval: options.needsApproval },
514 )
515 await impl.connect(transport)
516 return impl
517}
518
519/** Test-only: connect directly from a transport instance (skips resolveTransport). */
520export async function createMCPClientFromTransport<
521 TServer extends ServerDescriptor = AutomaticDescriptor,
522>(
523 transport: Transport,
524 prefix?: string,
525 clientOptions?: ClientOptions,
526): Promise<MCPClient<TServer>> {
527 const impl = new MCPClientImpl<TServer>(
528 prefix,
529 undefined,
530 undefined,
531 undefined,
532 clientOptions,
533 )
534 await impl.connect(transport)
535 return impl
536}