@juspay/neurolink 7.48.1 → 7.49.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 (130) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +215 -16
  3. package/dist/agent/directTools.d.ts +55 -0
  4. package/dist/agent/directTools.js +266 -0
  5. package/dist/cli/factories/commandFactory.d.ts +2 -0
  6. package/dist/cli/factories/commandFactory.js +130 -16
  7. package/dist/cli/index.js +0 -0
  8. package/dist/cli/loop/conversationSelector.d.ts +45 -0
  9. package/dist/cli/loop/conversationSelector.js +222 -0
  10. package/dist/cli/loop/optionsSchema.d.ts +1 -1
  11. package/dist/cli/loop/session.d.ts +36 -8
  12. package/dist/cli/loop/session.js +257 -61
  13. package/dist/core/baseProvider.js +9 -2
  14. package/dist/core/evaluation.js +5 -2
  15. package/dist/factories/providerRegistry.js +2 -2
  16. package/dist/lib/agent/directTools.d.ts +55 -0
  17. package/dist/lib/agent/directTools.js +266 -0
  18. package/dist/lib/core/baseProvider.js +9 -2
  19. package/dist/lib/core/evaluation.js +5 -2
  20. package/dist/lib/factories/providerRegistry.js +2 -2
  21. package/dist/lib/mcp/factory.d.ts +2 -157
  22. package/dist/lib/mcp/flexibleToolValidator.d.ts +1 -5
  23. package/dist/lib/mcp/index.d.ts +3 -2
  24. package/dist/lib/mcp/mcpCircuitBreaker.d.ts +1 -75
  25. package/dist/lib/mcp/mcpClientFactory.d.ts +1 -20
  26. package/dist/lib/mcp/mcpClientFactory.js +1 -0
  27. package/dist/lib/mcp/registry.d.ts +3 -10
  28. package/dist/lib/mcp/servers/agent/directToolsServer.d.ts +1 -1
  29. package/dist/lib/mcp/servers/aiProviders/aiCoreServer.d.ts +1 -1
  30. package/dist/lib/mcp/servers/utilities/utilityServer.d.ts +1 -1
  31. package/dist/lib/mcp/toolDiscoveryService.d.ts +3 -84
  32. package/dist/lib/mcp/toolRegistry.d.ts +2 -24
  33. package/dist/lib/middleware/builtin/guardrails.d.ts +5 -16
  34. package/dist/lib/middleware/builtin/guardrails.js +44 -39
  35. package/dist/lib/middleware/utils/guardrailsUtils.d.ts +64 -0
  36. package/dist/lib/middleware/utils/guardrailsUtils.js +387 -0
  37. package/dist/lib/neurolink.d.ts +1 -1
  38. package/dist/lib/providers/anthropic.js +46 -3
  39. package/dist/lib/providers/azureOpenai.js +8 -2
  40. package/dist/lib/providers/googleAiStudio.js +8 -2
  41. package/dist/lib/providers/googleVertex.js +11 -2
  42. package/dist/lib/providers/huggingFace.js +1 -1
  43. package/dist/lib/providers/litellm.js +1 -1
  44. package/dist/lib/providers/mistral.js +1 -1
  45. package/dist/lib/providers/openAI.js +46 -3
  46. package/dist/lib/session/globalSessionState.d.ts +26 -0
  47. package/dist/lib/session/globalSessionState.js +49 -0
  48. package/dist/lib/types/cli.d.ts +28 -0
  49. package/dist/lib/types/content.d.ts +18 -5
  50. package/dist/lib/types/contextTypes.d.ts +1 -1
  51. package/dist/lib/types/conversation.d.ts +55 -4
  52. package/dist/lib/types/fileTypes.d.ts +65 -0
  53. package/dist/lib/types/fileTypes.js +4 -0
  54. package/dist/lib/types/generateTypes.d.ts +12 -0
  55. package/dist/lib/types/guardrails.d.ts +103 -0
  56. package/dist/lib/types/guardrails.js +1 -0
  57. package/dist/lib/types/index.d.ts +4 -2
  58. package/dist/lib/types/index.js +4 -0
  59. package/dist/lib/types/mcpTypes.d.ts +407 -14
  60. package/dist/lib/types/streamTypes.d.ts +7 -0
  61. package/dist/lib/types/tools.d.ts +132 -35
  62. package/dist/lib/utils/csvProcessor.d.ts +68 -0
  63. package/dist/lib/utils/csvProcessor.js +277 -0
  64. package/dist/lib/utils/fileDetector.d.ts +57 -0
  65. package/dist/lib/utils/fileDetector.js +457 -0
  66. package/dist/lib/utils/imageProcessor.d.ts +10 -0
  67. package/dist/lib/utils/imageProcessor.js +22 -0
  68. package/dist/lib/utils/loopUtils.d.ts +71 -0
  69. package/dist/lib/utils/loopUtils.js +262 -0
  70. package/dist/lib/utils/messageBuilder.d.ts +2 -1
  71. package/dist/lib/utils/messageBuilder.js +197 -2
  72. package/dist/lib/utils/optionsUtils.d.ts +1 -1
  73. package/dist/mcp/factory.d.ts +2 -157
  74. package/dist/mcp/flexibleToolValidator.d.ts +1 -5
  75. package/dist/mcp/index.d.ts +3 -2
  76. package/dist/mcp/mcpCircuitBreaker.d.ts +1 -75
  77. package/dist/mcp/mcpClientFactory.d.ts +1 -20
  78. package/dist/mcp/mcpClientFactory.js +1 -0
  79. package/dist/mcp/registry.d.ts +3 -10
  80. package/dist/mcp/servers/agent/directToolsServer.d.ts +1 -1
  81. package/dist/mcp/servers/aiProviders/aiCoreServer.d.ts +1 -1
  82. package/dist/mcp/servers/utilities/utilityServer.d.ts +1 -1
  83. package/dist/mcp/toolDiscoveryService.d.ts +3 -84
  84. package/dist/mcp/toolRegistry.d.ts +2 -24
  85. package/dist/middleware/builtin/guardrails.d.ts +5 -16
  86. package/dist/middleware/builtin/guardrails.js +44 -39
  87. package/dist/middleware/utils/guardrailsUtils.d.ts +64 -0
  88. package/dist/middleware/utils/guardrailsUtils.js +387 -0
  89. package/dist/neurolink.d.ts +1 -1
  90. package/dist/providers/anthropic.js +46 -3
  91. package/dist/providers/azureOpenai.js +8 -2
  92. package/dist/providers/googleAiStudio.js +8 -2
  93. package/dist/providers/googleVertex.js +11 -2
  94. package/dist/providers/huggingFace.js +1 -1
  95. package/dist/providers/litellm.js +1 -1
  96. package/dist/providers/mistral.js +1 -1
  97. package/dist/providers/openAI.js +46 -3
  98. package/dist/session/globalSessionState.d.ts +26 -0
  99. package/dist/session/globalSessionState.js +49 -0
  100. package/dist/types/cli.d.ts +28 -0
  101. package/dist/types/content.d.ts +18 -5
  102. package/dist/types/contextTypes.d.ts +1 -1
  103. package/dist/types/conversation.d.ts +55 -4
  104. package/dist/types/fileTypes.d.ts +65 -0
  105. package/dist/types/fileTypes.js +4 -0
  106. package/dist/types/generateTypes.d.ts +12 -0
  107. package/dist/types/guardrails.d.ts +103 -0
  108. package/dist/types/guardrails.js +1 -0
  109. package/dist/types/index.d.ts +4 -2
  110. package/dist/types/index.js +4 -0
  111. package/dist/types/mcpTypes.d.ts +407 -14
  112. package/dist/types/modelTypes.d.ts +6 -6
  113. package/dist/types/streamTypes.d.ts +7 -0
  114. package/dist/types/tools.d.ts +132 -35
  115. package/dist/utils/csvProcessor.d.ts +68 -0
  116. package/dist/utils/csvProcessor.js +277 -0
  117. package/dist/utils/fileDetector.d.ts +57 -0
  118. package/dist/utils/fileDetector.js +457 -0
  119. package/dist/utils/imageProcessor.d.ts +10 -0
  120. package/dist/utils/imageProcessor.js +22 -0
  121. package/dist/utils/loopUtils.d.ts +71 -0
  122. package/dist/utils/loopUtils.js +262 -0
  123. package/dist/utils/messageBuilder.d.ts +2 -1
  124. package/dist/utils/messageBuilder.js +197 -2
  125. package/dist/utils/optionsUtils.d.ts +1 -1
  126. package/package.json +9 -3
  127. package/dist/lib/mcp/contracts/mcpContract.d.ts +0 -106
  128. package/dist/lib/mcp/contracts/mcpContract.js +0 -5
  129. package/dist/mcp/contracts/mcpContract.d.ts +0 -106
  130. package/dist/mcp/contracts/mcpContract.js +0 -5
