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 MCP server for the **Tasks** mode of the MCP demo — a real MCP
13 * server (via `@modelcontextprotocol/sdk`'s `McpServer`) speaking Streamable
14 * HTTP, exposing a single tool with `execution.taskSupport: 'required'`.
15 *
16 * Task-required tools cannot run through ordinary `tools/call`; the client
17 * must create a task, poll its status, and fetch the result. `@tanstack/ai-mcp`
18 * does this automatically via the SDK's experimental `callToolStream` flow —
19 * the companion `/api/mcp-tasks-chat` route connects here and runs the tool
20 * inside a real `chat()` agent loop.
21 *
22 * The appraisal deliberately takes ~4 seconds so a human can watch the task
23 * lifecycle: the chat UI shows a pending tool call while the client polls
24 * (every 500ms), then the distinctive appraisal total arrives. Lifecycle
25 * events are also console.logged (created → completed → result fetched).
26 *
27 * Stateless mode (no `sessionIdGenerator`) creates a fresh `McpServer` and
28 * transport per request; the globalThis-anchored task store persists task
29 * state across the follow-up polling requests.
30 */
31// Anchored on globalThis, NOT module scope: each `tasks/get` poll from the
32// client is its own HTTP request, and if Vite invalidates this module between
33// polls (HMR after an edit, a route-tree regeneration) a module-scoped store
34// would be re-created empty and in-flight polls would fail with "Task not
35// found". globalThis persists for the life of the dev-server process.
36interface TasksDemoState {
37 taskStore: InMemoryTaskStore
38 taskMessageQueue: InMemoryTaskMessageQueue
39}
40const globalState = globalThis as { __mcpTasksDemo?: TasksDemoState }
41const { taskStore, taskMessageQueue } = (globalState.__mcpTasksDemo ??= {
42 taskStore: new InMemoryTaskStore(),
43 taskMessageQueue: new InMemoryTaskMessageQueue(),
44})
45
46const APPRAISAL_DURATION_MS = 4_000
47const TASK_POLL_INTERVAL_MS = 500
48const PRICE_PER_GUITAR = 1_400
49
50function createTasksMcpServer(): McpServer {
51 const server = new McpServer(
52 {
53 name: 'guitar-appraisal-mcp',
54 version: '0.0.1',
55 },
56 {
57 capabilities: { tasks: { requests: { tools: { call: {} } } } },
58 taskStore,
59 taskMessageQueue,
60 defaultTaskPollInterval: TASK_POLL_INTERVAL_MS,
61 },
62 )
63
64 server.experimental.tasks.registerToolTask(
65 'appraise_guitar_collection',
66 {
67 description:
68 'Appraise a collection of guitars by their names/ids. Long-running: requires task-based execution (~4 seconds).',
69 inputSchema: { ids: z.array(z.string()) },
70 execution: { taskSupport: 'required' },
71 },
72 {
73 async createTask({ ids }, { taskStore: store, taskRequestedTtl }) {
74 const task = await store.createTask({
75 // ai-mcp doesn't request a TTL (undefined → never expires), and the
76 // store outlives requests — expire finished demo tasks after a minute
77 // so repeated manual runs don't accumulate for the dev-server lifetime.
78 ttl: taskRequestedTtl ?? 60_000,
79 pollInterval: TASK_POLL_INTERVAL_MS,
80 })
81 console.log(
82 `[mcp-tasks] created task ${task.taskId} — appraising ${ids.length} guitar(s), completes in ${APPRAISAL_DURATION_MS}ms`,
83 )
84 // Complete the task in the background; the client keeps polling
85 // getTask until the status turns terminal. Abort sends best-effort
86 // `tasks/cancel`. This demo timer is not wired to that cancel, so it
87 // may still fire and `storeTaskResult` then fails on a cancelled task.
88 setTimeout(() => {
89 const total = ids.length * PRICE_PER_GUITAR
90 store
91 .storeTaskResult(task.taskId, 'completed', {
92 content: [
93 {
94 type: 'text',
95 text: `Appraisal complete: ${ids.join(', ')} — $${PRICE_PER_GUITAR} each, $${total} total.`,
96 },
97 ],
98 })
99 .then(() =>
100 console.log(`[mcp-tasks] completed task ${task.taskId}`),
101 )
102 .catch((error) =>
103 console.error(
104 `[mcp-tasks] failed to complete task ${task.taskId}:`,
105 error,
106 ),
107 )
108 }, APPRAISAL_DURATION_MS)
109 return { task }
110 },
111 async getTask(_args, { taskId, taskStore: store }) {
112 return store.getTask(taskId)
113 },
114 async getTaskResult(_args, { taskId, taskStore: store }) {
115 const result = CallToolResultSchema.parse(
116 await store.getTaskResult(taskId),
117 )
118 console.log(`[mcp-tasks] fetched result for task ${taskId}`)
119 return result
120 },
121 },
122 )
123
124 return server
125}
126
127async function handleMcpRequest(request: Request): Promise<Response> {
128 const server = createTasksMcpServer()
129 const transport = new WebStandardStreamableHTTPServerTransport({
130 // Stateless mode — no session id is generated or validated. A fresh
131 // server+transport pair handles this single request and is then GC'd.
132 sessionIdGenerator: undefined,
133 })
134
135 // The McpServer assumes ownership of the transport and tears down its own
136 // per-request streams when the response stream completes; in stateless mode
137 // we deliberately do NOT close the transport here, since doing so before the
138 // SSE body drains would abort the in-flight response.
139 await server.connect(transport)
140
141 return transport.handleRequest(request)
142}
143
144export const Route = createFileRoute('/api/mcp-tasks-server')({
145 server: {
146 handlers: {
147 POST: ({ request }) => handleMcpRequest(request),
148 GET: ({ request }) => handleMcpRequest(request),
149 DELETE: ({ request }) => handleMcpRequest(request),
150 },
151 },
152})