@juspay/neurolink 9.26.2 → 9.28.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 (125) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +59 -9
  3. package/dist/cli/commands/config.d.ts +4 -4
  4. package/dist/cli/commands/mcp.d.ts +87 -0
  5. package/dist/cli/commands/mcp.js +1524 -0
  6. package/dist/cli/loop/optionsSchema.js +4 -0
  7. package/dist/core/modules/ToolsManager.js +29 -2
  8. package/dist/index.d.ts +2 -1
  9. package/dist/index.js +27 -1
  10. package/dist/lib/core/modules/ToolsManager.js +29 -2
  11. package/dist/lib/index.d.ts +2 -1
  12. package/dist/lib/index.js +27 -1
  13. package/dist/lib/mcp/agentExposure.d.ts +228 -0
  14. package/dist/lib/mcp/agentExposure.js +357 -0
  15. package/dist/lib/mcp/batching/index.d.ts +11 -0
  16. package/dist/lib/mcp/batching/index.js +11 -0
  17. package/dist/lib/mcp/batching/requestBatcher.d.ts +202 -0
  18. package/dist/lib/mcp/batching/requestBatcher.js +442 -0
  19. package/dist/lib/mcp/caching/index.d.ts +11 -0
  20. package/dist/lib/mcp/caching/index.js +11 -0
  21. package/dist/lib/mcp/caching/toolCache.d.ts +221 -0
  22. package/dist/lib/mcp/caching/toolCache.js +434 -0
  23. package/dist/lib/mcp/elicitation/elicitationManager.d.ts +169 -0
  24. package/dist/lib/mcp/elicitation/elicitationManager.js +377 -0
  25. package/dist/lib/mcp/elicitation/index.d.ts +11 -0
  26. package/dist/lib/mcp/elicitation/index.js +12 -0
  27. package/dist/lib/mcp/elicitation/types.d.ts +278 -0
  28. package/dist/lib/mcp/elicitation/types.js +11 -0
  29. package/dist/lib/mcp/elicitationProtocol.d.ts +228 -0
  30. package/dist/lib/mcp/elicitationProtocol.js +376 -0
  31. package/dist/lib/mcp/enhancedToolDiscovery.d.ts +205 -0
  32. package/dist/lib/mcp/enhancedToolDiscovery.js +482 -0
  33. package/dist/lib/mcp/index.d.ts +38 -1
  34. package/dist/lib/mcp/index.js +36 -3
  35. package/dist/lib/mcp/mcpRegistryClient.d.ts +332 -0
  36. package/dist/lib/mcp/mcpRegistryClient.js +489 -0
  37. package/dist/lib/mcp/mcpServerBase.d.ts +227 -0
  38. package/dist/lib/mcp/mcpServerBase.js +374 -0
  39. package/dist/lib/mcp/multiServerManager.d.ts +310 -0
  40. package/dist/lib/mcp/multiServerManager.js +580 -0
  41. package/dist/lib/mcp/routing/index.d.ts +11 -0
  42. package/dist/lib/mcp/routing/index.js +11 -0
  43. package/dist/lib/mcp/routing/toolRouter.d.ts +219 -0
  44. package/dist/lib/mcp/routing/toolRouter.js +417 -0
  45. package/dist/lib/mcp/serverCapabilities.d.ts +341 -0
  46. package/dist/lib/mcp/serverCapabilities.js +503 -0
  47. package/dist/lib/mcp/toolAnnotations.d.ts +154 -0
  48. package/dist/lib/mcp/toolAnnotations.js +240 -0
  49. package/dist/lib/mcp/toolConverter.d.ts +178 -0
  50. package/dist/lib/mcp/toolConverter.js +259 -0
  51. package/dist/lib/mcp/toolIntegration.d.ts +136 -0
  52. package/dist/lib/mcp/toolIntegration.js +335 -0
  53. package/dist/lib/memory/hippocampusInitializer.d.ts +2 -2
  54. package/dist/lib/memory/hippocampusInitializer.js +1 -1
  55. package/dist/lib/neurolink.d.ts +275 -2
  56. package/dist/lib/neurolink.js +596 -56
  57. package/dist/lib/providers/litellm.d.ts +10 -0
  58. package/dist/lib/providers/litellm.js +104 -2
  59. package/dist/lib/types/configTypes.d.ts +56 -0
  60. package/dist/lib/types/conversation.d.ts +2 -2
  61. package/dist/lib/types/generateTypes.d.ts +4 -0
  62. package/dist/lib/types/index.d.ts +2 -1
  63. package/dist/lib/types/modelTypes.d.ts +6 -6
  64. package/dist/lib/types/streamTypes.d.ts +2 -0
  65. package/dist/lib/types/tools.d.ts +2 -0
  66. package/dist/lib/utils/pricing.js +177 -17
  67. package/dist/lib/utils/schemaConversion.d.ts +6 -1
  68. package/dist/lib/utils/schemaConversion.js +50 -28
  69. package/dist/lib/workflow/config.d.ts +16 -16
  70. package/dist/mcp/agentExposure.d.ts +228 -0
  71. package/dist/mcp/agentExposure.js +356 -0
  72. package/dist/mcp/batching/index.d.ts +11 -0
  73. package/dist/mcp/batching/index.js +10 -0
  74. package/dist/mcp/batching/requestBatcher.d.ts +202 -0
  75. package/dist/mcp/batching/requestBatcher.js +441 -0
  76. package/dist/mcp/caching/index.d.ts +11 -0
  77. package/dist/mcp/caching/index.js +10 -0
  78. package/dist/mcp/caching/toolCache.d.ts +221 -0
  79. package/dist/mcp/caching/toolCache.js +433 -0
  80. package/dist/mcp/elicitation/elicitationManager.d.ts +169 -0
  81. package/dist/mcp/elicitation/elicitationManager.js +376 -0
  82. package/dist/mcp/elicitation/index.d.ts +11 -0
  83. package/dist/mcp/elicitation/index.js +11 -0
  84. package/dist/mcp/elicitation/types.d.ts +278 -0
  85. package/dist/mcp/elicitation/types.js +10 -0
  86. package/dist/mcp/elicitationProtocol.d.ts +228 -0
  87. package/dist/mcp/elicitationProtocol.js +375 -0
  88. package/dist/mcp/enhancedToolDiscovery.d.ts +205 -0
  89. package/dist/mcp/enhancedToolDiscovery.js +481 -0
  90. package/dist/mcp/index.d.ts +38 -1
  91. package/dist/mcp/index.js +36 -3
  92. package/dist/mcp/mcpRegistryClient.d.ts +332 -0
  93. package/dist/mcp/mcpRegistryClient.js +488 -0
  94. package/dist/mcp/mcpServerBase.d.ts +227 -0
  95. package/dist/mcp/mcpServerBase.js +373 -0
  96. package/dist/mcp/multiServerManager.d.ts +310 -0
  97. package/dist/mcp/multiServerManager.js +579 -0
  98. package/dist/mcp/routing/index.d.ts +11 -0
  99. package/dist/mcp/routing/index.js +10 -0
  100. package/dist/mcp/routing/toolRouter.d.ts +219 -0
  101. package/dist/mcp/routing/toolRouter.js +416 -0
  102. package/dist/mcp/serverCapabilities.d.ts +341 -0
  103. package/dist/mcp/serverCapabilities.js +502 -0
  104. package/dist/mcp/toolAnnotations.d.ts +154 -0
  105. package/dist/mcp/toolAnnotations.js +239 -0
  106. package/dist/mcp/toolConverter.d.ts +178 -0
  107. package/dist/mcp/toolConverter.js +258 -0
  108. package/dist/mcp/toolIntegration.d.ts +136 -0
  109. package/dist/mcp/toolIntegration.js +334 -0
  110. package/dist/memory/hippocampusInitializer.d.ts +2 -2
  111. package/dist/memory/hippocampusInitializer.js +1 -1
  112. package/dist/neurolink.d.ts +275 -2
  113. package/dist/neurolink.js +596 -56
  114. package/dist/providers/litellm.d.ts +10 -0
  115. package/dist/providers/litellm.js +104 -2
  116. package/dist/types/configTypes.d.ts +56 -0
  117. package/dist/types/conversation.d.ts +2 -2
  118. package/dist/types/generateTypes.d.ts +4 -0
  119. package/dist/types/index.d.ts +2 -1
  120. package/dist/types/streamTypes.d.ts +2 -0
  121. package/dist/types/tools.d.ts +2 -0
  122. package/dist/utils/pricing.js +177 -17
  123. package/dist/utils/schemaConversion.d.ts +6 -1
  124. package/dist/utils/schemaConversion.js +50 -28
  125. package/package.json +2 -2
