Open History to see the last commit
1/**
2 * /api/mcp-apps-chat — the data plane for the MCP Apps demo.
3 *
4 * Connects two MCP servers and hands them to `chat({ mcp })`:
5 * - the in-process STATIC weather-card server (same origin), and
6 * - the DYNAMIC Three.js server on :3001 (started by `npm run dev`).
7 *
8 * When the model calls a UI-linked tool, `@tanstack/ai` reads the linked
9 * `ui://` resource and emits a `ui-resource` event, so a `UIResourcePart`
10 * lands on the assistant message and the client can render the widget.
11 *
12 * The Three.js server runs as a separate process, so it may not be up. We
13 * connect each server independently and proceed with whichever connected,
14 * rather than failing the whole chat when only :3001 is down.
15 */
16import { createFileRoute } from '@tanstack/react-router'
17import {
18 chat,
19 chatParamsFromRequestBody,
20 maxIterations,
21 toServerSentEventsResponse,
22} from '@tanstack/ai'
23import { createMCPClient } from '@tanstack/ai-mcp'
24import type { MCPClient } from '@tanstack/ai-mcp'
25import { resolveTextAdapter } from '@/lib/mcp-provider-adapters'
26import {
27 SHOP_PREFIX,
28 SHOP_SERVER_PATH,
29 THREEJS_MCP_URL,
30 THREEJS_PREFIX,
31 WEATHER_PREFIX,
32 WEATHER_SERVER_PATH,
33} from '@/lib/mcp-apps'
34
35/** Connect one MCP server, returning null (with a warning) if it's unreachable. */
36async function tryConnect(
37 url: string,
38 prefix: string,
39): Promise<MCPClient | null> {
40 try {
41 return await createMCPClient({ transport: { type: 'http', url }, prefix })
42 } catch (error) {
43 console.warn(
44 `[api.mcp-apps-chat] could not connect MCP server "${prefix}" at ${url}:`,
45 error instanceof Error ? error.message : error,
46 )
47 return null
48 }
49}
50
51export const Route = createFileRoute('/api/mcp-apps-chat')({
52 server: {
53 handlers: {
54 POST: async ({ request }) => {
55 if (request.signal.aborted) return new Response(null, { status: 499 })
56
57 const abortController = new AbortController()
58
59 let params
60 try {
61 params = await chatParamsFromRequestBody(await request.json())
62 } catch (error) {
63 return new Response(
64 error instanceof Error ? error.message : 'Bad request',
65 { status: 400 },
66 )
67 }
68
69 const origin = new URL(request.url).origin
70 const [weather, shop, threejs] = await Promise.all([
71 tryConnect(`${origin}${WEATHER_SERVER_PATH}`, WEATHER_PREFIX),
72 tryConnect(`${origin}${SHOP_SERVER_PATH}`, SHOP_PREFIX),
73 tryConnect(THREEJS_MCP_URL, THREEJS_PREFIX),
74 ])
75 const clients = [weather, shop, threejs].filter(
76 (c): c is MCPClient => c !== null,
77 )
78
79 try {
80 // chat() discovers tools from every connected client and closes them
81 // when the stream drains (connection: 'close', the default).
82 const stream = chat({
83 adapter: resolveTextAdapter(params.forwardedProps.provider),
84 messages: params.messages,
85 mcp: { clients, connection: 'close' },
86 agentLoopStrategy: maxIterations(10),
87 threadId: params.threadId,
88 runId: params.runId,
89 abortController,
90 })
91
92 return toServerSentEventsResponse(stream, { abortController })
93 } catch (error) {
94 // chat() didn't take ownership (it never streamed), so close clients.
95 await Promise.allSettled(clients.map((c) => c.close()))
96 if (request.signal.aborted || abortController.signal.aborted) {
97 return new Response(null, { status: 499 })
98 }
99 return new Response(
100 JSON.stringify({
101 error:
102 error instanceof Error ? error.message : 'An error occurred',
103 }),
104 { status: 500, headers: { 'Content-Type': 'application/json' } },
105 )
106 }
107 },
108 },
109 },
110})