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

api.mcp-apps-call.ts

96 lines3.0 KB

1/**
2 * /api/mcp-apps-call — the interactive plane for the MCP Apps demo.
3 *
4 * Mounts `createMcpAppCallHandler` over the SAME two servers the chat route
5 * uses (static weather + dynamic Three.js). A widget POSTs an
6 * `McpAppCallRequest` ({ threadId, serverId, toolName, args? }); the handler
7 * routes by `serverId` (the tool-name prefix), reconnects to that server per
8 * call, enforces a same-server allowlist, proxies `callTool`, and returns the
9 * result as JSON. Stateless/serverless-safe.
10 */
11import { createFileRoute } from '@tanstack/react-router'
12import { createMCPClient } from '@tanstack/ai-mcp'
13import type { MCPClient } from '@tanstack/ai-mcp'
14import { createMcpAppCallHandler } from '@tanstack/ai-mcp/apps'
15import {
16 SHOP_PREFIX,
17 SHOP_SERVER_PATH,
18 THREEJS_MCP_URL,
19 THREEJS_PREFIX,
20 WEATHER_PREFIX,
21 WEATHER_SERVER_PATH,
22} from '@/lib/mcp-apps'
23​
24async function tryConnect(
25 url: string,
26 prefix: string,
27): Promise<MCPClient | null> {
28 try {
29 return await createMCPClient({ transport: { type: 'http', url }, prefix })
30 } catch {
31 return null
32 }
34​
35export const Route = createFileRoute('/api/mcp-apps-call')({
36 server: {
37 handlers: {
38 POST: async ({ request }) => {
39 let body: {
40 threadId?: unknown
41 serverId?: unknown
42 toolName?: unknown
43 args?: unknown
44 messageId?: unknown
45 }
46 try {
47 body = await request.json()
48 } catch {
49 return new Response('Bad request', { status: 400 })
50 }
51​
52 if (
53 typeof body.threadId !== 'string' ||
54 typeof body.toolName !== 'string'
55 ) {
56 return new Response('threadId and toolName are required', {
57 status: 400,
58 })
59 }
60​
61 const origin = new URL(request.url).origin
62 const clients = (
63 await Promise.all([
64 tryConnect(`${origin}${WEATHER_SERVER_PATH}`, WEATHER_PREFIX),
65 tryConnect(`${origin}${SHOP_SERVER_PATH}`, SHOP_PREFIX),
66 tryConnect(THREEJS_MCP_URL, THREEJS_PREFIX),
67 ])
68 ).filter((c): c is MCPClient => c !== null)
69​
70 const handler = createMcpAppCallHandler({ clients })
71​
72 try {
73 const result = await handler({
74 threadId: body.threadId,
75 serverId:
76 typeof body.serverId === 'string' ? body.serverId : undefined,
77 toolName: body.toolName,
78 args:
79 body.args !== null &&
80 typeof body.args === 'object' &&
81 !Array.isArray(body.args)
82 ? body.args
83 : undefined,
84 messageId:
85 typeof body.messageId === 'string' ? body.messageId : undefined,
86 })
87 return Response.json(result)
88 } finally {
89 // The handler reconnects its own per-call client; these are only read
90 // for their descriptors (getInfo()), so close them to avoid leaks.
91 await Promise.allSettled(clients.map((c) => c.close()))
92 }
93 },
94 },
95 },
96})