Open History to see the last commit
1/**
2 * /api/mcp-tasks-chat — task-required MCP tool execution via chat({ mcp }).
3 *
4 * Connects to the in-process Streamable HTTP MCP server at
5 * `/api/mcp-tasks-server` (same origin), whose only tool declares
6 * `execution.taskSupport: 'required'`. `@tanstack/ai-mcp` detects this during
7 * discovery and routes the call through the SDK's experimental task flow
8 * (create task → poll status → fetch result) instead of ordinary `tools/call`.
9 *
10 * From chat()'s perspective nothing changes — the tool call resolves like any
11 * other, just ~4 seconds later while the UI shows the pending tool call.
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'
22
23export const Route = createFileRoute('/api/mcp-tasks-chat')({
24 server: {
25 handlers: {
26 POST: async ({ request }) => {
27 const requestSignal = request.signal
28
29 if (requestSignal.aborted) {
30 return new Response(null, { status: 499 })
31 }
32
33 const abortController = new AbortController()
34
35 let params
36 try {
37 params = await chatParamsFromRequestBody(await request.json())
38 } catch (error) {
39 return new Response(
40 error instanceof Error ? error.message : 'Bad request',
41 { status: 400 },
42 )
43 }
44
45 let client
46 try {
47 // The task server is hosted by this same dev server — derive its
48 // URL from the incoming request so the demo works on any port.
49 const origin = new URL(request.url).origin
50 client = await createMCPClient({
51 transport: { type: 'http', url: `${origin}/api/mcp-tasks-server` },
52 })
53
54 // chat() discovers the task-required tool and closes the client
55 // when the stream drains — connection: 'close' (the default; shown
56 // explicitly). The model is encoded in the adapter.
57 const stream = chat({
58 adapter: resolveTextAdapter(params.forwardedProps.provider),
59 messages: params.messages,
60 mcp: {
61 clients: [client],
62 connection: 'close',
63 },
64 agentLoopStrategy: maxIterations(20),
65 threadId: params.threadId,
66 runId: params.runId,
67 abortController,
68 })
69
70 return toServerSentEventsResponse(stream, { abortController })
71 } catch (error: any) {
72 // chat() only owns the client once the stream is consumed — if
73 // setup throws before the response is returned, close it here.
74 if (client) await client.close().catch(() => {})
75 console.error('[api.mcp-tasks-chat] Error:', {
76 message: error?.message,
77 name: error?.name,
78 stack: error?.stack,
79 })
80 if (error.name === 'AbortError' || abortController.signal.aborted) {
81 return new Response(null, { status: 499 })
82 }
83 return new Response(
84 JSON.stringify({ error: error.message || 'An error occurred' }),
85 {
86 status: 500,
87 headers: { 'Content-Type': 'application/json' },
88 },
89 )
90 }
91 },
92 },
93 },
94})