@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,703 +0,0 @@
1
- /**
2
- * NeuroLink MCP Tool Orchestration Engine
3
- * Central orchestrator for coordinated tool execution with pipeline management
4
- * Coordinates factory, registry, context, and AI tools for seamless operation
5
- * Now with semaphore-based race condition prevention
6
- */
7
- import { defaultToolRegistry, } from "./tool-registry.js";
8
- import { defaultContextManager, } from "./context-manager.js";
9
- import { defaultSemaphoreManager, } from "./semaphore-manager.js";
10
- import { defaultSessionManager, } from "./session-manager.js";
11
- import { defaultErrorManager, ErrorCategory, ErrorSeverity, } from "./error-manager.js";
12
- import { initializeHealthMonitor, } from "./health-monitor.js";
13
- import { TransportManager, } from "./transport-manager.js";
14
- import { aiCoreServer } from "./servers/ai-providers/ai-core-server.js";
15
- /**
16
- * NeuroLink MCP Tool Orchestrator
17
- * Central coordination engine for tool execution, pipelines, and AI operations
18
- */
19
- export class MCPOrchestrator {
20
- registry;
21
- contextManager;
22
- semaphoreManager;
23
- sessionManager;
24
- errorManager;
25
- healthMonitor = null;
26
- transportManager = null;
27
- pipelineCounter = 0;
28
- constructor(registry, contextManager, semaphoreManager, sessionManager, errorManager) {
29
- this.registry = registry || defaultToolRegistry;
30
- this.contextManager = contextManager || defaultContextManager;
31
- this.semaphoreManager = semaphoreManager || defaultSemaphoreManager;
32
- this.sessionManager = sessionManager || defaultSessionManager;
33
- this.errorManager = errorManager || defaultErrorManager;
34
- // Initialize with AI Core Server
35
- this.initializeDefaultServers();
36
- }
37
- /**
38
- * Initialize with default servers (AI Core)
39
- */
40
- async initializeDefaultServers() {
41
- try {
42
- await this.registry.registerServer(aiCoreServer.id, aiCoreServer);
43
- // Only log in debug mode
44
- if (process.env.NEUROLINK_DEBUG === "true") {
45
- console.log("[Orchestrator] Initialized with AI Core Server");
46
- }
47
- }
48
- catch (error) {
49
- console.warn("[Orchestrator] Failed to register AI Core Server:", error);
50
- }
51
- }
52
- /**
53
- * Execute a single tool with full orchestration
54
- *
55
- * @param toolName Tool name to execute
56
- * @param params Tool parameters
57
- * @param contextRequest Context creation request
58
- * @param options Execution options
59
- * @returns Tool execution result
60
- */
61
- async executeTool(toolName, params, contextRequest = {}, options = {}) {
62
- // Create execution context
63
- const context = this.contextManager.createContext(contextRequest);
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
- const oldSessionId = context.sessionId;
74
- context.sessionId = session.id;
75
- // Remove old context and store updated context in context manager
76
- if (oldSessionId) {
77
- this.contextManager.removeContext(oldSessionId);
78
- }
79
- // Store the updated context with the new session ID
80
- this.contextManager.storeContext(context);
81
- }
82
- if (process.env.NEUROLINK_DEBUG === "true") {
83
- console.log(`[Orchestrator] Executing tool '${toolName}' in session ${context.sessionId}`);
84
- }
85
- // Use semaphore to prevent race conditions for the same tool
86
- // Each tool gets its own semaphore key to allow parallel execution of different tools
87
- const semaphoreKey = `tool:${toolName}`;
88
- const semaphoreResult = await this.semaphoreManager.acquire(semaphoreKey, async () => {
89
- try {
90
- // Add tool to the execution chain
91
- this.contextManager.addToToolChain(context, toolName);
92
- // Execute tool through registry
93
- const result = await this.registry.executeTool(toolName, params, context);
94
- if (process.env.NEUROLINK_DEBUG === "true") {
95
- console.log(`[Orchestrator] Tool '${toolName}' execution ${result.success ? "completed" : "failed"}`);
96
- }
97
- // Record error if tool execution failed
98
- if (!result.success && result.error) {
99
- this.errorManager.recordError(result.error, {
100
- category: ErrorCategory.TOOL_ERROR,
101
- severity: ErrorSeverity.HIGH,
102
- sessionId: session.id,
103
- toolName,
104
- parameters: params,
105
- executionContext: context,
106
- });
107
- }
108
- return result;
109
- }
110
- catch (error) {
111
- // Record unexpected errors
112
- const errorEntry = await this.errorManager.recordError(error, {
113
- category: ErrorCategory.TOOL_ERROR,
114
- severity: ErrorSeverity.CRITICAL,
115
- sessionId: session.id,
116
- toolName,
117
- parameters: params,
118
- executionContext: context,
119
- });
120
- // Return error result
121
- return {
122
- success: false,
123
- data: null,
124
- error: errorEntry.error,
125
- usage: {},
126
- };
127
- }
128
- }, context);
129
- // Handle semaphore errors
130
- if (!semaphoreResult.success) {
131
- const errorResult = {
132
- success: false,
133
- data: null,
134
- error: semaphoreResult.error || new Error("Semaphore acquisition failed"),
135
- usage: {
136
- executionTime: semaphoreResult.executionTime,
137
- waitTime: semaphoreResult.waitTime,
138
- },
139
- };
140
- // Update session with error result
141
- await this.sessionManager.updateSession(session.id, errorResult);
142
- return errorResult;
143
- }
144
- const result = semaphoreResult.result;
145
- // Update session with tool result
146
- await this.sessionManager.updateSession(session.id, result);
147
- // Enhance result with session information
148
- return {
149
- ...result,
150
- sessionId: session.id,
151
- sessionData: {
152
- toolHistory: session.toolHistory.length,
153
- state: Object.fromEntries(session.state),
154
- },
155
- };
156
- }
157
- /**
158
- * Execute a pipeline of tools with dependency management
159
- *
160
- * @param steps Pipeline steps to execute
161
- * @param contextRequest Context creation request
162
- * @param options Pipeline execution options
163
- * @returns Pipeline execution result
164
- */
165
- async executePipeline(steps, contextRequest = {}, options = {}) {
166
- const startTime = Date.now();
167
- const pipelineId = this.generatePipelineId();
168
- const { stopOnError = true, parallel = false, timeout = 60000, trackMetrics = true, validateInputs = true, } = options;
169
- // Create shared execution context
170
- const context = this.contextManager.createContext({
171
- ...contextRequest,
172
- sessionId: contextRequest.sessionId || pipelineId,
173
- });
174
- const results = new Map();
175
- const errors = new Map();
176
- let stepsExecuted = 0;
177
- let stepsSkipped = 0;
178
- console.log(`[Orchestrator] Starting pipeline ${pipelineId} with ${steps.length} steps`);
179
- try {
180
- if (parallel) {
181
- // Execute steps in parallel with dependency management
182
- await this.executeParallelPipeline(steps, context, results, errors, {
183
- timeout,
184
- trackMetrics,
185
- validateInputs,
186
- stopOnError,
187
- });
188
- }
189
- else {
190
- // Execute steps sequentially
191
- for (const step of steps) {
192
- const stepId = step.stepId || `step-${stepsExecuted + 1}`;
193
- try {
194
- console.log(`[Orchestrator] Executing step: ${stepId} (${step.toolName})`);
195
- // Use semaphore for each tool execution in pipeline
196
- const semaphoreKey = `tool:${step.toolName}`;
197
- const semaphoreResult = await this.semaphoreManager.acquire(semaphoreKey, async () => {
198
- return await this.registry.executeTool(step.toolName, step.params, context);
199
- }, context);
200
- const stepResult = semaphoreResult.success
201
- ? semaphoreResult.result
202
- : {
203
- success: false,
204
- data: null,
205
- error: semaphoreResult.error ||
206
- new Error("Semaphore acquisition failed"),
207
- usage: {
208
- executionTime: semaphoreResult.executionTime,
209
- waitTime: semaphoreResult.waitTime,
210
- },
211
- };
212
- results.set(stepId, stepResult);
213
- stepsExecuted++;
214
- if (!stepResult.success) {
215
- const error = stepResult.error;
216
- const errorMessage = error instanceof Error
217
- ? error.message
218
- : String(error) || "Unknown error";
219
- errors.set(stepId, errorMessage);
220
- if (stopOnError) {
221
- console.error(`[Orchestrator] Pipeline ${pipelineId} stopped due to error in step ${stepId}`);
222
- break;
223
- }
224
- }
225
- }
226
- catch (error) {
227
- const errorMessage = error instanceof Error ? error.message : String(error);
228
- errors.set(stepId, errorMessage);
229
- if (stopOnError) {
230
- console.error(`[Orchestrator] Pipeline ${pipelineId} stopped due to exception in step ${stepId}: ${errorMessage}`);
231
- break;
232
- }
233
- stepsSkipped++;
234
- }
235
- }
236
- }
237
- const executionTime = Date.now() - startTime;
238
- const success = errors.size === 0 || !stopOnError;
239
- console.log(`[Orchestrator] Pipeline ${pipelineId} completed in ${executionTime}ms - ${success ? "SUCCESS" : "FAILED"}`);
240
- return {
241
- success,
242
- results,
243
- errors,
244
- executionTime,
245
- stepsExecuted,
246
- stepsSkipped,
247
- metadata: {
248
- pipelineId,
249
- sessionId: context.sessionId,
250
- timestamp: Date.now(),
251
- parallel,
252
- },
253
- };
254
- }
255
- catch (error) {
256
- const executionTime = Date.now() - startTime;
257
- const errorMessage = error instanceof Error ? error.message : String(error);
258
- console.error(`[Orchestrator] Pipeline ${pipelineId} failed: ${errorMessage}`);
259
- return {
260
- success: false,
261
- results,
262
- errors: new Map([["pipeline", errorMessage]]),
263
- executionTime,
264
- stepsExecuted,
265
- stepsSkipped,
266
- metadata: {
267
- pipelineId,
268
- sessionId: context.sessionId,
269
- timestamp: Date.now(),
270
- parallel,
271
- },
272
- };
273
- }
274
- }
275
- /**
276
- * Execute AI text generation pipeline (high-level convenience method)
277
- *
278
- * @param prompt Text prompt for generation
279
- * @param contextRequest Context creation request
280
- * @param options Additional generation options
281
- * @returns Text generation result
282
- */
283
- async executeTextPipeline(prompt, contextRequest = {}, options = {}) {
284
- const startTime = Date.now();
285
- // Create execution context
286
- const context = this.contextManager.createContext(contextRequest);
287
- try {
288
- console.log(`[Orchestrator] Starting text pipeline for prompt: "${prompt.substring(0, 50)}..."`);
289
- // Build pipeline steps
290
- const steps = [];
291
- // Step 1: Provider selection (if not specified)
292
- if (!options.provider) {
293
- steps.push({
294
- stepId: "select-provider",
295
- toolName: "select-provider",
296
- params: {
297
- requirements: {
298
- maxTokens: options.maxTokens || 1000,
299
- costEfficient: true,
300
- },
301
- },
302
- });
303
- }
304
- // Step 2: Text generation
305
- steps.push({
306
- stepId: "generate",
307
- toolName: "generate",
308
- params: {
309
- prompt,
310
- provider: options.provider || "auto",
311
- model: options.model || "default",
312
- temperature: options.temperature || 0.7,
313
- maxTokens: options.maxTokens || 1000,
314
- systemPrompt: options.systemPrompt || "",
315
- },
316
- dependsOn: options.provider ? [] : ["select-provider"],
317
- });
318
- // Step 3: Custom tools (if specified)
319
- if (options.customTools && options.customTools.length > 0) {
320
- for (const toolName of options.customTools) {
321
- steps.push({
322
- stepId: `custom-${toolName}`,
323
- toolName,
324
- params: {
325
- /* tool-specific params */
326
- },
327
- dependsOn: ["generate"],
328
- });
329
- }
330
- }
331
- // Execute pipeline
332
- const pipelineResult = await this.executePipeline(steps, contextRequest, {
333
- stopOnError: true,
334
- parallel: false,
335
- trackMetrics: true,
336
- });
337
- const executionTime = Date.now() - startTime;
338
- // Extract text generation result
339
- const textResult = pipelineResult.results.get("generate");
340
- const providerResult = pipelineResult.results.get("select-provider");
341
- if (!textResult || !textResult.success) {
342
- throw new Error("Text generation failed");
343
- }
344
- const toolsUsed = Array.from(pipelineResult.results.keys());
345
- console.log(`[Orchestrator] Text pipeline completed in ${executionTime}ms`);
346
- return {
347
- success: true,
348
- text: textResult.data?.text,
349
- provider: textResult.data?.provider ||
350
- providerResult?.data?.provider,
351
- model: textResult.data?.model,
352
- executionTime,
353
- usage: textResult.usage,
354
- metadata: {
355
- sessionId: context.sessionId,
356
- timestamp: Date.now(),
357
- toolsUsed,
358
- },
359
- };
360
- }
361
- catch (error) {
362
- const executionTime = Date.now() - startTime;
363
- const errorMessage = error instanceof Error ? error.message : String(error);
364
- console.error(`[Orchestrator] Text pipeline failed: ${errorMessage}`);
365
- return {
366
- success: false,
367
- executionTime,
368
- metadata: {
369
- sessionId: context.sessionId,
370
- timestamp: Date.now(),
371
- toolsUsed: [],
372
- },
373
- };
374
- }
375
- }
376
- /**
377
- * Get orchestrator statistics
378
- *
379
- * @returns Comprehensive orchestrator statistics
380
- */
381
- getStats() {
382
- const stats = {
383
- registry: this.registry.getStats(),
384
- context: this.contextManager.getStats(),
385
- session: this.sessionManager.getStats(),
386
- error: this.errorManager.getStats(),
387
- orchestrator: {
388
- pipelinesExecuted: this.pipelineCounter,
389
- },
390
- };
391
- if (this.healthMonitor) {
392
- const healthStatus = this.healthMonitor.getHealthStatus();
393
- stats.health = {
394
- servers: Array.from(healthStatus.entries()).map(([id, health]) => ({
395
- id,
396
- status: health.status,
397
- checkCount: health.checkCount,
398
- errorCount: health.errorCount,
399
- lastSuccessfulCheck: health.lastSuccessfulCheck,
400
- })),
401
- };
402
- }
403
- return stats;
404
- }
405
- /**
406
- * Get session by ID
407
- *
408
- * @param sessionId Session identifier
409
- * @param extend Whether to extend session expiration
410
- * @returns Session or null if not found
411
- */
412
- async getSession(sessionId, extend = true) {
413
- return this.sessionManager.getSession(sessionId, extend);
414
- }
415
- /**
416
- * Create a new session for continuous tool calling
417
- *
418
- * @param contextRequest Context creation request
419
- * @param sessionOptions Session configuration options
420
- * @returns Created session
421
- */
422
- async createSession(contextRequest = {}, sessionOptions) {
423
- const context = this.contextManager.createContext(contextRequest);
424
- return this.sessionManager.createSession(context, sessionOptions);
425
- }
426
- /**
427
- * Set session state value
428
- *
429
- * @param sessionId Session identifier
430
- * @param key State key
431
- * @param value State value
432
- * @returns Success status
433
- */
434
- async setSessionState(sessionId, key, value) {
435
- return this.sessionManager.setSessionState(sessionId, key, value) !== null;
436
- }
437
- /**
438
- * Get session state value
439
- *
440
- * @param sessionId Session identifier
441
- * @param key State key
442
- * @returns State value or undefined
443
- */
444
- async getSessionState(sessionId, key) {
445
- const result = this.sessionManager.getSessionState(sessionId, key);
446
- return result;
447
- }
448
- /**
449
- * Get all active sessions
450
- *
451
- * @returns Array of active sessions
452
- */
453
- async getActiveSessions() {
454
- return this.sessionManager.getActiveSessions();
455
- }
456
- /**
457
- * Clean up expired sessions
458
- *
459
- * @returns Number of sessions cleaned
460
- */
461
- async cleanupSessions() {
462
- return this.sessionManager.cleanup();
463
- }
464
- /**
465
- * Get error history
466
- *
467
- * @param filter Optional filter criteria
468
- * @returns Filtered error history
469
- */
470
- getErrorHistory(filter) {
471
- return this.errorManager.getErrorHistory(filter);
472
- }
473
- /**
474
- * Clear error history
475
- */
476
- clearErrorHistory() {
477
- this.errorManager.clearHistory();
478
- }
479
- /**
480
- * Get recovery suggestion for last error
481
- *
482
- * @param sessionId Optional session ID to get last error from
483
- * @returns Recovery suggestion or null
484
- */
485
- getLastErrorRecovery(sessionId) {
486
- const filter = sessionId ? { sessionId, limit: 1 } : { limit: 1 };
487
- const errors = this.errorManager.getErrorHistory(filter);
488
- if (errors.length > 0) {
489
- return this.errorManager.getRecoverySuggestion(errors[0]);
490
- }
491
- return null;
492
- }
493
- /**
494
- * Initialize health monitoring
495
- *
496
- * @param options Health monitor options
497
- */
498
- initializeHealthMonitor(options) {
499
- this.healthMonitor = initializeHealthMonitor(this.registry, this.errorManager, options);
500
- }
501
- /**
502
- * Start health monitoring for all registered servers
503
- */
504
- startHealthMonitoring() {
505
- if (!this.healthMonitor) {
506
- this.initializeHealthMonitor();
507
- }
508
- this.healthMonitor.startMonitoring();
509
- }
510
- /**
511
- * Stop health monitoring
512
- */
513
- stopHealthMonitoring() {
514
- this.healthMonitor?.stopMonitoring();
515
- }
516
- /**
517
- * Register recovery callback for a server
518
- *
519
- * @param serverId Server ID
520
- * @param callback Recovery callback
521
- */
522
- registerRecoveryCallback(serverId, callback) {
523
- if (!this.healthMonitor) {
524
- this.initializeHealthMonitor();
525
- }
526
- this.healthMonitor.registerRecoveryCallback(serverId, callback);
527
- }
528
- /**
529
- * Get health status for all servers
530
- *
531
- * @returns Map of server health status
532
- */
533
- getHealthStatus() {
534
- return this.healthMonitor?.getHealthStatus() || new Map();
535
- }
536
- /**
537
- * Initialize transport manager for MCP connections
538
- *
539
- * @param options Transport manager options
540
- */
541
- initializeTransportManager(options) {
542
- this.transportManager = new TransportManager(this.errorManager, options);
543
- }
544
- /**
545
- * Connect to MCP server using specified transport
546
- *
547
- * @param config Transport configuration
548
- * @returns Connected MCP client
549
- */
550
- async connectTransport(config) {
551
- if (!this.transportManager) {
552
- this.initializeTransportManager();
553
- }
554
- return this.transportManager.connect(config);
555
- }
556
- /**
557
- * Disconnect from MCP server
558
- */
559
- async disconnectTransport() {
560
- await this.transportManager?.disconnect();
561
- }
562
- /**
563
- * Get transport connection status
564
- */
565
- getTransportStatus() {
566
- return (this.transportManager?.getStatus() || {
567
- connected: false,
568
- type: "stdio",
569
- reconnectAttempts: 0,
570
- });
571
- }
572
- /**
573
- * Check if transport is connected
574
- */
575
- isTransportConnected() {
576
- return this.transportManager?.isConnected() || false;
577
- }
578
- /**
579
- * Execute parallel pipeline with dependency management
580
- *
581
- * @private
582
- */
583
- async executeParallelPipeline(steps, context, results, errors, options) {
584
- // Build dependency graph
585
- const stepMap = new Map();
586
- const dependencyGraph = new Map();
587
- for (const step of steps) {
588
- const stepId = step.stepId || `step-${stepMap.size + 1}`;
589
- stepMap.set(stepId, { ...step, stepId });
590
- dependencyGraph.set(stepId, step.dependsOn || []);
591
- }
592
- // Execute steps in dependency order
593
- const completed = new Set();
594
- const executing = new Set();
595
- while (completed.size < steps.length) {
596
- const readySteps = Array.from(stepMap.keys()).filter((stepId) => {
597
- if (completed.has(stepId) || executing.has(stepId)) {
598
- return false;
599
- }
600
- const dependencies = dependencyGraph.get(stepId) || [];
601
- return dependencies.every((dep) => completed.has(dep));
602
- });
603
- if (readySteps.length === 0) {
604
- throw new Error("Circular dependency detected in pipeline");
605
- }
606
- // Execute ready steps in parallel
607
- const executePromises = readySteps.map(async (stepId) => {
608
- executing.add(stepId);
609
- const step = stepMap.get(stepId);
610
- try {
611
- // Use semaphore for parallel execution to prevent race conditions
612
- const semaphoreKey = `tool:${step.toolName}`;
613
- const semaphoreResult = await this.semaphoreManager.acquire(semaphoreKey, async () => {
614
- return await this.registry.executeTool(step.toolName, step.params, context);
615
- }, context);
616
- const result = semaphoreResult.success
617
- ? semaphoreResult.result
618
- : {
619
- success: false,
620
- data: null,
621
- error: semaphoreResult.error ||
622
- new Error("Semaphore acquisition failed"),
623
- usage: {
624
- executionTime: semaphoreResult.executionTime,
625
- waitTime: semaphoreResult.waitTime,
626
- },
627
- };
628
- results.set(stepId, result);
629
- if (!result.success) {
630
- const error = result.error;
631
- const errorMessage = error instanceof Error
632
- ? error.message
633
- : String(error) || "Unknown error";
634
- errors.set(stepId, errorMessage);
635
- }
636
- }
637
- catch (error) {
638
- const errorMessage = error instanceof Error ? error.message : String(error);
639
- errors.set(stepId, errorMessage);
640
- }
641
- finally {
642
- executing.delete(stepId);
643
- completed.add(stepId);
644
- }
645
- });
646
- await Promise.all(executePromises);
647
- // Check for errors and stop if configured
648
- if (options.stopOnError && errors.size > 0) {
649
- break;
650
- }
651
- }
652
- }
653
- /**
654
- * Generate unique pipeline ID
655
- *
656
- * @private
657
- */
658
- generatePipelineId() {
659
- this.pipelineCounter++;
660
- const timestamp = Date.now();
661
- const random = Math.random().toString(36).substring(2, 8);
662
- return `nlpipe-${timestamp}-${this.pipelineCounter}-${random}`;
663
- }
664
- }
665
- /**
666
- * Default orchestrator instance
667
- * Ready-to-use orchestrator with pre-configured registry and context manager
668
- */
669
- export const defaultOrchestrator = new MCPOrchestrator();
670
- /**
671
- * Utility function to execute tool with default orchestrator
672
- *
673
- * @param toolName Tool name to execute
674
- * @param params Tool parameters
675
- * @param contextRequest Context creation request
676
- * @param options Execution options
677
- * @returns Tool execution result
678
- */
679
- export async function executeTool(toolName, params, contextRequest, options) {
680
- return defaultOrchestrator.executeTool(toolName, params, contextRequest, options);
681
- }
682
- /**
683
- * Utility function to execute text generation pipeline
684
- *
685
- * @param prompt Text prompt for generation
686
- * @param contextRequest Context creation request
687
- * @param options Generation options
688
- * @returns Text generation result
689
- */
690
- export async function executeTextPipeline(prompt, contextRequest, options) {
691
- return defaultOrchestrator.executeTextPipeline(prompt, contextRequest, options);
692
- }
693
- /**
694
- * Utility function to execute pipeline with default orchestrator
695
- *
696
- * @param steps Pipeline steps
697
- * @param contextRequest Context creation request
698
- * @param options Pipeline options
699
- * @returns Pipeline execution result
700
- */
701
- export async function executePipeline(steps, contextRequest, options) {
702
- return defaultOrchestrator.executePipeline(steps, contextRequest, options);
703
- }