@juspay/neurolink 7.13.0 → 7.14.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 (132) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +89 -25
  3. package/dist/agent/directTools.d.ts +3 -3
  4. package/dist/agent/directTools.js +1 -1
  5. package/dist/cli/commands/mcp.js +67 -207
  6. package/dist/cli/factories/commandFactory.js +7 -1
  7. package/dist/cli/utils/interactiveSetup.js +1 -1
  8. package/dist/config/conversationMemoryConfig.js +2 -1
  9. package/dist/context/ContextManager.js +15 -4
  10. package/dist/context/config.js +5 -1
  11. package/dist/context/utils.js +1 -1
  12. package/dist/core/baseProvider.d.ts +11 -30
  13. package/dist/core/baseProvider.js +268 -42
  14. package/dist/core/conversationMemoryManager.js +3 -2
  15. package/dist/core/dynamicModels.d.ts +14 -14
  16. package/dist/core/dynamicModels.js +1 -1
  17. package/dist/core/evaluation.js +1 -1
  18. package/dist/core/factory.js +1 -1
  19. package/dist/factories/providerFactory.js +5 -11
  20. package/dist/factories/providerRegistry.js +2 -2
  21. package/dist/index.d.ts +5 -4
  22. package/dist/index.js +1 -1
  23. package/dist/lib/agent/directTools.js +1 -1
  24. package/dist/lib/config/conversationMemoryConfig.js +2 -1
  25. package/dist/lib/context/ContextManager.js +15 -4
  26. package/dist/lib/context/config.js +5 -1
  27. package/dist/lib/context/utils.js +1 -1
  28. package/dist/lib/core/baseProvider.d.ts +11 -30
  29. package/dist/lib/core/baseProvider.js +268 -42
  30. package/dist/lib/core/conversationMemoryManager.js +3 -2
  31. package/dist/lib/core/dynamicModels.js +1 -1
  32. package/dist/lib/core/evaluation.js +1 -1
  33. package/dist/lib/core/factory.js +1 -1
  34. package/dist/lib/factories/providerFactory.js +5 -11
  35. package/dist/lib/factories/providerRegistry.js +2 -2
  36. package/dist/lib/index.d.ts +5 -4
  37. package/dist/lib/index.js +1 -1
  38. package/dist/lib/mcp/externalServerManager.d.ts +148 -0
  39. package/dist/lib/mcp/externalServerManager.js +1038 -0
  40. package/dist/lib/mcp/mcpCircuitBreaker.d.ts +184 -0
  41. package/dist/lib/mcp/mcpCircuitBreaker.js +338 -0
  42. package/dist/lib/mcp/mcpClientFactory.d.ts +105 -0
  43. package/dist/lib/mcp/mcpClientFactory.js +421 -0
  44. package/dist/lib/mcp/toolDiscoveryService.d.ts +193 -0
  45. package/dist/lib/mcp/toolDiscoveryService.js +646 -0
  46. package/dist/lib/mcp/toolRegistry.d.ts +15 -11
  47. package/dist/lib/mcp/toolRegistry.js +118 -55
  48. package/dist/lib/models/modelResolver.js +1 -1
  49. package/dist/lib/neurolink.d.ts +139 -43
  50. package/dist/lib/neurolink.js +604 -174
  51. package/dist/lib/providers/googleVertex.d.ts +7 -1
  52. package/dist/lib/providers/googleVertex.js +34 -7
  53. package/dist/lib/providers/huggingFace.js +1 -1
  54. package/dist/lib/providers/mistral.js +3 -3
  55. package/dist/lib/providers/ollama.js +1 -1
  56. package/dist/lib/providers/openAI.d.ts +3 -2
  57. package/dist/lib/providers/openAI.js +2 -2
  58. package/dist/lib/providers/openaiCompatible.d.ts +1 -1
  59. package/dist/lib/providers/openaiCompatible.js +2 -2
  60. package/dist/lib/providers/sagemaker/config.js +1 -1
  61. package/dist/lib/sdk/toolRegistration.d.ts +4 -13
  62. package/dist/lib/sdk/toolRegistration.js +19 -66
  63. package/dist/lib/types/cli.d.ts +0 -1
  64. package/dist/lib/types/cli.js +0 -1
  65. package/dist/lib/types/common.d.ts +1 -2
  66. package/dist/lib/types/common.js +0 -1
  67. package/dist/lib/types/contextTypes.d.ts +1 -1
  68. package/dist/lib/types/contextTypes.js +3 -3
  69. package/dist/lib/types/externalMcp.d.ts +288 -0
  70. package/dist/lib/types/externalMcp.js +7 -0
  71. package/dist/lib/types/generateTypes.d.ts +0 -1
  72. package/dist/lib/types/index.d.ts +2 -2
  73. package/dist/lib/types/index.js +0 -1
  74. package/dist/lib/types/mcpTypes.d.ts +53 -99
  75. package/dist/lib/types/providers.d.ts +0 -1
  76. package/dist/lib/types/providers.js +0 -1
  77. package/dist/lib/types/tools.d.ts +2 -2
  78. package/dist/lib/types/tools.js +2 -2
  79. package/dist/lib/utils/factoryProcessing.js +1 -1
  80. package/dist/lib/utils/mcpDefaults.d.ts +54 -0
  81. package/dist/lib/utils/mcpDefaults.js +125 -0
  82. package/dist/lib/utils/providerConfig.d.ts +1 -1
  83. package/dist/lib/utils/providerConfig.js +2 -2
  84. package/dist/lib/utils/providerHealth.js +6 -6
  85. package/dist/mcp/externalServerManager.d.ts +148 -0
  86. package/dist/mcp/externalServerManager.js +1038 -0
  87. package/dist/mcp/mcpCircuitBreaker.d.ts +184 -0
  88. package/dist/mcp/mcpCircuitBreaker.js +338 -0
  89. package/dist/mcp/mcpClientFactory.d.ts +105 -0
  90. package/dist/mcp/mcpClientFactory.js +421 -0
  91. package/dist/mcp/toolDiscoveryService.d.ts +193 -0
  92. package/dist/mcp/toolDiscoveryService.js +646 -0
  93. package/dist/mcp/toolRegistry.d.ts +15 -11
  94. package/dist/mcp/toolRegistry.js +118 -55
  95. package/dist/models/modelResolver.js +1 -1
  96. package/dist/neurolink.d.ts +139 -43
  97. package/dist/neurolink.js +604 -174
  98. package/dist/providers/googleVertex.d.ts +7 -1
  99. package/dist/providers/googleVertex.js +34 -7
  100. package/dist/providers/huggingFace.js +1 -1
  101. package/dist/providers/mistral.js +3 -3
  102. package/dist/providers/ollama.js +1 -1
  103. package/dist/providers/openAI.d.ts +3 -2
  104. package/dist/providers/openAI.js +2 -2
  105. package/dist/providers/openaiCompatible.d.ts +1 -1
  106. package/dist/providers/openaiCompatible.js +2 -2
  107. package/dist/providers/sagemaker/config.js +1 -1
  108. package/dist/sdk/toolRegistration.d.ts +4 -13
  109. package/dist/sdk/toolRegistration.js +19 -66
  110. package/dist/types/cli.d.ts +0 -1
  111. package/dist/types/cli.js +0 -1
  112. package/dist/types/common.d.ts +1 -2
  113. package/dist/types/common.js +0 -1
  114. package/dist/types/contextTypes.d.ts +1 -1
  115. package/dist/types/contextTypes.js +3 -3
  116. package/dist/types/externalMcp.d.ts +288 -0
  117. package/dist/types/externalMcp.js +7 -0
  118. package/dist/types/generateTypes.d.ts +0 -1
  119. package/dist/types/index.d.ts +2 -2
  120. package/dist/types/index.js +0 -1
  121. package/dist/types/mcpTypes.d.ts +53 -99
  122. package/dist/types/providers.d.ts +0 -1
  123. package/dist/types/providers.js +0 -1
  124. package/dist/types/tools.d.ts +2 -2
  125. package/dist/types/tools.js +2 -2
  126. package/dist/utils/factoryProcessing.js +1 -1
  127. package/dist/utils/mcpDefaults.d.ts +54 -0
  128. package/dist/utils/mcpDefaults.js +125 -0
  129. package/dist/utils/providerConfig.d.ts +1 -1
  130. package/dist/utils/providerConfig.js +2 -2
  131. package/dist/utils/providerHealth.js +6 -6
  132. package/package.json +1 -1
