@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
@@ -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
  }
@@ -1,22 +1,15 @@
1
1
  /**
2
2
  * MCP Registry - Industry Standard Interface with camelCase
3
3
  */
4
- import type { DiscoveredMcp, ExecutionContext, ToolInfo } from "./contracts/mcpContract.js";
4
+ import type { DiscoveredMcp, McpRegistry } from "../types/mcpTypes.js";
5
+ import type { ToolInfo, ExecutionContext } from "../types/tools.js";
5
6
  import type { UnknownRecord } from "../types/common.js";
6
- /**
7
- * MCP Registry interface with optional methods for maximum flexibility
8
- */
9
- export interface McpRegistry {
10
- registerServer?(serverId: string, serverConfig?: unknown, context?: ExecutionContext): Promise<void>;
11
- executeTool?<T = unknown>(toolName: string, args?: unknown, context?: ExecutionContext): Promise<T>;
12
- listTools?(context?: ExecutionContext): Promise<ToolInfo[]>;
13
- }
14
7
  /**
15
8
  * Simple MCP registry for plugin management
16
9
  * Maintains backward compatibility with existing code
17
10
  */
18
11
  export declare class MCPRegistry implements McpRegistry {
19
- plugins: Map<string, DiscoveredMcp<import("../types/typeAliases.js").StandardRecord>>;
12
+ plugins: Map<string, DiscoveredMcp>;
20
13
  /**
21
14
  * Register a plugin
22
15
  */
@@ -5,4 +5,4 @@
5
5
  /**
6
6
  * Direct Tools Server - Agent direct tools for immediate use
7
7
  */
8
- export declare const directToolsServer: import("../../factory.js").NeuroLinkMCPServer;
8
+ export declare const directToolsServer: import("../../../types/mcpTypes.js").NeuroLinkMCPServer;
@@ -7,4 +7,4 @@
7
7
  * AI Core Server - Central hub for AI provider management
8
8
  * Provides provider selection and status checking functionality
9
9
  */
10
- export declare const aiCoreServer: import("../../factory.js").NeuroLinkMCPServer;
10
+ export declare const aiCoreServer: import("../../../types/mcpTypes.js").NeuroLinkMCPServer;
@@ -5,4 +5,4 @@
5
5
  /**
6
6
  * Utility Server - General utility tools
7
7
  */
8
- export declare const utilityServer: import("../../factory.js").NeuroLinkMCPServer;
8
+ export declare const utilityServer: import("../../../types/mcpTypes.js").NeuroLinkMCPServer;
@@ -5,90 +5,9 @@
5
5
  */
6
6
  import { EventEmitter } from "events";
7
7
  import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
8
- import type { ExternalMCPToolInfo, ExternalMCPToolResult, ExternalMCPToolContext } from "../types/externalMcp.js";
8
+ import type { ExternalMCPToolInfo, ExternalMCPToolResult } from "../types/externalMcp.js";
9
+ import type { ToolDiscoveryResult, ExternalToolExecutionOptions } from "../types/mcpTypes.js";
9
10
  import type { JsonObject } from "../types/common.js";
10
- /**
11
- * Tool discovery result
12
- */
13
- export interface ToolDiscoveryResult {
14
- /** Whether discovery was successful */
15
- success: boolean;
16
- /** Number of tools discovered */
17
- toolCount: number;
18
- /** Discovered tools */
19
- tools: ExternalMCPToolInfo[];
20
- /** Error message if failed */
21
- error?: string;
22
- /** Discovery duration in milliseconds */
23
- duration: number;
24
- /** Server ID */
25
- serverId: string;
26
- }
27
- /**
28
- * Tool execution options
29
- */
30
- export interface ToolExecutionOptions {
31
- /** Execution timeout in milliseconds */
32
- timeout?: number;
33
- /** Additional context for execution */
34
- context?: Partial<ExternalMCPToolContext>;
35
- /** Whether to validate input parameters */
36
- validateInput?: boolean;
37
- /** Whether to validate output */
38
- validateOutput?: boolean;
39
- }
40
- /**
41
- * Tool validation result
42
- */
43
- export interface ToolValidationResult {
44
- /** Whether the tool is valid */
45
- isValid: boolean;
46
- /** Validation errors */
47
- errors: string[];
48
- /** Validation warnings */
49
- warnings: string[];
50
- /** Tool metadata */
51
- metadata?: {
52
- category?: string;
53
- complexity?: "simple" | "moderate" | "complex";
54
- requiresAuth?: boolean;
55
- isDeprecated?: boolean;
56
- };
57
- }
58
- /**
59
- * Tool registry events
60
- */
61
- export interface ToolRegistryEvents {
62
- toolRegistered: {
63
- serverId: string;
64
- toolName: string;
65
- toolInfo: ExternalMCPToolInfo;
66
- timestamp: Date;
67
- };
68
- toolUnregistered: {
69
- serverId: string;
70
- toolName: string;
71
- timestamp: Date;
72
- };
73
- toolUpdated: {
74
- serverId: string;
75
- toolName: string;
76
- oldInfo: ExternalMCPToolInfo;
77
- newInfo: ExternalMCPToolInfo;
78
- timestamp: Date;
79
- };
80
- discoveryCompleted: {
81
- serverId: string;
82
- toolCount: number;
83
- duration: number;
84
- timestamp: Date;
85
- };
86
- discoveryFailed: {
87
- serverId: string;
88
- error: string;
89
- timestamp: Date;
90
- };
91
- }
92
11
  /**
93
12
  * ToolDiscoveryService
94
13
  * Handles automatic tool discovery and registration from external MCP servers
@@ -134,7 +53,7 @@ export declare class ToolDiscoveryService extends EventEmitter {
134
53
  /**
135
54
  * Execute a tool
136
55
  */
137
- executeTool(toolName: string, serverId: string, client: Client, parameters: JsonObject, options?: ToolExecutionOptions): Promise<ExternalMCPToolResult>;
56
+ executeTool(toolName: string, serverId: string, client: Client, parameters: JsonObject, options?: ExternalToolExecutionOptions): Promise<ExternalMCPToolResult>;
138
57
  /**
139
58
  * Validate tool parameters
140
59
  */
@@ -2,32 +2,10 @@
2
2
  * MCP Tool Registry - Extended Registry with Tool Management
3
3
  * Updated to match industry standard camelCase interfaces
4
4
  */
5
- import type { ExecutionContext, ToolInfo } from "./contracts/mcpContract.js";
6
- import type { ToolResult } from "./factory.js";
7
5
  import type { MCPServerInfo } from "../types/mcpTypes.js";
6
+ import type { ToolImplementation, ToolInfo, ExecutionContext } from "../types/tools.js";
8
7
  import { MCPRegistry } from "./registry.js";
9
8
  import type { HITLManager } from "../hitl/hitlManager.js";
10
- interface ToolImplementation {
11
- execute: (params: unknown, context?: ExecutionContext) => Promise<unknown> | unknown;
12
- description?: string;
13
- inputSchema?: unknown;
14
- outputSchema?: unknown;
15
- category?: string;
16
- permissions?: string[];
17
- }
18
- export type ToolExecutionResult = ToolResult;
19
- /**
20
- * Tool execution options
21
- */
22
- export interface ToolExecutionOptions {
23
- timeout?: number;
24
- retries?: number;
25
- context?: ExecutionContext;
26
- preferredSource?: string;
27
- fallbackEnabled?: boolean;
28
- validateBeforeExecution?: boolean;
29
- timeoutMs?: number;
30
- }
31
9
  export declare class MCPToolRegistry extends MCPRegistry {
32
10
  private tools;
33
11
  private toolImplementations;
@@ -163,4 +141,4 @@ export declare class MCPToolRegistry extends MCPRegistry {
163
141
  }
164
142
  export declare const toolRegistry: MCPToolRegistry;
165
143
  export declare const defaultToolRegistry: MCPToolRegistry;
166
- export type { ToolInfo } from "./contracts/mcpContract.js";
144
+ export type { ToolInfo } from "../types/tools.js";
@@ -1,20 +1,9 @@
1
- import type { LanguageModelV1 } from "ai";
2
1
  import type { NeuroLinkMiddleware } from "../../types/middlewareTypes.js";
2
+ import type { GuardrailsMiddlewareConfig } from "../../types/guardrails.js";
3
+ export type { GuardrailsMiddlewareConfig } from "../../types/guardrails.js";
3
4
  /**
4
- * Configuration for the Guardrails middleware.
5
- */
6
- export interface GuardrailsMiddlewareConfig {
7
- badWords?: {
8
- enabled?: boolean;
9
- list?: string[];
10
- };
11
- modelFilter?: {
12
- enabled?: boolean;
13
- filterModel?: LanguageModelV1;
14
- };
15
- }
16
- /**
17
- * Create Guardrails AI middleware for content filtering and policy enforcement.
18
- * @param config - Configuration for the guardrails middleware.
5
+ * Create Guardrails AI middleware for content filtering and policy enforcement
6
+ * @param config Configuration for the guardrails middleware
7
+ * @returns NeuroLink middleware instance
19
8
  */
20
9
  export declare function createGuardrailsMiddleware(config?: GuardrailsMiddlewareConfig): NeuroLinkMiddleware;
@@ -1,43 +1,48 @@
1
1
  import { generateText } from "ai";
2
+ import { createBlockedResponse, createBlockedStream, applyContentFiltering, handlePrecallGuardrails, } from "../utils/guardrailsUtils.js";
2
3
  import { logger } from "../../utils/logger.js";
3
4
  /**
4
- * Create Guardrails AI middleware for content filtering and policy enforcement.
5
- * @param config - Configuration for the guardrails middleware.
5
+ * Create Guardrails AI middleware for content filtering and policy enforcement
6
+ * @param config Configuration for the guardrails middleware
7
+ * @returns NeuroLink middleware instance
6
8
  */
7
9
  export function createGuardrailsMiddleware(config = {}) {
8
10
  const metadata = {
9
11
  id: "guardrails",
10
12
  name: "Guardrails AI",
11
- description: "Provides content filtering and policy enforcement using custom rules and AI models.",
13
+ description: "Provides comprehensive content filtering and policy enforcement using custom rules, AI models, and precall evaluation to filter inappropriate content before it reaches the LLM.",
12
14
  priority: 90,
13
15
  defaultEnabled: true,
14
16
  };
17
+ // WeakMap to store blocking state from transformParams to wrap methods
18
+ const blockingState = new WeakMap();
15
19
  const middleware = {
16
- wrapGenerate: async ({ doGenerate, params: _params }) => {
17
- logger.debug(`[GuardrailsMiddleware] Applying to generate call.`, {
18
- badWordsEnabled: !!config.badWords?.enabled,
19
- modelFilterEnabled: !!config.modelFilter?.enabled,
20
- });
20
+ transformParams: async ({ params }) => {
21
+ if (config.precallEvaluation?.enabled) {
22
+ const { shouldBlock, transformedParams } = await handlePrecallGuardrails(params, config.precallEvaluation);
23
+ // Store the blocking state for use in wrap methods
24
+ blockingState.set(transformedParams, shouldBlock);
25
+ return transformedParams;
26
+ }
27
+ return params;
28
+ },
29
+ wrapGenerate: async ({ doGenerate, params }) => {
30
+ logger.debug(`[GuardrailsMiddleware] Applying to generate call.`);
31
+ // Check if this request should be blocked (set by transformParams)
32
+ if (config.precallEvaluation?.enabled && blockingState.get(params)) {
33
+ return createBlockedResponse();
34
+ }
21
35
  let result = await doGenerate();
22
- // 1. Bad Word Filtering
23
- if (config.badWords?.enabled && config.badWords.list) {
24
- let filteredText = result.text;
25
- for (const term of config.badWords.list) {
26
- const regex = new RegExp(term, "gi");
27
- filteredText = filteredText?.replace(regex, "*".repeat(term.length));
28
- }
29
- if (result.text !== filteredText) {
30
- logger.debug(`[GuardrailsMiddleware] Redacted bad words from text.`);
31
- result = { ...result, text: filteredText ?? "" };
32
- }
36
+ const filterResult = applyContentFiltering(result.text || "", config.badWords, "generate");
37
+ if (filterResult.hasChanges) {
38
+ result = { ...result, text: filterResult.filteredText };
33
39
  }
34
- // 2. Model-based Filtering
35
40
  if (config.modelFilter?.enabled && config.modelFilter.filterModel) {
36
41
  logger.debug(`[GuardrailsMiddleware] Invoking model-based filter.`);
37
42
  try {
38
43
  const filterPrompt = `Is the following text safe? Respond with only "safe" or "unsafe".\n\nText: "${result.text}"`;
39
44
  const { text: filterResponse } = await generateText({
40
- model: config.modelFilter.filterModel, // Cast as any to satisfy type, will be resolved in integration
45
+ model: config.modelFilter.filterModel,
41
46
  prompt: filterPrompt,
42
47
  });
43
48
  if (filterResponse.toLowerCase().trim() === "unsafe") {
@@ -53,28 +58,28 @@ export function createGuardrailsMiddleware(config = {}) {
53
58
  }
54
59
  return result;
55
60
  },
56
- wrapStream: async ({ doStream, params: _params }) => {
57
- logger.debug(`[GuardrailsMiddleware] Applying to stream call.`, {
58
- badWordsEnabled: !!config.badWords?.enabled,
59
- });
60
- const { stream, ...rest } = await doStream();
61
- // Helper to escape regex special characters
62
- function escapeRegExp(string) {
63
- return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
61
+ wrapStream: async ({ doStream, params }) => {
62
+ logger.debug(`[GuardrailsMiddleware] Applying to stream call.`);
63
+ // Check if this request should be blocked (set by transformParams)
64
+ if (config.precallEvaluation?.enabled && blockingState.get(params)) {
65
+ return {
66
+ stream: createBlockedStream(),
67
+ rawCall: { rawPrompt: null, rawSettings: {} },
68
+ warnings: [],
69
+ };
64
70
  }
71
+ const { stream, ...rest } = await doStream();
65
72
  const transformStream = new TransformStream({
66
73
  transform(chunk, controller) {
67
74
  let filteredChunk = chunk;
68
- if (config.badWords?.enabled && config.badWords.list) {
69
- for (const term of config.badWords.list) {
70
- const regex = new RegExp(escapeRegExp(term), "gi");
71
- if (typeof filteredChunk === "object" &&
72
- "textDelta" in filteredChunk) {
73
- filteredChunk = {
74
- ...filteredChunk,
75
- textDelta: filteredChunk.textDelta.replace(regex, "*".repeat(term.length)),
76
- };
77
- }
75
+ if (typeof filteredChunk === "object" &&
76
+ "textDelta" in filteredChunk) {
77
+ const filterResult = applyContentFiltering(filteredChunk.textDelta, config.badWords, "stream");
78
+ if (filterResult.hasChanges) {
79
+ filteredChunk = {
80
+ ...filteredChunk,
81
+ textDelta: filterResult.filteredText,
82
+ };
78
83
  }
79
84
  }
80
85
  controller.enqueue(filteredChunk);