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'
12import type { jsonSchemaValidator } from '@modelcontextprotocol/sdk/validation'
13
14/**
15 * A JSON Schema validator that refuses everything.
16 *
17 * Stands in for `CfWorkerJsonSchemaValidator`, which exists because the SDK's
18 * default AJV provider compiles schemas with `new Function` — forbidden on edge
19 * runtimes, where it fails an entire `tools/list` against any server whose
20 * tools declare an `outputSchema`.
21 *
22 * Refusing rather than accepting is what makes the pass-through observable: the
23 * mock server's `get_guitar_price` returns `structuredContent` that AJV accepts,
24 * so a `clientOptions` that never reached the SDK would leave the run
25 * succeeding with the price in the transcript. With it installed, the tool call
26 * fails instead.
27 */
28const rejectingJsonSchemaValidator: jsonSchemaValidator = {
29 getValidator() {
30 return () => ({
31 valid: false,
32 data: undefined,
33 errorMessage: 'rejected by the injected validator',
34 })
35 },
36}
37
38/**
39 * Wrap the chat stream so the MCP client is closed only AFTER the stream has
40 * fully drained (or errored). Tool calls fire mid-stream, so closing the
41 * client earlier would abort an in-flight MCP tool call.
42 */
43async function* closeMcpOnDrain(
44 stream: AsyncIterable<StreamChunk>,
45 mcp: MCPClient,
46): AsyncGenerator<StreamChunk> {
47 try {
48 for await (const chunk of stream) {
49 yield chunk
50 }
51 } finally {
52 await mcp.close()
53 }
54}
55
56/**
57 * Drives a real `chat()` agent loop whose tools are discovered from the
58 * in-process mock MCP server (`api.mcp-server`) via `@tanstack/ai-mcp`.
59 *
60 * Flow:
61 * 1. `createMCPClient({ transport: { type: 'http', url } })` connects to the
62 * mock MCP server at this dev server's own origin.
63 * 2. `mcp.tools()` auto-discovers the server's tools (here: `get_guitar_price`)
64 * as TanStack `ServerTool`s whose `execute` proxies to the MCP server.
65 * 3. `chat()` runs the OpenAI adapter against aimock. The aimock fixture
66 * emits a `get_guitar_price` tool call; the MCP tool executes for real
67 * against the mock server, returning `{ id, price: 1999 }`; the result is
68 * fed back and the model emits a final answer mentioning the price.
69 * 4. The MCP client is closed in `finally` AFTER the stream fully drains —
70 * closing earlier would kill the connection mid tool-call.
71 */
72export const Route = createFileRoute('/api/mcp-test')({
73 server: {
74 handlers: {
75 POST: async ({ request }) => {
76 if (request.signal.aborted) {
77 return new Response(null, { status: 499 })
78 }
79
80 const abortController = new AbortController()
81 // Bridge request cancellation into the chat abort controller so an
82 // abort during setup (before the SSE handoff) is observed.
83 const onRequestAbort = () => abortController.abort()
84 request.signal.addEventListener('abort', onRequestAbort, {
85 once: true,
86 })
87
88 let params
89 try {
90 params = await chatParamsFromRequestBody(await request.json())
91 } catch (error) {
92 return new Response(
93 error instanceof Error ? error.message : 'Bad request',
94 { status: 400 },
95 )
96 }
97
98 const fp = params.forwardedProps
99 const testId = typeof fp.testId === 'string' ? fp.testId : undefined
100 const aimockPort =
101 fp.aimockPort != null ? Number(fp.aimockPort) : undefined
102 // Opt-in: install a custom `jsonSchemaValidator` through
103 // `clientOptions` so the spec can prove the option reaches the SDK.
104 const rejectStructuredOutput = fp.rejectStructuredOutput === true
105
106 // The mock MCP server lives at this same dev server's origin.
107 const origin = new URL(request.url).origin
108 const mcpUrl = `${origin}/api/mcp-server`
109
110 // Held in the outer scope so the catch below can close it on any
111 // error path that happens before the SSE stream takes ownership.
112 let mcp: MCPClient | undefined
113 try {
114 mcp = await createMCPClient({
115 transport: { type: 'http', url: mcpUrl },
116 ...(rejectStructuredOutput
117 ? {
118 clientOptions: {
119 jsonSchemaValidator: rejectingJsonSchemaValidator,
120 },
121 }
122 : {}),
123 })
124
125 const tools = await mcp.tools()
126
127 const adapterOptions = createTextAdapter(
128 'openai',
129 undefined,
130 aimockPort,
131 testId,
132 )
133
134 const stream = chat({
135 ...adapterOptions,
136 messages: params.messages,
137 tools,
138 threadId: params.threadId,
139 runId: params.runId,
140 agentLoopStrategy: maxIterations(5),
141 abortController,
142 })
143
144 // Close the MCP client only after the SSE stream fully drains —
145 // tool calls fire mid-stream, so an early close would abort them.
146 return toServerSentEventsResponse(closeMcpOnDrain(stream, mcp), {
147 abortController,
148 })
149 } catch (error) {
150 // The stream never took ownership of the client — close it here.
151 if (mcp) {
152 await mcp.close().catch(() => undefined)
153 }
154 console.error('[api.mcp-test] Error:', error)
155 if (
156 (error instanceof Error && error.name === 'AbortError') ||
157 abortController.signal.aborted
158 ) {
159 return new Response(null, { status: 499 })
160 }
161 const message =
162 error instanceof Error ? error.message : 'An error occurred'
163 return new Response(JSON.stringify({ error: message }), {
164 status: 500,
165 headers: { 'Content-Type': 'application/json' },
166 })
167 }
168 },
169 },
170 },
171})