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

api.mcp-test.ts

183 lines6.5 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 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 },
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 }
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 // Returns the server's instructions from the connect handshake.
76 GET: async ({ request }) => {
77 const origin = new URL(request.url).origin
78 const mcp = await createMCPClient({
79 transport: { type: 'http', url: `${origin}/api/mcp-server` },
80 })
81 try {
82 return Response.json({ instructions: mcp.instructions ?? null })
83 } finally {
84 await mcp.close()
85 }
86 },
87 POST: async ({ request }) => {
88 if (request.signal.aborted) {
89 return new Response(null, { status: 499 })
90 }
91​
92 const abortController = new AbortController()
93 // Bridge request cancellation into the chat abort controller so an
94 // abort during setup (before the SSE handoff) is observed.
95 const onRequestAbort = () => abortController.abort()
96 request.signal.addEventListener('abort', onRequestAbort, {
97 once: true,
98 })
99​
100 let params
101 try {
102 params = await chatParamsFromRequestBody(await request.json())
103 } catch (error) {
104 return new Response(
105 error instanceof Error ? error.message : 'Bad request',
106 { status: 400 },
107 )
108 }
109​
110 const fp = params.forwardedProps
111 const testId = typeof fp.testId === 'string' ? fp.testId : undefined
112 const aimockPort =
113 fp.aimockPort != null ? Number(fp.aimockPort) : undefined
114 // Opt-in: install a custom `jsonSchemaValidator` through
115 // `clientOptions` so the spec can prove the option reaches the SDK.
116 const rejectStructuredOutput = fp.rejectStructuredOutput === true
117​
118 // The mock MCP server lives at this same dev server's origin.
119 const origin = new URL(request.url).origin
120 const mcpUrl = `${origin}/api/mcp-server`
121​
122 // Held in the outer scope so the catch below can close it on any
123 // error path that happens before the SSE stream takes ownership.
124 let mcp: MCPClient | undefined
125 try {
126 mcp = await createMCPClient({
127 transport: { type: 'http', url: mcpUrl },
128 ...(rejectStructuredOutput
129 ? {
130 clientOptions: {
131 jsonSchemaValidator: rejectingJsonSchemaValidator,
132 },
133 }
134 : {}),
135 })
136​
137 const tools = await mcp.tools()
138​
139 const adapterOptions = createTextAdapter(
140 'openai',
141 undefined,
142 aimockPort,
143 testId,
144 )
145​
146 const stream = chat({
147 ...adapterOptions,
148 messages: params.messages,
149 tools,
150 threadId: params.threadId,
151 runId: params.runId,
152 agentLoopStrategy: maxIterations(5),
153 abortController,
154 })
155​
156 // Close the MCP client only after the SSE stream fully drains —
157 // tool calls fire mid-stream, so an early close would abort them.
158 return toServerSentEventsResponse(closeMcpOnDrain(stream, mcp), {
159 abortController,
160 })
161 } catch (error) {
162 // The stream never took ownership of the client — close it here.
163 if (mcp) {
164 await mcp.close().catch(() => undefined)
165 }
166 console.error('[api.mcp-test] Error:', error)
167 if (
168 (error instanceof Error && error.name === 'AbortError') ||
169 abortController.signal.aborted
170 ) {
171 return new Response(null, { status: 499 })
172 }
173 const message =
174 error instanceof Error ? error.message : 'An error occurred'
175 return new Response(JSON.stringify({ error: message }), {
176 status: 500,
177 headers: { 'Content-Type': 'application/json' },
178 })
179 }
180 },
181 },
182 },
183})