@juspay/neurolink 6.1.0 → 6.2.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 (303) hide show
  1. package/CHANGELOG.md +16 -6
  2. package/dist/agent/direct-tools.js +6 -5
  3. package/dist/cli/commands/config.d.ts +13 -13
  4. package/dist/cli/index.js +3 -9
  5. package/dist/config/configManager.js +11 -10
  6. package/dist/core/analytics.d.ts +11 -1
  7. package/dist/core/analytics.js +2 -2
  8. package/dist/core/base-provider.js +4 -18
  9. package/dist/core/dynamic-models.d.ts +8 -8
  10. package/dist/core/factory.js +3 -11
  11. package/dist/index.d.ts +2 -4
  12. package/dist/index.js +2 -11
  13. package/dist/lib/agent/direct-tools.js +6 -5
  14. package/dist/lib/config/configManager.js +11 -10
  15. package/dist/lib/core/analytics.d.ts +11 -1
  16. package/dist/lib/core/analytics.js +2 -2
  17. package/dist/lib/core/base-provider.js +4 -18
  18. package/dist/lib/core/dynamic-models.d.ts +8 -8
  19. package/dist/lib/core/factory.js +3 -11
  20. package/dist/lib/index.d.ts +2 -4
  21. package/dist/lib/index.js +2 -11
  22. package/dist/lib/mcp/factory.d.ts +1 -1
  23. package/dist/lib/mcp/index.d.ts +9 -21
  24. package/dist/lib/mcp/index.js +16 -57
  25. package/dist/lib/mcp/registry.js +1 -1
  26. package/dist/lib/mcp/servers/ai-providers/ai-analysis-tools.js +2 -1
  27. package/dist/lib/mcp/tool-registry.js +1 -1
  28. package/dist/lib/neurolink.d.ts +1 -9
  29. package/dist/lib/neurolink.js +22 -71
  30. package/dist/lib/providers/amazon-bedrock.js +5 -16
  31. package/dist/lib/providers/anthropic-baseprovider.js +3 -21
  32. package/dist/lib/providers/anthropic.js +4 -7
  33. package/dist/lib/providers/azure-openai.js +6 -3
  34. package/dist/lib/providers/google-vertex.js +5 -9
  35. package/dist/lib/providers/huggingFace.js +5 -10
  36. package/dist/lib/providers/mistral.js +5 -8
  37. package/dist/lib/providers/openAI.js +4 -7
  38. package/dist/lib/telemetry/index.js +2 -1
  39. package/dist/lib/utils/logger.d.ts +62 -2
  40. package/dist/lib/utils/logger.js +174 -9
  41. package/dist/lib/utils/providerConfig.d.ts +117 -0
  42. package/dist/lib/utils/providerConfig.js +353 -0
  43. package/dist/lib/utils/providerUtils.d.ts +2 -1
  44. package/dist/lib/utils/providerUtils.js +53 -36
  45. package/dist/lib/utils/timeout.d.ts +72 -1
  46. package/dist/lib/utils/timeout.js +203 -2
  47. package/dist/mcp/factory.d.ts +1 -1
  48. package/dist/mcp/index.d.ts +9 -21
  49. package/dist/mcp/index.js +16 -57
  50. package/dist/mcp/registry.js +1 -1
  51. package/dist/mcp/servers/ai-providers/ai-analysis-tools.js +2 -1
  52. package/dist/mcp/tool-registry.js +1 -1
  53. package/dist/neurolink.d.ts +1 -9
  54. package/dist/neurolink.js +22 -71
  55. package/dist/providers/amazon-bedrock.js +5 -16
  56. package/dist/providers/anthropic-baseprovider.js +3 -21
  57. package/dist/providers/anthropic.js +4 -7
  58. package/dist/providers/azure-openai.js +6 -3
  59. package/dist/providers/google-vertex.js +5 -9
  60. package/dist/providers/huggingFace.js +5 -10
  61. package/dist/providers/mistral.js +5 -8
  62. package/dist/providers/openAI.js +4 -7
  63. package/dist/telemetry/index.js +2 -1
  64. package/dist/utils/logger.d.ts +62 -2
  65. package/dist/utils/logger.js +174 -9
  66. package/dist/utils/providerConfig.d.ts +117 -0
  67. package/dist/utils/providerConfig.js +353 -0
  68. package/dist/utils/providerUtils.d.ts +2 -1
  69. package/dist/utils/providerUtils.js +53 -36
  70. package/dist/utils/timeout.d.ts +72 -1
  71. package/dist/utils/timeout.js +203 -2
  72. package/package.json +1 -1
  73. package/dist/chat/client-utils.d.ts +0 -95
  74. package/dist/chat/client-utils.js +0 -315
  75. package/dist/chat/index.d.ts +0 -24
  76. package/dist/chat/index.js +0 -33
  77. package/dist/chat/session-storage.d.ts +0 -77
  78. package/dist/chat/session-storage.js +0 -233
  79. package/dist/chat/session.d.ts +0 -96
  80. package/dist/chat/session.js +0 -257
  81. package/dist/chat/sse-handler.d.ts +0 -49
  82. package/dist/chat/sse-handler.js +0 -259
  83. package/dist/chat/types.d.ts +0 -74
  84. package/dist/chat/types.js +0 -5
  85. package/dist/chat/websocket-chat-handler.d.ts +0 -37
  86. package/dist/chat/websocket-chat-handler.js +0 -262
  87. package/dist/cli/commands/mcp.d.ts +0 -20
  88. package/dist/cli/commands/mcp.js +0 -1272
  89. package/dist/core/defaults.d.ts +0 -19
  90. package/dist/core/defaults.js +0 -29
  91. package/dist/core/evaluation-config.d.ts +0 -29
  92. package/dist/core/evaluation-config.js +0 -144
  93. package/dist/factories/compatibility-factory.d.ts +0 -35
  94. package/dist/factories/compatibility-factory.js +0 -71
  95. package/dist/factories/provider-generate-factory.d.ts +0 -20
  96. package/dist/factories/provider-generate-factory.js +0 -93
  97. package/dist/lib/chat/client-utils.d.ts +0 -95
  98. package/dist/lib/chat/client-utils.js +0 -315
  99. package/dist/lib/chat/index.d.ts +0 -24
  100. package/dist/lib/chat/index.js +0 -33
  101. package/dist/lib/chat/session-storage.d.ts +0 -77
  102. package/dist/lib/chat/session-storage.js +0 -233
  103. package/dist/lib/chat/session.d.ts +0 -96
  104. package/dist/lib/chat/session.js +0 -257
  105. package/dist/lib/chat/sse-handler.d.ts +0 -49
  106. package/dist/lib/chat/sse-handler.js +0 -259
  107. package/dist/lib/chat/types.d.ts +0 -74
  108. package/dist/lib/chat/types.js +0 -5
  109. package/dist/lib/chat/websocket-chat-handler.d.ts +0 -37
  110. package/dist/lib/chat/websocket-chat-handler.js +0 -262
  111. package/dist/lib/core/defaults.d.ts +0 -19
  112. package/dist/lib/core/defaults.js +0 -29
  113. package/dist/lib/core/evaluation-config.d.ts +0 -29
  114. package/dist/lib/core/evaluation-config.js +0 -144
  115. package/dist/lib/factories/compatibility-factory.d.ts +0 -35
  116. package/dist/lib/factories/compatibility-factory.js +0 -71
  117. package/dist/lib/factories/provider-generate-factory.d.ts +0 -20
  118. package/dist/lib/factories/provider-generate-factory.js +0 -93
  119. package/dist/lib/mcp/adapters/plugin-bridge.d.ts +0 -40
  120. package/dist/lib/mcp/adapters/plugin-bridge.js +0 -89
  121. package/dist/lib/mcp/auto-discovery.d.ts +0 -62
  122. package/dist/lib/mcp/auto-discovery.js +0 -149
  123. package/dist/lib/mcp/client.d.ts +0 -68
  124. package/dist/lib/mcp/client.js +0 -248
  125. package/dist/lib/mcp/config.d.ts +0 -31
  126. package/dist/lib/mcp/config.js +0 -99
  127. package/dist/lib/mcp/context-manager.d.ts +0 -171
  128. package/dist/lib/mcp/context-manager.js +0 -362
  129. package/dist/lib/mcp/contracts/mcp-contract.d.ts +0 -169
  130. package/dist/lib/mcp/contracts/mcp-contract.js +0 -58
  131. package/dist/lib/mcp/core/plugin-manager.d.ts +0 -46
  132. package/dist/lib/mcp/core/plugin-manager.js +0 -110
  133. package/dist/lib/mcp/demo/plugin-demo.d.ts +0 -20
  134. package/dist/lib/mcp/demo/plugin-demo.js +0 -118
  135. package/dist/lib/mcp/dynamic-chain-executor.d.ts +0 -225
  136. package/dist/lib/mcp/dynamic-chain-executor.js +0 -489
  137. package/dist/lib/mcp/dynamic-orchestrator.d.ts +0 -115
  138. package/dist/lib/mcp/dynamic-orchestrator.js +0 -351
  139. package/dist/lib/mcp/ecosystem.d.ts +0 -75
  140. package/dist/lib/mcp/ecosystem.js +0 -161
  141. package/dist/lib/mcp/error-manager.d.ts +0 -254
  142. package/dist/lib/mcp/error-manager.js +0 -501
  143. package/dist/lib/mcp/error-recovery.d.ts +0 -159
  144. package/dist/lib/mcp/error-recovery.js +0 -405
  145. package/dist/lib/mcp/external-client.d.ts +0 -88
  146. package/dist/lib/mcp/external-client.js +0 -331
  147. package/dist/lib/mcp/external-manager.d.ts +0 -112
  148. package/dist/lib/mcp/external-manager.js +0 -308
  149. package/dist/lib/mcp/function-calling.d.ts +0 -65
  150. package/dist/lib/mcp/function-calling.js +0 -642
  151. package/dist/lib/mcp/health-monitor.d.ts +0 -257
  152. package/dist/lib/mcp/health-monitor.js +0 -630
  153. package/dist/lib/mcp/initialize-tools.d.ts +0 -29
  154. package/dist/lib/mcp/initialize-tools.js +0 -261
  155. package/dist/lib/mcp/initialize.d.ts +0 -18
  156. package/dist/lib/mcp/initialize.js +0 -62
  157. package/dist/lib/mcp/logging.d.ts +0 -38
  158. package/dist/lib/mcp/logging.js +0 -100
  159. package/dist/lib/mcp/manager.d.ts +0 -68
  160. package/dist/lib/mcp/manager.js +0 -176
  161. package/dist/lib/mcp/neurolink-mcp-client.d.ts +0 -97
  162. package/dist/lib/mcp/neurolink-mcp-client.js +0 -462
  163. package/dist/lib/mcp/orchestrator.d.ts +0 -302
  164. package/dist/lib/mcp/orchestrator.js +0 -703
  165. package/dist/lib/mcp/plugin-manager.d.ts +0 -98
  166. package/dist/lib/mcp/plugin-manager.js +0 -296
  167. package/dist/lib/mcp/plugins/core/filesystem-mcp.d.ts +0 -36
  168. package/dist/lib/mcp/plugins/core/filesystem-mcp.js +0 -142
  169. package/dist/lib/mcp/plugins/filesystem-mcp.d.ts +0 -37
  170. package/dist/lib/mcp/plugins/filesystem-mcp.js +0 -54
  171. package/dist/lib/mcp/security-manager.d.ts +0 -87
  172. package/dist/lib/mcp/security-manager.js +0 -344
  173. package/dist/lib/mcp/semaphore-manager.d.ts +0 -137
  174. package/dist/lib/mcp/semaphore-manager.js +0 -329
  175. package/dist/lib/mcp/session-manager.d.ts +0 -187
  176. package/dist/lib/mcp/session-manager.js +0 -400
  177. package/dist/lib/mcp/session-persistence.d.ts +0 -93
  178. package/dist/lib/mcp/session-persistence.js +0 -301
  179. package/dist/lib/mcp/tool-integration.d.ts +0 -58
  180. package/dist/lib/mcp/tool-integration.js +0 -203
  181. package/dist/lib/mcp/transport-manager.d.ts +0 -154
  182. package/dist/lib/mcp/transport-manager.js +0 -334
  183. package/dist/lib/mcp/unified-mcp.d.ts +0 -133
  184. package/dist/lib/mcp/unified-mcp.js +0 -251
  185. package/dist/lib/mcp/unified-registry.d.ts +0 -165
  186. package/dist/lib/mcp/unified-registry.js +0 -538
  187. package/dist/lib/providers/analytics-helper.d.ts +0 -38
  188. package/dist/lib/providers/analytics-helper.js +0 -216
  189. package/dist/lib/providers/function-calling-provider.d.ts +0 -142
  190. package/dist/lib/providers/function-calling-provider.js +0 -630
  191. package/dist/lib/providers/mcp-provider.d.ts +0 -75
  192. package/dist/lib/providers/mcp-provider.js +0 -283
  193. package/dist/lib/providers/timeout-wrapper.d.ts +0 -40
  194. package/dist/lib/providers/timeout-wrapper.js +0 -100
  195. package/dist/lib/sdk/tool-extension.d.ts +0 -181
  196. package/dist/lib/sdk/tool-extension.js +0 -284
  197. package/dist/lib/services/streaming/streaming-manager.d.ts +0 -29
  198. package/dist/lib/services/streaming/streaming-manager.js +0 -245
  199. package/dist/lib/services/types.d.ts +0 -156
  200. package/dist/lib/services/types.js +0 -2
  201. package/dist/lib/services/websocket/websocket-server.d.ts +0 -34
  202. package/dist/lib/services/websocket/websocket-server.js +0 -305
  203. package/dist/lib/utils/provider-validation.d.ts +0 -36
  204. package/dist/lib/utils/provider-validation.js +0 -625
  205. package/dist/lib/utils/providerUtils-fixed.d.ts +0 -8
  206. package/dist/lib/utils/providerUtils-fixed.js +0 -94
  207. package/dist/lib/utils/streaming-utils.d.ts +0 -79
  208. package/dist/lib/utils/streaming-utils.js +0 -198
  209. package/dist/lib/utils/timeout-manager.d.ts +0 -75
  210. package/dist/lib/utils/timeout-manager.js +0 -244
  211. package/dist/mcp/adapters/plugin-bridge.d.ts +0 -40
  212. package/dist/mcp/adapters/plugin-bridge.js +0 -89
  213. package/dist/mcp/auto-discovery.d.ts +0 -62
  214. package/dist/mcp/auto-discovery.js +0 -149
  215. package/dist/mcp/client.d.ts +0 -68
  216. package/dist/mcp/client.js +0 -248
  217. package/dist/mcp/config.d.ts +0 -31
  218. package/dist/mcp/config.js +0 -99
  219. package/dist/mcp/context-manager.d.ts +0 -171
  220. package/dist/mcp/context-manager.js +0 -362
  221. package/dist/mcp/contracts/mcp-contract.d.ts +0 -169
  222. package/dist/mcp/contracts/mcp-contract.js +0 -58
  223. package/dist/mcp/core/plugin-manager.d.ts +0 -46
  224. package/dist/mcp/core/plugin-manager.js +0 -110
  225. package/dist/mcp/demo/plugin-demo.d.ts +0 -20
  226. package/dist/mcp/demo/plugin-demo.js +0 -118
  227. package/dist/mcp/dynamic-chain-executor.d.ts +0 -225
  228. package/dist/mcp/dynamic-chain-executor.js +0 -489
  229. package/dist/mcp/dynamic-orchestrator.d.ts +0 -115
  230. package/dist/mcp/dynamic-orchestrator.js +0 -351
  231. package/dist/mcp/ecosystem.d.ts +0 -75
  232. package/dist/mcp/ecosystem.js +0 -162
  233. package/dist/mcp/error-manager.d.ts +0 -254
  234. package/dist/mcp/error-manager.js +0 -501
  235. package/dist/mcp/error-recovery.d.ts +0 -159
  236. package/dist/mcp/error-recovery.js +0 -405
  237. package/dist/mcp/external-client.d.ts +0 -88
  238. package/dist/mcp/external-client.js +0 -331
  239. package/dist/mcp/external-manager.d.ts +0 -112
  240. package/dist/mcp/external-manager.js +0 -308
  241. package/dist/mcp/function-calling.d.ts +0 -65
  242. package/dist/mcp/function-calling.js +0 -642
  243. package/dist/mcp/health-monitor.d.ts +0 -257
  244. package/dist/mcp/health-monitor.js +0 -630
  245. package/dist/mcp/initialize-tools.d.ts +0 -29
  246. package/dist/mcp/initialize-tools.js +0 -262
  247. package/dist/mcp/initialize.d.ts +0 -18
  248. package/dist/mcp/initialize.js +0 -62
  249. package/dist/mcp/logging.d.ts +0 -38
  250. package/dist/mcp/logging.js +0 -100
  251. package/dist/mcp/manager.d.ts +0 -68
  252. package/dist/mcp/manager.js +0 -176
  253. package/dist/mcp/neurolink-mcp-client.d.ts +0 -97
  254. package/dist/mcp/neurolink-mcp-client.js +0 -462
  255. package/dist/mcp/orchestrator.d.ts +0 -302
  256. package/dist/mcp/orchestrator.js +0 -703
  257. package/dist/mcp/plugin-manager.d.ts +0 -98
  258. package/dist/mcp/plugin-manager.js +0 -297
  259. package/dist/mcp/plugins/core/filesystem-mcp.d.ts +0 -36
  260. package/dist/mcp/plugins/core/filesystem-mcp.js +0 -142
  261. package/dist/mcp/plugins/core/neurolink-mcp.json +0 -17
  262. package/dist/mcp/plugins/filesystem-mcp.d.ts +0 -37
  263. package/dist/mcp/plugins/filesystem-mcp.js +0 -54
  264. package/dist/mcp/security-manager.d.ts +0 -87
  265. package/dist/mcp/security-manager.js +0 -344
  266. package/dist/mcp/semaphore-manager.d.ts +0 -137
  267. package/dist/mcp/semaphore-manager.js +0 -329
  268. package/dist/mcp/session-manager.d.ts +0 -187
  269. package/dist/mcp/session-manager.js +0 -400
  270. package/dist/mcp/session-persistence.d.ts +0 -93
  271. package/dist/mcp/session-persistence.js +0 -302
  272. package/dist/mcp/tool-integration.d.ts +0 -58
  273. package/dist/mcp/tool-integration.js +0 -203
  274. package/dist/mcp/transport-manager.d.ts +0 -154
  275. package/dist/mcp/transport-manager.js +0 -335
  276. package/dist/mcp/unified-mcp.d.ts +0 -133
  277. package/dist/mcp/unified-mcp.js +0 -251
  278. package/dist/mcp/unified-registry.d.ts +0 -165
  279. package/dist/mcp/unified-registry.js +0 -539
  280. package/dist/providers/analytics-helper.d.ts +0 -38
  281. package/dist/providers/analytics-helper.js +0 -216
  282. package/dist/providers/function-calling-provider.d.ts +0 -142
  283. package/dist/providers/function-calling-provider.js +0 -630
  284. package/dist/providers/mcp-provider.d.ts +0 -75
  285. package/dist/providers/mcp-provider.js +0 -283
  286. package/dist/providers/timeout-wrapper.d.ts +0 -40
  287. package/dist/providers/timeout-wrapper.js +0 -100
  288. package/dist/sdk/tool-extension.d.ts +0 -181
  289. package/dist/sdk/tool-extension.js +0 -284
  290. package/dist/services/streaming/streaming-manager.d.ts +0 -29
  291. package/dist/services/streaming/streaming-manager.js +0 -245
  292. package/dist/services/types.d.ts +0 -156
  293. package/dist/services/types.js +0 -2
  294. package/dist/services/websocket/websocket-server.d.ts +0 -34
  295. package/dist/services/websocket/websocket-server.js +0 -306
  296. package/dist/utils/provider-validation.d.ts +0 -36
  297. package/dist/utils/provider-validation.js +0 -625
  298. package/dist/utils/providerUtils-fixed.d.ts +0 -8
  299. package/dist/utils/providerUtils-fixed.js +0 -94
  300. package/dist/utils/streaming-utils.d.ts +0 -79
  301. package/dist/utils/streaming-utils.js +0 -198
  302. package/dist/utils/timeout-manager.d.ts +0 -75
  303. package/dist/utils/timeout-manager.js +0 -244
