@juspay/neurolink 3.0.1 → 4.1.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 (232) hide show
  1. package/CHANGELOG.md +66 -6
  2. package/README.md +318 -27
  3. package/dist/agent/direct-tools.d.ts +6 -6
  4. package/dist/chat/client-utils.d.ts +92 -0
  5. package/dist/chat/client-utils.js +298 -0
  6. package/dist/chat/index.d.ts +27 -0
  7. package/dist/chat/index.js +41 -0
  8. package/dist/chat/session-storage.d.ts +77 -0
  9. package/dist/chat/session-storage.js +233 -0
  10. package/dist/chat/session.d.ts +95 -0
  11. package/dist/chat/session.js +257 -0
  12. package/dist/chat/sse-handler.d.ts +49 -0
  13. package/dist/chat/sse-handler.js +266 -0
  14. package/dist/chat/types.d.ts +73 -0
  15. package/dist/chat/types.js +5 -0
  16. package/dist/chat/websocket-chat-handler.d.ts +36 -0
  17. package/dist/chat/websocket-chat-handler.js +262 -0
  18. package/dist/cli/commands/config.js +12 -12
  19. package/dist/cli/commands/mcp.js +3 -4
  20. package/dist/cli/index.d.ts +0 -7
  21. package/dist/cli/index.js +247 -28
  22. package/dist/config/configManager.d.ts +60 -0
  23. package/dist/config/configManager.js +300 -0
  24. package/dist/config/types.d.ts +136 -0
  25. package/dist/config/types.js +43 -0
  26. package/dist/core/analytics.d.ts +23 -0
  27. package/dist/core/analytics.js +131 -0
  28. package/dist/core/constants.d.ts +41 -0
  29. package/dist/core/constants.js +50 -0
  30. package/dist/core/defaults.d.ts +18 -0
  31. package/dist/core/defaults.js +29 -0
  32. package/dist/core/evaluation-config.d.ts +29 -0
  33. package/dist/core/evaluation-config.js +144 -0
  34. package/dist/core/evaluation-providers.d.ts +30 -0
  35. package/dist/core/evaluation-providers.js +187 -0
  36. package/dist/core/evaluation.d.ts +117 -0
  37. package/dist/core/evaluation.js +528 -0
  38. package/dist/core/factory.js +33 -25
  39. package/dist/core/types.d.ts +165 -6
  40. package/dist/core/types.js +3 -4
  41. package/dist/index.d.ts +9 -4
  42. package/dist/index.js +25 -4
  43. package/dist/lib/agent/direct-tools.d.ts +6 -6
  44. package/dist/lib/chat/client-utils.d.ts +92 -0
  45. package/dist/lib/chat/client-utils.js +298 -0
  46. package/dist/lib/chat/index.d.ts +27 -0
  47. package/dist/lib/chat/index.js +41 -0
  48. package/dist/lib/chat/session-storage.d.ts +77 -0
  49. package/dist/lib/chat/session-storage.js +233 -0
  50. package/dist/lib/chat/session.d.ts +95 -0
  51. package/dist/lib/chat/session.js +257 -0
  52. package/dist/lib/chat/sse-handler.d.ts +49 -0
  53. package/dist/lib/chat/sse-handler.js +266 -0
  54. package/dist/lib/chat/types.d.ts +73 -0
  55. package/dist/lib/chat/types.js +5 -0
  56. package/dist/lib/chat/websocket-chat-handler.d.ts +36 -0
  57. package/dist/lib/chat/websocket-chat-handler.js +262 -0
  58. package/dist/lib/config/configManager.d.ts +60 -0
  59. package/dist/lib/config/configManager.js +300 -0
  60. package/dist/lib/config/types.d.ts +136 -0
  61. package/dist/lib/config/types.js +43 -0
  62. package/dist/lib/core/analytics.d.ts +23 -0
  63. package/dist/lib/core/analytics.js +131 -0
  64. package/dist/lib/core/constants.d.ts +41 -0
  65. package/dist/lib/core/constants.js +50 -0
  66. package/dist/lib/core/defaults.d.ts +18 -0
  67. package/dist/lib/core/defaults.js +29 -0
  68. package/dist/lib/core/evaluation-config.d.ts +29 -0
  69. package/dist/lib/core/evaluation-config.js +144 -0
  70. package/dist/lib/core/evaluation-providers.d.ts +30 -0
  71. package/dist/lib/core/evaluation-providers.js +187 -0
  72. package/dist/lib/core/evaluation.d.ts +117 -0
  73. package/dist/lib/core/evaluation.js +528 -0
  74. package/dist/lib/core/factory.js +33 -26
  75. package/dist/lib/core/types.d.ts +165 -6
  76. package/dist/lib/core/types.js +3 -4
  77. package/dist/lib/index.d.ts +9 -4
  78. package/dist/lib/index.js +25 -4
  79. package/dist/lib/mcp/contracts/mcpContract.d.ts +118 -0
  80. package/dist/lib/mcp/contracts/mcpContract.js +5 -0
  81. package/dist/lib/mcp/dynamic-chain-executor.d.ts +201 -0
  82. package/dist/lib/mcp/dynamic-chain-executor.js +489 -0
  83. package/dist/lib/mcp/dynamic-orchestrator.d.ts +109 -0
  84. package/dist/lib/mcp/dynamic-orchestrator.js +351 -0
  85. package/dist/lib/mcp/error-manager.d.ts +254 -0
  86. package/dist/lib/mcp/error-manager.js +501 -0
  87. package/dist/lib/mcp/error-recovery.d.ts +158 -0
  88. package/dist/lib/mcp/error-recovery.js +405 -0
  89. package/dist/lib/mcp/function-calling.js +11 -3
  90. package/dist/lib/mcp/health-monitor.d.ts +256 -0
  91. package/dist/lib/mcp/health-monitor.js +621 -0
  92. package/dist/lib/mcp/logging.js +5 -0
  93. package/dist/lib/mcp/neurolink-mcp-client.js +2 -1
  94. package/dist/lib/mcp/orchestrator.d.ts +136 -5
  95. package/dist/lib/mcp/orchestrator.js +332 -16
  96. package/dist/lib/mcp/registry.d.ts +71 -16
  97. package/dist/lib/mcp/registry.js +104 -6
  98. package/dist/lib/mcp/semaphore-manager.d.ts +137 -0
  99. package/dist/lib/mcp/semaphore-manager.js +329 -0
  100. package/dist/lib/mcp/servers/ai-providers/ai-workflow-tools.d.ts +2 -2
  101. package/dist/lib/mcp/servers/ai-providers/ai-workflow-tools.js +5 -4
  102. package/dist/lib/mcp/session-manager.d.ts +186 -0
  103. package/dist/lib/mcp/session-manager.js +400 -0
  104. package/dist/lib/mcp/session-persistence.d.ts +93 -0
  105. package/dist/lib/mcp/session-persistence.js +298 -0
  106. package/dist/lib/mcp/tool-integration.js +1 -1
  107. package/dist/lib/mcp/tool-registry.d.ts +55 -34
  108. package/dist/lib/mcp/tool-registry.js +111 -97
  109. package/dist/lib/mcp/transport-manager.d.ts +153 -0
  110. package/dist/lib/mcp/transport-manager.js +330 -0
  111. package/dist/lib/mcp/unified-mcp.js +6 -1
  112. package/dist/lib/mcp/unified-registry.d.ts +54 -5
  113. package/dist/lib/mcp/unified-registry.js +139 -6
  114. package/dist/lib/neurolink.d.ts +101 -0
  115. package/dist/lib/neurolink.js +147 -1
  116. package/dist/lib/providers/agent-enhanced-provider.d.ts +11 -2
  117. package/dist/lib/providers/agent-enhanced-provider.js +86 -15
  118. package/dist/lib/providers/amazonBedrock.d.ts +9 -1
  119. package/dist/lib/providers/amazonBedrock.js +26 -2
  120. package/dist/lib/providers/analytics-helper.d.ts +53 -0
  121. package/dist/lib/providers/analytics-helper.js +151 -0
  122. package/dist/lib/providers/anthropic.d.ts +11 -1
  123. package/dist/lib/providers/anthropic.js +29 -4
  124. package/dist/lib/providers/azureOpenAI.d.ts +3 -1
  125. package/dist/lib/providers/azureOpenAI.js +28 -4
  126. package/dist/lib/providers/function-calling-provider.d.ts +9 -1
  127. package/dist/lib/providers/function-calling-provider.js +14 -1
  128. package/dist/lib/providers/googleAIStudio.d.ts +15 -1
  129. package/dist/lib/providers/googleAIStudio.js +32 -2
  130. package/dist/lib/providers/googleVertexAI.d.ts +9 -1
  131. package/dist/lib/providers/googleVertexAI.js +31 -2
  132. package/dist/lib/providers/huggingFace.d.ts +3 -1
  133. package/dist/lib/providers/huggingFace.js +26 -3
  134. package/dist/lib/providers/mcp-provider.d.ts +9 -1
  135. package/dist/lib/providers/mcp-provider.js +12 -0
  136. package/dist/lib/providers/mistralAI.d.ts +3 -1
  137. package/dist/lib/providers/mistralAI.js +25 -2
  138. package/dist/lib/providers/ollama.d.ts +3 -1
  139. package/dist/lib/providers/ollama.js +27 -4
  140. package/dist/lib/providers/openAI.d.ts +15 -1
  141. package/dist/lib/providers/openAI.js +32 -2
  142. package/dist/lib/proxy/proxy-fetch.js +8 -7
  143. package/dist/lib/services/streaming/streaming-manager.d.ts +29 -0
  144. package/dist/lib/services/streaming/streaming-manager.js +244 -0
  145. package/dist/lib/services/types.d.ts +155 -0
  146. package/dist/lib/services/types.js +2 -0
  147. package/dist/lib/services/websocket/websocket-server.d.ts +34 -0
  148. package/dist/lib/services/websocket/websocket-server.js +304 -0
  149. package/dist/lib/telemetry/index.d.ts +15 -0
  150. package/dist/lib/telemetry/index.js +22 -0
  151. package/dist/lib/telemetry/telemetry-service.d.ts +47 -0
  152. package/dist/lib/telemetry/telemetry-service.js +259 -0
  153. package/dist/lib/utils/streaming-utils.d.ts +67 -0
  154. package/dist/lib/utils/streaming-utils.js +201 -0
  155. package/dist/mcp/contracts/mcpContract.d.ts +118 -0
  156. package/dist/mcp/contracts/mcpContract.js +5 -0
  157. package/dist/mcp/dynamic-chain-executor.d.ts +201 -0
  158. package/dist/mcp/dynamic-chain-executor.js +489 -0
  159. package/dist/mcp/dynamic-orchestrator.d.ts +109 -0
  160. package/dist/mcp/dynamic-orchestrator.js +351 -0
  161. package/dist/mcp/error-manager.d.ts +254 -0
  162. package/dist/mcp/error-manager.js +501 -0
  163. package/dist/mcp/error-recovery.d.ts +158 -0
  164. package/dist/mcp/error-recovery.js +405 -0
  165. package/dist/mcp/function-calling.js +11 -3
  166. package/dist/mcp/health-monitor.d.ts +256 -0
  167. package/dist/mcp/health-monitor.js +621 -0
  168. package/dist/mcp/logging.js +5 -0
  169. package/dist/mcp/neurolink-mcp-client.js +2 -1
  170. package/dist/mcp/orchestrator.d.ts +136 -5
  171. package/dist/mcp/orchestrator.js +332 -16
  172. package/dist/mcp/plugins/core/neurolink-mcp.json +15 -15
  173. package/dist/mcp/registry.d.ts +71 -16
  174. package/dist/mcp/registry.js +104 -6
  175. package/dist/mcp/semaphore-manager.d.ts +137 -0
  176. package/dist/mcp/semaphore-manager.js +329 -0
  177. package/dist/mcp/servers/ai-providers/ai-workflow-tools.d.ts +2 -2
  178. package/dist/mcp/servers/ai-providers/ai-workflow-tools.js +5 -4
  179. package/dist/mcp/session-manager.d.ts +186 -0
  180. package/dist/mcp/session-manager.js +400 -0
  181. package/dist/mcp/session-persistence.d.ts +93 -0
  182. package/dist/mcp/session-persistence.js +299 -0
  183. package/dist/mcp/tool-integration.js +1 -1
  184. package/dist/mcp/tool-registry.d.ts +55 -34
  185. package/dist/mcp/tool-registry.js +111 -97
  186. package/dist/mcp/transport-manager.d.ts +153 -0
  187. package/dist/mcp/transport-manager.js +331 -0
  188. package/dist/mcp/unified-mcp.js +6 -1
  189. package/dist/mcp/unified-registry.d.ts +54 -5
  190. package/dist/mcp/unified-registry.js +139 -6
  191. package/dist/neurolink.d.ts +101 -0
  192. package/dist/neurolink.js +147 -1
  193. package/dist/providers/agent-enhanced-provider.d.ts +11 -2
  194. package/dist/providers/agent-enhanced-provider.js +86 -15
  195. package/dist/providers/amazonBedrock.d.ts +9 -1
  196. package/dist/providers/amazonBedrock.js +26 -2
  197. package/dist/providers/analytics-helper.d.ts +53 -0
  198. package/dist/providers/analytics-helper.js +151 -0
  199. package/dist/providers/anthropic.d.ts +11 -1
  200. package/dist/providers/anthropic.js +29 -4
  201. package/dist/providers/azureOpenAI.d.ts +3 -1
  202. package/dist/providers/azureOpenAI.js +29 -4
  203. package/dist/providers/function-calling-provider.d.ts +9 -1
  204. package/dist/providers/function-calling-provider.js +14 -1
  205. package/dist/providers/googleAIStudio.d.ts +15 -1
  206. package/dist/providers/googleAIStudio.js +32 -2
  207. package/dist/providers/googleVertexAI.d.ts +9 -1
  208. package/dist/providers/googleVertexAI.js +31 -2
  209. package/dist/providers/huggingFace.d.ts +3 -1
  210. package/dist/providers/huggingFace.js +26 -3
  211. package/dist/providers/mcp-provider.d.ts +9 -1
  212. package/dist/providers/mcp-provider.js +12 -0
  213. package/dist/providers/mistralAI.d.ts +3 -1
  214. package/dist/providers/mistralAI.js +25 -2
  215. package/dist/providers/ollama.d.ts +3 -1
  216. package/dist/providers/ollama.js +27 -4
  217. package/dist/providers/openAI.d.ts +15 -1
  218. package/dist/providers/openAI.js +33 -2
  219. package/dist/proxy/proxy-fetch.js +8 -7
  220. package/dist/services/streaming/streaming-manager.d.ts +29 -0
  221. package/dist/services/streaming/streaming-manager.js +244 -0
  222. package/dist/services/types.d.ts +155 -0
  223. package/dist/services/types.js +2 -0
  224. package/dist/services/websocket/websocket-server.d.ts +34 -0
  225. package/dist/services/websocket/websocket-server.js +304 -0
  226. package/dist/telemetry/index.d.ts +15 -0
  227. package/dist/telemetry/index.js +22 -0
  228. package/dist/telemetry/telemetry-service.d.ts +47 -0
  229. package/dist/telemetry/telemetry-service.js +261 -0
  230. package/dist/utils/streaming-utils.d.ts +67 -0
  231. package/dist/utils/streaming-utils.js +201 -0
  232. package/package.json +245 -228
