-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathgateway-client.ts
More file actions
629 lines (551 loc) · 19.2 KB
/
Copy pathgateway-client.ts
File metadata and controls
629 lines (551 loc) · 19.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
/**
* GatewayClient — Aggregates tools, resources, and prompts from multiple
* MCP clients into a single unified Client.
*
* Key features:
* - Lazy client resolution (factory functions called on first use, cached)
* - Auto-pagination (fetches all pages from upstream clients)
* - Tool/prompt namespacing via slugified client keys (e.g. "my-server_toolName")
* - Per-client selection filtering (optional allowlist)
* - Metadata tagging (_meta.gatewayClientId on every item)
*/
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import type { RequestOptions } from "@modelcontextprotocol/sdk/shared/protocol.js";
import type {
CallToolRequest,
CallToolResult,
ClientCapabilities,
CompatibilityCallToolResult,
GetPromptRequest,
GetPromptResult,
Implementation,
ListPromptsResult,
ListResourcesResult,
ListResourceTemplatesResult,
ListToolsResult,
Prompt,
ReadResourceRequest,
ReadResourceResult,
Resource,
ResourceTemplate,
ServerCapabilities,
Tool,
} from "@modelcontextprotocol/sdk/types.js";
import type { IClient } from "../client-like.ts";
/**
* A concrete IClient instance or a factory that produces one (sync or async).
* Factories are invoked lazily on first use and the result is cached.
*/
export type ClientOrFactory = IClient | (() => IClient | Promise<IClient>);
/**
* Per-client entry with optional selection filters.
* When a selection array is provided, only items whose names appear in it
* are included. An empty array blocks all items. Undefined means pass all.
*/
export interface ClientEntry {
client: ClientOrFactory;
tools?: string[];
resources?: string[];
prompts?: string[];
}
/**
* Slugify a string for use as a namespace prefix.
* Produces lowercase alphanumeric + hyphens.
*/
export function slugify(input: string): string {
return input
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-|-$/g, "");
}
/**
* Maximum length for the slug portion of a namespaced tool/prompt name.
*
* MCP clients such as Claude Code prepend their own prefix to tool names
* (e.g. `mcp__<server>__`) and AI providers enforce a 128-character limit.
* Capping the slug at 32 characters keeps the full namespaced name short
* enough to stay within 128 even after client-side prefixing.
*/
const MAX_SLUG_LENGTH = 32;
/**
* Truncate a slug to {@link MAX_SLUG_LENGTH}, removing any trailing hyphen.
*/
export function capSlug(slug: string): string {
if (slug.length <= MAX_SLUG_LENGTH) return slug;
return slug.slice(0, MAX_SLUG_LENGTH).replace(/-$/, "");
}
/**
* Extract `gatewayClientId` from an item's `_meta` object.
* Returns `undefined` when the field is absent or not a string.
*/
export function getGatewayClientId(meta: unknown): string | undefined {
if (
meta &&
typeof meta === "object" &&
"gatewayClientId" in meta &&
typeof (meta as Record<string, unknown>).gatewayClientId === "string"
) {
return (meta as Record<string, unknown>).gatewayClientId as string;
}
return undefined;
}
/**
* Strip the gateway namespace prefix from a tool/prompt name.
* Requires `clientId` to compute the exact prefix to remove.
* Returns the input unchanged when no `clientId` is provided or the prefix doesn't match.
*/
export function stripToolNamespace(
namespacedName: string,
clientId?: string,
): string {
if (!clientId) return namespacedName;
const prefix = `${capSlug(slugify(clientId))}_`;
return namespacedName.startsWith(prefix)
? namespacedName.slice(prefix.length)
: namespacedName;
}
/**
* Strip namespace and normalize for display: removes the slug prefix,
* replaces `_` and `-` with spaces, and lowercases the result.
* Pair with CSS `capitalize` for Title Case rendering.
*/
export function displayToolName(
namespacedName: string,
clientId?: string,
): string {
return stripToolNamespace(namespacedName, clientId)
.replace(/[_-]/g, " ")
.toLowerCase();
}
export interface GatewayClientOptions {
clientInfo?: Implementation;
capabilities?: ClientCapabilities;
}
export class GatewayClient extends Client {
private readonly clients: Record<string, ClientEntry>;
private readonly slugToKey = new Map<string, string>();
private readonly keyToSlug = new Map<string, string>();
/** Cache of resolved client promises keyed by client key. */
private readonly resolvedClients = new Map<string, Promise<IClient>>();
/** Cached list results — set to null to invalidate. */
private toolsCache: Promise<ListToolsResult> | null = null;
private resourcesCache: Promise<ListResourcesResult> | null = null;
private resourceTemplatesCache: Promise<ListResourceTemplatesResult> | null =
null;
private promptsCache: Promise<ListPromptsResult> | null = null;
/** Route map for resources (URIs aren't namespaced). */
private resourceRouteMap = new Map<string, string>();
constructor(
clients: Record<string, ClientEntry>,
options?: GatewayClientOptions,
) {
super(options?.clientInfo ?? { name: "gateway-client", version: "1.0.0" }, {
capabilities: options?.capabilities,
});
this.clients = clients;
for (const key of Object.keys(clients)) {
const slug = capSlug(slugify(key));
if (this.slugToKey.has(slug)) {
throw new Error(
`GatewayClient: duplicate slug "${slug}" from keys "${this.slugToKey.get(slug)}" and "${key}"`,
);
}
this.slugToKey.set(slug, key);
this.keyToSlug.set(key, slug);
}
}
// ---------------------------------------------------------------------------
// Namespacing
// ---------------------------------------------------------------------------
private namespace(clientKey: string, name: string): string {
const slug = this.keyToSlug.get(clientKey) ?? capSlug(slugify(clientKey));
return `${slug}_${name}`;
}
/**
* Resolve a tool name to [clientKey, originalName].
* Fast path: parse namespace prefix. Fallback: search aggregated tools
* for an un-namespaced match (supports callers that don't know about
* namespacing, e.g. workflow tool steps).
*/
private async resolveToolTarget(
name: string,
): Promise<[clientKey: string, originalName: string]> {
// Fast path: namespace prefix matches a known client
const sep = name.indexOf("_");
if (sep !== -1) {
const slug = name.slice(0, sep);
const clientKey = this.slugToKey.get(slug);
if (clientKey) {
return [clientKey, name.slice(sep + 1)];
}
}
// Fallback: search aggregated tools by original (un-namespaced) name
const { tools } = await this.listTools();
for (const tool of tools) {
const clientId = getGatewayClientId(tool._meta);
if (!clientId) continue;
if (stripToolNamespace(tool.name, clientId) === name) {
return [clientId, name];
}
}
// Nothing matched — throw the original-style error
if (sep === -1) {
throw new Error(
`GatewayClient: could not resolve tool "${name}" — no namespace prefix and not found in any client`,
);
}
throw new Error(
`GatewayClient: unknown namespace "${name.slice(0, sep)}" in "${name}" and not found by original name in any client`,
);
}
/**
* Resolve a prompt name to [clientKey, originalName].
* Same logic as resolveToolTarget but searches prompts.
*/
private async resolvePromptTarget(
name: string,
): Promise<[clientKey: string, originalName: string]> {
// Fast path: namespace prefix matches a known client
const sep = name.indexOf("_");
if (sep !== -1) {
const slug = name.slice(0, sep);
const clientKey = this.slugToKey.get(slug);
if (clientKey) {
return [clientKey, name.slice(sep + 1)];
}
}
// Fallback: search aggregated prompts by original (un-namespaced) name
const { prompts } = await this.listPrompts();
for (const prompt of prompts) {
const clientId = getGatewayClientId(prompt._meta);
if (!clientId) continue;
if (stripToolNamespace(prompt.name, clientId) === name) {
return [clientId, name];
}
}
if (sep === -1) {
throw new Error(
`GatewayClient: could not resolve prompt "${name}" — no namespace prefix and not found in any client`,
);
}
throw new Error(
`GatewayClient: unknown namespace "${name.slice(0, sep)}" in "${name}" and not found by original name in any client`,
);
}
// ---------------------------------------------------------------------------
// Client resolution
// ---------------------------------------------------------------------------
/**
* Resolve a ClientOrFactory to a concrete IClient. The resolved Promise is
* cached so concurrent calls for the same key share a single resolution.
* If the factory throws, the cached promise is removed so subsequent calls
* retry the factory.
*/
private resolveClient(key: string): Promise<IClient> {
const existing = this.resolvedClients.get(key);
if (existing) {
return existing;
}
const entry = this.clients[key];
if (!entry) {
return Promise.reject(
new Error(`GatewayClient: unknown client key "${key}"`),
);
}
const clientOrFactory = entry.client;
const promise =
typeof clientOrFactory === "function"
? Promise.resolve(clientOrFactory())
: Promise.resolve(clientOrFactory);
// Remove from cache on failure so subsequent calls retry
const guarded = promise.catch((err) => {
this.resolvedClients.delete(key);
throw err;
});
this.resolvedClients.set(key, guarded);
return guarded;
}
/**
* Public access to a resolved client by key.
*/
getResolvedClient(key: string): Promise<IClient> {
return this.resolveClient(key);
}
// ---------------------------------------------------------------------------
// Auto-pagination helpers
// ---------------------------------------------------------------------------
private async fetchAllTools(client: IClient): Promise<Tool[]> {
const tools: Tool[] = [];
let cursor: string | undefined;
do {
const result = await client.listTools(cursor ? { cursor } : undefined);
tools.push(...result.tools);
cursor = result.nextCursor;
} while (cursor);
return tools;
}
private async fetchAllResources(client: IClient): Promise<Resource[]> {
const resources: Resource[] = [];
let cursor: string | undefined;
do {
const result = await client.listResources(
cursor ? { cursor } : undefined,
);
resources.push(...result.resources);
cursor = result.nextCursor;
} while (cursor);
return resources;
}
private async fetchAllResourceTemplates(
client: IClient,
): Promise<ResourceTemplate[]> {
const templates: ResourceTemplate[] = [];
let cursor: string | undefined;
do {
const result = await client.listResourceTemplates(
cursor ? { cursor } : undefined,
);
templates.push(...result.resourceTemplates);
cursor = result.nextCursor;
} while (cursor);
return templates;
}
private async fetchAllPrompts(client: IClient): Promise<Prompt[]> {
const prompts: Prompt[] = [];
let cursor: string | undefined;
do {
const result = await client.listPrompts(cursor ? { cursor } : undefined);
prompts.push(...result.prompts);
cursor = result.nextCursor;
} while (cursor);
return prompts;
}
// ---------------------------------------------------------------------------
// List methods (cached, namespaced, filtered)
// ---------------------------------------------------------------------------
override listTools(
_params?: unknown,
_options?: RequestOptions,
): Promise<ListToolsResult> {
if (!this.toolsCache) {
this.toolsCache = this.aggregateTools();
}
return this.toolsCache;
}
private async aggregateTools(): Promise<ListToolsResult> {
const tools: Tool[] = [];
for (const [clientKey, entry] of Object.entries(this.clients)) {
const client = await this.resolveClient(clientKey);
const clientTools = await this.fetchAllTools(client);
const selected = entry.tools;
const selectedSet = selected ? new Set(selected) : null;
for (const tool of clientTools) {
if (selectedSet && !selectedSet.has(tool.name)) continue;
tools.push({
...tool,
name: this.namespace(clientKey, tool.name),
_meta: {
...(tool._meta ?? {}),
gatewayClientId: clientKey,
},
});
}
}
return { tools };
}
override listResources(
_params?: unknown,
_options?: RequestOptions,
): Promise<ListResourcesResult> {
if (!this.resourcesCache) {
this.resourcesCache = this.aggregateResources();
}
return this.resourcesCache;
}
private async aggregateResources(): Promise<ListResourcesResult> {
const seen = new Set<string>();
const resources: Resource[] = [];
const routeMap = new Map<string, string>();
for (const [clientKey, entry] of Object.entries(this.clients)) {
const client = await this.resolveClient(clientKey);
const clientResources = await this.fetchAllResources(client);
const selected = entry.resources;
const selectedSet = selected ? new Set(selected) : null;
for (const resource of clientResources) {
if (
selectedSet &&
!selectedSet.has(resource.uri) &&
!(resource.name && selectedSet.has(resource.name))
)
continue;
if (seen.has(resource.uri)) {
console.warn(
`GatewayClient: duplicate resource "${resource.uri}" from client "${clientKey}" — skipping`,
);
continue;
}
seen.add(resource.uri);
routeMap.set(resource.uri, clientKey);
resources.push({
...resource,
_meta: {
...(resource._meta ?? {}),
gatewayClientId: clientKey,
},
});
}
}
this.resourceRouteMap = routeMap;
return { resources };
}
override listResourceTemplates(
_params?: unknown,
_options?: RequestOptions,
): Promise<ListResourceTemplatesResult> {
if (!this.resourceTemplatesCache) {
this.resourceTemplatesCache = this.aggregateResourceTemplates();
}
return this.resourceTemplatesCache;
}
private async aggregateResourceTemplates(): Promise<ListResourceTemplatesResult> {
const seen = new Set<string>();
const resourceTemplates: ResourceTemplate[] = [];
for (const [clientKey, _entry] of Object.entries(this.clients)) {
const client = await this.resolveClient(clientKey);
const clientTemplates = await this.fetchAllResourceTemplates(client);
for (const template of clientTemplates) {
if (seen.has(template.uriTemplate)) {
console.warn(
`GatewayClient: duplicate resource template "${template.uriTemplate}" from client "${clientKey}" — skipping`,
);
continue;
}
seen.add(template.uriTemplate);
resourceTemplates.push({
...template,
_meta: {
...(template._meta ?? {}),
gatewayClientId: clientKey,
},
});
}
}
return { resourceTemplates };
}
override listPrompts(
_params?: unknown,
_options?: RequestOptions,
): Promise<ListPromptsResult> {
if (!this.promptsCache) {
this.promptsCache = this.aggregatePrompts();
}
return this.promptsCache;
}
private async aggregatePrompts(): Promise<ListPromptsResult> {
const prompts: Prompt[] = [];
for (const [clientKey, entry] of Object.entries(this.clients)) {
const client = await this.resolveClient(clientKey);
const clientPrompts = await this.fetchAllPrompts(client);
const selected = entry.prompts;
const selectedSet = selected ? new Set(selected) : null;
for (const prompt of clientPrompts) {
if (selectedSet && !selectedSet.has(prompt.name)) continue;
prompts.push({
...prompt,
name: this.namespace(clientKey, prompt.name),
_meta: {
...(prompt._meta ?? {}),
gatewayClientId: clientKey,
},
});
}
}
return { prompts };
}
// ---------------------------------------------------------------------------
// Routing: callTool / readResource / getPrompt
// ---------------------------------------------------------------------------
override async callTool(
params: CallToolRequest["params"],
resultSchema?: unknown,
options?: RequestOptions,
): Promise<CallToolResult | CompatibilityCallToolResult> {
const [clientKey, originalName] = await this.resolveToolTarget(params.name);
const client = await this.resolveClient(clientKey);
return client.callTool(
{ ...params, name: originalName },
resultSchema,
options,
);
}
override async readResource(
params: ReadResourceRequest["params"],
_options?: RequestOptions,
): Promise<ReadResourceResult> {
const clientKey = await this.resolveResourceRoute(params.uri);
const client = await this.resolveClient(clientKey);
return client.readResource(params);
}
override async getPrompt(
params: GetPromptRequest["params"],
_options?: RequestOptions,
): Promise<GetPromptResult> {
const [clientKey, originalName] = await this.resolvePromptTarget(
params.name,
);
const client = await this.resolveClient(clientKey);
return client.getPrompt({ ...params, name: originalName });
}
/**
* Look up a resource URI in the route map. If not found, refresh and retry.
*/
private async resolveResourceRoute(uri: string): Promise<string> {
let clientKey = this.resourceRouteMap.get(uri);
if (clientKey) return clientKey;
// Cache might be stale — refresh and retry
this.resourcesCache = null;
await this.listResources();
clientKey = this.resourceRouteMap.get(uri);
if (clientKey) return clientKey;
throw new Error(
`GatewayClient: resource "${uri}" not found in any upstream client`,
);
}
// ---------------------------------------------------------------------------
// Capabilities & instructions
// ---------------------------------------------------------------------------
override getServerCapabilities(): ServerCapabilities {
return { tools: {}, resources: {}, prompts: {} };
}
override getInstructions(): string | undefined {
return undefined;
}
// ---------------------------------------------------------------------------
// Lifecycle
// ---------------------------------------------------------------------------
/**
* Invalidate all cached list results. The next call to any list method
* will re-fetch from all upstream clients.
*/
refresh(): void {
this.toolsCache = null;
this.resourcesCache = null;
this.resourceTemplatesCache = null;
this.promptsCache = null;
}
/**
* Close all resolved (materialized) clients. Uses Promise.allSettled so
* a failure in one client does not prevent closing others.
*/
override async close(): Promise<void> {
const closePromises = [...this.resolvedClients.values()].map((p) =>
p
.then((client) => client.close())
.catch(() => {
// Intentionally ignored — partial close failures are acceptable
}),
);
await Promise.allSettled(closePromises);
await super.close();
}
}