Open History to see the last commit
1---
2title: Managed MCP with chat()
3id: mcp-managed
4order: 9
5description: "Hand live MCP clients and pools to chat() via the mcp option and let it own tool discovery and connection lifecycle for you."
6keywords:
7 - tanstack ai
8 - mcp
9 - model context protocol
10 - chat mcp
11 - mcp clients
12 - keep-alive
13 - lazyTools
14 - onDiscoveryError
15 - toolFilter
16 - needsApproval
17---
18
19You have one or more live [MCP clients](./mcp) (or pools) and you want the model to use their tools — without writing boilerplate `await client.tools()` calls and `try/finally close()` blocks for every route. By the end of this guide you'll hand those clients to `chat()` via the `mcp` option and let it handle both discovery and lifecycle for you.
20
21> `createMCPClient` tries protocol `2026-07-28` first. If the server does not support that protocol, the client uses the 2025 initialize handshake.
22>
23> Package names for an `@modelcontextprotocol/sdk` import are in [MCP SDK packages](../migration/mcp-sdk).
24
25> **Managed (`mcp` prop) vs manual (`tools` spread)**
26>
27> - Use `mcp: { clients: [...] }` when you want **discovery + lifecycle** managed for you and you are happy with runtime-typed (`unknown`-argument) tools.
28> - Use `tools: [...await client.tools([toolDefinition(...)])]` when you need **fully-typed MCP tools** — the defs overload gives you Zod-validated, TypeScript-typed arguments. See [Manual MCP: typed tools, resources & prompts](./mcp-manual) and [Three Modes of Type Safety](./mcp#three-modes-of-type-safety).
29>
30> Both coexist in the same `chat()` call. Tools from `mcp.clients` are merged with any tools you pass explicitly via `tools`.
31
32## Hand a client to `chat()`
33
34The simplest path: create a client, hand it to `chat()`, and let the run clean it up. `connection` defaults to `'close'`, so the client is closed automatically once the run ends — on success, error, or abort.
35
36```ts ignore
37// src/routes/api.chat.ts
38import { createFileRoute } from '@tanstack/react-router'
39import { chat, toServerSentEventsResponse } from '@tanstack/ai'
40import { openaiText } from '@tanstack/ai-openai'
41import { createMCPClient } from '@tanstack/ai-mcp'
42
43export const Route = createFileRoute('/api/chat')({
44 server: {
45 handlers: {
46 POST: async ({ request }) => {
47 const { messages } = await request.json()
48
49 const mcpClient = await createMCPClient({
50 transport: {
51 type: 'http',
52 url: process.env.MCP_URL!,
53 headers: { Authorization: `Bearer ${process.env.MCP_TOKEN}` },
54 },
55 })
56
57 // chat() discovers mcpClient's tools and closes the connection when done.
58 // No try/finally needed.
59 const stream = chat({
60 adapter: openaiText('gpt-5.5'),
61 messages,
62 mcp: {
63 clients: [mcpClient],
64 // connection: 'close' is the default — shown here for clarity
65 connection: 'close',
66 },
67 })
68
69 return toServerSentEventsResponse(stream)
70 },
71 },
72 },
73})
74```
75
76The examples below show only the part that changes — the client setup and the `chat()` call. They all drop into the same route handler shape as above.
77
78## Multiple servers and pools
79
80Pass any mix of `MCPClient` instances and `MCPClients` pools. Their tools are discovered in parallel and merged into one flat tool set. Pools auto-prefix each server's tools with the config key to prevent name collisions.
81
82```ts
83import { chat } from '@tanstack/ai'
84import { openaiText } from '@tanstack/ai-openai'
85import { createMCPClient, createMCPClients } from '@tanstack/ai-mcp'
86
87const messages = [{ role: 'user' as const, content: 'Hello' }]
88
89// A pool of two servers — their tools are prefixed "github_" and "linear_"
90const githubLinearPool = await createMCPClients({
91 github: {
92 transport: {
93 type: 'http',
94 url: process.env.GITHUB_MCP_URL!,
95 headers: { Authorization: `Bearer ${process.env.GITHUB_MCP_TOKEN}` },
96 },
97 },
98 linear: {
99 transport: {
100 type: 'http',
101 url: process.env.LINEAR_MCP_URL!,
102 headers: { Authorization: `Bearer ${process.env.LINEAR_MCP_TOKEN}` },
103 },
104 },
105})
106
107// A standalone client for an internal server
108const internalClient = await createMCPClient({
109 transport: { type: 'http', url: process.env.INTERNAL_MCP_URL! },
110})
111
112// All three servers' tools are merged: github_*, linear_*, plus internal tools
113const stream = chat({
114 adapter: openaiText('gpt-5.5'),
115 messages,
116 mcp: {
117 clients: [githubLinearPool, internalClient],
118 connection: 'close',
119 },
120})
121```
122
123## Limit which tools the model gets
124
125`chat({ mcp })` sends every tool that each client discovers. To hide tools, or to require approval, set `toolFilter` or `needsApproval` on the client. `chat()` uses the options of each client:
126
127```ts
128import { chat } from '@tanstack/ai'
129import { openaiText } from '@tanstack/ai-openai'
130import { createMCPClient, createMCPClients } from '@tanstack/ai-mcp'
131
132const messages = [{ role: 'user' as const, content: 'Hello' }]
133
134// One client: send only read-only tools
135const github = await createMCPClient({
136 transport: { type: 'http', url: process.env.GITHUB_MCP_URL! },
137 toolFilter: (tool) => tool.annotations?.readOnlyHint === true,
138})
139
140// A pool: each server gets its own options
141const pool = await createMCPClients({
142 linear: {
143 transport: { type: 'http', url: process.env.LINEAR_MCP_URL! },
144 needsApproval: (tool) => tool.annotations?.readOnlyHint !== true,
145 },
146 docs: {
147 transport: { type: 'http', url: process.env.DOCS_MCP_URL! },
148 // Exactly these two tools, by server name
149 toolFilter: ['search_docs', 'get_page'],
150 },
151})
152
153const stream = chat({
154 adapter: openaiText('gpt-5.5'),
155 messages,
156 mcp: { clients: [github, pool] },
157})
158```
159
160A `toolFilter` list is strict. If the server has no tool with a listed name, or a name is listed twice, discovery fails:
161
162- A single client throws `MCPToolFilterError`.
163- A `createMCPClients` pool throws `MCPConnectionError`. Its `cause` is the `MCPToolFilterError`.
164
165`chat()` handles this like any other [discovery failure](#handling-discovery-failures). By default, the run fails before the first model call.
166
167The hints come from the server, and a compromised server can send false hints. For the trust rules and the list form, see [Limit and Gate Tools](./mcp#limit-and-gate-tools).
168
169## Keep connections warm
170
171Creating a new MCP connection on every request adds latency. For production routes with high request rates, create your pool once at module level and pass `connection: 'keep-alive'` so `chat()` never closes it. The pool stays ready for the next request. (Shown as a full route because the placement — module scope vs. handler scope — is the point.)
172
173**Server route (`src/routes/api.chat.ts`):**
174
175```ts ignore
176import { createFileRoute } from '@tanstack/react-router'
177import { chat, toServerSentEventsResponse } from '@tanstack/ai'
178import { openaiText } from '@tanstack/ai-openai'
179import { createMCPClients } from '@tanstack/ai-mcp'
180
181// Created once when the module loads. Shared across all requests.
182const sharedPool = await createMCPClients({
183 github: {
184 transport: {
185 type: 'http',
186 url: process.env.GITHUB_MCP_URL!,
187 headers: { Authorization: `Bearer ${process.env.GITHUB_MCP_TOKEN}` },
188 },
189 },
190 linear: {
191 transport: {
192 type: 'http',
193 url: process.env.LINEAR_MCP_URL!,
194 headers: { Authorization: `Bearer ${process.env.LINEAR_MCP_TOKEN}` },
195 },
196 },
197})
198
199export const Route = createFileRoute('/api/chat')({
200 server: {
201 handlers: {
202 POST: async ({ request }) => {
203 const { messages } = await request.json()
204
205 // keep-alive: sharedPool is never closed by chat(); stays warm for next call
206 const stream = chat({
207 adapter: openaiText('gpt-5.5'),
208 messages,
209 mcp: {
210 clients: [sharedPool],
211 connection: 'keep-alive',
212 },
213 })
214
215 return toServerSentEventsResponse(stream)
216 },
217 },
218 },
219})
220```
221
222**Client component (`src/components/Chat.tsx`):**
223
224```tsx
225import { useChat } from '@tanstack/ai-react'
226import { fetchServerSentEvents } from '@tanstack/ai-client'
227
228const chatOptions = {
229 connection: fetchServerSentEvents('/api/chat'),
230}
231
232export function Chat() {
233 const { messages, sendMessage, status } = useChat(chatOptions)
234
235 return (
236 <div>
237 <ul>
238 {messages.map((m) => (
239 <li key={m.id}>
240 <strong>{m.role}:</strong>{' '}
241 {m.parts.find((p) => p.type === 'text')?.content}
242 </li>
243 ))}
244 </ul>
245 <button
246 onClick={() => sendMessage({ content: 'List my open GitHub issues' })}
247 disabled={status === 'streaming'}
248 >
249 Ask
250 </button>
251 </div>
252 )
253}
254```
255
256## Lazy tool discovery
257
258When your MCP server exposes dozens of tools, sending every schema to the model inflates prompt size and cost. Set `lazyTools: true` to defer sending tool schemas until the model explicitly requests them.
259
260```ts
261import { chat } from '@tanstack/ai'
262import { openaiText } from '@tanstack/ai-openai'
263import { createMCPClient } from '@tanstack/ai-mcp'
264
265const messages = [{ role: 'user' as const, content: 'Hello' }]
266
267const mcpClient = await createMCPClient({
268 transport: { type: 'http', url: process.env.LARGE_MCP_URL! },
269})
270
271const stream = chat({
272 adapter: openaiText('gpt-5.5'),
273 messages,
274 mcp: {
275 clients: [mcpClient],
276 connection: 'close',
277 // Tools are registered but schemas are withheld until the model asks
278 lazyTools: true,
279 },
280})
281```
282
283`lazyTools: true` is forwarded to each source's `tools({ lazy: true })` call. See [Lazy Tool Discovery](./lazy-tool-discovery) for how the model discovers and loads lazy tools at runtime, and [the standalone lazy discovery section](./mcp#lazy-tool-discovery) for using `{ lazy: true }` directly with `client.tools()`.
284
285## Handling discovery failures
286
287By default, if any source fails during discovery, `chat()` throws immediately (fail-fast). When `connection: 'close'`, any sources that did connect are cleaned up before the error propagates — no leaked connections.
288
289**Fail-fast (default):**
290
291```ts
292import { chat } from '@tanstack/ai'
293import { openaiText } from '@tanstack/ai-openai'
294import { createMCPClient } from '@tanstack/ai-mcp'
295
296const messages = [{ role: 'user' as const, content: 'Hello' }]
297
298const mcpClient = await createMCPClient({
299 transport: { type: 'http', url: process.env.MCP_URL! },
300})
301
302// If discovery fails, chat() throws before the first model call.
303// mcpClient is closed automatically (connection: 'close' default).
304const stream = chat({
305 adapter: openaiText('gpt-5.5'),
306 messages,
307 mcp: {
308 clients: [mcpClient],
309 },
310})
311```
312
313**Skip a flaky server and proceed:**
314
315Use `onDiscoveryError` to log the problem and return normally — the failing source is skipped and the run continues with the remaining clients' tools.
316
317```ts
318import { chat } from '@tanstack/ai'
319import { openaiText } from '@tanstack/ai-openai'
320import { createMCPClient } from '@tanstack/ai-mcp'
321
322const messages = [{ role: 'user' as const, content: 'Hello' }]
323
324const primaryClient = await createMCPClient({
325 transport: { type: 'http', url: process.env.PRIMARY_MCP_URL! },
326})
327
328const optionalClient = await createMCPClient({
329 transport: { type: 'http', url: process.env.OPTIONAL_MCP_URL! },
330})
331
332const stream = chat({
333 adapter: openaiText('gpt-5.5'),
334 messages,
335 mcp: {
336 clients: [primaryClient, optionalClient],
337 connection: 'close',
338 onDiscoveryError(error, source) {
339 // Log the failure but let the run proceed without this source's tools.
340 // Throw here (or re-throw `error`) to fail the whole run instead.
341 console.warn('MCP discovery failed for a source, skipping.', error)
342 },
343 },
344})
345```
346
347> Sources passed to `onDiscoveryError` may have already connected before discovery failed. When `connection: 'close'`, they are still closed at the end of the run — even if their tools were skipped.
348
349## Tool name collisions
350
351If two sources in `mcp.clients` expose a tool with the same name, the run fails with an `MCPDuplicateToolNameError` (exported from `@tanstack/ai`) after merging the discovered tools. Note that `chat()` runs lazily — discovery happens when the stream is first consumed, so the error surfaces **through the stream** (the SSE response errors), not as a synchronous throw you can `try/catch` at the `chat()` call site. The fix is to prevent the collision up front: assign a `prefix` to one of the clients, or use `createMCPClients` (which auto-prefixes using the config key).
352
353```ts
354import { chat } from '@tanstack/ai'
355import { openaiText } from '@tanstack/ai-openai'
356import { createMCPClient } from '@tanstack/ai-mcp'
357
358const messages = [{ role: 'user' as const, content: 'Hello' }]
359
360// Both servers expose a tool called "search". Without prefixes the run
361// would fail with MCPDuplicateToolNameError. The prefix option resolves
362// the clash.
363const serverA = await createMCPClient({
364 transport: { type: 'http', url: process.env.SERVER_A_URL! },
365 prefix: 'alpha', // tools become "alpha_search", etc.
366})
367
368const serverB = await createMCPClient({
369 transport: { type: 'http', url: process.env.SERVER_B_URL! },
370 prefix: 'beta', // tools become "beta_search", etc.
371})
372
373const stream = chat({
374 adapter: openaiText('gpt-5.5'),
375 messages,
376 mcp: {
377 clients: [serverA, serverB],
378 connection: 'close',
379 },
380})
381```
382
383For the standalone `pool.tools()` collision behavior and the general `prefix` strategy, see [Tool Name Collisions](./mcp#tool-name-collisions) and [Disable or override the prefix](./mcp#disable-or-override-the-prefix).
384
385## Going further
386
387> **Need fully-typed tools, resources, or prompts in the run?** The `mcp` prop gives you runtime-typed tools and discovery. To spread `toolDefinition`-typed MCP tools, inject MCP resources and prompts, or cancel in-flight MCP calls, see [Manual MCP: typed tools, resources & prompts](./mcp-manual).