Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import { chat, chatParamsFromRequestBody, maxIterations } from '@tanstack/ai'
3import { createMCPClient } from '@tanstack/ai-mcp'
4import type { StreamChunk } from '@tanstack/ai'
5import { createTextAdapter } from '@/lib/providers'
6
7/**
8 * Validates `chat({ mcp: { connection } })` lifecycle semantics end-to-end.
9 *
10 * Runs a real `chat()` agent loop with one MCP client, drains it, then probes
11 * the client AFTER the run:
12 * - `connection: 'close'` (default) → chat closed the client → `client.tools()`
13 * now throws → `survivedAfterRun: false`.
14 * - `connection: 'keep-alive'` → chat left the client open → `client.tools()`
15 * still works → `survivedAfterRun: true` (we then close it ourselves).
16 *
17 * Returns JSON so the spec can assert the lifecycle deterministically without
18 * scraping the SSE stream. The aimock fixture (`fixtures/mcp/lifecycle.json`)
19 * returns a plain text turn (no tool call) — the tool isn't needed; only the
20 * client lifecycle is under test.
21 */
22export const Route = createFileRoute('/api/mcp-lifecycle-test')({
23 server: {
24 handlers: {
25 POST: async ({ request }) => {
26 let params
27 try {
28 params = await chatParamsFromRequestBody(await request.json())
29 } catch (error) {
30 return new Response(
31 error instanceof Error ? error.message : 'Bad request',
32 { status: 400 },
33 )
34 }
35
36 const fp = params.forwardedProps
37 const testId = typeof fp.testId === 'string' ? fp.testId : undefined
38 const aimockPort =
39 fp.aimockPort != null ? Number(fp.aimockPort) : undefined
40 const connection =
41 fp.connection === 'keep-alive' ? 'keep-alive' : 'close'
42
43 const origin = new URL(request.url).origin
44 const mcpUrl = `${origin}/api/mcp-server`
45
46 try {
47 const client = await createMCPClient({
48 transport: { type: 'http', url: mcpUrl },
49 })
50
51 const adapterOptions = createTextAdapter(
52 'openai',
53 undefined,
54 aimockPort,
55 testId,
56 )
57
58 const stream = chat({
59 ...adapterOptions,
60 messages: params.messages,
61 threadId: params.threadId,
62 runId: params.runId,
63 mcp: { clients: [client], connection },
64 agentLoopStrategy: maxIterations(3),
65 })
66
67 // Drain internally so chat()'s mcp dispose (the `finally`) has run by
68 // the time we probe the client below.
69 for await (const _chunk of stream as AsyncIterable<StreamChunk>) {
70 // discard
71 }
72
73 let survivedAfterRun = false
74 try {
75 await client.tools()
76 survivedAfterRun = true
77 } catch {
78 survivedAfterRun = false
79 }
80
81 // For keep-alive, chat left the connection open — close it now so the
82 // test doesn't leak an MCP connection.
83 if (survivedAfterRun) {
84 await client.close().catch(() => {})
85 }
86
87 return Response.json({ connection, survivedAfterRun })
88 } catch (error) {
89 const message =
90 error instanceof Error ? error.message : 'An error occurred'
91 return new Response(JSON.stringify({ error: message }), {
92 status: 500,
93 headers: { 'Content-Type': 'application/json' },
94 })
95 }
96 },
97 },
98 },
99})