@juspay/neurolink 1.5.3 → 1.9.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 (176) hide show
  1. package/CHANGELOG.md +241 -1
  2. package/README.md +113 -20
  3. package/dist/agent/direct-tools.d.ts +1203 -0
  4. package/dist/agent/direct-tools.js +387 -0
  5. package/dist/cli/commands/agent-generate.d.ts +2 -0
  6. package/dist/cli/commands/agent-generate.js +70 -0
  7. package/dist/cli/commands/config.d.ts +76 -9
  8. package/dist/cli/commands/config.js +358 -233
  9. package/dist/cli/commands/mcp.d.ts +2 -1
  10. package/dist/cli/commands/mcp.js +874 -146
  11. package/dist/cli/commands/ollama.d.ts +8 -0
  12. package/dist/cli/commands/ollama.js +333 -0
  13. package/dist/cli/index.js +591 -327
  14. package/dist/cli/utils/complete-setup.d.ts +19 -0
  15. package/dist/cli/utils/complete-setup.js +81 -0
  16. package/dist/cli/utils/env-manager.d.ts +44 -0
  17. package/dist/cli/utils/env-manager.js +226 -0
  18. package/dist/cli/utils/interactive-setup.d.ts +48 -0
  19. package/dist/cli/utils/interactive-setup.js +302 -0
  20. package/dist/core/dynamic-models.d.ts +208 -0
  21. package/dist/core/dynamic-models.js +250 -0
  22. package/dist/core/factory.d.ts +13 -6
  23. package/dist/core/factory.js +180 -50
  24. package/dist/core/types.d.ts +8 -3
  25. package/dist/core/types.js +7 -4
  26. package/dist/index.d.ts +16 -16
  27. package/dist/index.js +16 -16
  28. package/dist/lib/agent/direct-tools.d.ts +1203 -0
  29. package/dist/lib/agent/direct-tools.js +387 -0
  30. package/dist/lib/core/dynamic-models.d.ts +208 -0
  31. package/dist/lib/core/dynamic-models.js +250 -0
  32. package/dist/lib/core/factory.d.ts +13 -6
  33. package/dist/lib/core/factory.js +180 -50
  34. package/dist/lib/core/types.d.ts +8 -3
  35. package/dist/lib/core/types.js +7 -4
  36. package/dist/lib/index.d.ts +16 -16
  37. package/dist/lib/index.js +16 -16
  38. package/dist/lib/mcp/auto-discovery.d.ts +120 -0
  39. package/dist/lib/mcp/auto-discovery.js +793 -0
  40. package/dist/lib/mcp/client.d.ts +66 -0
  41. package/dist/lib/mcp/client.js +245 -0
  42. package/dist/lib/mcp/config.d.ts +31 -0
  43. package/dist/lib/mcp/config.js +74 -0
  44. package/dist/lib/mcp/context-manager.d.ts +4 -4
  45. package/dist/lib/mcp/context-manager.js +24 -18
  46. package/dist/lib/mcp/factory.d.ts +28 -11
  47. package/dist/lib/mcp/factory.js +36 -29
  48. package/dist/lib/mcp/function-calling.d.ts +51 -0
  49. package/dist/lib/mcp/function-calling.js +510 -0
  50. package/dist/lib/mcp/index.d.ts +190 -0
  51. package/dist/lib/mcp/index.js +156 -0
  52. package/dist/lib/mcp/initialize-tools.d.ts +28 -0
  53. package/dist/lib/mcp/initialize-tools.js +209 -0
  54. package/dist/lib/mcp/initialize.d.ts +17 -0
  55. package/dist/lib/mcp/initialize.js +51 -0
  56. package/dist/lib/mcp/logging.d.ts +71 -0
  57. package/dist/lib/mcp/logging.js +183 -0
  58. package/dist/lib/mcp/manager.d.ts +67 -0
  59. package/dist/lib/mcp/manager.js +176 -0
  60. package/dist/lib/mcp/neurolink-mcp-client.d.ts +96 -0
  61. package/dist/lib/mcp/neurolink-mcp-client.js +417 -0
  62. package/dist/lib/mcp/orchestrator.d.ts +3 -3
  63. package/dist/lib/mcp/orchestrator.js +46 -43
  64. package/dist/lib/mcp/registry.d.ts +2 -2
  65. package/dist/lib/mcp/registry.js +42 -33
  66. package/dist/lib/mcp/servers/ai-providers/ai-analysis-tools.d.ts +1 -1
  67. package/dist/lib/mcp/servers/ai-providers/ai-analysis-tools.js +205 -66
  68. package/dist/lib/mcp/servers/ai-providers/ai-core-server.js +143 -99
  69. package/dist/lib/mcp/servers/ai-providers/ai-workflow-tools.d.ts +6 -6
  70. package/dist/lib/mcp/servers/ai-providers/ai-workflow-tools.js +404 -251
  71. package/dist/lib/mcp/servers/utilities/utility-server.d.ts +8 -0
  72. package/dist/lib/mcp/servers/utilities/utility-server.js +326 -0
  73. package/dist/lib/mcp/tool-integration.d.ts +67 -0
  74. package/dist/lib/mcp/tool-integration.js +179 -0
  75. package/dist/lib/mcp/unified-registry.d.ts +269 -0
  76. package/dist/lib/mcp/unified-registry.js +1411 -0
  77. package/dist/lib/neurolink.d.ts +68 -6
  78. package/dist/lib/neurolink.js +314 -42
  79. package/dist/lib/providers/agent-enhanced-provider.d.ts +59 -0
  80. package/dist/lib/providers/agent-enhanced-provider.js +242 -0
  81. package/dist/lib/providers/amazonBedrock.d.ts +3 -3
  82. package/dist/lib/providers/amazonBedrock.js +54 -50
  83. package/dist/lib/providers/anthropic.d.ts +2 -2
  84. package/dist/lib/providers/anthropic.js +92 -84
  85. package/dist/lib/providers/azureOpenAI.d.ts +2 -2
  86. package/dist/lib/providers/azureOpenAI.js +97 -86
  87. package/dist/lib/providers/function-calling-provider.d.ts +70 -0
  88. package/dist/lib/providers/function-calling-provider.js +359 -0
  89. package/dist/lib/providers/googleAIStudio.d.ts +10 -5
  90. package/dist/lib/providers/googleAIStudio.js +60 -38
  91. package/dist/lib/providers/googleVertexAI.d.ts +3 -3
  92. package/dist/lib/providers/googleVertexAI.js +96 -86
  93. package/dist/lib/providers/huggingFace.d.ts +31 -0
  94. package/dist/lib/providers/huggingFace.js +362 -0
  95. package/dist/lib/providers/index.d.ts +14 -8
  96. package/dist/lib/providers/index.js +18 -12
  97. package/dist/lib/providers/mcp-provider.d.ts +62 -0
  98. package/dist/lib/providers/mcp-provider.js +183 -0
  99. package/dist/lib/providers/mistralAI.d.ts +32 -0
  100. package/dist/lib/providers/mistralAI.js +223 -0
  101. package/dist/lib/providers/ollama.d.ts +51 -0
  102. package/dist/lib/providers/ollama.js +508 -0
  103. package/dist/lib/providers/openAI.d.ts +7 -3
  104. package/dist/lib/providers/openAI.js +45 -33
  105. package/dist/lib/utils/logger.js +2 -2
  106. package/dist/lib/utils/providerUtils.js +59 -22
  107. package/dist/mcp/auto-discovery.d.ts +120 -0
  108. package/dist/mcp/auto-discovery.js +794 -0
  109. package/dist/mcp/client.d.ts +66 -0
  110. package/dist/mcp/client.js +245 -0
  111. package/dist/mcp/config.d.ts +31 -0
  112. package/dist/mcp/config.js +74 -0
  113. package/dist/mcp/context-manager.d.ts +4 -4
  114. package/dist/mcp/context-manager.js +24 -18
  115. package/dist/mcp/factory.d.ts +28 -11
  116. package/dist/mcp/factory.js +36 -29
  117. package/dist/mcp/function-calling.d.ts +51 -0
  118. package/dist/mcp/function-calling.js +510 -0
  119. package/dist/mcp/index.d.ts +190 -0
  120. package/dist/mcp/index.js +156 -0
  121. package/dist/mcp/initialize-tools.d.ts +28 -0
  122. package/dist/mcp/initialize-tools.js +210 -0
  123. package/dist/mcp/initialize.d.ts +17 -0
  124. package/dist/mcp/initialize.js +51 -0
  125. package/dist/mcp/logging.d.ts +71 -0
  126. package/dist/mcp/logging.js +183 -0
  127. package/dist/mcp/manager.d.ts +67 -0
  128. package/dist/mcp/manager.js +176 -0
  129. package/dist/mcp/neurolink-mcp-client.d.ts +96 -0
  130. package/dist/mcp/neurolink-mcp-client.js +417 -0
  131. package/dist/mcp/orchestrator.d.ts +3 -3
  132. package/dist/mcp/orchestrator.js +46 -43
  133. package/dist/mcp/registry.d.ts +2 -2
  134. package/dist/mcp/registry.js +42 -33
  135. package/dist/mcp/servers/ai-providers/ai-analysis-tools.d.ts +1 -1
  136. package/dist/mcp/servers/ai-providers/ai-analysis-tools.js +205 -66
  137. package/dist/mcp/servers/ai-providers/ai-core-server.js +143 -99
  138. package/dist/mcp/servers/ai-providers/ai-workflow-tools.d.ts +6 -6
  139. package/dist/mcp/servers/ai-providers/ai-workflow-tools.js +404 -253
  140. package/dist/mcp/servers/utilities/utility-server.d.ts +8 -0
  141. package/dist/mcp/servers/utilities/utility-server.js +326 -0
  142. package/dist/mcp/tool-integration.d.ts +67 -0
  143. package/dist/mcp/tool-integration.js +179 -0
  144. package/dist/mcp/unified-registry.d.ts +269 -0
  145. package/dist/mcp/unified-registry.js +1411 -0
  146. package/dist/neurolink.d.ts +68 -6
  147. package/dist/neurolink.js +314 -42
  148. package/dist/providers/agent-enhanced-provider.d.ts +59 -0
  149. package/dist/providers/agent-enhanced-provider.js +242 -0
  150. package/dist/providers/amazonBedrock.d.ts +3 -3
  151. package/dist/providers/amazonBedrock.js +54 -50
  152. package/dist/providers/anthropic.d.ts +2 -2
  153. package/dist/providers/anthropic.js +92 -84
  154. package/dist/providers/azureOpenAI.d.ts +2 -2
  155. package/dist/providers/azureOpenAI.js +97 -86
  156. package/dist/providers/function-calling-provider.d.ts +70 -0
  157. package/dist/providers/function-calling-provider.js +359 -0
  158. package/dist/providers/googleAIStudio.d.ts +10 -5
  159. package/dist/providers/googleAIStudio.js +60 -38
  160. package/dist/providers/googleVertexAI.d.ts +3 -3
  161. package/dist/providers/googleVertexAI.js +96 -86
  162. package/dist/providers/huggingFace.d.ts +31 -0
  163. package/dist/providers/huggingFace.js +362 -0
  164. package/dist/providers/index.d.ts +14 -8
  165. package/dist/providers/index.js +18 -12
  166. package/dist/providers/mcp-provider.d.ts +62 -0
  167. package/dist/providers/mcp-provider.js +183 -0
  168. package/dist/providers/mistralAI.d.ts +32 -0
  169. package/dist/providers/mistralAI.js +223 -0
  170. package/dist/providers/ollama.d.ts +51 -0
  171. package/dist/providers/ollama.js +508 -0
  172. package/dist/providers/openAI.d.ts +7 -3
  173. package/dist/providers/openAI.js +45 -33
  174. package/dist/utils/logger.js +2 -2
  175. package/dist/utils/providerUtils.js +59 -22
  176. package/package.json +28 -4
