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

api.mcp-apps-call.ts

83 lines3.0 KB

1import { createFileRoute } from '@tanstack/react-router'
2import { createMCPClient } from '@tanstack/ai-mcp'
3import { createMcpAppCallHandler } from '@tanstack/ai-mcp/apps'
4​
5/**
6 * MCP Apps — interactive plane. Mounts `createMcpAppCallHandler` and exposes it
7 * as a POST endpoint. A widget (or a test) POSTs an
8 * `McpAppCallRequest`-shaped body:
9 *
10 * { threadId, serverId, toolName, args?, messageId? }
11 *
12 * The handler reads the connection descriptor off the MCP client it was given
13 * (the same client you'd pass to `chat({ mcp: { clients } })`), reconnects to
14 * the in-process MCP Apps server (`api.mcp-apps-server`) per call, enforces a
15 * same-server allowlist (a tool the server does not expose → `{ ok: false }`),
16 * proxies `callTool`, and always closes the per-call client. We return its JSON
17 * result verbatim.
18 */
19export const Route = createFileRoute('/api/mcp-apps-call')({
20 server: {
21 handlers: {
22 POST: async ({ request }) => {
23 let body: {
24 threadId?: unknown
25 serverId?: unknown
26 toolName?: unknown
27 args?: unknown
28 messageId?: unknown
29 needsApproval?: unknown
30 }
31 try {
32 body = (await request.json()) as typeof body
33 } catch {
34 return new Response('Bad request', { status: 400 })
35 }
36​
37 if (
38 typeof body.threadId !== 'string' ||
39 typeof body.serverId !== 'string' ||
40 typeof body.toolName !== 'string'
41 ) {
42 return new Response('threadId, serverId and toolName are required', {
43 status: 400,
44 })
45 }
46​
47 // The MCP Apps server lives at this same dev server's origin. Create
48 // the client the same way `chat({ mcp })` would; the handler reads its
49 // descriptor (via getInfo) and reconnects per call.
50 const origin = new URL(request.url).origin
51 const widgets = await createMCPClient({
52 transport: { type: 'http', url: `${origin}/api/mcp-apps-server` },
53 prefix: 'widgets',
54 ...(body.needsApproval === true ? { needsApproval: () => true } : {}),
55 })
56 const handler = createMcpAppCallHandler({ clients: widgets })
57​
58 try {
59 const result = await handler({
60 threadId: body.threadId,
61 serverId: body.serverId,
62 toolName: body.toolName,
63 args:
64 body.args !== null &&
65 typeof body.args === 'object' &&
66 !Array.isArray(body.args)
67 ? body.args
68 : undefined,
69 messageId:
70 typeof body.messageId === 'string' ? body.messageId : undefined,
71 })
72​
73 return Response.json(result)
74 } finally {
75 // The handler reconnects its own per-call client; `widgets` is only
76 // read for its descriptor (getInfo() — pure data, valid post-close),
77 // so close it here to avoid leaking a connection per POST.
78 await widgets.close().catch(() => undefined)
79 }
80 },
81 },
82 },
83})