Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

api.mcp-managed-test.ts

96 lines3.3 KB

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 { createTextAdapter } from '@/lib/providers'
10​
11/**
12 * Drives a real `chat()` agent loop with MCP tool discovery managed entirely
13 * by `chat({ mcp })` — the caller does NOT manually call `mcp.tools()` or
14 * `mcp.close()`. This verifies that passing `mcp: { clients, connection }` to
15 * `chat()` correctly:
16 * 1. Auto-discovers tools from the MCP client (here: `get_guitar_price`).
17 * 2. Runs the tool inside the agent loop via the aimock fixture.
18 * 3. Closes the client after the stream drains (connection: 'close').
19 *
20 * Contrast with `api.mcp-test.ts` which manually calls `mcp.tools()`, wraps
21 * the stream in a `closeMcpOnDrain` generator, and passes `tools` directly.
22 */
23export const Route = createFileRoute('/api/mcp-managed-test')({
24 server: {
25 handlers: {
26 POST: async ({ request }) => {
27 if (request.signal.aborted) {
28 return new Response(null, { status: 499 })
29 }
30​
31 const abortController = new AbortController()
32​
33 let params
34 try {
35 params = await chatParamsFromRequestBody(await request.json())
36 } catch (error) {
37 return new Response(
38 error instanceof Error ? error.message : 'Bad request',
39 { status: 400 },
40 )
41 }
42​
43 const fp = params.forwardedProps
44 const testId = typeof fp.testId === 'string' ? fp.testId : undefined
45 const aimockPort =
46 fp.aimockPort != null ? Number(fp.aimockPort) : undefined
47​
48 // The mock MCP server lives at this same dev server's origin.
49 const origin = new URL(request.url).origin
50 const mcpServerUrl = `${origin}/api/mcp-server`
51​
52 try {
53 // Create the MCP client — but do NOT call client.tools() or
54 // client.close() here. Pass it to chat({ mcp }) and let chat manage
55 // the full lifecycle: discovery, execution, and teardown.
56 const client = await createMCPClient({
57 transport: { type: 'http', url: mcpServerUrl },
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 threadId: params.threadId,
71 runId: params.runId,
72 mcp: { clients: [client], connection: 'close' },
73 agentLoopStrategy: maxIterations(5),
74 abortController,
75 })
76​
77 return toServerSentEventsResponse(stream, { abortController })
78 } catch (error) {
79 console.error('[api.mcp-managed-test] Error:', error)
80 if (
81 (error instanceof Error && error.name === 'AbortError') ||
82 abortController.signal.aborted
83 ) {
84 return new Response(null, { status: 499 })
85 }
86 const message =
87 error instanceof Error ? error.message : 'An error occurred'
88 return new Response(JSON.stringify({ error: message }), {
89 status: 500,
90 headers: { 'Content-Type': 'application/json' },
91 })
92 }
93 },
94 },
95 },
96})