@@ -0,0 +1,205 @@
1
+ /**
2
+ * Enhanced Tool Discovery Service
3
+ *
4
+ * Extends the base tool discovery service with additional features:
5
+ * - Tool annotation support
6
+ * - Multi-server coordination
7
+ * - Advanced filtering and search
8
+ * - Tool versioning and compatibility checking
9
+ *
10
+ * @module mcp/enhancedToolDiscovery
11
+ * @since 8.39.0
12
+ */
13
+ import { EventEmitter } from "events";
14
+ import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
15
+ import type { ExternalMCPToolInfo } from "../types/externalMcp.js";
16
+ import type { MCPServerInfo, ToolDiscoveryResult } from "../types/mcpTypes.js";
17
+ import type { JsonObject } from "../types/common.js";
18
+ import { type MCPToolAnnotations } from "./toolAnnotations.js";
19
+ import { MultiServerManager, type UnifiedTool } from "./multiServerManager.js";
20
+ /**
21
+ * Enhanced tool info with annotations
22
+ */
23
+ export type EnhancedToolInfo = ExternalMCPToolInfo & {
24
+ annotations?: MCPToolAnnotations;
25
+ version?: string;
26
+ compatibleWith?: string[];
27
+ aliases?: string[];
28
+ examples?: Array<{
29
+ name: string;
30
+ description: string;
31
+ params: JsonObject;
32
+ }>;
33
+ };
34
+ /**
35
+ * Tool search criteria
36
+ */
37
+ export type ToolSearchCriteria = {
38
+ /**
39
+ * Search by name (partial match)
40
+ */
41
+ name?: string;
42
+ /**
43
+ * Search by description (keyword match)
44
+ */
45
+ description?: string;
46
+ /**
47
+ * Filter by server IDs
48
+ */
49
+ serverIds?: string[];
50
+ /**
51
+ * Filter by category
52
+ */
53
+ category?: string;
54
+ /**
55
+ * Filter by tags
56
+ */
57
+ tags?: string[];
58
+ /**
59
+ * Filter by annotation flags
60
+ */
61
+ annotations?: Partial<MCPToolAnnotations>;
62
+ /**
63
+ * Include unavailable tools
64
+ */
65
+ includeUnavailable?: boolean;
66
+ /**
67
+ * Maximum results
68
+ */
69
+ limit?: number;
70
+ /**
71
+ * Sort by field
72
+ */
73
+ sortBy?: "name" | "calls" | "successRate" | "avgExecutionTime";
74
+ /**
75
+ * Sort direction
76
+ */
77
+ sortDirection?: "asc" | "desc";
78
+ };
79
+ /**
80
+ * Tool search result
81
+ */
82
+ export type ToolSearchResult = {
83
+ tools: EnhancedToolInfo[];
84
+ totalCount: number;
85
+ criteria: ToolSearchCriteria;
86
+ executionTime: number;
87
+ };
88
+ /**
89
+ * Tool compatibility check result
90
+ */
91
+ export type CompatibilityCheckResult = {
92
+ compatible: boolean;
93
+ issues: string[];
94
+ warnings: string[];
95
+ recommendations: string[];
96
+ };
97
+ /**
98
+ * Enhanced Tool Discovery Service
99
+ *
100
+ * Provides advanced tool discovery features including annotation support,
101
+ * multi-server coordination, and powerful search capabilities.
102
+ *
103
+ * @example
104
+ * ```typescript
105
+ * const discovery = new EnhancedToolDiscovery();
106
+ *
107
+ * // Discover tools with annotation inference
108
+ * const result = await discovery.discoverToolsWithAnnotations(
109
+ * "github-server",
110
+ * client,
111
+ * );
112
+ *
113
+ * // Search for tools
114
+ * const searchResult = await discovery.searchTools({
115
+ * category: "file-system",
116
+ * annotations: { readOnlyHint: true },
117
+ * limit: 10,
118
+ * });
119
+ *
120
+ * // Get tools by safety level
121
+ * const safeTools = discovery.getToolsBySafetyLevel("safe");
122
+ * ```
123
+ */
124
+ export declare class EnhancedToolDiscovery extends EventEmitter {
125
+ private toolRegistry;
126
+ private serverToolsMap;
127
+ private multiServerManager;
128
+ private discoveryInProgress;
129
+ constructor(multiServerManager?: MultiServerManager);
130
+ /**
131
+ * Discover tools with automatic annotation inference
132
+ */
133
+ discoverToolsWithAnnotations(serverId: string, client: Client, timeout?: number): Promise<ToolDiscoveryResult>;
134
+ /**
135
+ * Create enhanced tool info with annotations
136
+ */
137
+ private createEnhancedToolInfo;
138
+ /**
139
+ * Infer category from tool definition
140
+ */
141
+ private inferCategory;
142
+ /**
143
+ * Search tools with advanced criteria
144
+ */
145
+ searchTools(criteria: ToolSearchCriteria): ToolSearchResult;
146
+ /**
147
+ * Get tools by safety level
148
+ */
149
+ getToolsBySafetyLevel(level: "safe" | "moderate" | "dangerous"): EnhancedToolInfo[];
150
+ /**
151
+ * Get tools requiring confirmation
152
+ */
153
+ getToolsRequiringConfirmation(): EnhancedToolInfo[];
154
+ /**
155
+ * Get read-only tools
156
+ */
157
+ getReadOnlyTools(): EnhancedToolInfo[];
158
+ /**
159
+ * Get unified tools from all servers
160
+ */
161
+ getUnifiedTools(): UnifiedTool[];
162
+ /**
163
+ * Register a server with the multi-server manager
164
+ */
165
+ registerServer(server: MCPServerInfo): void;
166
+ /**
167
+ * Update tool annotations
168
+ */
169
+ updateToolAnnotations(serverId: string, toolName: string, annotations: Partial<MCPToolAnnotations>): boolean;
170
+ /**
171
+ * Check tool compatibility
172
+ */
173
+ checkCompatibility(toolName: string, serverId: string, targetVersion?: string): CompatibilityCheckResult;
174
+ /**
175
+ * Get tool by key
176
+ */
177
+ getTool(serverId: string, toolName: string): EnhancedToolInfo | undefined;
178
+ /**
179
+ * Get all tools
180
+ */
181
+ getAllTools(): EnhancedToolInfo[];
182
+ /**
183
+ * Get tools for a server
184
+ */
185
+ getServerTools(serverId: string): EnhancedToolInfo[];
186
+ /**
187
+ * Clear tools for a server
188
+ */
189
+ clearServerTools(serverId: string): void;
190
+ /**
191
+ * Create tool key
192
+ */
193
+ private createToolKey;
194
+ /**
195
+ * Get statistics
196
+ */
197
+ getStatistics(): {
198
+ totalTools: number;
199
+ toolsByServer: Record<string, number>;
200
+ toolsByCategory: Record<string, number>;
201
+ toolsBySafetyLevel: Record<string, number>;
202
+ toolsWithAnnotations: number;
203
+ deprecatedTools: number;
204
+ };
205
+ }
@@ -0,0 +1,482 @@
1
+ /**
2
+ * Enhanced Tool Discovery Service
3
+ *
4
+ * Extends the base tool discovery service with additional features:
5
+ * - Tool annotation support
6
+ * - Multi-server coordination
7
+ * - Advanced filtering and search
8
+ * - Tool versioning and compatibility checking
9
+ *
10
+ * @module mcp/enhancedToolDiscovery
11
+ * @since 8.39.0
12
+ */
13
+ import { EventEmitter } from "events";
14
+ import { logger } from "../utils/logger.js";
15
+ import { withTimeout } from "../utils/async/withTimeout.js";
16
+ import { ErrorFactory } from "../utils/errorHandling.js";
17
+ import { inferAnnotations, } from "./toolAnnotations.js";
18
+ import { MultiServerManager } from "./multiServerManager.js";
19
+ /**
20
+ * Enhanced Tool Discovery Service
21
+ *
22
+ * Provides advanced tool discovery features including annotation support,
23
+ * multi-server coordination, and powerful search capabilities.
24
+ *
25
+ * @example
26
+ * ```typescript
27
+ * const discovery = new EnhancedToolDiscovery();
28
+ *
29
+ * // Discover tools with annotation inference
30
+ * const result = await discovery.discoverToolsWithAnnotations(
31
+ * "github-server",
32
+ * client,
33
+ * );
34
+ *
35
+ * // Search for tools
36
+ * const searchResult = await discovery.searchTools({
37
+ * category: "file-system",
38
+ * annotations: { readOnlyHint: true },
39
+ * limit: 10,
40
+ * });
41
+ *
42
+ * // Get tools by safety level
43
+ * const safeTools = discovery.getToolsBySafetyLevel("safe");
44
+ * ```
45
+ */
46
+ export class EnhancedToolDiscovery extends EventEmitter {
47
+ toolRegistry = new Map();
48
+ serverToolsMap = new Map();
49
+ multiServerManager;
50
+ discoveryInProgress = new Set();
51
+ constructor(multiServerManager) {
52
+ super();
53
+ this.multiServerManager = multiServerManager ?? new MultiServerManager();
54
+ }
55
+ /**
56
+ * Discover tools with automatic annotation inference
57
+ */
58
+ async discoverToolsWithAnnotations(serverId, client, timeout = 10000) {
59
+ const startTime = Date.now();
60
+ if (this.discoveryInProgress.has(serverId)) {
61
+ return {
62
+ success: false,
63
+ error: `Discovery already in progress for server: ${serverId}`,
64
+ toolCount: 0,
65
+ tools: [],
66
+ duration: Date.now() - startTime,
67
+ serverId,
68
+ };
69
+ }
70
+ this.discoveryInProgress.add(serverId);
71
+ try {
72
+ logger.info(`[EnhancedToolDiscovery] Starting discovery with annotations for: ${serverId}`);
73
+ // List tools from server
74
+ const listResult = await withTimeout(client.listTools(), timeout, "Discovery timeout");
75
+ if (!listResult?.tools) {
76
+ throw ErrorFactory.toolExecutionFailed("discoverTools", new Error("No tools returned from server"), serverId);
77
+ }
78
+ // Clear existing tools for this server
79
+ this.clearServerTools(serverId);
80
+ const registeredTools = [];
81
+ for (const tool of listResult.tools) {
82
+ const enhancedTool = this.createEnhancedToolInfo(serverId, tool);
83
+ const toolKey = this.createToolKey(serverId, tool.name);
84
+ this.toolRegistry.set(toolKey, enhancedTool);
85
+ // Track server tools
86
+ let serverTools = this.serverToolsMap.get(serverId);
87
+ if (!serverTools) {
88
+ serverTools = new Set();
89
+ this.serverToolsMap.set(serverId, serverTools);
90
+ }
91
+ serverTools.add(tool.name);
92
+ registeredTools.push(enhancedTool);
93
+ this.emit("toolDiscovered", {
94
+ serverId,
95
+ toolName: tool.name,
96
+ annotations: enhancedTool.annotations,
97
+ timestamp: new Date(),
98
+ });
99
+ }
100
+ logger.info(`[EnhancedToolDiscovery] Discovered ${registeredTools.length} tools with annotations from ${serverId}`);
101
+ return {
102
+ success: true,
103
+ toolCount: registeredTools.length,
104
+ tools: registeredTools,
105
+ duration: Date.now() - startTime,
106
+ serverId,
107
+ };
108
+ }
109
+ catch (error) {
110
+ const errorMessage = error instanceof Error ? error.message : String(error);
111
+ logger.error(`[EnhancedToolDiscovery] Discovery failed for ${serverId}:`, error);
112
+ return {
113
+ success: false,
114
+ error: errorMessage,
115
+ toolCount: 0,
116
+ tools: [],
117
+ duration: Date.now() - startTime,
118
+ serverId,
119
+ };
120
+ }
121
+ finally {
122
+ this.discoveryInProgress.delete(serverId);
123
+ }
124
+ }
125
+ /**
126
+ * Create enhanced tool info with annotations
127
+ */
128
+ createEnhancedToolInfo(serverId, tool) {
129
+ // Infer annotations from tool definition
130
+ const annotations = inferAnnotations({
131
+ name: tool.name,
132
+ description: tool.description ?? "",
133
+ });
134
+ return {
135
+ name: tool.name,
136
+ description: tool.description ?? "No description provided",
137
+ serverId,
138
+ inputSchema: tool.inputSchema,
139
+ isAvailable: true,
140
+ annotations,
141
+ version: "1.0.0",
142
+ stats: {
143
+ totalCalls: 0,
144
+ successfulCalls: 0,
145
+ failedCalls: 0,
146
+ averageExecutionTime: 0,
147
+ lastExecutionTime: 0,
148
+ },
149
+ metadata: {
150
+ category: this.inferCategory(tool),
151
+ deprecated: false,
152
+ },
153
+ };
154
+ }
155
+ /**
156
+ * Infer category from tool definition
157
+ */
158
+ inferCategory(tool) {
159
+ const name = tool.name.toLowerCase();
160
+ const desc = (tool.description ?? "").toLowerCase();
161
+ if (name.includes("git") || desc.includes("git")) {
162
+ return "version-control";
163
+ }
164
+ if (name.includes("file") ||
165
+ name.includes("read") ||
166
+ name.includes("write")) {
167
+ return "file-system";
168
+ }
169
+ if (name.includes("api") || name.includes("http")) {
170
+ return "api";
171
+ }
172
+ if (name.includes("data") || name.includes("query")) {
173
+ return "data";
174
+ }
175
+ if (name.includes("auth") || name.includes("login")) {
176
+ return "authentication";
177
+ }
178
+ if (name.includes("deploy") || name.includes("build")) {
179
+ return "deployment";
180
+ }
181
+ return "general";
182
+ }
183
+ /**
184
+ * Search tools with advanced criteria
185
+ */
186
+ searchTools(criteria) {
187
+ const startTime = Date.now();
188
+ let results = Array.from(this.toolRegistry.values());
189
+ // Filter by name
190
+ if (criteria.name) {
191
+ const searchName = criteria.name.toLowerCase();
192
+ results = results.filter((tool) => tool.name.toLowerCase().includes(searchName));
193
+ }
194
+ // Filter by description
195
+ if (criteria.description) {
196
+ const keywords = criteria.description.toLowerCase().split(/\s+/);
197
+ results = results.filter((tool) => {
198
+ const desc = tool.description.toLowerCase();
199
+ return keywords.some((keyword) => desc.includes(keyword));
200
+ });
201
+ }
202
+ // Filter by server IDs
203
+ if (criteria.serverIds?.length) {
204
+ const serverIds = criteria.serverIds;
205
+ results = results.filter((tool) => serverIds.includes(tool.serverId));
206
+ }
207
+ // Filter by category
208
+ if (criteria.category) {
209
+ results = results.filter((tool) => tool.metadata?.category === criteria.category);
210
+ }
211
+ // Filter by tags
212
+ if (criteria.tags?.length) {
213
+ const tags = criteria.tags;
214
+ results = results.filter((tool) => {
215
+ const toolTags = tool.annotations?.tags ?? [];
216
+ return tags.some((tag) => toolTags.includes(tag));
217
+ });
218
+ }
219
+ // Filter by annotations
220
+ if (criteria.annotations) {
221
+ const annotations = criteria.annotations;
222
+ results = results.filter((tool) => {
223
+ if (!tool.annotations) {
224
+ return false;
225
+ }
226
+ for (const [key, value] of Object.entries(annotations)) {
227
+ const annotationKey = key;
228
+ if (tool.annotations[annotationKey] !== value) {
229
+ return false;
230
+ }
231
+ }
232
+ return true;
233
+ });
234
+ }
235
+ // Filter unavailable
236
+ if (!criteria.includeUnavailable) {
237
+ results = results.filter((tool) => tool.isAvailable);
238
+ }
239
+ // Sort results
240
+ if (criteria.sortBy) {
241
+ const direction = criteria.sortDirection === "desc" ? -1 : 1;
242
+ results.sort((a, b) => {
243
+ let comparison = 0;
244
+ switch (criteria.sortBy) {
245
+ case "name":
246
+ comparison = a.name.localeCompare(b.name);
247
+ break;
248
+ case "calls":
249
+ comparison = a.stats.totalCalls - b.stats.totalCalls;
250
+ break;
251
+ case "successRate": {
252
+ const rateA = a.stats.totalCalls > 0
253
+ ? a.stats.successfulCalls / a.stats.totalCalls
254
+ : 0;
255
+ const rateB = b.stats.totalCalls > 0
256
+ ? b.stats.successfulCalls / b.stats.totalCalls
257
+ : 0;
258
+ comparison = rateA - rateB;
259
+ break;
260
+ }
261
+ case "avgExecutionTime":
262
+ comparison =
263
+ a.stats.averageExecutionTime - b.stats.averageExecutionTime;
264
+ break;
265
+ }
266
+ return comparison * direction;
267
+ });
268
+ }
269
+ // Apply limit
270
+ const totalCount = results.length;
271
+ if (criteria.limit && criteria.limit > 0) {
272
+ results = results.slice(0, criteria.limit);
273
+ }
274
+ return {
275
+ tools: results,
276
+ totalCount,
277
+ criteria,
278
+ executionTime: Date.now() - startTime,
279
+ };
280
+ }
281
+ /**
282
+ * Get tools by safety level
283
+ */
284
+ getToolsBySafetyLevel(level) {
285
+ return Array.from(this.toolRegistry.values()).filter((tool) => {
286
+ const annotations = tool.annotations ?? {};
287
+ switch (level) {
288
+ case "dangerous":
289
+ return annotations.destructiveHint === true;
290
+ case "safe":
291
+ return annotations.readOnlyHint === true;
292
+ case "moderate":
293
+ return !annotations.destructiveHint && !annotations.readOnlyHint;
294
+ default:
295
+ return false;
296
+ }
297
+ });
298
+ }
299
+ /**
300
+ * Get tools requiring confirmation
301
+ */
302
+ getToolsRequiringConfirmation() {
303
+ return Array.from(this.toolRegistry.values()).filter((tool) => tool.annotations?.requiresConfirmation === true ||
304
+ tool.annotations?.destructiveHint === true);
305
+ }
306
+ /**
307
+ * Get read-only tools
308
+ */
309
+ getReadOnlyTools() {
310
+ return Array.from(this.toolRegistry.values()).filter((tool) => tool.annotations?.readOnlyHint === true);
311
+ }
312
+ /**
313
+ * Get unified tools from all servers
314
+ */
315
+ getUnifiedTools() {
316
+ return this.multiServerManager.getUnifiedTools();
317
+ }
318
+ /**
319
+ * Register a server with the multi-server manager
320
+ */
321
+ registerServer(server) {
322
+ this.multiServerManager.addServer(server);
323
+ }
324
+ /**
325
+ * Update tool annotations
326
+ */
327
+ updateToolAnnotations(serverId, toolName, annotations) {
328
+ const toolKey = this.createToolKey(serverId, toolName);
329
+ const tool = this.toolRegistry.get(toolKey);
330
+ if (!tool) {
331
+ return false;
332
+ }
333
+ tool.annotations = {
334
+ ...tool.annotations,
335
+ ...annotations,
336
+ };
337
+ this.emit("annotationsUpdated", {
338
+ serverId,
339
+ toolName,
340
+ annotations: tool.annotations,
341
+ timestamp: new Date(),
342
+ });
343
+ return true;
344
+ }
345
+ /**
346
+ * Check tool compatibility
347
+ */
348
+ checkCompatibility(toolName, serverId, targetVersion) {
349
+ const toolKey = this.createToolKey(serverId, toolName);
350
+ const tool = this.toolRegistry.get(toolKey);
351
+ const issues = [];
352
+ const warnings = [];
353
+ const recommendations = [];
354
+ if (!tool) {
355
+ return {
356
+ compatible: false,
357
+ issues: [`Tool '${toolName}' not found on server '${serverId}'`],
358
+ warnings: [],
359
+ recommendations: [],
360
+ };
361
+ }
362
+ // Check version compatibility
363
+ if (targetVersion && tool.version) {
364
+ const toolVersion = tool.version.split(".").map(Number);
365
+ const target = targetVersion.split(".").map(Number);
366
+ if (toolVersion.some(isNaN) || target.some(isNaN)) {
367
+ warnings.push(`Non-standard version format: tool=${tool.version}, target=${targetVersion}`);
368
+ }
369
+ else if (toolVersion[0] !== target[0]) {
370
+ issues.push(`Major version mismatch: tool is v${tool.version}, target is v${targetVersion}`);
371
+ }
372
+ else if (toolVersion[1] < target[1]) {
373
+ warnings.push(`Minor version mismatch: tool is v${tool.version}, target is v${targetVersion}`);
374
+ }
375
+ }
376
+ // Check if tool is deprecated
377
+ if (tool.metadata?.deprecated) {
378
+ warnings.push("This tool is marked as deprecated");
379
+ recommendations.push("Consider using an alternative tool if available");
380
+ }
381
+ // Check if tool requires authentication
382
+ if (tool.annotations?.securityLevel === "restricted") {
383
+ recommendations.push("This tool requires elevated permissions");
384
+ }
385
+ return {
386
+ compatible: issues.length === 0,
387
+ issues,
388
+ warnings,
389
+ recommendations,
390
+ };
391
+ }
392
+ /**
393
+ * Get tool by key
394
+ */
395
+ getTool(serverId, toolName) {
396
+ return this.toolRegistry.get(this.createToolKey(serverId, toolName));
397
+ }
398
+ /**
399
+ * Get all tools
400
+ */
401
+ getAllTools() {
402
+ return Array.from(this.toolRegistry.values());
403
+ }
404
+ /**
405
+ * Get tools for a server
406
+ */
407
+ getServerTools(serverId) {
408
+ const toolNames = this.serverToolsMap.get(serverId);
409
+ if (!toolNames) {
410
+ return [];
411
+ }
412
+ return Array.from(toolNames)
413
+ .map((name) => this.getTool(serverId, name))
414
+ .filter((tool) => tool !== undefined);
415
+ }
416
+ /**
417
+ * Clear tools for a server
418
+ */
419
+ clearServerTools(serverId) {
420
+ const toolNames = this.serverToolsMap.get(serverId);
421
+ if (toolNames) {
422
+ for (const toolName of toolNames) {
423
+ this.toolRegistry.delete(this.createToolKey(serverId, toolName));
424
+ }
425
+ this.serverToolsMap.delete(serverId);
426
+ }
427
+ }
428
+ /**
429
+ * Create tool key
430
+ */
431
+ createToolKey(serverId, toolName) {
432
+ return `${serverId}:${toolName}`;
433
+ }
434
+ /**
435
+ * Get statistics
436
+ */
437
+ getStatistics() {
438
+ const toolsByServer = {};
439
+ const toolsByCategory = {};
440
+ const toolsBySafetyLevel = {
441
+ safe: 0,
442
+ moderate: 0,
443
+ dangerous: 0,
444
+ };
445
+ let toolsWithAnnotations = 0;
446
+ let deprecatedTools = 0;
447
+ for (const tool of this.toolRegistry.values()) {
448
+ // By server
449
+ toolsByServer[tool.serverId] = (toolsByServer[tool.serverId] ?? 0) + 1;
450
+ // By category
451
+ const category = tool.metadata?.category ?? "general";
452
+ toolsByCategory[category] = (toolsByCategory[category] ?? 0) + 1;
453
+ // By safety level
454
+ if (tool.annotations?.destructiveHint) {
455
+ toolsBySafetyLevel.dangerous++;
456
+ }
457
+ else if (tool.annotations?.readOnlyHint) {
458
+ toolsBySafetyLevel.safe++;
459
+ }
460
+ else {
461
+ toolsBySafetyLevel.moderate++;
462
+ }
463
+ // Count annotations
464
+ if (tool.annotations && Object.keys(tool.annotations).length > 0) {
465
+ toolsWithAnnotations++;
466
+ }
467
+ // Count deprecated
468
+ if (tool.metadata?.deprecated) {
469
+ deprecatedTools++;
470
+ }
471
+ }
472
+ return {
473
+ totalTools: this.toolRegistry.size,
474
+ toolsByServer,
475
+ toolsByCategory,
476
+ toolsBySafetyLevel,
477
+ toolsWithAnnotations,
478
+ deprecatedTools,
479
+ };
480
+ }
481
+ }
482
+ //# sourceMappingURL=enhancedToolDiscovery.js.map