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

mcp-managed.spec.ts

113 lines3.9 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 toolCallName?: string
24 toolCallId?: string
25 result?: unknown
26 content?: unknown
27 delta?: string
29​
30function parseSse(body: string): Array<StreamEvent> {
31 const events: Array<StreamEvent> = []
32 for (const line of body.split('\n')) {
33 const trimmed = line.trim()
34 if (!trimmed.startsWith('data:')) continue
35 const json = trimmed.slice('data:'.length).trim()
36 if (!json) continue
37 try {
38 events.push(JSON.parse(json) as StreamEvent)
39 } catch {
40 // Ignore non-JSON keepalive lines.
41 }
42 }
43 return events
45​
46test.describe('mcp-managed — chat({ mcp }) discovery + lifecycle', () => {
47 test('chat({ mcp }) discovers get_guitar_price and the result reaches the transcript', async ({
48 request,
49 testId,
50 aimockPort,
51 }) => {
52 // Minimal valid AG-UI RunAgentInput body — identical message to the basic
53 // MCP spec so the same aimock fixture (`fixtures/mcp/basic.json`) is used.
54 // Unique testId ensures sequenceIndex isolation from the other spec.
55 const res = await request.post('/api/mcp-managed-test', {
56 headers: { 'Content-Type': 'application/json' },
57 data: {
58 threadId: `mcp-managed-thread-${testId}`,
59 runId: `mcp-managed-run-${testId}`,
60 state: {},
61 messages: [
62 {
63 id: 'mcp-managed-msg-1',
64 role: 'user',
65 content: '[mcp] how much is the strat guitar',
66 },
67 ],
68 tools: [],
69 context: [],
70 forwardedProps: { testId, aimockPort },
71 },
72 })
73​
74 const body = await res.text()
75 expect(
76 res.ok(),
77 `mcp-managed-test route failed (${res.status()}): ${body}`,
78 ).toBe(true)
79​
80 const events = parseSse(body)
81​
82 // The agentic loop must have invoked the MCP tool via chat({ mcp }) discovery.
83 const toolStart = events.find(
84 (e) =>
85 e.type === 'TOOL_CALL_START' && e.toolCallName === 'get_guitar_price',
86 )
87 expect(
88 toolStart,
89 'expected a TOOL_CALL_START for get_guitar_price',
90 ).toBeTruthy()
91​
92 // The MCP tool result is emitted as the AG-UI TOOL_CALL_RESULT event. The
93 // price 1999 originates ONLY from the real MCP server (the fixture's
94 // tool-call args don't contain it), so finding it here proves the MCP tool
95 // actually executed against the in-process server via chat({ mcp }).
96 const toolResult = events.find((e) => e.type === 'TOOL_CALL_RESULT')
97 expect(toolResult, 'expected a TOOL_CALL_RESULT event').toBeTruthy()
98 const resultStr = JSON.stringify(toolResult?.content ?? '')
99 expect(resultStr).toContain('1999')
100 expect(resultStr).toContain('strat')
101​
102 // The final assistant text (post tool execution) must contain the price too.
103 const finalText = events
104 .filter((e) => e.type === 'TEXT_MESSAGE_CONTENT' && e.delta)
105 .map((e) => e.delta)
106 .join('')
107 expect(finalText).toContain('1999')
108​
109 // The run completed cleanly (no RUN_ERROR).
110 expect(events.some((e) => e.type === 'RUN_ERROR')).toBe(false)
111 expect(events.some((e) => e.type === 'RUN_FINISHED')).toBe(true)
112 })
113})