Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

pool.ts

224 lines8.5 KB

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 toolName?: MCPClientOptions['toolName']
56 requestOptions?: MCPClientOptions['requestOptions']
57 }
58 >
59 /** Close every client. */
60 close: () => Promise<void>
61 [Symbol.asyncDispose]: () => Promise<void>
63​
64export async function createMCPClients<
65 TServers extends Record<string, ServerDescriptor> = Record<
66 string,
67 ServerDescriptor
68 >,
69>(
70 // When TServers is a generated `MCPServers` map, the config keys are
71 // constrained to the declared servers (missing/typo'd key → compile error).
72 config: { [K in keyof TServers]: MCPClientOptions } & MCPClientsConfig,
73): Promise<MCPClients<TServers>> {
74 const names = Object.keys(config)
75​
76 // Connect all in parallel; on any failure, close the successes and throw once.
77 const settled = await Promise.allSettled(
78 names.map(async (name) => {
79 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
80 const opts = config[name]!
81 // default prefix = config key; `prefix: ''` disables; explicit string wins
82 const prefix = opts.prefix === undefined ? name : opts.prefix || undefined
83 const client = await createMCPClient({ ...opts, prefix })
84 return [name, client] as const
85 }),
86 )
87​
88 const ok = settled.filter(
89 (
90 r,
91 ): r is PromiseFulfilledResult<
92 readonly [string, MCPClient<ServerDescriptor>]
93 > => r.status === 'fulfilled',
94 )
95 const failed = settled
96 .map((r, i) => (r.status === 'rejected' ? names[i] : null))
97 .filter((n): n is string => n !== null)
98​
99 if (failed.length > 0) {
100 // Cleanup already-connected clients — no leaks.
101 await Promise.allSettled(ok.map((r) => r.value[1].close()))
102 // Attach the first rejection's reason as the cause so the underlying
103 // connect error isn't lost (mirrors the tools() path).
104 const firstRejection = settled.find(
105 (r): r is PromiseRejectedResult => r.status === 'rejected',
106 )
107 throw new MCPConnectionError(
108 `Failed to connect MCP server(s): ${failed.join(', ')}`,
109 firstRejection?.reason,
110 )
111 }
112​
113 // Cast via `unknown`: the runtime map is descriptor-agnostic
114 // (`MCPClient<ServerDescriptor>` values), but per-key the public type is the
115 // narrowed `MCPClient<TServers[K]>`. Those no longer structurally overlap
116 // because `tools()` is now descriptor-typed (`DescriptorTools<TServer>`), yet
117 // the generated descriptor is a compile-time overlay only — the runtime
118 // values are identical, so the through-`unknown` cast is sound here.
119 // oxlint-disable-next-line eslint-js/no-restricted-syntax -- descriptor is a compile-time overlay; runtime MCPClient values are identical regardless of TServer
120 const clients = Object.fromEntries(ok.map((r) => r.value)) as unknown as {
121 [K in keyof TServers]: MCPClient<TServers[K]>
122 }
123​
124 const pool: MCPClients<TServers> = {
125 clients,
126 async tools(options?: ToolsOptions): Promise<Array<McpServerTool>> {
127 // Settle (like the connect path) so a single failing server is reported
128 // by config key instead of rejecting with an unattributed SDK error.
129 const entries = Object.entries(clients)
130 const results = await Promise.allSettled(
131 entries.map(([, c]) =>
132 (c as MCPClient<ServerDescriptor>).tools(options),
133 ),
134 )
135 const failedNames = entries
136 .map(([key], i) => (results[i]?.status === 'rejected' ? key : null))
137 .filter((k): k is string => k !== null)
138 if (failedNames.length > 0) {
139 const firstFailure = results.find(
140 (r): r is PromiseRejectedResult => r.status === 'rejected',
141 )
142 throw new MCPConnectionError(
143 `Failed to list tools from MCP server(s): ${failedNames.join(', ')}`,
144 firstFailure?.reason,
145 )
146 }
147 const all = results.flatMap((r) =>
148 r.status === 'fulfilled' ? r.value : [],
149 )
150 const seen = new Set<string>()
151 for (const t of all) {
152 if (seen.has(t.name)) throw new DuplicateToolNameError(t.name)
153 seen.add(t.name)
154 }
155 return all
156 },
157 getServers(): Record<
158 string,
159 {
160 transport: TransportConfig | undefined
161 prefix: string | undefined
162 clientOptions?: ClientOptions
163 toolFilter?: MCPClientOptions['toolFilter']
164 needsApproval?: MCPClientOptions['needsApproval']
165 toolName?: MCPClientOptions['toolName']
166 requestOptions?: MCPClientOptions['requestOptions']
167 }
168 > {
169 // Keyed by config key (serverId / default prefix). Read each underlying
170 // client's original descriptor via getInfo().
171 return Object.fromEntries(
172 Object.entries(clients).map(([key, c]) => [key, c.getInfo()]),
173 )
174 },
175 async readResource(uri: string): Promise<ReadResourceResult> {
176 // Ownership isn't tracked, so try each client. A non-owning server may
177 // resolve an unrelated URI, so only accept a result whose `contents`
178 // actually include the requested `uri`; otherwise keep trying. A ui://
179 // read must reach the server that owns it.
180 const errors: Array<unknown> = []
181 const all = Object.values(clients)
182 for (const c of all) {
183 try {
184 const result = await (c as MCPClient<ServerDescriptor>).readResource(
185 uri,
186 )
187 if (result.contents.some((entry) => entry.uri === uri)) {
188 return result
189 }
190 } catch (err) {
191 errors.push(err)
192 }
193 }
194 // Distinguish the two failure modes and never leave `cause` undefined:
195 // - at least one client threw → attach EVERY thrown error as an
196 // AggregateError cause. Keeping all of them matters in a multi-server
197 // pool: if the owning server fails first and an unrelated server fails
198 // after, a "last error wins" cause would bury the error you actually need.
199 // - every client responded but none owned the uri → there is no thrown
200 // error to attach, so explain that the uri was not found on any server.
201 if (errors.length > 0) {
202 throw new Error(
203 `Failed to read MCP resource "${uri}": no client could resolve it (${errors.length} error(s) attached)`,
204 { cause: new AggregateError(errors) },
205 )
206 }
207 throw new Error(
208 `Failed to read MCP resource "${uri}": no configured MCP server owns this uri`,
209 )
210 },
211 async close(): Promise<void> {
212 await Promise.all(
213 Object.values(clients).map((c) =>
214 (c as MCPClient<ServerDescriptor>).close(),
215 ),
216 )
217 },
218 async [Symbol.asyncDispose](): Promise<void> {
219 await pool.close()
220 },
221 }
222​
223 return pool