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

client.ts

877 lines31.5 KB

1import { Client } from '@modelcontextprotocol/client'
2import {
3 DuplicateToolNameError,
4 MCPConnectionError,
5 MCPEventConfigError,
6 MCPTaskRequiredToolError,
7 MCPToolFilterError,
8 MCPToolNotFoundError,
9} from './errors'
10import { listPages } from './list-pages'
11import {
12 serverSupportsEvents,
13 withEventsClientCapability,
14} from './events/capability'
15import { createDirectMCPEvents } from './events/direct'
16import { createDiscoveryMCPEvents } from './events/discovery'
17import {
18 createManagedMCPEvents,
19 validateMCPEventOperations,
20} from './events/managed'
21import type {
22 DirectMCPEventsOptions,
23 ManagedMCPEvents,
24 ManagedMCPEventsOptions,
25 MCPEventAdapterTransport,
26 MCPEventOperations,
27 MCPEvents,
28 MCPEventsContext,
29 MCPEventsOptions,
30} from './events/types'
31import {
32 callMcpTool,
33 makeMcpExecute,
34 requiresTaskExecution,
35 sdkRequestOptions,
36 serverSupportsTaskCalls,
37 toolMcpMetadata,
38 toServerTools,
39} from './tools'
40import { directMCPClient } from './direct-client'
41import { isTransportInstance, resolveTransport } from './transport'
42import type {
43 DescriptorFromServer,
44 DirectClientOptions,
45 DirectMCPClient,
46} from './direct-client'
47import type { MCPServer } from './server/create-server'
48import type { TransportConfig, TransportInput } from './transport'
49import type {
50 AnyToolDefinition,
51 AutomaticDescriptor,
52 DescriptorTools,
53 MCPClientOptions,
54 MappedServerTools,
55 McpServerTool,
56 ServerDescriptor,
57 ToolsOptions,
58} from './types'
59import type {
60 ClientOptions,
61 DiscoverResult,
62 ElicitRequest,
63 ElicitResult,
64 GetPromptResult,
65 McpSubscription,
66 PriorDiscovery,
67 Prompt,
68 ReadResourceResult,
69 Request as McpRequest,
70 RequestMethod,
71 RequestOptions,
72 Resource,
73 ResourceTemplateType,
74 StandardSchemaV1,
75 Tool as McpToolDef,
76 Transport,
77} from '@modelcontextprotocol/client'
78import type { ServerTool } from '@tanstack/ai'
79​
80type CallToolResult = Awaited<ReturnType<Client['callTool']>>
81​
82/**
83 * The raw MCP result of `callTool`. When the tool output type is known,
84 * `structuredContent` has that type. An untyped tool keeps the SDK type.
85 */
86export type TypedCallToolResult<TOutput> = unknown extends TOutput
87 ? CallToolResult
88 : Omit<CallToolResult, 'structuredContent'> & { structuredContent?: TOutput }
89​
90type ToolPolicy = Pick<
91 MCPClientOptions,
92 'toolFilter' | 'needsApproval' | 'toolName' | 'requestOptions'
94​
95type ClientEvents = Pick<MCPClientOptions, 'onClose' | 'onToolListChanged'>
96​
97export interface MCPClient<
98 TServer extends ServerDescriptor = AutomaticDescriptor,
99> {
100 readonly capabilities: TServer['capabilities']
101 /**
102 * The server's instructions from the connect handshake: how to use its
103 * tools, meant for the model's system prompt. `undefined` when the server
104 * sends none.
105 *
106 * Optional so an existing hand-rolled `MCPClient` keeps compiling.
107 */
108 readonly instructions?: string
109 /**
110 * The `server/discover` result of this connection, or the `prior` it
111 * adopted. Save it and pass it back as `prior: { kind: 'modern', discover }`
112 * to skip the `server/discover` request on a later connect. `undefined`
113 * when the server speaks protocol `2025-11-25`, or after a
114 * `{ kind: 'legacy' }` prior.
115 */
116 getDiscoverResult: () => DiscoverResult | undefined
117 /**
118 * Auto-discovery: every server tool as a ServerTool. With a generated
119 * descriptor, tool names are typed as the descriptor's name literals;
120 * args/results stay untyped — use the `tools(defs)` overload for typed args.
121 *
122 * Both overloads yield {@link McpServerTool}s, so `tool.metadata.mcp` (the
123 * server's title / annotations) is typed without an annotation or a cast.
124 */
125 tools: {
126 (options?: ToolsOptions): Promise<DescriptorTools<TServer>>
127 /**
128 * Explicit: bind these TanStack toolDefinitions to the server (typed +
129 * validated, allowlist). Note: the runtime tool name is `toolName(tool)`
130 * when the client sets `toolName`, else `${prefix}_${def.name}` with a
131 * `prefix`. The static `TName` stays the definition name.
132 */
133 <const TDefs extends ReadonlyArray<AnyToolDefinition>>(
134 defs: TDefs,
135 options?: ToolsOptions,
136 ): Promise<MappedServerTools<TDefs>>
137 }
138 resources: () => Promise<Array<Resource>>
139 /**
140 * Reads one resource. With a typed server, `uri` is one of its resource URIs.
141 */
142 readResource: (
143 uri: TServer['resources'][keyof TServer['resources']]['uri'],
144 ) => Promise<ReadResourceResult>
145 resourceTemplates: () => Promise<Array<ResourceTemplateType>>
146 prompts: () => Promise<Array<Prompt>>
147 /**
148 * Renders one prompt. With a typed server, `name` is one of its prompt
149 * names and `args` has that prompt's argument type. MCP sends each
150 * argument as a string.
151 */
152 getPrompt: <TName extends keyof TServer['prompts'] & string>(
153 name: TName,
154 args?: TServer['prompts'][TName]['args'],
155 ) => Promise<GetPromptResult>
156 /**
157 * Call a tool directly and return its raw MCP result. Tools declaring
158 * `execution.taskSupport: 'required'` automatically use task execution when
159 * the server declares the tasks capability for tools/call. Pass
160 * `options.signal` to abort — an in-flight task is best-effort cancelled on
161 * the server.
162 *
163 * With a typed server, `name` is one of its tool names and `args` has
164 * that tool's input type. The result is the raw MCP result. For a tool
165 * with an output schema, `structuredContent` has the tool output type.
166 */
167 callTool: <TName extends keyof TServer['tools'] & string>(
168 name: TName,
169 args?: TServer['tools'][TName]['input'],
170 options?: { signal?: AbortSignal },
171 ) => Promise<TypedCallToolResult<TServer['tools'][TName]['output']>>
172 /**
173 * Sends one request with the SDK `Client.request`, with the same
174 * arguments. Use it for a method this client has no helper for, such as
175 * a method of an MCP extension. Pass a result schema as the second
176 * argument for a method that is not in the MCP spec. The client's
177 * `requestOptions` apply under the options you pass.
178 */
179 request: Client['request']
180 /**
181 * The ORIGINAL connection descriptor this client was created from — the
182 * `transport` input and `prefix` passed to `createMCPClient`. Used by
183 * `createMcpAppCallHandler` to reconnect per-call (serverless-safe) without
184 * a separate transport-config map.
185 *
186 * `transport` is `undefined` when the client was built from a ready-made
187 * `Transport` instance rather than a serializable config — either via
188 * `createMCPClientFromTransport` (test-only) or `createMCPClient({ transport:
189 * <instance> })`. A live `Transport` instance is single-use and cannot be
190 * reconnected, so only serializable `TransportConfig`s are retained here.
191 */
192 getInfo: () => {
193 transport: TransportConfig | undefined
194 prefix: string | undefined
195 /**
196 * The options this client was built with, so a caller that reconstructs it
197 * from this descriptor keeps them. Without it a rebuilt client silently
198 * reverts to the SDK defaults — including the AJV validator that edge
199 * runtimes cannot compile.
200 *
201 * Optional so an existing hand-rolled `MCPClient` keeps compiling.
202 */
203 clientOptions?: ClientOptions
204 toolFilter?: MCPClientOptions['toolFilter']
205 needsApproval?: MCPClientOptions['needsApproval']
206 toolName?: MCPClientOptions['toolName']
207 requestOptions?: MCPClientOptions['requestOptions']
208 }
209 close: () => Promise<void>
210 [Symbol.asyncDispose]: () => Promise<void>
211 /**
212 * MCP Events (SEP-3415). Always present after `createMCPClient` connects
213 * over a transport. Optional so a hand-rolled `MCPClient` keeps compiling.
214 *
215 * Managed mode narrows this to {@link ManagedMCPEvents} via overloads.
216 *
217 * @experimental
218 */
219 readonly experimental_events?: MCPEvents
221​
222/**
223 * Client created with `experimental_events: { adapter }`.
224 *
225 * @experimental
226 */
227export type ManagedMCPClient<
228 TDescriptor extends ServerDescriptor = AutomaticDescriptor,
229> = Omit<MCPClient<TDescriptor>, 'experimental_events'> & {
230 readonly experimental_events: ManagedMCPEvents
232​
233class MCPClientImpl<TServer extends ServerDescriptor> implements Omit<
234 MCPClient<TServer>,
235 'experimental_events'
236> {
237 capabilities: TServer['capabilities'] = {}
238 instructions: string | undefined
239 experimental_events?: MCPEvents | ManagedMCPEvents
240 readonly #client: Client
241 #closed = false
242 // Set when connect succeeds. A close before that is a failed connect.
243 #connected = false
244 readonly #events: ClientEvents
245 #toolDefinitions?: Map<string, McpToolDef>
246 // Open only after a spec 2026 connect when the server can report tool changes.
247 #toolListSubscription?: McpSubscription
248 private readonly prefix?: string
249 // The ORIGINAL serializable transport config (undefined for clients built
250 // from a ready-made Transport instance, which is single-use / not reconnectable).
251 readonly #transport: TransportConfig | undefined
252 // Retained for the same reason as #transport: the MCP Apps call handler
253 // rebuilds a client per call from getInfo(), and a rebuilt client that lost
254 // `jsonSchemaValidator` falls straight back to AJV.
255 readonly #clientOptions: ClientOptions | undefined
256 readonly #policy: ToolPolicy
257 readonly #eventsOptions?: MCPEventsOptions
258 readonly #eventsTransport: MCPEventAdapterTransport
259 readonly #managedOps?: MCPEventOperations
260​
261 constructor(
262 prefix?: string,
263 name = 'tanstack-ai-mcp',
264 version = '0.0.1',
265 transport?: TransportConfig,
266 clientOptions?: ClientOptions,
267 policy: ToolPolicy = {},
268 onElicit?: OnElicit,
269 events: ClientEvents = {},
270 eventsSetup?: {
271 options?: MCPEventsOptions
272 transport: MCPEventAdapterTransport
273 },
274 ) {
275 this.prefix = prefix
276 this.#transport = transport
277 this.#clientOptions = clientOptions
278 this.#policy = policy
279 this.#events = events
280 this.#eventsOptions = eventsSetup?.options
281 this.#eventsTransport = eventsSetup?.transport ?? { type: 'custom' }
282 this.#managedOps = bindManagedOperations(
283 eventsSetup?.options,
284 this.#eventsTransport,
285 )
286 const capabilities = {
287 elicitation: { form: {} },
288 sampling: {},
289 ...clientOptions?.capabilities,
290 }
291 // Try spec 2026-07-28 first. If the server does not support it, the
292 // client uses the 2025 initialize handshake. Caller options still apply.
293 // `mode` stays `auto` even when `clientOptions` sets another mode.
294 // A spec 2026 server returns `input_required` only to a client that
295 // declares elicitation and sampling. `chat()` turns that result into an
296 // `mcp_input` interrupt, so the client declares both by default.
297 this.#client = new Client(
298 { name, version },
299 {
300 ...clientOptions,
301 capabilities:
302 eventsSetup?.options === undefined
303 ? capabilities
304 : withEventsClientCapability(capabilities),
305 versionNegotiation: {
306 ...clientOptions?.versionNegotiation,
307 mode: 'auto',
308 },
309 },
310 )
311 // A spec 2025 server asks for input with a request to the client.
312 if (onElicit) {
313 this.#client.setRequestHandler('elicitation/create', (request) =>
314 onElicit(request.params),
315 )
316 }
317 }
318​
319 getInfo(): {
320 transport: TransportConfig | undefined
321 prefix: string | undefined
322 clientOptions?: ClientOptions
323 toolFilter?: MCPClientOptions['toolFilter']
324 needsApproval?: MCPClientOptions['needsApproval']
325 toolName?: MCPClientOptions['toolName']
326 requestOptions?: MCPClientOptions['requestOptions']
327 } {
328 const { toolFilter, needsApproval, toolName, requestOptions } = this.#policy
329 return {
330 transport: this.#transport,
331 prefix: this.prefix,
332 ...(this.#clientOptions ? { clientOptions: this.#clientOptions } : {}),
333 ...(toolFilter ? { toolFilter } : {}),
334 ...(needsApproval ? { needsApproval } : {}),
335 ...(toolName ? { toolName } : {}),
336 ...(requestOptions ? { requestOptions } : {}),
337 }
338 }
339​
340 async connect(transport: Transport, prior?: PriorDiscovery): Promise<void> {
341 try {
342 // A tools/list_changed notice drops the cached definitions so the next
343 // callTool reads each tool's execution mode again.
344 this.#client.setNotificationHandler(
345 'notifications/tools/list_changed',
346 () => {
347 this.#toolDefinitions = undefined
348 this.#events.onToolListChanged?.()
349 },
350 )
351 // The SDK calls `onclose` for every close, also for our own `close()`.
352 // Only a close that this client did not start is reported.
353 this.#client.onclose = () => {
354 const isDropped = this.#connected && !this.#closed
355 if (isDropped) this.#events.onClose?.()
356 }
357 // The connect handshake gets the request options too, so `timeout`
358 // also limits a server that does not answer while it connects.
359 // With `prior`, the SDK skips the server/discover probe and sends
360 // nothing here, so a dead or unauthorized server fails on first use.
361 await this.#client.connect(transport, {
362 ...sdkRequestOptions(this.#policy.requestOptions),
363 prior,
364 })
365 this.capabilities = this.#client.getServerCapabilities() ?? {}
366 this.instructions = this.#client.getInstructions()
367 this.experimental_events = this.#createEventsApi()
368 // A failed listen only means that tool changes are not pushed.
369 // The connection still works, so the error does not fail connect.
370 await this.#listenForToolListChanges().catch(() => undefined)
371 this.#connected = true
372 } catch (err) {
373 await this.#toolListSubscription?.close().catch(() => undefined)
374 await this.#client.close().catch(() => undefined)
375 throw new MCPConnectionError('Failed to connect to MCP server', err)
376 }
377 }
378​
379 // Spec 2026 does not push tool-list changes. Open subscriptions/listen when
380 // the server says it can report them. The notice handler above drops the cache.
381 async #listenForToolListChanges() {
382 if (this.#client.getProtocolEra() !== 'modern') return
383 const tools = this.#client.getServerCapabilities()?.tools
384 if (tools?.listChanged !== true) return
385 this.#toolListSubscription = await this.#client.listen({
386 toolsListChanged: true,
387 })
388 }
389​
390 // Read every tools/list page into the definition cache.
391 // listPages throws when a cursor repeats or the page cap is passed.
392 // A raw list does not compile `jsonSchemaValidator`. On spec 2025, SDK
393 // `callTool` then skips output checks. So `tools()` follows the raw walk
394 // with `listTools()` to fill the SDK cache and run the validator.
395 // Spec 2026 calls pass the listed input schema to `callTool` for the
396 // Mcp-Param-* headers, and do not read that cache. So the second walk is
397 // skipped there.
398 // `raw: true` is the lazy `callTool` path. It must stay free of that cache.
399 async #listTools(options?: { raw?: boolean }) {
400 const client = this.#client
401 const requestOptions = sdkRequestOptions(this.#policy.requestOptions)
402 const defs = await listPages(async (cursor) => {
403 const page =
404 cursor === undefined
405 ? await client.request({ method: 'tools/list' }, requestOptions)
406 : await client.request(
407 { method: 'tools/list', params: { cursor } },
408 requestOptions,
409 )
410 return { items: page.tools, nextCursor: page.nextCursor }
411 })
412 this.#toolDefinitions = new Map(defs.map((def) => [def.name, def]))
413 if (options?.raw !== true && client.getProtocolEra() !== 'modern') {
414 await client.listTools(undefined, requestOptions)
415 }
416 return defs
417 }
418​
419 async tools(
420 defsOrOptions?: ReadonlyArray<AnyToolDefinition> | ToolsOptions,
421 maybeOptions: ToolsOptions = {},
422 ): Promise<Array<McpServerTool>> {
423 if (this.#closed) throw new MCPConnectionError('MCP client is closed')
424​
425 const isDefs = Array.isArray(defsOrOptions)
426 const options: ToolsOptions = isDefs
427 ? maybeOptions
428 : // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
429 ((defsOrOptions as ToolsOptions) ?? {}) // SDK interop: defsOrOptions may be undefined at runtime even though TS types it as ToolsOptions here
430​
431 const { toolFilter, needsApproval, toolName, requestOptions } = this.#policy
432 const listed = await this.#listTools()
433 const defs = applyToolFilter(
434 listed,
435 toolFilter,
436 serverSupportsTaskCalls(this.#client),
437 )
438​
439 let tools: Array<McpServerTool>
440 if (isDefs) {
441 // Explicit path: bind each TanStack toolDefinition to the server by name.
442 const available = new Map(defs.map((tool) => [tool.name, tool]))
443 tools = (defsOrOptions as ReadonlyArray<AnyToolDefinition>).map((def) => {
444 const serverTool = available.get(def.name)
445 if (!serverTool) throw new MCPToolNotFoundError(def.name)
446 // A task-required tool on a server without the tasks capability for
447 // tools/call cannot be invoked (every call fails) — refuse the binding.
448 if (
449 requiresTaskExecution(serverTool) &&
450 !serverSupportsTaskCalls(this.#client)
451 ) {
452 throw new MCPTaskRequiredToolError(def.name)
453 }
454 const bound = def.server(
455 makeMcpExecute(
456 this.#client,
457 def.name,
458 Boolean(def.outputSchema),
459 requiresTaskExecution(serverTool),
460 requestOptions,
461 serverTool.inputSchema,
462 ),
463 ) as ServerTool
464 // A caller-supplied definition may already carry its own `mcp` block,
465 // and `metadata.mcp` is untyped there — only spread it when it really
466 // is a plain object.
467 const existingMcp: unknown = bound.metadata?.mcp
468 const mcpBase =
469 existingMcp !== null && typeof existingMcp === 'object'
470 ? existingMcp
471 : {}
472 // Rebuilt rather than mutated in place: assigning `metadata` on a
473 // `ServerTool` can't narrow its declared `Record<string, any> |
474 // undefined` type, so a fresh literal is what lets the return value be
475 // an `McpServerTool` (typed `metadata.mcp`) without a cast.
476 //
477 // Stamping MCP metadata lets `serverToolNameOf` (and the call handler)
478 // recover the UNPREFIXED native name + serverId, and carries the
479 // server's display title / annotations to the host — mirrors
480 // toServerTools.
481 // `toolName` wins over the prefix. metadata.mcp keeps the server name.
482 const name =
483 toolName?.(serverTool) ??
484 (this.prefix ? `${this.prefix}_${def.name}` : def.name)
485 const tool: McpServerTool = {
486 ...bound,
487 name,
488 ...(options.lazy ? { lazy: true } : {}),
489 metadata: {
490 ...bound.metadata,
491 mcp: { ...mcpBase, ...toolMcpMetadata(serverTool, this.prefix) },
492 },
493 }
494 return tool
495 })
496 } else {
497 // Auto-discovery path.
498 tools = toServerTools(this.#client, defs, {
499 prefix: this.prefix,
500 toolName,
501 lazy: options.lazy,
502 needsApproval,
503 requestOptions,
504 })
505 }
506​
507 // Local duplicate guard (within one client's own list — applies to both branches).
508 const seen = new Set<string>()
509 for (const t of tools) {
510 if (seen.has(t.name)) throw new DuplicateToolNameError(t.name)
511 seen.add(t.name)
512 }
513 return tools
514 }
515​
516 async resources(): Promise<Array<Resource>> {
517 if (this.#closed) throw new MCPConnectionError('MCP client is closed')
518 const options = sdkRequestOptions(this.#policy.requestOptions)
519 return (await this.#client.listResources(undefined, options)).resources
520 }
521​
522 async readResource(uri: string): Promise<ReadResourceResult> {
523 if (this.#closed) throw new MCPConnectionError('MCP client is closed')
524 const options = sdkRequestOptions(this.#policy.requestOptions)
525 return this.#client.readResource({ uri }, options)
526 }
527​
528 async resourceTemplates(): Promise<Array<ResourceTemplateType>> {
529 if (this.#closed) throw new MCPConnectionError('MCP client is closed')
530 const options = sdkRequestOptions(this.#policy.requestOptions)
531 return (await this.#client.listResourceTemplates(undefined, options))
532 .resourceTemplates
533 }
534​
535 async prompts(): Promise<Array<Prompt>> {
536 if (this.#closed) throw new MCPConnectionError('MCP client is closed')
537 const options = sdkRequestOptions(this.#policy.requestOptions)
538 return (await this.#client.listPrompts(undefined, options)).prompts
539 }
540​
541 async getPrompt(name: string, args?: unknown): Promise<GetPromptResult> {
542 if (this.#closed) throw new MCPConnectionError('MCP client is closed')
543 // MCP prompt arguments are strings.
544 const promptArgs = isArgs(args)
545 ? Object.fromEntries(
546 Object.entries(args).map(([key, value]) => [key, String(value)]),
547 )
548 : undefined
549 const options = sdkRequestOptions(this.#policy.requestOptions)
550 return this.#client.getPrompt({ name, arguments: promptArgs }, options)
551 }
552​
553 async callTool<TName extends keyof TServer['tools'] & string>(
554 name: TName,
555 args?: TServer['tools'][TName]['input'],
556 options?: { signal?: AbortSignal },
557 ): Promise<TypedCallToolResult<TServer['tools'][TName]['output']>> {
558 if (this.#closed) throw new MCPConnectionError('MCP client is closed')
559 if (!this.#toolDefinitions) {
560 // Lazy discovery so task-required tools work without a prior tools()
561 // call. Best-effort: a server whose tools/list fails (or omits the
562 // tool) still gets the plain tools/call it would have received before
563 // task support existed. See #listTools.
564 try {
565 await this.#listTools({ raw: true })
566 } catch {
567 // fall through to a plain tools/call
568 }
569 }
570 const definition = this.#toolDefinitions?.get(name)
571 const taskRequired =
572 definition !== undefined && requiresTaskExecution(definition)
573 // A known task-required tool on a server without the tasks capability can
574 // never execute — fail with the clear local error rather than the server's
575 // opaque -32600 (mirrors the tools([...defs]) binding guard).
576 if (taskRequired && !serverSupportsTaskCalls(this.#client)) {
577 throw new MCPTaskRequiredToolError(name)
578 }
579 const result = await callMcpTool(
580 this.#client,
581 name,
582 isArgs(args) ? args : {},
583 taskRequired,
584 options?.signal,
585 undefined,
586 this.#policy.requestOptions,
587 definition?.inputSchema,
588 )
589 // Trust boundary: the server type says what `structuredContent` holds.
590 // The client does not check the wire value against that type.
591 return result as TypedCallToolResult<TServer['tools'][TName]['output']>
592 }
593​
594 // The SDK method is overloaded: (request, options?) for a spec method, and
595 // (request, resultSchema, options?) for any other. This takes both shapes
596 // and forwards the same one, so the casts to the SDK types are safe.
597 request = (async (
598 request: McpRequest,
599 schemaOrOptions?: StandardSchemaV1 | RequestOptions,
600 options?: RequestOptions,
601 ) => {
602 if (this.#closed) throw new MCPConnectionError('MCP client is closed')
603 const defaults = sdkRequestOptions(this.#policy.requestOptions)
604 if (schemaOrOptions !== undefined && '~standard' in schemaOrOptions) {
605 return this.#client.request(request, schemaOrOptions, {
606 ...defaults,
607 ...options,
608 })
609 }
610 return this.#client.request(
611 request as { method: RequestMethod; params?: Record<string, unknown> },
612 { ...defaults, ...schemaOrOptions },
613 )
614 }) as Client['request']
615​
616 getDiscoverResult(): DiscoverResult | undefined {
617 return this.#client.getDiscoverResult()
618 }
619​
620 async close(): Promise<void> {
621 if (this.#closed) return
622 this.#closed = true
623 const subscription = this.#toolListSubscription
624 this.#toolListSubscription = undefined
625 try {
626 await subscription?.close()
627 } finally {
628 await this.#client.close()
629 }
630 }
631​
632 async [Symbol.asyncDispose](): Promise<void> {
633 await this.close()
634 }
635​
636 #createEventsApi(): MCPEvents | ManagedMCPEvents {
637 const ctx = this.#eventsContext()
638 if (this.#managedOps !== undefined) {
639 return createManagedMCPEvents(ctx, this.#managedOps)
640 }
641 if (
642 this.#eventsOptions !== undefined &&
643 isDirectEvents(this.#eventsOptions)
644 ) {
645 return createDirectMCPEvents(ctx, this.#eventsOptions)
646 }
647 return createDiscoveryMCPEvents(ctx)
648 }
649​
650 #eventsContext(): MCPEventsContext {
651 return {
652 assertOpen: () => {
653 if (this.#closed) throw new MCPConnectionError('MCP client is closed')
654 },
655 supportsEvents: serverSupportsEvents(this.capabilities),
656 transport: this.#eventsTransport,
657 request: (method, params, schema, signal) =>
658 this.#client.request(
659 { method, params },
660 schema,
661 sdkRequestOptions(this.#policy.requestOptions, signal),
662 ),
663 }
664 }
666​
667function isArgs(value: unknown): value is Record<string, unknown> {
668 return typeof value === 'object' && value !== null && !Array.isArray(value)
670​
671/**
672 * Applies the client `toolFilter` to the listed tools.
673 * A function keeps the tools it returns `true` for.
674 * A list keeps exactly the listed tools, in list order. A missing or
675 * repeated name throws `MCPToolFilterError`. A listed tool that needs a task
676 * on a server without task support throws `MCPTaskRequiredToolError`.
677 */
678function applyToolFilter(
679 listed: Array<McpToolDef>,
680 toolFilter: MCPClientOptions['toolFilter'],
681 supportsTasks: boolean,
682): Array<McpToolDef> {
683 if (toolFilter === undefined) return listed
684 if (typeof toolFilter === 'function') {
685 return listed.filter((def) => toolFilter(def))
686 }
687 const byName = new Map(listed.map((def) => [def.name, def]))
688 const seen = new Set<string>()
689 const repeated = new Set<string>()
690 const missing: Array<string> = []
691 const kept: Array<McpToolDef> = []
692 for (const name of toolFilter) {
693 if (seen.has(name)) {
694 repeated.add(name)
695 continue
696 }
697 seen.add(name)
698 const def = byName.get(name)
699 if (def === undefined) missing.push(name)
700 else kept.push(def)
701 }
702 if (missing.length > 0 || repeated.size > 0) {
703 throw new MCPToolFilterError({
704 missing,
705 repeated: [...repeated],
706 available: listed.map((def) => def.name),
707 })
708 }
709 const unsupported = kept.find(
710 (def) => requiresTaskExecution(def) && !supportsTasks,
711 )
712 if (unsupported !== undefined) {
713 throw new MCPTaskRequiredToolError(unsupported.name)
714 }
715 return kept
717​
718/**
719 * Connects to an MCP server.
720 *
721 * Pass `transport` for a server at a URL, on SSE, or on stdio.
722 * The client speaks MCP over that transport, so server auth applies.
723 *
724 * To type a transport client from a TanStack server, pass `typeof server`
725 * as the type argument. Import the server with `import type`.
726 *
727 * Pass `server` to call a `createMCPServer` result in this process.
728 * That client calls the tool functions directly. It opens no connection,
729 * and the server `auth` option does not run.
730 *
731 * @param options - A transport, or a TanStack MCP server in this process
732 *
733 * @example
734 * ```ts
735 * const remote = await createMCPClient<typeof server>({
736 * transport: { type: 'http', url: 'https://mcp.example.com/mcp' },
737 * })
738 * await remote.callTool('get_weather', { city: 'Paris' })
739 *
740 * const local = await createMCPClient({ server })
741 * await local.callTool('get_weather', { city: 'Paris' })
742 * ```
743 */
744export async function createMCPClient<
745 TDescriptor extends ServerDescriptor = AutomaticDescriptor,
746>(
747 options: MCPClientOptions & { experimental_events: ManagedMCPEventsOptions },
748): Promise<ManagedMCPClient<TDescriptor>>
749export async function createMCPClient<TServer extends MCPServer>(
750 options: MCPClientOptions & { experimental_events: ManagedMCPEventsOptions },
751): Promise<ManagedMCPClient<DescriptorFromServer<TServer>>>
752export async function createMCPClient<TServer extends MCPServer>(
753 options: DirectClientOptions<TServer>,
754): Promise<DirectMCPClient<TServer>>
755export async function createMCPClient<
756 TDescriptor extends ServerDescriptor = AutomaticDescriptor,
757>(
758 options: MCPClientOptions,
759): Promise<MCPClient<TDescriptor> & { readonly experimental_events: MCPEvents }>
760export async function createMCPClient<TServer extends MCPServer>(
761 options: MCPClientOptions,
762): Promise<
763 MCPClient<DescriptorFromServer<TServer>> & {
764 readonly experimental_events: MCPEvents
765 }
767export async function createMCPClient(
768 options: MCPClientOptions | DirectClientOptions<MCPServer>,
769): Promise<MCPClient | ManagedMCPClient | DirectMCPClient<MCPServer>> {
770 if ('server' in options) {
771 return directMCPClient(options.server)
772 }
773 return connectTransport(options)
775​
776/** Answers a spec 2025 `elicitation/create` request. */
777export type OnElicit = (
778 params: ElicitRequest['params'],
779) => Promise<ElicitResult>
780​
781/**
782 * Connects a client to a transport. The harness passes `onElicit` to answer
783 * the `elicitation/create` requests of spec 2025 servers. `options.onClose`
784 * and `options.onToolListChanged` get the events of the connection.
785 */
786export async function connectTransport<
787 TServer extends ServerDescriptor = AutomaticDescriptor,
788>(options: MCPClientOptions, onElicit?: OnElicit) {
789 const transport = await resolveTransport(options.transport, {
790 events: options.experimental_events !== undefined,
791 })
792 const impl = new MCPClientImpl<TServer>(
793 options.prefix,
794 options.name,
795 options.version,
796 // Only a serializable config is reconnectable; a ready-made Transport
797 // instance is single-use, so it is not retained as a descriptor.
798 isTransportInstance(options.transport) ? undefined : options.transport,
799 options.clientOptions,
800 {
801 toolFilter: options.toolFilter,
802 needsApproval: options.needsApproval,
803 toolName: options.toolName,
804 requestOptions: options.requestOptions,
805 },
806 onElicit,
807 {
808 onClose: options.onClose,
809 onToolListChanged: options.onToolListChanged,
810 },
811 {
812 options: options.experimental_events,
813 transport: eventsTransportOf(options.transport),
814 },
815 )
816 await impl.connect(transport, options.prior)
817 return impl as MCPClient<TServer> & {
818 readonly experimental_events: MCPEvents | ManagedMCPEvents
819 }
821​
822/** Test-only: connect directly from a transport instance (skips resolveTransport). */
823export async function createMCPClientFromTransport<
824 TServer extends ServerDescriptor = AutomaticDescriptor,
825>(
826 transport: Transport,
827 prefix?: string,
828 clientOptions?: ClientOptions,
829): Promise<MCPClient<TServer>> {
830 const impl = new MCPClientImpl<TServer>(
831 prefix,
832 undefined,
833 undefined,
834 undefined,
835 clientOptions,
836 )
837 await impl.connect(transport)
838 return impl as MCPClient<TServer>
840​
841function isDirectEvents(
842 options: MCPEventsOptions,
843): options is DirectMCPEventsOptions {
844 return options.store !== undefined
846​
847function eventsTransportOf(input: TransportInput): MCPEventAdapterTransport {
848 if (isTransportInstance(input)) return { type: 'custom' }
849 if (input.type === 'http') return { type: 'http', url: input.url }
850 if (input.type === 'sse') return { type: 'sse', url: input.url }
851 return { type: 'custom' }
853​
854function bindManagedOperations(
855 options: MCPEventsOptions | undefined,
856 transport: MCPEventAdapterTransport,
857): MCPEventOperations | undefined {
858 if (options === undefined) return undefined
859 const hasStore = options.store !== undefined
860 const hasAdapter = options.adapter !== undefined
861 if (hasStore && hasAdapter) {
862 throw new MCPEventConfigError(
863 'experimental_events cannot include both store and adapter',
864 )
865 }
866 if (!hasStore && !hasAdapter) {
867 throw new MCPEventConfigError(
868 'experimental_events requires store or adapter',
869 )
870 }
871 if (!hasAdapter) return undefined
872 const adapter = options.adapter
873 if (typeof adapter.createAdapter !== 'function') {
874 throw new MCPEventConfigError('adapter is missing createAdapter')
875 }
876 return validateMCPEventOperations(adapter.createAdapter({ transport }))