Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import {
3 chat,
4 chatParamsFromRequestBody,
5 maxIterations,
6 toServerSentEventsResponse,
7} from '@tanstack/ai'
8import { createMCPClient } from '@tanstack/ai-mcp'
9import type { MCPClient } from '@tanstack/ai-mcp'
10import { createTextAdapter } from '@/lib/providers'
11
12/**
13 * MCP Apps — data plane. Drives a real `chat()` agent loop whose tools are
14 * discovered from the in-process MCP Apps server (`api.mcp-apps-server`).
15 *
16 * The client is passed via `chat({ mcp: { clients: [mcp] } })` (NOT as
17 * pre-discovered `tools`) on purpose: only `MCPManager.discover()` binds the
18 * client's `readResource` onto the ui-linked tool's metadata, which is what
19 * lets `@tanstack/ai` eagerly read `ui://show_widget` and emit the
20 * `ui-resource` CUSTOM event after `show_widget` executes. With
21 * `connection: 'close'` (default), chat() owns the client lifecycle and closes
22 * it once the stream drains, so we don't close it ourselves.
23 */
24export const Route = createFileRoute('/api/mcp-apps-chat')({
25 server: {
26 handlers: {
27 POST: async ({ request }) => {
28 if (request.signal.aborted) {
29 return new Response(null, { status: 499 })
30 }
31
32 const abortController = new AbortController()
33 const onRequestAbort = () => abortController.abort()
34 request.signal.addEventListener('abort', onRequestAbort, { once: true })
35
36 let params
37 try {
38 params = await chatParamsFromRequestBody(await request.json())
39 } catch (error) {
40 return new Response(
41 error instanceof Error ? error.message : 'Bad request',
42 { status: 400 },
43 )
44 }
45
46 const fp = params.forwardedProps
47 const testId = typeof fp.testId === 'string' ? fp.testId : undefined
48 const aimockPort =
49 fp.aimockPort != null ? Number(fp.aimockPort) : undefined
50
51 const origin = new URL(request.url).origin
52 const mcpUrl = `${origin}/api/mcp-apps-server`
53
54 let mcp: MCPClient | undefined
55 try {
56 mcp = await createMCPClient({
57 transport: { type: 'http', url: mcpUrl },
58 })
59
60 const adapterOptions = createTextAdapter(
61 'openai',
62 undefined,
63 aimockPort,
64 testId,
65 )
66
67 const stream = chat({
68 ...adapterOptions,
69 messages: params.messages,
70 mcp: { clients: [mcp] },
71 threadId: params.threadId,
72 runId: params.runId,
73 agentLoopStrategy: maxIterations(5),
74 abortController,
75 })
76
77 // chat() owns the MCP client (connection: 'close' default) and closes
78 // it after the stream drains, so we don't close it here.
79 return toServerSentEventsResponse(stream, { abortController })
80 } catch (error) {
81 if (mcp) {
82 await mcp.close().catch(() => undefined)
83 }
84 console.error('[api.mcp-apps-chat] Error:', error)
85 if (
86 (error instanceof Error && error.name === 'AbortError') ||
87 abortController.signal.aborted
88 ) {
89 return new Response(null, { status: 499 })
90 }
91 const message =
92 error instanceof Error ? error.message : 'An error occurred'
93 return new Response(JSON.stringify({ error: message }), {
94 status: 500,
95 headers: { 'Content-Type': 'application/json' },
96 })
97 }
98 },
99 },
100 },
101})