@@ -1,630 +0,0 @@
1
- /**
2
- * NeuroLink MCP Health Monitoring System
3
- * Provides periodic health checks, connection status tracking, and auto-recovery
4
- * Based on health monitoring patterns from Cline
5
- */
6
- import { ErrorManager, ErrorCategory, ErrorSeverity } from "./error-manager.js";
7
- /**
8
- * Connection status states
9
- */
10
- export var ConnectionStatus;
11
- (function (ConnectionStatus) {
12
- ConnectionStatus["DISCONNECTED"] = "DISCONNECTED";
13
- ConnectionStatus["CONNECTING"] = "CONNECTING";
14
- ConnectionStatus["CONNECTED"] = "CONNECTED";
15
- ConnectionStatus["CHECKING"] = "CHECKING";
16
- ConnectionStatus["ERROR"] = "ERROR";
17
- ConnectionStatus["RECOVERING"] = "RECOVERING";
18
- })(ConnectionStatus || (ConnectionStatus = {}));
19
- /**
20
- * Ping health check - Simple availability check
21
- */
22
- export class PingHealthCheck {
23
- name = "ping";
24
- async check(serverId, registry) {
25
- const startTime = Date.now();
26
- try {
27
- // Try to list tools as a simple ping
28
- const tools = await registry.listTools();
29
- const latency = Date.now() - startTime;
30
- return {
31
- success: true,
32
- status: ConnectionStatus.CONNECTED,
33
- latency,
34
- timestamp: Date.now(),
35
- };
36
- }
37
- catch (error) {
38
- return {
39
- success: false,
40
- status: ConnectionStatus.ERROR,
41
- error: error instanceof Error ? error : new Error(String(error)),
42
- timestamp: Date.now(),
43
- };
44
- }
45
- }
46
- }
47
- /**
48
- * Tool list validation check - Ensures tools are accessible
49
- */
50
- export class ToolListValidationCheck {
51
- name = "tool-validation";
52
- async check(serverId, registry) {
53
- const startTime = Date.now();
54
- try {
55
- const tools = await registry.listTools();
56
- const latency = Date.now() - startTime;
57
- if (!tools || tools.length === 0) {
58
- return {
59
- success: false,
60
- status: ConnectionStatus.ERROR,
61
- message: "No tools available from server",
62
- latency,
63
- timestamp: Date.now(),
64
- };
65
- }
66
- return {
67
- success: true,
68
- status: ConnectionStatus.CONNECTED,
69
- message: `${tools.length} tools available`,
70
- latency,
71
- timestamp: Date.now(),
72
- };
73
- }
74
- catch (error) {
75
- return {
76
- success: false,
77
- status: ConnectionStatus.ERROR,
78
- error: error instanceof Error ? error : new Error(String(error)),
79
- timestamp: Date.now(),
80
- };
81
- }
82
- }
83
- }
84
- /**
85
- * Performance baseline check - Monitors response times
86
- */
87
- export class PerformanceCheck {
88
- name = "performance";
89
- performanceThreshold;
90
- constructor(thresholdMs = 1000) {
91
- this.performanceThreshold = thresholdMs;
92
- }
93
- async check(serverId, registry) {
94
- const startTime = Date.now();
95
- try {
96
- const tools = await registry.listTools();
97
- const latency = Date.now() - startTime;
98
- if (latency > this.performanceThreshold) {
99
- return {
100
- success: true, // Still successful, just slow
101
- status: ConnectionStatus.CONNECTED,
102
- message: `Performance degraded: ${latency}ms (threshold: ${this.performanceThreshold}ms)`,
103
- latency,
104
- timestamp: Date.now(),
105
- };
106
- }
107
- return {
108
- success: true,
109
- status: ConnectionStatus.CONNECTED,
110
- message: `Performance normal: ${latency}ms`,
111
- latency,
112
- timestamp: Date.now(),
113
- };
114
- }
115
- catch (error) {
116
- return {
117
- success: false,
118
- status: ConnectionStatus.ERROR,
119
- error: error instanceof Error ? error : new Error(String(error)),
120
- timestamp: Date.now(),
121
- };
122
- }
123
- }
124
- }
125
- /**
126
- * Health Monitor for MCP connections
127
- */
128
- export class HealthMonitor {
129
- registry;
130
- errorManager;
131
- serverHealth = new Map();
132
- checkInterval;
133
- checkTimeout;
134
- maxRecoveryAttempts;
135
- recoveryDelay;
136
- enableAutoRecovery;
137
- checkTimers = new Map();
138
- strategies = new Map();
139
- isMonitoring = false;
140
- recoveryCallbacks = new Map();
141
- constructor(registry, errorManager, options = {}) {
142
- this.registry = registry;
143
- this.errorManager = errorManager;
144
- this.checkInterval = options.checkInterval || 30000; // 30 seconds
145
- this.checkTimeout = options.checkTimeout || 5000; // 5 seconds
146
- this.maxRecoveryAttempts = options.maxRecoveryAttempts || 3;
147
- this.recoveryDelay = options.recoveryDelay || 5000; // 5 seconds
148
- this.enableAutoRecovery = options.enableAutoRecovery ?? true;
149
- // Initialize default strategies
150
- this.strategies.set("ping", new PingHealthCheck());
151
- this.strategies.set("tool-validation", new ToolListValidationCheck());
152
- this.strategies.set("performance", new PerformanceCheck());
153
- }
154
- /**
155
- * Start monitoring all registered servers
156
- */
157
- startMonitoring() {
158
- if (this.isMonitoring) {
159
- return;
160
- }
161
- this.isMonitoring = true;
162
- const servers = this.registry.listServers();
163
- if (process.env.NEUROLINK_DEBUG === "true") {
164
- console.log(`[HealthMonitor] Starting monitoring for ${servers.length} servers`);
165
- }
166
- // Initialize health tracking for each server
167
- servers.forEach((serverId) => {
168
- if (!this.serverHealth.has(serverId)) {
169
- this.serverHealth.set(serverId, {
170
- serverId,
171
- status: ConnectionStatus.DISCONNECTED,
172
- checkCount: 0,
173
- errorCount: 0,
174
- recoveryAttempts: 0,
175
- });
176
- }
177
- // Start periodic checks
178
- this.scheduleHealthCheck(serverId);
179
- });
180
- }
181
- /**
182
- * Stop monitoring all servers
183
- */
184
- stopMonitoring() {
185
- this.isMonitoring = false;
186
- // Clear all timers
187
- this.checkTimers.forEach((timer) => clearTimeout(timer));
188
- this.checkTimers.clear();
189
- if (process.env.NEUROLINK_DEBUG === "true") {
190
- console.log("[HealthMonitor] Stopped monitoring");
191
- }
192
- }
193
- /**
194
- * Perform health check for a specific server
195
- *
196
- * @param serverId Server to check
197
- * @param strategy Strategy name to use (default: "ping")
198
- * @returns Health check result
199
- */
200
- async checkServerHealth(serverId, strategy = "ping") {
201
- const health = this.serverHealth.get(serverId) || {
202
- serverId,
203
- status: ConnectionStatus.DISCONNECTED,
204
- checkCount: 0,
205
- errorCount: 0,
206
- recoveryAttempts: 0,
207
- };
208
- // Update status to checking
209
- health.status = ConnectionStatus.CHECKING;
210
- this.serverHealth.set(serverId, health);
211
- // Get strategy
212
- const checkStrategy = this.strategies.get(strategy);
213
- if (!checkStrategy) {
214
- return {
215
- success: false,
216
- status: ConnectionStatus.ERROR,
217
- error: new Error(`Unknown health check strategy: ${strategy}`),
218
- timestamp: Date.now(),
219
- };
220
- }
221
- // Perform check with timeout
222
- const timeoutPromise = new Promise((_, reject) => {
223
- setTimeout(() => reject(new Error("Health check timeout")), this.checkTimeout);
224
- });
225
- try {
226
- const result = await Promise.race([
227
- checkStrategy.check(serverId, this.registry),
228
- timeoutPromise,
229
- ]);
230
- // Update health status
231
- health.checkCount++;
232
- health.lastCheck = result;
233
- if (result.success) {
234
- health.status = ConnectionStatus.CONNECTED;
235
- health.lastSuccessfulCheck = Date.now();
236
- health.errorCount = 0;
237
- health.recoveryAttempts = 0;
238
- }
239
- else {
240
- health.status = ConnectionStatus.ERROR;
241
- health.errorCount++;
242
- // Record error
243
- this.errorManager.recordError(result.error || new Error("Health check failed"), {
244
- category: ErrorCategory.NETWORK_ERROR,
245
- severity: ErrorSeverity.HIGH,
246
- toolName: `health-check-${serverId}`,
247
- });
248
- }
249
- this.serverHealth.set(serverId, health);
250
- // Trigger recovery if enabled and failed
251
- if (!result.success &&
252
- this.enableAutoRecovery &&
253
- health.recoveryAttempts < this.maxRecoveryAttempts) {
254
- // Schedule recovery after returning result
255
- setTimeout(() => this.triggerRecovery(serverId), 0);
256
- }
257
- return result;
258
- }
259
- catch (error) {
260
- // Handle timeout or other errors
261
- const errorResult = {
262
- success: false,
263
- status: ConnectionStatus.ERROR,
264
- error: error instanceof Error ? error : new Error(String(error)),
265
- timestamp: Date.now(),
266
- };
267
- health.status = ConnectionStatus.ERROR;
268
- health.errorCount++;
269
- health.lastCheck = errorResult;
270
- this.serverHealth.set(serverId, health);
271
- // Record error
272
- this.errorManager.recordError(error, {
273
- category: ErrorCategory.TIMEOUT_ERROR,
274
- severity: ErrorSeverity.HIGH,
275
- toolName: `health-check-${serverId}`,
276
- });
277
- return errorResult;
278
- }
279
- }
280
- /**
281
- * Get health status for all servers
282
- *
283
- * @returns Map of server health information
284
- */
285
- getHealthStatus() {
286
- return new Map(this.serverHealth);
287
- }
288
- /**
289
- * Get health status for a specific server
290
- *
291
- * @param serverId Server ID
292
- * @returns Server health information or null
293
- */
294
- getServerHealth(serverId) {
295
- return this.serverHealth.get(serverId) || null;
296
- }
297
- /**
298
- * Register a recovery callback for a server
299
- *
300
- * @param serverId Server ID
301
- * @param callback Recovery callback function
302
- */
303
- registerRecoveryCallback(serverId, callback) {
304
- this.recoveryCallbacks.set(serverId, callback);
305
- }
306
- /**
307
- * Add a custom health check strategy
308
- *
309
- * @param strategy Health check strategy
310
- */
311
- addStrategy(strategy) {
312
- this.strategies.set(strategy.name, strategy);
313
- }
314
- /**
315
- * Schedule periodic health check for a server
316
- *
317
- * @private
318
- */
319
- scheduleHealthCheck(serverId) {
320
- if (!this.isMonitoring) {
321
- return;
322
- }
323
- // Clear existing timer if any
324
- const existingTimer = this.checkTimers.get(serverId);
325
- if (existingTimer) {
326
- clearTimeout(existingTimer);
327
- }
328
- // Schedule next check
329
- const timer = setTimeout(async () => {
330
- await this.checkServerHealth(serverId);
331
- // Reschedule if still monitoring
332
- if (this.isMonitoring) {
333
- this.scheduleHealthCheck(serverId);
334
- }
335
- }, this.checkInterval);
336
- this.checkTimers.set(serverId, timer);
337
- // Update next check time
338
- const health = this.serverHealth.get(serverId);
339
- if (health) {
340
- health.nextCheckTime = Date.now() + this.checkInterval;
341
- this.serverHealth.set(serverId, health);
342
- }
343
- }
344
- /**
345
- * Trigger recovery for a server
346
- *
347
- * @private
348
- */
349
- async triggerRecovery(serverId) {
350
- const health = this.serverHealth.get(serverId);
351
- if (!health) {
352
- return;
353
- }
354
- health.status = ConnectionStatus.RECOVERING;
355
- health.recoveryAttempts++;
356
- this.serverHealth.set(serverId, health);
357
- if (process.env.NEUROLINK_DEBUG === "true") {
358
- console.log(`[HealthMonitor] Triggering recovery for ${serverId} (attempt ${health.recoveryAttempts}/${this.maxRecoveryAttempts})`);
359
- }
360
- // Use exponential backoff for recovery delay
361
- const delay = this.recoveryDelay * Math.pow(2, health.recoveryAttempts - 1);
362
- setTimeout(async () => {
363
- // Call custom recovery callback if registered
364
- const callback = this.recoveryCallbacks.get(serverId);
365
- if (callback) {
366
- try {
367
- await callback(serverId);
368
- // Perform immediate health check after recovery
369
- const result = await this.checkServerHealth(serverId);
370
- if (result.success) {
371
- if (process.env.NEUROLINK_DEBUG === "true") {
372
- console.log(`[HealthMonitor] Recovery successful for ${serverId}`);
373
- }
374
- }
375
- }
376
- catch (error) {
377
- this.errorManager.recordError(error, {
378
- category: ErrorCategory.UNKNOWN_ERROR,
379
- severity: ErrorSeverity.CRITICAL,
380
- toolName: `recovery-${serverId}`,
381
- });
382
- }
383
- }
384
- }, delay);
385
- }
386
- /**
387
- * Generate comprehensive health report
388
- *
389
- * @returns Health report with server statuses and metrics
390
- */
391
- generateHealthReport() {
392
- const servers = Array.from(this.serverHealth.values());
393
- const now = Date.now();
394
- // Calculate summary
395
- const summary = {
396
- totalServers: servers.length,
397
- healthyServers: servers.filter((s) => s.status === ConnectionStatus.CONNECTED).length,
398
- unhealthyServers: servers.filter((s) => s.status === ConnectionStatus.ERROR).length,
399
- recoveringServers: servers.filter((s) => s.status === ConnectionStatus.RECOVERING).length,
400
- overallHealth: 0,
401
- };
402
- // Calculate server details
403
- const serverReports = servers.map((server) => {
404
- const successRate = server.checkCount > 0
405
- ? ((server.checkCount - server.errorCount) / server.checkCount) * 100
406
- : 0;
407
- const uptime = server.lastSuccessfulCheck && server.checkCount > 0
408
- ? ((now - server.lastSuccessfulCheck) /
409
- (server.checkCount * this.checkInterval)) *
410
- 100
411
- : 0;
412
- // Calculate average latency from recent checks
413
- const avgLatency = server.lastCheck?.latency || 0;
414
- // Calculate health score (0-100)
415
- let health = 100;
416
- health -= server.errorCount * 10; // -10 per error
417
- health -= server.recoveryAttempts * 5; // -5 per recovery attempt
418
- if (server.status === ConnectionStatus.ERROR) {
419
- health -= 50;
420
- }
421
- if (server.status === ConnectionStatus.RECOVERING) {
422
- health -= 25;
423
- }
424
- health = Math.max(0, Math.min(100, health));
425
- return {
426
- serverId: server.serverId,
427
- status: server.status,
428
- health,
429
- uptime: Math.min(100, uptime),
430
- avgLatency,
431
- lastError: server.lastCheck?.error?.message,
432
- metrics: {
433
- totalChecks: server.checkCount,
434
- successfulChecks: server.checkCount - server.errorCount,
435
- failedChecks: server.errorCount,
436
- recoveryAttempts: server.recoveryAttempts,
437
- },
438
- };
439
- });
440
- // Calculate overall health
441
- summary.overallHealth =
442
- serverReports.length > 0
443
- ? Math.round(serverReports.reduce((sum, s) => sum + s.health, 0) /
444
- serverReports.length)
445
- : 100;
446
- // Generate trends (simplified for now)
447
- const trends = {
448
- healthHistory: this.getHealthHistory(),
449
- errorRate: this.calculateErrorRate(),
450
- avgRecoveryTime: this.calculateAvgRecoveryTime(),
451
- };
452
- // Generate recommendations
453
- const recommendations = this.generateRecommendations(summary, serverReports);
454
- return {
455
- summary,
456
- servers: serverReports,
457
- trends,
458
- recommendations,
459
- };
460
- }
461
- /**
462
- * Get health metrics for monitoring dashboards
463
- *
464
- * @returns Simplified metrics for real-time monitoring
465
- */
466
- getHealthMetrics() {
467
- const report = this.generateHealthReport();
468
- // Determine overall status
469
- let status;
470
- if (report.summary.overallHealth >= 80) {
471
- status = "healthy";
472
- }
473
- else if (report.summary.overallHealth >= 50) {
474
- status = "degraded";
475
- }
476
- else {
477
- status = "critical";
478
- }
479
- // Generate active alerts
480
- const activeAlerts = [];
481
- this.serverHealth.forEach((health, serverId) => {
482
- if (health.status === ConnectionStatus.ERROR) {
483
- activeAlerts.push({
484
- serverId,
485
- severity: health.errorCount > 5 ? "critical" : "high",
486
- message: health.lastCheck?.error?.message || "Server unreachable",
487
- timestamp: health.lastCheck?.timestamp || Date.now(),
488
- });
489
- }
490
- else if (health.status === ConnectionStatus.RECOVERING) {
491
- activeAlerts.push({
492
- serverId,
493
- severity: "medium",
494
- message: `Recovery attempt ${health.recoveryAttempts}/${this.maxRecoveryAttempts}`,
495
- timestamp: Date.now(),
496
- });
497
- }
498
- });
499
- // Calculate performance metrics
500
- const latencies = report.servers
501
- .map((s) => s.avgLatency)
502
- .filter((l) => l > 0);
503
- const performance = {
504
- avgLatency: latencies.length > 0
505
- ? Math.round(latencies.reduce((sum, l) => sum + l, 0) / latencies.length)
506
- : 0,
507
- maxLatency: latencies.length > 0 ? Math.max(...latencies) : 0,
508
- successRate: report.servers.length > 0
509
- ? (report.summary.healthyServers / report.summary.totalServers) * 100
510
- : 100,
511
- };
512
- // Build server status map
513
- const serverStatuses = {};
514
- this.serverHealth.forEach((health, serverId) => {
515
- serverStatuses[serverId] = health.status;
516
- });
517
- return {
518
- status,
519
- healthScore: report.summary.overallHealth,
520
- activeAlerts,
521
- serverStatuses,
522
- performance,
523
- };
524
- }
525
- /**
526
- * Subscribe to health events
527
- *
528
- * @param event Event type to subscribe to
529
- * @param callback Callback function
530
- */
531
- on(event, callback) {
532
- // Implementation would use EventEmitter
533
- // For now, just a placeholder
534
- }
535
- /**
536
- * Get health history for trend analysis
537
- *
538
- * @private
539
- */
540
- getHealthHistory() {
541
- // In a real implementation, this would track health over time
542
- // For now, return current snapshot
543
- const report = this.generateHealthReport();
544
- return [
545
- {
546
- timestamp: Date.now(),
547
- health: report.summary.overallHealth,
548
- },
549
- ];
550
- }
551
- /**
552
- * Calculate error rate
553
- *
554
- * @private
555
- */
556
- calculateErrorRate() {
557
- let totalErrors = 0;
558
- this.serverHealth.forEach((health) => {
559
- totalErrors += health.errorCount;
560
- });
561
- // Errors per hour (simplified)
562
- const hoursMonitored = (Date.now() - (Date.now() - this.checkInterval * 10)) / (1000 * 60 * 60);
563
- return hoursMonitored > 0 ? totalErrors / hoursMonitored : 0;
564
- }
565
- /**
566
- * Calculate average recovery time
567
- *
568
- * @private
569
- */
570
- calculateAvgRecoveryTime() {
571
- // Simplified - would track actual recovery times
572
- return this.recoveryDelay * 2; // Assume average of 2 attempts
573
- }
574
- /**
575
- * Generate health recommendations
576
- *
577
- * @private
578
- */
579
- generateRecommendations(summary, servers) {
580
- const recommendations = [];
581
- // Type-safe access to summary properties
582
- const overallHealth = typeof summary.overallHealth === "number" ? summary.overallHealth : 0;
583
- const unhealthyServers = typeof summary.unhealthyServers === "number"
584
- ? summary.unhealthyServers
585
- : 0;
586
- const totalServers = typeof summary.totalServers === "number" ? summary.totalServers : 1;
587
- // Check overall health
588
- if (overallHealth < 50) {
589
- recommendations.push("Critical: System health is below 50%. Immediate attention required.");
590
- }
591
- // Check unhealthy servers
592
- if (unhealthyServers > totalServers * 0.3) {
593
- recommendations.push("Multiple servers are failing. Check network connectivity and server availability.");
594
- }
595
- // Check recovery attempts
596
- const highRecoveryServers = servers.filter((s) => typeof s.metrics === "object" &&
597
- s.metrics &&
598
- typeof s.metrics.recoveryAttempts === "number" &&
599
- s.metrics.recoveryAttempts > 2);
600
- if (highRecoveryServers.length > 0) {
601
- recommendations.push(`Servers with repeated recovery attempts: ${highRecoveryServers.map((s) => (typeof s.serverId === "string" ? s.serverId : "unknown")).join(", ")}. Consider manual intervention.`);
602
- }
603
- // Check latency
604
- const highLatencyServers = servers.filter((s) => typeof s.avgLatency === "number" && s.avgLatency > 1000);
605
- if (highLatencyServers.length > 0) {
606
- recommendations.push(`High latency detected on servers: ${highLatencyServers.map((s) => (typeof s.serverId === "string" ? s.serverId : "unknown")).join(", ")}. Check server load and network conditions.`);
607
- }
608
- // Positive feedback
609
- if (overallHealth >= 90) {
610
- recommendations.push("System health is excellent. All servers are operating normally.");
611
- }
612
- return recommendations;
613
- }
614
- }
615
- /**
616
- * Default health monitor instance (to be initialized with registry and error manager)
617
- */
618
- export let defaultHealthMonitor = null;
619
- /**
620
- * Initialize default health monitor
621
- *
622
- * @param registry Tool registry
623
- * @param errorManager Error manager
624
- * @param options Health monitor options
625
- * @returns Health monitor instance
626
- */
627
- export function initializeHealthMonitor(registry, errorManager, options) {
628
- defaultHealthMonitor = new HealthMonitor(registry, errorManager, options);
629
- return defaultHealthMonitor;
630
- }
@@ -1,29 +0,0 @@
1
- /**
2
- * NeuroLink MCP Tool Initialization
3
- * Following Lighthouse's pattern for registering MCP server tools with the client
4
- */
5
- import type { NeuroLinkMCPClient } from "./client.js";
6
- import type { NeuroLinkExecutionContext } from "./factory.js";
7
- import type { UnknownRecord } from "../types/common.js";
8
- /**
9
- * Initialize and register tools from MCP Servers with the MCP client
10
- * Following Lighthouse's pattern for tool registration
11
- */
12
- export declare const initializeMCPTools: (sessionId: string, client: NeuroLinkMCPClient, context: NeuroLinkExecutionContext) => Promise<void>;
13
- /**
14
- * Get all available tools across all servers
15
- * Useful for documentation and discovery
16
- */
17
- export declare function getAllAvailableTools(inMemoryServers?: Map<string, UnknownRecord>): Promise<Array<{
18
- serverId: string;
19
- serverTitle: string;
20
- toolName: string;
21
- namespacedName: string;
22
- description: string;
23
- isImplemented: boolean;
24
- }>>;
25
- /**
26
- * Initialize tools for a specific server only
27
- * Useful for selective tool registration
28
- */
29
- export declare function initializeServerTools(serverId: string, client: NeuroLinkMCPClient, context: NeuroLinkExecutionContext): Promise<number>;