@@ -2,10 +2,16 @@
2
2
  * NeuroLink MCP Tool Orchestration Engine
3
3
  * Central orchestrator for coordinated tool execution with pipeline management
4
4
  * Coordinates factory, registry, context, and AI tools for seamless operation
5
+ * Now with semaphore-based race condition prevention
5
6
  */
6
7
  import type { ToolResult } from "./factory.js";
7
8
  import { MCPToolRegistry, type ToolExecutionOptions } from "./tool-registry.js";
8
9
  import { ContextManager, type ContextRequest } from "./context-manager.js";
10
+ import { SemaphoreManager } from "./semaphore-manager.js";
11
+ import { SessionManager, type OrchestratorSession, type SessionOptions } from "./session-manager.js";
12
+ import { ErrorManager } from "./error-manager.js";
13
+ import { HealthMonitor, type HealthMonitorOptions } from "./health-monitor.js";
14
+ import { TransportManager, type TransportConfig, type TransportManagerOptions } from "./transport-manager.js";
9
15
  /**
10
16
  * Pipeline execution options
11
17
  */
@@ -67,10 +73,15 @@ export interface TextPipelineResult {
67
73
  * Central coordination engine for tool execution, pipelines, and AI operations
68
74
  */
69
75
  export declare class MCPOrchestrator {
70
- private registry;
71
- private contextManager;
72
- private pipelineCounter;
73
- constructor(registry?: MCPToolRegistry, contextManager?: ContextManager);
76
+ protected registry: MCPToolRegistry;
77
+ protected contextManager: ContextManager;
78
+ protected semaphoreManager: SemaphoreManager;
79
+ protected sessionManager: SessionManager;
80
+ protected errorManager: ErrorManager;
81
+ protected healthMonitor: HealthMonitor | null;
82
+ protected transportManager: TransportManager | null;
83
+ protected pipelineCounter: number;
84
+ constructor(registry?: MCPToolRegistry, contextManager?: ContextManager, semaphoreManager?: SemaphoreManager, sessionManager?: SessionManager, errorManager?: ErrorManager);
74
85
  /**
75
86
  * Initialize with default servers (AI Core)
76
87
  */
@@ -84,7 +95,9 @@ export declare class MCPOrchestrator {
84
95
  * @param options Execution options
85
96
  * @returns Tool execution result
86
97
  */
87
- executeTool(toolName: string, params: any, contextRequest?: ContextRequest, options?: ToolExecutionOptions): Promise<ToolResult>;
98
+ executeTool(toolName: string, params: any, contextRequest?: ContextRequest, options?: ToolExecutionOptions & {
99
+ sessionOptions?: SessionOptions;
100
+ }): Promise<ToolResult>;
88
101
  /**
89
102
  * Execute a pipeline of tools with dependency management
90
103
  *
@@ -118,10 +131,128 @@ export declare class MCPOrchestrator {
118
131
  getStats(): {
119
132
  registry: any;
120
133
  context: any;
134
+ session: any;
135
+ error: any;
136
+ health?: any;
121
137
  orchestrator: {
122
138
  pipelinesExecuted: number;
123
139
  };
124
140
  };
141
+ /**
142
+ * Get session by ID
143
+ *
144
+ * @param sessionId Session identifier
145
+ * @param extend Whether to extend session expiration
146
+ * @returns Session or null if not found
147
+ */
148
+ getSession(sessionId: string, extend?: boolean): Promise<OrchestratorSession | null>;
149
+ /**
150
+ * Create a new session for continuous tool calling
151
+ *
152
+ * @param contextRequest Context creation request
153
+ * @param sessionOptions Session configuration options
154
+ * @returns Created session
155
+ */
156
+ createSession(contextRequest?: ContextRequest, sessionOptions?: SessionOptions): Promise<OrchestratorSession>;
157
+ /**
158
+ * Set session state value
159
+ *
160
+ * @param sessionId Session identifier
161
+ * @param key State key
162
+ * @param value State value
163
+ * @returns Success status
164
+ */
165
+ setSessionState(sessionId: string, key: string, value: any): Promise<boolean>;
166
+ /**
167
+ * Get session state value
168
+ *
169
+ * @param sessionId Session identifier
170
+ * @param key State key
171
+ * @returns State value or undefined
172
+ */
173
+ getSessionState(sessionId: string, key: string): Promise<any>;
174
+ /**
175
+ * Get all active sessions
176
+ *
177
+ * @returns Array of active sessions
178
+ */
179
+ getActiveSessions(): Promise<OrchestratorSession[]>;
180
+ /**
181
+ * Clean up expired sessions
182
+ *
183
+ * @returns Number of sessions cleaned
184
+ */
185
+ cleanupSessions(): Promise<number>;
186
+ /**
187
+ * Get error history
188
+ *
189
+ * @param filter Optional filter criteria
190
+ * @returns Filtered error history
191
+ */
192
+ getErrorHistory(filter?: Parameters<ErrorManager["getErrorHistory"]>[0]): import("./error-manager.js").ErrorEntry[];
193
+ /**
194
+ * Clear error history
195
+ */
196
+ clearErrorHistory(): void;
197
+ /**
198
+ * Get recovery suggestion for last error
199
+ *
200
+ * @param sessionId Optional session ID to get last error from
201
+ * @returns Recovery suggestion or null
202
+ */
203
+ getLastErrorRecovery(sessionId?: string): string | null;
204
+ /**
205
+ * Initialize health monitoring
206
+ *
207
+ * @param options Health monitor options
208
+ */
209
+ initializeHealthMonitor(options?: HealthMonitorOptions): void;
210
+ /**
211
+ * Start health monitoring for all registered servers
212
+ */
213
+ startHealthMonitoring(): void;
214
+ /**
215
+ * Stop health monitoring
216
+ */
217
+ stopHealthMonitoring(): void;
218
+ /**
219
+ * Register recovery callback for a server
220
+ *
221
+ * @param serverId Server ID
222
+ * @param callback Recovery callback
223
+ */
224
+ registerRecoveryCallback(serverId: string, callback: (serverId: string) => Promise<void>): void;
225
+ /**
226
+ * Get health status for all servers
227
+ *
228
+ * @returns Map of server health status
229
+ */
230
+ getHealthStatus(): Map<any, any>;
231
+ /**
232
+ * Initialize transport manager for MCP connections
233
+ *
234
+ * @param options Transport manager options
235
+ */
236
+ initializeTransportManager(options?: TransportManagerOptions): void;
237
+ /**
238
+ * Connect to MCP server using specified transport
239
+ *
240
+ * @param config Transport configuration
241
+ * @returns Connected MCP client
242
+ */
243
+ connectTransport(config: TransportConfig): Promise<any>;
244
+ /**
245
+ * Disconnect from MCP server
246
+ */
247
+ disconnectTransport(): Promise<void>;
248
+ /**
249
+ * Get transport connection status
250
+ */
251
+ getTransportStatus(): import("./transport-manager.js").TransportStatus;
252
+ /**
253
+ * Check if transport is connected
254
+ */
255
+ isTransportConnected(): boolean;
125
256
  /**
126
257
  * Execute parallel pipeline with dependency management
127
258
  *
@@ -2,9 +2,15 @@
2
2
  * NeuroLink MCP Tool Orchestration Engine
3
3
  * Central orchestrator for coordinated tool execution with pipeline management
4
4
  * Coordinates factory, registry, context, and AI tools for seamless operation
5
+ * Now with semaphore-based race condition prevention
5
6
  */
6
7
  import { MCPToolRegistry, defaultToolRegistry, } from "./tool-registry.js";
7
8
  import { ContextManager, defaultContextManager, createExecutionContext, } from "./context-manager.js";
9
+ import { SemaphoreManager, defaultSemaphoreManager, } from "./semaphore-manager.js";
10
+ import { SessionManager, defaultSessionManager, } from "./session-manager.js";
11
+ import { ErrorManager, defaultErrorManager, ErrorCategory, ErrorSeverity, } from "./error-manager.js";
12
+ import { HealthMonitor, initializeHealthMonitor, } from "./health-monitor.js";
13
+ import { TransportManager, } from "./transport-manager.js";
8
14
  import { aiCoreServer } from "./servers/ai-providers/ai-core-server.js";
9
15
  /**
10
16
  * NeuroLink MCP Tool Orchestrator
@@ -13,10 +19,18 @@ import { aiCoreServer } from "./servers/ai-providers/ai-core-server.js";
13
19
  export class MCPOrchestrator {
14
20
  registry;
15
21
  contextManager;
22
+ semaphoreManager;
23
+ sessionManager;
24
+ errorManager;
25
+ healthMonitor = null;
26
+ transportManager = null;
16
27
  pipelineCounter = 0;
17
- constructor(registry, contextManager) {
28
+ constructor(registry, contextManager, semaphoreManager, sessionManager, errorManager) {
18
29
  this.registry = registry || defaultToolRegistry;
19
30
  this.contextManager = contextManager || defaultContextManager;
31
+ this.semaphoreManager = semaphoreManager || defaultSemaphoreManager;
32
+ this.sessionManager = sessionManager || defaultSessionManager;
33
+ this.errorManager = errorManager || defaultErrorManager;
20
34
  // Initialize with AI Core Server
21
35
  this.initializeDefaultServers();
22
36
  }
@@ -26,7 +40,10 @@ export class MCPOrchestrator {
26
40
  async initializeDefaultServers() {
27
41
  try {
28
42
  await this.registry.registerServer(aiCoreServer.id, aiCoreServer);
29
- console.log("[Orchestrator] Initialized with AI Core Server");
43
+ // Only log in debug mode
44
+ if (process.env.NEUROLINK_DEBUG === "true") {
45
+ console.log("[Orchestrator] Initialized with AI Core Server");
46
+ }
30
47
  }
31
48
  catch (error) {
32
49
  console.warn("[Orchestrator] Failed to register AI Core Server:", error);
@@ -44,11 +61,89 @@ export class MCPOrchestrator {
44
61
  async executeTool(toolName, params, contextRequest = {}, options = {}) {
45
62
  // Create execution context
46
63
  const context = this.contextManager.createContext(contextRequest);
47
- console.log(`[Orchestrator] Executing tool '${toolName}' in session ${context.sessionId}`);
48
- // Execute tool through registry
49
- const result = await this.registry.executeTool(toolName, params, context);
50
- console.log(`[Orchestrator] Tool '${toolName}' execution ${result.success ? "completed" : "failed"}`);
51
- return result;
64
+ // Get or create session for continuous tool calling
65
+ let session = null;
66
+ if (context.sessionId) {
67
+ session = await this.sessionManager.getSession(context.sessionId);
68
+ }
69
+ if (!session) {
70
+ // Create new session with options
71
+ session = await this.sessionManager.createSession(context, options.sessionOptions);
72
+ // Update context with new session ID
73
+ context.sessionId = session.id;
74
+ }
75
+ if (process.env.NEUROLINK_DEBUG === "true") {
76
+ console.log(`[Orchestrator] Executing tool '${toolName}' in session ${context.sessionId}`);
77
+ }
78
+ // Use semaphore to prevent race conditions for the same tool
79
+ // Each tool gets its own semaphore key to allow parallel execution of different tools
80
+ const semaphoreKey = `tool:${toolName}`;
81
+ const semaphoreResult = await this.semaphoreManager.acquire(semaphoreKey, async () => {
82
+ try {
83
+ // Execute tool through registry
84
+ const result = await this.registry.executeTool(toolName, params, context);
85
+ if (process.env.NEUROLINK_DEBUG === "true") {
86
+ console.log(`[Orchestrator] Tool '${toolName}' execution ${result.success ? "completed" : "failed"}`);
87
+ }
88
+ // Record error if tool execution failed
89
+ if (!result.success && result.error) {
90
+ this.errorManager.recordError(result.error, {
91
+ category: ErrorCategory.TOOL_ERROR,
92
+ severity: ErrorSeverity.HIGH,
93
+ sessionId: session.id,
94
+ toolName,
95
+ parameters: params,
96
+ executionContext: context,
97
+ });
98
+ }
99
+ return result;
100
+ }
101
+ catch (error) {
102
+ // Record unexpected errors
103
+ const errorEntry = await this.errorManager.recordError(error, {
104
+ category: ErrorCategory.TOOL_ERROR,
105
+ severity: ErrorSeverity.CRITICAL,
106
+ sessionId: session.id,
107
+ toolName,
108
+ parameters: params,
109
+ executionContext: context,
110
+ });
111
+ // Return error result
112
+ return {
113
+ success: false,
114
+ data: null,
115
+ error: errorEntry.error,
116
+ usage: {},
117
+ };
118
+ }
119
+ }, context);
120
+ // Handle semaphore errors
121
+ if (!semaphoreResult.success) {
122
+ const errorResult = {
123
+ success: false,
124
+ data: null,
125
+ error: semaphoreResult.error || new Error("Semaphore acquisition failed"),
126
+ usage: {
127
+ executionTime: semaphoreResult.executionTime,
128
+ waitTime: semaphoreResult.waitTime,
129
+ },
130
+ };
131
+ // Update session with error result
132
+ await this.sessionManager.updateSession(session.id, errorResult);
133
+ return errorResult;
134
+ }
135
+ const result = semaphoreResult.result;
136
+ // Update session with tool result
137
+ await this.sessionManager.updateSession(session.id, result);
138
+ // Enhance result with session information
139
+ return {
140
+ ...result,
141
+ sessionId: session.id,
142
+ sessionData: {
143
+ toolHistory: session.toolHistory.length,
144
+ state: Object.fromEntries(session.state),
145
+ },
146
+ };
52
147
  }
53
148
  /**
54
149
  * Execute a pipeline of tools with dependency management
@@ -88,13 +183,30 @@ export class MCPOrchestrator {
88
183
  const stepId = step.stepId || `step-${stepsExecuted + 1}`;
89
184
  try {
90
185
  console.log(`[Orchestrator] Executing step: ${stepId} (${step.toolName})`);
91
- const stepResult = await this.registry.executeTool(step.toolName, step.params, context);
186
+ // Use semaphore for each tool execution in pipeline
187
+ const semaphoreKey = `tool:${step.toolName}`;
188
+ const semaphoreResult = await this.semaphoreManager.acquire(semaphoreKey, async () => {
189
+ return await this.registry.executeTool(step.toolName, step.params, context);
190
+ }, context);
191
+ const stepResult = semaphoreResult.success
192
+ ? semaphoreResult.result
193
+ : {
194
+ success: false,
195
+ data: null,
196
+ error: semaphoreResult.error ||
197
+ new Error("Semaphore acquisition failed"),
198
+ usage: {
199
+ executionTime: semaphoreResult.executionTime,
200
+ waitTime: semaphoreResult.waitTime,
201
+ },
202
+ };
92
203
  results.set(stepId, stepResult);
93
204
  stepsExecuted++;
94
205
  if (!stepResult.success) {
95
- const errorMessage = stepResult.error instanceof Error
96
- ? stepResult.error.message
97
- : stepResult.error || "Unknown error";
206
+ const error = stepResult.error;
207
+ const errorMessage = error instanceof Error
208
+ ? error.message
209
+ : String(error) || "Unknown error";
98
210
  errors.set(stepId, errorMessage);
99
211
  if (stopOnError) {
100
212
  console.error(`[Orchestrator] Pipeline ${pipelineId} stopped due to error in step ${stepId}`);
@@ -257,13 +369,200 @@ export class MCPOrchestrator {
257
369
  * @returns Comprehensive orchestrator statistics
258
370
  */
259
371
  getStats() {
260
- return {
372
+ const stats = {
261
373
  registry: this.registry.getStats(),
262
374
  context: this.contextManager.getStats(),
375
+ session: this.sessionManager.getStats(),
376
+ error: this.errorManager.getStats(),
263
377
  orchestrator: {
264
378
  pipelinesExecuted: this.pipelineCounter,
265
379
  },
266
380
  };
381
+ if (this.healthMonitor) {
382
+ const healthStatus = this.healthMonitor.getHealthStatus();
383
+ stats.health = {
384
+ servers: Array.from(healthStatus.entries()).map(([id, health]) => ({
385
+ id,
386
+ status: health.status,
387
+ checkCount: health.checkCount,
388
+ errorCount: health.errorCount,
389
+ lastSuccessfulCheck: health.lastSuccessfulCheck,
390
+ })),
391
+ };
392
+ }
393
+ return stats;
394
+ }
395
+ /**
396
+ * Get session by ID
397
+ *
398
+ * @param sessionId Session identifier
399
+ * @param extend Whether to extend session expiration
400
+ * @returns Session or null if not found
401
+ */
402
+ async getSession(sessionId, extend = true) {
403
+ return this.sessionManager.getSession(sessionId, extend);
404
+ }
405
+ /**
406
+ * Create a new session for continuous tool calling
407
+ *
408
+ * @param contextRequest Context creation request
409
+ * @param sessionOptions Session configuration options
410
+ * @returns Created session
411
+ */
412
+ async createSession(contextRequest = {}, sessionOptions) {
413
+ const context = this.contextManager.createContext(contextRequest);
414
+ return this.sessionManager.createSession(context, sessionOptions);
415
+ }
416
+ /**
417
+ * Set session state value
418
+ *
419
+ * @param sessionId Session identifier
420
+ * @param key State key
421
+ * @param value State value
422
+ * @returns Success status
423
+ */
424
+ async setSessionState(sessionId, key, value) {
425
+ return this.sessionManager.setSessionState(sessionId, key, value) !== null;
426
+ }
427
+ /**
428
+ * Get session state value
429
+ *
430
+ * @param sessionId Session identifier
431
+ * @param key State key
432
+ * @returns State value or undefined
433
+ */
434
+ async getSessionState(sessionId, key) {
435
+ return this.sessionManager.getSessionState(sessionId, key);
436
+ }
437
+ /**
438
+ * Get all active sessions
439
+ *
440
+ * @returns Array of active sessions
441
+ */
442
+ async getActiveSessions() {
443
+ return this.sessionManager.getActiveSessions();
444
+ }
445
+ /**
446
+ * Clean up expired sessions
447
+ *
448
+ * @returns Number of sessions cleaned
449
+ */
450
+ async cleanupSessions() {
451
+ return this.sessionManager.cleanup();
452
+ }
453
+ /**
454
+ * Get error history
455
+ *
456
+ * @param filter Optional filter criteria
457
+ * @returns Filtered error history
458
+ */
459
+ getErrorHistory(filter) {
460
+ return this.errorManager.getErrorHistory(filter);
461
+ }
462
+ /**
463
+ * Clear error history
464
+ */
465
+ clearErrorHistory() {
466
+ this.errorManager.clearHistory();
467
+ }
468
+ /**
469
+ * Get recovery suggestion for last error
470
+ *
471
+ * @param sessionId Optional session ID to get last error from
472
+ * @returns Recovery suggestion or null
473
+ */
474
+ getLastErrorRecovery(sessionId) {
475
+ const filter = sessionId ? { sessionId, limit: 1 } : { limit: 1 };
476
+ const errors = this.errorManager.getErrorHistory(filter);
477
+ if (errors.length > 0) {
478
+ return this.errorManager.getRecoverySuggestion(errors[0]);
479
+ }
480
+ return null;
481
+ }
482
+ /**
483
+ * Initialize health monitoring
484
+ *
485
+ * @param options Health monitor options
486
+ */
487
+ initializeHealthMonitor(options) {
488
+ this.healthMonitor = initializeHealthMonitor(this.registry, this.errorManager, options);
489
+ }
490
+ /**
491
+ * Start health monitoring for all registered servers
492
+ */
493
+ startHealthMonitoring() {
494
+ if (!this.healthMonitor) {
495
+ this.initializeHealthMonitor();
496
+ }
497
+ this.healthMonitor.startMonitoring();
498
+ }
499
+ /**
500
+ * Stop health monitoring
501
+ */
502
+ stopHealthMonitoring() {
503
+ this.healthMonitor?.stopMonitoring();
504
+ }
505
+ /**
506
+ * Register recovery callback for a server
507
+ *
508
+ * @param serverId Server ID
509
+ * @param callback Recovery callback
510
+ */
511
+ registerRecoveryCallback(serverId, callback) {
512
+ if (!this.healthMonitor) {
513
+ this.initializeHealthMonitor();
514
+ }
515
+ this.healthMonitor.registerRecoveryCallback(serverId, callback);
516
+ }
517
+ /**
518
+ * Get health status for all servers
519
+ *
520
+ * @returns Map of server health status
521
+ */
522
+ getHealthStatus() {
523
+ return this.healthMonitor?.getHealthStatus() || new Map();
524
+ }
525
+ /**
526
+ * Initialize transport manager for MCP connections
527
+ *
528
+ * @param options Transport manager options
529
+ */
530
+ initializeTransportManager(options) {
531
+ this.transportManager = new TransportManager(this.errorManager, options);
532
+ }
533
+ /**
534
+ * Connect to MCP server using specified transport
535
+ *
536
+ * @param config Transport configuration
537
+ * @returns Connected MCP client
538
+ */
539
+ async connectTransport(config) {
540
+ if (!this.transportManager) {
541
+ this.initializeTransportManager();
542
+ }
543
+ return this.transportManager.connect(config);
544
+ }
545
+ /**
546
+ * Disconnect from MCP server
547
+ */
548
+ async disconnectTransport() {
549
+ await this.transportManager?.disconnect();
550
+ }
551
+ /**
552
+ * Get transport connection status
553
+ */
554
+ getTransportStatus() {
555
+ return (this.transportManager?.getStatus() || {
556
+ connected: false,
557
+ type: "stdio",
558
+ reconnectAttempts: 0,
559
+ });
560
+ }
561
+ /**
562
+ * Check if transport is connected
563
+ */
564
+ isTransportConnected() {
565
+ return this.transportManager?.isConnected() || false;
267
566
  }
268
567
  /**
269
568
  * Execute parallel pipeline with dependency management
@@ -298,12 +597,29 @@ export class MCPOrchestrator {
298
597
  executing.add(stepId);
299
598
  const step = stepMap.get(stepId);
300
599
  try {
301
- const result = await this.registry.executeTool(step.toolName, step.params, context);
600
+ // Use semaphore for parallel execution to prevent race conditions
601
+ const semaphoreKey = `tool:${step.toolName}`;
602
+ const semaphoreResult = await this.semaphoreManager.acquire(semaphoreKey, async () => {
603
+ return await this.registry.executeTool(step.toolName, step.params, context);
604
+ }, context);
605
+ const result = semaphoreResult.success
606
+ ? semaphoreResult.result
607
+ : {
608
+ success: false,
609
+ data: null,
610
+ error: semaphoreResult.error ||
611
+ new Error("Semaphore acquisition failed"),
612
+ usage: {
613
+ executionTime: semaphoreResult.executionTime,
614
+ waitTime: semaphoreResult.waitTime,
615
+ },
616
+ };
302
617
  results.set(stepId, result);
303
618
  if (!result.success) {
304
- const errorMessage = result.error instanceof Error
305
- ? result.error.message
306
- : result.error || "Unknown error";
619
+ const error = result.error;
620
+ const errorMessage = error instanceof Error
621
+ ? error.message
622
+ : String(error) || "Unknown error";
307
623
  errors.set(stepId, errorMessage);
308
624
  }
309
625
  }
@@ -1,17 +1,17 @@
1
1
  {
2
- "name": "@neurolink-mcp/filesystem",
3
- "version": "1.0.0",
4
- "main": "./filesystem-mcp.js",
5
- "description": "Provides secure file system operations for NeuroLink agents",
6
- "author": "NeuroLink Team",
7
- "license": "MIT",
8
- "engine": {
9
- "neurolink": ">=1.9.0 <2.0.0"
10
- },
11
- "permissions": [
12
- "fs:read:./**/*",
13
- "fs:write:./output/**/*",
14
- "fs:write:./temp/**/*"
15
- ],
16
- "keywords": ["filesystem", "file", "mcp", "plugin"]
2
+ "name": "@neurolink-mcp/filesystem",
3
+ "version": "1.0.0",
4
+ "main": "./filesystem-mcp.js",
5
+ "description": "Provides secure file system operations for NeuroLink agents",
6
+ "author": "NeuroLink Team",
7
+ "license": "MIT",
8
+ "engine": {
9
+ "neurolink": ">=1.9.0 <2.0.0"
10
+ },
11
+ "permissions": [
12
+ "fs:read:./**/*",
13
+ "fs:write:./output/**/*",
14
+ "fs:write:./temp/**/*"
15
+ ],
16
+ "keywords": ["filesystem", "file", "mcp", "plugin"]
17
17
  }