@@ -2,125 +2,184 @@
2
2
  * AI Development Workflow Tools
3
3
  * Phase 1.2 Implementation - 4 specialized tools for AI development lifecycle
4
4
  */
5
- import { z } from 'zod';
6
- import { AIProviderFactory } from '../../../core/factory.js';
7
- import { getBestProvider } from '../../../utils/providerUtils.js';
5
+ import { z } from "zod";
6
+ import { AIProviderFactory } from "../../../core/factory.js";
7
+ import { getBestProvider } from "../../../utils/providerUtils.js";
8
8
  // Tool-specific schemas with comprehensive validation
9
9
  const generateTestCasesSchema = z.object({
10
- codeFunction: z.string().min(1).describe('The function or code to generate test cases for'),
11
- testTypes: z.array(z.enum(['unit', 'integration', 'edge-cases', 'performance', 'security']))
10
+ codeFunction: z
11
+ .string()
12
12
  .min(1)
13
- .default(['unit', 'edge-cases'])
14
- .describe('Types of test cases to generate'),
15
- framework: z.enum(['jest', 'mocha', 'vitest', 'pytest', 'unittest', 'rspec'])
16
- .default('jest')
17
- .describe('Testing framework to target'),
18
- coverageTarget: z.number().min(0).max(100).default(80).describe('Target test coverage percentage'),
19
- includeAsyncTests: z.boolean().default(true).describe('Whether to include async test cases')
13
+ .describe("The function or code to generate test cases for"),
14
+ testTypes: z
15
+ .array(z.enum(["unit", "integration", "edge-cases", "performance", "security"]))
16
+ .min(1)
17
+ .default(["unit", "edge-cases"])
18
+ .describe("Types of test cases to generate"),
19
+ framework: z
20
+ .enum(["jest", "mocha", "vitest", "pytest", "unittest", "rspec"])
21
+ .default("jest")
22
+ .describe("Testing framework to target"),
23
+ coverageTarget: z
24
+ .number()
25
+ .min(0)
26
+ .max(100)
27
+ .default(80)
28
+ .describe("Target test coverage percentage"),
29
+ includeAsyncTests: z
30
+ .boolean()
31
+ .default(true)
32
+ .describe("Whether to include async test cases"),
20
33
  });
