@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
- * Enhanced AI Provider with Real Function Calling Support
3
- * Integrates MCP tools directly with AI SDK's function calling capabilities
4
- * This is the missing piece that enables true AI function calling!
5
- */
6
- import { generateText as aiGenerate, Output, } from "ai";
7
- import { getAvailableFunctionTools, executeFunctionCall, isFunctionCallingAvailable, } from "../mcp/function-calling.js";
8
- import { createExecutionContext } from "../mcp/context-manager.js";
9
- import { mcpLogger } from "../mcp/logging.js";
10
- import { DEFAULT_MAX_TOKENS, DEFAULT_MAX_STEPS } from "../core/constants.js";
11
- /**
12
- * Enhanced provider that enables real function calling with MCP tools
13
- */
14
- export class FunctionCallingProvider {
15
- baseProvider;
16
- enableFunctionCalling;
17
- sessionId;
18
- userId;
19
- cachedToolsObject = null;
20
- cachedToolMap = null;
21
- cacheTimestamp = null;
22
- cacheExpiryMs;
23
- constructor(baseProvider, options = {}) {
24
- this.baseProvider = baseProvider;
25
- this.enableFunctionCalling = options.enableFunctionCalling ?? true;
26
- this.sessionId = options.sessionId || `function-calling-${Date.now()}`;
27
- this.userId = options.userId || "function-calling-user";
28
- // Configurable cache expiry: default 5 minutes, with environment override, then constructor option
29
- const defaultExpiryMs = 5 * 60 * 1000; // 5 minutes
30
- const envExpiryMs = process.env.NEUROLINK_CACHE_EXPIRY_MS
31
- ? parseInt(process.env.NEUROLINK_CACHE_EXPIRY_MS, 10)
32
- : undefined;
33
- this.cacheExpiryMs =
34
- options.cacheExpiryMs ?? envExpiryMs ?? defaultExpiryMs;
35
- }
36
- /**
37
- * PRIMARY METHOD: Stream content using AI (recommended for new code)
38
- * Future-ready for multi-modal capabilities with current text focus
39
- */
40
- async stream(optionsOrPrompt, analysisSchema) {
41
- const functionTag = "FunctionCallingProvider.stream";
42
- const startTime = Date.now();
43
- // Parse parameters - support both string and options object
44
- const options = typeof optionsOrPrompt === "string"
45
- ? { input: { text: optionsOrPrompt } }
46
- : optionsOrPrompt;
47
- // Validate input
48
- if (!options?.input?.text ||
49
- typeof options.input.text !== "string" ||
50
- options.input.text.trim() === "") {
51
- throw new Error("Stream options must include input.text as a non-empty string");
52
- }
53
- // Use base provider's stream implementation
54
- const baseResult = await this.baseProvider.stream(options);
55
- if (!baseResult) {
56
- throw new Error("No stream response received from provider");
57
- }
58
- // Return the result with function-calling metadata
59
- return {
60
- ...baseResult,
61
- provider: "function-calling",
62
- model: options.model || "unknown",
63
- metadata: {
64
- streamId: `function-calling-${Date.now()}`,
65
- startTime,
66
- },
67
- };
68
- }
69
- /**
70
- * Generate text with real function calling support
71
- */
72
- async generate(optionsOrPrompt, analysisSchema) {
73
- const options = typeof optionsOrPrompt === "string"
74
- ? { prompt: optionsOrPrompt }
75
- : optionsOrPrompt;
76
- const functionTag = "FunctionCallingProvider.generate";
77
- // If function calling is disabled, use base provider
78
- if (!this.enableFunctionCalling) {
79
- mcpLogger.debug(`[${functionTag}] Function calling disabled, using base provider`);
80
- const result = await this.baseProvider.generate(options, analysisSchema);
81
- if (!result) {
82
- return {
83
- content: "No response generated",
84
- provider: "function-calling",
85
- model: "unknown",
86
- };
87
- }
88
- return result;
89
- }
90
- try {
91
- // Check if function calling is available
92
- const functionsAvailable = await isFunctionCallingAvailable();
93
- if (!functionsAvailable) {
94
- mcpLogger.debug(`[${functionTag}] No functions available, using base provider`);
95
- const result = await this.baseProvider.generate(options, analysisSchema);
96
- if (!result) {
97
- return {
98
- content: "No response generated",
99
- provider: "function-calling",
100
- model: "unknown",
101
- };
102
- }
103
- return result;
104
- }
105
- // Get available function tools (with automatic cache invalidation)
106
- let toolsObject, toolMap;
107
- const now = Date.now();
108
- const isCacheExpired = this.cacheTimestamp === null ||
109
- now - this.cacheTimestamp > this.cacheExpiryMs;
110
- if (this.cachedToolsObject && this.cachedToolMap && !isCacheExpired) {
111
- toolsObject = this.cachedToolsObject;
112
- toolMap = this.cachedToolMap;
113
- mcpLogger.debug(`[${functionTag}] Using cached tools (${Math.round((now - this.cacheTimestamp) / 1000)}s old)`);
114
- }
115
- else {
116
- if (isCacheExpired && this.cachedToolsObject) {
117
- mcpLogger.debug(`[${functionTag}] Cache expired, refreshing tools`);
118
- }
119
- const result = await getAvailableFunctionTools();
120
- toolsObject = result.toolsObject;
121
- toolMap = result.toolMap;
122
- // Cache the results for future use with timestamp
123
- this.cachedToolsObject = toolsObject;
124
- this.cachedToolMap = toolMap;
125
- this.cacheTimestamp = now;
126
- mcpLogger.debug(`[${functionTag}] Cached ${Object.keys(toolsObject).length} tools with expiry in ${this.cacheExpiryMs / 1000}s`);
127
- }
128
- const tools = Object.values(toolsObject);
129
- if (tools.length === 0) {
130
- mcpLogger.debug(`[${functionTag}] No tools available, using base provider`);
131
- const result = await this.baseProvider.generate(options, analysisSchema);
132
- if (!result) {
133
- return {
134
- content: "No response generated",
135
- provider: "function-calling",
136
- model: "unknown",
137
- };
138
- }
139
- return result;
140
- }
141
- mcpLogger.debug(`[${functionTag}] Function calling enabled with ${tools.length} tools`);
142
- // Create execution context
143
- const context = createExecutionContext({
144
- sessionId: this.sessionId,
145
- userId: this.userId,
146
- aiProvider: this.baseProvider.constructor.name,
147
- });
148
- // Use the AI SDK's native function calling by calling generate directly
149
- // We can now use the toolsObject directly instead of converting from array
150
- const result = await this.generateWithToolsObject(options, toolsObject, toolMap, context, analysisSchema);
151
- if (!result) {
152
- return {
153
- content: "No response generated",
154
- provider: "function-calling",
155
- model: "unknown",
156
- };
157
- }
158
- // Enhance result with function calling metadata
159
- const enhancedResult = {
160
- ...result,
161
- functionCallingEnabled: true,
162
- availableFunctions: tools.length,
163
- mcpIntegration: {
164
- sessionId: this.sessionId,
165
- functionCallsSupported: true,
166
- toolsRegistered: tools.length,
167
- },
168
- };
169
- mcpLogger.debug(`[${functionTag}] Function-calling generation completed with ${result.toolCalls?.length || 0} tool calls`);
170
- return enhancedResult;
171
- }
172
- catch (error) {
173
- mcpLogger.warn(`[${functionTag}] Function calling failed, using base provider:`, error);
174
- const result = await this.baseProvider.generate(options, analysisSchema);
175
- if (!result) {
176
- return {
177
- content: "No response generated",
178
- provider: "function-calling",
179
- model: "unknown",
180
- };
181
- }
182
- return result;
183
- }
184
- }
185
- /**
186
- * Generate text with tools using the AI SDK's generate function (with tools object)
187
- */
188
- async generateWithToolsObject(options, toolsObject, toolMap, context, analysisSchema) {
189
- const functionTag = "FunctionCallingProvider.generateWithToolsObject";
190
- try {
191
- // Use the toolsObject directly with proper execution wrapped
192
- const toolsWithExecution = this.wrapToolsWithExecution(toolsObject, toolMap, context);
193
- mcpLogger.debug(`[${functionTag}] Using tools object with ${Object.keys(toolsWithExecution).length} tools`);
194
- // Get the model from base provider
195
- const modelInfo = await this.getModelFromProvider();
196
- if (!modelInfo) {
197
- mcpLogger.warn(`[${functionTag}] Could not get model from provider, falling back to base provider`);
198
- const result = await this.baseProvider.generate(options, analysisSchema);
199
- if (!result) {
200
- return {
201
- content: "No response generated",
202
- provider: "function-calling",
203
- model: "unknown",
204
- };
205
- }
206
- return result;
207
- }
208
- // Use AI SDK's generate directly with tools
209
- const generateOptions = {
210
- model: modelInfo.model,
211
- prompt: options.prompt,
212
- system: options.systemPrompt || "You are a helpful AI assistant.",
213
- temperature: options.temperature || 0.7,
214
- maxTokens: options.maxTokens ?? DEFAULT_MAX_TOKENS,
215
- tools: toolsWithExecution,
216
- toolChoice: "auto", // Let the AI decide when to use tools
217
- maxSteps: options.maxSteps ?? DEFAULT_MAX_STEPS, // Enable multi-turn tool execution
218
- };
219
- // Add experimental_output if schema is provided
220
- if (analysisSchema) {
221
- generateOptions.experimental_output = Output.object({
222
- schema: analysisSchema,
223
- });
224
- }
225
- const result = await aiGenerate(generateOptions);
226
- mcpLogger.debug(`[${functionTag}] AI SDK generate completed`, {
227
- toolCalls: result.toolCalls?.length || 0,
228
- finishReason: result.finishReason,
229
- usage: result.usage,
230
- });
231
- return {
232
- content: result.text,
233
- provider: "function-calling",
234
- model: "unknown",
235
- usage: result.usage
236
- ? {
237
- inputTokens: result.usage.promptTokens,
238
- outputTokens: result.usage.completionTokens,
239
- totalTokens: result.usage.totalTokens,
240
- }
241
- : undefined,
242
- responseTime: 0,
243
- toolsUsed: result.toolCalls?.map((tc) => tc.toolName) || [],
244
- toolExecutions: [],
245
- enhancedWithTools: (result.toolCalls?.length || 0) > 0,
246
- availableTools: [],
247
- };
248
- }
249
- catch (error) {
250
- mcpLogger.error(`[${functionTag}] Failed to generate text with tools:`, error);
251
- throw error;
252
- }
253
- }
254
- /**
255
- * Generate text using AI SDK's native function calling (legacy array-based)
256
- */
257
- async generateWithTools(options, tools, toolMap, context, analysisSchema) {
258
- const functionTag = "FunctionCallingProvider.generateWithTools";
259
- try {
260
- // Convert our tools to AI SDK format with proper execution
261
- const toolsWithExecution = this.convertToAISDKTools(tools, toolMap, context);
262
- mcpLogger.debug(`[${functionTag}] Calling AI SDK generate with ${Object.keys(toolsWithExecution).length} tools and maxSteps: ${options.maxSteps ?? DEFAULT_MAX_STEPS}`);
263
- mcpLogger.debug(`[${functionTag}] Sanitized tool names:`, Object.keys(toolsWithExecution));
264
- // Log the first few tools to debug the issue
265
- const toolNames = Object.keys(toolsWithExecution);
266
- mcpLogger.debug(`[${functionTag}] First 5 tool names:`, toolNames.slice(0, 5));
267
- // Get the model from base provider (this requires accessing the private model property)
268
- // For now, we'll create the model directly based on the provider type
269
- // This is a temporary solution until we have proper model access
270
- const modelInfo = await this.getModelFromProvider();
271
- if (!modelInfo) {
272
- mcpLogger.warn(`[${functionTag}] Could not get model from provider, falling back to base provider`);
273
- const result = await this.baseProvider.generate(options, analysisSchema);
274
- if (!result) {
275
- return {
276
- content: "No response generated",
277
- provider: "function-calling",
278
- model: "unknown",
279
- };
280
- }
281
- return result;
282
- }
283
- // Use AI SDK's generate directly with tools
284
- const generateOptions = {
285
- model: modelInfo.model,
286
- prompt: options.prompt,
287
- system: options.systemPrompt || "You are a helpful AI assistant.",
288
- temperature: options.temperature || 0.7,
289
- maxTokens: options.maxTokens ?? DEFAULT_MAX_TOKENS,
290
- tools: toolsWithExecution,
291
- toolChoice: "auto", // Let the AI decide when to use tools
292
- maxSteps: options.maxSteps ?? DEFAULT_MAX_STEPS, // Enable multi-turn tool execution
293
- };
294
- // Add experimental_output if schema is provided
295
- if (analysisSchema) {
296
- generateOptions.experimental_output = Output.object({
297
- schema: analysisSchema,
298
- });
299
- }
300
- const result = await aiGenerate(generateOptions);
301
- mcpLogger.debug(`[${functionTag}] AI SDK generate completed`, {
302
- toolCalls: result.toolCalls?.length || 0,
303
- finishReason: result.finishReason,
304
- usage: result.usage,
305
- });
306
- return {
307
- content: result.text,
308
- provider: "function-calling",
309
- model: "unknown",
310
- usage: result.usage
311
- ? {
312
- inputTokens: result.usage.promptTokens,
313
- outputTokens: result.usage.completionTokens,
314
- totalTokens: result.usage.totalTokens,
315
- }
316
- : undefined,
317
- responseTime: 0,
318
- toolsUsed: result.toolCalls?.map((tc) => tc.toolName) || [],
319
- toolExecutions: [],
320
- enhancedWithTools: (result.toolCalls?.length || 0) > 0,
321
- availableTools: [],
322
- };
323
- }
324
- catch (error) {
325
- mcpLogger.error(`[${functionTag}] Failed to generate text with tools:`, error);
326
- throw error;
327
- }
328
- }
329
- /**
330
- * Get the model from the base provider
331
- * This is a temporary solution - ideally we'd have a getModel() method on AIProvider
332
- */
333
- async getModelFromProvider() {
334
- const functionTag = "FunctionCallingProvider.getModelFromProvider";
335
- try {
336
- // Try to access the model property if it exists
337
- const provider = this.baseProvider;
338
- // Check if provider has a model property
339
- if (provider.model) {
340
- mcpLogger.debug(`[${functionTag}] Found model property on provider`);
341
- return { model: provider.model };
342
- }
343
- // Check if provider has a getModel method
344
- if (typeof provider.getModel === "function") {
345
- mcpLogger.debug(`[${functionTag}] Found getModel method on provider`);
346
- const model = await provider.getModel();
347
- return { model: model };
348
- }
349
- mcpLogger.warn(`[${functionTag}] Could not find model on provider`);
350
- return null;
351
- }
352
- catch (error) {
353
- mcpLogger.error(`[${functionTag}] Error getting model from provider:`, error);
354
- return null;
355
- }
356
- }
357
- /**
358
- * Sanitize tool name to comply with AI provider requirements
359
- */
360
- sanitizeToolName(name) {
361
- // Replace any character that's not alphanumeric, underscore, dot, or dash
362
- // Also ensure it starts with a letter or underscore
363
- let sanitized = name.replace(/[^a-zA-Z0-9_.-]/g, "_");
364
- // If it doesn't start with a letter or underscore, prepend an underscore
365
- if (!/^[a-zA-Z_]/.test(sanitized)) {
366
- sanitized = "_" + sanitized;
367
- }
368
- // Ensure it's not longer than 64 characters
369
- if (sanitized.length > 64) {
370
- sanitized = sanitized.substring(0, 64);
371
- }
372
- return sanitized;
373
- }
374
- /**
375
- * Wrap tools with proper execution context (for object-based tools)
376
- */
377
- wrapToolsWithExecution(toolsObject, toolMap, context) {
378
- const functionTag = "FunctionCallingProvider.wrapToolsWithExecution";
379
- const wrappedTools = {};
380
- for (const [toolName, tool] of Object.entries(toolsObject)) {
381
- const toolInfo = toolMap.get(toolName);
382
- const originalToolName = toolInfo ? toolInfo.toolName : toolName;
383
- // Create a version with actual MCP execution
384
- wrappedTools[toolName] = {
385
- description: tool.description,
386
- parameters: tool.parameters,
387
- execute: async (args) => {
388
- // Debug logging only in debug mode
389
- if (process.env.NEUROLINK_DEBUG === "true") {
390
- const providerName = this.baseProvider.constructor.name;
391
- mcpLogger.debug(`Tool execution - Provider: ${providerName}`);
392
- mcpLogger.debug(`Tool: ${toolName} (original: ${originalToolName})`);
393
- mcpLogger.debug(`Args:`, args);
394
- }
395
- try {
396
- // Execute the actual MCP tool
397
- const result = await executeFunctionCall(toolName, args);
398
- if (process.env.NEUROLINK_DEBUG === "true") {
399
- mcpLogger.debug(`Tool result:`, result);
400
- }
401
- if (result.success) {
402
- return result.data || { success: true };
403
- }
404
- else {
405
- return { error: result.error || "Tool execution failed" };
406
- }
407
- }
408
- catch (error) {
409
- mcpLogger.error(`[${functionTag}] Tool execution error: ${toolName}`, error);
410
- return {
411
- error: error instanceof Error ? error.message : String(error),
412
- };
413
- }
414
- },
415
- };
416
- }
417
- return wrappedTools;
418
- }
419
- /**
420
- * Convert our tools to AI SDK format with proper execution (legacy array-based)
421
- */
422
- convertToAISDKTools(tools, toolMap, context) {
423
- const functionTag = "FunctionCallingProvider.convertToAISDKTools";
424
- const convertedTools = {};
425
- const sanitizedNameMap = new Map(); // Maps sanitized names back to original
426
- // Convert the toolMap to easily access by index
427
- const toolInfoArray = Array.from(toolMap.entries());
428
- tools.forEach((tool, index) => {
429
- // Use the actual tool name from the map for better debugging
430
- const [mapKey, toolInfo] = toolInfoArray[index] || [
431
- `tool_${index}`,
432
- null,
433
- ];
434
- // Use the already sanitized mapKey instead of re-sanitizing the raw toolName
435
- const sanitizedToolName = mapKey;
436
- const originalToolName = toolInfo ? toolInfo.toolName : `tool_${index}`;
437
- // Store the mapping for later reference
438
- sanitizedNameMap.set(sanitizedToolName, originalToolName);
439
- // Create a version with actual MCP execution
440
- convertedTools[sanitizedToolName] = {
441
- description: tool.description,
442
- parameters: tool.parameters,
443
- execute: async (args) => {
444
- // Debug logging only in debug mode
445
- if (process.env.NEUROLINK_DEBUG === "true") {
446
- const providerName = this.baseProvider.constructor.name;
447
- mcpLogger.debug(`Tool execution - Provider: ${providerName}`);
448
- mcpLogger.debug(`Tool: ${sanitizedToolName} (original: ${originalToolName})`);
449
- mcpLogger.debug("Args received:", args);
450
- }
451
- mcpLogger.debug(`[${functionTag}] Executing MCP tool: ${sanitizedToolName} (original: ${originalToolName}, ${toolInfo?.serverId}.${toolInfo?.toolName})`, args);
452
- try {
453
- if (toolInfo) {
454
- const mcpToolName = `${toolInfo.serverId}.${toolInfo.toolName}`;
455
- // Log execution details in debug mode only
456
- if (process.env.NEUROLINK_DEBUG === "true") {
457
- mcpLogger.debug("Calling executeFunctionCall with:", {
458
- mcpToolName,
459
- args,
460
- });
461
- }
462
- const result = await executeFunctionCall(mcpToolName, args, context);
463
- if (process.env.NEUROLINK_DEBUG === "true") {
464
- mcpLogger.debug("Tool execution result:", {
465
- success: result.success,
466
- hasData: !!result.data,
467
- error: result.error,
468
- });
469
- }
470
- mcpLogger.debug(`[${functionTag}] Tool execution result for ${sanitizedToolName}:`, {
471
- success: result.success,
472
- hasData: !!result.data,
473
- error: result.error,
474
- });
475
- if (result.success) {
476
- return (result.data || {
477
- success: true,
478
- message: "Tool executed successfully",
479
- });
480
- }
481
- else {
482
- return { error: result.error || "Tool execution failed" };
483
- }
484
- }
485
- // Fallback execution - Tool info not found
486
- mcpLogger.warn(`[${functionTag}] Tool info not found for ${sanitizedToolName}, using fallback`);
487
- return { success: false, error: "Tool mapping not found" };
488
- }
489
- catch (error) {
490
- if (process.env.NEUROLINK_DEBUG === "true") {
491
- mcpLogger.debug("Tool execution error:", error);
492
- }
493
- mcpLogger.error(`[${functionTag}] Tool execution failed for ${sanitizedToolName}:`, error);
494
- return {
495
- error: error instanceof Error ? error.message : String(error),
496
- };
497
- }
498
- },
499
- };
500
- });
501
- mcpLogger.debug(`[${functionTag}] Converted ${Object.keys(convertedTools).length} tools for AI SDK:`, Object.keys(convertedTools));
502
- // Log first tool details for debugging in debug mode only
503
- if (process.env.NEUROLINK_DEBUG === "true") {
504
- const firstToolName = Object.keys(convertedTools)[0];
505
- if (firstToolName) {
506
- mcpLogger.debug("First tool details:", {
507
- name: firstToolName,
508
- description: convertedTools[firstToolName].description,
509
- parameters: convertedTools[firstToolName].parameters,
510
- });
511
- }
512
- }
513
- return convertedTools;
514
- }
515
- /**
516
- * Create function-aware system prompt
517
- */
518
- createFunctionAwareSystemPrompt(originalPrompt, tools) {
519
- const basePrompt = originalPrompt || "You are a helpful AI assistant.";
520
- if (tools.length === 0) {
521
- return basePrompt;
522
- }
523
- const functionList = tools
524
- .map((tool, index) => `${index + 1}. ${tool.description || "No description available"}`)
525
- .join("\n");
526
- return `${basePrompt}
527
-
528
- IMPORTANT: You have access to ${tools.length} specialized functions that can provide real-time information and capabilities:
529
-
530
- ${functionList}
531
-
532
- CRITICAL INSTRUCTIONS:
533
- - When asked about the current time, date, or timezone, you MUST use the time/date functions
534
- - When asked to list files or access the filesystem, you MUST use the filesystem functions
535
- - When asked about system information, you MUST use the appropriate system functions
536
- - DO NOT say "I cannot access" or "I don't have access" - you DO have access through these functions
537
- - Always use available functions instead of providing placeholder or estimated information
538
-
539
- These functions provide accurate, real-time data. Use them actively to enhance your responses.`;
540
- }
541
- /**
542
- * Alias for generate() - CLI-SDK consistency
543
- */
544
- /**
545
- * Clear cached tools - Cache Invalidation Strategy
546
- *
547
- * WHEN TO CALL clearToolsCache():
548
- *
549
- * 1. **MCP Server Changes**: When MCP servers are added, removed, or restarted
550
- * - After calling unifiedRegistry.addServer() or removeServer()
551
- * - When MCP server configurations change
552
- * - After MCP server restart or reconnection
553
- *
554
- * 2. **Tool Registration Changes**: When custom tools are modified
555
- * - After registering new SDK tools via registerTool()
556
- * - When tool implementations change
557
- * - After unregistering tools
558
- *
559
- * 3. **Provider Reinitialization**: When the provider context changes
560
- * - Before switching between different AI providers
561
- * - When session context changes significantly
562
- * - After provider authentication refresh
563
- *
564
- * 4. **Error Recovery**: When tool execution encounters systematic failures
565
- * - After MCP connection errors are resolved
566
- * - When tool discovery needs to be re-run
567
- * - During error recovery workflows
568
- *
569
- * 5. **Development/Testing**: During development and testing cycles
570
- * - Between test cases that modify tool availability
571
- * - When testing different tool configurations
572
- * - During hot reloading scenarios
573
- *
574
- * CACHE LIFECYCLE:
575
- * - Cache is populated on first generate() call via getAvailableFunctionTools()
576
- * - Cache persists across multiple generate() calls for performance
577
- * - Cache is invalidated by calling this method
578
- * - Next generate() call will rebuild cache from current tool state
579
- *
580
- * PERFORMANCE IMPACT:
581
- * - Clearing cache forces tool discovery on next usage (~100-500ms overhead)
582
- * - Recommended to clear cache proactively rather than reactively
583
- * - Consider batching tool changes before clearing cache
584
- *
585
- * THREAD SAFETY:
586
- * - This method is not thread-safe
587
- * - Avoid calling during active generate() operations
588
- * - Safe to call between separate AI generation requests
589
- */
590
- clearToolsCache() {
591
- this.cachedToolsObject = null;
592
- this.cachedToolMap = null;
593
- this.cacheTimestamp = null;
594
- }
595
- /**
596
- * Short alias for generate() - CLI-SDK consistency
597
- */
598
- async gen(optionsOrPrompt, analysisSchema) {
599
- return this.generate(optionsOrPrompt, analysisSchema);
600
- }
601
- }
602
- /**
603
- * Create a function-calling enhanced version of any AI provider
604
- */
605
- export function createFunctionCallingProvider(baseProvider, options) {
606
- return new FunctionCallingProvider(baseProvider, options);
607
- }
608
- /**
609
- * Enhanced MCP Provider Factory that creates function-calling enabled providers
610
- */
611
- export function createMCPAwareProviderV3(baseProvider, options = {}) {
612
- const functionTag = "createMCPAwareProviderV3";
613
- // If MCP is disabled, return base provider
614
- if (options.enableMCP === false) {
615
- mcpLogger.debug(`[${functionTag}] MCP disabled, returning base provider`);
616
- return baseProvider;
617
- }
618
- // Create function-calling enhanced provider
619
- const enhancedProvider = createFunctionCallingProvider(baseProvider, {
620
- enableFunctionCalling: options.enableFunctionCalling,
621
- sessionId: options.sessionId,
622
- userId: options.userId,
623
- cacheExpiryMs: options.cacheExpiryMs,
624
- });
625
- mcpLogger.debug(`[${functionTag}] Created MCP-aware provider with function calling`, {
626
- providerName: options.providerName,
627
- enableFunctionCalling: options.enableFunctionCalling !== false,
628
- });
629
- return enhancedProvider;
630
- }