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

mcp.spec.ts

170 lines6.0 KB

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