Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import {
3 InMemoryTaskMessageQueue,
4 InMemoryTaskStore,
5} from '@modelcontextprotocol/sdk/experimental/tasks'
6import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
7import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js'
8import { CallToolResultSchema } from '@modelcontextprotocol/sdk/types.js'
9import { z } from 'zod'
10
11/**
12 * In-process mock MCP server hosted as a TanStack Start API route.
13 *
14 * This is a *real* MCP server (via `@modelcontextprotocol/sdk`'s `McpServer`)
15 * speaking the Streamable HTTP protocol over Web Standard Request/Response.
16 * The companion `api.mcp-test` route connects to it at this same dev-server
17 * origin via `@tanstack/ai-mcp`'s `createMCPClient({ transport: { type:
18 * 'http', url } })`, discovers its tools, and runs them inside a real `chat()`
19 * agent loop (with the LLM mocked by aimock).
20 *
21 * Stateless mode (no `sessionIdGenerator`) creates a fresh `McpServer` and
22 * transport per request. The module-scoped task store persists task state
23 * across the follow-up polling requests made by `callToolStream`; no session
24 * bookkeeping is needed.
25 *
26 * `get_guitar_price` provides an ordinary deterministic tool. The
27 * task-required `appraise_guitar_collection` tool returns a distinctive total
28 * through the real task create/status/result flow.
29 */
30const taskStore = new InMemoryTaskStore()
31const taskMessageQueue = new InMemoryTaskMessageQueue()
32
33function createMockMcpServer(): McpServer {
34 const server = new McpServer(
35 {
36 name: 'guitar-store-mcp-mock',
37 version: '0.0.1',
38 },
39 {
40 capabilities: { tasks: { requests: { tools: { call: {} } } } },
41 instructions: 'Quote guitar prices in US dollars.',
42 taskStore,
43 taskMessageQueue,
44 defaultTaskPollInterval: 1,
45 },
46 )
47
48 server.registerTool(
49 'get_guitar_price',
50 {
51 // A display `title` plus behavior `annotations` — server-declared hints
52 // that @tanstack/ai-mcp must forward onto `metadata.mcp` so a host can
53 // label the tool and shape its approval UI (see api.mcp-status-test).
54 title: 'Guitar Price Lookup',
55 description: 'Get the price of a guitar by its id',
56 inputSchema: { id: z.string() },
57 outputSchema: { id: z.string(), price: z.number() },
58 annotations: {
59 readOnlyHint: true,
60 destructiveHint: false,
61 idempotentHint: true,
62 openWorldHint: false,
63 },
64 },
65 ({ id }) => {
66 const payload = { id, price: 1999 }
67 return {
68 content: [{ type: 'text' as const, text: JSON.stringify(payload) }],
69 structuredContent: payload,
70 }
71 },
72 )
73
74 server.experimental.tasks.registerToolTask(
75 'appraise_guitar_collection',
76 {
77 description: 'Long-running appraisal that requires task-based execution',
78 inputSchema: { ids: z.array(z.string()) },
79 execution: { taskSupport: 'required' },
80 },
81 {
82 async createTask({ ids }, { taskStore: store, taskRequestedTtl }) {
83 const task = await store.createTask({
84 ttl: taskRequestedTtl,
85 pollInterval: 1,
86 })
87 await store.storeTaskResult(task.taskId, 'completed', {
88 content: [
89 {
90 type: 'text',
91 text: `Appraised ${ids.join(', ')} at 4200 total`,
92 },
93 ],
94 })
95 return { task }
96 },
97 async getTask(_args, { taskId, taskStore: store }) {
98 return store.getTask(taskId)
99 },
100 async getTaskResult(_args, { taskId, taskStore: store }) {
101 return CallToolResultSchema.parse(await store.getTaskResult(taskId))
102 },
103 },
104 )
105
106 // Never stores a result. Abort tests poll until the client signal fires.
107 server.experimental.tasks.registerToolTask(
108 'hanging_appraisal',
109 {
110 description: 'Task-required tool that never reaches a terminal result',
111 inputSchema: { ids: z.array(z.string()) },
112 execution: { taskSupport: 'required' },
113 },
114 {
115 async createTask(_args, { taskStore: store, taskRequestedTtl }) {
116 const task = await store.createTask({
117 ttl: taskRequestedTtl ?? 10_000,
118 pollInterval: 1,
119 })
120 return { task }
121 },
122 async getTask(_args, { taskId, taskStore: store }) {
123 return store.getTask(taskId)
124 },
125 async getTaskResult(_args, { taskId, taskStore: store }) {
126 return CallToolResultSchema.parse(await store.getTaskResult(taskId))
127 },
128 },
129 )
130
131 // A static resource + prompt so the resource/prompt read+convert path can be
132 // exercised end-to-end (see api.mcp-status-test). The catalog text carries a
133 // distinctive token (STRAT-001) the spec asserts survives conversion.
134 server.registerResource(
135 'catalog',
136 'guitar://catalog',
137 { description: 'Featured guitar catalog', mimeType: 'text/plain' },
138 async () => ({
139 contents: [
140 {
141 uri: 'guitar://catalog',
142 text: 'Featured guitar: Fender Stratocaster (SKU STRAT-001), price 1999.',
143 },
144 ],
145 }),
146 )
147
148 server.registerPrompt(
149 'recommend_guitar',
150 { description: 'Ask for a beginner-friendly guitar recommendation' },
151 () => ({
152 messages: [
153 {
154 role: 'user',
155 content: {
156 type: 'text',
157 text: 'Recommend a beginner-friendly electric guitar under $500.',
158 },
159 },
160 ],
161 }),
162 )
163
164 return server
165}
166
167async function handleMcpRequest(request: Request): Promise<Response> {
168 const server = createMockMcpServer()
169 const transport = new WebStandardStreamableHTTPServerTransport({
170 // Stateless mode — no session id is generated or validated. A fresh
171 // server+transport pair handles this single request and is then GC'd.
172 sessionIdGenerator: undefined,
173 })
174
175 // The McpServer assumes ownership of the transport and tears down its own
176 // per-request streams when the response stream completes; in stateless mode
177 // we deliberately do NOT close the transport here, since doing so before the
178 // SSE body drains would abort the in-flight response.
179 await server.connect(transport)
180
181 return transport.handleRequest(request)
182}
183
184export const Route = createFileRoute('/api/mcp-server')({
185 server: {
186 handlers: {
187 POST: ({ request }) => handleMcpRequest(request),
188 GET: ({ request }) => handleMcpRequest(request),
189 DELETE: ({ request }) => handleMcpRequest(request),
190 },
191 },
192})