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

api.mcp-server.ts

191 lines6.3 KB

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 taskStore,
42 taskMessageQueue,
43 defaultTaskPollInterval: 1,
44 },
45 )
46​
47 server.registerTool(
48 'get_guitar_price',
49 {
50 // A display `title` plus behavior `annotations` — server-declared hints
51 // that @tanstack/ai-mcp must forward onto `metadata.mcp` so a host can
52 // label the tool and shape its approval UI (see api.mcp-status-test).
53 title: 'Guitar Price Lookup',
54 description: 'Get the price of a guitar by its id',
55 inputSchema: { id: z.string() },
56 outputSchema: { id: z.string(), price: z.number() },
57 annotations: {
58 readOnlyHint: true,
59 destructiveHint: false,
60 idempotentHint: true,
61 openWorldHint: false,
62 },
63 },
64 ({ id }) => {
65 const payload = { id, price: 1999 }
66 return {
67 content: [{ type: 'text' as const, text: JSON.stringify(payload) }],
68 structuredContent: payload,
69 }
70 },
71 )
72​
73 server.experimental.tasks.registerToolTask(
74 'appraise_guitar_collection',
75 {
76 description: 'Long-running appraisal that requires task-based execution',
77 inputSchema: { ids: z.array(z.string()) },
78 execution: { taskSupport: 'required' },
79 },
80 {
81 async createTask({ ids }, { taskStore: store, taskRequestedTtl }) {
82 const task = await store.createTask({
83 ttl: taskRequestedTtl,
84 pollInterval: 1,
85 })
86 await store.storeTaskResult(task.taskId, 'completed', {
87 content: [
88 {
89 type: 'text',
90 text: `Appraised ${ids.join(', ')} at 4200 total`,
91 },
92 ],
93 })
94 return { task }
95 },
96 async getTask(_args, { taskId, taskStore: store }) {
97 return store.getTask(taskId)
98 },
99 async getTaskResult(_args, { taskId, taskStore: store }) {
100 return CallToolResultSchema.parse(await store.getTaskResult(taskId))
101 },
102 },
103 )
104​
105 // Never stores a result. Abort tests poll until the client signal fires.
106 server.experimental.tasks.registerToolTask(
107 'hanging_appraisal',
108 {
109 description: 'Task-required tool that never reaches a terminal result',
110 inputSchema: { ids: z.array(z.string()) },
111 execution: { taskSupport: 'required' },
112 },
113 {
114 async createTask(_args, { taskStore: store, taskRequestedTtl }) {
115 const task = await store.createTask({
116 ttl: taskRequestedTtl ?? 10_000,
117 pollInterval: 1,
118 })
119 return { task }
120 },
121 async getTask(_args, { taskId, taskStore: store }) {
122 return store.getTask(taskId)
123 },
124 async getTaskResult(_args, { taskId, taskStore: store }) {
125 return CallToolResultSchema.parse(await store.getTaskResult(taskId))
126 },
127 },
128 )
129​
130 // A static resource + prompt so the resource/prompt read+convert path can be
131 // exercised end-to-end (see api.mcp-status-test). The catalog text carries a
132 // distinctive token (STRAT-001) the spec asserts survives conversion.
133 server.registerResource(
134 'catalog',
135 'guitar://catalog',
136 { description: 'Featured guitar catalog', mimeType: 'text/plain' },
137 async () => ({
138 contents: [
139 {
140 uri: 'guitar://catalog',
141 text: 'Featured guitar: Fender Stratocaster (SKU STRAT-001), price 1999.',
142 },
143 ],
144 }),
145 )
146​
147 server.registerPrompt(
148 'recommend_guitar',
149 { description: 'Ask for a beginner-friendly guitar recommendation' },
150 () => ({
151 messages: [
152 {
153 role: 'user',
154 content: {
155 type: 'text',
156 text: 'Recommend a beginner-friendly electric guitar under $500.',
157 },
158 },
159 ],
160 }),
161 )
162​
163 return server
165​
166async function handleMcpRequest(request: Request): Promise<Response> {
167 const server = createMockMcpServer()
168 const transport = new WebStandardStreamableHTTPServerTransport({
169 // Stateless mode — no session id is generated or validated. A fresh
170 // server+transport pair handles this single request and is then GC'd.
171 sessionIdGenerator: undefined,
172 })
173​
174 // The McpServer assumes ownership of the transport and tears down its own
175 // per-request streams when the response stream completes; in stateless mode
176 // we deliberately do NOT close the transport here, since doing so before the
177 // SSE body drains would abort the in-flight response.
178 await server.connect(transport)
179​
180 return transport.handleRequest(request)
182​
183export const Route = createFileRoute('/api/mcp-server')({
184 server: {
185 handlers: {
186 POST: ({ request }) => handleMcpRequest(request),
187 GET: ({ request }) => handleMcpRequest(request),
188 DELETE: ({ request }) => handleMcpRequest(request),
189 },
190 },
191})