Open History to see the last commit
1/**
2 * Integration: a real `createMCPClients(...)` pool passed into `chat({ mcp })`.
3 *
4 * The chat-side unit tests (packages/ai) cover the `MCPToolSource` contract with
5 * fake sources, and `pool.test.ts` covers the pool's own `tools()`/`close()`.
6 * This wires the two together end-to-end: a live in-memory MCP server pool
7 * handed to `chat()` must have its (prefixed) tools discovered into the run and
8 * its connections closed when the run drains — proving the pool genuinely
9 * satisfies the `MCPToolSource` shape `chat({ mcp })` consumes.
10 */
11import { describe, expect, it, vi } from 'vitest'
12import {
13 InMemoryTransport,
14 SUPPORTED_PROTOCOL_VERSIONS,
15} from '@modelcontextprotocol/client'
16import { Server } from '@modelcontextprotocol/server'
17import { EventType, chat } from '@tanstack/ai'
18import type { AdapterYieldChunk, AnyTextAdapter } from '@tanstack/ai'
19import type { Transport } from '@modelcontextprotocol/client'
20import { createMCPClients } from '../src/pool'
21import { makeServerWithWeatherTool } from './helpers/in-memory-server'
22
23/**
24 * Minimal text adapter: captures the tool names handed to `chatStream` (so we
25 * can assert the pool's tools were discovered + merged) and emits a complete
26 * AG-UI lifecycle so the engine finishes cleanly.
27 */
28function makeMockAdapter(
29 onTools: (names: Array<string>) => void,
30): AnyTextAdapter {
31 const chatStream: AnyTextAdapter['chatStream'] = (options) => {
32 const tools = options.tools ?? []
33 onTools(tools.map((tool) => tool.name))
34 return textEvents()
35 }
36 return {
37 kind: 'text',
38 name: 'mock',
39 model: 'test-model',
40 '~types': {
41 providerOptions: {},
42 inputModalities: ['text'],
43 messageMetadataByModality: {
44 text: undefined,
45 image: undefined,
46 audio: undefined,
47 video: undefined,
48 document: undefined,
49 },
50 toolCapabilities: [],
51 toolCallMetadata: undefined,
52 systemPromptMetadata: undefined,
53 },
54 chatStream,
55 structuredOutput: async () => ({ data: {}, rawText: '{}' }),
56 }
57}
58
59async function* textEvents(): AsyncGenerator<AdapterYieldChunk> {
60 const timestamp = Date.now()
61 yield {
62 type: EventType.RUN_STARTED,
63 runId: 'r1',
64 threadId: 't1',
65 timestamp,
66 }
67 yield {
68 type: EventType.TEXT_MESSAGE_START,
69 messageId: 'm1',
70 role: 'assistant',
71 timestamp,
72 }
73 yield {
74 type: EventType.TEXT_MESSAGE_CONTENT,
75 messageId: 'm1',
76 delta: 'ok',
77 timestamp,
78 }
79 yield {
80 type: EventType.TEXT_MESSAGE_END,
81 messageId: 'm1',
82 timestamp,
83 }
84 yield {
85 type: EventType.RUN_FINISHED,
86 runId: 'r1',
87 threadId: 't1',
88 finishReason: 'stop',
89 timestamp,
90 }
91}
92
93async function drain(stream: AsyncIterable<unknown>): Promise<void> {
94 for await (const _chunk of stream) {
95 // discard
96 }
97}
98
99async function runPoolChat(transport: Transport, connection?: 'keep-alive') {
100 const pool = await createMCPClients({
101 weather: { transport },
102 })
103 const closeSpy = vi.spyOn(pool, 'close')
104 let seenTools: Array<string> = []
105 const adapter = makeMockAdapter((names) => {
106 seenTools = names
107 })
108 const stream = chat({
109 threadId: 'thread-1',
110 adapter,
111 messages: [{ role: 'user', content: 'hi' }],
112 mcp: {
113 clients: [pool],
114 ...(connection === undefined ? {} : { connection }),
115 },
116 })
117 await drain(stream)
118 return { pool, closeSpy, seenTools }
119}
120
121describe('createMCPClients pool → chat({ mcp })', () => {
122 it("discovers the pool's prefixed tools and closes the pool after the run", async () => {
123 const { clientTransport } = await makeServerWithWeatherTool()
124 const { seenTools, closeSpy } = await runPoolChat(clientTransport)
125
126 // Pool tool was discovered + merged into the run (auto-prefixed by config key).
127 expect(seenTools).toContain('weather_get_weather')
128 // Default connection ('close') disposes the pool when the run drains.
129 expect(closeSpy).toHaveBeenCalledTimes(1)
130 })
131
132 it("keep-alive: the pool is NOT closed when connection is 'keep-alive'", async () => {
133 const { clientTransport } = await makeServerWithWeatherTool()
134 const { closeSpy, pool } = await runPoolChat(clientTransport, 'keep-alive')
135
136 expect(closeSpy).not.toHaveBeenCalled()
137 await pool.close() // clean up the kept-alive connection
138 })
139
140 it('discovers tools from a spec 2026 server', async () => {
141 const clientTransport = await makeModernWeatherTransport()
142 const { seenTools, closeSpy } = await runPoolChat(clientTransport)
143
144 expect(seenTools).toEqual(['weather_get_weather'])
145 expect(closeSpy).toHaveBeenCalledTimes(1)
146 })
147})
148
149// The server has no public setter for the negotiated era, so the test sets it.
150async function makeModernWeatherTransport() {
151 const [clientTransport, serverTransport] =
152 InMemoryTransport.createLinkedPair()
153 const server = new Server(
154 { name: 'modern-weather', version: '1.0.0' },
155 {
156 capabilities: { tools: {} },
157 supportedProtocolVersions: [...SUPPORTED_PROTOCOL_VERSIONS, '2026-07-28'],
158 },
159 )
160 Object.assign(server, { _negotiatedProtocolVersion: '2026-07-28' })
161 server.setRequestHandler('tools/list', () => ({
162 tools: [
163 {
164 name: 'get_weather',
165 description: 'Get weather for a city',
166 inputSchema: {
167 type: 'object',
168 properties: { city: { type: 'string' } },
169 },
170 },
171 ],
172 }))
173 server.setRequestHandler('tools/call', () => ({
174 content: [{ type: 'text' as const, text: 'Sunny' }],
175 }))
176 await server.connect(serverTransport)
177 return clientTransport
178}