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: { transport: { type: 'http', url: process.env.DOCS_MCP_URL! } },
147})
148
149const stream = chat({
150 adapter: openaiText('gpt-5.5'),
151 messages,
152 mcp: { clients: [github, pool] },
153})
154```
155
156The hints come from the server, and a compromised server can send false hints. For the trust rules and a name-based filter, see [Limit and Gate Tools](./mcp#limit-and-gate-tools).
157
158## Keep connections warm
159
160Creating 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.)
161
162**Server route (`src/routes/api.chat.ts`):**
163
164```ts ignore
165import { createFileRoute } from '@tanstack/react-router'
166import { chat, toServerSentEventsResponse } from '@tanstack/ai'
167import { openaiText } from '@tanstack/ai-openai'
168import { createMCPClients } from '@tanstack/ai-mcp'
169
170// Created once when the module loads. Shared across all requests.
171const sharedPool = await createMCPClients({
172 github: {
173 transport: {
174 type: 'http',
175 url: process.env.GITHUB_MCP_URL!,
176 headers: { Authorization: `Bearer ${process.env.GITHUB_MCP_TOKEN}` },
177 },
178 },
179 linear: {
180 transport: {
181 type: 'http',
182 url: process.env.LINEAR_MCP_URL!,
183 headers: { Authorization: `Bearer ${process.env.LINEAR_MCP_TOKEN}` },
184 },
185 },
186})
187
188export const Route = createFileRoute('/api/chat')({
189 server: {
190 handlers: {
191 POST: async ({ request }) => {
192 const { messages } = await request.json()
193
194 // keep-alive: sharedPool is never closed by chat(); stays warm for next call
195 const stream = chat({
196 adapter: openaiText('gpt-5.5'),
197 messages,
198 mcp: {
199 clients: [sharedPool],
200 connection: 'keep-alive',
201 },
202 })
203
204 return toServerSentEventsResponse(stream)
205 },
206 },
207 },
208})
209```
210
211**Client component (`src/components/Chat.tsx`):**
212
213```tsx
214import { useChat } from '@tanstack/ai-react'
215import { fetchServerSentEvents } from '@tanstack/ai-client'
216
217const chatOptions = {
218 connection: fetchServerSentEvents('/api/chat'),
219}
220
221export function Chat() {
222 const { messages, sendMessage, status } = useChat(chatOptions)
223
224 return (
225 <div>
226 <ul>
227 {messages.map((m) => (
228 <li key={m.id}>
229 <strong>{m.role}:</strong>{' '}
230 {m.parts.find((p) => p.type === 'text')?.content}
231 </li>
232 ))}
233 </ul>
234 <button
235 onClick={() => sendMessage({ content: 'List my open GitHub issues' })}
236 disabled={status === 'streaming'}
237 >
238 Ask
239 </button>
240 </div>
241 )
242}
243```
244
245## Lazy tool discovery
246
247When 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.
248
249```ts
250import { chat } from '@tanstack/ai'
251import { openaiText } from '@tanstack/ai-openai'
252import { createMCPClient } from '@tanstack/ai-mcp'
253
254const messages = [{ role: 'user' as const, content: 'Hello' }]
255
256const mcpClient = await createMCPClient({
257 transport: { type: 'http', url: process.env.LARGE_MCP_URL! },
258})
259
260const stream = chat({
261 adapter: openaiText('gpt-5.5'),
262 messages,
263 mcp: {
264 clients: [mcpClient],
265 connection: 'close',
266 // Tools are registered but schemas are withheld until the model asks
267 lazyTools: true,
268 },
269})
270```
271
272`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()`.
273
274## Handling discovery failures
275
276By 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.
277
278**Fail-fast (default):**
279
280```ts
281import { chat } from '@tanstack/ai'
282import { openaiText } from '@tanstack/ai-openai'
283import { createMCPClient } from '@tanstack/ai-mcp'
284
285const messages = [{ role: 'user' as const, content: 'Hello' }]
286
287const mcpClient = await createMCPClient({
288 transport: { type: 'http', url: process.env.MCP_URL! },
289})
290
291// If discovery fails, chat() throws before the first model call.
292// mcpClient is closed automatically (connection: 'close' default).
293const stream = chat({
294 adapter: openaiText('gpt-5.5'),
295 messages,
296 mcp: {
297 clients: [mcpClient],
298 },
299})
300```
301
302**Skip a flaky server and proceed:**
303
304Use `onDiscoveryError` to log the problem and return normally — the failing source is skipped and the run continues with the remaining clients' tools.
305
306```ts
307import { chat } from '@tanstack/ai'
308import { openaiText } from '@tanstack/ai-openai'
309import { createMCPClient } from '@tanstack/ai-mcp'
310
311const messages = [{ role: 'user' as const, content: 'Hello' }]
312
313const primaryClient = await createMCPClient({
314 transport: { type: 'http', url: process.env.PRIMARY_MCP_URL! },
315})
316
317const optionalClient = await createMCPClient({
318 transport: { type: 'http', url: process.env.OPTIONAL_MCP_URL! },
319})
320
321const stream = chat({
322 adapter: openaiText('gpt-5.5'),
323 messages,
324 mcp: {
325 clients: [primaryClient, optionalClient],
326 connection: 'close',
327 onDiscoveryError(error, source) {
328 // Log the failure but let the run proceed without this source's tools.
329 // Throw here (or re-throw `error`) to fail the whole run instead.
330 console.warn('MCP discovery failed for a source, skipping.', error)
331 },
332 },
333})
334```
335
336> 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.
337
338## Tool name collisions
339
340If 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).
341
342```ts
343import { chat } from '@tanstack/ai'
344import { openaiText } from '@tanstack/ai-openai'
345import { createMCPClient } from '@tanstack/ai-mcp'
346
347const messages = [{ role: 'user' as const, content: 'Hello' }]
348
349// Both servers expose a tool called "search". Without prefixes the run
350// would fail with MCPDuplicateToolNameError. The prefix option resolves
351// the clash.
352const serverA = await createMCPClient({
353 transport: { type: 'http', url: process.env.SERVER_A_URL! },
354 prefix: 'alpha', // tools become "alpha_search", etc.
355})
356
357const serverB = await createMCPClient({
358 transport: { type: 'http', url: process.env.SERVER_B_URL! },
359 prefix: 'beta', // tools become "beta_search", etc.
360})
361
362const stream = chat({
363 adapter: openaiText('gpt-5.5'),
364 messages,
365 mcp: {
366 clients: [serverA, serverB],
367 connection: 'close',
368 },
369})
370```
371
372For 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).
373
374## Going further
375
376> **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).