Open History to see the last commit
1import { describe, expect, it } from 'vitest'
2import {
3 InMemoryTransport,
4 SUPPORTED_PROTOCOL_VERSIONS,
5} from '@modelcontextprotocol/client'
6import { Server } from '@modelcontextprotocol/server'
7import { DuplicateToolNameError } from '../src/errors'
8import { createMCPClients } from '../src/pool'
9import {
10 makeServerWithMismatchedResource,
11 makeServerWithResource,
12 makeServerWithWeatherTool,
13} from './helpers/in-memory-server'
14import type { Transport } from '@modelcontextprotocol/client'
15
16describe('createMCPClients', () => {
17 it('connects to many servers and flattens auto-prefixed tools', async () => {
18 const a = await makeServerWithWeatherTool()
19 const b = await makeServerWithWeatherTool()
20 await using pool = await createMCPClients({
21 alpha: { transport: a.clientTransport },
22 beta: { transport: b.clientTransport },
23 })
24 const names = (await pool.tools()).map((t) => t.name)
25 expect(names).toContain('alpha_get_weather')
26 expect(names).toContain('beta_get_weather') // no collision despite same server tool name
27 })
28
29 it('exposes typed per-server access via .clients', async () => {
30 const a = await makeServerWithWeatherTool()
31 await using pool = await createMCPClients({
32 alpha: { transport: a.clientTransport },
33 })
34
35 expect(await pool.clients.alpha!.tools()).toBeDefined()
36 })
37
38 it('forwards ToolsOptions (lazy) to every server', async () => {
39 const a = await makeServerWithWeatherTool()
40 const b = await makeServerWithWeatherTool()
41 await using pool = await createMCPClients({
42 alpha: { transport: a.clientTransport },
43 beta: { transport: b.clientTransport },
44 })
45 const tools = await pool.tools({ lazy: true })
46 expect(tools.length).toBeGreaterThan(0)
47 expect(tools.every((t) => t.lazy === true)).toBe(true)
48 })
49
50 it('names the failing server by config key when tools() discovery fails', async () => {
51 const a = await makeServerWithWeatherTool()
52 const b = await makeServerWithWeatherTool()
53 const pool = await createMCPClients({
54 alpha: { transport: a.clientTransport },
55 beta: { transport: b.clientTransport },
56 })
57 // Force a per-server discovery failure after connect.
58
59 await pool.clients.beta!.close()
60 await expect(pool.tools()).rejects.toThrow(
61 /Failed to list tools from MCP server\(s\): beta/,
62 )
63 await pool.close()
64 })
65
66 it('readResource routes to the owning client and returns its result', async () => {
67 // alpha has no resources; res owns file:///hello.txt. The pool tries each
68 // client and returns the first success, so it must reach `res`.
69 const alpha = await makeServerWithWeatherTool()
70 const res = await makeServerWithResource()
71 await using pool = await createMCPClients({
72 alpha: { transport: alpha.clientTransport },
73 res: { transport: res.clientTransport },
74 })
75 const read = await pool.readResource('file:///hello.txt')
76 expect(read.contents[0]).toMatchObject({
77 uri: 'file:///hello.txt',
78 text: 'hello from resource',
79 })
80 })
81
82 it('readResource skips a client that resolves but returns a non-matching uri', async () => {
83 // `mismatch` resolves the read without error but stamps a DIFFERENT uri on
84 // its contents; the pool must skip it and reach the owning `res` server.
85 const mismatch = await makeServerWithMismatchedResource()
86 const res = await makeServerWithResource()
87 await using pool = await createMCPClients({
88 // mismatch first so it's tried before the owning server
89 mismatch: { transport: mismatch.clientTransport },
90 res: { transport: res.clientTransport },
91 })
92 const read = await pool.readResource('file:///hello.txt')
93 expect(read.contents[0]).toMatchObject({
94 uri: 'file:///hello.txt',
95 text: 'hello from resource',
96 })
97 })
98
99 it('readResource throws when no client can resolve the uri', async () => {
100 const alpha = await makeServerWithWeatherTool()
101 await using pool = await createMCPClients({
102 alpha: { transport: alpha.clientTransport },
103 })
104 await expect(pool.readResource('file:///missing.txt')).rejects.toThrow()
105 })
106
107 it('readResource: when a client throws, surfaces the last error as cause', async () => {
108 // alpha has no resources → its readResource throws. With no owning server,
109 // the thrown error must be attached as `cause` (not left undefined).
110 const alpha = await makeServerWithWeatherTool()
111 await using pool = await createMCPClients({
112 alpha: { transport: alpha.clientTransport },
113 })
114 const err: unknown = await pool
115 .readResource('file:///missing.txt')
116 .catch((e: unknown) => e)
117 if (!(err instanceof Error)) throw new Error('expected an Error')
118 expect(err.cause).toBeInstanceOf(Error)
119 })
120
121 it('readResource: when all clients resolve but none owns the uri, throws without a cause', async () => {
122 // `mismatch` resolves the read WITHOUT throwing but stamps a different uri,
123 // so no client owns `file:///hello.txt`. No error was thrown, so there is
124 // no `cause` to attach — the message must explain the uri is unowned.
125 const mismatch = await makeServerWithMismatchedResource()
126 await using pool = await createMCPClients({
127 mismatch: { transport: mismatch.clientTransport },
128 })
129 const err: unknown = await pool
130 .readResource('file:///hello.txt')
131 .catch((e: unknown) => e)
132 if (!(err instanceof Error)) throw new Error('expected an Error')
133 expect(err.message).toMatch(/no configured MCP server owns/)
134 expect(err.cause).toBeUndefined()
135 })
136
137 it('getServers() returns each server descriptor keyed by config key', async () => {
138 const a = await makeServerWithWeatherTool()
139 const b = await makeServerWithWeatherTool()
140 await using pool = await createMCPClients({
141 alpha: { transport: a.clientTransport },
142 beta: { transport: b.clientTransport, prefix: 'wx' },
143 })
144 // transport is undefined here because these clients are built from
145 // in-memory Transport instances (single-use, not reconnectable); only
146 // serializable configs are retained. The keying (config key) and prefix
147 // resolution (default = config key vs explicit) are what this asserts.
148 expect(pool.getServers()).toEqual({
149 alpha: { transport: undefined, prefix: 'alpha' },
150 beta: { transport: undefined, prefix: 'wx' },
151 })
152 })
153
154 it('closes already-connected clients and throws if one server fails', async () => {
155 const a = await makeServerWithWeatherTool()
156 // Wrap alpha's transport close so we can assert cleanup actually ran.
157 const originalClose = a.clientTransport.close.bind(a.clientTransport)
158 let alphaClosed = false
159 a.clientTransport.close = async () => {
160 alphaClosed = true
161 await originalClose()
162 }
163 const broken: Transport = {
164 start: async () => {
165 throw new Error('nope')
166 },
167 send: async () => {},
168 close: async () => {},
169 }
170 await expect(
171 createMCPClients({
172 alpha: { transport: a.clientTransport },
173 beta: { transport: broken },
174 }),
175 ).rejects.toThrow(/beta/)
176 expect(alphaClosed).toBe(true)
177 })
178
179 it('lists tools from a spec 2026 server and a spec 2025 server', async () => {
180 const modern = await makeModernWeatherTransport()
181 const legacy = await makeServerWithWeatherTool()
182 await using pool = await createMCPClients({
183 modern: { transport: modern },
184 legacy: { transport: legacy.clientTransport },
185 })
186 const names = (await pool.tools()).map((tool) => tool.name).sort()
187 expect(names).toEqual(['legacy_get_weather', 'modern_get_weather'])
188 })
189
190 it('names each server tools with its own toolName', async () => {
191 const a = await makeServerWithWeatherTool()
192 const b = await makeServerWithWeatherTool()
193 const alphaName = (tool: { name: string }) => `mcp__alpha__${tool.name}`
194 await using pool = await createMCPClients({
195 alpha: { transport: a.clientTransport, toolName: alphaName },
196 beta: {
197 transport: b.clientTransport,
198 toolName: (tool) => `mcp__beta__${tool.name}`,
199 },
200 })
201 const names = (await pool.tools()).map((tool) => tool.name).sort()
202 expect(names).toEqual(['mcp__alpha__get_weather', 'mcp__beta__get_weather'])
203 expect(pool.getServers().alpha).toStrictEqual({
204 transport: undefined,
205 prefix: 'alpha',
206 toolName: alphaName,
207 })
208 })
209
210 it('throws DuplicateToolNameError when toolName gives two servers one name', async () => {
211 const a = await makeServerWithWeatherTool()
212 const b = await makeServerWithWeatherTool()
213 await using pool = await createMCPClients({
214 alpha: { transport: a.clientTransport, toolName: (tool) => tool.name },
215 beta: { transport: b.clientTransport, toolName: (tool) => tool.name },
216 })
217 await expect(pool.tools()).rejects.toThrow(DuplicateToolNameError)
218 })
219
220 it('reports each server requestOptions on getServers()', async () => {
221 const a = await makeServerWithWeatherTool()
222 await using pool = await createMCPClients({
223 alpha: {
224 transport: a.clientTransport,
225 requestOptions: { timeout: 5000 },
226 },
227 })
228 expect(pool.getServers()).toStrictEqual({
229 alpha: {
230 transport: undefined,
231 prefix: 'alpha',
232 requestOptions: { timeout: 5000 },
233 },
234 })
235 })
236})
237
238// The server has no public setter for the negotiated era, so the test sets it.
239async function makeModernWeatherTransport() {
240 const [clientTransport, serverTransport] =
241 InMemoryTransport.createLinkedPair()
242 const server = new Server(
243 { name: 'modern-weather', version: '1.0.0' },
244 {
245 capabilities: { tools: {} },
246 supportedProtocolVersions: [...SUPPORTED_PROTOCOL_VERSIONS, '2026-07-28'],
247 },
248 )
249 Object.assign(server, { _negotiatedProtocolVersion: '2026-07-28' })
250 server.setRequestHandler('tools/list', () => ({
251 tools: [
252 {
253 name: 'get_weather',
254 description: 'Get weather for a city',
255 inputSchema: {
256 type: 'object',
257 properties: { city: { type: 'string' } },
258 },
259 },
260 ],
261 }))
262 server.setRequestHandler('tools/call', () => ({
263 content: [{ type: 'text' as const, text: 'Sunny' }],
264 }))
265 await server.connect(serverTransport)
266 return clientTransport
267}