@@ -8,6 +8,7 @@ import * as fs from "fs";
8
8
  import * as path from "path";
9
9
  import { logger } from "../utils/logger.js";
10
10
  import { VertexAI } from "@google-cloud/vertexai";
11
+ import { CSVProcessor } from "../utils/csvProcessor.js";
11
12
  // Runtime Google Search tool creation - bypasses TypeScript strict typing
12
13
  function createGoogleSearchTools() {
13
14
  const searchTool = {};
@@ -336,6 +337,271 @@ export const directAgentTools = {
336
337
  }
337
338
  },
338
339
  }),
340
+ analyzeCSV: tool({
341
+ description: "Analyze CSV file for accurate counting, aggregation, and statistical analysis. Use this for precise data operations like counting rows by column, calculating sums/averages, finding min/max values, etc. The tool reads the file directly - do NOT pass CSV content.",
342
+ parameters: z.object({
343
+ filePath: z
344
+ .string()
345
+ .refine((inputPath) => {
346
+ const resolvedPath = path.resolve(inputPath);
347
+ const normalizedPath = resolvedPath
348
+ .toLowerCase()
349
+ .replace(/\\/g, "/");
350
+ const sensitivePatterns = [
351
+ "/etc/",
352
+ "/sys/",
353
+ "/proc/",
354
+ "/dev/",
355
+ "/root/",
356
+ "/.ssh/",
357
+ "/private/etc/",
358
+ "/private/var/",
359
+ "c:/windows/",
360
+ "c:/program files/",
361
+ "c:/programdata/",
362
+ ];
363
+ return !sensitivePatterns.some((pattern) => normalizedPath.startsWith(pattern));
364
+ }, {
365
+ message: "Invalid file path: access to system directories is not allowed",
366
+ })
367
+ .describe("Path to the CSV file to analyze (e.g., 'test/data.csv' or '/absolute/path/file.csv')"),
368
+ operation: z
369
+ .enum([
370
+ "count_by_column",
371
+ "sum_by_column",
372
+ "average_by_column",
373
+ "min_max_by_column",
374
+ "describe",
375
+ ])
376
+ .describe("Type of analysis to perform"),
377
+ column: z
378
+ .string()
379
+ .optional()
380
+ .describe("Column name for the operation (required for most operations)"),
381
+ maxRows: z
382
+ .number()
383
+ .optional()
384
+ .describe("Maximum rows to process (default: 1000)"),
385
+ }),
386
+ execute: async ({ filePath, operation, column, maxRows = 1000 }) => {
387
+ const startTime = Date.now();
388
+ logger.info(`[analyzeCSV] 🚀 START: file=${filePath}, operation=${operation}, column=${column}, maxRows=${maxRows}`);
389
+ try {
390
+ // Resolve file path
391
+ logger.debug(`[analyzeCSV] Resolving file: ${filePath}`);
392
+ const path = await import("path");
393
+ // Resolve path (support both relative and absolute)
394
+ const resolvedPath = path.isAbsolute(filePath)
395
+ ? filePath
396
+ : path.resolve(process.cwd(), filePath);
397
+ logger.debug(`[analyzeCSV] Resolved path: ${resolvedPath}`);
398
+ // Parse CSV using streaming from disk (memory efficient)
399
+ logger.info(`[analyzeCSV] Starting CSV parsing (max ${maxRows} rows)...`);
400
+ const rows = (await CSVProcessor.parseCSVFile(resolvedPath, maxRows));
401
+ logger.info(`[analyzeCSV] ✅ CSV parsing complete: ${rows.length} rows`);
402
+ if (rows.length === 0) {
403
+ logger.warn(`[analyzeCSV] No data rows found`);
404
+ return {
405
+ success: false,
406
+ error: "No data rows found in CSV",
407
+ };
408
+ }
409
+ // Log column names
410
+ const columnNames = rows.length > 0 ? Object.keys(rows[0]) : [];
411
+ logger.info(`[analyzeCSV] Found ${rows.length} rows with columns:`, columnNames);
412
+ logger.info(`[analyzeCSV] Executing operation: ${operation}`);
413
+ let result;
414
+ switch (operation) {
415
+ case "count_by_column": {
416
+ logger.info(`[analyzeCSV] count_by_column: column=${column}`);
417
+ if (!column) {
418
+ return {
419
+ success: false,
420
+ error: "Column name required for count_by_column operation",
421
+ };
422
+ }
423
+ // Count occurrences of each value in the column
424
+ const counts = {};
425
+ logger.debug(`[analyzeCSV] Counting rows...`);
426
+ for (const row of rows) {
427
+ const value = row[column];
428
+ if (value !== undefined) {
429
+ counts[value] = (counts[value] || 0) + 1;
430
+ }
431
+ }
432
+ logger.debug(`[analyzeCSV] Found ${Object.keys(counts).length} unique values`);
433
+ // Sort by count descending
434
+ logger.debug(`[analyzeCSV] Sorting results...`);
435
+ result = Object.fromEntries(Object.entries(counts).sort(([, a], [, b]) => b - a));
436
+ logger.info(`[analyzeCSV] ✅ count_by_column complete. Result:`, result);
437
+ break;
438
+ }
439
+ case "sum_by_column": {
440
+ logger.info(`[analyzeCSV] sum_by_column: column=${column}`);
441
+ if (!column) {
442
+ return {
443
+ success: false,
444
+ error: "Column name required for sum_by_column operation",
445
+ };
446
+ }
447
+ // Sum numeric values from the target column itself for each group
448
+ const groups = {};
449
+ logger.debug(`[analyzeCSV] Grouping and summing ${rows.length} rows...`);
450
+ let processedRows = 0;
451
+ let totalNumericValuesFound = 0;
452
+ for (const row of rows) {
453
+ const key = row[column];
454
+ if (!key) {
455
+ continue;
456
+ }
457
+ // Parse numeric value from the target column
458
+ const value = row[column];
459
+ if (value === undefined || value === null || value === "") {
460
+ continue;
461
+ }
462
+ const num = parseFloat(value);
463
+ if (isNaN(num)) {
464
+ continue;
465
+ }
466
+ if (!groups[key]) {
467
+ groups[key] = 0;
468
+ }
469
+ groups[key] += num;
470
+ totalNumericValuesFound++;
471
+ processedRows++;
472
+ if (processedRows % 10 === 0) {
473
+ logger.debug(`[analyzeCSV] Processed ${processedRows}/${rows.length} rows`);
474
+ }
475
+ }
476
+ // Fail fast if no numeric data found in the requested column
477
+ if (totalNumericValuesFound === 0) {
478
+ return {
479
+ success: false,
480
+ error: `No numeric data found in column "${column}" for sum_by_column operation`,
481
+ };
482
+ }
483
+ logger.debug(`[analyzeCSV] Calculated sums for ${Object.keys(groups).length} groups (${totalNumericValuesFound} numeric values)`);
484
+ result = groups;
485
+ logger.info(`[analyzeCSV] ✅ sum_by_column complete`);
486
+ break;
487
+ }
488
+ case "average_by_column": {
489
+ logger.info(`[analyzeCSV] average_by_column: column=${column}`);
490
+ if (!column) {
491
+ return {
492
+ success: false,
493
+ error: "Column name required for average_by_column operation",
494
+ };
495
+ }
496
+ // Average numeric values from the target column itself for each group
497
+ const groups = {};
498
+ logger.debug(`[analyzeCSV] Grouping and averaging ${rows.length} rows...`);
499
+ let processedRows = 0;
500
+ let totalNumericValuesFound = 0;
501
+ for (const row of rows) {
502
+ const key = row[column];
503
+ if (!key) {
504
+ continue;
505
+ }
506
+ // Parse numeric value from the target column
507
+ const value = row[column];
508
+ if (value === undefined || value === null || value === "") {
509
+ continue;
510
+ }
511
+ const num = parseFloat(value);
512
+ if (isNaN(num)) {
513
+ continue;
514
+ }
515
+ if (!groups[key]) {
516
+ groups[key] = { sum: 0, count: 0 };
517
+ }
518
+ groups[key].sum += num;
519
+ groups[key].count++;
520
+ totalNumericValuesFound++;
521
+ processedRows++;
522
+ if (processedRows % 10 === 0) {
523
+ logger.debug(`[analyzeCSV] Processed ${processedRows}/${rows.length} rows`);
524
+ }
525
+ }
526
+ // Fail fast if no numeric data found in the requested column
527
+ if (totalNumericValuesFound === 0) {
528
+ return {
529
+ success: false,
530
+ error: `No numeric data found in column "${column}" for average_by_column operation`,
531
+ };
532
+ }
533
+ logger.debug(`[analyzeCSV] Calculated averages for ${Object.keys(groups).length} groups (${totalNumericValuesFound} numeric values)`);
534
+ result = Object.fromEntries(Object.entries(groups).map(([k, v]) => [
535
+ k,
536
+ v.count > 0 ? v.sum / v.count : 0,
537
+ ]));
538
+ logger.info(`[analyzeCSV] ✅ average_by_column complete`);
539
+ break;
540
+ }
541
+ case "min_max_by_column": {
542
+ if (!column) {
543
+ return {
544
+ success: false,
545
+ error: "Column name required for min_max_by_column operation",
546
+ };
547
+ }
548
+ const values = rows
549
+ .map((row) => row[column])
550
+ .filter((v) => v !== undefined && v !== "");
551
+ const numericValues = values
552
+ .map((v) => parseFloat(v))
553
+ .filter((n) => !isNaN(n));
554
+ if (numericValues.length === 0) {
555
+ return {
556
+ success: false,
557
+ error: `No numeric data found in column "${column}" for min_max_by_column operation`,
558
+ };
559
+ }
560
+ result = {
561
+ min: Math.min(...numericValues),
562
+ max: Math.max(...numericValues),
563
+ numericCount: numericValues.length,
564
+ totalCount: values.length,
565
+ };
566
+ break;
567
+ }
568
+ case "describe": {
569
+ const columnNames = rows.length > 0 ? Object.keys(rows[0]) : [];
570
+ result = {
571
+ total_rows: rows.length,
572
+ columns: columnNames,
573
+ column_count: columnNames.length,
574
+ };
575
+ break;
576
+ }
577
+ default:
578
+ return {
579
+ success: false,
580
+ error: `Unknown operation: ${operation}`,
581
+ };
582
+ }
583
+ const duration = Date.now() - startTime;
584
+ logger.info(`[analyzeCSV] 🏁 COMPLETE: ${operation} took ${duration}ms`);
585
+ const response = {
586
+ success: true,
587
+ operation,
588
+ column,
589
+ result: JSON.stringify(result, null, 2),
590
+ rowCount: rows.length,
591
+ };
592
+ logger.debug(`[analyzeCSV] 📤 RETURNING TO LLM:`, JSON.stringify(response, null, 2));
593
+ return response;
594
+ }
595
+ catch (error) {
596
+ return {
597
+ success: false,
598
+ error: error instanceof Error ? error.message : String(error),
599
+ operation,
600
+ column,
601
+ };
602
+ }
603
+ },
604
+ }),
339
605
  websearchGrounding: tool({
340
606
  description: "Search the web for current information using Google Search grounding. Returns raw search data for AI processing.",
341
607
  parameters: z.object({
@@ -98,6 +98,7 @@ export class BaseProvider {
98
98
  // Convert stream options to text generation options
99
99
  const textOptions = {
100
100
  prompt: options.input?.text || "",
101
+ input: options.input,
101
102
  systemPrompt: options.systemPrompt,
102
103
  temperature: options.temperature,
103
104
  maxTokens: options.maxTokens,
@@ -111,6 +112,7 @@ export class BaseProvider {
111
112
  evaluationDomain: options.evaluationDomain,
112
113
  toolUsageContext: options.toolUsageContext,
113
114
  context: options.context,
115
+ csvOptions: options.csvOptions,
114
116
  };
115
117
  logger.debug(`Calling generate for fake streaming`, {
116
118
  provider: this.providerName,
@@ -229,7 +231,9 @@ export class BaseProvider {
229
231
  const input = opts.input;
230
232
  const hasImages = !!input?.images?.length;
231
233
  const hasContent = !!input?.content?.length;
232
- return hasImages || hasContent;
234
+ const hasCSVFiles = !!input?.csvFiles?.length;
235
+ const hasFiles = !!input?.files?.length;
236
+ return hasImages || hasContent || hasCSVFiles || hasFiles;
233
237
  };
234
238
  let messages;
235
239
  if (hasMultimodalInput(options)) {
@@ -242,7 +246,10 @@ export class BaseProvider {
242
246
  text: options.prompt || options.input?.text || "",
243
247
  images: input?.images,
244
248
  content: input?.content,
249
+ csvFiles: input?.csvFiles,
250
+ files: input?.files,
245
251
  },
252
+ csvOptions: options.csvOptions,
246
253
  provider: options.provider,
247
254
  model: options.model,
248
255
  temperature: options.temperature,
@@ -258,7 +265,7 @@ export class BaseProvider {
258
265
  if (process.env.NEUROLINK_DEBUG === "true") {
259
266
  logger.debug("No multimodal input detected, using standard message builder");
260
267
  }
261
- messages = buildMessagesArray(options);
268
+ messages = await buildMessagesArray(options);
262
269
  }
263
270
  // Convert messages to Vercel AI SDK format
264
271
  return messages.map((msg) => {
@@ -225,8 +225,11 @@ Completeness: [score]
225
225
  Overall: [score]
226
226
  Reasoning: [Provide a detailed explanation of your evaluation, explaining why you gave these scores. Include specific observations about the response's strengths and all possible areas for improvement.]
227
227
  `;
228
- // Generate evaluation
229
- const result = await provider.generate(prompt);
228
+ // Generate evaluation (simple text prompt only - no file processing)
229
+ const result = await provider.generate({
230
+ input: { text: prompt },
231
+ disableTools: true, // Evaluation doesn't need tools
232
+ });
230
233
  if (!result) {
231
234
  logger.debug(`[${functionTag}] No response from provider`);
232
235
  return getDefaultEvaluation("no-response", Date.now() - startTime, context);
@@ -45,9 +45,9 @@ export class ProviderRegistry {
45
45
  }, undefined, // Let provider read BEDROCK_MODEL from .env
46
46
  ["bedrock", "aws"]);
47
47
  // Register Azure OpenAI provider
48
- ProviderFactory.registerProvider(AIProviderName.AZURE, async (modelName) => {
48
+ ProviderFactory.registerProvider(AIProviderName.AZURE, async (modelName, _providerName, sdk) => {
49
49
  const { AzureOpenAIProvider } = await import("../providers/azureOpenai.js");
50
- return new AzureOpenAIProvider(modelName);
50
+ return new AzureOpenAIProvider(modelName, sdk);
51
51
  }, process.env.AZURE_MODEL ||
52
52
  process.env.AZURE_OPENAI_MODEL ||
53
53
  process.env.AZURE_OPENAI_DEPLOYMENT ||
@@ -3,162 +3,7 @@
3
3
  * Factory-First Architecture: MCP servers create tools for internal orchestration
4
4
  * Compatible with MCP patterns for seamless integration
5
5
  */
6
- import type { ExecutionContext } from "./contracts/mcpContract.js";
7
- /**
8
- * MCP Server Categories for organization and discovery
9
- */
10
- export type MCPServerCategory = "aiProviders" | "frameworks" | "development" | "business" | "content" | "data" | "integrations" | "automation" | "analysis" | "custom";
11
- /**
12
- * Tool execution context - Rich context passed to every tool execution
13
- * Following standard patterns for rich tool context
14
- * Extends ExecutionContext for compatibility
15
- */
16
- export interface NeuroLinkExecutionContext extends ExecutionContext {
17
- aiProvider?: string;
18
- modelId?: string;
19
- temperature?: number;
20
- maxTokens?: number;
21
- appId?: string;
22
- clientId?: string;
23
- clientVersion?: string;
24
- organizationId?: string;
25
- projectId?: string;
26
- environment?: string;
27
- environmentType?: "development" | "staging" | "production";
28
- platform?: string;
29
- device?: string;
30
- browser?: string;
31
- userAgent?: string;
32
- frameworkType?: "react" | "vue" | "svelte" | "next" | "nuxt" | "sveltekit";
33
- toolChain?: string[];
34
- parentToolId?: string;
35
- locale?: string;
36
- timezone?: string;
37
- ipAddress?: string;
38
- requestId?: string;
39
- timestamp?: number;
40
- permissions?: string[];
41
- features?: string[];
42
- enableDemoMode?: boolean;
43
- securityLevel?: "public" | "private" | "organization";
44
- metadata?: Record<string, unknown>;
45
- [key: string]: unknown;
46
- }
47
- /**
48
- * Tool execution result - Standardized result format
49
- */
50
- export interface ToolResult {
51
- success: boolean;
52
- data?: unknown;
53
- error?: string | Error;
54
- usage?: {
55
- tokens?: number;
56
- cost?: number;
57
- provider?: string;
58
- model?: string;
59
- executionTime?: number;
60
- };
61
- metadata?: {
62
- toolName?: string;
63
- serverId?: string;
64
- serverTitle?: string;
65
- sessionId?: string;
66
- timestamp?: number;
67
- executionTime?: number;
68
- executionId?: string;
69
- [key: string]: unknown;
70
- };
71
- }
72
- /**
73
- * MCP Tool Interface - Standalone definition to avoid confusion with ToolDefinition execute signature
74
- */
75
- /**
76
- * NeuroLink MCP Tool Interface - Standardized tool definition for MCP integration
77
- *
78
- * This interface defines the contract for all tools in the NeuroLink ecosystem,
79
- * ensuring consistent execution patterns and metadata handling across different
80
- * MCP servers and tool implementations.
81
- *
82
- * Key features:
83
- * - Promise-based execution with ToolResult return type
84
- * - Rich context support for session management and permissions
85
- * - Optional schema validation for input/output
86
- * - Comprehensive metadata support for tool discovery
87
- *
88
- * @example
89
- * ```typescript
90
- * const calculatorTool: NeuroLinkMCPTool = {
91
- * name: "calculator",
92
- * description: "Performs basic arithmetic operations",
93
- * category: "math",
94
- * inputSchema: z.object({ a: z.number(), b: z.number(), op: z.string() }),
95
- * async execute(params, context) {
96
- * const { a, b, op } = params as { a: number; b: number; op: string };
97
- * const result = op === "add" ? a + b : a - b;
98
- * return { success: true, data: result };
99
- * }
100
- * };
101
- * ```
102
- */
103
- export interface NeuroLinkMCPTool {
104
- /** Unique tool identifier for MCP registration and execution */
105
- name: string;
106
- /** Human-readable description of tool functionality */
107
- description: string;
108
- /** Optional category for tool organization and discovery */
109
- category?: string;
110
- /** Optional input schema for parameter validation (Zod or JSON Schema) */
111
- inputSchema?: unknown;
112
- /** Optional output schema for result validation */
113
- outputSchema?: unknown;
114
- /** Implementation status flag for development tracking */
115
- isImplemented?: boolean;
116
- /** Required permissions for tool execution in secured environments */
117
- permissions?: string[];
118
- /** Tool version for compatibility and update management */
119
- version?: string;
120
- /** Additional metadata for tool information and capabilities */
121
- metadata?: Record<string, unknown>;
122
- /**
123
- * Tool execution function with standardized signature
124
- *
125
- * @param params - Input parameters for the tool (validated against inputSchema if provided)
126
- * @param context - Execution context with session, user, and environment information
127
- * @returns Promise resolving to ToolResult with success status, data, and metadata
128
- * @throws ValidationError if parameters fail validation
129
- */
130
- execute: (params: unknown, context: NeuroLinkExecutionContext) => Promise<ToolResult>;
131
- }
132
- /**
133
- * MCP Server Interface - Standard compatible
134
- */
135
- export interface NeuroLinkMCPServer {
136
- id: string;
137
- title: string;
138
- description?: string;
139
- version?: string;
140
- category?: MCPServerCategory;
141
- visibility?: "public" | "private" | "organization";
142
- tools: Record<string, NeuroLinkMCPTool>;
143
- registerTool(tool: NeuroLinkMCPTool): NeuroLinkMCPServer;
144
- metadata?: Record<string, unknown>;
145
- dependencies?: string[];
146
- capabilities?: string[];
147
- }
148
- /**
149
- * MCP Server Configuration for creation
150
- */
151
- export interface MCPServerConfig {
152
- id: string;
153
- title: string;
154
- description?: string;
155
- version?: string;
156
- category?: MCPServerCategory;
157
- visibility?: "public" | "private" | "organization";
158
- metadata?: Record<string, unknown>;
159
- dependencies?: string[];
160
- capabilities?: string[];
161
- }
6
+ import type { MCPServerDomainCategory, NeuroLinkMCPTool, NeuroLinkMCPServer, MCPServerConfig } from "../types/mcpTypes.js";
162
7
  /**
163
8
  * Create MCP Server Factory Function
164
9
  *
@@ -200,7 +45,7 @@ export declare function getServerInfo(server: NeuroLinkMCPServer): {
200
45
  id: string;
201
46
  title: string;
202
47
  description?: string;
203
- category?: MCPServerCategory;
48
+ category?: MCPServerDomainCategory;
204
49
  toolCount: number;
205
50
  capabilities: string[];
206
51
  };
@@ -9,11 +9,7 @@
9
9
  * - No context-specific validation or arbitrary pattern restrictions
10
10
  * - Designed to support ALL legitimate MCP tools (github.create_repo, filesystem.read_file, etc.)
11
11
  */
12
- export interface FlexibleValidationResult {
13
- isValid: boolean;
14
- error?: string;
15
- warnings?: string[];
16
- }
12
+ import type { FlexibleValidationResult } from "../types/mcpTypes.js";
17
13
  export declare class FlexibleToolValidator {
18
14
  private static readonly MAX_TOOL_NAME_LENGTH;
19
15
  private static readonly MIN_TOOL_NAME_LENGTH;
@@ -3,10 +3,11 @@
3
3
  * Universal AI Development Platform with Extensible Plugin Architecture
4
4
  * Implementation based on research blueprint
5
5
  */
6
- export type { McpMetadata, ExecutionContext, DiscoveredMcp, ToolInfo, ToolExecutionResult, } from "./contracts/mcpContract.js";
6
+ export type { McpMetadata, DiscoveredMcp } from "../types/mcpTypes.js";
7
+ export type { ExecutionContext, ToolInfo, ToolExecutionResult, } from "../types/tools.js";
7
8
  export { mcpLogger } from "../utils/logger.js";
8
9
  export type { LogLevel } from "../utils/logger.js";
9
- import type { McpMetadata } from "./contracts/mcpContract.js";
10
+ import type { McpMetadata } from "../types/mcpTypes.js";
10
11
  /**
11
12
  * Initialize the MCP ecosystem - simplified
12
13
  */
@@ -4,81 +4,7 @@
4
4
  * Provides fault tolerance and prevents cascading failures
5
5
  */
6
6
  import { EventEmitter } from "events";
7
- /**
8
- * Circuit breaker states
9
- */
10
- export type CircuitBreakerState = "closed" | "open" | "half-open";
11
- /**
12
- * Circuit breaker configuration
13
- */
14
- export interface CircuitBreakerConfig {
15
- /** Number of failures before opening the circuit */
16
- failureThreshold: number;
17
- /** Time to wait before attempting reset (milliseconds) */
18
- resetTimeout: number;
19
- /** Maximum calls allowed in half-open state */
20
- halfOpenMaxCalls: number;
21
- /** Timeout for individual operations (milliseconds) */
22
- operationTimeout: number;
23
- /** Minimum number of calls before calculating failure rate */
24
- minimumCallsBeforeCalculation: number;
25
- /** Window size for calculating failure rate (milliseconds) */
26
- statisticsWindowSize: number;
27
- }
28
- /**
29
- * Circuit breaker statistics
30
- */
31
- export interface CircuitBreakerStats {
32
- /** Current state */
33
- state: CircuitBreakerState;
34
- /** Total number of calls */
35
- totalCalls: number;
36
- /** Number of successful calls */
37
- successfulCalls: number;
38
- /** Number of failed calls */
39
- failedCalls: number;
40
- /** Current failure rate (0-1) */
41
- failureRate: number;
42
- /** Calls in current time window */
43
- windowCalls: number;
44
- /** Last state change timestamp */
45
- lastStateChange: Date;
46
- /** Next retry time (for open state) */
47
- nextRetryTime?: Date;
48
- /** Half-open call count */
49
- halfOpenCalls: number;
50
- }
51
- /**
52
- * Circuit breaker events
53
- */
54
- export interface CircuitBreakerEvents {
55
- stateChange: {
56
- oldState: CircuitBreakerState;
57
- newState: CircuitBreakerState;
58
- reason: string;
59
- timestamp: Date;
60
- };
61
- callSuccess: {
62
- duration: number;
63
- timestamp: Date;
64
- };
65
- callFailure: {
66
- error: string;
67
- duration: number;
68
- timestamp: Date;
69
- };
70
- circuitOpen: {
71
- failureRate: number;
72
- totalCalls: number;
73
- timestamp: Date;
74
- };
75
- circuitHalfOpen: {
76
- timestamp: Date;
77
- };
78
- circuitClosed: {
79
- timestamp: Date;
80
- };
81
- }
7
+ import type { CircuitBreakerConfig, CircuitBreakerStats } from "../types/mcpTypes.js";
82
8
  /**
83
9
  * MCPCircuitBreaker
84
10
  * Implements circuit breaker pattern for fault tolerance
@@ -8,26 +8,7 @@ import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
8
8
  import type { ClientCapabilities } from "@modelcontextprotocol/sdk/types.js";
9
9
  import { ChildProcess } from "child_process";
10
10
  import type { MCPTransportType } from "../types/externalMcp.js";
11
- import type { MCPServerInfo } from "../types/mcpTypes.js";
12
- /**
13
- * MCP client creation result
14
- */
15
- export interface MCPClientResult {
16
- /** Whether client creation was successful */
17
- success: boolean;
18
- /** Created client instance */
19
- client?: Client;
20
- /** Created transport instance */
21
- transport?: Transport;
22
- /** Created process (for stdio transport) */
23
- process?: ChildProcess;
24
- /** Error message if failed */
25
- error?: string;
26
- /** Creation duration in milliseconds */
27
- duration: number;
28
- /** Server capabilities reported during handshake */
29
- capabilities?: ClientCapabilities;
30
- }
11
+ import type { MCPServerInfo, MCPClientResult } from "../types/mcpTypes.js";
31
12
  /**
32
13
  * MCPClientFactory
33
14
  * Factory class for creating MCP clients with different transports
@@ -205,6 +205,7 @@ export class MCPClientFactory {
205
205
  .filter(([, value]) => value !== undefined)
206
206
  .map(([key, value]) => [key, String(value)])),
207
207
  cwd: config.cwd,
208
+ stderr: "ignore", // Suppress MCP server startup messages
208
209
  });
209
210
  return { transport, process: childProcess };
210
211
  }