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## Timeouts
253
254A slow MCP server can hold a request for a long time. By default, each request waits up to 60 seconds, then fails. A tool that runs longer, such as a report or a build, fails at that limit too.
255
256Set `requestOptions` to change the limit for the connect handshake, tool lists, tool calls, resource requests, and prompt requests:
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 requestOptions: {
264 // Wait up to 2 minutes for each request.
265 timeout: 120_000,
266 // Start the 2 minutes again each time the server reports progress.
267 resetTimeoutOnProgress: true,
268 },
269})
270```
271
272- `timeout`: the limit in milliseconds. The SDK default is 60,000.
273- `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 there only `timeout` applies.
274- 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`.
275- The `subscriptions/listen` stream and task status polls keep the SDK defaults.
276- A request that runs out of time throws an `SdkError` from `@modelcontextprotocol/client`, with the code `SdkErrorCode.RequestTimeout`.
277
278Each server in [`createMCPClients`](#multi-server-pool) can have its own `requestOptions`. [MCP Apps](../mcp/apps) widget calls use the options of the same client.
279
280## Three Modes of Type Safety
281
282### Mode 1 — Auto-discovery (`client.tools()`)
283
284Call `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.
285
286```ts
287import { createMCPClient } from '@tanstack/ai-mcp'
288
289const mcp = await createMCPClient({
290 transport: { type: 'http', url: 'https://my-mcp-server.example.com/mcp' },
291})
292const tools = await mcp.tools()
293// tools: ServerTool[] — args typed unknown at compile time
294```
295
296If a server sends an input schema without `properties`, the tool gets `properties: {}`. A schema without `type` gets `type: 'object'`. Some providers reject an object schema without `properties`, and these defaults keep those tools working. The client does not change a schema that has both fields.
297
298MCP 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).
299
300> **Task-based tools are supported.** Tools that declare
301> `execution.taskSupport: 'required'` automatically run through the MCP SDK's
302> experimental `tasks/callToolStream` flow. TanStack AI waits through task
303> status updates and returns the terminal result to the model. Tools declaring
304> `taskSupport: 'optional'` continue to use ordinary `callTool` execution.
305> Task execution needs the server to declare the tasks capability for
306> `tools/call`; a server that lists a task-required tool without it is
307> skipped by auto-discovery (the tool could never be invoked).
308>
309> If the chat run aborts, TanStack AI stops waiting for the task and sends a
310> best-effort `tasks/cancel` for a remote task the server has already created.
311
312### Mode 2 — Explicit definitions (`client.tools([...defs])`)
313
314Pass 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.
315
316```ts
317import { toolDefinition } from '@tanstack/ai'
318import { createMCPClient } from '@tanstack/ai-mcp'
319import { z } from 'zod'
320
321const searchDef = toolDefinition({
322 name: 'search',
323 description: 'Search for items',
324 inputSchema: z.object({ query: z.string() }),
325 outputSchema: z.array(z.object({ id: z.string(), title: z.string() })),
326})
327
328const mcp = await createMCPClient({
329 transport: { type: 'http', url: 'https://my-mcp-server.example.com/mcp' },
330})
331const tools = await mcp.tools([searchDef])
332// tools[0].execute is typed: (args: { query: string }) => ...
333```
334
335### Mode 3 — Generated types (`createMCPClient<GeneratedServer>`)
336
337Run 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.)
338
339> 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`.
340
341## Tool Titles & Annotations
342
343MCP 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.
344
345| `metadata.mcp` field | Value |
346|---|---|
347| `title` | `string` — display name, resolved with the spec's precedence: the tool's `title` → `annotations.title` → `name`. Always set. |
348| `annotations` | A frozen copy of the server's `annotations` object. Absent when the server declares none. To change a value, copy it first: `{ ...tool.metadata.mcp.annotations, readOnlyHint: false }`. |
349| `serverToolName` | `string` — server-native (unprefixed) tool name. |
350| `serverId` | The client's `prefix` (undefined when there is none). |
351| `uiResourceUri` | [MCP Apps](../mcp/apps) widget link, when the tool declares one. |
352
353The 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:
354
355```ts
356import { createMCPClient } from '@tanstack/ai-mcp'
357
358const url = 'https://my-mcp-server.example.com/mcp'
359
360// Trust comes from YOUR configuration — an allowlist of servers you operate or
361// have vetted — never from anything the server itself sends.
362const trustedServers = new Set(['https://my-mcp-server.example.com/mcp'])
363const serverIsTrusted = trustedServers.has(url)
364
365const mcp = await createMCPClient({ transport: { type: 'http', url } })
366
367const tools = (await mcp.tools()).map((tool) => {
368 const meta = tool.metadata.mcp
369 const advertisedReadOnly = meta.annotations?.readOnlyHint === true
370 return {
371 ...tool,
372 // Approval is the default. A hint may only relax it for a server whose
373 // trust you established independently; on any other server the same hint
374 // is a label/recommendation and changes nothing about approval.
375 needsApproval: !(serverIsTrusted && advertisedReadOnly),
376 }
377})
378```
379
380> **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.
381
382Titles 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.
383
384`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.
385
386To label tools in your UI, expose the forwarded metadata from a server route — the MCP client itself must stay server-side:
387
388```ts ignore
389// src/routes/api.mcp-tools.ts
390import { createFileRoute } from '@tanstack/react-router'
391import { createMCPClient } from '@tanstack/ai-mcp'
392
393export const Route = createFileRoute('/api/mcp-tools')({
394 server: {
395 handlers: {
396 GET: async () => {
397 await using mcp = await createMCPClient({
398 transport: { type: 'http', url: process.env.MCP_URL! },
399 })
400 const catalog = (await mcp.tools()).map((tool) => ({
401 name: tool.name,
402 // `title` is always set — the fallback chain already ran.
403 title: tool.metadata.mcp.title,
404 description: tool.description,
405 readOnly: tool.metadata.mcp.annotations?.readOnlyHint === true,
406 }))
407 return Response.json({ tools: catalog })
408 },
409 },
410 },
411})
412```
413
414```tsx
415// src/components/ToolCatalog.tsx
416import { useEffect, useState } from 'react'
417
418interface ToolSummary {
419 name: string
420 title: string
421 description?: string
422 readOnly: boolean
423}
424
425export function ToolCatalog() {
426 const [tools, setTools] = useState<Array<ToolSummary>>([])
427
428 useEffect(() => {
429 fetch('/api/mcp-tools')
430 .then((res) => res.json())
431 .then((body: { tools: Array<ToolSummary> }) => setTools(body.tools))
432 }, [])
433
434 return (
435 <ul>
436 {tools.map((tool) => (
437 <li key={tool.name}>
438 {/* Server-declared title, with the hint driving the badge */}
439 <strong>{tool.title}</strong> {tool.readOnly ? '(read-only)' : '(writes)'}
440 <div>{tool.description}</div>
441 </li>
442 ))}
443 </ul>
444 )
445}
446```
447
448## Limit and Gate Tools
449
450By 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:
451
452- `toolFilter`: a function that returns `false` to hide a tool, or a list of the tool names to keep.
453- `needsApproval`: return `true` to pause the run for [approval](./tool-approval) before each call to the tool.
454
455A `toolFilter` function and `needsApproval` 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.
456
457Send only the tools that the server marks read-only:
458
459```ts
460import { createMCPClient } from '@tanstack/ai-mcp'
461
462const mcp = await createMCPClient({
463 transport: { type: 'http', url: 'https://my-mcp-server.example.com/mcp' },
464 toolFilter: (tool) => tool.annotations?.readOnlyHint === true,
465})
466
467const tools = await mcp.tools() // only read-only tools
468```
469
470A tool with no `annotations` does not pass this filter.
471
472On a server that you do not trust, list the tools by name. You control the names, and the server controls the hints:
473
474```ts
475import { createMCPClient } from '@tanstack/ai-mcp'
476
477const mcp = await createMCPClient({
478 transport: { type: 'http', url: 'https://my-mcp-server.example.com/mcp' },
479 toolFilter: ['search_issues', 'get_issue'],
480})
481
482const tools = await mcp.tools() // search_issues, then get_issue
483```
484
485A list is strict:
486
487- The tools come back in the list order.
488- 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.
489- A listed tool that needs task execution, on a server without task support, throws `MCPTaskRequiredToolError`.
490- An empty list keeps no tools.
491
492A function does not fail when a tool is missing. If the tool list of the server can change, use a function.
493
494Keep every tool, but ask the user before a tool runs:
495
496```ts
497import { createMCPClient } from '@tanstack/ai-mcp'
498
499const url = 'https://my-mcp-server.example.com/mcp'
500// Trust comes from your configuration, not from the server.
501const trustedServers = new Set(['https://my-mcp-server.example.com/mcp'])
502const serverIsTrusted = trustedServers.has(url)
503
504const mcp = await createMCPClient({
505 transport: { type: 'http', url },
506 // A read-only hint skips approval only on a server that you trust.
507 needsApproval: (tool) =>
508 !(serverIsTrusted && tool.annotations?.readOnlyHint === true),
509})
510```
511
512The 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).
513
514In a [pool](#multi-server-pool), each server gets its own options:
515
516```ts
517import { createMCPClients } from '@tanstack/ai-mcp'
518
519const pool = await createMCPClients({
520 github: {
521 transport: { type: 'http', url: process.env.GITHUB_MCP_URL! },
522 toolFilter: (tool) => tool.annotations?.readOnlyHint === true,
523 },
524 docs: { transport: { type: 'http', url: process.env.DOCS_MCP_URL! } },
525})
526```
527
528The options apply in these places:
529
530- **`tools()`**: `toolFilter` hides tools, and `needsApproval` marks tools.
531- **`tools([...defs])`**: `toolFilter` applies. A definition that the filter hides throws `MCPToolNotFoundError`. `needsApproval` does not apply, because each `toolDefinition` has its own `needsApproval`.
532- **`chat({ mcp })`**: both apply, because `chat()` calls `tools()` on the client. See [Managed MCP](./mcp-managed).
533- **[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 }`.
534- **`callTool()`**: neither applies. Your code calls the tool directly, and the model is not involved.
535
536> **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.
537
538`McpTool` is exported if you need to name the type of the `tool` argument.
539
540## Multi-Server Pool
541
542`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.
543
544```ts
545import { createMCPClients } from '@tanstack/ai-mcp'
546
547const pool = await createMCPClients({
548 github: { transport: { type: 'http', url: process.env.GITHUB_MCP_URL! } },
549 linear: { transport: { type: 'http', url: process.env.LINEAR_MCP_URL! } },
550})
551
552// tools: [github_search_repos, github_create_issue, linear_create_issue, ...]
553const tools = await pool.tools()
554```
555
556`pool.tools()` collects all servers' tools and throws `DuplicateToolNameError` if any two names collide after prefixing.
557
558### Per-server access
559
560```ts
561import { createMCPClients } from '@tanstack/ai-mcp'
562
563const pool = await createMCPClients({
564 github: { transport: { type: 'http', url: process.env.GITHUB_MCP_URL! } },
565 linear: { transport: { type: 'http', url: process.env.LINEAR_MCP_URL! } },
566})
567
568const linearTools = await pool.clients.linear!.tools()
569const resources = await pool.clients.github!.resources()
570```
571
572### Disable or override the prefix
573
574```ts
575import { createMCPClients } from '@tanstack/ai-mcp'
576
577const pool = await createMCPClients({
578 github: {
579 transport: { type: 'http', url: process.env.GITHUB_MCP_URL! },
580 prefix: 'gh', // override: "gh_search_repos"
581 },
582 internal: {
583 transport: { type: 'http', url: process.env.INTERNAL_MCP_URL! },
584 prefix: '', // disable prefix entirely
585 },
586})
587```
588
589### Closing the pool
590
591```ts ignore
592await pool.close()
593// or
594await using pool = await createMCPClients({ /* server configs */ })
595```
596
597If any server fails to connect, already-connected clients are closed before the error is thrown — no leaks.
598
599## Lifecycle
600
601> **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.
602
603When you manage the client manually, it is **caller-owned**: `chat()` never closes it.
604
605Tools 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.
606
607### Streaming route handlers — close via middleware
608
609Exactly one of `onFinish`/`onAbort`/`onError` fires per run, after the agent loop ends:
610
611```ts
612import { chat, toServerSentEventsResponse } from '@tanstack/ai'
613import { openaiText } from '@tanstack/ai-openai'
614import { createMCPClient } from '@tanstack/ai-mcp'
615
616export async function POST(request: Request) {
617 const { messages } = await request.json()
618 const url = 'https://my-mcp-server.example.com/mcp'
619 const mcp = await createMCPClient({ transport: { type: 'http', url } })
620 const stream = chat({
621 adapter: openaiText('gpt-5.5'),
622 messages,
623 tools: await mcp.tools(),
624 middleware: [
625 {
626 name: 'mcp-close',
627 onFinish: () => mcp.close(),
628 onAbort: () => mcp.close(),
629 onError: () => mcp.close(),
630 },
631 ],
632 })
633 return toServerSentEventsResponse(stream)
634}
635```
636
637### Manual close — when you consume the stream in scope
638
639`try/finally` is correct when the stream is drained before the scope exits:
640
641```ts
642import { chat } from '@tanstack/ai'
643import { openaiText } from '@tanstack/ai-openai'
644import { createMCPClient } from '@tanstack/ai-mcp'
645
646const messages = [{ role: 'user' as const, content: 'Hello' }]
647const url = 'https://my-mcp-server.example.com/mcp'
648const mcp = await createMCPClient({ transport: { type: 'http', url } })
649try {
650 const stream = chat({
651 adapter: openaiText('gpt-5.5'),
652 messages,
653 tools: await mcp.tools(),
654 })
655 for await (const chunk of stream) {
656 // handle chunks — the stream is fully consumed inside this block
657 }
658} finally {
659 await mcp.close()
660}
661```
662
663### `await using` (Explicit Resource Management)
664
665If 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:
666
667```ts
668import { chat } from '@tanstack/ai'
669import { openaiText } from '@tanstack/ai-openai'
670import { createMCPClient } from '@tanstack/ai-mcp'
671
672const messages = [{ role: 'user' as const, content: 'Hello' }]
673const url = 'https://my-mcp-server.example.com/mcp'
674await using mcp = await createMCPClient({ transport: { type: 'http', url } })
675const stream = chat({
676 adapter: openaiText('gpt-5.5'),
677 messages,
678 tools: await mcp.tools(),
679})
680for await (const chunk of stream) {
681 // handle chunks
682}
683// mcp.close() is called automatically when the block exits
684```
685
686## Tool Name Collisions
687
688When mixing tools from multiple sources, duplicate names throw `DuplicateToolNameError`:
689
690```ts
691import { createMCPClients, DuplicateToolNameError } from '@tanstack/ai-mcp'
692
693const pool = await createMCPClients({
694 github: { transport: { type: 'http', url: process.env.GITHUB_MCP_URL! } },
695 linear: { transport: { type: 'http', url: process.env.LINEAR_MCP_URL! } },
696})
697
698try {
699 const tools = await pool.tools()
700} catch (err) {
701 if (err instanceof DuplicateToolNameError) {
702 console.error('Conflicting tool name:', err.toolName)
703 // Fix: set a unique prefix on one of the clients
704 }
705}
706```
707
708Use a unique `prefix` on each client to avoid collisions — `createMCPClients` does this automatically using the config key.
709
710## Name Tools Yourself
711
712The model sees `<prefix>_<tool>`, or the server's tool name when there is no prefix. Some apps need another pattern, for example a fixed `mcp__<server>__<tool>` form, or names without characters that a provider rejects.
713
714Pass `toolName`. It gets the tool definition from the server and returns the name the model sees. It wins over `prefix`:
715
716```ts
717import { createMCPClient } from '@tanstack/ai-mcp'
718
719// Keep only letters, digits, `_`, and `-` in the name.
720const clean = (value: string) => value.replace(/[^A-Za-z0-9_-]/g, '_')
721
722const mcp = await createMCPClient({
723 transport: { type: 'http', url: 'https://my-mcp-server.example.com/mcp' },
724 toolName: (tool) => `mcp__github__${clean(tool.name)}`,
725})
726
727const tools = await mcp.tools() // mcp__github__search_issues, ...
728```
729
730- The name applies to `tools()` and to `tools([...defs])`.
731- `metadata.mcp.serverToolName` keeps the server's own name. [MCP Apps](../mcp/apps) widget calls use it, and `callTool()` takes it, so both still reach the tool.
732- `metadata.mcp.serverId` is still the client `prefix`.
733- MCP Apps routes widget calls by `prefix`. If you use MCP Apps with `toolName`, keep a `prefix` on each client.
734- Two tools with the same final name throw `DuplicateToolNameError`, in one client and across a pool.
735
736In a pool, each server gets its own `toolName`:
737
738```ts
739import { createMCPClients } from '@tanstack/ai-mcp'
740
741const pool = await createMCPClients({
742 github: {
743 transport: { type: 'http', url: process.env.GITHUB_MCP_URL! },
744 toolName: (tool) => `mcp__github__${tool.name}`,
745 },
746 linear: {
747 transport: { type: 'http', url: process.env.LINEAR_MCP_URL! },
748 toolName: (tool) => `mcp__linear__${tool.name}`,
749 },
750})
751
752const tools = await pool.tools() // mcp__github__..., mcp__linear__...
753```
754
755## Lazy Tool Discovery
756
757Pass `{ 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.
758
759```ts
760import { createMCPClient } from '@tanstack/ai-mcp'
761
762const mcp = await createMCPClient({
763 transport: { type: 'http', url: 'https://my-mcp-server.example.com/mcp' },
764})
765const tools = await mcp.tools({ lazy: true })
766// All tools are marked lazy: true
767```
768
769Works with the pool too:
770
771```ts
772import { createMCPClients } from '@tanstack/ai-mcp'
773
774const pool = await createMCPClients({
775 github: { transport: { type: 'http', url: process.env.GITHUB_MCP_URL! } },
776 linear: { transport: { type: 'http', url: process.env.LINEAR_MCP_URL! } },
777})
778const tools = await pool.tools({ lazy: true })
779```
780
781See [Lazy Tool Discovery](./lazy-tool-discovery) for how the LLM discovers lazy tools at runtime.
782
783## Using MCP with `chat()`
784
785The 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:
786
787> **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).
788
789> **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).
790
791## Error Reference
792
793| Error class | When thrown |
794|---|---|
795| `MCPConnectionError` | `createMCPClient` fails to connect, or a method is called after `close()` |
796| `DuplicateToolNameError` | Two tools have the same name within one client or across the pool |
797| `MCPToolNotFoundError` | A `toolDefinition` name passed to `tools([...defs])` is not found on the server, or the client's `toolFilter` hides it |
798| `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` |
799| `MCPTaskRequiredToolError` | A task-required tool was bound via `tools([...defs])`, listed in a `toolFilter` list, or called via `callTool()`, but the server does not declare the tasks capability for `tools/call`, so the call can never run |
800
801For the `MCPDuplicateToolNameError` thrown when merging tools from multiple sources inside a `chat({ mcp })` run, see [Managed MCP with `chat()`](./mcp-managed#tool-name-collisions).