@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.
Files changed (80) 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 +2 -2
  25. package/dist/client/index.d.ts +2 -2
  26. package/dist/client/react.d.mts +94 -8
  27. package/dist/client/react.d.ts +94 -8
  28. package/dist/client/react.js +364 -26
  29. package/dist/client/react.js.map +1 -1
  30. package/dist/client/react.mjs +358 -27
  31. package/dist/client/react.mjs.map +1 -1
  32. package/dist/client/vue.d.mts +4 -4
  33. package/dist/client/vue.d.ts +4 -4
  34. package/dist/client/vue.js +11 -2
  35. package/dist/client/vue.js.map +1 -1
  36. package/dist/client/vue.mjs +11 -2
  37. package/dist/client/vue.mjs.map +1 -1
  38. package/dist/{index-CQr9q0bF.d.mts → index-DcYfpY3H.d.mts} +1 -1
  39. package/dist/{index-nE_7Io0I.d.ts → index-GfC_eNEv.d.ts} +1 -1
  40. package/dist/index.d.mts +4 -3
  41. package/dist/index.d.ts +4 -3
  42. package/dist/index.js +938 -12
  43. package/dist/index.js.map +1 -1
  44. package/dist/index.mjs +923 -13
  45. package/dist/index.mjs.map +1 -1
  46. package/dist/server/index.d.mts +2 -2
  47. package/dist/server/index.d.ts +2 -2
  48. package/dist/server/index.js +58 -12
  49. package/dist/server/index.js.map +1 -1
  50. package/dist/server/index.mjs +58 -12
  51. package/dist/server/index.mjs.map +1 -1
  52. package/dist/shared/index.d.mts +86 -4
  53. package/dist/shared/index.d.ts +86 -4
  54. package/dist/shared/index.js +874 -0
  55. package/dist/shared/index.js.map +1 -1
  56. package/dist/shared/index.mjs +865 -1
  57. package/dist/shared/index.mjs.map +1 -1
  58. package/dist/tool-router-Bo8qZbsD.d.ts +325 -0
  59. package/dist/tool-router-XnWVxPzv.d.mts +325 -0
  60. package/dist/{types-CW6lghof.d.mts → types-CfCoIsWI.d.mts} +27 -1
  61. package/dist/{types-CW6lghof.d.ts → types-CfCoIsWI.d.ts} +27 -1
  62. package/package.json +3 -2
  63. package/src/adapters/agui-adapter.ts +79 -0
  64. package/src/adapters/ai-adapter.ts +75 -0
  65. package/src/adapters/langchain-adapter.ts +74 -0
  66. package/src/client/react/index.ts +16 -0
  67. package/src/client/react/oauth-popup.tsx +446 -0
  68. package/src/client/react/use-mcp-apps.tsx +50 -32
  69. package/src/client/react/use-mcp.ts +36 -3
  70. package/src/client/vue/use-mcp.ts +38 -3
  71. package/src/server/handlers/sse-handler.ts +39 -0
  72. package/src/server/index.ts +2 -0
  73. package/src/server/mcp/oauth-client.ts +35 -15
  74. package/src/shared/index.ts +36 -0
  75. package/src/shared/meta-tools.ts +387 -0
  76. package/src/shared/schema-compressor.ts +124 -0
  77. package/src/shared/tool-index.ts +499 -0
  78. package/src/shared/tool-router.ts +469 -0
  79. package/src/shared/types.ts +30 -0
  80. package/supabase/migrations/20260421010000_add_session_cleanup_cron.sql +32 -0
