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

api.mcp-apps-server.ts

147 lines5.1 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 exercising the **MCP Apps** plumbing.
13 *
14 * Mirrors `api.mcp-server`, but its single tool `show_widget` LINKS a UI
15 * resource via `_meta.ui.resourceUri = 'ui://show_widget'`, and the matching
16 * `ui://show_widget` resource is registered with `text/html` content. This is
17 * the data half of MCP Apps:
18 *
19 * - When `chat()` discovers this tool through `@tanstack/ai-mcp` and the tool
20 * executes, `@tanstack/ai` eagerly reads the linked `ui://` resource and
21 * emits a `ui-resource` CUSTOM event so a `UIResourcePart` lands on the
22 * assistant message. The HTML carries the distinctive token
23 * `MCP_APPS_WIDGET_OK` so the spec can assert the widget HTML survived the
24 * read → CUSTOM event → stream path.
25 * - The same tool is the interactive half: a POST to
26 * `api.mcp-apps-call` (mounting `createMcpAppCallHandler`) proxies
27 * `callTool('show_widget')` here and gets back the structured result
28 * carrying `MCP_APPS_CALL_OK`.
29 *
30 * Stateless mode (no `sessionIdGenerator`): a fresh server + transport per
31 * request, matching `api.mcp-server`.
32 */
33const WIDGET_URI = 'ui://show_widget'
34const WIDGET_HTML =
35 '<!doctype html><html><body><div id="widget">MCP_APPS_WIDGET_OK</div></body></html>'
36const taskStore = new InMemoryTaskStore()
37const taskMessageQueue = new InMemoryTaskMessageQueue()
38​
39function createMockAppsMcpServer(): McpServer {
40 const server = new McpServer(
41 {
42 name: 'mcp-apps-mock',
43 version: '0.0.1',
44 },
45 {
46 capabilities: { tasks: { requests: { tools: { call: {} } } } },
47 taskStore,
48 taskMessageQueue,
49 defaultTaskPollInterval: 1,
50 },
51 )
52​
53 // A tool that links a ui:// resource via the MCP Apps `_meta.ui.resourceUri`
54 // convention. `@tanstack/ai-mcp` discovery stamps this onto the ServerTool's
55 // `metadata.mcp.uiResourceUri`, which drives the ui-resource emit at runtime.
56 const widgetTool = server.registerTool(
57 'show_widget',
58 {
59 description: 'Render a widget for the given title',
60 inputSchema: { title: z.string() },
61 outputSchema: { title: z.string(), status: z.string() },
62 },
63 ({ title }) => {
64 const payload = { title, status: 'MCP_APPS_CALL_OK' }
65 return {
66 content: [{ type: 'text' as const, text: JSON.stringify(payload) }],
67 structuredContent: payload,
68 }
69 },
70 )
71 // `registerTool`'s config doesn't accept `_meta` directly in the SDK; the
72 // RegisteredTool exposes `_meta` as a mutable property surfaced at list time.
73 widgetTool._meta = { ui: { resourceUri: WIDGET_URI } }
74​
75 // A task-required action exercises the Apps call handler's direct
76 // MCPClient.callTool path, which must select task execution after discovery.
77 server.experimental.tasks.registerToolTask(
78 'run_widget_task',
79 {
80 description: 'Run a task-required action from an MCP App',
81 inputSchema: { action: z.string() },
82 execution: { taskSupport: 'required' },
83 },
84 {
85 async createTask({ action }, { taskStore: store, taskRequestedTtl }) {
86 const task = await store.createTask({
87 ttl: taskRequestedTtl,
88 pollInterval: 1,
89 })
90 await store.storeTaskResult(task.taskId, 'completed', {
91 content: [
92 {
93 type: 'text',
94 text: `MCP_APPS_TASK_CALL_OK:${action}`,
95 },
96 ],
97 })
98 return { task }
99 },
100 async getTask(_args, { taskId, taskStore: store }) {
101 return store.getTask(taskId)
102 },
103 async getTaskResult(_args, { taskId, taskStore: store }) {
104 return CallToolResultSchema.parse(await store.getTaskResult(taskId))
105 },
106 },
107 )
108​
109 // The linked ui:// resource — its HTML is what the client widget would
110 // render. We only assert OUR plumbing carries this HTML, not that any
111 // third-party renderer mounts it.
112 server.registerResource(
113 'show_widget_ui',
114 WIDGET_URI,
115 { description: 'Widget UI for show_widget', mimeType: 'text/html' },
116 () => ({
117 contents: [
118 {
119 uri: WIDGET_URI,
120 mimeType: 'text/html',
121 text: WIDGET_HTML,
122 },
123 ],
124 }),
125 )
126​
127 return server
129​
130async function handleMcpRequest(request: Request): Promise<Response> {
131 const server = createMockAppsMcpServer()
132 const transport = new WebStandardStreamableHTTPServerTransport({
133 sessionIdGenerator: undefined,
134 })
135 await server.connect(transport)
136 return transport.handleRequest(request)
138​
139export const Route = createFileRoute('/api/mcp-apps-server')({
140 server: {
141 handlers: {
142 POST: ({ request }) => handleMcpRequest(request),
143 GET: ({ request }) => handleMcpRequest(request),
144 DELETE: ({ request }) => handleMcpRequest(request),
145 },
146 },
147})