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 { StreamChunk } from '@tanstack/ai'
10import type { MCPClient } from '@tanstack/ai-mcp'
11import { createTextAdapter } from '@/lib/providers'
12
13async function* closeMcpOnDrain(
14 stream: AsyncIterable<StreamChunk>,
15 mcp: MCPClient,
16): AsyncGenerator<StreamChunk> {
17 try {
18 for await (const chunk of stream) {
19 yield chunk
20 }
21 } finally {
22 await mcp.close()
23 }
24}
25
26/**
27 * Runs `chat()` with the tools of `api.mcp-input-server`.
28 *
29 * The first request pauses with an `mcp_input` interrupt.
30 * A second request with `parentRunId` and `resume` sends the answer.
31 * The tool then runs again and returns the forecast.
32 */
33export const Route = createFileRoute('/api/mcp-input-test')({
34 server: {
35 handlers: {
36 POST: async ({ request }) => {
37 let params
38 try {
39 params = await chatParamsFromRequestBody(await request.json())
40 } catch (error) {
41 return new Response(
42 error instanceof Error ? error.message : 'Bad request',
43 { status: 400 },
44 )
45 }
46
47 const fp = params.forwardedProps
48 const testId = typeof fp.testId === 'string' ? fp.testId : undefined
49 const aimockPort =
50 fp.aimockPort != null ? Number(fp.aimockPort) : undefined
51 const origin = new URL(request.url).origin
52
53 let mcp: MCPClient | undefined
54 try {
55 mcp = await createMCPClient({
56 transport: { type: 'http', url: `${origin}/api/mcp-input-server` },
57 })
58 const tools = await mcp.tools()
59 const stream = chat({
60 ...createTextAdapter('openai', undefined, aimockPort, testId),
61 messages: params.messages,
62 tools,
63 threadId: params.threadId,
64 runId: params.runId,
65 ...(params.parentRunId ? { parentRunId: params.parentRunId } : {}),
66 ...(params.resume ? { resume: params.resume } : {}),
67 agentLoopStrategy: maxIterations(5),
68 })
69 return toServerSentEventsResponse(closeMcpOnDrain(stream, mcp))
70 } catch (error) {
71 if (mcp) await mcp.close().catch(() => undefined)
72 const message =
73 error instanceof Error ? error.message : 'An error occurred'
74 return new Response(JSON.stringify({ error: message }), {
75 status: 500,
76 headers: { 'Content-Type': 'application/json' },
77 })
78 }
79 },
80 },
81 },
82})