package/dist/index.mjs CHANGED
@@ -1716,13 +1716,8 @@ var MCPClient = class _MCPClient {
1716
1716
  this.transportType = transportType;
1717
1717
  this.emitStateChange("CONNECTED");
1718
1718
  this.emitProgress("Connected successfully");
1719
- const existingSession = await storage.getSession(this.identity, this.sessionId);
1720
- const needsTransportUpdate = !existingSession || existingSession.transportType !== this.transportType;
1721
- const needsTtlPromotion = !existingSession || existingSession.active !== true;
1722
- if (needsTransportUpdate || needsTtlPromotion) {
1723
- console.log(`[MCPClient] Saving session ${this.sessionId} with 12hr TTL (connect success)`);
1724
- await this.saveSession(SESSION_TTL_SECONDS, true);
1725
- }
1719
+ console.log(`[MCPClient] Saving session ${this.sessionId} with 12hr TTL (connect success)`);
1720
+ await this.saveSession(SESSION_TTL_SECONDS, true);
1726
1721
  } catch (error) {
1727
1722
  if (error instanceof UnauthorizedError$1 || error instanceof Error && error.message.toLowerCase().includes("unauthorized")) {
1728
1723
  let authUrl = "";
@@ -1760,6 +1755,13 @@ var MCPClient = class _MCPClient {
1760
1755
  const errorMessage = error instanceof Error ? error.message : "Connection failed";
1761
1756
  this.emitError(errorMessage, "connection");
1762
1757
  this.emitStateChange("FAILED");
1758
+ try {
1759
+ const existingSession = await storage.getSession(this.identity, this.sessionId);
1760
+ if (!existingSession || existingSession.active !== true) {
1761
+ await storage.removeSession(this.identity, this.sessionId);
1762
+ }
1763
+ } catch {
1764
+ }
1763
1765
  throw error;
1764
1766
  }
1765
1767
  }
@@ -1783,6 +1785,7 @@ var MCPClient = class _MCPClient {
1783
1785
  const transportsToTry = this.transportType ? [this.transportType] : ["streamable_http", "sse"];
1784
1786
  let lastError;
1785
1787
  let tokensExchanged = false;
1788
+ let authenticatedStateEmitted = false;
1786
1789
  for (const currentType of transportsToTry) {
1787
1790
  const isLastAttempt = currentType === transportsToTry[transportsToTry.length - 1];
1788
1791
  try {
@@ -1794,8 +1797,10 @@ var MCPClient = class _MCPClient {
1794
1797
  } else {
1795
1798
  this.emitProgress(`Tokens already exchanged, skipping auth step for ${currentType}...`);
1796
1799
  }
1797
- this.transportType = currentType;
1798
- this.emitStateChange("AUTHENTICATED");
1800
+ if (!authenticatedStateEmitted) {
1801
+ this.emitStateChange("AUTHENTICATED");
1802
+ authenticatedStateEmitted = true;
1803
+ }
1799
1804
  this.emitProgress("Creating authenticated client...");
1800
1805
  this.client = new Client(
1801
1806
  {
@@ -1814,6 +1819,7 @@ var MCPClient = class _MCPClient {
1814
1819
  );
1815
1820
  this.emitStateChange("CONNECTING");
1816
1821
  await this.client.connect(this.transport);
1822
+ this.transportType = currentType;
1817
1823
  this.emitStateChange("CONNECTED");
1818
1824
  console.log(`[MCPClient] Updating session ${this.sessionId} to 12hr TTL (OAuth complete)`);
1819
1825
  await this.saveSession(SESSION_TTL_SECONDS, true);
@@ -2195,7 +2201,9 @@ var MCPClient = class _MCPClient {
2195
2201
  * @returns Server name or undefined
2196
2202
  */
2197
2203
  getServerName() {
2198
- return this.serverName;
2204
+ const info = this.client?.getServerVersion();
2205
+ console.log("server info ->", info);
2206
+ return info?.title ?? info?.name ?? this.serverName;
2199
2207
  }
2200
2208
  /**
2201
2209
  * Gets the server ID
@@ -2678,9 +2686,23 @@ var SSEConnectionManager = class {
2678
2686
  if (existing) {
2679
2687
  return existing;
2680
2688
  }
2689
+ const session = await storage.getSession(this.identity, sessionId);
2690
+ if (!session) {
2691
+ throw new Error("Session not found");
2692
+ }
2681
2693
  const client = new MCPClient({
2682
2694
  identity: this.identity,
2683
- sessionId
2695
+ sessionId,
2696
+ // These fields are optional in MCPClient, but when rehydrating a known
2697
+ // stored session on the server we pass them explicitly to preserve the
2698
+ // original transport/connection metadata instead of relying on lazy
2699
+ // reloading during initialize().
2700
+ serverId: session.serverId,
2701
+ serverName: session.serverName,
2702
+ serverUrl: session.serverUrl,
2703
+ callbackUrl: session.callbackUrl,
2704
+ transportType: session.transportType,
2705
+ headers: session.headers
2684
2706
  });
2685
2707
  client.onConnectionEvent((event) => this.emitConnectionEvent(event));
2686
2708
  client.onObservabilityEvent((event) => this.sendEvent(event));
@@ -2737,6 +2759,16 @@ var SSEConnectionManager = class {
2737
2759
  const client = new MCPClient({
2738
2760
  identity: this.identity,
2739
2761
  sessionId,
2762
+ // These fields are optional in MCPClient, but when rehydrating a known
2763
+ // stored session on the server we pass them explicitly to preserve the
2764
+ // original transport/connection metadata instead of relying on lazy
2765
+ // reloading during initialize().
2766
+ serverId: session.serverId,
2767
+ serverName: session.serverName,
2768
+ serverUrl: session.serverUrl,
2769
+ callbackUrl: session.callbackUrl,
2770
+ transportType: session.transportType,
2771
+ headers: session.headers,
2740
2772
  ...clientMetadata
2741
2773
  });
2742
2774
  client.onConnectionEvent((event) => this.emitConnectionEvent(event));
@@ -2769,7 +2801,21 @@ var SSEConnectionManager = class {
2769
2801
  try {
2770
2802
  const client = new MCPClient({
2771
2803
  identity: this.identity,
2772
- sessionId
2804
+ sessionId,
2805
+ // These fields are optional in MCPClient, but when rehydrating a known
2806
+ // stored session on the server we pass them explicitly to preserve the
2807
+ // original connection metadata instead of relying on lazy
2808
+ // reloading during initialize().
2809
+ serverId: session.serverId,
2810
+ serverName: session.serverName,
2811
+ serverUrl: session.serverUrl,
2812
+ callbackUrl: session.callbackUrl,
2813
+ // NOTE: transportType is intentionally omitted here.
2814
+ // The session's stored transportType is a placeholder ('streamable_http')
2815
+ // set before transport negotiation. Omitting it lets MCPClient auto-negotiate
2816
+ // (try streamable_http → SSE fallback), which is critical for servers like
2817
+ // Neon that only support SSE transport.
2818
+ headers: session.headers
2773
2819
  });
2774
2820
  client.onConnectionEvent((event) => this.emitConnectionEvent(event));
2775
2821
  await client.finishAuth(code);
@@ -3771,6 +3817,870 @@ function findToolByName(connections, toolName) {
3771
3817
  return void 0;
3772
3818
  }
3773
3819
 
3774
- export { APP_HOST_DEFAULTS, AppHost, AuthenticationError, ConfigurationError, ConnectionError, DEFAULT_CLIENT_NAME, DEFAULT_CLIENT_URI, DEFAULT_HEARTBEAT_INTERVAL_MS, DEFAULT_LOGO_URI, DEFAULT_MCP_APP_CSP, DEFAULT_POLICY_URI, DisposableStore, Emitter, InvalidStateError, MCPClient, MCP_CLIENT_NAME, MCP_CLIENT_VERSION, McpError, MultiSessionClient, NotConnectedError, REDIS_KEY_PREFIX, RpcErrorCodes, SANDBOX_PROXY_READY_METHOD, SANDBOX_RESOURCE_READY_METHOD, SESSION_TTL_SECONDS, SOFTWARE_ID, SOFTWARE_VERSION, SSEClient, SSEConnectionManager, STATE_EXPIRATION_MS, SessionNotFoundError, SessionValidationError, StorageOAuthClientProvider, TOKEN_EXPIRY_BUFFER_MS, ToolExecutionError, UnauthorizedError, createNextMcpHandler, createSSEHandler, findToolByName, getToolUiResourceUri, isCallToolSuccess, isConnectAuthRequired, isConnectError, isConnectSuccess, isListToolsSuccess, sanitizeServerLabel, storage };
3820
+ // src/shared/tool-index.ts
3821
+ var CALIBRATION_DIVISOR = 3.6;
3822
+ function classifyChar(ch) {
3823
+ const code = ch.charCodeAt(0);
3824
+ if (code <= 32 || ch === "{" || ch === "}" || ch === "[" || ch === "]" || ch === ":" || ch === ",") return 1;
3825
+ if (code >= 33 && code <= 47) return 1.5;
3826
+ if (code >= 48 && code <= 57) return 2;
3827
+ if (code >= 65 && code <= 90) return 3.5;
3828
+ if (code >= 97 && code <= 122) return 4;
3829
+ return 2.5;
3830
+ }
3831
+ var ToolIndex = class _ToolIndex {
3832
+ constructor(options = {}) {
3833
+ /** All indexed tools keyed by name (supports duplicates). */
3834
+ __publicField(this, "tools", /* @__PURE__ */ new Map());
3835
+ /** Precomputed lightweight summaries keyed by document. */
3836
+ __publicField(this, "toolSummaries", /* @__PURE__ */ new Map());
3837
+ /** Pre-computed search text for keyword matching (lowercase), keyed by document. */
3838
+ __publicField(this, "searchTexts", /* @__PURE__ */ new Map());
3839
+ /** Pre-computed IDF values per token (computed once on build). */
3840
+ __publicField(this, "idf", /* @__PURE__ */ new Map());
3841
+ /** Per-tool TF vectors (Map<token, tf>). */
3842
+ __publicField(this, "tfVectors", /* @__PURE__ */ new Map());
3843
+ /** Optional: pre-computed embedding vectors per tool. */
3844
+ __publicField(this, "embeddings", /* @__PURE__ */ new Map());
3845
+ /** BM25: document lengths in tokens for each tool. */
3846
+ __publicField(this, "docLengths", /* @__PURE__ */ new Map());
3847
+ /** BM25: average document length across the entire index. */
3848
+ __publicField(this, "avgDocLength", 0);
3849
+ /** Cached total estimated token cost across all indexed tools. */
3850
+ __publicField(this, "totalTokenCost", 0);
3851
+ __publicField(this, "options");
3852
+ this.options = {
3853
+ embedFn: options.embedFn ?? void 0,
3854
+ keywordWeight: options.keywordWeight ?? 0.4
3855
+ };
3856
+ }
3857
+ // -----------------------------------------------------------------------
3858
+ // Indexing
3859
+ // -----------------------------------------------------------------------
3860
+ /**
3861
+ * Build (or rebuild) the index from the given tool set.
3862
+ * Call this after connecting / reconnecting to MCP servers.
3863
+ */
3864
+ async buildIndex(tools) {
3865
+ this.tools.clear();
3866
+ this.toolSummaries.clear();
3867
+ this.searchTexts.clear();
3868
+ this.idf.clear();
3869
+ this.tfVectors.clear();
3870
+ this.embeddings.clear();
3871
+ this.docLengths.clear();
3872
+ this.avgDocLength = 0;
3873
+ this.totalTokenCost = 0;
3874
+ const allTokenSets = /* @__PURE__ */ new Map();
3875
+ let totalLength = 0;
3876
+ for (const tool of tools) {
3877
+ const docKey = this.getDocumentKey(tool);
3878
+ if (!this.tools.has(tool.name)) {
3879
+ this.tools.set(tool.name, []);
3880
+ }
3881
+ this.tools.get(tool.name).push(tool);
3882
+ const estimatedTokens = _ToolIndex.estimateTokens(tool);
3883
+ this.toolSummaries.set(docKey, {
3884
+ name: tool.name,
3885
+ description: tool.description ?? "",
3886
+ serverName: tool.serverName,
3887
+ sessionId: tool.sessionId,
3888
+ estimatedTokens
3889
+ });
3890
+ this.totalTokenCost += estimatedTokens;
3891
+ const text = this.buildSearchableText(tool).toLowerCase();
3892
+ this.searchTexts.set(docKey, text);
3893
+ const tokens = this.tokenize(text);
3894
+ const tf = /* @__PURE__ */ new Map();
3895
+ const uniqueTokens = /* @__PURE__ */ new Set();
3896
+ for (const tok of tokens) {
3897
+ tf.set(tok, (tf.get(tok) ?? 0) + 1);
3898
+ uniqueTokens.add(tok);
3899
+ }
3900
+ const maxTf = Math.max(...tf.values(), 1);
3901
+ for (const [k, v] of tf) {
3902
+ tf.set(k, v / maxTf);
3903
+ }
3904
+ this.tfVectors.set(docKey, tf);
3905
+ allTokenSets.set(docKey, uniqueTokens);
3906
+ const length = tokens.length;
3907
+ this.docLengths.set(docKey, length);
3908
+ totalLength += length;
3909
+ }
3910
+ this.avgDocLength = totalLength / (tools.length || 1);
3911
+ const totalDocs = tools.length || 1;
3912
+ const dfCounts = /* @__PURE__ */ new Map();
3913
+ for (const tokenSet of allTokenSets.values()) {
3914
+ for (const tok of tokenSet) {
3915
+ dfCounts.set(tok, (dfCounts.get(tok) ?? 0) + 1);
3916
+ }
3917
+ }
3918
+ for (const [tok, df] of dfCounts) {
3919
+ this.idf.set(tok, Math.log(totalDocs / df) + 1);
3920
+ }
3921
+ if (this.options.embedFn) {
3922
+ const names = [...this.searchTexts.keys()];
3923
+ const texts = names.map((n) => this.searchTexts.get(n));
3924
+ try {
3925
+ const vectors = await this.options.embedFn(texts);
3926
+ for (let i = 0; i < names.length; i++) {
3927
+ if (vectors[i]) {
3928
+ this.embeddings.set(names[i], vectors[i]);
3929
+ }
3930
+ }
3931
+ } catch (err) {
3932
+ console.warn("[ToolIndex] Embedding generation failed, falling back to keyword-only search:", err);
3933
+ }
3934
+ }
3935
+ }
3936
+ // -----------------------------------------------------------------------
3937
+ // Search
3938
+ // -----------------------------------------------------------------------
3939
+ /**
3940
+ * Search the index and return the top-K most relevant tools.
3941
+ *
3942
+ * When an `embedFn` is configured the final score is a weighted blend of
3943
+ * keyword TF-IDF similarity and embedding cosine-similarity:
3944
+ *
3945
+ * `score = keywordWeight × keyword_score + (1 - keywordWeight) × cosine_score`
3946
+ */
3947
+ async search(query, topK = 5) {
3948
+ if (this.tools.size === 0) return [];
3949
+ const queryLower = query.toLowerCase();
3950
+ const queryTokens = this.tokenize(queryLower);
3951
+ const keywordScores = /* @__PURE__ */ new Map();
3952
+ const k1 = 1.2;
3953
+ const b = 0.75;
3954
+ for (const [docKey, docTf] of this.tfVectors) {
3955
+ let score = 0;
3956
+ const docLen = this.docLengths.get(docKey) ?? 0;
3957
+ for (const tok of queryTokens) {
3958
+ const tfVal = docTf.get(tok) ?? 0;
3959
+ if (tfVal === 0) continue;
3960
+ const idf = this.idf.get(tok) ?? 0;
3961
+ const numerator = tfVal * (k1 + 1);
3962
+ const denominator = tfVal + k1 * (1 - b + b * (docLen / this.avgDocLength));
3963
+ score += idf * (numerator / denominator);
3964
+ }
3965
+ keywordScores.set(docKey, score);
3966
+ }
3967
+ let embeddingScores = null;
3968
+ if (this.options.embedFn && this.embeddings.size > 0) {
3969
+ try {
3970
+ const [queryEmbedding] = await this.options.embedFn([queryLower]);
3971
+ if (queryEmbedding) {
3972
+ embeddingScores = /* @__PURE__ */ new Map();
3973
+ for (const [docKey, vec] of this.embeddings) {
3974
+ embeddingScores.set(docKey, this.cosineSimilarity(queryEmbedding, vec));
3975
+ }
3976
+ }
3977
+ } catch {
3978
+ }
3979
+ }
3980
+ const kw = this.options.keywordWeight;
3981
+ const finalScores = [];
3982
+ for (const docKey of this.toolSummaries.keys()) {
3983
+ const kwScore = keywordScores.get(docKey) ?? 0;
3984
+ const embScore = embeddingScores?.get(docKey) ?? 0;
3985
+ const score = embeddingScores ? kw * kwScore + (1 - kw) * embScore : kwScore;
3986
+ if (score > 0) {
3987
+ finalScores.push({ docKey, score });
3988
+ }
3989
+ }
3990
+ finalScores.sort((a, b2) => b2.score - a.score);
3991
+ return finalScores.slice(0, topK).map(({ docKey }) => {
3992
+ return this.toolSummaries.get(docKey);
3993
+ });
3994
+ }
3995
+ /**
3996
+ * Search tools using a regex pattern.
3997
+ * Matches against name, description, and parameter metadata.
3998
+ */
3999
+ searchRegex(pattern, topK = 5) {
4000
+ if (this.tools.size === 0) return [];
4001
+ try {
4002
+ let flags = "";
4003
+ let cleanPattern = pattern;
4004
+ if (pattern.includes("(?i)")) {
4005
+ flags = "i";
4006
+ cleanPattern = pattern.replace(/\(\?i\)/g, "");
4007
+ }
4008
+ const regex = new RegExp(cleanPattern, flags || void 0);
4009
+ const matches = [];
4010
+ for (const [docKey, text] of this.searchTexts) {
4011
+ const tool = this.toolSummaries.get(docKey);
4012
+ if (!tool) continue;
4013
+ if (regex.test(text) || regex.test(tool.name)) {
4014
+ let score = 1;
4015
+ if (tool.name === cleanPattern) score = 10;
4016
+ else if (tool.name.startsWith(cleanPattern)) score = 5;
4017
+ else if (tool.name.toLowerCase().includes(cleanPattern.toLowerCase())) score = 2;
4018
+ matches.push({ docKey, score });
4019
+ }
4020
+ }
4021
+ matches.sort((a, b) => b.score - a.score);
4022
+ return matches.slice(0, topK).map(({ docKey }) => {
4023
+ return this.toolSummaries.get(docKey);
4024
+ });
4025
+ } catch (err) {
4026
+ console.warn("[ToolIndex] Regex search failed:", err);
4027
+ return [];
4028
+ }
4029
+ }
4030
+ // -----------------------------------------------------------------------
4031
+ // Accessors
4032
+ // -----------------------------------------------------------------------
4033
+ /**
4034
+ * Get tool definition(s) by name.
4035
+ * If namespace is provided, it tries to match sessionId or serverName.
4036
+ */
4037
+ getTool(name, namespace) {
4038
+ const list = this.tools.get(name) ?? [];
4039
+ if (!namespace) return list;
4040
+ return list.filter((t) => t.sessionId === namespace || t.serverName === namespace);
4041
+ }
4042
+ /** All indexed tool names. */
4043
+ getToolNames() {
4044
+ return [...this.tools.keys()];
4045
+ }
4046
+ /** Number of indexed tools (including duplicates). */
4047
+ get size() {
4048
+ let count = 0;
4049
+ for (const list of this.tools.values()) {
4050
+ count += list.length;
4051
+ }
4052
+ return count;
4053
+ }
4054
+ /** Total estimated token cost of all indexed tool schemas. */
4055
+ getTotalTokenCost() {
4056
+ return this.totalTokenCost;
4057
+ }
4058
+ // -----------------------------------------------------------------------
4059
+ // Static Helpers
4060
+ // -----------------------------------------------------------------------
4061
+ /**
4062
+ * Estimate token count of a tool's full schema (name + description + inputSchema).
4063
+ *
4064
+ * Uses character-class weighted counting calibrated against cl100k_base.
4065
+ * Accuracy is typically within ±10% for JSON Schema payloads.
4066
+ */
4067
+ static estimateTokens(tool) {
4068
+ const parts = [tool.name];
4069
+ if (tool.description) parts.push(tool.description);
4070
+ if (tool.inputSchema) parts.push(JSON.stringify(tool.inputSchema));
4071
+ const text = parts.join(" ");
4072
+ let weightedLen = 0;
4073
+ for (let i = 0; i < text.length; i++) {
4074
+ weightedLen += 1 / classifyChar(text[i]);
4075
+ }
4076
+ return Math.ceil(weightedLen / (1 / CALIBRATION_DIVISOR));
4077
+ }
4078
+ // -----------------------------------------------------------------------
4079
+ // Internals
4080
+ // -----------------------------------------------------------------------
4081
+ /** Build a single searchable string from tool metadata. */
4082
+ buildSearchableText(tool) {
4083
+ const parts = [tool.name];
4084
+ if (tool.description) parts.push(tool.description);
4085
+ if (tool.inputSchema && typeof tool.inputSchema === "object") {
4086
+ const schema = tool.inputSchema;
4087
+ const props = schema.properties;
4088
+ if (props) {
4089
+ for (const [key, val] of Object.entries(props)) {
4090
+ parts.push(key);
4091
+ if (val && typeof val === "object" && val.description) {
4092
+ parts.push(val.description);
4093
+ }
4094
+ }
4095
+ }
4096
+ }
4097
+ return parts.join(" ");
4098
+ }
4099
+ getDocumentKey(tool) {
4100
+ return `${tool.sessionId}::${tool.serverName}::${tool.name}`;
4101
+ }
4102
+ /** Simple whitespace + camelCase + snake_case tokenizer. */
4103
+ tokenize(text) {
4104
+ 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);
4105
+ }
4106
+ /** Cosine similarity between two vectors. */
4107
+ cosineSimilarity(a, b) {
4108
+ const len = Math.min(a.length, b.length);
4109
+ let dot = 0;
4110
+ let magA = 0;
4111
+ let magB = 0;
4112
+ for (let i = 0; i < len; i++) {
4113
+ dot += a[i] * b[i];
4114
+ magA += a[i] * a[i];
4115
+ magB += b[i] * b[i];
4116
+ }
4117
+ const denom = Math.sqrt(magA) * Math.sqrt(magB);
4118
+ return denom > 0 ? dot / denom : 0;
4119
+ }
4120
+ };
4121
+
4122
+ // src/shared/schema-compressor.ts
4123
+ var SchemaCompressor = class _SchemaCompressor {
4124
+ /**
4125
+ * Convert a full MCP Tool definition to a compact summary.
4126
+ *
4127
+ * The compact form omits `inputSchema` entirely and optionally generates
4128
+ * a short `parameterHint` from the schema's top-level properties.
4129
+ */
4130
+ static toCompact(tool) {
4131
+ const compact = {
4132
+ name: tool.name,
4133
+ description: tool.description
4134
+ };
4135
+ if (tool.inputSchema && typeof tool.inputSchema === "object") {
4136
+ const schema = tool.inputSchema;
4137
+ if (schema.properties) {
4138
+ const required = new Set(schema.required ?? []);
4139
+ const parts = [];
4140
+ for (const [key, val] of Object.entries(schema.properties)) {
4141
+ const type = val?.type ?? "any";
4142
+ const enumSuffix = val?.enum && Array.isArray(val.enum) ? `: ${val.enum.map((e) => `'${e}'`).join(" | ")}` : `: ${type}`;
4143
+ parts.push(required.has(key) ? `${key}${enumSuffix}` : `${key}?${enumSuffix}`);
4144
+ }
4145
+ if (parts.length > 0) {
4146
+ compact.parameterHint = `(${parts.join(", ")})`;
4147
+ }
4148
+ }
4149
+ }
4150
+ return compact;
4151
+ }
4152
+ /**
4153
+ * Convert an array of tools to compact form, optionally limiting the count.
4154
+ */
4155
+ static compactAll(tools, options) {
4156
+ const limited = options?.maxTools ? tools.slice(0, options.maxTools) : tools;
4157
+ return limited.map((t) => _SchemaCompressor.toCompact(t));
4158
+ }
4159
+ /**
4160
+ * Estimate token savings from using compact vs full tool schemas.
4161
+ */
4162
+ static estimateSavings(tools) {
4163
+ let fullTokens = 0;
4164
+ let compactTokens = 0;
4165
+ for (const tool of tools) {
4166
+ fullTokens += ToolIndex.estimateTokens(tool);
4167
+ const compact = _SchemaCompressor.toCompact(tool);
4168
+ const text = [compact.name, compact.description ?? "", compact.parameterHint ?? ""].join(" ");
4169
+ compactTokens += Math.ceil(text.length / 4);
4170
+ }
4171
+ const saved = fullTokens - compactTokens;
4172
+ const pct = fullTokens > 0 ? (saved / fullTokens * 100).toFixed(1) : "0.0";
4173
+ return {
4174
+ fullTokens,
4175
+ compactTokens,
4176
+ savedTokens: saved,
4177
+ savingsPercent: `${pct}%`
4178
+ };
4179
+ }
4180
+ };
4181
+
4182
+ // src/shared/meta-tools.ts
4183
+ function createSearchToolDefinition() {
4184
+ return {
4185
+ name: "mcp_search_tool_bm25",
4186
+ 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".',
4187
+ inputSchema: {
4188
+ type: "object",
4189
+ properties: {
4190
+ query: {
4191
+ type: "string",
4192
+ description: "Natural language description of the capability you need."
4193
+ },
4194
+ limit: {
4195
+ type: "number",
4196
+ description: "Maximum number of results to return (default: 5, max: 20)."
4197
+ }
4198
+ },
4199
+ required: ["query"]
4200
+ }
4201
+ };
4202
+ }
4203
+ function createRegexSearchToolDefinition() {
4204
+ return {
4205
+ name: "mcp_search_tool_regex",
4206
+ 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".',
4207
+ inputSchema: {
4208
+ type: "object",
4209
+ properties: {
4210
+ query: {
4211
+ type: "string",
4212
+ description: 'Regex pattern to search for (e.g., "^get_.*_data", "database").'
4213
+ },
4214
+ limit: {
4215
+ type: "number",
4216
+ description: "Maximum number of results to return (default: 5, max: 20)."
4217
+ }
4218
+ },
4219
+ required: ["query"]
4220
+ }
4221
+ };
4222
+ }
4223
+ function createGetSchemaToolDefinition() {
4224
+ return {
4225
+ name: "mcp_get_tool_schema",
4226
+ 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.",
4227
+ inputSchema: {
4228
+ type: "object",
4229
+ properties: {
4230
+ toolName: {
4231
+ type: "string",
4232
+ description: "The exact tool name returned by mcp_search_tool_bm25."
4233
+ },
4234
+ serverName: {
4235
+ type: "string",
4236
+ description: "Optional: The server name provided in mcp_search_tool_bm25. Required if multiple tools have the same name."
4237
+ }
4238
+ },
4239
+ required: ["toolName"]
4240
+ }
4241
+ };
4242
+ }
4243
+ function createExecuteToolDefinition() {
4244
+ return {
4245
+ name: "mcp_execute_tool",
4246
+ 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.",
4247
+ inputSchema: {
4248
+ type: "object",
4249
+ properties: {
4250
+ toolName: {
4251
+ type: "string",
4252
+ description: "The exact tool name from mcp_search_tool_bm25 results."
4253
+ },
4254
+ serverName: {
4255
+ type: "string",
4256
+ description: "Optional: The server name provided in mcp_search_tool_bm25. Required if multiple tools have the same name."
4257
+ },
4258
+ args: {
4259
+ type: "object",
4260
+ description: "Arguments matching the tool's inputSchema. Omit or pass {} if the tool takes no parameters.",
4261
+ additionalProperties: true
4262
+ }
4263
+ },
4264
+ required: ["toolName"]
4265
+ }
4266
+ };
4267
+ }
4268
+ async function executeMetaTool(toolName, args, router, callToolFn) {
4269
+ const resolveToolSchema = (name, namespace) => {
4270
+ try {
4271
+ return { tool: router.getToolSchema(name, namespace) };
4272
+ } catch (err) {
4273
+ const errorMessage = err instanceof Error ? err.message : String(err);
4274
+ return {
4275
+ error: {
4276
+ content: [{ type: "text", text: errorMessage }],
4277
+ isError: true
4278
+ }
4279
+ };
4280
+ }
4281
+ };
4282
+ switch (toolName) {
4283
+ case "mcp_search_tool_bm25": {
4284
+ const query = String(args.query ?? "");
4285
+ const limit = Math.min(Number(args.limit) || 5, 20);
4286
+ const results = await router.searchTools(query, limit);
4287
+ const text = results.length === 0 ? "No tools found matching your query. Try different keywords." : results.map(
4288
+ (t, i) => `${i + 1}. **${t.name}** (server: ${t.serverName})
4289
+ ${t.description}
4290
+ Estimated tokens: ${t.estimatedTokens}`
4291
+ ).join("\n");
4292
+ return {
4293
+ content: [{ type: "text", text }],
4294
+ isError: false
4295
+ };
4296
+ }
4297
+ case "mcp_search_tool_regex": {
4298
+ const pattern = String(args.query ?? "");
4299
+ const limit = Math.min(Number(args.limit) || 5, 20);
4300
+ const results = await router.searchToolsRegex(pattern, limit);
4301
+ const text = results.length === 0 ? "No tools matched your regex pattern. Try a broader pattern." : results.map(
4302
+ (t, i) => `${i + 1}. **${t.name}** (server: ${t.serverName})
4303
+ ${t.description}
4304
+ Estimated tokens: ${t.estimatedTokens}`
4305
+ ).join("\n");
4306
+ return {
4307
+ content: [{ type: "text", text }],
4308
+ isError: false
4309
+ };
4310
+ }
4311
+ case "mcp_get_tool_schema": {
4312
+ const name = String(args.toolName ?? "");
4313
+ const namespace = String(args.serverName ?? "") || void 0;
4314
+ const { tool, error } = resolveToolSchema(name, namespace);
4315
+ if (error) {
4316
+ return error;
4317
+ }
4318
+ if (!tool) {
4319
+ return {
4320
+ content: [
4321
+ {
4322
+ type: "text",
4323
+ text: `Tool "${name}" not found. Use mcp_search_tool_bm25 to find available tools first.`
4324
+ }
4325
+ ],
4326
+ isError: true
4327
+ };
4328
+ }
4329
+ const schema = {
4330
+ name: tool.name,
4331
+ description: tool.description,
4332
+ inputSchema: tool.inputSchema
4333
+ };
4334
+ return {
4335
+ content: [{ type: "text", text: JSON.stringify(schema, null, 2) }],
4336
+ isError: false
4337
+ };
4338
+ }
4339
+ case "mcp_execute_tool": {
4340
+ const targetToolName = String(args.toolName ?? "");
4341
+ const namespace = String(args.serverName ?? "") || void 0;
4342
+ const toolArgs = args.args ?? {};
4343
+ if (!targetToolName) {
4344
+ return {
4345
+ content: [{ type: "text", text: 'Missing required parameter "toolName". Specify which tool to execute.' }],
4346
+ isError: true
4347
+ };
4348
+ }
4349
+ const { tool, error } = resolveToolSchema(targetToolName, namespace);
4350
+ if (error) {
4351
+ return error;
4352
+ }
4353
+ if (!tool) {
4354
+ return {
4355
+ content: [
4356
+ {
4357
+ type: "text",
4358
+ text: `Tool "${targetToolName}" not found. Use mcp_search_tool_bm25 to discover available tools first.`
4359
+ }
4360
+ ],
4361
+ isError: true
4362
+ };
4363
+ }
4364
+ if (!callToolFn) {
4365
+ return {
4366
+ content: [{ type: "text", text: "Tool execution is not available. No callToolFn was configured." }],
4367
+ isError: true
4368
+ };
4369
+ }
4370
+ try {
4371
+ const result = await callToolFn(targetToolName, toolArgs, namespace);
4372
+ if (result && typeof result === "object" && "content" in result) {
4373
+ return result;
4374
+ }
4375
+ const text = typeof result === "string" ? result : JSON.stringify(result, null, 2);
4376
+ return {
4377
+ content: [{ type: "text", text }],
4378
+ isError: false
4379
+ };
4380
+ } catch (err) {
4381
+ const errorMessage = err instanceof Error ? err.message : String(err);
4382
+ return {
4383
+ content: [{ type: "text", text: `Tool execution failed: ${errorMessage}` }],
4384
+ isError: true
4385
+ };
4386
+ }
4387
+ }
4388
+ default:
4389
+ return null;
4390
+ }
4391
+ }
4392
+ function isMetaTool(toolName) {
4393
+ return toolName === "mcp_search_tool_bm25" || toolName === "mcp_search_tool_regex" || toolName === "mcp_get_tool_schema" || toolName === "mcp_execute_tool";
4394
+ }
4395
+ function resolveMetaToolProxy(toolName, args) {
4396
+ if (toolName === "mcp_execute_tool") {
4397
+ const innerName = args?.toolName;
4398
+ const innerArgs = args?.args;
4399
+ return {
4400
+ toolName: typeof innerName === "string" && innerName ? innerName : toolName,
4401
+ args: innerArgs && typeof innerArgs === "object" && !Array.isArray(innerArgs) ? innerArgs : {}
4402
+ };
4403
+ }
4404
+ const match = toolName.match(/(?:tool_[^_]+_)?(.+)$/);
4405
+ const resolvedName = match?.[1] ?? toolName;
4406
+ return { toolName: resolvedName, args: args ?? {} };
4407
+ }
4408
+
4409
+ // src/shared/tool-router.ts
4410
+ var ToolRouter = class {
4411
+ constructor(client, options = {}) {
4412
+ this.client = client;
4413
+ this.options = options;
4414
+ __publicField(this, "index");
4415
+ __publicField(this, "allTools", []);
4416
+ __publicField(this, "groupsMap", /* @__PURE__ */ new Map());
4417
+ __publicField(this, "strategy");
4418
+ __publicField(this, "maxTools");
4419
+ __publicField(this, "compactSchemas");
4420
+ __publicField(this, "activeGroups");
4421
+ __publicField(this, "customGroups");
4422
+ __publicField(this, "initialized", false);
4423
+ this.strategy = options.strategy ?? "all";
4424
+ this.maxTools = options.maxTools ?? 40;
4425
+ this.compactSchemas = options.compactSchemas ?? false;
4426
+ this.activeGroups = new Set(options.activeGroups ?? []);
4427
+ this.customGroups = options.groups;
4428
+ this.index = new ToolIndex({
4429
+ embedFn: options.embedFn,
4430
+ keywordWeight: options.keywordWeight
4431
+ });
4432
+ }
4433
+ // -----------------------------------------------------------------------
4434
+ // Core Public API
4435
+ // -----------------------------------------------------------------------
4436
+ /**
4437
+ * Get tools filtered by the current strategy.
4438
+ * This is the main method adapters should call.
4439
+ *
4440
+ * - `all` → returns all tools (unchanged behavior)
4441
+ * - `search` → returns only meta-tools (mcp_search_tool_bm25, mcp_get_tool_schema, mcp_execute_tool)
4442
+ * - `groups` → returns tools from active groups only
4443
+ */
4444
+ async getFilteredTools() {
4445
+ await this.ensureInitialized();
4446
+ switch (this.strategy) {
4447
+ case "search":
4448
+ return this.getMetaToolDefinitions();
4449
+ case "groups":
4450
+ return this.getGroupFilteredTools();
4451
+ case "all":
4452
+ default:
4453
+ if (this.compactSchemas) {
4454
+ return this.allTools.map((t) => {
4455
+ const compact = SchemaCompressor.toCompact(t);
4456
+ return {
4457
+ name: compact.name,
4458
+ description: (compact.description ?? "") + (compact.parameterHint ? ` Parameters: ${compact.parameterHint}` : ""),
4459
+ inputSchema: { type: "object", properties: {} }
4460
+ };
4461
+ });
4462
+ }
4463
+ return [...this.allTools];
4464
+ }
4465
+ }
4466
+ /**
4467
+ * Search tools by natural-language query.
4468
+ * Works regardless of strategy.
4469
+ */
4470
+ async searchTools(query, topK) {
4471
+ await this.ensureInitialized();
4472
+ return this.index.search(query, topK ?? this.maxTools);
4473
+ }
4474
+ /**
4475
+ * Search tools by regex pattern.
4476
+ * Matches against name, description, and parameter metadata.
4477
+ */
4478
+ async searchToolsRegex(pattern, topK) {
4479
+ await this.ensureInitialized();
4480
+ return this.index.searchRegex(pattern, topK ?? this.maxTools);
4481
+ }
4482
+ /**
4483
+ * Get the full tool definition by name.
4484
+ * If tool name is ambiguous, use namespace to specify the server.
4485
+ */
4486
+ getToolSchema(toolName, namespace) {
4487
+ const matches = this.index.getTool(toolName, namespace);
4488
+ if (matches.length === 0) return void 0;
4489
+ if (matches.length > 1) {
4490
+ const servers = matches.map((m) => m.serverName).join(", ");
4491
+ throw new Error(
4492
+ `Tool "${toolName}" is provided by multiple servers: [${servers}]. Please specify the desired "serverName" as a namespace.`
4493
+ );
4494
+ }
4495
+ return matches[0];
4496
+ }
4497
+ /**
4498
+ * Get compact (schema-less) summaries for all tools.
4499
+ */
4500
+ getCompactTools() {
4501
+ return SchemaCompressor.compactAll(this.allTools);
4502
+ }
4503
+ // -----------------------------------------------------------------------
4504
+ // Group Management
4505
+ // -----------------------------------------------------------------------
4506
+ /** Get all available groups with their tool lists and active status. */
4507
+ getGroups() {
4508
+ return new Map(this.groupsMap);
4509
+ }
4510
+ /** Activate specific groups. Pass empty array to activate all. */
4511
+ setActiveGroups(groups) {
4512
+ this.activeGroups = new Set(groups);
4513
+ for (const [name, info] of this.groupsMap) {
4514
+ info.active = this.activeGroups.size === 0 || this.activeGroups.has(name);
4515
+ }
4516
+ }
4517
+ /** Get the names of currently active groups. */
4518
+ getActiveGroups() {
4519
+ return [...this.activeGroups];
4520
+ }
4521
+ // -----------------------------------------------------------------------
4522
+ // Stats & Introspection
4523
+ // -----------------------------------------------------------------------
4524
+ /** Total token cost of all tools if loaded without filtering. */
4525
+ getTotalTokenCost() {
4526
+ return this.index.getTotalTokenCost();
4527
+ }
4528
+ /** Estimate token cost of the currently filtered tool set. */
4529
+ async getFilteredTokenCost() {
4530
+ const tools = await this.getFilteredTools();
4531
+ let total = 0;
4532
+ for (const tool of tools) {
4533
+ total += ToolIndex.estimateTokens(tool);
4534
+ }
4535
+ return total;
4536
+ }
4537
+ /** Get compression stats showing savings from current strategy. */
4538
+ getCompressionStats() {
4539
+ return SchemaCompressor.estimateSavings(this.allTools);
4540
+ }
4541
+ /** Number of total indexed tools. */
4542
+ get totalToolCount() {
4543
+ return this.allTools.length;
4544
+ }
4545
+ /** Change strategy at runtime. */
4546
+ setStrategy(strategy) {
4547
+ this.strategy = strategy;
4548
+ }
4549
+ /**
4550
+ * Force a re-index of tools from all connected clients.
4551
+ * Call this after adding/removing MCP server connections.
4552
+ */
4553
+ async refresh() {
4554
+ this.initialized = false;
4555
+ await this.ensureInitialized();
4556
+ }
4557
+ /**
4558
+ * Execute a tool by routing to the correct MCP client.
4559
+ * Used by the `mcp_execute_tool` meta-tool to proxy tool calls.
4560
+ */
4561
+ async callTool(toolName, args, namespace) {
4562
+ await this.ensureInitialized();
4563
+ const indexedTool = this.getToolSchema(toolName, namespace);
4564
+ if (!indexedTool) {
4565
+ throw new Error(
4566
+ `Tool "${toolName}" not found${namespace ? ` on server "${namespace}"` : ""}. Use mcp_search_tool_bm25 or mcp_search_tool_regex to discover available tools.`
4567
+ );
4568
+ }
4569
+ const clients = this.getClients();
4570
+ const targetClient = clients.find(
4571
+ (c) => typeof c.getSessionId === "function" && c.getSessionId() === indexedTool.sessionId
4572
+ ) ?? clients.find((c) => c.isConnected());
4573
+ if (!targetClient) {
4574
+ throw new Error(`No connected client found for tool "${toolName}"`);
4575
+ }
4576
+ return await targetClient.callTool(toolName, args);
4577
+ }
4578
+ // -----------------------------------------------------------------------
4579
+ // Internals
4580
+ // -----------------------------------------------------------------------
4581
+ /** Lazy initialization — fetches tools from all connected clients. */
4582
+ async ensureInitialized() {
4583
+ if (this.initialized) return;
4584
+ this.allTools = await this.fetchAllTools();
4585
+ await this.index.buildIndex(this.allTools);
4586
+ this.buildGroups();
4587
+ this.initialized = true;
4588
+ }
4589
+ /** Fetch tools from all connected MCP clients. */
4590
+ async fetchAllTools() {
4591
+ const clients = this.getClients();
4592
+ const result = [];
4593
+ for (const client of clients) {
4594
+ if (!client.isConnected()) continue;
4595
+ try {
4596
+ const { tools } = await client.listTools();
4597
+ const serverId = typeof client.getServerId === "function" ? client.getServerId() ?? "unknown" : "unknown";
4598
+ const serverName = (typeof client.getServerName === "function" ? client.getServerName() : void 0) ?? serverId;
4599
+ const sessionId = typeof client.getSessionId === "function" ? client.getSessionId() ?? "unknown" : "unknown";
4600
+ for (const tool of tools) {
4601
+ result.push({
4602
+ ...tool,
4603
+ serverName,
4604
+ sessionId
4605
+ });
4606
+ }
4607
+ } catch (err) {
4608
+ console.warn("[ToolRouter] Failed to fetch tools from client:", err);
4609
+ }
4610
+ }
4611
+ return result;
4612
+ }
4613
+ /** Resolve the client input to a flat array of ToolClient instances. */
4614
+ getClients() {
4615
+ if (Array.isArray(this.client)) {
4616
+ return this.client;
4617
+ }
4618
+ if (typeof this.client.getClients === "function") {
4619
+ return this.client.getClients();
4620
+ }
4621
+ return [this.client];
4622
+ }
4623
+ /** Build group map from custom config or auto-detect from server names. */
4624
+ buildGroups() {
4625
+ this.groupsMap.clear();
4626
+ if (this.customGroups) {
4627
+ for (const [name, tools] of Object.entries(this.customGroups)) {
4628
+ this.groupsMap.set(name, {
4629
+ tools,
4630
+ active: this.activeGroups.size === 0 || this.activeGroups.has(name)
4631
+ });
4632
+ }
4633
+ } else {
4634
+ const serverTools = /* @__PURE__ */ new Map();
4635
+ for (const tool of this.allTools) {
4636
+ const group = tool.serverName;
4637
+ if (!serverTools.has(group)) {
4638
+ serverTools.set(group, []);
4639
+ }
4640
+ serverTools.get(group).push(tool.name);
4641
+ }
4642
+ for (const [serverName, tools] of serverTools) {
4643
+ this.groupsMap.set(serverName, {
4644
+ tools,
4645
+ active: this.activeGroups.size === 0 || this.activeGroups.has(serverName)
4646
+ });
4647
+ }
4648
+ }
4649
+ }
4650
+ /** Return only tools belonging to currently active groups. */
4651
+ getGroupFilteredTools() {
4652
+ const activeToolNames = /* @__PURE__ */ new Set();
4653
+ for (const [, info] of this.groupsMap) {
4654
+ if (info.active) {
4655
+ for (const name of info.tools) {
4656
+ activeToolNames.add(name);
4657
+ }
4658
+ }
4659
+ }
4660
+ const filtered = this.allTools.filter((t) => activeToolNames.has(t.name));
4661
+ if (this.compactSchemas) {
4662
+ return filtered.slice(0, this.maxTools).map((t) => {
4663
+ const compact = SchemaCompressor.toCompact(t);
4664
+ return {
4665
+ name: compact.name,
4666
+ description: (compact.description ?? "") + (compact.parameterHint ? ` Parameters: ${compact.parameterHint}` : ""),
4667
+ inputSchema: { type: "object", properties: {} }
4668
+ };
4669
+ });
4670
+ }
4671
+ return filtered.slice(0, this.maxTools);
4672
+ }
4673
+ /** The 4 meta-tool definitions exposed in `search` strategy. */
4674
+ getMetaToolDefinitions() {
4675
+ return [
4676
+ createSearchToolDefinition(),
4677
+ createRegexSearchToolDefinition(),
4678
+ createGetSchemaToolDefinition(),
4679
+ createExecuteToolDefinition()
4680
+ ];
4681
+ }
4682
+ };
4683
+
4684
+ export { APP_HOST_DEFAULTS, AppHost, AuthenticationError, ConfigurationError, ConnectionError, DEFAULT_CLIENT_NAME, DEFAULT_CLIENT_URI, DEFAULT_HEARTBEAT_INTERVAL_MS, DEFAULT_LOGO_URI, DEFAULT_MCP_APP_CSP, DEFAULT_POLICY_URI, DisposableStore, Emitter, InvalidStateError, MCPClient, MCP_CLIENT_NAME, MCP_CLIENT_VERSION, McpError, MultiSessionClient, NotConnectedError, REDIS_KEY_PREFIX, RpcErrorCodes, SANDBOX_PROXY_READY_METHOD, SANDBOX_RESOURCE_READY_METHOD, SESSION_TTL_SECONDS, SOFTWARE_ID, SOFTWARE_VERSION, SSEClient, SSEConnectionManager, STATE_EXPIRATION_MS, SchemaCompressor, SessionNotFoundError, SessionValidationError, StorageOAuthClientProvider, TOKEN_EXPIRY_BUFFER_MS, ToolExecutionError, ToolIndex, ToolRouter, UnauthorizedError, createExecuteToolDefinition, createGetSchemaToolDefinition, createNextMcpHandler, createRegexSearchToolDefinition, createSSEHandler, createSearchToolDefinition, executeMetaTool, findToolByName, getToolUiResourceUri, isCallToolSuccess, isConnectAuthRequired, isConnectError, isConnectSuccess, isListToolsSuccess, isMetaTool, resolveMetaToolProxy, sanitizeServerLabel, storage };
3775
4685
  //# sourceMappingURL=index.mjs.map
3776
4686
  //# sourceMappingURL=index.mjs.map