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

client.ts

668 lines24.5 KB

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