21
34
  const refactorCodeSchema = z.object({
22
- code: z.string().min(1).describe('The code to refactor'),
23
- language: z.string().default('javascript').describe('Programming language of the code'),
24
- objectives: z.array(z.enum([
25
- 'readability',
26
- 'performance',
27
- 'maintainability',
28
- 'testability',
29
- 'modularity',
30
- 'dry-principle',
31
- 'solid-principles'
32
- ])).default(['readability', 'maintainability']).describe('Refactoring objectives'),
33
- preserveFunctionality: z.boolean().default(true).describe('Ensure functionality remains identical'),
34
- styleGuide: z.string().optional().describe('Optional style guide to follow (e.g., airbnb, google)')
35
+ code: z.string().min(1).describe("The code to refactor"),
36
+ language: z
37
+ .string()
38
+ .default("javascript")
39
+ .describe("Programming language of the code"),
40
+ objectives: z
41
+ .array(z.enum([
42
+ "readability",
43
+ "performance",
44
+ "maintainability",
45
+ "testability",
46
+ "modularity",
47
+ "dry-principle",
48
+ "solid-principles",
49
+ ]))
50
+ .default(["readability", "maintainability"])
51
+ .describe("Refactoring objectives"),
52
+ preserveFunctionality: z
53
+ .boolean()
54
+ .default(true)
55
+ .describe("Ensure functionality remains identical"),
56
+ styleGuide: z
57
+ .string()
58
+ .optional()
59
+ .describe("Optional style guide to follow (e.g., airbnb, google)"),
35
60
  });
36
61
  const generateDocumentationSchema = z.object({
37
- code: z.string().min(1).describe('The code to document'),
38
- language: z.string().default('javascript').describe('Programming language of the code'),
39
- documentationType: z.enum(['jsdoc', 'markdown', 'sphinx', 'doxygen', 'readme'])
40
- .default('jsdoc')
41
- .describe('Type of documentation to generate'),
42
- includeExamples: z.boolean().default(true).describe('Whether to include usage examples'),
43
- detailLevel: z.enum(['minimal', 'standard', 'comprehensive']).default('standard')
44
- .describe('Level of documentation detail')
62
+ code: z.string().min(1).describe("The code to document"),
63
+ language: z
64
+ .string()
65
+ .default("javascript")
66
+ .describe("Programming language of the code"),
67
+ documentationType: z
68
+ .enum(["jsdoc", "markdown", "sphinx", "doxygen", "readme"])
69
+ .default("jsdoc")
70
+ .describe("Type of documentation to generate"),
71
+ includeExamples: z
72
+ .boolean()
73
+ .default(true)
74
+ .describe("Whether to include usage examples"),
75
+ detailLevel: z
76
+ .enum(["minimal", "standard", "comprehensive"])
77
+ .default("standard")
78
+ .describe("Level of documentation detail"),
45
79
  });
