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

mcp-advanced.md

668 lines25.5 KB

1---
2title: "MCP Server Tools: Advanced"
3id: mcp-advanced
4order: 13
5description: "Every option of the TanStack AI MCP client: OAuth, custom transports, timeouts, type safety, tool annotations, tool filters, pools, lifecycle, tool names, lazy discovery, and errors."
6keywords:
7 - tanstack ai
8 - mcp
9 - model context protocol
10 - mcp client
11 - createMCPClient
12 - createMCPClients
13 - toolFilter
14 - needsApproval
15 - oauth
16---
17​
18This page is the reference for `createMCPClient` and `createMCPClients`. To connect your first server, start at [MCP Server Tools](./mcp).
19​
20## Authentication
21​
22### Static tokens (headers)
23​
24If the server takes an API key or a bearer token, pass `headers` on the `http` or `sse` transport. The client sends them with each request:
25​
26```ts
27import { createMCPClient } from '@tanstack/ai-mcp'
28​
29const mcp = await createMCPClient({
30 transport: {
31 type: 'http',
32 url: 'https://my-mcp-server.example.com/mcp',
33 headers: { Authorization: `Bearer ${process.env.MCP_TOKEN}` },
34 },
35})
36```
37​
38### OAuth (`authProvider`)
39​
40If the server uses the [MCP authorization spec](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization) (OAuth 2.1), pass an `authProvider` on the `http` or `sse` transport. The value is an `OAuthClientProvider` from `@modelcontextprotocol/client`.
41​
42The transport does these steps for you:
43​
44- It attaches the token.
45- It refreshes the token.
46- It sends the request again on a 401.
47​
48```ts ignore
49import { createMCPClient } from '@tanstack/ai-mcp'
50import type { OAuthClientProvider } from '@modelcontextprotocol/client'
51import { myTokenStore } from './token-store'
52​
53// Server-side: back the provider with tokens you persist (database, KV, ...).
54// `tokens()` returning a valid (or refreshable) token set is all the SDK
55// needs to authenticate requests.
56const myOAuthProvider: OAuthClientProvider = myTokenStore.provider()
57​
58const mcp = await createMCPClient({
59 transport: {
60 type: 'http',
61 url: 'https://my-mcp-server.example.com/mcp',
62 authProvider: myOAuthProvider,
63 },
64})
65```
66​
67For a provider with stored tokens and a working refresh, this form is all you need.
68​
69An interactive redirect flow needs one more step. After the redirect, you must call `finishAuth(code)` on the transport. `createMCPClient` makes the transport internally, so you cannot reach it. Make the transport yourself instead:
70​
711. Make a `StreamableHTTPClientTransport` with your `authProvider`, and keep a reference to it.
722. In your OAuth callback route, call `transport.finishAuth(code)`.
733. Pass the transport to `createMCPClient({ transport })`. See [Custom transport](#custom-transport).
74​
75## Custom transport
76​
77You can pass any `Transport` instance as the `transport` option. For tests in the same process, `@tanstack/ai-mcp` exports `InMemoryTransport`:
78​
79```ts
80import { createMCPClient, InMemoryTransport } from '@tanstack/ai-mcp'
81​
82const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair()
83const mcp = await createMCPClient({ transport: clientTransport })
84```
85​
86For a custom network transport, pass a `Transport` from `@modelcontextprotocol/client`:
87​
88```ts ignore
89import { StreamableHTTPClientTransport } from '@modelcontextprotocol/client'
90​
91const transport = new StreamableHTTPClientTransport(new URL('https://example.com/mcp'))
92const mcp = await createMCPClient({ transport })
93```
94​
95## Timeouts
96​
97By default, each request waits up to 60 seconds, then fails. A long tool, such as a report or a build, fails at that limit too.
98​
99Set `requestOptions` to change the limit. It applies to the connect handshake, tool lists, tool calls, resource requests, and prompt requests:
100​
101```ts
102import { createMCPClient } from '@tanstack/ai-mcp'
103​
104const mcp = await createMCPClient({
105 transport: { type: 'http', url: 'https://my-mcp-server.example.com/mcp' },
106 requestOptions: {
107 // Wait up to 2 minutes for each request.
108 timeout: 120_000,
109 // Start the 2 minutes again each time the server reports progress.
110 resetTimeoutOnProgress: true,
111 },
112})
113```
114​
115- `timeout`: the limit in milliseconds. The SDK default is 60,000.
116- `resetTimeoutOnProgress`: start the timeout again when the server sends a progress notification. A tool call on protocol `2026-07-28` gets no progress notifications, so only `timeout` applies there.
117​
118Edge cases:
119​
120- On a `stdio` server, connect can take up to two times `timeout`. When the version check runs out of time, the SDK tries the older handshake with its own `timeout`.
121- The `subscriptions/listen` stream and task status polls keep the SDK defaults.
122- A request that runs out of time throws an `SdkError` from `@modelcontextprotocol/client`, with the code `SdkErrorCode.RequestTimeout`.
123​
124Each server in a [pool](#multi-server-pool) can have its own `requestOptions`. [MCP Apps](../mcp/apps) widget calls use the options of the same client.
125​
126## Three Modes of Type Safety
127​
128### Mode 1: auto-discovery
129​
130Call `tools()` with no arguments to get every tool of the server. This needs no setup. The tool arguments have the type `unknown` at compile time. The client uses the MCP JSON Schema to check them at runtime.
131​
132```ts
133import { createMCPClient } from '@tanstack/ai-mcp'
134​
135const mcp = await createMCPClient({
136 transport: { type: 'http', url: 'https://my-mcp-server.example.com/mcp' },
137})
138const tools = await mcp.tools()
139// tools: ServerTool[] (args typed unknown at compile time)
140```
141​
142Some providers reject an object schema without `properties`. To keep those tools working, the client adds defaults:
143​
144- A schema without `properties` gets `properties: {}`.
145- A schema without `type` gets `type: 'object'`.
146- A schema that has both fields does not change.
147​
148MCP schemas often use `$ref` or `oneOf`. On adapters built on the OpenAI API, those tools go out without strict mode, and the adapter warns in development. See [Tools that cannot use strict mode](../adapters/openai-advanced.md#tools-that-cannot-use-strict-mode).
149​
150Task-based tools work too:
151​
152- A tool with `execution.taskSupport: 'required'` runs through the experimental `tasks/callToolStream` flow of the MCP SDK. TanStack AI waits through the task status updates and gives the final result to the model.
153- A tool with `taskSupport: 'optional'` uses a normal `callTool`.
154- Task execution needs the server to declare the tasks capability for `tools/call`. If the server lists a task-required tool without it, auto-discovery skips the tool, because nothing can call it.
155- If the chat run aborts, TanStack AI stops the wait and sends a best-effort `tasks/cancel` for a remote task that the server already made.
156​
157### Mode 2: explicit definitions
158​
159Pass TanStack `toolDefinition()` instances to get full TypeScript types and Zod validation. You get only the named tools back. If a name is not on the server, `tools()` throws `MCPToolNotFoundError`. Task-required tools use the same task execution as Mode 1.
160​
161```ts
162import { toolDefinition } from '@tanstack/ai'
163import { createMCPClient } from '@tanstack/ai-mcp'
164import { z } from 'zod'
165​
166const searchDef = toolDefinition({
167 name: 'search',
168 description: 'Search for items',
169 inputSchema: z.object({ query: z.string() }),
170 outputSchema: z.array(z.object({ id: z.string(), title: z.string() })),
171})
172​
173const mcp = await createMCPClient({
174 transport: { type: 'http', url: 'https://my-mcp-server.example.com/mcp' },
175})
176const tools = await mcp.tools([searchDef])
177// tools[0].execute is typed: (args: { query: string }) => ...
178```
179​
180### Mode 3: generated types
181​
182Run the CLI against a live server to generate an `interface` for each server. Then pass the type as a generic to `createMCPClient`. You get:
183​
184- Tool names narrowed to the literal names of the server.
185- Compile-checked config keys on a pool.
186- No runtime cost.
187​
188Tool arguments stay `unknown` on this path. For typed arguments, use Mode 2 too.
189​
190See [MCP Type Generation](./mcp-codegen) for the `mcp.config.ts` setup, the `generate` CLI, and how to use the types.
191​
192## Tool Titles & Annotations
193​
194An MCP server can send display and behavior data with each tool:
195​
196- `title`: a name for people to read.
197- `annotations`: hints such as `readOnlyHint`, `destructiveHint`, `idempotentHint`, `openWorldHint`, and an older `annotations.title`.
198​
199`@tanstack/ai-mcp` puts this data on `metadata.mcp` of each tool. It does this in Mode 1 and in Mode 2. Use it to label tools in your UI and to pick which tools need a confirmation step.
200​
201| `metadata.mcp` field | Value |
202|---|---|
203| `title` | `string`. The display name, in this order of precedence: the `title` of the tool, then `annotations.title`, then `name`. Always set. |
204| `annotations` | A frozen copy of the `annotations` object of the server. Not set when the server sends none. To change a value, copy it first: `{ ...tool.metadata.mcp.annotations, readOnlyHint: false }`. |
205| `serverToolName` | `string`. The tool name on the server, without a prefix. |
206| `serverId` | The `prefix` of the client. `undefined` when there is no prefix. |
207| `uiResourceUri` | The [MCP Apps](../mcp/apps) widget link, when the tool declares one. |
208​
209`tools()` returns `McpServerTool` items. Each one is a normal `ServerTool`, so it goes into `chat({ tools })` as is. Its `metadata.mcp` has a static type, so you can read it with no cast. A misspelled field is a compile error:
210​
211```ts
212import { createMCPClient } from '@tanstack/ai-mcp'
213​
214const url = 'https://my-mcp-server.example.com/mcp'
215​
216// Trust comes from YOUR configuration (an allowlist of servers that you run
217// or checked), never from anything that the server sends.
218const trustedServers = new Set(['https://my-mcp-server.example.com/mcp'])
219const serverIsTrusted = trustedServers.has(url)
220​
221const mcp = await createMCPClient({ transport: { type: 'http', url } })
222​
223const tools = (await mcp.tools()).map((tool) => {
224 const meta = tool.metadata.mcp
225 const advertisedReadOnly = meta.annotations?.readOnlyHint === true
226 return {
227 ...tool,
228 // Approval is the default. A hint can relax it only on a server that
229 // you trust for other reasons. On any other server, the hint is only
230 // a label, and it does not change approval.
231 needsApproval: !(serverIsTrusted && advertisedReadOnly),
232 }
233})
234```
235​
236> [!WARNING]
237> Do not use annotations as a security boundary. Every field, `title` too, is a hint from the server. A bad server can mark a tool that deletes records with `readOnlyHint: true`.
239> - On a server that you do not trust, a hint must never skip approval, sandboxing, or authorization. Show it as a label only.
240> - On a server that you trust for other reasons, a hint can relax a confirmation step, as in the sample above.
241​
242Titles are for display only:
243​
244- A title never changes the tool `name` that the model gets.
245- A `prefix` applies to the name (`wx_get_weather`), not to the title.
246​
247`McpToolMetadata`, `McpServerTool`, and `ToolAnnotations` (from the MCP SDK) are exported. Use them to name the types in your own signatures. You do not need them to read the data.
248​
249To label tools in your UI, send the data from a server route. The MCP client must stay on the server:
250​
251```ts ignore
252// src/routes/api.mcp-tools.ts
253import { createFileRoute } from '@tanstack/react-router'
254import { createMCPClient } from '@tanstack/ai-mcp'
255​
256export const Route = createFileRoute('/api/mcp-tools')({
257 server: {
258 handlers: {
259 GET: async () => {
260 await using mcp = await createMCPClient({
261 transport: { type: 'http', url: process.env.MCP_URL! },
262 })
263 const catalog = (await mcp.tools()).map((tool) => ({
264 name: tool.name,
265 // `title` is always set. The fallback order already ran.
266 title: tool.metadata.mcp.title,
267 description: tool.description,
268 readOnly: tool.metadata.mcp.annotations?.readOnlyHint === true,
269 }))
270 return Response.json({ tools: catalog })
271 },
272 },
273 },
274})
275```
276​
277```tsx
278// src/components/ToolCatalog.tsx
279import { useEffect, useState } from 'react'
280​
281interface ToolSummary {
282 name: string
283 title: string
284 description?: string
285 readOnly: boolean
287​
288export function ToolCatalog() {
289 const [tools, setTools] = useState<Array<ToolSummary>>([])
290​
291 useEffect(() => {
292 fetch('/api/mcp-tools')
293 .then((res) => res.json())
294 .then((body: { tools: Array<ToolSummary> }) => setTools(body.tools))
295 }, [])
296​
297 return (
298 <ul>
299 {tools.map((tool) => (
300 <li key={tool.name}>
301 {/* Server-declared title, with the hint driving the badge */}
302 <strong>{tool.title}</strong> {tool.readOnly ? '(read-only)' : '(writes)'}
303 <div>{tool.description}</div>
304 </li>
305 ))}
306 </ul>
307 )
309```
310​
311## Limit and Gate Tools
312​
313By default, the model gets every tool that the server lists, and each tool runs without approval. A server can expose tools that write or delete data. Two client options control this:
314​
315- `toolFilter`: a function that returns `false` to hide a tool, or a list of the tool names to keep.
316- `needsApproval`: return `true` to pause the run for [approval](./tool-approval) before each call to the tool.
317​
318Both options are off by default. A `toolFilter` function and `needsApproval` get the tool definition from the server. It has the server `name` (without a prefix), the `title`, and the `annotations`.
319​
320Send only the tools that the server marks read-only:
321​
322```ts
323import { createMCPClient } from '@tanstack/ai-mcp'
324​
325const mcp = await createMCPClient({
326 transport: { type: 'http', url: 'https://my-mcp-server.example.com/mcp' },
327 toolFilter: (tool) => tool.annotations?.readOnlyHint === true,
328})
329​
330const tools = await mcp.tools() // only read-only tools
331```
332​
333A tool with no `annotations` does not pass this filter.
334​
335On a server that you do not trust, list the tools by name. You control the names, and the server controls the hints:
336​
337```ts
338import { createMCPClient } from '@tanstack/ai-mcp'
339​
340const mcp = await createMCPClient({
341 transport: { type: 'http', url: 'https://my-mcp-server.example.com/mcp' },
342 toolFilter: ['search_issues', 'get_issue'],
343})
344​
345const tools = await mcp.tools() // search_issues, then get_issue
346```
347​
348A list is strict:
349​
350- The tools come back in the list order.
351- A name that the server does not have, or a name listed twice, throws `MCPToolFilterError`. Its `missing`, `repeated`, and `available` fields name the tools. A typo fails the `tools()` call, so the model never runs with fewer tools than you expect.
352- A listed tool that needs task execution, on a server without task support, throws `MCPTaskRequiredToolError`.
353- An empty list keeps no tools.
354​
355A function does not fail when a tool is missing. If the tool list of the server can change, use a function.
356​
357Keep every tool, but ask the user before a tool runs:
358​
359```ts
360import { createMCPClient } from '@tanstack/ai-mcp'
361​
362const url = 'https://my-mcp-server.example.com/mcp'
363// Trust comes from your configuration, not from the server.
364const trustedServers = new Set(['https://my-mcp-server.example.com/mcp'])
365const serverIsTrusted = trustedServers.has(url)
366​
367const mcp = await createMCPClient({
368 transport: { type: 'http', url },
369 // A read-only hint skips approval only on a server that you trust.
370 needsApproval: (tool) =>
371 !(serverIsTrusted && tool.annotations?.readOnlyHint === true),
372})
373```
374​
375The run stops with an approval interrupt for each gated call. The client approves or denies it the same way as for any other tool. See [Tool Approval Flow](./tool-approval).
376​
377In a [pool](#multi-server-pool), each server gets its own options:
378​
379```ts
380import { createMCPClients } from '@tanstack/ai-mcp'
381​
382const pool = await createMCPClients({
383 github: {
384 transport: { type: 'http', url: process.env.GITHUB_MCP_URL! },
385 toolFilter: (tool) => tool.annotations?.readOnlyHint === true,
386 },
387 docs: { transport: { type: 'http', url: process.env.DOCS_MCP_URL! } },
388})
389```
390​
391Where the options apply:
392​
393| Call | `toolFilter` | `needsApproval` |
394|---|---|---|
395| `tools()` | Hides tools. | Marks tools. |
396| `tools([...defs])` | Applies. A definition that the filter hides throws `MCPToolNotFoundError`. | Does not apply. Each `toolDefinition` has its own `needsApproval`. |
397| `chat({ mcp })` | Applies, because `chat()` calls `tools()`. See [Managed MCP](./mcp-managed). | Applies. |
398| [MCP Apps](../mcp/apps) widget calls | Applies. A widget cannot call a hidden tool. | Applies. A widget call has no approval step, so a call to a marked tool returns `{ ok: false }`. |
399| `callTool()` | Does not apply. Your code calls the tool, not the model. | Does not apply. |
400​
401> [!WARNING]
402> The hints come from the server. A compromised server can mark a delete tool `readOnlyHint: true`. For a server that you do not trust, use a name list or `needsApproval`.
403​
404If you need to name the type of the `tool` argument, use the exported `McpTool` type.
405​
406## Multi-Server Pool
407​
408`createMCPClients` connects to many servers at the same time and merges their tools into one flat array. Each tool name gets the config key as a prefix, so names from two servers do not collide.
409​
410```ts
411import { createMCPClients } from '@tanstack/ai-mcp'
412​
413const pool = await createMCPClients({
414 github: { transport: { type: 'http', url: process.env.GITHUB_MCP_URL! } },
415 linear: { transport: { type: 'http', url: process.env.LINEAR_MCP_URL! } },
416})
417​
418// tools: [github_search_repos, github_create_issue, linear_create_issue, ...]
419const tools = await pool.tools()
420```
421​
422`pool.tools()` collects the tools of all servers. If two names are the same after the prefix, it throws `DuplicateToolNameError`.
423​
424### Per-server access
425​
426```ts
427import { createMCPClients } from '@tanstack/ai-mcp'
428​
429const pool = await createMCPClients({
430 github: { transport: { type: 'http', url: process.env.GITHUB_MCP_URL! } },
431 linear: { transport: { type: 'http', url: process.env.LINEAR_MCP_URL! } },
432})
433​
434const linearTools = await pool.clients.linear!.tools()
435const resources = await pool.clients.github!.resources()
436```
437​
438### Disable or override the prefix
439​
440```ts
441import { createMCPClients } from '@tanstack/ai-mcp'
442​
443const pool = await createMCPClients({
444 github: {
445 transport: { type: 'http', url: process.env.GITHUB_MCP_URL! },
446 prefix: 'gh', // override: "gh_search_repos"
447 },
448 internal: {
449 transport: { type: 'http', url: process.env.INTERNAL_MCP_URL! },
450 prefix: '', // disable prefix entirely
451 },
452})
453```
454​
455### Closing the pool
456​
457```ts ignore
458await pool.close()
459// or
460await using pool = await createMCPClients({ /* server configs */ })
461```
462​
463If one server fails to connect, the pool closes the clients that did connect, then throws. No connection stays open.
464​
465## Lifecycle
466​
467> [!TIP]
468> If you pass clients to `chat()` in the `mcp` option, you can skip this section. `chat()` closes the connections when the run ends. See [Managed MCP with chat()](./mcp-managed).
469​
470When you spread tools into `tools` yourself, you own the client. `chat()` never closes it.
471​
472Tools run while the response stream is read. So close the client only after the stream is fully read.
473​
474In a route that returns a streaming `Response`, a `try/finally` around the `return` closes the client too early. The same is true for `await using` at function scope. The client closes before the body streams, and tool calls in progress fail. Close it in a middleware hook instead.
475​
476### Streaming route handlers: close via middleware
477​
478After the agent loop ends, exactly one of `onFinish`, `onAbort`, or `onError` runs:
479​
480```ts
481import { chat, toServerSentEventsResponse } from '@tanstack/ai'
482import { openaiText } from '@tanstack/ai-openai'
483import { createMCPClient } from '@tanstack/ai-mcp'
484​
485export async function POST(request: Request) {
486 const { messages, threadId } = await request.json()
487 const url = 'https://my-mcp-server.example.com/mcp'
488 const mcp = await createMCPClient({ transport: { type: 'http', url } })
489 const stream = chat({
490 adapter: openaiText('gpt-6.1-sol'),
491 messages,
492 threadId,
493 tools: await mcp.tools(),
494 middleware: [
495 {
496 name: 'mcp-close',
497 onFinish: () => mcp.close(),
498 onAbort: () => mcp.close(),
499 onError: () => mcp.close(),
500 },
501 ],
502 })
503 return toServerSentEventsResponse(stream)
505```
506​
507### Manual close: when you read the stream in scope
508​
509`try/finally` is correct when you read the full stream before the scope ends:
510​
511```ts
512import { chat } from '@tanstack/ai'
513import { openaiText } from '@tanstack/ai-openai'
514import { createMCPClient } from '@tanstack/ai-mcp'
515​
516const messages = [{ role: 'user' as const, content: 'Hello' }]
517const url = 'https://my-mcp-server.example.com/mcp'
518const mcp = await createMCPClient({ transport: { type: 'http', url } })
519try {
520 const stream = chat({
521 adapter: openaiText('gpt-6.1-sol'),
522 messages,
523 threadId: 'thread-1',
524 tools: await mcp.tools(),
525 })
526 for await (const chunk of stream) {
527 // handle chunks: the stream is fully read inside this block
528 }
529} finally {
530 await mcp.close()
532```
533​
534### `await using` (Explicit Resource Management)
535​
536This needs a runtime with `Symbol.asyncDispose`: Node 18.2+ with TypeScript `target: "es2022"` and `lib: ["esnext"]`. The same rule applies: read the stream in scope. The client closes when the block ends:
537​
538```ts
539import { chat } from '@tanstack/ai'
540import { openaiText } from '@tanstack/ai-openai'
541import { createMCPClient } from '@tanstack/ai-mcp'
542​
543const messages = [{ role: 'user' as const, content: 'Hello' }]
544const url = 'https://my-mcp-server.example.com/mcp'
545await using mcp = await createMCPClient({ transport: { type: 'http', url } })
546const stream = chat({
547 adapter: openaiText('gpt-6.1-sol'),
548 messages,
549 threadId: 'thread-1',
550 tools: await mcp.tools(),
551})
552for await (const chunk of stream) {
553 // handle chunks
555// mcp.close() is called automatically when the block exits
556```
557​
558## Tool Name Collisions
559​
560When you mix tools from many sources, two tools with the same name throw `DuplicateToolNameError`:
561​
562```ts
563import { createMCPClients, DuplicateToolNameError } from '@tanstack/ai-mcp'
564​
565const pool = await createMCPClients({
566 github: { transport: { type: 'http', url: process.env.GITHUB_MCP_URL! } },
567 linear: { transport: { type: 'http', url: process.env.LINEAR_MCP_URL! } },
568})
569​
570try {
571 const tools = await pool.tools()
572} catch (err) {
573 if (err instanceof DuplicateToolNameError) {
574 console.error('Conflicting tool name:', err.toolName)
575 // Fix: set a unique prefix on one of the clients
576 }
578```
579​
580To prevent a collision, give each client a unique `prefix`. `createMCPClients` does this for you with the config key.
581​
582## Name Tools Yourself
583​
584The model gets `<prefix>_<tool>`, or the server tool name when there is no prefix. Some apps need another pattern. For example:
585​
586- A fixed `mcp__<server>__<tool>` form.
587- Names without characters that a provider rejects.
588​
589Pass `toolName`. It gets the tool definition from the server and returns the name that the model gets. It wins over `prefix`:
590​
591```ts
592import { createMCPClient } from '@tanstack/ai-mcp'
593​
594// Keep only letters, digits, `_`, and `-` in the name.
595const clean = (value: string) => value.replace(/[^A-Za-z0-9_-]/g, '_')
596​
597const mcp = await createMCPClient({
598 transport: { type: 'http', url: 'https://my-mcp-server.example.com/mcp' },
599 toolName: (tool) => `mcp__github__${clean(tool.name)}`,
600})
601​
602const tools = await mcp.tools() // mcp__github__search_issues, ...
603```
604​
605- The name applies to `tools()` and to `tools([...defs])`.
606- `metadata.mcp.serverToolName` keeps the server name of the tool. [MCP Apps](../mcp/apps) widget calls use it, and `callTool()` takes it, so both still reach the tool.
607- `metadata.mcp.serverId` is still the client `prefix`.
608- MCP Apps routes widget calls by `prefix`. If you use MCP Apps with `toolName`, keep a `prefix` on each client.
609- Two tools with the same final name throw `DuplicateToolNameError`, in one client and across a pool.
610​
611In a pool, each server gets its own `toolName`:
612​
613```ts
614import { createMCPClients } from '@tanstack/ai-mcp'
615​
616const pool = await createMCPClients({
617 github: {
618 transport: { type: 'http', url: process.env.GITHUB_MCP_URL! },
619 toolName: (tool) => `mcp__github__${tool.name}`,
620 },
621 linear: {
622 transport: { type: 'http', url: process.env.LINEAR_MCP_URL! },
623 toolName: (tool) => `mcp__linear__${tool.name}`,
624 },
625})
626​
627const tools = await pool.tools() // mcp__github__..., mcp__linear__...
628```
629​
630## Lazy Tool Discovery
631​
632A server with many tools sends many schemas to the model, and each schema costs tokens. Pass `{ lazy: true }` to send a schema only when the model asks for it:
633​
634```ts
635import { createMCPClient } from '@tanstack/ai-mcp'
636​
637const mcp = await createMCPClient({
638 transport: { type: 'http', url: 'https://my-mcp-server.example.com/mcp' },
639})
640const tools = await mcp.tools({ lazy: true })
641// All tools are marked lazy: true
642```
643​
644It works on a pool too:
645​
646```ts
647import { createMCPClients } from '@tanstack/ai-mcp'
648​
649const pool = await createMCPClients({
650 github: { transport: { type: 'http', url: process.env.GITHUB_MCP_URL! } },
651 linear: { transport: { type: 'http', url: process.env.LINEAR_MCP_URL! } },
652})
653const tools = await pool.tools({ lazy: true })
654```
655​
656See [Lazy Tool Discovery](./lazy-tool-discovery) for how the model finds lazy tools at runtime.
657​
658## Error Reference
659​
660| Error class | When thrown |
661|---|---|
662| `MCPConnectionError` | `createMCPClient` cannot connect, or you call a method after `close()`. |
663| `DuplicateToolNameError` | Two tools have the same name in one client or across the pool. |
664| `MCPToolNotFoundError` | A `toolDefinition` name passed to `tools([...defs])` is not on the server, or the `toolFilter` of the client hides it. |
665| `MCPToolFilterError` | A `toolFilter` list names a tool that the server does not have, or names a tool twice. In a pool, `pool.tools()` throws `MCPConnectionError` with this error as its `cause`. |
666| `MCPTaskRequiredToolError` | A task-required tool came from `tools([...defs])`, a `toolFilter` list, or `callTool()`, but the server does not declare the tasks capability for `tools/call`. The call can never run. |
667​
668For the `MCPDuplicateToolNameError` that a `chat({ mcp })` run throws when it merges tools from many sources, see [Managed MCP with chat()](./mcp-managed#tool-name-collisions).