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