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

server.md

333 lines11.4 KB

1---
2title: Serve Tools over HTTP
3id: mcp-server
4order: 13
5description: "Serve your TanStack tools as an MCP server with createMCPServer, so Claude Desktop, Cursor, or any other MCP host can call them."
6keywords:
7 - tanstack ai
8 - mcp
9 - model context protocol
10 - mcp server
11 - createMCPServer
12 - tanstack start
13 - cloudflare workers
14---
15​
16`createMCPServer` exposes your TanStack server tools over MCP. A host such as Claude Desktop or Cursor can then call them.
17​
18Your route returns `server.fetch(request)`, and the host connects to that URL.
19​
20## Quick setup
21​
22This setup uses TanStack Start. For Cloudflare Workers, see [Cloudflare Workers](#cloudflare-workers).
23​
241. Install the packages:
25​
26<!-- ::start:tabs variant="package-manager" mode="install" -->
27​
28react: @tanstack/ai @tanstack/ai-mcp @modelcontextprotocol/server zod
29vue: @tanstack/ai @tanstack/ai-mcp @modelcontextprotocol/server zod
30solid: @tanstack/ai @tanstack/ai-mcp @modelcontextprotocol/server zod
31svelte: @tanstack/ai @tanstack/ai-mcp @modelcontextprotocol/server zod
32preact: @tanstack/ai @tanstack/ai-mcp @modelcontextprotocol/server zod
33angular: @tanstack/ai @tanstack/ai-mcp @modelcontextprotocol/server zod
34vanilla: @tanstack/ai @tanstack/ai-mcp @modelcontextprotocol/server zod
35octane: @tanstack/ai @tanstack/ai-mcp @modelcontextprotocol/server zod
36​
37<!-- ::end:tabs -->
38​
392. Create `src/mcp-server.ts` with your tools:
40​
41```ts
42// src/mcp-server.ts
43import { toolDefinition } from '@tanstack/ai'
44import { createMCPServer } from '@tanstack/ai-mcp/server'
45import { z } from 'zod'
46​
47const getWeather = toolDefinition({
48 name: 'get_weather',
49 description: 'Get the weather for a city',
50 inputSchema: z.object({
51 city: z.string(),
52 }),
53}).server(async ({ city }) => {
54 return `Sunny in ${city}`
55})
56​
57export const server = createMCPServer({
58 name: 'weather',
59 version: '1.0.0',
60 tools: [getWeather],
61})
62​
63export function handleMcp(request: Request) {
64 return server.fetch(request)
66```
67​
683. Create the route, and send each request to `handleMcp`:
69​
70```ts ignore
71// src/routes/api.mcp.ts
72import { createFileRoute } from '@tanstack/react-router'
73import { handleMcp } from '../mcp-server'
74​
75export const Route = createFileRoute('/api/mcp')({
76 server: {
77 handlers: {
78 GET: ({ request }) => handleMcp(request),
79 POST: ({ request }) => handleMcp(request),
80 DELETE: ({ request }) => handleMcp(request),
81 },
82 },
83})
84```
85​
864. Start the app. Then add the URL of the route (for example, `http://localhost:3000/api/mcp`) to your MCP host.
87​
88The host lists `get_weather`, and it can call the tool. The answer is `Sunny in Paris` for the city `Paris`.
89​
90For a full app with a tool, a resource, and a prompt, follow [Build an MCP Server](../tutorials/mcp-server).
91​
92## How it works
93​
94- You create the server once. `handleMcp` calls `server.fetch` for each request.
95- The server speaks MCP over HTTP. It finds the tool by name, parses the input with `inputSchema`, and runs your `.server()` function.
96- By default the server keeps no session. As a result, any instance can answer any request, and a serverless host works with no extra setup.
97​
98To call this server from your own `chat()` route, see [MCP Server Tools](../tools/mcp).
99​
100## Cloudflare Workers
101​
1021. Save the server code from the quick setup as `src/mcp-server.ts`.
1032. Call `handleMcp` for each request:
104​
105```ts
106// src/index.ts
107import { handleMcp } from './mcp-server'
108​
109export default {
110 async fetch(request: Request) {
111 return handleMcp(request)
112 },
114```
115​
116The worker URL is the MCP URL. Each request can reach a different instance. This works because the server keeps no spec 2025 session by default. See [MCP Server Sessions](./server-sessions).
117​
118## Tell the host what a tool does
119​
120A host asks the user before it runs a tool, unless the tool says that it only reads. Set `metadata.title` and `metadata.annotations` on the tool definition. The host gets them as the MCP tool title and annotations.
121​
122```ts
123import { toolDefinition } from '@tanstack/ai'
124import { z } from 'zod'
125​
126export const listNotes = toolDefinition({
127 name: 'list_notes',
128 description: 'List the notes of the signed-in user',
129 inputSchema: z.object({}),
130 metadata: {
131 title: 'List notes',
132 annotations: { readOnlyHint: true, idempotentHint: true },
133 },
134}).server(async () => [])
135```
136​
137The annotation names are the MCP names:
138​
139- `readOnlyHint`: the tool changes nothing.
140- `destructiveHint`: the tool can delete or overwrite data.
141- `idempotentHint`: a repeat call with the same input changes nothing more.
142- `openWorldHint`: the tool reaches outside your system.
143​
144To show an [MCP Apps](./apps) view for a tool, set `metadata._meta`. The host gets it as the MCP tool `_meta`. The key `ui.resourceUri` links the tool to the `ui://` resource of the view.
145​
146```ts
147import { toolDefinition } from '@tanstack/ai'
148import { z } from 'zod'
149​
150export const showChart = toolDefinition({
151 name: 'show_chart',
152 description: 'Show the sales chart',
153 inputSchema: z.object({}),
154 metadata: {
155 _meta: { ui: { resourceUri: 'ui://charts/sales' } },
156 },
157}).server(async () => ({ total: 42 }))
158```
159​
160## Call the server with types
161​
162Your app calls the deployed server. You want a wrong tool name or a wrong argument to fail at compile time.
163​
1641. Export `server` from `src/mcp-server.ts`.
1652. In the app, import its type with `import type`.
1663. Pass `typeof server` to `createMCPClient`, with the URL of the server.
167​
168```ts
169// app/weather.ts
170import { createMCPClient } from '@tanstack/ai-mcp'
171import type { server } from '../src/mcp-server'
172​
173export async function forecast(city: string) {
174 const client = await createMCPClient<typeof server>({
175 transport: { type: 'http', url: 'https://mcp.example.com/api/mcp' },
176 })
177 try {
178 return await client.callTool('get_weather', { city })
179 } finally {
180 await client.close()
181 }
183```
184​
185Now `callTool('get_weather', { city })` goes to the deployed server, and `callTool('get_wether', { city })` fails the type check.
186​
187What the types check:
188​
189- `callTool` accepts only the tool names of `server`, and the input type of each tool.
190- `getPrompt` accepts only the prompt names of `server`, and the argument type of each prompt.
191- `readResource` accepts only the resource URIs of `server`.
192​
193`import type` keeps the server code out of the app bundle.
194​
195## Add more to your server
196​
197Pick the one you need:
198​
199- Serve documents and prompts: [Serve Resources and Prompts](./server-content).
200- Let only signed-in users call the tools: [MCP Server Auth](./server-auth).
201- Ask the user a question from a tool: [Ask for Input](./server-input).
202- Run a long tool in the background: [MCP Server Tasks](./server-tasks).
203- Let a desktop host start your server as a local process: [MCP Server on stdio](./server-stdio).
204​
205## Advanced
206​
207### Log SDK errors
208​
209Some errors never reach your tool code:
210​
211- transport errors
212- protocol errors
213- rejected requests
214​
215Pass `onerror` to send them to your logs. `serveMCPStdio` also sends its transport errors there. `onerror` only reports. The response does not change.
216​
217```ts
218import { createMCPServer } from '@tanstack/ai-mcp/server'
219​
220const server = createMCPServer({
221 name: 'weather',
222 version: '1.0.0',
223 onerror: (error) => console.error('MCP error', error),
224})
225```
226​
227### Serve an MCP extension
228​
229An [MCP extension](https://modelcontextprotocol.io/extensions/overview) adds methods that the core spec does not have. For example, the [Skills extension](https://modelcontextprotocol.io/extensions/skills/overview) adds `skills/list` and `skills/get`. A client uses an extension only when the server lists it in `capabilities.extensions`.
230​
231Pass `setup` to get each SDK `McpServer` before it connects. Declare the extension there, then add a handler for each of its methods:
232​
233```ts
234import { createMCPServer } from '@tanstack/ai-mcp/server'
235import { z } from 'zod'
236​
237const server = createMCPServer({
238 name: 'notes',
239 version: '1.0.0',
240 setup: (mcp, context) => {
241 const userId = context?.userId
242 mcp.server.registerCapabilities({
243 extensions: { 'com.example/notes': {} },
244 })
245 mcp.server.setRequestHandler(
246 'notes/count',
247 { params: z.object({}) },
248 () => ({ count: typeof userId === 'string' ? userId.length : 0 }),
249 )
250 },
251})
252​
253export function handleMcp(request: Request, userId: string) {
254 return server.handle(request, { context: { userId } })
256```
257​
258Rules for `setup`:
259​
260- It runs each time the server builds an `McpServer`. That is each request, or once for each spec 2025 session when `sessions` is `'memory'`. Keep it fast.
261- The second argument is the `context` object from `server.handle`. On a spec 2025 memory session, that value is from the request that opened the session. A later request on that session does not run `setup` again. A tool on the later request sees the new context.
262- It must be synchronous. The server connects as soon as `setup` returns, so an `async` function fails the request.
263- Add new methods only. Do not replace a method that the server already handles, such as `tools/call`.
264​
265To call the method from a client, see [Extension methods](../tools/mcp-manual#extension-methods).
266​
267### Shape the result yourself
268​
269By default, the server shapes the tool result for you:
270​
271- It parses the tool output with its `outputSchema`. If the output does not match, the call returns a tool error that names the tool.
272- It sends the output as one text block.
273- If the output is an object, it also goes on `structuredContent`.
274​
275When you want more than one block, or `isError` without an exception, return an MCP `CallToolResult` from a tool with no `outputSchema`. The server sends it as is.
276​
277```ts
278import { toolDefinition } from '@tanstack/ai'
279import { z } from 'zod'
280import { db } from './db'
281​
282export const countNotes = toolDefinition({
283 name: 'count_notes',
284 description: 'Count the notes and list them',
285 inputSchema: z.object({}),
286}).server(async () => {
287 const notes = await db.notes.list()
288 return {
289 content: [
290 { type: 'text' as const, text: `${notes.length} notes.` },
291 { type: 'text' as const, text: JSON.stringify(notes) },
292 ],
293 structuredContent: { count: notes.length },
294 }
295})
296```
297​
298The first block is a short summary for the model. The second block is the data.
299​
300### Fixed lists and subscriptions
301​
302`createMCPServer` serves fixed lists of tools, resources, and prompts. As a result:
303​
304- It reports `listChanged: false`.
305- It answers `subscriptions/listen` with JSON-RPC `-32601`.
306- A Worker does not keep an idle subscription stream open.
307​
308### What the typed HTTP client returns
309​
310For `createMCPClient<typeof server>({ transport })`:
311​
312- The client connects to the URL and speaks MCP. The server `auth` option runs, the same as for any host.
313- `callTool` returns the MCP result. For a tool with an `outputSchema`, `structuredContent` has the output type of the tool.
314​
315### Call the server in the same process
316​
317When the app and the server run in one process, pass the server object:
318​
319```ts
320import { createMCPClient } from '@tanstack/ai-mcp'
321import { server } from '../src/mcp-server'
322​
323const client = await createMCPClient({ server })
324const text = await client.callTool('get_weather', { city: 'Paris' })
325```
326​
327This client opens no connection. It calls the tool function directly and returns the tool output.
328​
329- The server `auth` option does not run.
330- The client has no `tools()`, so you cannot pass it to `chat()`.
331- A tool gets the spec 2026 context. `ctx.context.requestInput` throws, and `ctx.context.sample` uses the `sample` option of the server.
332- `callTool` parses the output with the tool `outputSchema`, the same as the HTTP server.
333- `readResource(uri, context)` puts `context` on the resource `ctx.context`. Without it, `ctx.context` is `{}`.