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

mcp-server.md

274 lines7.9 KB

1---
2title: Build an MCP Server
3id: mcp-server
4order: 5
5description: "Serve a tool, a resource, and a prompt over MCP from a TanStack Start app. A typed client calls all three and keeps their types."
6keywords:
7 - tanstack ai
8 - tutorial
9 - mcp
10 - mcp server
11 - createMCPServer
12 - tools
13 - resources
14 - prompts
15 - tanstack start
16---
17​
18This tutorial serves a tool, a file, and a prompt with `createMCPServer` on a TanStack Start route.
19​
20A page in the same app calls the server with a typed client and shows the three results. It takes about 10 minutes, and you do not need a model key.
21​
22This tutorial uses React and Start. For the short guide, open [Serve Tools over HTTP](../mcp/server).
23​
24## 1. Create a Start app
25​
26```bash
27npx @tanstack/cli@latest create
28```
29​
30Pick React. For more options, see [Start getting started](https://tanstack.com/start/latest/docs/framework/react/quick-start).
31​
32Install these packages:
33​
34<!-- ::start:tabs variant="package-manager" mode="install" -->
35​
36react: @tanstack/ai @tanstack/ai-mcp zod
37​
38<!-- ::end:tabs -->
39​
40## 2. Write the server
41​
42Create `src/mcp-server.ts`. It defines three things:
43​
44- **A tool**: `get_weather` returns the weather for one city. `outputSchema` makes the result a string for the client.
45- **A resource**: a short city guide. A host reads it by URI.
46- **A prompt**: `trip_brief` asks for a one-day plan. A host renders it with a city name.
47​
48```ts
49import { toolDefinition } from '@tanstack/ai'
50import {
51 createMCPServer,
52 promptDefinition,
53 resourceDefinition,
54} from '@tanstack/ai-mcp/server'
55import { z } from 'zod'
56​
57const getWeather = toolDefinition({
58 name: 'get_weather',
59 description: 'Get the weather for a city',
60 inputSchema: z.object({
61 city: z.string(),
62 }),
63 outputSchema: z.string(),
64}).server(async ({ city }) => {
65 return `Sunny in ${city}`
66})
67​
68const cityGuide = resourceDefinition({
69 uri: 'file:///city-guide.md',
70 name: 'city-guide',
71 mimeType: 'text/markdown',
72}).read(async () => ({
73 text: '# Paris\n\nPack a light jacket.',
74}))
75​
76const tripBrief = promptDefinition({
77 name: 'trip_brief',
78 description: 'Write a short trip brief for a city',
79 argsSchema: z.object({
80 city: z.string(),
81 }),
82}).render(async ({ city }) => [
83 {
84 role: 'user',
85 content: `Write a one-day plan for ${city}.`,
86 },
87])
88​
89export const server = createMCPServer({
90 name: 'travel',
91 version: '1.0.0',
92 tools: [getWeather],
93 resources: [cityGuide],
94 prompts: [tripBrief],
95})
96​
97export function handleMcp(request: Request) {
98 return server.fetch(request)
100```
101​
102The file creates the server once. `handleMcp` calls `server.fetch` for each request.
103​
104## 3. Mount the route
105​
106Create `src/routes/api.mcp.ts`. The route path is `/api/mcp`.
107​
108```ts ignore
109import { createFileRoute } from '@tanstack/react-router'
110import { handleMcp } from '../mcp-server'
111​
112export const Route = createFileRoute('/api/mcp')({
113 server: {
114 handlers: {
115 GET: ({ request }) => handleMcp(request),
116 POST: ({ request }) => handleMcp(request),
117 DELETE: ({ request }) => handleMcp(request),
118 },
119 },
120})
121```
122​
123Each method has a job:
124​
125- `POST` carries the JSON-RPC body.
126- `GET` opens the stream from the 2025 spec.
127- `DELETE` closes that session.
128​
129## 4. Call the server from the page
130​
131Create `src/lib/call-server.ts`. Pass `server` to `createMCPClient`.
132​
133```ts
134import { createServerFn } from '@tanstack/react-start'
135import { createMCPClient } from '@tanstack/ai-mcp'
136import { server } from '../mcp-server'
137​
138export type DeskResult = {
139 forecast: string
140 guide: string
141 brief: string
143​
144export const callDesk = createServerFn({ method: 'POST' }).handler(
145 async (): Promise<DeskResult> => {
146 const client = await createMCPClient({ server })
147 const forecast = await client.callTool('get_weather', { city: 'Paris' })
148 const guide = await client.readResource('file:///city-guide.md')
149 const prompt = await client.getPrompt('trip_brief', { city: 'Paris' })
150 const message = prompt[0]
151 return {
152 forecast,
153 guide: guide.text,
154 brief: message === undefined ? '' : message.content,
155 }
156 },
158```
159​
160The calls are type-safe:
161​
162- `get_weather` is the only tool name. `city` is a string, and the result is a string.
163- `file:///city-guide.md` is the only resource URI.
164- `trip_brief` is the only prompt name. `city` is a string.
165​
166A wrong name is a type error. A number for `city` is a type error.
167​
168Replace `src/routes/index.tsx` with this page. The button calls `callDesk`.
169​
170```tsx ignore
171import { createFileRoute } from '@tanstack/react-router'
172import { useState } from 'react'
173import { callDesk } from '@/lib/call-server'
174import type { DeskResult } from '@/lib/call-server'
175​
176function McpServerPage() {
177 const [result, setResult] = useState<DeskResult | null>(null)
178 const [error, setError] = useState('')
179 const [pending, setPending] = useState(false)
180​
181 async function onCall() {
182 setError('')
183 setPending(true)
184 try {
185 setResult(await callDesk())
186 } catch (caught) {
187 setResult(null)
188 setError(caught instanceof Error ? caught.message : 'The call failed.')
189 } finally {
190 setPending(false)
191 }
192 }
193​
194 return (
195 <main className="mx-auto max-w-2xl p-6">
196 <h1 className="mb-2 text-3xl font-bold text-white">Travel desk</h1>
197 <p className="mb-6 text-gray-300">
198 This page calls your MCP server. The server has one tool, one resource,
199 and one prompt.
200 </p>
201 <button
202 type="button"
203 className="rounded bg-white px-4 py-2 font-semibold text-gray-900 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-white disabled:opacity-60"
204 disabled={pending}
205 onClick={() => {
206 void onCall()
207 }}
208 >
209 {pending ? 'The call is in progress' : 'Call the server'}
210 </button>
211 {error !== '' ? (
212 <p className="mt-4 text-red-300" role="alert">
213 {error}
214 </p>
215 ) : null}
216 {result !== null ? (
217 <div className="mt-8 space-y-6 text-gray-100">
218 <section>
219 <h2 className="text-xl font-semibold">Forecast</h2>
220 <p>{result.forecast}</p>
221 </section>
222 <section>
223 <h2 className="text-xl font-semibold">City guide</h2>
224 <pre className="whitespace-pre-wrap">{result.guide}</pre>
225 </section>
226 <section>
227 <h2 className="text-xl font-semibold">Trip brief</h2>
228 <p>{result.brief}</p>
229 </section>
230 </div>
231 ) : null}
232 </main>
233 )
235​
236export const Route = createFileRoute('/')({
237 component: McpServerPage,
238})
239```
240​
241## 5. Run the app
242​
2431. In the app folder, run `pnpm dev`.
2442. Open the URL that the dev server prints. The default is http://localhost:3000.
2453. Click Call the server.
246​
247The page shows `Sunny in Paris`, the city guide, and the trip brief.
248​
249<!-- ::client-example library=ai framework=react slug=mcp-server -->
250​
251The full example is on GitHub: [TanStack/ai `examples/react/mcp-server`](https://github.com/TanStack/ai/tree/main/examples/react/mcp-server).
252​
253## How it works
254​
255The app has three parts:
256​
257- **The server file** defines the tool, the resource, and the prompt.
258- **The route** sends each HTTP request at `/api/mcp` to that server. A remote MCP host connects here.
259- **The page** calls the server through `createMCPClient` and shows the results.
260​
261The `server` object keeps the types. `createMCPClient({ server })` uses them to check the tool name, the resource URI, and the prompt arguments.
262​
263This client calls the server in the same process:
264​
265- It opens no network connection.
266- The server `auth` option does not run.
267​
268An app that calls the deployed server over HTTP can use the same types with `import type`. [Call the server with types](../mcp/server#call-the-server-with-types) shows how.
269​
270Next, pick the one you need:
271​
272- The tool must ask the user a question: [Ask for Input](../mcp/server-input).
273- A tool returns before the work ends: [MCP Server Tasks](../mcp/server-tasks).
274- The server must require a bearer token: [MCP Server Auth](../mcp/server-auth).