Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

mcp.md

187 lines6.1 KB

1---
2title: MCP Server Tools
3id: mcp
4order: 8
5description: "Connect TanStack AI to a Model Context Protocol server with createMCPClient, and give the model the tools of that server in chat()."
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`createMCPClient` connects to an MCP server. Pass that client to `chat()` in the `mcp` option.
19​
20> [!NOTE]
21> MCP tools run on the server. Call `createMCPClient` in a server route or a serverless function, never in browser code.
22​
23## Quick setup
24​
25You need a working chat first. If you do not have one, start with the [Quick Start](../getting-started/quick-start).
26​
271. Install the MCP client:
28​
29<!-- ::start:tabs variant="package-manager" mode="install" -->
30​
31react: @tanstack/ai-mcp @modelcontextprotocol/client
32vue: @tanstack/ai-mcp @modelcontextprotocol/client
33solid: @tanstack/ai-mcp @modelcontextprotocol/client
34svelte: @tanstack/ai-mcp @modelcontextprotocol/client
35preact: @tanstack/ai-mcp @modelcontextprotocol/client
36angular: @tanstack/ai-mcp @modelcontextprotocol/client
37vanilla: @tanstack/ai-mcp @modelcontextprotocol/client
38octane: @tanstack/ai-mcp @modelcontextprotocol/client
39​
40<!-- ::end:tabs -->
41​
422. In your chat route, connect to the server and pass the client to `chat()`. Change the URL to the URL of your MCP server:
43​
44```ts ignore
45// src/routes/api.chat.ts (TanStack Start)
46import { createFileRoute } from '@tanstack/react-router'
47import { chat, toServerSentEventsResponse } from '@tanstack/ai'
48import { openaiText } from '@tanstack/ai-openai'
49import { createMCPClient } from '@tanstack/ai-mcp'
50​
51export const Route = createFileRoute('/api/chat')({
52 server: {
53 handlers: {
54 POST: async ({ request }) => {
55 const { messages, threadId } = await request.json()
56​
57 const mcp = await createMCPClient({
58 transport: {
59 type: 'http',
60 url: 'https://my-mcp-server.example.com/mcp',
61 },
62 })
63​
64 // chat() finds the tools and closes the client when the run ends.
65 const stream = chat({
66 adapter: openaiText('gpt-6.1-sol'),
67 messages,
68 threadId,
69 mcp: { clients: [mcp] },
70 })
71​
72 return toServerSentEventsResponse(stream)
73 },
74 },
75 },
76})
77```
78​
793. Keep your client code. `useChat` reads this endpoint the same way as any other chat endpoint:
80​
81```tsx
82// src/components/Chat.tsx
83import { useChat } from '@tanstack/ai-react'
84import { fetchServerSentEvents } from '@tanstack/ai-client'
85​
86export function Chat() {
87 const { messages, sendMessage, status } = useChat({
88 connection: fetchServerSentEvents('/api/chat'),
89 threadId: 'support-chat',
90 })
91​
92 return (
93 <div>
94 {messages.map((m) => (
95 <div key={m.id}>
96 <strong>{m.role}:</strong>{' '}
97 {m.parts.find((p) => p.type === 'text')?.content}
98 </div>
99 ))}
100 <button
101 onClick={() => sendMessage({ content: 'Hello' })}
102 disabled={status === 'streaming'}
103 >
104 Send
105 </button>
106 </div>
107 )
109```
110​
111Now ask the model something that needs one of the server tools. The model calls the tool, your server runs it on the MCP server, and the answer streams back.
112​
113## How it works
114​
115- `createMCPClient` connects to the server. It tries protocol `2026-07-28` first. If the server does not support it, the client uses the 2025 handshake.
116- `chat({ mcp })` asks each client for its tools before the first model call.
117- When the model calls a tool, `chat()` sends the call to the MCP server and gives the result back to the model.
118- When the run ends, `chat()` closes the client. This happens on success, on error, and on abort.
119​
120> [!NOTE]
121> MCP tool arguments have the type `unknown` at compile time. The client checks them against the JSON Schema of the server at runtime.
122​
123## Connect to your server
124​
125Pick the transport that your server uses.
126​
127HTTP (Streamable HTTP) is the usual choice for a remote server. Add `headers` when the server needs a token:
128​
129```ts
130import { createMCPClient } from '@tanstack/ai-mcp'
131​
132const mcp = await createMCPClient({
133 transport: {
134 type: 'http',
135 url: 'https://my-mcp-server.example.com/mcp',
136 headers: { Authorization: `Bearer ${process.env.MCP_TOKEN}` },
137 },
138})
139```
140​
141SSE is for servers that use the older SSE transport:
142​
143```ts
144import { createMCPClient } from '@tanstack/ai-mcp'
145​
146const mcp = await createMCPClient({
147 transport: {
148 type: 'sse',
149 url: 'https://my-mcp-server.example.com/sse',
150 headers: { Authorization: `Bearer ${process.env.MCP_TOKEN}` },
151 },
152})
153```
154​
155stdio starts a local MCP process. It works in Node.js only. It has its own import path, so edge bundles do not include Node modules:
156​
157```ts
158import { stdioTransport } from '@tanstack/ai-mcp/stdio'
159import { createMCPClient } from '@tanstack/ai-mcp'
160​
161const mcp = await createMCPClient({
162 transport: stdioTransport({
163 command: 'node',
164 args: ['./my-mcp-server.js'],
165 env: { API_KEY: process.env.API_KEY ?? '' },
166 }),
167})
168```
169​
170For OAuth, custom transports, and timeouts, see [MCP Server Tools: Advanced](./mcp-advanced).
171​
172## What to read next
173​
174- **Hide tools or ask the user first.** A server can expose tools that write or delete data. See [Limit and Gate Tools](./mcp-advanced#limit-and-gate-tools).
175- **Many servers, warm connections, or a flaky server.** See [Managed MCP with chat()](./mcp-managed).
176- **Typed tool arguments, resources, and prompts.** See [Manual MCP](./mcp-manual).
177- **Compile-checked tool names.** See [MCP Type Generation](./mcp-codegen).
178- **The server asks the user for input during a tool call.** See [MCP Client Input](./mcp-input).
179​
180> [!NOTE]
181> This page is about MCP on your server. To expose browser actions to a browser agent, see [WebMCP Tools](./webmcp). WebMCP calls go to the browser agent, and they do not become tool results in a TanStack chat run.
182​
183Package names for an `@modelcontextprotocol/sdk` import are in [MCP SDK packages](../migration/mcp-sdk).
184​
185## Advanced
186​
187Every option of the client is on [MCP Server Tools: Advanced](./mcp-advanced): OAuth, timeouts, the three modes of type safety, tool annotations, pools, lifecycle, tool names, lazy discovery, and the error reference.