Open History to see the last commit
1---
2title: Managed MCP with chat()
3id: mcp-managed
4order: 9
5description: "Pass MCP clients and pools to chat() in the mcp option. chat() finds their tools and closes the connections 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
19Pass MCP clients to `chat()` in the `mcp` option. `chat()` loads their tools and closes the clients when the run ends.
20
21## Quick setup
22
231. Make a client in your chat route.
242. Pass it in `mcp.clients`.
25
26```ts ignore
27// src/routes/api.chat.ts
28import { createFileRoute } from '@tanstack/react-router'
29import { chat, toServerSentEventsResponse } from '@tanstack/ai'
30import { openaiText } from '@tanstack/ai-openai'
31import { createMCPClient } from '@tanstack/ai-mcp'
32
33export const Route = createFileRoute('/api/chat')({
34 server: {
35 handlers: {
36 POST: async ({ request }) => {
37 const { messages, threadId } = await request.json()
38
39 const mcpClient = await createMCPClient({
40 transport: {
41 type: 'http',
42 url: process.env.MCP_URL!,
43 headers: { Authorization: `Bearer ${process.env.MCP_TOKEN}` },
44 },
45 })
46
47 // chat() finds the tools of mcpClient and closes it when the run ends.
48 const stream = chat({
49 adapter: openaiText('gpt-6.1-sol'),
50 messages,
51 threadId,
52 mcp: {
53 clients: [mcpClient],
54 // 'close' is the default. It is shown here so you can see it.
55 connection: 'close',
56 },
57 })
58
59 return toServerSentEventsResponse(stream)
60 },
61 },
62 },
63})
64```
65
66That is all. There is no `try/finally`. Your `useChat` code does not change.
67
68## How it works
69
70- Before the first model call, `chat()` calls `tools()` on each client at the same time and merges the results into one tool set.
71- Tools from `mcp.clients` merge with any tools that you pass in `tools`. You can use both in one call.
72- `connection: 'close'` (the default) closes each client when the run ends: on success, on error, and on abort.
73- `connection: 'keep-alive'` never closes the clients. You own them.
74
75> [!NOTE]
76> Tools from `mcp` have arguments of type `unknown` at compile time. For Zod-validated, typed arguments, spread `await client.tools([toolDefinition(...)])` into `tools` yourself. See [Manual MCP](./mcp-manual) and [Three Modes of Type Safety](./mcp-advanced#three-modes-of-type-safety).
77
78The samples below show only the client setup and the `chat()` call. They go into the same route as above.
79
80## Multiple servers and pools
81
82Pass any mix of `MCPClient` instances and `MCPClients` pools. A pool adds the config key as a prefix to the tool names of each server, so the names do not collide.
83
84```ts
85import { chat } from '@tanstack/ai'
86import { openaiText } from '@tanstack/ai-openai'
87import { createMCPClient, createMCPClients } from '@tanstack/ai-mcp'
88
89const messages = [{ role: 'user' as const, content: 'Hello' }]
90
91// A pool of two servers. Their tools get the prefixes "github_" and "linear_".
92const githubLinearPool = await createMCPClients({
93 github: {
94 transport: {
95 type: 'http',
96 url: process.env.GITHUB_MCP_URL!,
97 headers: { Authorization: `Bearer ${process.env.GITHUB_MCP_TOKEN}` },
98 },
99 },
100 linear: {
101 transport: {
102 type: 'http',
103 url: process.env.LINEAR_MCP_URL!,
104 headers: { Authorization: `Bearer ${process.env.LINEAR_MCP_TOKEN}` },
105 },
106 },
107})
108
109// A standalone client for an internal server
110const internalClient = await createMCPClient({
111 transport: { type: 'http', url: process.env.INTERNAL_MCP_URL! },
112})
113
114// The tools of all three servers merge: github_*, linear_*, and the internal tools
115const stream = chat({
116 adapter: openaiText('gpt-6.1-sol'),
117 messages,
118 threadId: 'thread-1',
119 mcp: {
120 clients: [githubLinearPool, internalClient],
121 connection: 'close',
122 },
123})
124```
125
126## Limit which tools the model gets
127
128`chat({ mcp })` sends every tool that each client finds. To hide tools, or to ask for approval, set `toolFilter` or `needsApproval` on the client. `chat()` uses the options of each client:
129
130```ts
131import { chat } from '@tanstack/ai'
132import { openaiText } from '@tanstack/ai-openai'
133import { createMCPClient, createMCPClients } from '@tanstack/ai-mcp'
134
135const messages = [{ role: 'user' as const, content: 'Hello' }]
136
137// One client: send only read-only tools
138const github = await createMCPClient({
139 transport: { type: 'http', url: process.env.GITHUB_MCP_URL! },
140 toolFilter: (tool) => tool.annotations?.readOnlyHint === true,
141})
142
143// A pool: each server gets its own options
144const pool = await createMCPClients({
145 linear: {
146 transport: { type: 'http', url: process.env.LINEAR_MCP_URL! },
147 needsApproval: (tool) => tool.annotations?.readOnlyHint !== true,
148 },
149 docs: {
150 transport: { type: 'http', url: process.env.DOCS_MCP_URL! },
151 // Exactly these two tools, by server name
152 toolFilter: ['search_docs', 'get_page'],
153 },
154})
155
156const stream = chat({
157 adapter: openaiText('gpt-6.1-sol'),
158 messages,
159 threadId: 'thread-1',
160 mcp: { clients: [github, pool] },
161})
162```
163
164A `toolFilter` list is strict. If the server has no tool with a listed name, or a name is listed twice, discovery fails:
165
166- A single client throws `MCPToolFilterError`.
167- A `createMCPClients` pool throws `MCPConnectionError`. Its `cause` is the `MCPToolFilterError`.
168
169`chat()` handles this like any other [discovery failure](#handling-discovery-failures). By default, the run fails before the first model call.
170
171> [!WARNING]
172> The 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-advanced#limit-and-gate-tools).
173
174## Keep connections warm
175
176A new MCP connection on each request adds latency. On a busy route, make the pool once at module level and pass `connection: 'keep-alive'`. Then `chat()` never closes the pool, and the next request uses the same connections.
177
178Where you make the pool is important here, so this is a full route.
179
180Server route (`src/routes/api.chat.ts`):
181
182```ts ignore
183import { createFileRoute } from '@tanstack/react-router'
184import { chat, toServerSentEventsResponse } from '@tanstack/ai'
185import { openaiText } from '@tanstack/ai-openai'
186import { createMCPClients } from '@tanstack/ai-mcp'
187
188// Made once when the module loads. All requests share it.
189const sharedPool = await createMCPClients({
190 github: {
191 transport: {
192 type: 'http',
193 url: process.env.GITHUB_MCP_URL!,
194 headers: { Authorization: `Bearer ${process.env.GITHUB_MCP_TOKEN}` },
195 },
196 },
197 linear: {
198 transport: {
199 type: 'http',
200 url: process.env.LINEAR_MCP_URL!,
201 headers: { Authorization: `Bearer ${process.env.LINEAR_MCP_TOKEN}` },
202 },
203 },
204})
205
206export const Route = createFileRoute('/api/chat')({
207 server: {
208 handlers: {
209 POST: async ({ request }) => {
210 const { messages, threadId } = await request.json()
211
212 // keep-alive: chat() never closes sharedPool. It stays warm for the next call.
213 const stream = chat({
214 adapter: openaiText('gpt-6.1-sol'),
215 messages,
216 threadId,
217 mcp: {
218 clients: [sharedPool],
219 connection: 'keep-alive',
220 },
221 })
222
223 return toServerSentEventsResponse(stream)
224 },
225 },
226 },
227})
228```
229
230Client component (`src/components/Chat.tsx`):
231
232```tsx
233import { useChat } from '@tanstack/ai-react'
234import { fetchServerSentEvents } from '@tanstack/ai-client'
235
236const chatOptions = {
237 connection: fetchServerSentEvents('/api/chat'),
238 threadId: 'support-chat',
239}
240
241export function Chat() {
242 const { messages, sendMessage, status } = useChat(chatOptions)
243
244 return (
245 <div>
246 <ul>
247 {messages.map((m) => (
248 <li key={m.id}>
249 <strong>{m.role}:</strong>{' '}
250 {m.parts.find((p) => p.type === 'text')?.content}
251 </li>
252 ))}
253 </ul>
254 <button
255 onClick={() => sendMessage({ content: 'List my open GitHub issues' })}
256 disabled={status === 'streaming'}
257 >
258 Ask
259 </button>
260 </div>
261 )
262}
263```
264
265## Lazy tool discovery
266
267A server with dozens of tools makes the prompt big and expensive. Set `lazyTools: true` to send a tool schema only when the model asks for it:
268
269```ts
270import { chat } from '@tanstack/ai'
271import { openaiText } from '@tanstack/ai-openai'
272import { createMCPClient } from '@tanstack/ai-mcp'
273
274const messages = [{ role: 'user' as const, content: 'Hello' }]
275
276const mcpClient = await createMCPClient({
277 transport: { type: 'http', url: process.env.LARGE_MCP_URL! },
278})
279
280const stream = chat({
281 adapter: openaiText('gpt-6.1-sol'),
282 messages,
283 threadId: 'thread-1',
284 mcp: {
285 clients: [mcpClient],
286 connection: 'close',
287 // The tools are registered, but their schemas wait until the model asks
288 lazyTools: true,
289 },
290})
291```
292
293`chat()` passes `lazyTools: true` to the `tools({ lazy: true })` call of each source. See [Lazy Tool Discovery](./lazy-tool-discovery) for how the model finds lazy tools. To use `{ lazy: true }` on `client.tools()` directly, see [Lazy Tool Discovery for MCP](./mcp-advanced#lazy-tool-discovery).
294
295## Advanced
296
297### Handling discovery failures
298
299By default, if one source fails during discovery, `chat()` fails at once. With `connection: 'close'`, `chat()` first closes the sources that did connect. No connection stays open.
300
301Fail fast (the default):
302
303```ts
304import { chat } from '@tanstack/ai'
305import { openaiText } from '@tanstack/ai-openai'
306import { createMCPClient } from '@tanstack/ai-mcp'
307
308const messages = [{ role: 'user' as const, content: 'Hello' }]
309
310const mcpClient = await createMCPClient({
311 transport: { type: 'http', url: process.env.MCP_URL! },
312})
313
314// If discovery fails, chat() throws before the first model call.
315// mcpClient closes automatically (connection: 'close' is the default).
316const stream = chat({
317 adapter: openaiText('gpt-6.1-sol'),
318 messages,
319 threadId: 'thread-1',
320 mcp: {
321 clients: [mcpClient],
322 },
323})
324```
325
326Skip a flaky server and continue: use `onDiscoveryError` to log the error and return normally. `chat()` skips the failed source and runs with the tools of the other clients.
327
328```ts
329import { chat } from '@tanstack/ai'
330import { openaiText } from '@tanstack/ai-openai'
331import { createMCPClient } from '@tanstack/ai-mcp'
332
333const messages = [{ role: 'user' as const, content: 'Hello' }]
334
335const primaryClient = await createMCPClient({
336 transport: { type: 'http', url: process.env.PRIMARY_MCP_URL! },
337})
338
339const optionalClient = await createMCPClient({
340 transport: { type: 'http', url: process.env.OPTIONAL_MCP_URL! },
341})
342
343const stream = chat({
344 adapter: openaiText('gpt-6.1-sol'),
345 messages,
346 threadId: 'thread-1',
347 mcp: {
348 clients: [primaryClient, optionalClient],
349 connection: 'close',
350 onDiscoveryError(error, source) {
351 // Log the failure, and let the run continue without the tools of this source.
352 // Throw here (or throw `error` again) to fail the whole run instead.
353 console.warn('MCP discovery failed for a source, skipping.', error)
354 },
355 },
356})
357```
358
359> [!NOTE]
360> A source that `onDiscoveryError` gets can be connected already. With `connection: 'close'`, `chat()` still closes it when the run ends, even though it skipped its tools.
361
362### Tool name collisions
363
364If two sources in `mcp.clients` have a tool with the same name, the run fails with `MCPDuplicateToolNameError` (exported from `@tanstack/ai`).
365
366`chat()` is lazy. Discovery starts when something first reads the stream. So the error comes through the stream (the SSE response fails). You cannot catch it with a `try/catch` around the `chat()` call.
367
368Prevent the collision instead. Give one of the clients a `prefix`, or use `createMCPClients`, which adds the config key as a prefix:
369
370```ts
371import { chat } from '@tanstack/ai'
372import { openaiText } from '@tanstack/ai-openai'
373import { createMCPClient } from '@tanstack/ai-mcp'
374
375const messages = [{ role: 'user' as const, content: 'Hello' }]
376
377// Both servers have a tool called "search". Without prefixes, the run
378// fails with MCPDuplicateToolNameError. The prefix option prevents this.
379const serverA = await createMCPClient({
380 transport: { type: 'http', url: process.env.SERVER_A_URL! },
381 prefix: 'alpha', // tools become "alpha_search", and so on
382})
383
384const serverB = await createMCPClient({
385 transport: { type: 'http', url: process.env.SERVER_B_URL! },
386 prefix: 'beta', // tools become "beta_search", and so on
387})
388
389const stream = chat({
390 adapter: openaiText('gpt-6.1-sol'),
391 messages,
392 threadId: 'thread-1',
393 mcp: {
394 clients: [serverA, serverB],
395 connection: 'close',
396 },
397})
398```
399
400For collisions in `pool.tools()` and the `prefix` options, see [Tool Name Collisions](./mcp-advanced#tool-name-collisions) and [Disable or override the prefix](./mcp-advanced#disable-or-override-the-prefix).