@mcp-ts/sdk 1.3.10 → 1.5.0

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