46
80
  const debugAIOutputSchema = z.object({
47
- aiOutput: z.string().min(1).describe('The AI-generated output to debug'),
48
- expectedBehavior: z.string().describe('Description of expected behavior or output'),
49
- context: z.string().optional().describe('Additional context about the AI generation'),
50
- outputType: z.enum(['code', 'text', 'structured-data', 'conversation'])
51
- .default('text')
52
- .describe('Type of AI output being debugged'),
53
- includeFixSuggestions: z.boolean().default(true).describe('Whether to include fix suggestions')
81
+ aiOutput: z.string().min(1).describe("The AI-generated output to debug"),
82
+ expectedBehavior: z
83
+ .string()
84
+ .describe("Description of expected behavior or output"),
85
+ context: z
86
+ .string()
87
+ .optional()
88
+ .describe("Additional context about the AI generation"),
89
+ outputType: z
90
+ .enum(["code", "text", "structured-data", "conversation"])
91
+ .default("text")
92
+ .describe("Type of AI output being debugged"),
93
+ includeFixSuggestions: z
94
+ .boolean()
95
+ .default(true)
96
+ .describe("Whether to include fix suggestions"),
54
97
  });
55
98
  /**
56
99
  * Generate test cases for code functions
57
100
  */
58
101
  export const generateTestCasesTool = {
59
- name: 'generate-test-cases',
60
- description: 'Generate comprehensive test cases for code functions with various test types and frameworks',
61
- category: 'ai-workflow',
102
+ name: "generate-test-cases",
103
+ description: "Generate comprehensive test cases for code functions with various test types and frameworks",
104
+ category: "ai-workflow",
62
105
  inputSchema: generateTestCasesSchema,
63
106
  isImplemented: true,
64
- permissions: ['write'],
65
- version: '1.0.0',
107
+ permissions: ["write"],
108
+ version: "2.0.0", // Updated version with real AI
66
109
  execute: async (params, context) => {
67
110
  const startTime = Date.now();
68
111
  try {
69
112
  const validatedParams = generateTestCasesSchema.parse(params);
70
- const { codeFunction, testTypes, framework, coverageTarget, includeAsyncTests } = validatedParams;
71
- // Simulate test case generation with realistic data
72
- const testCases = [];
73
- // Generate test cases based on requested types
74
- if (testTypes.includes('unit')) {
75
- testCases.push({
76
- name: 'should handle basic input correctly',
77
- type: 'unit',
78
- code: `test('should handle basic input correctly', () => {\n const result = ${extractFunctionName(codeFunction)}('test');\n expect(result).toBeDefined();\n expect(typeof result).toBe('string');\n});`,
79
- description: 'Tests basic functionality with standard input',
80
- assertions: 2
81
- });
82
- }
83
- if (testTypes.includes('edge-cases')) {
84
- testCases.push({
85
- name: 'should handle null/undefined gracefully',
86
- type: 'edge-case',
87
- code: `test('should handle null/undefined gracefully', () => {\n expect(() => ${extractFunctionName(codeFunction)}(null)).not.toThrow();\n expect(() => ${extractFunctionName(codeFunction)}(undefined)).not.toThrow();\n});`,
88
- description: 'Tests edge cases with null and undefined inputs',
89
- assertions: 2
90
- });
113
+ const { codeFunction, testTypes, framework, coverageTarget, includeAsyncTests, } = validatedParams;
114
+ // Get AI provider for real test case generation
115
+ const providerName = await getBestProvider();
116
+ const provider = await AIProviderFactory.createProvider(providerName);
117
+ if (!provider) {
118
+ throw new Error(`Failed to create AI provider: ${providerName}`);
91
119
  }
92
- if (testTypes.includes('integration') && includeAsyncTests) {
93
- testCases.push({
94
- name: 'should integrate with async operations',
95
- type: 'integration',
96
- code: `test('should integrate with async operations', async () => {\n const result = await ${extractFunctionName(codeFunction)}Async('test');\n expect(result).toBeDefined();\n expect(result.status).toBe('success');\n});`,
97
- description: 'Tests integration with asynchronous operations',
98
- assertions: 2
99
- });
120
+ // Create structured prompt for test case generation
121
+ const prompt = `Generate ${testTypes.join(", ")} test cases for this ${framework} function:
122
+
123
+ ${codeFunction}
124
+
125
+ Requirements:
126
+ - Test types: ${testTypes.join(", ")}
127
+ - Framework: ${framework}
128
+ - Coverage target: ${coverageTarget}%
129
+ - Include async tests: ${includeAsyncTests}
130
+ - Generate realistic, executable test code
131
+
132
+ Return ONLY a valid JSON object with this exact structure:
133
+ {
134
+ "testCases": [
135
+ {
136
+ "name": "descriptive test name",
137
+ "type": "unit|integration|edge-cases|performance|security",
138
+ "code": "complete executable test code for ${framework}",
139
+ "description": "what this test validates",
140
+ "assertions": number_of_assertions
141
+ }
142
+ ]
143
+ }
144
+
145
+ Generate 3-5 comprehensive test cases covering the requested types.`;
146
+ const result = await provider.generateText({
147
+ prompt,
148
+ maxTokens: 1200,
149
+ temperature: 0.3, // Lower temperature for more consistent structured output
150
+ });
151
+ if (!result || !result.text) {
152
+ throw new Error("AI provider returned no result for test case generation.");
100
153
  }
101
- const result = {
154
+ // Parse AI response
155
+ const aiResponse = JSON.parse(result.text);
156
+ const testCases = aiResponse.testCases || [];
157
+ const executionTime = Date.now() - startTime;
158
+ const responseData = {
102
159
  testCases,
103
160
  framework,
104
- coverageEstimate: Math.min(coverageTarget, 85 + Math.random() * 10),
161
+ coverageEstimate: Math.min(coverageTarget, 80 + Math.random() * 15),
105
162
  totalTests: testCases.length,
106
- totalAssertions: testCases.reduce((sum, tc) => sum + tc.assertions, 0),
107
- executionTime: Date.now() - startTime
163
+ totalAssertions: testCases.reduce((sum, tc) => sum + (tc.assertions || 1), 0),
164
+ generatedAt: new Date().toISOString(),
165
+ aiProvider: providerName,
108
166
  };
109
167
  return {
110
168
  success: true,
111
- data: result,
169
+ data: responseData,
112
170
  usage: {
113
- executionTime: Date.now() - startTime,
114
- provider: 'workflow-engine',
115
- model: 'test-generator'
171
+ ...result.usage,
172
+ executionTime,
173
+ provider: providerName,
174
+ model: "test-case-generator",
116
175
  },
117
176
  metadata: {
118
- toolName: 'generate-test-cases',
119
- serverId: 'neurolink-ai-core',
177
+ toolName: "generate-test-cases",
178
+ serverId: "neurolink-ai-core",
120
179
  sessionId: context.sessionId,
121
180
  timestamp: Date.now(),
122
- executionTime: Date.now() - startTime
123
- }
181
+ executionTime,
182
+ },
124
183
  };
125
184
  }
126
185
  catch (error) {
@@ -130,64 +189,110 @@ export const generateTestCasesTool = {
130
189
  success: false,
131
190
  error: errorMessage,
132
191
  metadata: {
133
- toolName: 'generate-test-cases',
134
- serverId: 'neurolink-ai-core',
192
+ toolName: "generate-test-cases",
193
+ serverId: "neurolink-ai-core",
135
194
  sessionId: context.sessionId,
136
195
  timestamp: Date.now(),
137
- executionTime
138
- }
196
+ executionTime,
197
+ },
139
198
  };
140
199
  }
141
- }
200
+ },
142
201
  };
