Open History to see the last commit
1import { createMCPClient } from './client'
2import { DuplicateToolNameError, MCPConnectionError } from './errors'
3import type { MCPClient } from './client'
4import type {
5 MCPClientOptions,
6 McpServerTool,
7 ServerDescriptor,
8 ToolsOptions,
9} from './types'
10import type {
11 ClientOptions,
12 ReadResourceResult,
13} from '@modelcontextprotocol/client'
14import type { TransportConfig } from './transport'
15
16export type MCPClientsConfig = Record<string, MCPClientOptions>
17
18export interface MCPClients<
19 TServers extends Record<string, ServerDescriptor> = Record<
20 string,
21 ServerDescriptor
22 >,
23> {
24 /** Typed per-server access (typed defs, resources, prompts on one server). */
25 readonly clients: { [K in keyof TServers]: MCPClient<TServers[K]> }
26 /**
27 * All servers' tools, flattened and auto-prefixed by config key.
28 * `options` (including `lazy`) is forwarded to every client's `tools()`.
29 */
30 tools: (options?: ToolsOptions) => Promise<Array<McpServerTool>>
31 /**
32 * Reads an MCP resource by URI, routing to the owning client. A `ui://`
33 * resource read must hit the server that owns it; since the pool does not
34 * track ownership, each underlying client is tried in turn and the first
35 * success is returned. If every client fails, the last error is thrown.
36 *
37 * Required so a pool source emits `ui-resource` events for MCP Apps widgets
38 * (the chat manager binds `readResource` only when the source exposes it).
39 */
40 readResource: (uri: string) => Promise<ReadResourceResult>
41 /**
42 * The connection descriptors for every server in the pool, keyed by config
43 * key (the serverId / default prefix). Used by `createMcpAppCallHandler` to
44 * reconnect per-call (serverless-safe) without a separate transport-config
45 * map. Each value mirrors the owning client's `getInfo()`.
46 */
47 getServers: () => Record<
48 string,
49 {
50 transport: TransportConfig | undefined
51 prefix: string | undefined
52 clientOptions?: ClientOptions
53 toolFilter?: MCPClientOptions['toolFilter']
54 needsApproval?: MCPClientOptions['needsApproval']
55 }
56 >
57 /** Close every client. */
58 close: () => Promise<void>
59 [Symbol.asyncDispose]: () => Promise<void>
60}
61
62export async function createMCPClients<
63 TServers extends Record<string, ServerDescriptor> = Record<
64 string,
65 ServerDescriptor
66 >,
67>(
68 // When TServers is a generated `MCPServers` map, the config keys are
69 // constrained to the declared servers (missing/typo'd key → compile error).
70 config: { [K in keyof TServers]: MCPClientOptions } & MCPClientsConfig,
71): Promise<MCPClients<TServers>> {
72 const names = Object.keys(config)
73
74 // Connect all in parallel; on any failure, close the successes and throw once.
75 const settled = await Promise.allSettled(
76 names.map(async (name) => {
77 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
78 const opts = config[name]!
79 // default prefix = config key; `prefix: ''` disables; explicit string wins
80 const prefix = opts.prefix === undefined ? name : opts.prefix || undefined
81 const client = await createMCPClient({ ...opts, prefix })
82 return [name, client] as const
83 }),
84 )
85
86 const ok = settled.filter(
87 (
88 r,
89 ): r is PromiseFulfilledResult<
90 readonly [string, MCPClient<ServerDescriptor>]
91 > => r.status === 'fulfilled',
92 )
93 const failed = settled
94 .map((r, i) => (r.status === 'rejected' ? names[i] : null))
95 .filter((n): n is string => n !== null)
96
97 if (failed.length > 0) {
98 // Cleanup already-connected clients — no leaks.
99 await Promise.allSettled(ok.map((r) => r.value[1].close()))
100 // Attach the first rejection's reason as the cause so the underlying
101 // connect error isn't lost (mirrors the tools() path).
102 const firstRejection = settled.find(
103 (r): r is PromiseRejectedResult => r.status === 'rejected',
104 )
105 throw new MCPConnectionError(
106 `Failed to connect MCP server(s): ${failed.join(', ')}`,
107 firstRejection?.reason,
108 )
109 }
110
111 // Cast via `unknown`: the runtime map is descriptor-agnostic
112 // (`MCPClient<ServerDescriptor>` values), but per-key the public type is the
113 // narrowed `MCPClient<TServers[K]>`. Those no longer structurally overlap
114 // because `tools()` is now descriptor-typed (`DescriptorTools<TServer>`), yet
115 // the generated descriptor is a compile-time overlay only — the runtime
116 // values are identical, so the through-`unknown` cast is sound here.
117 // oxlint-disable-next-line eslint-js/no-restricted-syntax -- descriptor is a compile-time overlay; runtime MCPClient values are identical regardless of TServer
118 const clients = Object.fromEntries(ok.map((r) => r.value)) as unknown as {
119 [K in keyof TServers]: MCPClient<TServers[K]>
120 }
121
122 const pool: MCPClients<TServers> = {
123 clients,
124 async tools(options?: ToolsOptions): Promise<Array<McpServerTool>> {
125 // Settle (like the connect path) so a single failing server is reported
126 // by config key instead of rejecting with an unattributed SDK error.
127 const entries = Object.entries(clients)
128 const results = await Promise.allSettled(
129 entries.map(([, c]) =>
130 (c as MCPClient<ServerDescriptor>).tools(options),
131 ),
132 )
133 const failedNames = entries
134 .map(([key], i) => (results[i]?.status === 'rejected' ? key : null))
135 .filter((k): k is string => k !== null)
136 if (failedNames.length > 0) {
137 const firstFailure = results.find(
138 (r): r is PromiseRejectedResult => r.status === 'rejected',
139 )
140 throw new MCPConnectionError(
141 `Failed to list tools from MCP server(s): ${failedNames.join(', ')}`,
142 firstFailure?.reason,
143 )
144 }
145 const all = results.flatMap((r) =>
146 r.status === 'fulfilled' ? r.value : [],
147 )
148 const seen = new Set<string>()
149 for (const t of all) {
150 if (seen.has(t.name)) throw new DuplicateToolNameError(t.name)
151 seen.add(t.name)
152 }
153 return all
154 },
155 getServers(): Record<
156 string,
157 {
158 transport: TransportConfig | undefined
159 prefix: string | undefined
160 clientOptions?: ClientOptions
161 toolFilter?: MCPClientOptions['toolFilter']
162 needsApproval?: MCPClientOptions['needsApproval']
163 }
164 > {
165 // Keyed by config key (serverId / default prefix). Read each underlying
166 // client's original descriptor via getInfo().
167 return Object.fromEntries(
168 Object.entries(clients).map(([key, c]) => [key, c.getInfo()]),
169 )
170 },
171 async readResource(uri: string): Promise<ReadResourceResult> {
172 // Ownership isn't tracked, so try each client. A non-owning server may
173 // resolve an unrelated URI, so only accept a result whose `contents`
174 // actually include the requested `uri`; otherwise keep trying. A ui://
175 // read must reach the server that owns it.
176 const errors: Array<unknown> = []
177 const all = Object.values(clients)
178 for (const c of all) {
179 try {
180 const result = await (c as MCPClient<ServerDescriptor>).readResource(
181 uri,
182 )
183 if (result.contents.some((entry) => entry.uri === uri)) {
184 return result
185 }
186 } catch (err) {
187 errors.push(err)
188 }
189 }
190 // Distinguish the two failure modes and never leave `cause` undefined:
191 // - at least one client threw → attach EVERY thrown error as an
192 // AggregateError cause. Keeping all of them matters in a multi-server
193 // pool: if the owning server fails first and an unrelated server fails
194 // after, a "last error wins" cause would bury the error you actually need.
195 // - every client responded but none owned the uri → there is no thrown
196 // error to attach, so explain that the uri was not found on any server.
197 if (errors.length > 0) {
198 throw new Error(
199 `Failed to read MCP resource "${uri}": no client could resolve it (${errors.length} error(s) attached)`,
200 { cause: new AggregateError(errors) },
201 )
202 }
203 throw new Error(
204 `Failed to read MCP resource "${uri}": no configured MCP server owns this uri`,
205 )
206 },
207 async close(): Promise<void> {
208 await Promise.all(
209 Object.values(clients).map((c) =>
210 (c as MCPClient<ServerDescriptor>).close(),
211 ),
212 )
213 },
214 async [Symbol.asyncDispose](): Promise<void> {
215 await pool.close()
216 },
217 }
218
219 return pool
220}