Open History to see the last commit
1---
2title: MCP Server Tools
3id: mcp
4order: 8
5description: "Connect TanStack AI to any Model Context Protocol server with createMCPClient to discover and execute its tools."
6keywords:
7 - tanstack ai
8 - mcp
9 - model context protocol
10 - mcp tools
11 - mcp client
12 - server tools
13 - createMCPClient
14 - createMCPClients
15 - type safety
16---
17
18`@tanstack/ai-mcp` is a host-side [Model Context Protocol](https://modelcontextprotocol.io) client for TanStack AI. It connects your server route to any MCP-compliant server and makes that server's tools, resources, and prompts available inside `chat()`.
19
20> MCP tool execution is **server-side only**. The `createMCPClient` call lives in a server route (or serverless function) — never in browser code.
21
22## Server MCP and WebMCP
23
24Server MCP and WebMCP solve different problems.
25
26| Integration | Where it runs | What it does |
27|---|---|---|
28| Server MCP | Your server route | Connects TanStack `chat()` to tools, resources, and prompts from an MCP server. |
29| WebMCP | The browser page | Exposes executable client tools to a browser agent through `document.modelContext`. |
30
31WebMCP calls return directly to the browser agent. They do not become tool results in a TanStack chat run.
32
33See [WebMCP Tools](./webmcp) to expose browser actions. If your server needs MCP server tools, continue with this guide.
34
35## Installation
36
37<!-- ::start:tabs variant="package-manager" mode="install" -->
38
39react: @tanstack/ai-mcp @modelcontextprotocol/client
40vue: @tanstack/ai-mcp @modelcontextprotocol/client
41solid: @tanstack/ai-mcp @modelcontextprotocol/client
42svelte: @tanstack/ai-mcp @modelcontextprotocol/client
43preact: @tanstack/ai-mcp @modelcontextprotocol/client
44angular: @tanstack/ai-mcp @modelcontextprotocol/client
45vanilla: @tanstack/ai-mcp @modelcontextprotocol/client
46octane: @tanstack/ai-mcp @modelcontextprotocol/client
47
48<!-- ::end:tabs -->
49
50> `createMCPClient` tries protocol `2026-07-28` first. If the server does not support that protocol, the client uses the 2025 initialize handshake.
51>
52> Package names for an `@modelcontextprotocol/sdk` import are in [MCP SDK packages](../migration/mcp-sdk).
53
54## Quick Start
55
56The simplest integration is the managed `mcp` option: hand the client to `chat()` and it discovers the tools and closes the connection when the run ends — no lifecycle code at all.
57
58```ts ignore
59// src/routes/api.chat.ts (TanStack Start)
60import { createFileRoute } from '@tanstack/react-router'
61import { chat, toServerSentEventsResponse } from '@tanstack/ai'
62import { openaiText } from '@tanstack/ai-openai'
63import { createMCPClient } from '@tanstack/ai-mcp'
64
65export const Route = createFileRoute('/api/chat')({
66 server: {
67 handlers: {
68 POST: async ({ request }) => {
69 const { messages } = await request.json()
70
71 const mcp = await createMCPClient({
72 transport: {
73 type: 'http',
74 url: 'https://my-mcp-server.example.com/mcp',
75 },
76 })
77
78 // chat() discovers the tools and closes the client when the run ends.
79 const stream = chat({
80 adapter: openaiText('gpt-5.5'),
81 messages,
82 mcp: { clients: [mcp] },
83 })
84
85 return toServerSentEventsResponse(stream)
86 },
87 },
88 },
89})
90```
91
92> Need fully-typed tool arguments, resources, prompts, or your own lifecycle? Spread tools manually instead — see [Manual MCP: typed tools, resources & prompts](./mcp-manual) and the [Lifecycle](#lifecycle) section below.
93
94On the client side, consume the stream with `useChat` exactly as you would any other TanStack AI endpoint:
95
96```tsx
97// src/components/Chat.tsx
98import { useChat } from '@tanstack/ai-react'
99import { fetchServerSentEvents } from '@tanstack/ai-client'
100
101export function Chat() {
102 const { messages, sendMessage, status } = useChat({
103 connection: fetchServerSentEvents('/api/chat'),
104 })
105
106 return (
107 <div>
108 {messages.map((m) => (
109 <div key={m.id}>
110 <strong>{m.role}:</strong>{' '}
111 {m.parts.find((p) => p.type === 'text')?.content}
112 </div>
113 ))}
114 <button
115 onClick={() => sendMessage({ content: 'Hello' })}
116 disabled={status === 'streaming'}
117 >
118 Send
119 </button>
120 </div>
121 )
122}
123```
124
125## Transports
126
127### HTTP (Streamable HTTP)
128
129The preferred transport for remote servers. Uses the MCP Streamable HTTP protocol.
130
131```ts
132import { createMCPClient } from '@tanstack/ai-mcp'
133
134const mcp = await createMCPClient({
135 transport: {
136 type: 'http',
137 url: 'https://my-mcp-server.example.com/mcp',
138 headers: { Authorization: `Bearer ${process.env.MCP_TOKEN}` },
139 },
140})
141```
142
143### SSE (Server-Sent Events)
144
145For servers that implement the legacy SSE transport.
146
147```ts
148import { createMCPClient } from '@tanstack/ai-mcp'
149
150const mcp = await createMCPClient({
151 transport: {
152 type: 'sse',
153 url: 'https://my-mcp-server.example.com/sse',
154 headers: { Authorization: `Bearer ${process.env.MCP_TOKEN}` },
155 },
156})
157```
158
159### stdio (Node.js only)
160
161For spawning a local MCP process. Because stdio imports Node-native modules, it is isolated behind a subpath import so edge bundles stay clean.
162
163```ts
164import { stdioTransport } from '@tanstack/ai-mcp/stdio'
165import { createMCPClient } from '@tanstack/ai-mcp'
166
167const mcp = await createMCPClient({
168 transport: stdioTransport({
169 command: 'node',
170 args: ['./my-mcp-server.js'],
171 env: { API_KEY: process.env.API_KEY ?? '' },
172 }),
173})
174```
175
176### Custom transport (escape hatch)
177
178Pass any `Transport` instance directly as the `transport` option. For in-process testing, `InMemoryTransport` is re-exported from `@tanstack/ai-mcp`:
179
180```ts
181import { createMCPClient, InMemoryTransport } from '@tanstack/ai-mcp'
182
183const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair()
184const mcp = await createMCPClient({ transport: clientTransport })
185```
186
187For a custom network transport, pass a `Transport` from `@modelcontextprotocol/client`:
188
189```ts ignore
190import { StreamableHTTPClientTransport } from '@modelcontextprotocol/client'
191
192const transport = new StreamableHTTPClientTransport(new URL('https://example.com/mcp'))
193const mcp = await createMCPClient({ transport })
194```
195
196## Authentication
197
198### Static tokens (headers)
199
200For servers that take a pre-provisioned API key or bearer token, pass `headers` on the `http`/`sse` transport config — they are sent with every request:
201
202```ts
203import { createMCPClient } from '@tanstack/ai-mcp'
204
205const mcp = await createMCPClient({
206 transport: {
207 type: 'http',
208 url: 'https://my-mcp-server.example.com/mcp',
209 headers: { Authorization: `Bearer ${process.env.MCP_TOKEN}` },
210 },
211})
212```
213
214### OAuth (`authProvider`)
215
216If the server implements the [MCP authorization spec](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization) (OAuth 2.1), pass an `authProvider` on the `http` or `sse` config.
217
218The `authProvider` value is an `OAuthClientProvider` from `@modelcontextprotocol/client`.
219
220The transport attaches the token. The transport refreshes the token. The transport retries the request on 401.
221
222```ts ignore
223import { createMCPClient } from '@tanstack/ai-mcp'
224import type { OAuthClientProvider } from '@modelcontextprotocol/client'
225import { myTokenStore } from './token-store'
226
227// Server-side: back the provider with tokens you persist (database, KV, ...).
228// `tokens()` returning a valid (or refreshable) token set is all the SDK
229// needs to authenticate requests.
230const myOAuthProvider: OAuthClientProvider = myTokenStore.provider()
231
232const mcp = await createMCPClient({
233 transport: {
234 type: 'http',
235 url: 'https://my-mcp-server.example.com/mcp',
236 authProvider: myOAuthProvider,
237 },
238})
239```
240
241> **Interactive authorization (redirect flows).** Completing an authorization-code
242> grant requires calling `finishAuth(code)` on the transport after the user is
243> redirected back — and `createMCPClient` constructs the transport internally,
244> so it cannot expose it. If you need the interactive flow, build the transport
245> yourself and pass it in (the escape hatch above): construct a
246> `StreamableHTTPClientTransport` with your `authProvider`, keep a reference,
247> call `transport.finishAuth(code)` in your OAuth callback route, then hand the
248> transport to `createMCPClient({ transport })`. For typical server-side use —
249> a provider backed by pre-provisioned or stored tokens with working refresh —
250> the config form shown above is all you need.
251
252## Three Modes of Type Safety
253
254### Mode 1 — Auto-discovery (`client.tools()`)
255
256Call `tools()` with no arguments to discover every tool the server exposes. This requires no extra setup. Tool argument types are `unknown` at compile time; the MCP JSON Schema is used for runtime validation.
257
258```ts
259import { createMCPClient } from '@tanstack/ai-mcp'
260
261const mcp = await createMCPClient({
262 transport: { type: 'http', url: 'https://my-mcp-server.example.com/mcp' },
263})
264const tools = await mcp.tools()
265// tools: ServerTool[] — args typed unknown at compile time
266```
267
268MCP schemas often use `$ref` or `oneOf`. On adapters built on the OpenAI API, those tools are sent without strict mode, and the adapter warns in development. See [Tools that cannot use strict mode](../adapters/openai.md#tools-that-cannot-use-strict-mode).
269
270> **Task-based tools are supported.** Tools that declare
271> `execution.taskSupport: 'required'` automatically run through the MCP SDK's
272> experimental `tasks/callToolStream` flow. TanStack AI waits through task
273> status updates and returns the terminal result to the model. Tools declaring
274> `taskSupport: 'optional'` continue to use ordinary `callTool` execution.
275> Task execution needs the server to declare the tasks capability for
276> `tools/call`; a server that lists a task-required tool without it is
277> skipped by auto-discovery (the tool could never be invoked).
278>
279> If the chat run aborts, TanStack AI stops waiting for the task and sends a
280> best-effort `tasks/cancel` for a remote task the server has already created.
281
282### Mode 2 — Explicit definitions (`client.tools([...defs])`)
283
284Pass TanStack `toolDefinition()` instances to get full TypeScript types and Zod validation. Only the named tools are returned (allowlist). `MCPToolNotFoundError` is thrown if a name isn't on the server. Task-required tools use the same automatic task execution described in Mode 1.
285
286```ts
287import { toolDefinition } from '@tanstack/ai'
288import { createMCPClient } from '@tanstack/ai-mcp'
289import { z } from 'zod'
290
291const searchDef = toolDefinition({
292 name: 'search',
293 description: 'Search for items',
294 inputSchema: z.object({ query: z.string() }),
295 outputSchema: z.array(z.object({ id: z.string(), title: z.string() })),
296})
297
298const mcp = await createMCPClient({
299 transport: { type: 'http', url: 'https://my-mcp-server.example.com/mcp' },
300})
301const tools = await mcp.tools([searchDef])
302// tools[0].execute is typed: (args: { query: string }) => ...
303```
304
305### Mode 3 — Generated types (`createMCPClient<GeneratedServer>`)
306
307Run the CLI against a live server to generate per-server `interface` types, then pass the generated type as a generic — tool names are narrowed to the server's literal names and pool config keys are compile-checked, with zero runtime overhead. (Tool *arguments* stay untyped on the discovery path — combine with Mode 2 for typed args.)
308
309> See [MCP Type Generation](./mcp-codegen) for the full `mcp.config.ts` setup, the `generate` CLI, and how to wire the generated types into `createMCPClient` and `createMCPClients`.
310
311## Tool Titles & Annotations
312
313MCP servers can ship display and behavior metadata alongside each tool: a human-readable `title` and a set of `annotations` hints (`readOnlyHint`, `destructiveHint`, `idempotentHint`, `openWorldHint`, plus a legacy `annotations.title`). `@tanstack/ai-mcp` forwards all of it onto each discovered tool's `metadata.mcp`, on **both** the auto-discovery and explicit-definition paths, so you can label tools in your UI and decide which ones need a confirmation step.
314
315| `metadata.mcp` field | Value |
316|---|---|
317| `title` | `string` — display name, resolved with the spec's precedence: the tool's `title` → `annotations.title` → `name`. Always set. |
318| `annotations` | The server's `annotations` object, forwarded verbatim. Absent when the server declares none. |
319| `serverToolName` | `string` — server-native (unprefixed) tool name. |
320| `serverId` | The client's `prefix` (undefined when there is none). |
321| `uiResourceUri` | [MCP Apps](../mcp/apps) widget link, when the tool declares one. |
322
323The block is typed, so just read it. `tools()` returns `McpServerTool`s — a plain `ServerTool` (it still drops straight into `chat({ tools })`) whose `metadata.mcp` is statically known to be present and shaped like the table above. No annotation, no cast, and a misspelled field is a compile error:
324
325```ts
326import { createMCPClient } from '@tanstack/ai-mcp'
327
328const url = 'https://my-mcp-server.example.com/mcp'
329
330// Trust comes from YOUR configuration — an allowlist of servers you operate or
331// have vetted — never from anything the server itself sends.
332const trustedServers = new Set(['https://my-mcp-server.example.com/mcp'])
333const serverIsTrusted = trustedServers.has(url)
334
335const mcp = await createMCPClient({ transport: { type: 'http', url } })
336
337const tools = (await mcp.tools()).map((tool) => {
338 const meta = tool.metadata.mcp
339 const advertisedReadOnly = meta.annotations?.readOnlyHint === true
340 return {
341 ...tool,
342 // Approval is the default. A hint may only relax it for a server whose
343 // trust you established independently; on any other server the same hint
344 // is a label/recommendation and changes nothing about approval.
345 needsApproval: !(serverIsTrusted && advertisedReadOnly),
346 }
347})
348```
349
350> **Annotations are advisory, never a security boundary.** The MCP spec is explicit that every field — including `title` — is a hint that may not faithfully describe what the tool actually does, and a malicious or compromised server can claim anything (`readOnlyHint: true` on a tool that deletes records). Do not use them as the security boundary for an untrusted server: never let a hint alone waive approval, sandboxing, or authorization. On a server you have independently established as trusted, a hint may *relax* a confirmation step, as above; everywhere else, treat annotations as display labels and recommendations only — surface `readOnlyHint` as a badge (see the UI example below) rather than acting on it.
351
352Titles are display-only: they never change the tool `name` sent to the model, and a `prefix` still applies to the name (`wx_get_weather`), not to the title.
353
354`McpToolMetadata` and `McpServerTool` are both exported if you need to name the shapes in your own signatures (`ToolAnnotations` too, re-exported from the MCP SDK). You don't need them just to read the block.
355
356To label tools in your UI, expose the forwarded metadata from a server route — the MCP client itself must stay server-side:
357
358```ts ignore
359// src/routes/api.mcp-tools.ts
360import { createFileRoute } from '@tanstack/react-router'
361import { createMCPClient } from '@tanstack/ai-mcp'
362
363export const Route = createFileRoute('/api/mcp-tools')({
364 server: {
365 handlers: {
366 GET: async () => {
367 await using mcp = await createMCPClient({
368 transport: { type: 'http', url: process.env.MCP_URL! },
369 })
370 const catalog = (await mcp.tools()).map((tool) => ({
371 name: tool.name,
372 // `title` is always set — the fallback chain already ran.
373 title: tool.metadata.mcp.title,
374 description: tool.description,
375 readOnly: tool.metadata.mcp.annotations?.readOnlyHint === true,
376 }))
377 return Response.json({ tools: catalog })
378 },
379 },
380 },
381})
382```
383
384```tsx
385// src/components/ToolCatalog.tsx
386import { useEffect, useState } from 'react'
387
388interface ToolSummary {
389 name: string
390 title: string
391 description?: string
392 readOnly: boolean
393}
394
395export function ToolCatalog() {
396 const [tools, setTools] = useState<Array<ToolSummary>>([])
397
398 useEffect(() => {
399 fetch('/api/mcp-tools')
400 .then((res) => res.json())
401 .then((body: { tools: Array<ToolSummary> }) => setTools(body.tools))
402 }, [])
403
404 return (
405 <ul>
406 {tools.map((tool) => (
407 <li key={tool.name}>
408 {/* Server-declared title, with the hint driving the badge */}
409 <strong>{tool.title}</strong> {tool.readOnly ? '(read-only)' : '(writes)'}
410 <div>{tool.description}</div>
411 </li>
412 ))}
413 </ul>
414 )
415}
416```
417
418## Limit and Gate Tools
419
420By 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:
421
422- `toolFilter`: return `false` to hide a tool from the model.
423- `needsApproval`: return `true` to pause the run for [approval](./tool-approval) before each call to the tool.
424
425Both options receive the tool definition that the server sent. The definition has the native (unprefixed) `name`, the `title`, and the `annotations`. Both options are off by default.
426
427Send only the tools that the server marks read-only:
428
429```ts
430import { createMCPClient } from '@tanstack/ai-mcp'
431
432const mcp = await createMCPClient({
433 transport: { type: 'http', url: 'https://my-mcp-server.example.com/mcp' },
434 toolFilter: (tool) => tool.annotations?.readOnlyHint === true,
435})
436
437const tools = await mcp.tools() // only read-only tools
438```
439
440A tool with no `annotations` does not pass this filter.
441
442On a server that you do not trust, filter by name. You control the names, and the server controls the hints:
443
444```ts
445import { createMCPClient } from '@tanstack/ai-mcp'
446
447const allowed = new Set(['search_issues', 'get_issue'])
448
449const mcp = await createMCPClient({
450 transport: { type: 'http', url: 'https://my-mcp-server.example.com/mcp' },
451 toolFilter: (tool) => allowed.has(tool.name),
452})
453```
454
455Keep every tool, but ask the user before a tool runs:
456
457```ts
458import { createMCPClient } from '@tanstack/ai-mcp'
459
460const url = 'https://my-mcp-server.example.com/mcp'
461// Trust comes from your configuration, not from the server.
462const trustedServers = new Set(['https://my-mcp-server.example.com/mcp'])
463const serverIsTrusted = trustedServers.has(url)
464
465const mcp = await createMCPClient({
466 transport: { type: 'http', url },
467 // A read-only hint skips approval only on a server that you trust.
468 needsApproval: (tool) =>
469 !(serverIsTrusted && tool.annotations?.readOnlyHint === true),
470})
471```
472
473The 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).
474
475In a [pool](#multi-server-pool), each server gets its own options:
476
477```ts
478import { createMCPClients } from '@tanstack/ai-mcp'
479
480const pool = await createMCPClients({
481 github: {
482 transport: { type: 'http', url: process.env.GITHUB_MCP_URL! },
483 toolFilter: (tool) => tool.annotations?.readOnlyHint === true,
484 },
485 docs: { transport: { type: 'http', url: process.env.DOCS_MCP_URL! } },
486})
487```
488
489The options apply in these places:
490
491- **`tools()`**: `toolFilter` hides tools, and `needsApproval` marks tools.
492- **`tools([...defs])`**: `toolFilter` applies. A definition that the filter hides throws `MCPToolNotFoundError`. `needsApproval` does not apply, because each `toolDefinition` has its own `needsApproval`.
493- **`chat({ mcp })`**: both apply, because `chat()` calls `tools()` on the client. See [Managed MCP](./mcp-managed).
494- **[MCP Apps](../mcp/apps) widget calls**: both apply. A widget cannot call a tool that the filter hides. A widget call has no approval step, so a call to a tool that `needsApproval` marks returns `{ ok: false }`.
495- **`callTool()`**: neither applies. Your code calls the tool directly, and the model is not involved.
496
497> **The hints come from the server.** A compromised server can mark a delete tool `readOnlyHint: true`. Use a name allowlist or `needsApproval` for a server that you do not trust.
498
499`McpTool` is exported if you need to name the type of the `tool` argument.
500
501## Multi-Server Pool
502
503`createMCPClients` connects to many servers in parallel and merges their tools into one flat array. Each server's tools are automatically prefixed with the config key to prevent name collisions.
504
505```ts
506import { createMCPClients } from '@tanstack/ai-mcp'
507
508const pool = await createMCPClients({
509 github: { transport: { type: 'http', url: process.env.GITHUB_MCP_URL! } },
510 linear: { transport: { type: 'http', url: process.env.LINEAR_MCP_URL! } },
511})
512
513// tools: [github_search_repos, github_create_issue, linear_create_issue, ...]
514const tools = await pool.tools()
515```
516
517`pool.tools()` collects all servers' tools and throws `DuplicateToolNameError` if any two names collide after prefixing.
518
519### Per-server access
520
521```ts
522import { createMCPClients } from '@tanstack/ai-mcp'
523
524const pool = await createMCPClients({
525 github: { transport: { type: 'http', url: process.env.GITHUB_MCP_URL! } },
526 linear: { transport: { type: 'http', url: process.env.LINEAR_MCP_URL! } },
527})
528
529const linearTools = await pool.clients.linear!.tools()
530const resources = await pool.clients.github!.resources()
531```
532
533### Disable or override the prefix
534
535```ts
536import { createMCPClients } from '@tanstack/ai-mcp'
537
538const pool = await createMCPClients({
539 github: {
540 transport: { type: 'http', url: process.env.GITHUB_MCP_URL! },
541 prefix: 'gh', // override: "gh_search_repos"
542 },
543 internal: {
544 transport: { type: 'http', url: process.env.INTERNAL_MCP_URL! },
545 prefix: '', // disable prefix entirely
546 },
547})
548```
549
550### Closing the pool
551
552```ts ignore
553await pool.close()
554// or
555await using pool = await createMCPClients({ /* server configs */ })
556```
557
558If any server fails to connect, already-connected clients are closed before the error is thrown — no leaks.
559
560## Lifecycle
561
562> **You can skip this entire section** by passing clients to `chat()` via the `mcp` option (as in the Quick Start) — `chat()` discovers tools and closes the connections when the run ends. See [Managed MCP with `chat()`](./mcp-managed). Read on only if you spread tools manually and own `close()` yourself.
563
564When you manage the client manually, it is **caller-owned**: `chat()` never closes it.
565
566Tools execute **lazily while the response stream is consumed**, so only close the client after the stream is fully drained. In a route handler that returns a streaming `Response`, a `try/finally` around the `return` (or `await using` at function scope) closes the client *before* the body streams — in-flight tool calls would fail. Close in a middleware terminal hook instead.
567
568### Streaming route handlers — close via middleware
569
570Exactly one of `onFinish`/`onAbort`/`onError` fires per run, after the agent loop ends:
571
572```ts
573import { chat, toServerSentEventsResponse } from '@tanstack/ai'
574import { openaiText } from '@tanstack/ai-openai'
575import { createMCPClient } from '@tanstack/ai-mcp'
576
577export async function POST(request: Request) {
578 const { messages } = await request.json()
579 const url = 'https://my-mcp-server.example.com/mcp'
580 const mcp = await createMCPClient({ transport: { type: 'http', url } })
581 const stream = chat({
582 adapter: openaiText('gpt-5.5'),
583 messages,
584 tools: await mcp.tools(),
585 middleware: [
586 {
587 name: 'mcp-close',
588 onFinish: () => mcp.close(),
589 onAbort: () => mcp.close(),
590 onError: () => mcp.close(),
591 },
592 ],
593 })
594 return toServerSentEventsResponse(stream)
595}
596```
597
598### Manual close — when you consume the stream in scope
599
600`try/finally` is correct when the stream is drained before the scope exits:
601
602```ts
603import { chat } from '@tanstack/ai'
604import { openaiText } from '@tanstack/ai-openai'
605import { createMCPClient } from '@tanstack/ai-mcp'
606
607const messages = [{ role: 'user' as const, content: 'Hello' }]
608const url = 'https://my-mcp-server.example.com/mcp'
609const mcp = await createMCPClient({ transport: { type: 'http', url } })
610try {
611 const stream = chat({
612 adapter: openaiText('gpt-5.5'),
613 messages,
614 tools: await mcp.tools(),
615 })
616 for await (const chunk of stream) {
617 // handle chunks — the stream is fully consumed inside this block
618 }
619} finally {
620 await mcp.close()
621}
622```
623
624### `await using` (Explicit Resource Management)
625
626If your runtime supports `Symbol.asyncDispose` (Node 18.2+ with TypeScript `target: "es2022"` + `lib: ["esnext"]`), the same in-scope-consumption rule applies — the client closes when the block exits:
627
628```ts
629import { chat } from '@tanstack/ai'
630import { openaiText } from '@tanstack/ai-openai'
631import { createMCPClient } from '@tanstack/ai-mcp'
632
633const messages = [{ role: 'user' as const, content: 'Hello' }]
634const url = 'https://my-mcp-server.example.com/mcp'
635await using mcp = await createMCPClient({ transport: { type: 'http', url } })
636const stream = chat({
637 adapter: openaiText('gpt-5.5'),
638 messages,
639 tools: await mcp.tools(),
640})
641for await (const chunk of stream) {
642 // handle chunks
643}
644// mcp.close() is called automatically when the block exits
645```
646
647## Tool Name Collisions
648
649When mixing tools from multiple sources, duplicate names throw `DuplicateToolNameError`:
650
651```ts
652import { createMCPClients, DuplicateToolNameError } from '@tanstack/ai-mcp'
653
654const pool = await createMCPClients({
655 github: { transport: { type: 'http', url: process.env.GITHUB_MCP_URL! } },
656 linear: { transport: { type: 'http', url: process.env.LINEAR_MCP_URL! } },
657})
658
659try {
660 const tools = await pool.tools()
661} catch (err) {
662 if (err instanceof DuplicateToolNameError) {
663 console.error('Conflicting tool name:', err.toolName)
664 // Fix: set a unique prefix on one of the clients
665 }
666}
667```
668
669Use a unique `prefix` on each client to avoid collisions — `createMCPClients` does this automatically using the config key.
670
671## Lazy Tool Discovery
672
673Pass `{ lazy: true }` to defer sending tool schemas to the LLM until it explicitly asks for them. This reduces token usage when working with tool-heavy servers.
674
675```ts
676import { createMCPClient } from '@tanstack/ai-mcp'
677
678const mcp = await createMCPClient({
679 transport: { type: 'http', url: 'https://my-mcp-server.example.com/mcp' },
680})
681const tools = await mcp.tools({ lazy: true })
682// All tools are marked lazy: true
683```
684
685Works with the pool too:
686
687```ts
688import { createMCPClients } from '@tanstack/ai-mcp'
689
690const pool = await createMCPClients({
691 github: { transport: { type: 'http', url: process.env.GITHUB_MCP_URL! } },
692 linear: { transport: { type: 'http', url: process.env.LINEAR_MCP_URL! } },
693})
694const tools = await pool.tools({ lazy: true })
695```
696
697See [Lazy Tool Discovery](./lazy-tool-discovery) for how the LLM discovers lazy tools at runtime.
698
699## Using MCP with `chat()`
700
701The Quick Start above hands tools to `chat()` manually via `tools: await mcp.tools()` and closes the client yourself. Two follow-on guides cover richer integrations:
702
703> **Let `chat()` own discovery and lifecycle.** Pass live clients and pools to `chat()` via the `mcp` option and it discovers tools and closes connections for you — no `try/finally` per route. See [Managed MCP with `chat()`](./mcp-managed).
704
705> **Resources, prompts, and fully-typed manual tools.** Inject MCP resources and prompts into a `chat()` run, cancel in-flight MCP calls, and spread `toolDefinition`-typed tools. See [Manual MCP: typed tools, resources & prompts](./mcp-manual).
706
707## Error Reference
708
709| Error class | When thrown |
710|---|---|
711| `MCPConnectionError` | `createMCPClient` fails to connect, or a method is called after `close()` |
712| `DuplicateToolNameError` | Two tools have the same name within one client or across the pool |
713| `MCPToolNotFoundError` | A `toolDefinition` name passed to `tools([...defs])` is not found on the server |
714| `MCPTaskRequiredToolError` | A task-required tool was bound via `tools([...defs])` or called via `callTool()` but the server does not declare the tasks capability for `tools/call`, so the call could never execute |
715
716For the `MCPDuplicateToolNameError` thrown when merging tools from multiple sources inside a `chat({ mcp })` run, see [Managed MCP with `chat()`](./mcp-managed#tool-name-collisions).