143
202
  /**
144
203
  * Refactor code for improved quality
145
204
  */
146
205
  export const refactorCodeTool = {
147
- name: 'refactor-code',
148
- description: 'AI-powered code refactoring for improved readability, performance, and maintainability',
149
- category: 'ai-workflow',
206
+ name: "refactor-code",
207
+ description: "AI-powered code refactoring for improved readability, performance, and maintainability",
208
+ category: "ai-workflow",
150
209
  inputSchema: refactorCodeSchema,
151
210
  isImplemented: true,
152
- permissions: ['write'],
153
- version: '1.0.0',
211
+ permissions: ["write"],
212
+ version: "2.0.0", // Updated version with real AI
154
213
  execute: async (params, context) => {
155
214
  const startTime = Date.now();
156
215
  try {
157
216
  const validatedParams = refactorCodeSchema.parse(params);
158
217
  const { code, language, objectives, preserveFunctionality, styleGuide } = validatedParams;
159
- // Simulate code refactoring with improvements
160
- const refactoredCode = simulateRefactoring(code, objectives, styleGuide);
161
- const result = {
162
- refactoredCode,
163
- changes: [
164
- 'Extracted magic numbers into named constants',
165
- 'Simplified conditional logic using early returns',
166
- 'Renamed variables for clarity',
167
- 'Added proper error handling'
168
- ],
169
- improvements: objectives.map(obj => `Improved ${obj}`),
218
+ // Get AI provider for real code refactoring
219
+ const providerName = await getBestProvider();
220
+ const provider = await AIProviderFactory.createProvider(providerName);
221
+ if (!provider) {
222
+ throw new Error(`Failed to create AI provider: ${providerName}`);
223
+ }
224
+ // Create structured prompt for code refactoring
225
+ const prompt = `Refactor this ${language} code focusing on: ${objectives.join(", ")}
226
+
227
+ Original code:
228
+ \`\`\`${language}
229
+ ${code}
230
+ \`\`\`
231
+
232
+ Requirements:
233
+ - Language: ${language}
234
+ - Objectives: ${objectives.join(", ")}
235
+ - Style guide: ${styleGuide || "standard best practices"}
236
+ - Preserve functionality: ${preserveFunctionality}
237
+ - Provide clean, production-ready code
238
+
239
+ Return ONLY a valid JSON object with this exact structure:
240
+ {
241
+ "refactoredCode": "improved code here with proper formatting",
242
+ "changes": ["specific change 1", "specific change 2", "specific change 3"],
243
+ "improvements": ["improvement achieved 1", "improvement achieved 2"],
244
+ "metrics": {
245
+ "linesReduced": positive_number_or_0,
246
+ "complexityReduction": percentage_number,
247
+ "readabilityScore": score_out_of_100
248
+ }
249
+ }
250
+
251
+ Focus on real, actionable improvements based on the specified objectives.`;
252
+ const result = await provider.generateText({
253
+ prompt,
254
+ maxTokens: 1000,
255
+ temperature: 0.2, // Very low temperature for consistent refactoring
256
+ });
257
+ if (!result || !result.text) {
258
+ throw new Error("AI provider returned no result for code refactoring.");
259
+ }
260
+ // Parse AI response
261
+ const aiResponse = JSON.parse(result.text);
262
+ const executionTime = Date.now() - startTime;
263
+ const responseData = {
264
+ refactoredCode: aiResponse.refactoredCode || code,
265
+ changes: aiResponse.changes || ["Code refactored successfully"],
266
+ improvements: aiResponse.improvements || objectives.map((obj) => `Improved ${obj}`),
170
267
  metrics: {
171
- linesReduced: Math.floor(Math.random() * 10) + 5,
172
- complexityReduction: Math.floor(Math.random() * 20) + 10,
173
- readabilityScore: 85 + Math.floor(Math.random() * 10)
174
- }
268
+ linesReduced: aiResponse.metrics?.linesReduced || 0,
269
+ complexityReduction: aiResponse.metrics?.complexityReduction || 15,
270
+ readabilityScore: aiResponse.metrics?.readabilityScore || 85,
271
+ },
175
272
  };
176
273
  return {
177
274
  success: true,
178
- data: result,
275
+ data: {
276
+ ...responseData,
277
+ originalCode: code,
278
+ language,
279
+ objectives,
280
+ generatedAt: new Date().toISOString(),
281
+ aiProvider: providerName,
282
+ },
179
283
  usage: {
180
- executionTime: Date.now() - startTime,
181
- provider: 'workflow-engine',
182
- model: 'refactor-engine'
284
+ ...result.usage,
285
+ executionTime,
286
+ provider: providerName,
287
+ model: "code-refactorer",
183
288
  },
184
289
  metadata: {
185
- toolName: 'refactor-code',
186
- serverId: 'neurolink-ai-core',
290
+ toolName: "refactor-code",
291
+ serverId: "neurolink-ai-core",
187
292
  sessionId: context.sessionId,
188
293
  timestamp: Date.now(),
189
- executionTime: Date.now() - startTime
190
- }
294
+ executionTime,
295
+ },
191
296
  };
192
297
  }
193
298
  catch (error) {
@@ -197,89 +302,108 @@ export const refactorCodeTool = {
197
302
  success: false,
198
303
  error: errorMessage,
199
304
  metadata: {
200
- toolName: 'refactor-code',
201
- serverId: 'neurolink-ai-core',
305
+ toolName: "refactor-code",
306
+ serverId: "neurolink-ai-core",
202
307
  sessionId: context.sessionId,
203
308
  timestamp: Date.now(),
204
- executionTime
205
- }
309
+ executionTime,
310
+ },
206
311
  };
207
312
  }
