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

mcp-server.md

270 lines7.7 KB

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