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

mcp-managed.spec.ts

116 lines4.0 KB

1import { test, expect } from './fixtures'
2​
3/**
4 * MCP tool discovery + execution managed by `chat({ mcp })`.
5 *
6 * Proves that passing `mcp: { clients, connection: 'close' }` to `chat()` is
7 * sufficient to:
8 * 1. Auto-discover tools from the MCP client (no manual `mcp.tools()` call).
9 * 2. Execute the discovered tool (`get_guitar_price`) inside the agent loop.
10 * 3. Close the MCP client after the stream drains (no manual `mcp.close()`).
11 *
12 * The route under test (`api.mcp-managed-test`) does NOT call `mcp.tools()` or
13 * `mcp.close()` — it delegates both to `chat({ mcp })`. Compare with
14 * `api.mcp-test`, which manually calls `mcp.tools()` and wraps the stream in a
15 * `closeMcpOnDrain` generator.
16 *
17 * Same fixture as the basic MCP test (`fixtures/mcp/basic.json`). Each test
18 * gets a unique `testId` so `sequenceIndex` is isolated between the two specs.
19 */
20​
21type StreamEvent = {
22 type: string
23 toolName?: 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-managed — chat({ mcp }) discovery + lifecycle', () => {
48 test('chat({ mcp }) discovers get_guitar_price and the result reaches the transcript', async ({
49 request,
50 testId,
51 aimockPort,
52 }) => {
53 // Minimal valid AG-UI RunAgentInput body — identical message to the basic
54 // MCP spec so the same aimock fixture (`fixtures/mcp/basic.json`) is used.
55 // Unique testId ensures sequenceIndex isolation from the other spec.
56 const res = await request.post('/api/mcp-managed-test', {
57 headers: { 'Content-Type': 'application/json' },
58 data: {
59 threadId: `mcp-managed-thread-${testId}`,
60 runId: `mcp-managed-run-${testId}`,
61 state: {},
62 messages: [
63 {
64 id: 'mcp-managed-msg-1',
65 role: 'user',
66 content: '[mcp] how much is the strat guitar',
67 },
68 ],
69 tools: [],
70 context: [],
71 forwardedProps: { testId, aimockPort },
72 },
73 })
74​
75 const body = await res.text()
76 expect(
77 res.ok(),
78 `mcp-managed-test route failed (${res.status()}): ${body}`,
79 ).toBe(true)
80​
81 const events = parseSse(body)
82​
83 // The agentic loop must have invoked the MCP tool via chat({ mcp }) discovery.
84 const toolStart = events.find(
85 (e) =>
86 e.type === 'TOOL_CALL_START' &&
87 (e.toolName === 'get_guitar_price' ||
88 e.toolCallName === 'get_guitar_price'),
89 )
90 expect(
91 toolStart,
92 'expected a TOOL_CALL_START for get_guitar_price',
93 ).toBeTruthy()
94​
95 // The MCP tool result is emitted as the AG-UI TOOL_CALL_RESULT event. The
96 // price 1999 originates ONLY from the real MCP server (the fixture's
97 // tool-call args don't contain it), so finding it here proves the MCP tool
98 // actually executed against the in-process server via chat({ mcp }).
99 const toolResult = events.find((e) => e.type === 'TOOL_CALL_RESULT')
100 expect(toolResult, 'expected a TOOL_CALL_RESULT event').toBeTruthy()
101 const resultStr = JSON.stringify(toolResult?.content ?? '')
102 expect(resultStr).toContain('1999')
103 expect(resultStr).toContain('strat')
104​
105 // The final assistant text (post tool execution) must contain the price too.
106 const finalText = events
107 .filter((e) => e.type === 'TEXT_MESSAGE_CONTENT' && e.delta)
108 .map((e) => e.delta)
109 .join('')
110 expect(finalText).toContain('1999')
111​
112 // The run completed cleanly (no RUN_ERROR).
113 expect(events.some((e) => e.type === 'RUN_ERROR')).toBe(false)
114 expect(events.some((e) => e.type === 'RUN_FINISHED')).toBe(true)
115 })
116})