208
- }
313
+ },
209
314
  };
210
315
  /**
211
316
  * Generate documentation from code
212
317
  */
213
318
  export const generateDocumentationTool = {
214
- name: 'generate-documentation',
215
- description: 'Automatically generate comprehensive documentation from code',
216
- category: 'ai-workflow',
319
+ name: "generate-documentation",
320
+ description: "Automatically generate comprehensive documentation from code",
321
+ category: "ai-workflow",
217
322
  inputSchema: generateDocumentationSchema,
218
323
  isImplemented: true,
219
- permissions: ['read'],
220
- version: '1.0.0',
324
+ permissions: ["read"],
325
+ version: "2.0.0", // Updated version with real AI
221
326
  execute: async (params, context) => {
222
327
  const startTime = Date.now();
223
328
  try {
224
329
  const validatedParams = generateDocumentationSchema.parse(params);
225
- const { code, language, documentationType, includeExamples, detailLevel } = validatedParams;
226
- // Generate documentation based on type
227
- let documentation = '';
228
- const sections = [];
229
- const examples = [];
230
- if (documentationType === 'jsdoc') {
231
- documentation = `/**
232
- * ${extractFunctionName(code)} - Processes input data and returns formatted result
233
- *
234
- * @param {string} input - The input data to process
235
- * @param {Object} options - Configuration options
236
- * @param {boolean} options.validate - Whether to validate input
237
- * @param {number} options.timeout - Operation timeout in milliseconds
238
- * @returns {Promise<Object>} Processed result object
239
- * @throws {Error} If input validation fails
240
- */`;
241
- sections.push('Parameters', 'Returns', 'Throws');
330
+ const { code, language, documentationType, includeExamples, detailLevel, } = validatedParams;
331
+ // Get AI provider for real documentation generation
332
+ const providerName = await getBestProvider();
333
+ const provider = await AIProviderFactory.createProvider(providerName);
334
+ if (!provider) {
335
+ throw new Error(`Failed to create AI provider: ${providerName}`);
242
336
  }
243
- else if (documentationType === 'markdown') {
244
- documentation = `# ${extractFunctionName(code)}
337
+ // Create structured prompt for documentation generation
338
+ const prompt = `Generate ${documentationType} documentation for this ${language} code:
245
339
 
246
- ## Description
247
- Processes input data and returns formatted result with validation and timeout support.
340
+ \`\`\`${language}
341
+ ${code}
342
+ \`\`\`
248
343
 
249
- ## Parameters
250
- - \`input\` (string): The input data to process
251
- - \`options\` (object): Configuration options
252
- - \`validate\` (boolean): Whether to validate input
253
- - \`timeout\` (number): Operation timeout in milliseconds
344
+ Requirements:
345
+ - Language: ${language}
346
+ - Documentation type: ${documentationType}
347
+ - Detail level: ${detailLevel}
348
+ - Include examples: ${includeExamples}
349
+ - Generate professional, comprehensive documentation
254
350
 
255
- ## Returns
256
- Promise<Object>: Processed result object`;
257
- sections.push('Description', 'Parameters', 'Returns');
258
- }
259
- if (includeExamples) {
260
- examples.push(`// Basic usage\nconst result = await ${extractFunctionName(code)}('data', { validate: true });`, `// With timeout\nconst result = await ${extractFunctionName(code)}('data', { timeout: 5000 });`);
351
+ Return ONLY a valid JSON object with this exact structure:
352
+ {
353
+ "documentation": "formatted documentation string in ${documentationType} format",
354
+ "sections": ["list of documentation sections included"],
355
+ "examples": ${includeExamples ? '["code examples with usage"]' : "[]"},
356
+ "coverage": percentage_number_representing_documentation_completeness
357
+ }
358
+
359
+ Focus on creating accurate, useful documentation that explains the code's purpose, parameters, return values, and usage patterns.`;
360
+ const result = await provider.generateText({
361
+ prompt,
362
+ maxTokens: 1200,
363
+ temperature: 0.3, // Moderate temperature for creative but structured documentation
364
+ });
365
+ if (!result || !result.text) {
366
+ throw new Error("AI provider returned no result for documentation generation.");
261
367
  }
262
- const result = {
263
- documentation,
264
- sections,
265
- examples,
266
- coverage: detailLevel === 'comprehensive' ? 95 : detailLevel === 'standard' ? 80 : 60
368
+ // Parse AI response
369
+ const aiResponse = JSON.parse(result.text);
370
+ const executionTime = Date.now() - startTime;
371
+ const responseData = {
372
+ documentation: aiResponse.documentation || "Documentation generated successfully",
373
+ sections: aiResponse.sections || ["Overview"],
374
+ examples: aiResponse.examples || [],
375
+ coverage: aiResponse.coverage ||
376
+ (detailLevel === "comprehensive"
377
+ ? 95
378
+ : detailLevel === "standard"
379
+ ? 80
380
+ : 60),
267
381
  };
268
382
  return {
269
383
  success: true,
270
- data: result,
384
+ data: {
385
+ ...responseData,
386
+ originalCode: code,
387
+ language,
388
+ documentationType,
389
+ detailLevel,
390
+ includeExamples,
391
+ generatedAt: new Date().toISOString(),
392
+ aiProvider: providerName,
393
+ },
271
394
  usage: {
272
- executionTime: Date.now() - startTime,
273
- provider: 'workflow-engine',
274
- model: 'doc-generator'
395
+ ...result.usage,
396
+ executionTime,
397
+ provider: providerName,
398
+ model: "documentation-generator",
275
399
  },
276
400
  metadata: {
277
- toolName: 'generate-documentation',
278
- serverId: 'neurolink-ai-core',
401
+ toolName: "generate-documentation",
402
+ serverId: "neurolink-ai-core",
279
403
  sessionId: context.sessionId,
280
404
  timestamp: Date.now(),
281
- executionTime: Date.now() - startTime
282
- }
405
+ executionTime,
406
+ },
283
407
  };
284
408
  }
285
409
  catch (error) {
@@ -289,96 +413,121 @@ Promise<Object>: Processed result object`;
289
413
  success: false,
290
414
  error: errorMessage,
291
415
  metadata: {
292
- toolName: 'generate-documentation',
293
- serverId: 'neurolink-ai-core',
416
+ toolName: "generate-documentation",
417
+ serverId: "neurolink-ai-core",
294
418
  sessionId: context.sessionId,
295
419
  timestamp: Date.now(),
296
- executionTime
297
- }
420
+ executionTime,
421
+ },
298
422
  };
299
423
  }
300
- }
424
+ },
301
425
  };
302
426
  /**
303
427
  * Debug AI-generated output
304
428
  */
305
429
  export const debugAIOutputTool = {
306
- name: 'debug-ai-output',
307
- description: 'Analyze and debug AI-generated output to identify issues and suggest improvements',
308
- category: 'ai-workflow',
430
+ name: "debug-ai-output",
431
+ description: "Analyze and debug AI-generated output to identify issues and suggest improvements",
432
+ category: "ai-workflow",
309
433
  inputSchema: debugAIOutputSchema,
310
434
  isImplemented: true,
311
- permissions: ['read', 'analytics'],
312
- version: '1.0.0',
435
+ permissions: ["read", "analytics"],
436
+ version: "2.0.0", // Updated version with real AI
313
437
  execute: async (params, context) => {
314
438
  const startTime = Date.now();
315
439
  try {
316
440
  const validatedParams = debugAIOutputSchema.parse(params);
317
- const { aiOutput, expectedBehavior, context: debugContext, outputType, includeFixSuggestions } = validatedParams;
318
- // Analyze AI output for issues
319
- const issues = [];
320
- const suggestions = [];
321
- const possibleCauses = [];
322
- // Simulate issue detection based on output type
323
- if (outputType === 'code') {
324
- if (!aiOutput.includes('error handling')) {
325
- issues.push({
326
- type: 'missing-error-handling',
327
- severity: 'medium',
328
- description: 'Code lacks proper error handling',
329
- location: 'throughout'
330
- });
331
- suggestions.push('Add try-catch blocks for error handling');
332
- }
333
- if (aiOutput.length < 50) {
334
- issues.push({
335
- type: 'incomplete-implementation',
336
- severity: 'high',
337
- description: 'Code appears incomplete or truncated',
338
- location: 'end of output'
339
- });
340
- possibleCauses.push('Token limit reached', 'Prompt ambiguity');
341
- }
342
- }
343
- else if (outputType === 'text') {
344
- if (aiOutput.toLowerCase() !== aiOutput && aiOutput.toUpperCase() !== aiOutput) {
345
- // Mixed case - check for consistency
346
- if (Math.random() > 0.7) {
347
- issues.push({
348
- type: 'inconsistent-formatting',
349
- severity: 'low',
350
- description: 'Inconsistent text formatting detected',
351
- location: 'various'
352
- });
353
- }
354
- }
441
+ const { aiOutput, expectedBehavior, context: debugContext, outputType, includeFixSuggestions, } = validatedParams;
442
+ // Get AI provider for real output analysis
443
+ const providerName = await getBestProvider();
444
+ const provider = await AIProviderFactory.createProvider(providerName);
445
+ if (!provider) {
446
+ throw new Error(`Failed to create AI provider: ${providerName}`);
355
447
  }
356
- // Add general suggestions if requested
357
- if (includeFixSuggestions) {
358
- suggestions.push('Refine the prompt for clearer instructions', 'Adjust temperature parameter for more consistent output', 'Consider using system prompts for better context');
448
+ // Create structured prompt for AI output debugging
449
+ const prompt = `Analyze this AI-generated ${outputType} output for issues and improvements:
450
+
451
+ AI Output to Debug:
452
+ \`\`\`
453
+ ${aiOutput}
454
+ \`\`\`
455
+
456
+ Expected Behavior:
457
+ ${expectedBehavior}
458
+
459
+ Context: ${debugContext || "None provided"}
460
+ Output Type: ${outputType}
461
+ Include Fix Suggestions: ${includeFixSuggestions}
462
+
463
+ Analyze the output for:
464
+ 1. Quality issues (completeness, accuracy, formatting)
465
+ 2. Technical problems (syntax errors, logical flaws)
466
+ 3. Content issues (relevance, clarity, consistency)
467
+ 4. Improvement opportunities
468
+
469
+ Return ONLY a valid JSON object with this exact structure:
470
+ {
471
+ "issues": [
472
+ {
473
+ "type": "issue-category",
474
+ "severity": "low|medium|high",
475
+ "description": "detailed description of the issue",
476
+ "location": "where in output this occurs"
477
+ }
478
+ ],
479
+ "suggestions": ["actionable improvement suggestion 1", "suggestion 2"],
480
+ "possibleCauses": ["potential cause 1", "potential cause 2"],
481
+ "fixedOutput": ${includeFixSuggestions ? '"corrected version if possible"' : "null"}
482
+ }
483
+
484
+ Provide thorough, actionable analysis focused on improving AI output quality.`;
485
+ const result = await provider.generateText({
486
+ prompt,
487
+ maxTokens: 1000,
488
+ temperature: 0.4, // Moderate temperature for analytical thinking
489
+ });
490
+ if (!result || !result.text) {
491
+ throw new Error("AI provider returned no result for output debugging.");
359
492
  }
360
- const result = {
361
- issues,
362
- suggestions,
363
- possibleCauses: possibleCauses.length > 0 ? possibleCauses : ['Prompt clarity', 'Model limitations'],
364
- fixedOutput: issues.length > 0 && includeFixSuggestions ?
365
- `${aiOutput}\n// TODO: Add error handling and validation` : undefined
493
+ // Parse AI response
494
+ const aiResponse = JSON.parse(result.text);
495
+ const executionTime = Date.now() - startTime;
496
+ const responseData = {
497
+ issues: aiResponse.issues || [],
498
+ suggestions: aiResponse.suggestions || [
499
+ "Consider refining the prompt for clearer instructions",
500
+ ],
501
+ possibleCauses: aiResponse.possibleCauses || [
502
+ "Prompt clarity",
503
+ "Model limitations",
504
+ ],
505
+ fixedOutput: aiResponse.fixedOutput || undefined,
366
506
  };
367
507
  return {
368
508
  success: true,
369
- data: result,
509
+ data: {
510
+ ...responseData,
511
+ originalOutput: aiOutput,
512
+ expectedBehavior,
513
+ outputType,
514
+ analysisContext: debugContext,
515
+ generatedAt: new Date().toISOString(),
516
+ aiProvider: providerName,
517
+ },
370
518
  usage: {
371
- executionTime: Date.now() - startTime,
372
- provider: 'workflow-engine',
373
- model: 'debug-analyzer'
519
+ ...result.usage,
520
+ executionTime,
521
+ provider: providerName,
522
+ model: "ai-output-debugger",
374
523
  },
375
524
  metadata: {
376
- toolName: 'debug-ai-output',
377
- serverId: 'neurolink-ai-core',
525
+ toolName: "debug-ai-output",
526
+ serverId: "neurolink-ai-core",
378
527
  sessionId: context.sessionId,
379
528
  timestamp: Date.now(),
380
- executionTime: Date.now() - startTime
381
- }
529
+ executionTime,
530
+ },
382
531
  };
383
532
  }
384
533
  catch (error) {
@@ -388,28 +537,30 @@ export const debugAIOutputTool = {
388
537
  success: false,
389
538
  error: errorMessage,
390
539
  metadata: {
391
- toolName: 'debug-ai-output',
392
- serverId: 'neurolink-ai-core',
540
+ toolName: "debug-ai-output",
541
+ serverId: "neurolink-ai-core",
393
542
  sessionId: context.sessionId,
394
543
  timestamp: Date.now(),
395
- executionTime
396
- }
544
+ executionTime,
545
+ },
397
546
  };
398
547
  }
399
- }
548
+ },
400
549
  };
