Open History to see the last commit
1/**
2 * /api/mcp-chat — Managed MCP lifecycle via chat({ mcp }).
3 *
4 * Demonstrates the chat({ mcp }) prop pattern with MULTIPLE clients:
5 * 1. Two MCP clients are created (everything + memory servers, both keyless).
6 * 2. They are passed to chat() via mcp.clients — chat() handles tool
7 * discovery and closes both clients when the stream drains (connection: 'close').
8 * 3. No manual client.tools() or client.close() calls needed.
9 *
10 * Uses @modelcontextprotocol/server-everything and @modelcontextprotocol/server-memory
11 * (both keyless, via npx). Only OPENAI_API_KEY is required — no MCP-specific keys needed.
12 */
13import { createFileRoute } from '@tanstack/react-router'
14import {
15 chat,
16 chatParamsFromRequestBody,
17 maxIterations,
18 toServerSentEventsResponse,
19} from '@tanstack/ai'
20import { createMCPClient } from '@tanstack/ai-mcp'
21import { resolveTextAdapter } from '@/lib/mcp-provider-adapters'
22import { everythingTransport, memoryTransport } from '@/lib/mcp-servers'
23
24export const Route = createFileRoute('/api/mcp-chat')({
25 server: {
26 handlers: {
27 POST: async ({ request }) => {
28 const requestSignal = request.signal
29
30 if (requestSignal.aborted) {
31 return new Response(null, { status: 499 })
32 }
33
34 const abortController = new AbortController()
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 let clients
47 try {
48 // Connect two keyless MCP servers in parallel.
49 // Prefixes disambiguate tools if both servers expose same-named tools.
50 // OPENAI_API_KEY is used by the LLM adapter (separate from the
51 // keyless MCP server transports which need no credentials).
52 // Settle (don't Promise.all) so that if one server fails to connect,
53 // the sibling that DID connect is closed before rethrowing — no
54 // leaked stdio subprocess. (createMCPClients does this for you;
55 // shown manually here because this route demonstrates individual clients.)
56 const settled = await Promise.allSettled([
57 createMCPClient({
58 transport: everythingTransport(),
59 prefix: 'everything',
60 }),
61 createMCPClient({
62 transport: memoryTransport(),
63 prefix: 'memory',
64 }),
65 ])
66 const rejected = settled.find(
67 (r): r is PromiseRejectedResult => r.status === 'rejected',
68 )
69 if (rejected) {
70 await Promise.allSettled(
71 settled.map((r) =>
72 r.status === 'fulfilled' ? r.value.close() : Promise.resolve(),
73 ),
74 )
75 throw rejected.reason
76 }
77 clients = settled.flatMap((r) =>
78 r.status === 'fulfilled' ? [r.value] : [],
79 )
80
81 // chat() discovers tools from both clients and closes them when the
82 // stream drains — connection: 'close' (the default; shown explicitly).
83 // The model is encoded in the adapter; do not pass it separately.
84 const stream = chat({
85 adapter: resolveTextAdapter(params.forwardedProps.provider),
86 messages: params.messages,
87 mcp: {
88 clients,
89 connection: 'close',
90 },
91 agentLoopStrategy: maxIterations(20),
92 threadId: params.threadId,
93 runId: params.runId,
94 abortController,
95 })
96
97 return toServerSentEventsResponse(stream, { abortController })
98 } catch (error: any) {
99 // chat() only owns the clients once the stream is consumed — if
100 // setup throws before the response is returned, close them here.
101 if (clients) await Promise.allSettled(clients.map((c) => c.close()))
102 console.error('[api.mcp-chat] Error:', {
103 message: error?.message,
104 name: error?.name,
105 stack: error?.stack,
106 })
107 if (error.name === 'AbortError' || abortController.signal.aborted) {
108 return new Response(null, { status: 499 })
109 }
110 return new Response(
111 JSON.stringify({ error: error.message || 'An error occurred' }),
112 {
113 status: 500,
114 headers: { 'Content-Type': 'application/json' },
115 },
116 )
117 }
118 },
119 },
120 },
121})