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

api.mcp-manual.ts

168 lines6.1 KB

1/**
2 * /api/mcp-manual — MANUAL MCP client pattern.
3 *
4 * Demonstrates the fully-manual use-case:
5 * 1. The caller creates the MCP client and owns its lifecycle.
6 * 2. Tools are discovered via client.tools() and spread into chat() explicitly.
7 * 3. Resources and prompts from the server are fetched and injected into the
8 * conversation as extra context before the user's messages.
9 * 4. The MCP client is closed AFTER the SSE stream fully drains (tool calls
10 * fire mid-stream, so an earlier close would abort them).
11 *
12 * Uses @modelcontextprotocol/server-everything (keyless, via npx) as the MCP
13 * server. Only OPENAI_API_KEY is required — no MCP-specific API keys needed.
14 */
15import { createFileRoute } from '@tanstack/react-router'
16import {
17 chat,
18 chatParamsFromRequestBody,
19 maxIterations,
20 toServerSentEventsResponse,
21} from '@tanstack/ai'
22import {
23 createMCPClient,
24 mcpPromptToMessages,
25 mcpResourceToContentPart,
26} from '@tanstack/ai-mcp'
27import type { ModelMessage, StreamChunk } from '@tanstack/ai'
28import type { MCPClient } from '@tanstack/ai-mcp'
29import { resolveTextAdapter } from '@/lib/mcp-provider-adapters'
30import { everythingTransport } from '@/lib/mcp-servers'
31​
32/**
33 * Wrap the chat stream so the MCP client is closed AFTER the stream has fully
34 * drained (or errored). Tool calls fire mid-stream; closing the client earlier
35 * would abort any in-flight MCP tool call.
36 */
37async function* closeMcpOnDrain(
38 stream: AsyncIterable<StreamChunk>,
39 mcp: MCPClient,
40): AsyncGenerator<StreamChunk> {
41 try {
42 for await (const chunk of stream) {
43 yield chunk
44 }
45 } finally {
46 await mcp.close()
47 }
49​
50export const Route = createFileRoute('/api/mcp-manual')({
51 server: {
52 handlers: {
53 POST: async ({ request }) => {
54 // Capture signal before reading body (it may be aborted after consumption)
55 const requestSignal = request.signal
56​
57 if (requestSignal.aborted) {
58 return new Response(null, { status: 499 }) // 499 = Client Closed Request
59 }
60​
61 const abortController = new AbortController()
62​
63 let params
64 try {
65 params = await chatParamsFromRequestBody(await request.json())
66 } catch (error) {
67 return new Response(
68 error instanceof Error ? error.message : 'Bad request',
69 { status: 400 },
70 )
71 }
72​
73 // Held in the outer scope so the catch below can close it on any
74 // error path that happens before the SSE stream takes ownership.
75 let client: MCPClient | undefined
76 try {
77 // --- MCP: create and connect to the everything server (keyless, stdio) ---
78 client = await createMCPClient({
79 transport: everythingTransport(),
80 })
81​
82 // Auto-discover all tools from the MCP server.
83 const tools = await client.tools()
84​
85 // --- MCP: resources — inject the first resource as context (if any) ---
86 const contextMessages: Array<ModelMessage> = []
87​
88 try {
89 const resources = await client.resources()
90 if (resources.length > 0) {
91 // Read the first resource and convert each content block to a ContentPart.
92 const readResult = await client.readResource(resources[0].uri)
93 const parts = readResult.contents.map(mcpResourceToContentPart)
94 if (parts.length > 0) {
95 contextMessages.push({
96 role: 'user',
97 content: [
98 ...parts,
99 {
100 type: 'text',
101 content:
102 '[MCP resource context injected from server-everything — use this as background information if relevant]',
103 },
104 ],
105 })
106 }
107 }
108 } catch {
109 // Resources are optional — proceed without them if unavailable.
110 }
111​
112 // --- MCP: prompts — prepend the first available prompt (if any) ---
113 try {
114 const availablePrompts = await client.prompts()
115 if (availablePrompts.length > 0) {
116 const firstPrompt = availablePrompts[0]!
117 const promptResult = await client.getPrompt(firstPrompt.name)
118 const promptMessages = mcpPromptToMessages(promptResult)
119 // Prepend prompt messages before resource context and user messages.
120 contextMessages.unshift(...promptMessages)
121 }
122 } catch {
123 // Prompts are optional — proceed without them if unavailable.
124 }
125​
126 // OPENAI_API_KEY is used by the LLM adapter (separate from the
127 // keyless MCP server transport which needs no credentials).
128 // The model is encoded in the adapter; do not pass it separately.
129 const stream = chat({
130 adapter: resolveTextAdapter(params.forwardedProps.provider),
131 messages: [...contextMessages, ...params.messages],
132 tools,
133 agentLoopStrategy: maxIterations(20),
134 threadId: params.threadId,
135 runId: params.runId,
136 abortController,
137 })
138​
139 // Close the MCP client only after the SSE stream fully drains.
140 return toServerSentEventsResponse(closeMcpOnDrain(stream, client), {
141 abortController,
142 })
143 } catch (error: any) {
144 // The stream never took ownership of the client — close it here so
145 // the stdio MCP process isn't leaked.
146 if (client) {
147 await client.close().catch(() => undefined)
148 }
149 console.error('[api.mcp-manual] Error:', {
150 message: error?.message,
151 name: error?.name,
152 stack: error?.stack,
153 })
154 if (error.name === 'AbortError' || abortController.signal.aborted) {
155 return new Response(null, { status: 499 })
156 }
157 return new Response(
158 JSON.stringify({ error: error.message || 'An error occurred' }),
159 {
160 status: 500,
161 headers: { 'Content-Type': 'application/json' },
162 },
163 )
164 }
165 },
166 },
167 },
168})