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

api.mcp-input-test.ts

110 lines3.5 KB

1import { createFileRoute } from '@tanstack/react-router'
2import {
3 chat,
4 chatParamsFromRequestBody,
5 maxIterations,
6 toServerSentEventsResponse,
7} from '@tanstack/ai'
8import { createMCPClient, isMCPInputRequiredError } from '@tanstack/ai-mcp'
9import type { AnyTool, 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 }
25​
26/**
27 * Give each input request of `tool` the interrupt `reason`. The thrown
28 * value keeps its MCP input-required shape.
29 */
30function withInterruptReason(tool: AnyTool, reason: string): AnyTool {
31 const { execute } = tool
32 if (!execute) return tool
33 return {
34 ...tool,
35 execute: async (args, context) => {
36 try {
37 return await execute(args, context)
38 } catch (error) {
39 if (isMCPInputRequiredError(error)) Object.assign(error, { reason })
40 throw error
41 }
42 },
43 }
45​
46/**
47 * Runs `chat()` with the tools of `api.mcp-input-server`.
48 *
49 * The first request pauses with an `mcp_input` interrupt.
50 * A second request with `parentRunId` and `resume` sends the answer.
51 * The tool then runs again and returns the forecast.
52 * `forwardedProps.interruptReason` sets the reason of the pause.
53 */
54export const Route = createFileRoute('/api/mcp-input-test')({
55 server: {
56 handlers: {
57 POST: async ({ request }) => {
58 let params
59 try {
60 params = await chatParamsFromRequestBody(await request.json())
61 } catch (error) {
62 return new Response(
63 error instanceof Error ? error.message : 'Bad request',
64 { status: 400 },
65 )
66 }
67​
68 const fp = params.forwardedProps
69 const testId = typeof fp.testId === 'string' ? fp.testId : undefined
70 const aimockPort =
71 fp.aimockPort != null ? Number(fp.aimockPort) : undefined
72 const origin = new URL(request.url).origin
73​
74 let mcp: MCPClient | undefined
75 try {
76 mcp = await createMCPClient({
77 transport: { type: 'http', url: `${origin}/api/mcp-input-server` },
78 })
79 const reason =
80 typeof fp.interruptReason === 'string'
81 ? fp.interruptReason
82 : undefined
83 const mcpTools = await mcp.tools()
84 const tools = reason
85 ? mcpTools.map((tool) => withInterruptReason(tool, reason))
86 : mcpTools
87 const stream = chat({
88 ...createTextAdapter('openai', undefined, aimockPort, testId),
89 messages: params.messages,
90 tools,
91 threadId: params.threadId,
92 runId: params.runId,
93 ...(params.parentRunId ? { parentRunId: params.parentRunId } : {}),
94 ...(params.resume ? { resume: params.resume } : {}),
95 agentLoopStrategy: maxIterations(5),
96 })
97 return toServerSentEventsResponse(closeMcpOnDrain(stream, mcp))
98 } catch (error) {
99 if (mcp) await mcp.close().catch(() => undefined)
100 const message =
101 error instanceof Error ? error.message : 'An error occurred'
102 return new Response(JSON.stringify({ error: message }), {
103 status: 500,
104 headers: { 'Content-Type': 'application/json' },
105 })
106 }
107 },
108 },
109 },
110})