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 adapter,
110 messages: [{ role: 'user', content: 'hi' }],
111 mcp: {
112 clients: [pool],
113 ...(connection === undefined ? {} : { connection }),
114 },
115 })
116 await drain(stream)
117 return { pool, closeSpy, seenTools }
118}
119
120describe('createMCPClients pool → chat({ mcp })', () => {
121 it("discovers the pool's prefixed tools and closes the pool after the run", async () => {
122 const { clientTransport } = await makeServerWithWeatherTool()
123 const { seenTools, closeSpy } = await runPoolChat(clientTransport)
124
125 // Pool tool was discovered + merged into the run (auto-prefixed by config key).
126 expect(seenTools).toContain('weather_get_weather')
127 // Default connection ('close') disposes the pool when the run drains.
128 expect(closeSpy).toHaveBeenCalledTimes(1)
129 })
130
131 it("keep-alive: the pool is NOT closed when connection is 'keep-alive'", async () => {
132 const { clientTransport } = await makeServerWithWeatherTool()
133 const { closeSpy, pool } = await runPoolChat(clientTransport, 'keep-alive')
134
135 expect(closeSpy).not.toHaveBeenCalled()
136 await pool.close() // clean up the kept-alive connection
137 })
138
139 it('discovers tools from a spec 2026 server', async () => {
140 const clientTransport = await makeModernWeatherTransport()
141 const { seenTools, closeSpy } = await runPoolChat(clientTransport)
142
143 expect(seenTools).toEqual(['weather_get_weather'])
144 expect(closeSpy).toHaveBeenCalledTimes(1)
145 })
146})
147
148// The server has no public setter for the negotiated era, so the test sets it.
149async function makeModernWeatherTransport() {
150 const [clientTransport, serverTransport] =
151 InMemoryTransport.createLinkedPair()
152 const server = new Server(
153 { name: 'modern-weather', version: '1.0.0' },
154 {
155 capabilities: { tools: {} },
156 supportedProtocolVersions: [...SUPPORTED_PROTOCOL_VERSIONS, '2026-07-28'],
157 },
158 )
159 Object.assign(server, { _negotiatedProtocolVersion: '2026-07-28' })
160 server.setRequestHandler('tools/list', () => ({
161 tools: [
162 {
163 name: 'get_weather',
164 description: 'Get weather for a city',
165 inputSchema: {
166 type: 'object',
167 properties: { city: { type: 'string' } },
168 },
169 },
170 ],
171 }))
172 server.setRequestHandler('tools/call', () => ({
173 content: [{ type: 'text' as const, text: 'Sunny' }],
174 }))
175 await server.connect(serverTransport)
176 return clientTransport
177}