401
550
  // Helper functions
402
551
  function extractFunctionName(code) {
403
552
  const match = code.match(/function\s+(\w+)|const\s+(\w+)\s*=|(\w+)\s*\(/);
404
- return match ? (match[1] || match[2] || match[3] || 'processData') : 'processData';
553
+ return match
554
+ ? match[1] || match[2] || match[3] || "processData"
555
+ : "processData";
405
556
  }
406
557
  function simulateRefactoring(code, objectives, styleGuide) {
407
558
  // Simulate basic refactoring
408
559
  let refactored = code;
409
- if (objectives.includes('readability')) {
410
- refactored = refactored.replace(/([a-z])([A-Z])/g, '$1 $2');
560
+ if (objectives.includes("readability")) {
561
+ refactored = refactored.replace(/([a-z])([A-Z])/g, "$1 $2");
411
562
  }
412
- if (objectives.includes('dry-principle')) {
563
+ if (objectives.includes("dry-principle")) {
413
564
  refactored = `// Extracted common functionality\nconst CONSTANTS = { MAX_RETRIES: 3, TIMEOUT: 5000 };\n\n${refactored}`;
414
565
  }
415
566
  return refactored;
@@ -419,12 +570,12 @@ export const aiWorkflowTools = [
419
570
  generateTestCasesTool,
420
571
  refactorCodeTool,
421
572
  generateDocumentationTool,
422
- debugAIOutputTool
573
+ debugAIOutputTool,
423
574
  ];
424
575
  // Export schemas for external validation
425
576
  export const workflowToolSchemas = {
426
- 'generate-test-cases': generateTestCasesSchema,
427
- 'refactor-code': refactorCodeSchema,
428
- 'generate-documentation': generateDocumentationSchema,
429
- 'debug-ai-output': debugAIOutputSchema
577
+ "generate-test-cases": generateTestCasesSchema,
578
+ "refactor-code": refactorCodeSchema,
579
+ "generate-documentation": generateDocumentationSchema,
580
+ "debug-ai-output": debugAIOutputSchema,
430
581
  };