@mcp-ts/sdk 1.4.0 → 1.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -27
- package/dist/adapters/agui-adapter.d.mts +16 -0
- package/dist/adapters/agui-adapter.d.ts +16 -0
- package/dist/adapters/agui-adapter.js +185 -0
- package/dist/adapters/agui-adapter.js.map +1 -1
- package/dist/adapters/agui-adapter.mjs +185 -0
- package/dist/adapters/agui-adapter.mjs.map +1 -1
- package/dist/adapters/agui-middleware.d.mts +2 -0
- package/dist/adapters/agui-middleware.d.ts +2 -0
- package/dist/adapters/agui-middleware.js.map +1 -1
- package/dist/adapters/agui-middleware.mjs.map +1 -1
- package/dist/adapters/ai-adapter.d.mts +21 -0
- package/dist/adapters/ai-adapter.d.ts +21 -0
- package/dist/adapters/ai-adapter.js +175 -0
- package/dist/adapters/ai-adapter.js.map +1 -1
- package/dist/adapters/ai-adapter.mjs +175 -0
- package/dist/adapters/ai-adapter.mjs.map +1 -1
- package/dist/adapters/langchain-adapter.d.mts +16 -0
- package/dist/adapters/langchain-adapter.d.ts +16 -0
- package/dist/adapters/langchain-adapter.js +179 -0
- package/dist/adapters/langchain-adapter.js.map +1 -1
- package/dist/adapters/langchain-adapter.mjs +179 -0
- package/dist/adapters/langchain-adapter.mjs.map +1 -1
- package/dist/client/index.d.mts +2 -2
- package/dist/client/index.d.ts +2 -2
- package/dist/client/react.d.mts +94 -8
- package/dist/client/react.d.ts +94 -8
- package/dist/client/react.js +364 -26
- package/dist/client/react.js.map +1 -1
- package/dist/client/react.mjs +358 -27
- package/dist/client/react.mjs.map +1 -1
- package/dist/client/vue.d.mts +4 -4
- package/dist/client/vue.d.ts +4 -4
- package/dist/client/vue.js +11 -2
- package/dist/client/vue.js.map +1 -1
- package/dist/client/vue.mjs +11 -2
- package/dist/client/vue.mjs.map +1 -1
- package/dist/{index-CQr9q0bF.d.mts → index-DcYfpY3H.d.mts} +1 -1
- package/dist/{index-nE_7Io0I.d.ts → index-GfC_eNEv.d.ts} +1 -1
- package/dist/index.d.mts +4 -3
- package/dist/index.d.ts +4 -3
- package/dist/index.js +938 -12
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +923 -13
- package/dist/index.mjs.map +1 -1
- package/dist/server/index.d.mts +2 -2
- package/dist/server/index.d.ts +2 -2
- package/dist/server/index.js +58 -12
- package/dist/server/index.js.map +1 -1
- package/dist/server/index.mjs +58 -12
- package/dist/server/index.mjs.map +1 -1
- package/dist/shared/index.d.mts +86 -4
- package/dist/shared/index.d.ts +86 -4
- package/dist/shared/index.js +874 -0
- package/dist/shared/index.js.map +1 -1
- package/dist/shared/index.mjs +865 -1
- package/dist/shared/index.mjs.map +1 -1
- package/dist/tool-router-Bo8qZbsD.d.ts +325 -0
- package/dist/tool-router-XnWVxPzv.d.mts +325 -0
- package/dist/{types-CW6lghof.d.mts → types-CfCoIsWI.d.mts} +27 -1
- package/dist/{types-CW6lghof.d.ts → types-CfCoIsWI.d.ts} +27 -1
- package/package.json +3 -2
- package/src/adapters/agui-adapter.ts +79 -0
- package/src/adapters/ai-adapter.ts +75 -0
- package/src/adapters/langchain-adapter.ts +74 -0
- package/src/client/react/index.ts +16 -0
- package/src/client/react/oauth-popup.tsx +446 -0
- package/src/client/react/use-mcp-apps.tsx +50 -32
- package/src/client/react/use-mcp.ts +36 -3
- package/src/client/vue/use-mcp.ts +38 -3
- package/src/server/handlers/sse-handler.ts +39 -0
- package/src/server/index.ts +2 -0
- package/src/server/mcp/oauth-client.ts +35 -15
- package/src/shared/index.ts +36 -0
- package/src/shared/meta-tools.ts +387 -0
- package/src/shared/schema-compressor.ts +124 -0
- package/src/shared/tool-index.ts +499 -0
- package/src/shared/tool-router.ts +469 -0
- package/src/shared/types.ts +30 -0
- package/supabase/migrations/20260421010000_add_session_cleanup_cron.sql +32 -0
package/dist/shared/index.mjs
CHANGED
|
@@ -210,6 +210,870 @@ function findToolByName(connections, toolName) {
|
|
|
210
210
|
return void 0;
|
|
211
211
|
}
|
|
212
212
|
|
|
213
|
-
|
|
213
|
+
// src/shared/tool-index.ts
|
|
214
|
+
var CALIBRATION_DIVISOR = 3.6;
|
|
215
|
+
function classifyChar(ch) {
|
|
216
|
+
const code = ch.charCodeAt(0);
|
|
217
|
+
if (code <= 32 || ch === "{" || ch === "}" || ch === "[" || ch === "]" || ch === ":" || ch === ",") return 1;
|
|
218
|
+
if (code >= 33 && code <= 47) return 1.5;
|
|
219
|
+
if (code >= 48 && code <= 57) return 2;
|
|
220
|
+
if (code >= 65 && code <= 90) return 3.5;
|
|
221
|
+
if (code >= 97 && code <= 122) return 4;
|
|
222
|
+
return 2.5;
|
|
223
|
+
}
|
|
224
|
+
var ToolIndex = class _ToolIndex {
|
|
225
|
+
constructor(options = {}) {
|
|
226
|
+
/** All indexed tools keyed by name (supports duplicates). */
|
|
227
|
+
__publicField(this, "tools", /* @__PURE__ */ new Map());
|
|
228
|
+
/** Precomputed lightweight summaries keyed by document. */
|
|
229
|
+
__publicField(this, "toolSummaries", /* @__PURE__ */ new Map());
|
|
230
|
+
/** Pre-computed search text for keyword matching (lowercase), keyed by document. */
|
|
231
|
+
__publicField(this, "searchTexts", /* @__PURE__ */ new Map());
|
|
232
|
+
/** Pre-computed IDF values per token (computed once on build). */
|
|
233
|
+
__publicField(this, "idf", /* @__PURE__ */ new Map());
|
|
234
|
+
/** Per-tool TF vectors (Map<token, tf>). */
|
|
235
|
+
__publicField(this, "tfVectors", /* @__PURE__ */ new Map());
|
|
236
|
+
/** Optional: pre-computed embedding vectors per tool. */
|
|
237
|
+
__publicField(this, "embeddings", /* @__PURE__ */ new Map());
|
|
238
|
+
/** BM25: document lengths in tokens for each tool. */
|
|
239
|
+
__publicField(this, "docLengths", /* @__PURE__ */ new Map());
|
|
240
|
+
/** BM25: average document length across the entire index. */
|
|
241
|
+
__publicField(this, "avgDocLength", 0);
|
|
242
|
+
/** Cached total estimated token cost across all indexed tools. */
|
|
243
|
+
__publicField(this, "totalTokenCost", 0);
|
|
244
|
+
__publicField(this, "options");
|
|
245
|
+
this.options = {
|
|
246
|
+
embedFn: options.embedFn ?? void 0,
|
|
247
|
+
keywordWeight: options.keywordWeight ?? 0.4
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
// -----------------------------------------------------------------------
|
|
251
|
+
// Indexing
|
|
252
|
+
// -----------------------------------------------------------------------
|
|
253
|
+
/**
|
|
254
|
+
* Build (or rebuild) the index from the given tool set.
|
|
255
|
+
* Call this after connecting / reconnecting to MCP servers.
|
|
256
|
+
*/
|
|
257
|
+
async buildIndex(tools) {
|
|
258
|
+
this.tools.clear();
|
|
259
|
+
this.toolSummaries.clear();
|
|
260
|
+
this.searchTexts.clear();
|
|
261
|
+
this.idf.clear();
|
|
262
|
+
this.tfVectors.clear();
|
|
263
|
+
this.embeddings.clear();
|
|
264
|
+
this.docLengths.clear();
|
|
265
|
+
this.avgDocLength = 0;
|
|
266
|
+
this.totalTokenCost = 0;
|
|
267
|
+
const allTokenSets = /* @__PURE__ */ new Map();
|
|
268
|
+
let totalLength = 0;
|
|
269
|
+
for (const tool of tools) {
|
|
270
|
+
const docKey = this.getDocumentKey(tool);
|
|
271
|
+
if (!this.tools.has(tool.name)) {
|
|
272
|
+
this.tools.set(tool.name, []);
|
|
273
|
+
}
|
|
274
|
+
this.tools.get(tool.name).push(tool);
|
|
275
|
+
const estimatedTokens = _ToolIndex.estimateTokens(tool);
|
|
276
|
+
this.toolSummaries.set(docKey, {
|
|
277
|
+
name: tool.name,
|
|
278
|
+
description: tool.description ?? "",
|
|
279
|
+
serverName: tool.serverName,
|
|
280
|
+
sessionId: tool.sessionId,
|
|
281
|
+
estimatedTokens
|
|
282
|
+
});
|
|
283
|
+
this.totalTokenCost += estimatedTokens;
|
|
284
|
+
const text = this.buildSearchableText(tool).toLowerCase();
|
|
285
|
+
this.searchTexts.set(docKey, text);
|
|
286
|
+
const tokens = this.tokenize(text);
|
|
287
|
+
const tf = /* @__PURE__ */ new Map();
|
|
288
|
+
const uniqueTokens = /* @__PURE__ */ new Set();
|
|
289
|
+
for (const tok of tokens) {
|
|
290
|
+
tf.set(tok, (tf.get(tok) ?? 0) + 1);
|
|
291
|
+
uniqueTokens.add(tok);
|
|
292
|
+
}
|
|
293
|
+
const maxTf = Math.max(...tf.values(), 1);
|
|
294
|
+
for (const [k, v] of tf) {
|
|
295
|
+
tf.set(k, v / maxTf);
|
|
296
|
+
}
|
|
297
|
+
this.tfVectors.set(docKey, tf);
|
|
298
|
+
allTokenSets.set(docKey, uniqueTokens);
|
|
299
|
+
const length = tokens.length;
|
|
300
|
+
this.docLengths.set(docKey, length);
|
|
301
|
+
totalLength += length;
|
|
302
|
+
}
|
|
303
|
+
this.avgDocLength = totalLength / (tools.length || 1);
|
|
304
|
+
const totalDocs = tools.length || 1;
|
|
305
|
+
const dfCounts = /* @__PURE__ */ new Map();
|
|
306
|
+
for (const tokenSet of allTokenSets.values()) {
|
|
307
|
+
for (const tok of tokenSet) {
|
|
308
|
+
dfCounts.set(tok, (dfCounts.get(tok) ?? 0) + 1);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
for (const [tok, df] of dfCounts) {
|
|
312
|
+
this.idf.set(tok, Math.log(totalDocs / df) + 1);
|
|
313
|
+
}
|
|
314
|
+
if (this.options.embedFn) {
|
|
315
|
+
const names = [...this.searchTexts.keys()];
|
|
316
|
+
const texts = names.map((n) => this.searchTexts.get(n));
|
|
317
|
+
try {
|
|
318
|
+
const vectors = await this.options.embedFn(texts);
|
|
319
|
+
for (let i = 0; i < names.length; i++) {
|
|
320
|
+
if (vectors[i]) {
|
|
321
|
+
this.embeddings.set(names[i], vectors[i]);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
} catch (err) {
|
|
325
|
+
console.warn("[ToolIndex] Embedding generation failed, falling back to keyword-only search:", err);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
// -----------------------------------------------------------------------
|
|
330
|
+
// Search
|
|
331
|
+
// -----------------------------------------------------------------------
|
|
332
|
+
/**
|
|
333
|
+
* Search the index and return the top-K most relevant tools.
|
|
334
|
+
*
|
|
335
|
+
* When an `embedFn` is configured the final score is a weighted blend of
|
|
336
|
+
* keyword TF-IDF similarity and embedding cosine-similarity:
|
|
337
|
+
*
|
|
338
|
+
* `score = keywordWeight × keyword_score + (1 - keywordWeight) × cosine_score`
|
|
339
|
+
*/
|
|
340
|
+
async search(query, topK = 5) {
|
|
341
|
+
if (this.tools.size === 0) return [];
|
|
342
|
+
const queryLower = query.toLowerCase();
|
|
343
|
+
const queryTokens = this.tokenize(queryLower);
|
|
344
|
+
const keywordScores = /* @__PURE__ */ new Map();
|
|
345
|
+
const k1 = 1.2;
|
|
346
|
+
const b = 0.75;
|
|
347
|
+
for (const [docKey, docTf] of this.tfVectors) {
|
|
348
|
+
let score = 0;
|
|
349
|
+
const docLen = this.docLengths.get(docKey) ?? 0;
|
|
350
|
+
for (const tok of queryTokens) {
|
|
351
|
+
const tfVal = docTf.get(tok) ?? 0;
|
|
352
|
+
if (tfVal === 0) continue;
|
|
353
|
+
const idf = this.idf.get(tok) ?? 0;
|
|
354
|
+
const numerator = tfVal * (k1 + 1);
|
|
355
|
+
const denominator = tfVal + k1 * (1 - b + b * (docLen / this.avgDocLength));
|
|
356
|
+
score += idf * (numerator / denominator);
|
|
357
|
+
}
|
|
358
|
+
keywordScores.set(docKey, score);
|
|
359
|
+
}
|
|
360
|
+
let embeddingScores = null;
|
|
361
|
+
if (this.options.embedFn && this.embeddings.size > 0) {
|
|
362
|
+
try {
|
|
363
|
+
const [queryEmbedding] = await this.options.embedFn([queryLower]);
|
|
364
|
+
if (queryEmbedding) {
|
|
365
|
+
embeddingScores = /* @__PURE__ */ new Map();
|
|
366
|
+
for (const [docKey, vec] of this.embeddings) {
|
|
367
|
+
embeddingScores.set(docKey, this.cosineSimilarity(queryEmbedding, vec));
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
} catch {
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
const kw = this.options.keywordWeight;
|
|
374
|
+
const finalScores = [];
|
|
375
|
+
for (const docKey of this.toolSummaries.keys()) {
|
|
376
|
+
const kwScore = keywordScores.get(docKey) ?? 0;
|
|
377
|
+
const embScore = embeddingScores?.get(docKey) ?? 0;
|
|
378
|
+
const score = embeddingScores ? kw * kwScore + (1 - kw) * embScore : kwScore;
|
|
379
|
+
if (score > 0) {
|
|
380
|
+
finalScores.push({ docKey, score });
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
finalScores.sort((a, b2) => b2.score - a.score);
|
|
384
|
+
return finalScores.slice(0, topK).map(({ docKey }) => {
|
|
385
|
+
return this.toolSummaries.get(docKey);
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
/**
|
|
389
|
+
* Search tools using a regex pattern.
|
|
390
|
+
* Matches against name, description, and parameter metadata.
|
|
391
|
+
*/
|
|
392
|
+
searchRegex(pattern, topK = 5) {
|
|
393
|
+
if (this.tools.size === 0) return [];
|
|
394
|
+
try {
|
|
395
|
+
let flags = "";
|
|
396
|
+
let cleanPattern = pattern;
|
|
397
|
+
if (pattern.includes("(?i)")) {
|
|
398
|
+
flags = "i";
|
|
399
|
+
cleanPattern = pattern.replace(/\(\?i\)/g, "");
|
|
400
|
+
}
|
|
401
|
+
const regex = new RegExp(cleanPattern, flags || void 0);
|
|
402
|
+
const matches = [];
|
|
403
|
+
for (const [docKey, text] of this.searchTexts) {
|
|
404
|
+
const tool = this.toolSummaries.get(docKey);
|
|
405
|
+
if (!tool) continue;
|
|
406
|
+
if (regex.test(text) || regex.test(tool.name)) {
|
|
407
|
+
let score = 1;
|
|
408
|
+
if (tool.name === cleanPattern) score = 10;
|
|
409
|
+
else if (tool.name.startsWith(cleanPattern)) score = 5;
|
|
410
|
+
else if (tool.name.toLowerCase().includes(cleanPattern.toLowerCase())) score = 2;
|
|
411
|
+
matches.push({ docKey, score });
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
matches.sort((a, b) => b.score - a.score);
|
|
415
|
+
return matches.slice(0, topK).map(({ docKey }) => {
|
|
416
|
+
return this.toolSummaries.get(docKey);
|
|
417
|
+
});
|
|
418
|
+
} catch (err) {
|
|
419
|
+
console.warn("[ToolIndex] Regex search failed:", err);
|
|
420
|
+
return [];
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
// -----------------------------------------------------------------------
|
|
424
|
+
// Accessors
|
|
425
|
+
// -----------------------------------------------------------------------
|
|
426
|
+
/**
|
|
427
|
+
* Get tool definition(s) by name.
|
|
428
|
+
* If namespace is provided, it tries to match sessionId or serverName.
|
|
429
|
+
*/
|
|
430
|
+
getTool(name, namespace) {
|
|
431
|
+
const list = this.tools.get(name) ?? [];
|
|
432
|
+
if (!namespace) return list;
|
|
433
|
+
return list.filter((t) => t.sessionId === namespace || t.serverName === namespace);
|
|
434
|
+
}
|
|
435
|
+
/** All indexed tool names. */
|
|
436
|
+
getToolNames() {
|
|
437
|
+
return [...this.tools.keys()];
|
|
438
|
+
}
|
|
439
|
+
/** Number of indexed tools (including duplicates). */
|
|
440
|
+
get size() {
|
|
441
|
+
let count = 0;
|
|
442
|
+
for (const list of this.tools.values()) {
|
|
443
|
+
count += list.length;
|
|
444
|
+
}
|
|
445
|
+
return count;
|
|
446
|
+
}
|
|
447
|
+
/** Total estimated token cost of all indexed tool schemas. */
|
|
448
|
+
getTotalTokenCost() {
|
|
449
|
+
return this.totalTokenCost;
|
|
450
|
+
}
|
|
451
|
+
// -----------------------------------------------------------------------
|
|
452
|
+
// Static Helpers
|
|
453
|
+
// -----------------------------------------------------------------------
|
|
454
|
+
/**
|
|
455
|
+
* Estimate token count of a tool's full schema (name + description + inputSchema).
|
|
456
|
+
*
|
|
457
|
+
* Uses character-class weighted counting calibrated against cl100k_base.
|
|
458
|
+
* Accuracy is typically within ±10% for JSON Schema payloads.
|
|
459
|
+
*/
|
|
460
|
+
static estimateTokens(tool) {
|
|
461
|
+
const parts = [tool.name];
|
|
462
|
+
if (tool.description) parts.push(tool.description);
|
|
463
|
+
if (tool.inputSchema) parts.push(JSON.stringify(tool.inputSchema));
|
|
464
|
+
const text = parts.join(" ");
|
|
465
|
+
let weightedLen = 0;
|
|
466
|
+
for (let i = 0; i < text.length; i++) {
|
|
467
|
+
weightedLen += 1 / classifyChar(text[i]);
|
|
468
|
+
}
|
|
469
|
+
return Math.ceil(weightedLen / (1 / CALIBRATION_DIVISOR));
|
|
470
|
+
}
|
|
471
|
+
// -----------------------------------------------------------------------
|
|
472
|
+
// Internals
|
|
473
|
+
// -----------------------------------------------------------------------
|
|
474
|
+
/** Build a single searchable string from tool metadata. */
|
|
475
|
+
buildSearchableText(tool) {
|
|
476
|
+
const parts = [tool.name];
|
|
477
|
+
if (tool.description) parts.push(tool.description);
|
|
478
|
+
if (tool.inputSchema && typeof tool.inputSchema === "object") {
|
|
479
|
+
const schema = tool.inputSchema;
|
|
480
|
+
const props = schema.properties;
|
|
481
|
+
if (props) {
|
|
482
|
+
for (const [key, val] of Object.entries(props)) {
|
|
483
|
+
parts.push(key);
|
|
484
|
+
if (val && typeof val === "object" && val.description) {
|
|
485
|
+
parts.push(val.description);
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
return parts.join(" ");
|
|
491
|
+
}
|
|
492
|
+
getDocumentKey(tool) {
|
|
493
|
+
return `${tool.sessionId}::${tool.serverName}::${tool.name}`;
|
|
494
|
+
}
|
|
495
|
+
/** Simple whitespace + camelCase + snake_case tokenizer. */
|
|
496
|
+
tokenize(text) {
|
|
497
|
+
return text.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/[_-]/g, " ").replace(/[^a-z0-9\s]/g, "").split(/\s+/).filter((t) => t.length > 1);
|
|
498
|
+
}
|
|
499
|
+
/** Cosine similarity between two vectors. */
|
|
500
|
+
cosineSimilarity(a, b) {
|
|
501
|
+
const len = Math.min(a.length, b.length);
|
|
502
|
+
let dot = 0;
|
|
503
|
+
let magA = 0;
|
|
504
|
+
let magB = 0;
|
|
505
|
+
for (let i = 0; i < len; i++) {
|
|
506
|
+
dot += a[i] * b[i];
|
|
507
|
+
magA += a[i] * a[i];
|
|
508
|
+
magB += b[i] * b[i];
|
|
509
|
+
}
|
|
510
|
+
const denom = Math.sqrt(magA) * Math.sqrt(magB);
|
|
511
|
+
return denom > 0 ? dot / denom : 0;
|
|
512
|
+
}
|
|
513
|
+
};
|
|
514
|
+
|
|
515
|
+
// src/shared/schema-compressor.ts
|
|
516
|
+
var SchemaCompressor = class _SchemaCompressor {
|
|
517
|
+
/**
|
|
518
|
+
* Convert a full MCP Tool definition to a compact summary.
|
|
519
|
+
*
|
|
520
|
+
* The compact form omits `inputSchema` entirely and optionally generates
|
|
521
|
+
* a short `parameterHint` from the schema's top-level properties.
|
|
522
|
+
*/
|
|
523
|
+
static toCompact(tool) {
|
|
524
|
+
const compact = {
|
|
525
|
+
name: tool.name,
|
|
526
|
+
description: tool.description
|
|
527
|
+
};
|
|
528
|
+
if (tool.inputSchema && typeof tool.inputSchema === "object") {
|
|
529
|
+
const schema = tool.inputSchema;
|
|
530
|
+
if (schema.properties) {
|
|
531
|
+
const required = new Set(schema.required ?? []);
|
|
532
|
+
const parts = [];
|
|
533
|
+
for (const [key, val] of Object.entries(schema.properties)) {
|
|
534
|
+
const type = val?.type ?? "any";
|
|
535
|
+
const enumSuffix = val?.enum && Array.isArray(val.enum) ? `: ${val.enum.map((e) => `'${e}'`).join(" | ")}` : `: ${type}`;
|
|
536
|
+
parts.push(required.has(key) ? `${key}${enumSuffix}` : `${key}?${enumSuffix}`);
|
|
537
|
+
}
|
|
538
|
+
if (parts.length > 0) {
|
|
539
|
+
compact.parameterHint = `(${parts.join(", ")})`;
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
return compact;
|
|
544
|
+
}
|
|
545
|
+
/**
|
|
546
|
+
* Convert an array of tools to compact form, optionally limiting the count.
|
|
547
|
+
*/
|
|
548
|
+
static compactAll(tools, options) {
|
|
549
|
+
const limited = options?.maxTools ? tools.slice(0, options.maxTools) : tools;
|
|
550
|
+
return limited.map((t) => _SchemaCompressor.toCompact(t));
|
|
551
|
+
}
|
|
552
|
+
/**
|
|
553
|
+
* Estimate token savings from using compact vs full tool schemas.
|
|
554
|
+
*/
|
|
555
|
+
static estimateSavings(tools) {
|
|
556
|
+
let fullTokens = 0;
|
|
557
|
+
let compactTokens = 0;
|
|
558
|
+
for (const tool of tools) {
|
|
559
|
+
fullTokens += ToolIndex.estimateTokens(tool);
|
|
560
|
+
const compact = _SchemaCompressor.toCompact(tool);
|
|
561
|
+
const text = [compact.name, compact.description ?? "", compact.parameterHint ?? ""].join(" ");
|
|
562
|
+
compactTokens += Math.ceil(text.length / 4);
|
|
563
|
+
}
|
|
564
|
+
const saved = fullTokens - compactTokens;
|
|
565
|
+
const pct = fullTokens > 0 ? (saved / fullTokens * 100).toFixed(1) : "0.0";
|
|
566
|
+
return {
|
|
567
|
+
fullTokens,
|
|
568
|
+
compactTokens,
|
|
569
|
+
savedTokens: saved,
|
|
570
|
+
savingsPercent: `${pct}%`
|
|
571
|
+
};
|
|
572
|
+
}
|
|
573
|
+
};
|
|
574
|
+
|
|
575
|
+
// src/shared/meta-tools.ts
|
|
576
|
+
function createSearchToolDefinition() {
|
|
577
|
+
return {
|
|
578
|
+
name: "mcp_search_tool_bm25",
|
|
579
|
+
description: 'Search the catalog of available tools using BM25 natural language ranking. Returns tool names, descriptions, and server info. Use this FIRST to find relevant tools before calling them. Example queries: "database query", "send email", "github pull request".',
|
|
580
|
+
inputSchema: {
|
|
581
|
+
type: "object",
|
|
582
|
+
properties: {
|
|
583
|
+
query: {
|
|
584
|
+
type: "string",
|
|
585
|
+
description: "Natural language description of the capability you need."
|
|
586
|
+
},
|
|
587
|
+
limit: {
|
|
588
|
+
type: "number",
|
|
589
|
+
description: "Maximum number of results to return (default: 5, max: 20)."
|
|
590
|
+
}
|
|
591
|
+
},
|
|
592
|
+
required: ["query"]
|
|
593
|
+
}
|
|
594
|
+
};
|
|
595
|
+
}
|
|
596
|
+
function createRegexSearchToolDefinition() {
|
|
597
|
+
return {
|
|
598
|
+
name: "mcp_search_tool_regex",
|
|
599
|
+
description: 'Search the catalog of available tools using a Python-style regex pattern. Matches against tool names, descriptions, and parameter descriptions. Example patterns: "^github_", "weather", "(?i)slack".',
|
|
600
|
+
inputSchema: {
|
|
601
|
+
type: "object",
|
|
602
|
+
properties: {
|
|
603
|
+
query: {
|
|
604
|
+
type: "string",
|
|
605
|
+
description: 'Regex pattern to search for (e.g., "^get_.*_data", "database").'
|
|
606
|
+
},
|
|
607
|
+
limit: {
|
|
608
|
+
type: "number",
|
|
609
|
+
description: "Maximum number of results to return (default: 5, max: 20)."
|
|
610
|
+
}
|
|
611
|
+
},
|
|
612
|
+
required: ["query"]
|
|
613
|
+
}
|
|
614
|
+
};
|
|
615
|
+
}
|
|
616
|
+
function createGetSchemaToolDefinition() {
|
|
617
|
+
return {
|
|
618
|
+
name: "mcp_get_tool_schema",
|
|
619
|
+
description: "Get the full input schema (parameters) for a specific tool. Call this after mcp_search_tool_bm25 to get the parameter details needed to call a tool correctly.",
|
|
620
|
+
inputSchema: {
|
|
621
|
+
type: "object",
|
|
622
|
+
properties: {
|
|
623
|
+
toolName: {
|
|
624
|
+
type: "string",
|
|
625
|
+
description: "The exact tool name returned by mcp_search_tool_bm25."
|
|
626
|
+
},
|
|
627
|
+
serverName: {
|
|
628
|
+
type: "string",
|
|
629
|
+
description: "Optional: The server name provided in mcp_search_tool_bm25. Required if multiple tools have the same name."
|
|
630
|
+
}
|
|
631
|
+
},
|
|
632
|
+
required: ["toolName"]
|
|
633
|
+
}
|
|
634
|
+
};
|
|
635
|
+
}
|
|
636
|
+
function createExecuteToolDefinition() {
|
|
637
|
+
return {
|
|
638
|
+
name: "mcp_execute_tool",
|
|
639
|
+
description: "Execute a tool that was discovered via mcp_search_tool_bm25. You MUST call mcp_get_tool_schema first to know the correct parameters. Pass the exact tool name and its arguments.",
|
|
640
|
+
inputSchema: {
|
|
641
|
+
type: "object",
|
|
642
|
+
properties: {
|
|
643
|
+
toolName: {
|
|
644
|
+
type: "string",
|
|
645
|
+
description: "The exact tool name from mcp_search_tool_bm25 results."
|
|
646
|
+
},
|
|
647
|
+
serverName: {
|
|
648
|
+
type: "string",
|
|
649
|
+
description: "Optional: The server name provided in mcp_search_tool_bm25. Required if multiple tools have the same name."
|
|
650
|
+
},
|
|
651
|
+
args: {
|
|
652
|
+
type: "object",
|
|
653
|
+
description: "Arguments matching the tool's inputSchema. Omit or pass {} if the tool takes no parameters.",
|
|
654
|
+
additionalProperties: true
|
|
655
|
+
}
|
|
656
|
+
},
|
|
657
|
+
required: ["toolName"]
|
|
658
|
+
}
|
|
659
|
+
};
|
|
660
|
+
}
|
|
661
|
+
async function executeMetaTool(toolName, args, router, callToolFn) {
|
|
662
|
+
const resolveToolSchema = (name, namespace) => {
|
|
663
|
+
try {
|
|
664
|
+
return { tool: router.getToolSchema(name, namespace) };
|
|
665
|
+
} catch (err) {
|
|
666
|
+
const errorMessage = err instanceof Error ? err.message : String(err);
|
|
667
|
+
return {
|
|
668
|
+
error: {
|
|
669
|
+
content: [{ type: "text", text: errorMessage }],
|
|
670
|
+
isError: true
|
|
671
|
+
}
|
|
672
|
+
};
|
|
673
|
+
}
|
|
674
|
+
};
|
|
675
|
+
switch (toolName) {
|
|
676
|
+
case "mcp_search_tool_bm25": {
|
|
677
|
+
const query = String(args.query ?? "");
|
|
678
|
+
const limit = Math.min(Number(args.limit) || 5, 20);
|
|
679
|
+
const results = await router.searchTools(query, limit);
|
|
680
|
+
const text = results.length === 0 ? "No tools found matching your query. Try different keywords." : results.map(
|
|
681
|
+
(t, i) => `${i + 1}. **${t.name}** (server: ${t.serverName})
|
|
682
|
+
${t.description}
|
|
683
|
+
Estimated tokens: ${t.estimatedTokens}`
|
|
684
|
+
).join("\n");
|
|
685
|
+
return {
|
|
686
|
+
content: [{ type: "text", text }],
|
|
687
|
+
isError: false
|
|
688
|
+
};
|
|
689
|
+
}
|
|
690
|
+
case "mcp_search_tool_regex": {
|
|
691
|
+
const pattern = String(args.query ?? "");
|
|
692
|
+
const limit = Math.min(Number(args.limit) || 5, 20);
|
|
693
|
+
const results = await router.searchToolsRegex(pattern, limit);
|
|
694
|
+
const text = results.length === 0 ? "No tools matched your regex pattern. Try a broader pattern." : results.map(
|
|
695
|
+
(t, i) => `${i + 1}. **${t.name}** (server: ${t.serverName})
|
|
696
|
+
${t.description}
|
|
697
|
+
Estimated tokens: ${t.estimatedTokens}`
|
|
698
|
+
).join("\n");
|
|
699
|
+
return {
|
|
700
|
+
content: [{ type: "text", text }],
|
|
701
|
+
isError: false
|
|
702
|
+
};
|
|
703
|
+
}
|
|
704
|
+
case "mcp_get_tool_schema": {
|
|
705
|
+
const name = String(args.toolName ?? "");
|
|
706
|
+
const namespace = String(args.serverName ?? "") || void 0;
|
|
707
|
+
const { tool, error } = resolveToolSchema(name, namespace);
|
|
708
|
+
if (error) {
|
|
709
|
+
return error;
|
|
710
|
+
}
|
|
711
|
+
if (!tool) {
|
|
712
|
+
return {
|
|
713
|
+
content: [
|
|
714
|
+
{
|
|
715
|
+
type: "text",
|
|
716
|
+
text: `Tool "${name}" not found. Use mcp_search_tool_bm25 to find available tools first.`
|
|
717
|
+
}
|
|
718
|
+
],
|
|
719
|
+
isError: true
|
|
720
|
+
};
|
|
721
|
+
}
|
|
722
|
+
const schema = {
|
|
723
|
+
name: tool.name,
|
|
724
|
+
description: tool.description,
|
|
725
|
+
inputSchema: tool.inputSchema
|
|
726
|
+
};
|
|
727
|
+
return {
|
|
728
|
+
content: [{ type: "text", text: JSON.stringify(schema, null, 2) }],
|
|
729
|
+
isError: false
|
|
730
|
+
};
|
|
731
|
+
}
|
|
732
|
+
case "mcp_execute_tool": {
|
|
733
|
+
const targetToolName = String(args.toolName ?? "");
|
|
734
|
+
const namespace = String(args.serverName ?? "") || void 0;
|
|
735
|
+
const toolArgs = args.args ?? {};
|
|
736
|
+
if (!targetToolName) {
|
|
737
|
+
return {
|
|
738
|
+
content: [{ type: "text", text: 'Missing required parameter "toolName". Specify which tool to execute.' }],
|
|
739
|
+
isError: true
|
|
740
|
+
};
|
|
741
|
+
}
|
|
742
|
+
const { tool, error } = resolveToolSchema(targetToolName, namespace);
|
|
743
|
+
if (error) {
|
|
744
|
+
return error;
|
|
745
|
+
}
|
|
746
|
+
if (!tool) {
|
|
747
|
+
return {
|
|
748
|
+
content: [
|
|
749
|
+
{
|
|
750
|
+
type: "text",
|
|
751
|
+
text: `Tool "${targetToolName}" not found. Use mcp_search_tool_bm25 to discover available tools first.`
|
|
752
|
+
}
|
|
753
|
+
],
|
|
754
|
+
isError: true
|
|
755
|
+
};
|
|
756
|
+
}
|
|
757
|
+
if (!callToolFn) {
|
|
758
|
+
return {
|
|
759
|
+
content: [{ type: "text", text: "Tool execution is not available. No callToolFn was configured." }],
|
|
760
|
+
isError: true
|
|
761
|
+
};
|
|
762
|
+
}
|
|
763
|
+
try {
|
|
764
|
+
const result = await callToolFn(targetToolName, toolArgs, namespace);
|
|
765
|
+
if (result && typeof result === "object" && "content" in result) {
|
|
766
|
+
return result;
|
|
767
|
+
}
|
|
768
|
+
const text = typeof result === "string" ? result : JSON.stringify(result, null, 2);
|
|
769
|
+
return {
|
|
770
|
+
content: [{ type: "text", text }],
|
|
771
|
+
isError: false
|
|
772
|
+
};
|
|
773
|
+
} catch (err) {
|
|
774
|
+
const errorMessage = err instanceof Error ? err.message : String(err);
|
|
775
|
+
return {
|
|
776
|
+
content: [{ type: "text", text: `Tool execution failed: ${errorMessage}` }],
|
|
777
|
+
isError: true
|
|
778
|
+
};
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
default:
|
|
782
|
+
return null;
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
function isMetaTool(toolName) {
|
|
786
|
+
return toolName === "mcp_search_tool_bm25" || toolName === "mcp_search_tool_regex" || toolName === "mcp_get_tool_schema" || toolName === "mcp_execute_tool";
|
|
787
|
+
}
|
|
788
|
+
function resolveMetaToolProxy(toolName, args) {
|
|
789
|
+
if (toolName === "mcp_execute_tool") {
|
|
790
|
+
const innerName = args?.toolName;
|
|
791
|
+
const innerArgs = args?.args;
|
|
792
|
+
return {
|
|
793
|
+
toolName: typeof innerName === "string" && innerName ? innerName : toolName,
|
|
794
|
+
args: innerArgs && typeof innerArgs === "object" && !Array.isArray(innerArgs) ? innerArgs : {}
|
|
795
|
+
};
|
|
796
|
+
}
|
|
797
|
+
const match = toolName.match(/(?:tool_[^_]+_)?(.+)$/);
|
|
798
|
+
const resolvedName = match?.[1] ?? toolName;
|
|
799
|
+
return { toolName: resolvedName, args: args ?? {} };
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
// src/shared/tool-router.ts
|
|
803
|
+
var ToolRouter = class {
|
|
804
|
+
constructor(client, options = {}) {
|
|
805
|
+
this.client = client;
|
|
806
|
+
this.options = options;
|
|
807
|
+
__publicField(this, "index");
|
|
808
|
+
__publicField(this, "allTools", []);
|
|
809
|
+
__publicField(this, "groupsMap", /* @__PURE__ */ new Map());
|
|
810
|
+
__publicField(this, "strategy");
|
|
811
|
+
__publicField(this, "maxTools");
|
|
812
|
+
__publicField(this, "compactSchemas");
|
|
813
|
+
__publicField(this, "activeGroups");
|
|
814
|
+
__publicField(this, "customGroups");
|
|
815
|
+
__publicField(this, "initialized", false);
|
|
816
|
+
this.strategy = options.strategy ?? "all";
|
|
817
|
+
this.maxTools = options.maxTools ?? 40;
|
|
818
|
+
this.compactSchemas = options.compactSchemas ?? false;
|
|
819
|
+
this.activeGroups = new Set(options.activeGroups ?? []);
|
|
820
|
+
this.customGroups = options.groups;
|
|
821
|
+
this.index = new ToolIndex({
|
|
822
|
+
embedFn: options.embedFn,
|
|
823
|
+
keywordWeight: options.keywordWeight
|
|
824
|
+
});
|
|
825
|
+
}
|
|
826
|
+
// -----------------------------------------------------------------------
|
|
827
|
+
// Core Public API
|
|
828
|
+
// -----------------------------------------------------------------------
|
|
829
|
+
/**
|
|
830
|
+
* Get tools filtered by the current strategy.
|
|
831
|
+
* This is the main method adapters should call.
|
|
832
|
+
*
|
|
833
|
+
* - `all` → returns all tools (unchanged behavior)
|
|
834
|
+
* - `search` → returns only meta-tools (mcp_search_tool_bm25, mcp_get_tool_schema, mcp_execute_tool)
|
|
835
|
+
* - `groups` → returns tools from active groups only
|
|
836
|
+
*/
|
|
837
|
+
async getFilteredTools() {
|
|
838
|
+
await this.ensureInitialized();
|
|
839
|
+
switch (this.strategy) {
|
|
840
|
+
case "search":
|
|
841
|
+
return this.getMetaToolDefinitions();
|
|
842
|
+
case "groups":
|
|
843
|
+
return this.getGroupFilteredTools();
|
|
844
|
+
case "all":
|
|
845
|
+
default:
|
|
846
|
+
if (this.compactSchemas) {
|
|
847
|
+
return this.allTools.map((t) => {
|
|
848
|
+
const compact = SchemaCompressor.toCompact(t);
|
|
849
|
+
return {
|
|
850
|
+
name: compact.name,
|
|
851
|
+
description: (compact.description ?? "") + (compact.parameterHint ? ` Parameters: ${compact.parameterHint}` : ""),
|
|
852
|
+
inputSchema: { type: "object", properties: {} }
|
|
853
|
+
};
|
|
854
|
+
});
|
|
855
|
+
}
|
|
856
|
+
return [...this.allTools];
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
/**
|
|
860
|
+
* Search tools by natural-language query.
|
|
861
|
+
* Works regardless of strategy.
|
|
862
|
+
*/
|
|
863
|
+
async searchTools(query, topK) {
|
|
864
|
+
await this.ensureInitialized();
|
|
865
|
+
return this.index.search(query, topK ?? this.maxTools);
|
|
866
|
+
}
|
|
867
|
+
/**
|
|
868
|
+
* Search tools by regex pattern.
|
|
869
|
+
* Matches against name, description, and parameter metadata.
|
|
870
|
+
*/
|
|
871
|
+
async searchToolsRegex(pattern, topK) {
|
|
872
|
+
await this.ensureInitialized();
|
|
873
|
+
return this.index.searchRegex(pattern, topK ?? this.maxTools);
|
|
874
|
+
}
|
|
875
|
+
/**
|
|
876
|
+
* Get the full tool definition by name.
|
|
877
|
+
* If tool name is ambiguous, use namespace to specify the server.
|
|
878
|
+
*/
|
|
879
|
+
getToolSchema(toolName, namespace) {
|
|
880
|
+
const matches = this.index.getTool(toolName, namespace);
|
|
881
|
+
if (matches.length === 0) return void 0;
|
|
882
|
+
if (matches.length > 1) {
|
|
883
|
+
const servers = matches.map((m) => m.serverName).join(", ");
|
|
884
|
+
throw new Error(
|
|
885
|
+
`Tool "${toolName}" is provided by multiple servers: [${servers}]. Please specify the desired "serverName" as a namespace.`
|
|
886
|
+
);
|
|
887
|
+
}
|
|
888
|
+
return matches[0];
|
|
889
|
+
}
|
|
890
|
+
/**
|
|
891
|
+
* Get compact (schema-less) summaries for all tools.
|
|
892
|
+
*/
|
|
893
|
+
getCompactTools() {
|
|
894
|
+
return SchemaCompressor.compactAll(this.allTools);
|
|
895
|
+
}
|
|
896
|
+
// -----------------------------------------------------------------------
|
|
897
|
+
// Group Management
|
|
898
|
+
// -----------------------------------------------------------------------
|
|
899
|
+
/** Get all available groups with their tool lists and active status. */
|
|
900
|
+
getGroups() {
|
|
901
|
+
return new Map(this.groupsMap);
|
|
902
|
+
}
|
|
903
|
+
/** Activate specific groups. Pass empty array to activate all. */
|
|
904
|
+
setActiveGroups(groups) {
|
|
905
|
+
this.activeGroups = new Set(groups);
|
|
906
|
+
for (const [name, info] of this.groupsMap) {
|
|
907
|
+
info.active = this.activeGroups.size === 0 || this.activeGroups.has(name);
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
/** Get the names of currently active groups. */
|
|
911
|
+
getActiveGroups() {
|
|
912
|
+
return [...this.activeGroups];
|
|
913
|
+
}
|
|
914
|
+
// -----------------------------------------------------------------------
|
|
915
|
+
// Stats & Introspection
|
|
916
|
+
// -----------------------------------------------------------------------
|
|
917
|
+
/** Total token cost of all tools if loaded without filtering. */
|
|
918
|
+
getTotalTokenCost() {
|
|
919
|
+
return this.index.getTotalTokenCost();
|
|
920
|
+
}
|
|
921
|
+
/** Estimate token cost of the currently filtered tool set. */
|
|
922
|
+
async getFilteredTokenCost() {
|
|
923
|
+
const tools = await this.getFilteredTools();
|
|
924
|
+
let total = 0;
|
|
925
|
+
for (const tool of tools) {
|
|
926
|
+
total += ToolIndex.estimateTokens(tool);
|
|
927
|
+
}
|
|
928
|
+
return total;
|
|
929
|
+
}
|
|
930
|
+
/** Get compression stats showing savings from current strategy. */
|
|
931
|
+
getCompressionStats() {
|
|
932
|
+
return SchemaCompressor.estimateSavings(this.allTools);
|
|
933
|
+
}
|
|
934
|
+
/** Number of total indexed tools. */
|
|
935
|
+
get totalToolCount() {
|
|
936
|
+
return this.allTools.length;
|
|
937
|
+
}
|
|
938
|
+
/** Change strategy at runtime. */
|
|
939
|
+
setStrategy(strategy) {
|
|
940
|
+
this.strategy = strategy;
|
|
941
|
+
}
|
|
942
|
+
/**
|
|
943
|
+
* Force a re-index of tools from all connected clients.
|
|
944
|
+
* Call this after adding/removing MCP server connections.
|
|
945
|
+
*/
|
|
946
|
+
async refresh() {
|
|
947
|
+
this.initialized = false;
|
|
948
|
+
await this.ensureInitialized();
|
|
949
|
+
}
|
|
950
|
+
/**
|
|
951
|
+
* Execute a tool by routing to the correct MCP client.
|
|
952
|
+
* Used by the `mcp_execute_tool` meta-tool to proxy tool calls.
|
|
953
|
+
*/
|
|
954
|
+
async callTool(toolName, args, namespace) {
|
|
955
|
+
await this.ensureInitialized();
|
|
956
|
+
const indexedTool = this.getToolSchema(toolName, namespace);
|
|
957
|
+
if (!indexedTool) {
|
|
958
|
+
throw new Error(
|
|
959
|
+
`Tool "${toolName}" not found${namespace ? ` on server "${namespace}"` : ""}. Use mcp_search_tool_bm25 or mcp_search_tool_regex to discover available tools.`
|
|
960
|
+
);
|
|
961
|
+
}
|
|
962
|
+
const clients = this.getClients();
|
|
963
|
+
const targetClient = clients.find(
|
|
964
|
+
(c) => typeof c.getSessionId === "function" && c.getSessionId() === indexedTool.sessionId
|
|
965
|
+
) ?? clients.find((c) => c.isConnected());
|
|
966
|
+
if (!targetClient) {
|
|
967
|
+
throw new Error(`No connected client found for tool "${toolName}"`);
|
|
968
|
+
}
|
|
969
|
+
return await targetClient.callTool(toolName, args);
|
|
970
|
+
}
|
|
971
|
+
// -----------------------------------------------------------------------
|
|
972
|
+
// Internals
|
|
973
|
+
// -----------------------------------------------------------------------
|
|
974
|
+
/** Lazy initialization — fetches tools from all connected clients. */
|
|
975
|
+
async ensureInitialized() {
|
|
976
|
+
if (this.initialized) return;
|
|
977
|
+
this.allTools = await this.fetchAllTools();
|
|
978
|
+
await this.index.buildIndex(this.allTools);
|
|
979
|
+
this.buildGroups();
|
|
980
|
+
this.initialized = true;
|
|
981
|
+
}
|
|
982
|
+
/** Fetch tools from all connected MCP clients. */
|
|
983
|
+
async fetchAllTools() {
|
|
984
|
+
const clients = this.getClients();
|
|
985
|
+
const result = [];
|
|
986
|
+
for (const client of clients) {
|
|
987
|
+
if (!client.isConnected()) continue;
|
|
988
|
+
try {
|
|
989
|
+
const { tools } = await client.listTools();
|
|
990
|
+
const serverId = typeof client.getServerId === "function" ? client.getServerId() ?? "unknown" : "unknown";
|
|
991
|
+
const serverName = (typeof client.getServerName === "function" ? client.getServerName() : void 0) ?? serverId;
|
|
992
|
+
const sessionId = typeof client.getSessionId === "function" ? client.getSessionId() ?? "unknown" : "unknown";
|
|
993
|
+
for (const tool of tools) {
|
|
994
|
+
result.push({
|
|
995
|
+
...tool,
|
|
996
|
+
serverName,
|
|
997
|
+
sessionId
|
|
998
|
+
});
|
|
999
|
+
}
|
|
1000
|
+
} catch (err) {
|
|
1001
|
+
console.warn("[ToolRouter] Failed to fetch tools from client:", err);
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
return result;
|
|
1005
|
+
}
|
|
1006
|
+
/** Resolve the client input to a flat array of ToolClient instances. */
|
|
1007
|
+
getClients() {
|
|
1008
|
+
if (Array.isArray(this.client)) {
|
|
1009
|
+
return this.client;
|
|
1010
|
+
}
|
|
1011
|
+
if (typeof this.client.getClients === "function") {
|
|
1012
|
+
return this.client.getClients();
|
|
1013
|
+
}
|
|
1014
|
+
return [this.client];
|
|
1015
|
+
}
|
|
1016
|
+
/** Build group map from custom config or auto-detect from server names. */
|
|
1017
|
+
buildGroups() {
|
|
1018
|
+
this.groupsMap.clear();
|
|
1019
|
+
if (this.customGroups) {
|
|
1020
|
+
for (const [name, tools] of Object.entries(this.customGroups)) {
|
|
1021
|
+
this.groupsMap.set(name, {
|
|
1022
|
+
tools,
|
|
1023
|
+
active: this.activeGroups.size === 0 || this.activeGroups.has(name)
|
|
1024
|
+
});
|
|
1025
|
+
}
|
|
1026
|
+
} else {
|
|
1027
|
+
const serverTools = /* @__PURE__ */ new Map();
|
|
1028
|
+
for (const tool of this.allTools) {
|
|
1029
|
+
const group = tool.serverName;
|
|
1030
|
+
if (!serverTools.has(group)) {
|
|
1031
|
+
serverTools.set(group, []);
|
|
1032
|
+
}
|
|
1033
|
+
serverTools.get(group).push(tool.name);
|
|
1034
|
+
}
|
|
1035
|
+
for (const [serverName, tools] of serverTools) {
|
|
1036
|
+
this.groupsMap.set(serverName, {
|
|
1037
|
+
tools,
|
|
1038
|
+
active: this.activeGroups.size === 0 || this.activeGroups.has(serverName)
|
|
1039
|
+
});
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
}
|
|
1043
|
+
/** Return only tools belonging to currently active groups. */
|
|
1044
|
+
getGroupFilteredTools() {
|
|
1045
|
+
const activeToolNames = /* @__PURE__ */ new Set();
|
|
1046
|
+
for (const [, info] of this.groupsMap) {
|
|
1047
|
+
if (info.active) {
|
|
1048
|
+
for (const name of info.tools) {
|
|
1049
|
+
activeToolNames.add(name);
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
}
|
|
1053
|
+
const filtered = this.allTools.filter((t) => activeToolNames.has(t.name));
|
|
1054
|
+
if (this.compactSchemas) {
|
|
1055
|
+
return filtered.slice(0, this.maxTools).map((t) => {
|
|
1056
|
+
const compact = SchemaCompressor.toCompact(t);
|
|
1057
|
+
return {
|
|
1058
|
+
name: compact.name,
|
|
1059
|
+
description: (compact.description ?? "") + (compact.parameterHint ? ` Parameters: ${compact.parameterHint}` : ""),
|
|
1060
|
+
inputSchema: { type: "object", properties: {} }
|
|
1061
|
+
};
|
|
1062
|
+
});
|
|
1063
|
+
}
|
|
1064
|
+
return filtered.slice(0, this.maxTools);
|
|
1065
|
+
}
|
|
1066
|
+
/** The 4 meta-tool definitions exposed in `search` strategy. */
|
|
1067
|
+
getMetaToolDefinitions() {
|
|
1068
|
+
return [
|
|
1069
|
+
createSearchToolDefinition(),
|
|
1070
|
+
createRegexSearchToolDefinition(),
|
|
1071
|
+
createGetSchemaToolDefinition(),
|
|
1072
|
+
createExecuteToolDefinition()
|
|
1073
|
+
];
|
|
1074
|
+
}
|
|
1075
|
+
};
|
|
1076
|
+
|
|
1077
|
+
export { AuthenticationError, ConfigurationError, ConnectionError, DEFAULT_CLIENT_NAME, DEFAULT_CLIENT_URI, DEFAULT_HEARTBEAT_INTERVAL_MS, DEFAULT_LOGO_URI, DEFAULT_POLICY_URI, DisposableStore, Emitter, InvalidStateError, MCP_CLIENT_NAME, MCP_CLIENT_VERSION, McpError, NotConnectedError, REDIS_KEY_PREFIX, RpcErrorCodes, SESSION_TTL_SECONDS, SOFTWARE_ID, SOFTWARE_VERSION, STATE_EXPIRATION_MS, SchemaCompressor, SessionNotFoundError, SessionValidationError, TOKEN_EXPIRY_BUFFER_MS, ToolExecutionError, ToolIndex, ToolRouter, UnauthorizedError, createExecuteToolDefinition, createGetSchemaToolDefinition, createRegexSearchToolDefinition, createSearchToolDefinition, executeMetaTool, findToolByName, getToolUiResourceUri, isCallToolSuccess, isConnectAuthRequired, isConnectError, isConnectSuccess, isListToolsSuccess, isMetaTool, resolveMetaToolProxy, sanitizeServerLabel };
|
|
214
1078
|
//# sourceMappingURL=index.mjs.map
|
|
215
1079
|
//# sourceMappingURL=index.mjs.map
|