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