Open History to see the last commit
1import { test, expect } from './fixtures'
2
3/**
4 * MCP server tool discovery + execution inside chat().
5 *
6 * Proves the `@tanstack/ai-mcp` package end-to-end against the real E2E
7 * harness:
8 * - `api.mcp-server` hosts a real in-process MCP server (Streamable HTTP)
9 * exposing one deterministic tool `get_guitar_price` ({ id } → { id,
10 * price: 1999 }).
11 * - `api.mcp-test` connects to it via `createMCPClient`, discovers the tool
12 * with `mcp.tools()`, and runs it inside a real `chat()` agent loop with
13 * the LLM mocked by aimock.
14 * - The aimock fixture (`fixtures/mcp/basic.json`) makes the model emit a
15 * `get_guitar_price` tool call then a final answer.
16 *
17 * The MCP server is the *only* source of the price `1999`: the fixture's
18 * tool-call arguments don't contain it. So asserting `1999` reaches the
19 * streamed `TOOL_CALL_END.result` proves the MCP tool actually executed.
20 */
21
22type StreamEvent = {
23 type: string
24 toolName?: string
25 toolCallName?: string
26 toolCallId?: string
27 result?: unknown
28 content?: unknown
29 delta?: string
30}
31
32function parseSse(body: string): Array<StreamEvent> {
33 const events: Array<StreamEvent> = []
34 for (const line of body.split('\n')) {
35 const trimmed = line.trim()
36 if (!trimmed.startsWith('data:')) continue
37 const json = trimmed.slice('data:'.length).trim()
38 if (!json) continue
39 try {
40 events.push(JSON.parse(json) as StreamEvent)
41 } catch {
42 // Ignore non-JSON keepalive lines.
43 }
44 }
45 return events
46}
47
48test.describe('mcp — server tool discovery + execution in chat()', () => {
49 test('exposes the server instructions on the client', async ({ request }) => {
50 const res = await request.get('/api/mcp-test')
51 expect(res.ok(), await res.text()).toBe(true)
52 expect(await res.json()).toEqual({
53 instructions: 'Quote guitar prices in US dollars.',
54 })
55 })
56
57 test('discovers get_guitar_price from the MCP server and the result reaches the transcript', async ({
58 request,
59 testId,
60 aimockPort,
61 }) => {
62 // Minimal valid AG-UI RunAgentInput body (the route parses it via
63 // chatParamsFromRequestBody).
64 const res = await request.post('/api/mcp-test', {
65 headers: { 'Content-Type': 'application/json' },
66 data: {
67 threadId: `mcp-thread-${testId}`,
68 runId: `mcp-run-${testId}`,
69 state: {},
70 messages: [
71 {
72 id: 'mcp-msg-1',
73 role: 'user',
74 content: '[mcp] how much is the strat guitar',
75 },
76 ],
77 tools: [],
78 context: [],
79 forwardedProps: { testId, aimockPort },
80 },
81 })
82
83 const body = await res.text()
84 expect(res.ok(), `mcp-test route failed (${res.status()}): ${body}`).toBe(
85 true,
86 )
87
88 const events = parseSse(body)
89
90 // The agentic loop must have invoked the MCP tool.
91 const toolStart = events.find(
92 (e) =>
93 e.type === 'TOOL_CALL_START' &&
94 (e.toolName === 'get_guitar_price' ||
95 e.toolCallName === 'get_guitar_price'),
96 )
97 expect(
98 toolStart,
99 'expected a TOOL_CALL_START for get_guitar_price',
100 ).toBeTruthy()
101
102 // The MCP tool result is emitted as the AG-UI TOOL_CALL_RESULT event. The
103 // price 1999 originates ONLY from the real MCP server (the fixture's
104 // tool-call args don't contain it), so finding it here proves the MCP tool
105 // actually executed against the in-process server.
106 const toolResult = events.find((e) => e.type === 'TOOL_CALL_RESULT')
107 expect(toolResult, 'expected a TOOL_CALL_RESULT event').toBeTruthy()
108 const resultStr = JSON.stringify(toolResult?.content ?? '')
109 expect(resultStr).toContain('1999')
110 expect(resultStr).toContain('strat')
111
112 // And the final assistant text (post tool execution) streamed through.
113 const finalText = events
114 .filter((e) => e.type === 'TEXT_MESSAGE_CONTENT' && e.delta)
115 .map((e) => e.delta)
116 .join('')
117 expect(finalText).toContain('1999')
118
119 // The run completed cleanly (no RUN_ERROR).
120 expect(events.some((e) => e.type === 'RUN_ERROR')).toBe(false)
121 expect(events.some((e) => e.type === 'RUN_FINISHED')).toBe(true)
122 })
123
124 test('clientOptions reaches the SDK client — a custom validator changes the outcome', async ({
125 request,
126 testId,
127 aimockPort,
128 }) => {
129 // Same server, same fixture, one flag: the route installs a
130 // `jsonSchemaValidator` that refuses everything via `clientOptions`.
131 //
132 // The mock server's `get_guitar_price` declares an `outputSchema` and
133 // returns `structuredContent` the SDK's default AJV provider accepts, so a
134 // `clientOptions` that was dropped on the floor would leave this run
135 // identical to the test above. It is not: the tool call fails validation.
136 //
137 // That option is how an edge runtime installs a validator that does not
138 // compile schemas with `new Function`, which AJV does and Cloudflare
139 // Workers forbid.
140 const res = await request.post('/api/mcp-test', {
141 headers: { 'Content-Type': 'application/json' },
142 data: {
143 threadId: `mcp-opts-thread-${testId}`,
144 runId: `mcp-opts-run-${testId}`,
145 state: {},
146 messages: [
147 {
148 id: 'mcp-opts-msg-1',
149 role: 'user',
150 content: '[mcp] how much is the strat guitar',
151 },
152 ],
153 tools: [],
154 context: [],
155 forwardedProps: { testId, aimockPort, rejectStructuredOutput: true },
156 },
157 })
158
159 const body = await res.text()
160 const events = parseSse(body)
161
162 const toolResult = events.find((e) => e.type === 'TOOL_CALL_RESULT')
163 expect(toolResult, 'expected a TOOL_CALL_RESULT event').toBeTruthy()
164 const resultStr = JSON.stringify(toolResult?.content ?? '')
165
166 expect(resultStr).toContain('rejected by the injected validator')
167 // The other half of the proof: the payload the default validator accepts
168 // never reaches the tool result. Asserted on the tool result rather than the
169 // whole transcript — the aimock fixture's final answer is a recorded script
170 // that names the price whether or not the tool succeeded.
171 expect(resultStr).not.toContain('1999')
172 })
173})