@@ -0,0 +1,1038 @@
1
+ /**
2
+ * External MCP Server Manager
3
+ * Handles lifecycle management of external MCP servers including:
4
+ * - Process spawning and management
5
+ * - Health monitoring and automatic restart
6
+ * - Connection management and cleanup
7
+ * - Tool discovery and registration
8
+ */
9
+ import { EventEmitter } from "events";
10
+ import { mcpLogger } from "../utils/logger.js";
11
+ import { MCPClientFactory } from "./mcpClientFactory.js";
12
+ import { ToolDiscoveryService } from "./toolDiscoveryService.js";
13
+ import { toolRegistry } from "./toolRegistry.js";
14
+ import { detectCategory } from "../utils/mcpDefaults.js";
15
+ /**
16
+ * Type guard to validate if an object can be safely used as Record<string, JsonValue>
17
+ */
18
+ function isValidJsonRecord(value) {
19
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
20
+ return false;
21
+ }
22
+ const record = value;
23
+ return Object.values(record).every((val) => {
24
+ // JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue }
25
+ if (val === null ||
26
+ typeof val === "string" ||
27
+ typeof val === "number" ||
28
+ typeof val === "boolean") {
29
+ return true;
30
+ }
31
+ if (Array.isArray(val)) {
32
+ return val.every((item) => isValidJsonRecord(item) ||
33
+ typeof item === "string" ||
34
+ typeof item === "number" ||
35
+ typeof item === "boolean" ||
36
+ item === null);
37
+ }
38
+ if (typeof val === "object" && val !== null) {
39
+ return isValidJsonRecord(val);
40
+ }
41
+ return false;
42
+ });
43
+ }
44
+ /**
45
+ * Safely converts unknown metadata to Record<string, JsonValue> or returns undefined
46
+ */
47
+ function safeMetadataConversion(metadata) {
48
+ return isValidJsonRecord(metadata) ? metadata : undefined;
49
+ }
50
+ /**
51
+ * Type guard to validate external MCP server configuration
52
+ */
53
+ function isValidExternalMCPServerConfig(config) {
54
+ if (typeof config !== "object" || config === null) {
55
+ return false;
56
+ }
57
+ const record = config;
58
+ return (typeof record.command === "string" &&
59
+ (record.args === undefined || Array.isArray(record.args)) &&
60
+ (record.env === undefined ||
61
+ (typeof record.env === "object" && record.env !== null)) &&
62
+ (record.transport === undefined || typeof record.transport === "string") &&
63
+ (record.timeout === undefined || typeof record.timeout === "number") &&
64
+ (record.retries === undefined || typeof record.retries === "number") &&
65
+ (record.healthCheckInterval === undefined ||
66
+ typeof record.healthCheckInterval === "number") &&
67
+ (record.autoRestart === undefined ||
68
+ typeof record.autoRestart === "boolean") &&
69
+ (record.cwd === undefined || typeof record.cwd === "string") &&
70
+ (record.url === undefined || typeof record.url === "string") &&
71
+ (record.metadata === undefined ||
72
+ (typeof record.metadata === "object" && record.metadata !== null)));
73
+ }
74
+ export class ExternalServerManager extends EventEmitter {
75
+ servers = new Map();
76
+ config;
77
+ isShuttingDown = false;
78
+ toolDiscovery;
79
+ enableMainRegistryIntegration;
80
+ constructor(config = {}, options = {}) {
81
+ super();
82
+ // Set defaults for configuration
83
+ this.config = {
84
+ maxServers: config.maxServers ?? 10,
85
+ defaultTimeout: config.defaultTimeout ?? 10000,
86
+ defaultHealthCheckInterval: config.defaultHealthCheckInterval ?? 30000,
87
+ enableAutoRestart: config.enableAutoRestart ?? true,
88
+ maxRestartAttempts: config.maxRestartAttempts ?? 3,
89
+ restartBackoffMultiplier: config.restartBackoffMultiplier ?? 2,
90
+ enablePerformanceMonitoring: config.enablePerformanceMonitoring ?? true,
91
+ logLevel: config.logLevel ?? "info",
92
+ };
93
+ // Enable main tool registry integration by default
94
+ this.enableMainRegistryIntegration =
95
+ options.enableMainRegistryIntegration ?? true;
96
+ // Initialize tool discovery service
97
+ this.toolDiscovery = new ToolDiscoveryService();
98
+ // Forward tool discovery events
99
+ this.toolDiscovery.on("toolRegistered", (event) => {
100
+ this.emit("toolDiscovered", event);
101
+ });
102
+ this.toolDiscovery.on("toolUnregistered", (event) => {
103
+ this.emit("toolRemoved", event);
104
+ });
105
+ // Handle process cleanup
106
+ process.on("SIGINT", () => this.shutdown());
107
+ process.on("SIGTERM", () => this.shutdown());
108
+ process.on("beforeExit", () => this.shutdown());
109
+ }
110
+ /**
111
+ * Load MCP server configurations from .mcp-config.json file
112
+ * Automatically registers servers found in the configuration
113
+ * @param configPath Optional path to config file (defaults to .mcp-config.json in cwd)
114
+ * @returns Promise resolving to number of servers loaded
115
+ */
116
+ async loadMCPConfiguration(configPath) {
117
+ const fs = await import("fs");
118
+ const path = await import("path");
119
+ const finalConfigPath = configPath || path.join(process.cwd(), ".mcp-config.json");
120
+ if (!fs.existsSync(finalConfigPath)) {
121
+ mcpLogger.debug(`[ExternalServerManager] No MCP config found at ${finalConfigPath}`);
122
+ return { serversLoaded: 0, errors: [] };
123
+ }
124
+ mcpLogger.debug(`[ExternalServerManager] Loading MCP configuration from ${finalConfigPath}`);
125
+ try {
126
+ const configContent = fs.readFileSync(finalConfigPath, "utf8");
127
+ const config = JSON.parse(configContent);
128
+ if (!config.mcpServers || typeof config.mcpServers !== "object") {
129
+ mcpLogger.debug("[ExternalServerManager] No mcpServers found in configuration");
130
+ return { serversLoaded: 0, errors: [] };
131
+ }
132
+ let serversLoaded = 0;
133
+ const errors = [];
134
+ for (const [serverId, serverConfig] of Object.entries(config.mcpServers)) {
135
+ try {
136
+ // Validate and convert config format to MCPServerInfo
137
+ if (!isValidExternalMCPServerConfig(serverConfig)) {
138
+ throw new Error(`Invalid server config for ${serverId}: missing required properties or wrong types`);
139
+ }
140
+ const externalConfig = {
141
+ id: serverId,
142
+ name: serverId,
143
+ description: `External MCP server: ${serverId}`,
144
+ transport: typeof serverConfig.transport === "string"
145
+ ? serverConfig.transport
146
+ : "stdio",
147
+ status: "initializing",
148
+ tools: [],
149
+ command: serverConfig.command,
150
+ args: Array.isArray(serverConfig.args)
151
+ ? serverConfig.args
152
+ : [],
153
+ env: typeof serverConfig.env === "object" && serverConfig.env !== null
154
+ ? serverConfig.env
155
+ : {},
156
+ timeout: typeof serverConfig.timeout === "number"
157
+ ? serverConfig.timeout
158
+ : undefined,
159
+ retries: typeof serverConfig.retries === "number"
160
+ ? serverConfig.retries
161
+ : undefined,
162
+ healthCheckInterval: typeof serverConfig.healthCheckInterval === "number"
163
+ ? serverConfig.healthCheckInterval
164
+ : undefined,
165
+ autoRestart: typeof serverConfig.autoRestart === "boolean"
166
+ ? serverConfig.autoRestart
167
+ : undefined,
168
+ cwd: typeof serverConfig.cwd === "string"
169
+ ? serverConfig.cwd
170
+ : undefined,
171
+ url: typeof serverConfig.url === "string"
172
+ ? serverConfig.url
173
+ : undefined,
174
+ metadata: safeMetadataConversion(serverConfig.metadata),
175
+ };
176
+ const result = await this.addServer(serverId, externalConfig);
177
+ if (result.success) {
178
+ serversLoaded++;
179
+ mcpLogger.debug(`[ExternalServerManager] Successfully loaded MCP server: ${serverId}`);
180
+ }
181
+ else {
182
+ const error = `Failed to load server ${serverId}: ${result.error}`;
183
+ errors.push(error);
184
+ mcpLogger.warn(`[ExternalServerManager] ${error}`);
185
+ }
186
+ }
187
+ catch (error) {
188
+ const errorMsg = `Failed to load MCP server ${serverId}: ${error instanceof Error ? error.message : String(error)}`;
189
+ errors.push(errorMsg);
190
+ mcpLogger.warn(`[ExternalServerManager] ${errorMsg}`);
191
+ // Continue with other servers - don't let one failure break everything
192
+ }
193
+ }
194
+ mcpLogger.info(`[ExternalServerManager] MCP configuration loading complete: ${serversLoaded} servers loaded, ${errors.length} errors`);
195
+ return { serversLoaded, errors };
196
+ }
197
+ catch (error) {
198
+ const errorMsg = `Failed to load MCP configuration: ${error instanceof Error ? error.message : String(error)}`;
199
+ mcpLogger.error(`[ExternalServerManager] ${errorMsg}`);
200
+ return { serversLoaded: 0, errors: [errorMsg] };
201
+ }
202
+ }
203
+ /**
204
+ * Validate external MCP server configuration
205
+ */
206
+ validateConfig(config) {
207
+ const errors = [];
208
+ const warnings = [];
209
+ const suggestions = [];
210
+ // Required fields validation
211
+ if (!config.id || typeof config.id !== "string") {
212
+ errors.push("Server ID is required and must be a string");
213
+ }
214
+ if (!config.command || typeof config.command !== "string") {
215
+ errors.push("Command is required and must be a string");
216
+ }
217
+ if (!Array.isArray(config.args)) {
218
+ errors.push("Args must be an array");
219
+ }
220
+ if (!["stdio", "sse", "websocket"].includes(config.transport)) {
221
+ errors.push("Transport must be one of: stdio, sse, websocket");
222
+ }
223
+ // URL validation for non-stdio transports
224
+ if ((config.transport === "sse" || config.transport === "websocket") &&
225
+ !config.url) {
226
+ errors.push(`URL is required for ${config.transport} transport`);
227
+ }
228
+ // Warnings for common issues
229
+ if (config.timeout && config.timeout < 5000) {
230
+ warnings.push("Timeout less than 5 seconds may cause connection issues");
231
+ }
232
+ if (config.retries && config.retries > 5) {
233
+ warnings.push("High retry count may slow down error recovery");
234
+ }
235
+ // Suggestions for optimization
236
+ if (!config.healthCheckInterval) {
237
+ suggestions.push("Consider setting a health check interval for better reliability");
238
+ }
239
+ if (config.autoRestart === undefined) {
240
+ suggestions.push("Consider enabling auto-restart for production use");
241
+ }
242
+ return {
243
+ isValid: errors.length === 0,
244
+ errors,
245
+ warnings,
246
+ suggestions,
247
+ };
248
+ }
249
+ /**
250
+ * Convert MCPServerInfo format (keeping for backward compatibility)
251
+ * Helper function for transitioning to zero-conversion architecture
252
+ */
253
+ convertConfigToMCPServerInfo(serverId, config) {
254
+ return {
255
+ id: serverId,
256
+ name: String(config.metadata?.title || serverId),
257
+ description: `External MCP server (${config.transport})`,
258
+ status: "initializing",
259
+ transport: config.transport,
260
+ command: config.command,
261
+ args: config.args,
262
+ env: config.env,
263
+ tools: [], // Will be populated after server connection
264
+ metadata: {
265
+ category: "external",
266
+ // Store additional ExternalMCPServerConfig fields in metadata
267
+ timeout: config.timeout,
268
+ retries: config.retries,
269
+ healthCheckInterval: config.healthCheckInterval,
270
+ autoRestart: config.autoRestart,
271
+ cwd: config.cwd,
272
+ url: config.url,
273
+ ...(safeMetadataConversion(config.metadata) || {}),
274
+ },
275
+ };
276
+ }
277
+ async addServer(serverId, configOrServerInfo) {
278
+ const startTime = Date.now();
279
+ try {
280
+ // Use MCPServerInfo directly (zero-conversion architecture)
281
+ const serverInfo = "transport" in configOrServerInfo &&
282
+ "command" in configOrServerInfo &&
283
+ !("tools" in configOrServerInfo)
284
+ ? this.convertConfigToMCPServerInfo(serverId, configOrServerInfo)
285
+ : configOrServerInfo;
286
+ // Check server limit
287
+ if (this.servers.size >= this.config.maxServers) {
288
+ return {
289
+ success: false,
290
+ error: `Maximum number of servers (${this.config.maxServers}) reached`,
291
+ serverId,
292
+ duration: Date.now() - startTime,
293
+ };
294
+ }
295
+ // Validate configuration (for backward compatibility, create temporary config)
296
+ const tempConfig = {
297
+ id: serverId,
298
+ name: serverInfo.name,
299
+ description: serverInfo.description,
300
+ transport: serverInfo.transport,
301
+ status: serverInfo.status,
302
+ tools: serverInfo.tools,
303
+ command: serverInfo.command || "",
304
+ args: serverInfo.args || [],
305
+ env: serverInfo.env || {},
306
+ timeout: serverInfo.metadata?.timeout,
307
+ retries: serverInfo.metadata?.retries,
308
+ healthCheckInterval: serverInfo.metadata?.healthCheckInterval,
309
+ autoRestart: serverInfo.metadata?.autoRestart,
310
+ cwd: serverInfo.metadata?.cwd,
311
+ url: serverInfo.metadata?.url,
312
+ metadata: safeMetadataConversion(serverInfo.metadata),
313
+ };
314
+ const validation = this.validateConfig(tempConfig);
315
+ if (!validation.isValid) {
316
+ return {
317
+ success: false,
318
+ error: `Configuration validation failed: ${validation.errors.join(", ")}`,
319
+ serverId,
320
+ duration: Date.now() - startTime,
321
+ };
322
+ }
323
+ // Check for duplicate server ID
324
+ if (this.servers.has(serverId)) {
325
+ return {
326
+ success: false,
327
+ error: `Server with ID '${serverId}' already exists`,
328
+ serverId,
329
+ duration: Date.now() - startTime,
330
+ };
331
+ }
332
+ mcpLogger.info(`[ExternalServerManager] Adding server: ${serverId}`, {
333
+ command: serverInfo.command,
334
+ transport: serverInfo.transport,
335
+ });
336
+ // Create server instance as RuntimeMCPServerInfo (transition to zero-conversion)
337
+ const instance = {
338
+ ...serverInfo,
339
+ process: null,
340
+ client: null,
341
+ transportInstance: null,
342
+ status: "initializing",
343
+ reconnectAttempts: 0,
344
+ maxReconnectAttempts: this.config.maxRestartAttempts,
345
+ toolsMap: new Map(),
346
+ metrics: {
347
+ totalConnections: 0,
348
+ totalDisconnections: 0,
349
+ totalErrors: 0,
350
+ totalToolCalls: 0,
351
+ averageResponseTime: 0,
352
+ lastResponseTime: 0,
353
+ },
354
+ config: tempConfig,
355
+ };
356
+ // Store the instance
357
+ this.servers.set(serverId, instance);
358
+ // Start the server
359
+ await this.startServer(serverId);
360
+ const finalInstance = this.servers.get(serverId);
361
+ // Convert RuntimeMCPServerInfo to ExternalMCPServerInstance for return
362
+ const convertedInstance = {
363
+ config: finalInstance.config,
364
+ process: finalInstance.process,
365
+ client: finalInstance.client,
366
+ transport: finalInstance.transportInstance,
367
+ status: finalInstance.status,
368
+ lastError: finalInstance.lastError,
369
+ startTime: finalInstance.startTime,
370
+ lastHealthCheck: finalInstance.lastHealthCheck,
371
+ reconnectAttempts: finalInstance.reconnectAttempts,
372
+ maxReconnectAttempts: finalInstance.maxReconnectAttempts,
373
+ tools: finalInstance.toolsMap,
374
+ toolsArray: finalInstance.toolsArray,
375
+ capabilities: finalInstance.capabilities,
376
+ healthTimer: finalInstance.healthTimer,
377
+ restartTimer: finalInstance.restartTimer,
378
+ metrics: finalInstance.metrics,
379
+ };
380
+ return {
381
+ success: true,
382
+ data: convertedInstance,
383
+ serverId,
384
+ duration: Date.now() - startTime,
385
+ metadata: {
386
+ timestamp: Date.now(),
387
+ operation: "addServer",
388
+ toolsDiscovered: finalInstance.tools.length,
389
+ },
390
+ };
391
+ }
392
+ catch (error) {
393
+ mcpLogger.error(`[ExternalServerManager] Failed to add server ${serverId}:`, error);
394
+ // Clean up if instance was created
395
+ this.servers.delete(serverId);
396
+ return {
397
+ success: false,
398
+ error: error instanceof Error ? error.message : String(error),
399
+ serverId,
400
+ duration: Date.now() - startTime,
401
+ };
402
+ }
403
+ }
404
+ /**
405
+ * Remove an external MCP server
406
+ */
407
+ async removeServer(serverId) {
408
+ const startTime = Date.now();
409
+ try {
410
+ const instance = this.servers.get(serverId);
411
+ if (!instance) {
412
+ return {
413
+ success: false,
414
+ error: `Server '${serverId}' not found`,
415
+ serverId,
416
+ duration: Date.now() - startTime,
417
+ };
418
+ }
419
+ mcpLogger.info(`[ExternalServerManager] Removing server: ${serverId}`);
420
+ // Stop the server
421
+ await this.stopServer(serverId);
422
+ // Remove from registry
423
+ this.servers.delete(serverId);
424
+ // Emit event
425
+ this.emit("disconnected", {
426
+ serverId,
427
+ reason: "Manually removed",
428
+ timestamp: new Date(),
429
+ });
430
+ return {
431
+ success: true,
432
+ serverId,
433
+ duration: Date.now() - startTime,
434
+ metadata: {
435
+ timestamp: Date.now(),
436
+ operation: "removeServer",
437
+ },
438
+ };
439
+ }
440
+ catch (error) {
441
+ mcpLogger.error(`[ExternalServerManager] Failed to remove server ${serverId}:`, error);
442
+ return {
443
+ success: false,
444
+ error: error instanceof Error ? error.message : String(error),
445
+ serverId,
446
+ duration: Date.now() - startTime,
447
+ };
448
+ }
449
+ }
450
+ /**
451
+ * Start an external MCP server
452
+ */
453
+ async startServer(serverId) {
454
+ const instance = this.servers.get(serverId);
455
+ if (!instance) {
456
+ throw new Error(`Server '${serverId}' not found`);
457
+ }
458
+ const config = instance.config;
459
+ try {
460
+ this.updateServerStatus(serverId, "connecting");
461
+ mcpLogger.debug(`[ExternalServerManager] Starting server: ${serverId}`, {
462
+ command: config.command,
463
+ args: config.args,
464
+ transport: config.transport,
465
+ });
466
+ // Create MCP client using the factory
467
+ const clientResult = await MCPClientFactory.createClient(config, config.timeout || this.config.defaultTimeout);
468
+ if (!clientResult.success ||
469
+ !clientResult.client ||
470
+ !clientResult.transport) {
471
+ throw new Error(`Failed to create MCP client: ${clientResult.error}`);
472
+ }
473
+ // Store client components
474
+ instance.client = clientResult.client;
475
+ instance.transportInstance = clientResult.transport;
476
+ instance.process = clientResult.process || null;
477
+ instance.capabilities = safeMetadataConversion(clientResult.capabilities);
478
+ instance.startTime = new Date();
479
+ instance.lastHealthCheck = new Date();
480
+ instance.metrics.totalConnections++;
481
+ // Handle process events if there's a process
482
+ if (instance.process) {
483
+ instance.process.on("error", (error) => {
484
+ mcpLogger.error(`[ExternalServerManager] Process error for ${serverId}:`, error);
485
+ this.handleServerError(serverId, error);
486
+ });
487
+ instance.process.on("exit", (code, signal) => {
488
+ mcpLogger.warn(`[ExternalServerManager] Process exited for ${serverId}`, {
489
+ code,
490
+ signal,
491
+ });
492
+ this.handleServerDisconnection(serverId, `Process exited with code ${code}`);
493
+ });
494
+ // Log stderr for debugging
495
+ instance.process.stderr?.on("data", (data) => {
496
+ const message = data.toString().trim();
497
+ if (message) {
498
+ mcpLogger.debug(`[ExternalServerManager] ${serverId} stderr:`, message);
499
+ }
500
+ });
501
+ }
502
+ this.updateServerStatus(serverId, "connected");
503
+ // Discover tools from the server
504
+ await this.discoverServerTools(serverId);
505
+ // Register tools with main registry if integration is enabled
506
+ if (this.enableMainRegistryIntegration) {
507
+ await this.registerServerToolsWithMainRegistry(serverId);
508
+ }
509
+ // Start health monitoring
510
+ this.startHealthMonitoring(serverId);
511
+ // Emit connected event
512
+ this.emit("connected", {
513
+ serverId,
514
+ toolCount: instance.toolsMap.size,
515
+ timestamp: new Date(),
516
+ });
517
+ mcpLogger.info(`[ExternalServerManager] Server started successfully: ${serverId}`);
518
+ }
519
+ catch (error) {
520
+ mcpLogger.error(`[ExternalServerManager] Failed to start server ${serverId}:`, error);
521
+ this.updateServerStatus(serverId, "failed");
522
+ instance.lastError =
523
+ error instanceof Error ? error.message : String(error);
524
+ throw error;
525
+ }
526
+ }
527
+ /**
528
+ * Stop an external MCP server
529
+ */
530
+ async stopServer(serverId) {
531
+ const instance = this.servers.get(serverId);
532
+ if (!instance) {
533
+ return;
534
+ }
535
+ try {
536
+ this.updateServerStatus(serverId, "stopping");
537
+ // Clear timers
538
+ if (instance.healthTimer) {
539
+ clearInterval(instance.healthTimer);
540
+ instance.healthTimer = undefined;
541
+ }
542
+ if (instance.restartTimer) {
543
+ clearTimeout(instance.restartTimer);
544
+ instance.restartTimer = undefined;
545
+ }
546
+ // Unregister tools from main registry if integration is enabled
547
+ if (this.enableMainRegistryIntegration) {
548
+ this.unregisterServerToolsFromMainRegistry(serverId);
549
+ }
550
+ // Clear server tools from discovery service
551
+ this.toolDiscovery.clearServerTools(serverId);
552
+ // Close MCP client using factory cleanup
553
+ if (instance.client && instance.transportInstance) {
554
+ try {
555
+ await MCPClientFactory.closeClient(instance.client, instance.transportInstance, instance.process || undefined);
556
+ }
557
+ catch (error) {
558
+ mcpLogger.debug(`[ExternalServerManager] Error closing client for ${serverId}:`, error);
559
+ }
560
+ instance.client = null;
561
+ instance.transportInstance = null;
562
+ instance.process = null;
563
+ }
564
+ this.updateServerStatus(serverId, "stopped");
565
+ mcpLogger.info(`[ExternalServerManager] Server stopped: ${serverId}`);
566
+ }
567
+ catch (error) {
568
+ mcpLogger.error(`[ExternalServerManager] Error stopping server ${serverId}:`, error);
569
+ this.updateServerStatus(serverId, "failed");
570
+ }
571
+ }
572
+ /**
573
+ * Update server status and emit events
574
+ */
575
+ updateServerStatus(serverId, newStatus) {
576
+ const instance = this.servers.get(serverId);
577
+ if (!instance) {
578
+ return;
579
+ }
580
+ const oldStatus = instance.status;
581
+ // Map ExternalMCPServerStatus to MCPServerInfo status
582
+ const mappedStatus = newStatus === "connecting" || newStatus === "restarting"
583
+ ? "initializing"
584
+ : newStatus === "stopping" || newStatus === "stopped"
585
+ ? "stopping"
586
+ : newStatus === "connected"
587
+ ? "connected"
588
+ : newStatus === "disconnected"
589
+ ? "disconnected"
590
+ : "failed";
591
+ instance.status = mappedStatus;
592
+ // Emit status change event
593
+ this.emit("statusChanged", {
594
+ serverId,
595
+ oldStatus,
596
+ newStatus,
597
+ timestamp: new Date(),
598
+ });
599
+ mcpLogger.debug(`[ExternalServerManager] Status changed for ${serverId}: ${oldStatus} -> ${newStatus}`);
600
+ }
601
+ /**
602
+ * Handle server errors
603
+ */
604
+ handleServerError(serverId, error) {
605
+ const instance = this.servers.get(serverId);
606
+ if (!instance) {
607
+ return;
608
+ }
609
+ instance.lastError = error.message;
610
+ instance.metrics.totalErrors++;
611
+ mcpLogger.error(`[ExternalServerManager] Server error for ${serverId}:`, error);
612
+ // Emit failed event
613
+ this.emit("failed", {
614
+ serverId,
615
+ error: error.message,
616
+ timestamp: new Date(),
617
+ });
618
+ // Attempt restart if enabled
619
+ if (this.config.enableAutoRestart && !this.isShuttingDown) {
620
+ this.scheduleRestart(serverId);
621
+ }
622
+ else {
623
+ this.updateServerStatus(serverId, "failed");
624
+ }
625
+ }
626
+ /**
627
+ * Handle server disconnection
628
+ */
629
+ handleServerDisconnection(serverId, reason) {
630
+ const instance = this.servers.get(serverId);
631
+ if (!instance) {
632
+ return;
633
+ }
634
+ instance.metrics.totalDisconnections++;
635
+ mcpLogger.warn(`[ExternalServerManager] Server disconnected ${serverId}: ${reason}`);
636
+ // Emit disconnected event
637
+ this.emit("disconnected", {
638
+ serverId,
639
+ reason,
640
+ timestamp: new Date(),
641
+ });
642
+ // Attempt restart if enabled
643
+ if (this.config.enableAutoRestart && !this.isShuttingDown) {
644
+ this.scheduleRestart(serverId);
645
+ }
646
+ else {
647
+ this.updateServerStatus(serverId, "disconnected");
648
+ }
649
+ }
650
+ /**
651
+ * Schedule server restart with exponential backoff
652
+ */
653
+ scheduleRestart(serverId) {
654
+ const instance = this.servers.get(serverId);
655
+ if (!instance) {
656
+ return;
657
+ }
658
+ if (instance.reconnectAttempts >= instance.maxReconnectAttempts) {
659
+ mcpLogger.error(`[ExternalServerManager] Max restart attempts reached for ${serverId}`);
660
+ this.updateServerStatus(serverId, "failed");
661
+ return;
662
+ }
663
+ instance.reconnectAttempts++;
664
+ this.updateServerStatus(serverId, "restarting");
665
+ const delay = Math.min(1000 *
666
+ Math.pow(this.config.restartBackoffMultiplier, instance.reconnectAttempts - 1), 30000);
667
+ mcpLogger.info(`[ExternalServerManager] Scheduling restart for ${serverId} in ${delay}ms (attempt ${instance.reconnectAttempts})`);
668
+ instance.restartTimer = setTimeout(async () => {
669
+ try {
670
+ await this.stopServer(serverId);
671
+ await this.startServer(serverId);
672
+ // Reset restart attempts on successful restart
673
+ instance.reconnectAttempts = 0;
674
+ }
675
+ catch (error) {
676
+ mcpLogger.error(`[ExternalServerManager] Restart failed for ${serverId}:`, error);
677
+ this.scheduleRestart(serverId); // Try again
678
+ }
679
+ }, delay);
680
+ }
681
+ /**
682
+ * Start health monitoring for a server
683
+ */
684
+ startHealthMonitoring(serverId) {
685
+ const instance = this.servers.get(serverId);
686
+ if (!instance || !this.config.enablePerformanceMonitoring) {
687
+ return;
688
+ }
689
+ const interval = instance.config.healthCheckInterval ??
690
+ this.config.defaultHealthCheckInterval;
691
+ instance.healthTimer = setInterval(async () => {
692
+ await this.performHealthCheck(serverId);
693
+ }, interval);
694
+ }
695
+ /**
696
+ * Perform health check on a server
697
+ */
698
+ async performHealthCheck(serverId) {
699
+ const instance = this.servers.get(serverId);
700
+ if (!instance || instance.status !== "connected") {
701
+ return;
702
+ }
703
+ const startTime = Date.now();
704
+ try {
705
+ // For now, simple process check
706
+ let isHealthy = true;
707
+ const issues = [];
708
+ if (instance.process && instance.process.killed) {
709
+ isHealthy = false;
710
+ issues.push("Process is killed");
711
+ }
712
+ const responseTime = Date.now() - startTime;
713
+ instance.lastHealthCheck = new Date();
714
+ const health = {
715
+ serverId,
716
+ isHealthy,
717
+ status: instance.status,
718
+ checkedAt: new Date(),
719
+ responseTime,
720
+ toolCount: instance.toolsMap.size,
721
+ issues,
722
+ performance: {
723
+ uptime: instance.startTime
724
+ ? Date.now() - instance.startTime.getTime()
725
+ : 0,
726
+ averageResponseTime: instance.metrics.averageResponseTime,
727
+ },
728
+ };
729
+ // Emit health check event
730
+ this.emit("healthCheck", {
731
+ serverId,
732
+ health,
733
+ timestamp: new Date(),
734
+ });
735
+ if (!isHealthy) {
736
+ mcpLogger.warn(`[ExternalServerManager] Health check failed for ${serverId}:`, issues);
737
+ this.handleServerError(serverId, new Error(`Health check failed: ${issues.join(", ")}`));
738
+ }
739
+ }
740
+ catch (error) {
741
+ mcpLogger.error(`[ExternalServerManager] Health check error for ${serverId}:`, error);
742
+ this.handleServerError(serverId, error instanceof Error ? error : new Error(String(error)));
743
+ }
744
+ }
745
+ /**
746
+ * Get server instance - converted to ExternalMCPServerInstance for compatibility
747
+ */
748
+ getServer(serverId) {
749
+ const runtime = this.servers.get(serverId);
750
+ if (!runtime) {
751
+ return undefined;
752
+ }
753
+ return {
754
+ config: runtime.config,
755
+ process: runtime.process,
756
+ client: runtime.client,
757
+ transport: runtime.transportInstance,
758
+ status: runtime.status,
759
+ lastError: runtime.lastError,
760
+ startTime: runtime.startTime,
761
+ lastHealthCheck: runtime.lastHealthCheck,
762
+ reconnectAttempts: runtime.reconnectAttempts,
763
+ maxReconnectAttempts: runtime.maxReconnectAttempts,
764
+ tools: runtime.toolsMap,
765
+ toolsArray: runtime.toolsArray,
766
+ capabilities: runtime.capabilities,
767
+ healthTimer: runtime.healthTimer,
768
+ restartTimer: runtime.restartTimer,
769
+ metrics: runtime.metrics,
770
+ };
771
+ }
772
+ /**
773
+ * Get all servers - converted to ExternalMCPServerInstance for compatibility
774
+ */
775
+ getAllServers() {
776
+ const converted = new Map();
777
+ for (const [serverId, runtime] of this.servers.entries()) {
778
+ converted.set(serverId, {
779
+ config: runtime.config,
780
+ process: runtime.process,
781
+ client: runtime.client,
782
+ transport: runtime.transportInstance,
783
+ status: runtime.status,
784
+ lastError: runtime.lastError,
785
+ startTime: runtime.startTime,
786
+ lastHealthCheck: runtime.lastHealthCheck,
787
+ reconnectAttempts: runtime.reconnectAttempts,
788
+ maxReconnectAttempts: runtime.maxReconnectAttempts,
789
+ tools: runtime.toolsMap,
790
+ toolsArray: runtime.toolsArray,
791
+ capabilities: runtime.capabilities,
792
+ healthTimer: runtime.healthTimer,
793
+ restartTimer: runtime.restartTimer,
794
+ metrics: runtime.metrics,
795
+ });
796
+ }
797
+ return converted;
798
+ }
799
+ /**
800
+ * List servers as MCPServerInfo - ZERO conversion needed
801
+ */
802
+ listServers() {
803
+ return Array.from(this.servers.values());
804
+ }
805
+ /**
806
+ * Get server statuses
807
+ */
808
+ getServerStatuses() {
809
+ const statuses = [];
810
+ for (const [serverId, instance] of Array.from(this.servers.entries())) {
811
+ const uptime = instance.startTime
812
+ ? Date.now() - instance.startTime.getTime()
813
+ : 0;
814
+ statuses.push({
815
+ serverId,
816
+ isHealthy: instance.status === "connected",
817
+ status: instance.status,
818
+ checkedAt: instance.lastHealthCheck || new Date(),
819
+ toolCount: instance.toolsMap.size,
820
+ issues: instance.lastError ? [instance.lastError] : [],
821
+ performance: {
822
+ uptime,
823
+ averageResponseTime: instance.metrics.averageResponseTime,
824
+ },
825
+ });
826
+ }
827
+ return statuses;
828
+ }
829
+ /**
830
+ * Shutdown all servers
831
+ */
832
+ async shutdown() {
833
+ if (this.isShuttingDown) {
834
+ return;
835
+ }
836
+ this.isShuttingDown = true;
837
+ mcpLogger.info("[ExternalServerManager] Shutting down all servers...");
838
+ const shutdownPromises = Array.from(this.servers.keys()).map((serverId) => this.stopServer(serverId).catch((error) => {
839
+ mcpLogger.error(`[ExternalServerManager] Error shutting down ${serverId}:`, error);
840
+ }));
841
+ await Promise.all(shutdownPromises);
842
+ this.servers.clear();
843
+ mcpLogger.info("[ExternalServerManager] All servers shut down");
844
+ }
845
+ /**
846
+ * Get manager statistics
847
+ */
848
+ getStatistics() {
849
+ let connectedServers = 0;
850
+ let failedServers = 0;
851
+ let totalTools = 0;
852
+ let totalConnections = 0;
853
+ let totalErrors = 0;
854
+ for (const instance of Array.from(this.servers.values())) {
855
+ if (instance.status === "connected") {
856
+ connectedServers++;
857
+ }
858
+ else if (instance.status === "failed") {
859
+ failedServers++;
860
+ }
861
+ totalTools += instance.toolsMap.size;
862
+ totalConnections += instance.metrics.totalConnections;
863
+ totalErrors += instance.metrics.totalErrors;
864
+ }
865
+ return {
866
+ totalServers: this.servers.size,
867
+ connectedServers,
868
+ failedServers,
869
+ totalTools,
870
+ totalConnections,
871
+ totalErrors,
872
+ };
873
+ }
874
+ /**
875
+ * Discover tools from a server
876
+ */
877
+ async discoverServerTools(serverId) {
878
+ const instance = this.servers.get(serverId);
879
+ if (!instance || !instance.client) {
880
+ throw new Error(`Server '${serverId}' not found or not connected`);
881
+ }
882
+ try {
883
+ mcpLogger.debug(`[ExternalServerManager] Discovering tools for server: ${serverId}`);
884
+ const discoveryResult = await this.toolDiscovery.discoverTools(serverId, instance.client, this.config.defaultTimeout);
885
+ if (discoveryResult.success) {
886
+ instance.toolsMap.clear();
887
+ instance.toolsArray = undefined;
888
+ instance.tools = [];
889
+ for (const tool of discoveryResult.tools) {
890
+ instance.toolsMap.set(tool.name, tool);
891
+ instance.tools.push({
892
+ name: tool.name,
893
+ description: tool.description,
894
+ inputSchema: tool.inputSchema,
895
+ });
896
+ }
897
+ mcpLogger.info(`[ExternalServerManager] Discovered ${discoveryResult.toolCount} tools for ${serverId}`);
898
+ }
899
+ else {
900
+ mcpLogger.warn(`[ExternalServerManager] Tool discovery failed for ${serverId}: ${discoveryResult.error}`);
901
+ }
902
+ }
903
+ catch (error) {
904
+ mcpLogger.error(`[ExternalServerManager] Tool discovery error for ${serverId}:`, error);
905
+ }
906
+ }
907
+ /**
908
+ * Register server tools with main tool registry for unified access
909
+ * This enables external MCP tools to be accessed via the main toolRegistry.executeTool()
910
+ */
911
+ async registerServerToolsWithMainRegistry(serverId) {
912
+ const instance = this.servers.get(serverId);
913
+ if (!instance) {
914
+ throw new Error(`Server '${serverId}' not found`);
915
+ }
916
+ try {
917
+ mcpLogger.debug(`[ExternalServerManager] Registering ${instance.toolsMap.size} tools with main registry for server: ${serverId}`);
918
+ for (const [toolName, tool] of instance.toolsMap.entries()) {
919
+ const toolId = `${serverId}.${toolName}`;
920
+ const toolInfo = {
921
+ name: toolName,
922
+ description: tool.description || toolName,
923
+ inputSchema: tool.inputSchema || {},
924
+ serverId: serverId,
925
+ category: detectCategory({ isExternal: true, serverId }),
926
+ };
927
+ // Register with main tool registry
928
+ try {
929
+ toolRegistry.registerTool(toolId, toolInfo, {
930
+ execute: async (params, context) => {
931
+ // Execute tool via ExternalServerManager for proper lifecycle management
932
+ return await this.executeTool(serverId, toolName, params, { timeout: this.config.defaultTimeout });
933
+ },
934
+ });
935
+ mcpLogger.debug(`[ExternalServerManager] Registered tool with main registry: ${toolId}`);
936
+ }
937
+ catch (registrationError) {
938
+ mcpLogger.warn(`[ExternalServerManager] Failed to register tool ${toolId} with main registry:`, registrationError);
939
+ }
940
+ }
941
+ mcpLogger.info(`[ExternalServerManager] Successfully registered ${instance.toolsMap.size} tools with main registry for ${serverId}`);
942
+ }
943
+ catch (error) {
944
+ mcpLogger.error(`[ExternalServerManager] Failed to register tools with main registry for ${serverId}:`, error);
945
+ }
946
+ }
947
+ /**
948
+ * Unregister server tools from main tool registry
949
+ */
950
+ unregisterServerToolsFromMainRegistry(serverId) {
951
+ const instance = this.servers.get(serverId);
952
+ if (!instance || !this.enableMainRegistryIntegration) {
953
+ return;
954
+ }
955
+ try {
956
+ mcpLogger.debug(`[ExternalServerManager] Unregistering tools from main registry for server: ${serverId}`);
957
+ for (const [toolName] of instance.toolsMap.entries()) {
958
+ const toolId = `${serverId}.${toolName}`;
959
+ try {
960
+ toolRegistry.removeTool(toolId);
961
+ mcpLogger.debug(`[ExternalServerManager] Unregistered tool from main registry: ${toolId}`);
962
+ }
963
+ catch (error) {
964
+ mcpLogger.debug(`[ExternalServerManager] Failed to unregister tool ${toolId}:`, error);
965
+ }
966
+ }
967
+ mcpLogger.debug(`[ExternalServerManager] Completed unregistering tools from main registry for ${serverId}`);
968
+ }
969
+ catch (error) {
970
+ mcpLogger.error(`[ExternalServerManager] Error unregistering tools from main registry for ${serverId}:`, error);
971
+ }
972
+ }
973
+ /**
974
+ * Execute a tool on a specific server
975
+ */
976
+ async executeTool(serverId, toolName, parameters, options) {
977
+ const instance = this.servers.get(serverId);
978
+ if (!instance) {
979
+ throw new Error(`Server '${serverId}' not found`);
980
+ }
981
+ if (!instance.client) {
982
+ throw new Error(`Server '${serverId}' is not connected`);
983
+ }
984
+ if (instance.status !== "connected") {
985
+ throw new Error(`Server '${serverId}' is not in connected state: ${instance.status}`);
986
+ }
987
+ const startTime = Date.now();
988
+ try {
989
+ // Execute tool through discovery service
990
+ const result = await this.toolDiscovery.executeTool(toolName, serverId, instance.client, parameters, {
991
+ timeout: options?.timeout || this.config.defaultTimeout,
992
+ });
993
+ const duration = Date.now() - startTime;
994
+ // Update metrics
995
+ instance.metrics.totalToolCalls++;
996
+ instance.metrics.lastResponseTime = duration;
997
+ // Update average response time
998
+ const totalTime = instance.metrics.averageResponseTime *
999
+ (instance.metrics.totalToolCalls - 1) +
1000
+ duration;
1001
+ instance.metrics.averageResponseTime =
1002
+ totalTime / instance.metrics.totalToolCalls;
1003
+ if (result.success) {
1004
+ mcpLogger.debug(`[ExternalServerManager] Tool executed successfully: ${toolName} on ${serverId}`, {
1005
+ duration,
1006
+ });
1007
+ return result.data;
1008
+ }
1009
+ else {
1010
+ throw new Error(result.error || "Tool execution failed");
1011
+ }
1012
+ }
1013
+ catch (error) {
1014
+ const duration = Date.now() - startTime;
1015
+ instance.metrics.totalErrors++;
1016
+ mcpLogger.error(`[ExternalServerManager] Tool execution failed: ${toolName} on ${serverId}`, error);
1017
+ throw error;
1018
+ }
1019
+ }
1020
+ /**
1021
+ * Get all tools from all servers
1022
+ */
1023
+ getAllTools() {
1024
+ return this.toolDiscovery.getAllTools();
1025
+ }
1026
+ /**
1027
+ * Get tools for a specific server
1028
+ */
1029
+ getServerTools(serverId) {
1030
+ return this.toolDiscovery.getServerTools(serverId);
1031
+ }
1032
+ /**
1033
+ * Get tool discovery service
1034
+ */
1035
+ getToolDiscovery() {
1036
+ return this.toolDiscovery;
1037
+ }
1038
+ }