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

server.md

219 lines6.5 KB

1---
2title: Serve Tools over HTTP
3id: mcp-server
4order: 13
5description: "Serve TanStack tools over HTTP with createMCPServer so a 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​
16You have TanStack server tools. A host cannot call those tools over HTTP.
17​
18For a tool, a resource, and a prompt in one app, open [Build an MCP Server](../tutorials/mcp-server).
19​
20`createMCPServer` serves those tools over MCP. Return `server.fetch(request)` from your route.
21​
22```ts
23// src/mcp-server.ts
24import { toolDefinition } from '@tanstack/ai'
25import { createMCPServer } from '@tanstack/ai-mcp/server'
26import { z } from 'zod'
27​
28const getWeather = toolDefinition({
29 name: 'get_weather',
30 description: 'Get the weather for a city',
31 inputSchema: z.object({
32 city: z.string(),
33 }),
34}).server(async ({ city }) => {
35 return `Sunny in ${city}`
36})
37​
38export const server = createMCPServer({
39 name: 'weather',
40 version: '1.0.0',
41 tools: [getWeather],
42})
43​
44export function handleMcp(request: Request) {
45 return server.fetch(request)
47```
48​
49Create the server once. `handleMcp` calls `fetch` for each request.
50​
51## Installation
52​
53Install these packages:
54​
55<!-- ::start:tabs variant="package-manager" mode="install" -->
56​
57react: @tanstack/ai-mcp @modelcontextprotocol/server
58vue: @tanstack/ai-mcp @modelcontextprotocol/server
59solid: @tanstack/ai-mcp @modelcontextprotocol/server
60svelte: @tanstack/ai-mcp @modelcontextprotocol/server
61preact: @tanstack/ai-mcp @modelcontextprotocol/server
62angular: @tanstack/ai-mcp @modelcontextprotocol/server
63vanilla: @tanstack/ai-mcp @modelcontextprotocol/server
64octane: @tanstack/ai-mcp @modelcontextprotocol/server
65​
66<!-- ::end:tabs -->
67​
68## TanStack Start
69​
701. Save the server code as `src/mcp-server.ts`.
712. Forward each request to `handleMcp`.
72​
73```ts ignore
74// src/routes/api.mcp.ts
75import { createFileRoute } from '@tanstack/react-router'
76import { handleMcp } from '../mcp-server'
77​
78export const Route = createFileRoute('/api/mcp')({
79 server: {
80 handlers: {
81 GET: ({ request }) => handleMcp(request),
82 POST: ({ request }) => handleMcp(request),
83 DELETE: ({ request }) => handleMcp(request),
84 },
85 },
86})
87```
88​
89The route path is `/api/mcp`.
90​
91## Cloudflare Workers
92​
931. Save the server code as `src/mcp-server.ts`.
942. Call `handleMcp` for each request.
95​
96```ts
97// src/index.ts
98import { handleMcp } from './mcp-server'
99​
100export default {
101 async fetch(request: Request) {
102 return handleMcp(request)
103 },
105```
106​
107The worker URL is the MCP URL.
108​
109The host can list `get_weather`. Then the host can call that tool.
110​
111To call this URL from `chat()`, see [MCP Server Tools](../tools/mcp).
112​
113## Tell the host what a tool does
114​
115A host asks the user before it runs a tool, unless the tool says it only reads. Set `metadata.title` and `metadata.annotations` on the tool definition. The host gets them as the MCP tool title and annotations.
116​
117```ts
118import { toolDefinition } from '@tanstack/ai'
119import { z } from 'zod'
120​
121export const listNotes = toolDefinition({
122 name: 'list_notes',
123 description: 'List the notes of the signed-in user',
124 inputSchema: z.object({}),
125 metadata: {
126 title: 'List notes',
127 annotations: { readOnlyHint: true, idempotentHint: true },
128 },
129}).server(async () => [])
130```
131​
132The annotation names are the MCP names:
133​
134- `readOnlyHint`: the tool changes nothing.
135- `destructiveHint`: the tool can delete or overwrite data.
136- `idempotentHint`: a repeat call with the same input changes nothing more.
137- `openWorldHint`: the tool reaches outside your system.
138​
139## Shape the result yourself
140​
141The server sends the tool output as one text block. An object also goes on `structuredContent`. When 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.
142​
143```ts
144import { toolDefinition } from '@tanstack/ai'
145import { z } from 'zod'
146import { db } from './db'
147​
148export const countNotes = toolDefinition({
149 name: 'count_notes',
150 description: 'Count the notes and list them',
151 inputSchema: z.object({}),
152}).server(async () => {
153 const notes = await db.notes.list()
154 return {
155 content: [
156 { type: 'text' as const, text: `${notes.length} notes.` },
157 { type: 'text' as const, text: JSON.stringify(notes) },
158 ],
159 structuredContent: { count: notes.length },
160 }
161})
162```
163​
164The first block is a short summary for the model. The second block is the data.
165​
166## Call the server with types
167​
168Your app calls the deployed server. You want a wrong tool name or a wrong argument to fail at compile time.
169​
1701. Export `server` from `src/mcp-server.ts`.
1712. In the app, import its type with `import type`.
1723. Pass `typeof server` to `createMCPClient`, with the URL of the server.
173​
174```ts
175// app/weather.ts
176import { createMCPClient } from '@tanstack/ai-mcp'
177import type { server } from '../src/mcp-server'
178​
179export async function forecast(city: string) {
180 const client = await createMCPClient<typeof server>({
181 transport: { type: 'http', url: 'https://mcp.example.com/api/mcp' },
182 })
183 try {
184 return await client.callTool('get_weather', { city })
185 } finally {
186 await client.close()
187 }
189```
190​
191The client connects to the URL and speaks MCP. The server `auth` option runs, the same as for any host.
192​
193- `callTool` accepts only the tool names of `server`, and each tool's input type.
194- `callTool` returns the MCP result. For a tool with an `outputSchema`, `structuredContent` has the tool output type.
195- `getPrompt` accepts only the prompt names of `server`, and each prompt's argument type.
196- `readResource` accepts only the resource URIs of `server`.
197- `import type` keeps the server code out of the app bundle.
198​
199### Call the server in the same process
200​
201When the app and the server run in one process, pass the server object:
202​
203```ts
204import { createMCPClient } from '@tanstack/ai-mcp'
205import { server } from '../src/mcp-server'
206​
207const client = await createMCPClient({ server })
208const text = await client.callTool('get_weather', { city: 'Paris' })
209```
210​
211This client opens no connection. It calls the tool function directly and returns the tool output.
212​
213- The server `auth` option does not run.
214- The client has no `tools()`, so you cannot pass it to `chat()`.
215- A tool gets the spec 2026 context. `ctx.context.requestInput` throws, and `ctx.context.sample` uses the `sample` option of the server.
216​
217Now `callTool('get_weather', { city })` goes to the deployed server, and `callTool('get_wether', { city })` fails the type check.
218​
219If the host starts a local process, see [MCP Server on stdio](./server-stdio).