UNPKG

@juspay/neurolink

Version:

Universal AI Development Platform with working MCP integration, multi-provider support, and professional CLI. Built-in tools operational, 58+ external MCP servers discoverable. Connect to filesystem, GitHub, database operations, and more. Build, test, and

508 lines (507 loc) 18.9 kB
/** * NeuroLink - Unified AI Interface with Real MCP Tool Integration * * REDESIGNED FALLBACK CHAIN - NO CIRCULAR DEPENDENCIES * Enhanced AI provider system with natural MCP tool access. * Uses real MCP infrastructure for tool discovery and execution. */ import type { TextGenerationOptions, TextGenerationResult } from "./core/types.js"; import type { GenerateOptions, GenerateResult } from "./types/generateTypes.js"; import type { StreamOptions, StreamResult } from "./types/streamTypes.js"; import type { MCPServerInfo, MCPExecutableTool } from "./types/mcpTypes.js"; import type { JsonObject } from "./types/common.js"; import type { BatchOperationResult } from "./types/typeAliases.js"; import { EventEmitter } from "events"; import type { ConversationMemoryConfig } from "./types/conversationTypes.js"; import type { ExternalMCPServerInstance, ExternalMCPOperationResult, ExternalMCPToolInfo } from "./types/externalMcp.js"; export interface ProviderStatus { provider: string; status: "working" | "failed" | "not-configured"; configured: boolean; authenticated: boolean; error?: string; responseTime?: number; model?: string; } export interface MCPStatus { mcpInitialized: boolean; totalServers: number; availableServers: number; autoDiscoveredCount: number; totalTools: number; autoDiscoveredServers: MCPServerInfo[]; customToolsCount: number; inMemoryServersCount: number; externalMCPServersCount?: number; externalMCPConnectedCount?: number; externalMCPFailedCount?: number; externalMCPServers?: MCPServerInfo[]; error?: string; [key: string]: unknown; } import type { ContextManagerConfig } from "./context/types.js"; export declare class NeuroLink { private mcpInitialized; private emitter; private contextManager; private autoDiscoveredServerInfos; private externalServerManager; private toolCircuitBreakers; private toolExecutionMetrics; /** * Helper method to emit tool end event in a consistent way * Used by executeTool in both success and error paths * @param toolName - Name of the tool * @param startTime - Timestamp when tool execution started * @param success - Whether the tool execution was successful */ private emitToolEndEvent; private conversationMemory?; constructor(config?: { conversationMemory?: Partial<ConversationMemoryConfig>; }); /** * Initialize MCP registry with enhanced error handling and resource cleanup * Uses isolated async context to prevent hanging */ private initializeMCP; /** * MAIN ENTRY POINT: Enhanced generate method with new function signature * Replaces both generateText and legacy methods */ /** * Extracts the original prompt text from the provided input. * If a string is provided, it returns the string directly. * If a GenerateOptions object is provided, it returns the input text from the object. * @param optionsOrPrompt The prompt input, either as a string or a GenerateOptions object. * @returns The original prompt text as a string. */ private _extractOriginalPrompt; /** * Enables automatic context summarization for the NeuroLink instance. * Once enabled, the instance will maintain conversation history and * automatically summarize it when it exceeds token limits. * @param config Optional configuration to override default summarization settings. */ enableContextSummarization(config?: Partial<ContextManagerConfig>): void; generate(optionsOrPrompt: GenerateOptions | string): Promise<GenerateResult>; /** * BACKWARD COMPATIBILITY: Legacy generateText method * Internally calls generate() and converts result format */ generateText(options: TextGenerationOptions): Promise<TextGenerationResult>; /** * REDESIGNED INTERNAL GENERATION - NO CIRCULAR DEPENDENCIES * * This method implements a clean fallback chain: * 1. Initialize conversation memory if enabled * 2. Inject conversation history into prompt * 3. Try MCP-enhanced generation if available * 4. Fall back to direct provider generation * 5. Store conversation turn for future context */ private generateTextInternal; /** * Try MCP-enhanced generation (no fallback recursion) */ private tryMCPGeneration; /** * Direct provider generation (no MCP, no recursion) */ private directProviderGeneration; /** * Create tool-aware system prompt that informs AI about available tools */ private createToolAwareSystemPrompt; /** * Execute tools if available through centralized registry * Simplified approach without domain detection - relies on tool registry */ private detectAndExecuteTools; /** * Enhance prompt with tool results (domain-agnostic) */ private enhancePromptWithToolResults; /** * BACKWARD COMPATIBILITY: Legacy streamText method * Internally calls stream() and converts result format */ streamText(prompt: string, options?: Partial<StreamOptions>): Promise<AsyncIterable<string>>; /** * PRIMARY METHOD: Stream content using AI (recommended for new code) * Future-ready for multi-modal capabilities with current text focus */ stream(options: StreamOptions): Promise<StreamResult>; /** * Get the EventEmitter to listen to NeuroLink events * @returns EventEmitter instance */ getEventEmitter(): EventEmitter<[never]>; /** * Register a custom tool that will be available to all AI providers * @param name - Unique name for the tool * @param tool - Tool in MCPExecutableTool format (unified MCP protocol type) */ registerTool(name: string, tool: MCPExecutableTool): void; /** * Register multiple tools at once - Supports both object and array formats * @param tools - Object mapping tool names to MCPExecutableTool format OR Array of tools with names * * Object format (existing): { toolName: MCPExecutableTool, ... } * Array format (Lighthouse compatible): [{ name: string, tool: MCPExecutableTool }, ...] */ registerTools(tools: Record<string, MCPExecutableTool> | Array<{ name: string; tool: MCPExecutableTool; }>): void; /** * Unregister a custom tool * @param name - Name of the tool to remove * @returns true if the tool was removed, false if it didn't exist */ unregisterTool(name: string): boolean; /** * Get all registered custom tools * @returns Map of tool names to MCPExecutableTool format */ getCustomTools(): Map<string, MCPExecutableTool>; /** * Add an in-memory MCP server (from git diff) * Allows registration of pre-instantiated server objects * @param serverId - Unique identifier for the server * @param serverInfo - Server configuration */ addInMemoryMCPServer(serverId: string, serverInfo: MCPServerInfo): Promise<void>; /** * Get all registered in-memory servers * @returns Map of server IDs to MCPServerInfo */ getInMemoryServers(): Map<string, MCPServerInfo>; /** * Get in-memory servers as MCPServerInfo - ZERO conversion needed * Now fetches from centralized tool registry instead of local duplication * @returns Array of MCPServerInfo */ getInMemoryServerInfos(): MCPServerInfo[]; /** * Get auto-discovered servers as MCPServerInfo - ZERO conversion needed * @returns Array of MCPServerInfo */ getAutoDiscoveredServerInfos(): MCPServerInfo[]; /** * Execute a specific tool by name with robust error handling * Supports both custom tools and MCP server tools with timeout, retry, and circuit breaker patterns * @param toolName - Name of the tool to execute * @param params - Parameters to pass to the tool * @param options - Execution options * @returns Tool execution result */ executeTool<T = unknown>(toolName: string, params?: unknown, options?: { timeout?: number; maxRetries?: number; retryDelayMs?: number; }): Promise<T>; /** * Internal tool execution method (extracted for better error handling) */ private executeToolInternal; /** * Get all available tools including custom and in-memory ones * @returns Array of available tools with metadata */ getAllAvailableTools(): Promise<{ name: string; description: string; server: string; category?: string; inputSchema?: import("./types/typeAliases.js").StandardRecord; }[]>; /** * Get comprehensive status of all AI providers * Primary method for provider health checking and diagnostics */ getProviderStatus(options?: { quiet?: boolean; }): Promise<ProviderStatus[]>; /** * Test a specific AI provider's connectivity and authentication * @param providerName - Name of the provider to test * @returns Promise resolving to true if provider is working */ testProvider(providerName: string): Promise<boolean>; /** * Internal method to test provider connection with minimal generation call */ private testProviderConnection; /** * Get the best available AI provider based on configuration and availability * @param requestedProvider - Optional preferred provider name * @returns Promise resolving to the best provider name */ getBestProvider(requestedProvider?: string): Promise<string>; /** * Get list of all available AI provider names * @returns Array of supported provider names */ getAvailableProviders(): Promise<string[]>; /** * Validate if a provider name is supported * @param providerName - Provider name to validate * @returns True if provider name is valid */ isValidProvider(providerName: string): Promise<boolean>; /** * Get comprehensive MCP (Model Context Protocol) status information * @returns Promise resolving to MCP status details */ getMCPStatus(): Promise<MCPStatus>; /** * List all configured MCP servers with their status * @returns Promise resolving to array of MCP server information */ listMCPServers(): Promise<MCPServerInfo[]>; /** * Test connectivity to a specific MCP server * @param serverId - ID of the MCP server to test * @returns Promise resolving to true if server is reachable */ testMCPServer(serverId: string): Promise<boolean>; /** * Check if a provider has the required environment variables configured * @param providerName - Name of the provider to check * @returns Promise resolving to true if provider has required env vars */ hasProviderEnvVars(providerName: string): Promise<boolean>; /** * Perform comprehensive health check on a specific provider * @param providerName - Name of the provider to check * @param options - Health check options * @returns Promise resolving to detailed health status */ checkProviderHealth(providerName: string, options?: { timeout?: number; includeConnectivityTest?: boolean; includeModelValidation?: boolean; cacheResults?: boolean; }): Promise<{ provider: string; isHealthy: boolean; isConfigured: boolean; hasApiKey: boolean; lastChecked: Date; error?: string; warning?: string; responseTime?: number; configurationIssues: string[]; recommendations: string[]; }>; /** * Check health of all supported providers * @param options - Health check options * @returns Promise resolving to array of health statuses for all providers */ checkAllProvidersHealth(options?: { timeout?: number; includeConnectivityTest?: boolean; includeModelValidation?: boolean; cacheResults?: boolean; }): Promise<Array<{ provider: string; isHealthy: boolean; isConfigured: boolean; hasApiKey: boolean; lastChecked: Date; error?: string; warning?: string; responseTime?: number; configurationIssues: string[]; recommendations: string[]; }>>; /** * Get a summary of provider health across all supported providers * @returns Promise resolving to health summary statistics */ getProviderHealthSummary(): Promise<{ total: number; healthy: number; configured: number; hasIssues: number; healthyProviders: string[]; unhealthyProviders: string[]; recommendations: string[]; }>; /** * Clear provider health cache (useful for re-testing after configuration changes) * @param providerName - Optional specific provider to clear cache for */ clearProviderHealthCache(providerName?: string): Promise<void>; /** * Get execution metrics for all tools * @returns Object with execution metrics for each tool */ getToolExecutionMetrics(): Record<string, { totalExecutions: number; successfulExecutions: number; failedExecutions: number; successRate: number; averageExecutionTime: number; lastExecutionTime: number; }>; /** * Get circuit breaker status for all tools * @returns Object with circuit breaker status for each tool */ getToolCircuitBreakerStatus(): Record<string, { state: "closed" | "open" | "half-open"; failureCount: number; isHealthy: boolean; }>; /** * Reset circuit breaker for a specific tool * @param toolName - Name of the tool to reset circuit breaker for */ resetToolCircuitBreaker(toolName: string): void; /** * Clear all tool execution metrics */ clearToolExecutionMetrics(): void; /** * Get comprehensive tool health report * @returns Detailed health report for all tools */ getToolHealthReport(): Promise<{ totalTools: number; healthyTools: number; unhealthyTools: number; tools: Record<string, { name: string; isHealthy: boolean; metrics: { totalExecutions: number; successRate: number; averageExecutionTime: number; lastExecutionTime: number; }; circuitBreaker: { state: "closed" | "open" | "half-open"; failureCount: number; }; issues: string[]; recommendations: string[]; }>; }>; /** * Get conversation memory statistics (public API) */ getConversationStats(): Promise<import("./types/conversationTypes.js").ConversationMemoryStats>; /** * Clear conversation history for a specific session (public API) */ clearConversationSession(sessionId: string): Promise<boolean>; /** * Clear all conversation history (public API) */ clearAllConversations(): Promise<void>; /** * Add an external MCP server * Automatically discovers and registers tools from the server * @param serverId - Unique identifier for the server * @param config - External MCP server configuration * @returns Operation result with server instance */ addExternalMCPServer(serverId: string, config: MCPServerInfo): Promise<ExternalMCPOperationResult<ExternalMCPServerInstance>>; /** * Remove an external MCP server * Stops the server and removes all its tools * @param serverId - ID of the server to remove * @returns Operation result */ removeExternalMCPServer(serverId: string): Promise<ExternalMCPOperationResult<void>>; /** * List all external MCP servers * @returns Array of server health information */ listExternalMCPServers(): Array<{ serverId: string; status: string; toolCount: number; uptime: number; isHealthy: boolean; config: MCPServerInfo; }>; /** * Get external MCP server status * @param serverId - ID of the server * @returns Server instance or undefined if not found */ getExternalMCPServer(serverId: string): ExternalMCPServerInstance | undefined; /** * Execute a tool from an external MCP server * @param serverId - ID of the server * @param toolName - Name of the tool * @param parameters - Tool parameters * @param options - Execution options * @returns Tool execution result */ executeExternalMCPTool(serverId: string, toolName: string, parameters: JsonObject, options?: { timeout?: number; }): Promise<unknown>; /** * Get all tools from external MCP servers * @returns Array of external tool information */ getExternalMCPTools(): ExternalMCPToolInfo[]; /** * Get tools from a specific external MCP server * @param serverId - ID of the server * @returns Array of tool information for the server */ getExternalMCPServerTools(serverId: string): ExternalMCPToolInfo[]; /** * Test connection to an external MCP server * @param config - Server configuration to test * @returns Test result with connection status */ testExternalMCPConnection(config: MCPServerInfo): Promise<BatchOperationResult>; /** * Get external MCP server manager statistics * @returns Statistics about external servers and tools */ getExternalMCPStatistics(): { totalServers: number; connectedServers: number; failedServers: number; totalTools: number; totalConnections: number; totalErrors: number; }; /** * Shutdown all external MCP servers * Called automatically on process exit */ shutdownExternalMCPServers(): Promise<void>; /** * Convert external MCP tools to Vercel AI SDK tool format * This allows AI providers to use external tools directly */ private convertExternalMCPToolsToAISDKFormat; /** * Convert JSON Schema to AI SDK compatible format * For now, we'll skip schema validation and let the AI SDK handle parameters dynamically */ private convertJSONSchemaToAISDKFormat; /** * Unregister external MCP tools from a specific server */ private unregisterExternalMCPToolsFromRegistry; /** * Unregister a specific external MCP tool from the main registry */ private unregisterExternalMCPToolFromRegistry; /** * Unregister all external MCP tools from the main registry */ private unregisterAllExternalMCPToolsFromRegistry; } export declare const neurolink: NeuroLink; export default neurolink;