/** * NCP Orchestrator - Real MCP Connections * Based on commercial NCP implementation */ import ProfileManager from '../profiles/profile-manager.js'; import { ParameterInfo } from '../services/tool-schema-parser.js'; import { InternalMCPManager } from '../internal-mcps/internal-mcp-manager.js'; import type { ElicitationServer } from '../utils/elicitation-helper.js'; interface DiscoveryResult { toolName: string; mcpName: string; confidence: number; description?: string; schema?: any; } interface ExecutionResult { success: boolean; content?: any; error?: string; } export declare class NCPOrchestrator { private definitions; private connections; private toolToMCP; private allTools; private profileName; private readonly QUICK_PROBE_TIMEOUT; private readonly SLOW_PROBE_TIMEOUT; private readonly CONNECTION_TIMEOUT; private readonly IDLE_TIMEOUT; private readonly CLEANUP_INTERVAL; private readonly MAX_CONNECTIONS; private readonly MAX_EXECUTIONS_PER_CONNECTION; private cleanupTimer?; private discovery; private healthMonitor; private cachePatcher; private csvCache; private updateChecker; private showProgress; private indexingProgress; private indexingStartTime; private profileManager; private internalMCPManager; private backgroundInitPromise; private newlyIndexedMCPs; private cliScanner; private codeExecutor; private skillsManager; private skillPrompts; private fileWatcher; private forceRetry; private clientInfo; private toolDiscoveryService; private cacheService; private skillsService; private photonService; /** * ⚠️ CRITICAL: Default profile MUST be 'all' - DO NOT CHANGE! * * The 'all' profile is the universal profile that contains all MCPs. * This default is used by MCPServer and all CLI commands. * * DO NOT change this to 'default' or any other name - it will break everything. */ constructor(profileName?: string, showProgress?: boolean, forceRetry?: boolean); private loadProfile; /** * Create a minimal context for facade services * This provides read-only access to orchestrator state */ private createFacadeContext; /** * Get or create ToolDiscoveryService (lazy initialization) */ private getToolDiscoveryService; /** * Get or create CacheService (lazy initialization) */ private getCacheService; /** * Get or create SkillsService (lazy initialization) */ private getSkillsService; /** * Get or create PhotonService (lazy initialization) */ private getPhotonService; initialize(): Promise; /** * Run heavy initialization in background (non-blocking) */ private runBackgroundInitialization; /** * Set elicitation server for runtime network permissions * Creates adapter to convert ElicitationServer format to NetworkPolicy format * Called from MCPServer after construction to wire up elicitation support */ setElicitationServer(elicitationServer: ElicitationServer): void; /** * Conditionally trigger CLI auto-discovery * Enhances vector search by indexing available CLI tools when shell MCP is present * Enable with: export NCP_CLI_AUTOSCAN=true */ private maybeAutoScanCLITools; /** * Load and register agent skills from ~/.ncp/skills * * Skills are discoverable via find (like internal MCPs) with skill: prefix * Each skill is ONE discoverable entity with progressive disclosure via depth parameter */ private loadSkills; /** * Dynamically add a skill (for file watching) * Delegates to SkillsService for atomic operations */ addSkill(skillName: string, skillPath: string): Promise; /** * Dynamically remove a skill (for file watching) * Delegates to SkillsService for atomic operations */ removeSkill(skillName: string): Promise; /** * Dynamically update a skill (for file watching) * Delegates to SkillsService for atomic operations */ updateSkill(skillName: string, skillPath: string): Promise; /** * Dynamically add a photon (for file watching) * Delegates to PhotonService for atomic operations */ addPhoton(photonName: string, photonPath: string): Promise; /** * Dynamically remove a photon (for file watching) * Delegates to PhotonService for atomic operations */ removePhoton(photonName: string): Promise; /** * Dynamically update a photon (for file watching) * Delegates to PhotonService for atomic operations */ updatePhoton(photonName: string, photonPath: string): Promise; /** * Start FileWatcher for dynamic skill and photon discovery * Watches ~/.ncp/skills/ and ~/.ncp/photons/ directories for changes * Automatically loads/unloads skills and photons without requiring restart */ private startFileWatcher; /** * Stop FileWatcher for cleanup * Called during orchestrator shutdown to prevent resource leaks */ stopFileWatcher(): Promise; /** * Execute a skill with progressive disclosure * Skills return content based on depth parameter: * - depth=1: Metadata only * - depth=2: + Full SKILL.md content (default) * - depth=3: + File tree listing */ private executeSkill; /** * Get file tree for a skill directory */ private getSkillFileTree; /** * Recursively list directory contents for skills */ private listSkillDirectoryRecursive; /** * Run CLI scan in background to enhance vector search * Discovered tools are indexed as capabilities to help AI understand shell possibilities */ /** * Background CLI scan - Only scans and caches CLI tools * Enhancement happens dynamically during search (query-specific) */ private runBackgroundCliScan; /** * Get relevant CLI tools for a query (query-specific matching) * Returns CLI tool descriptions that match the query */ private getRelevantCLITools; /** * Load cached tools from CSV */ private loadFromCSVCache; private discoverMCPTools; /** * Create appropriate transport based on config * Supports both stdio (command/args) and HTTP/SSE (url) transports * Handles OAuth authentication for HTTP/SSE connections */ private createTransport; /** * Get authentication token for MCP * Handles OAuth Device Flow and token refresh */ private getAuthToken; private probeMCPTools; find(query: string, limit?: number, detailed?: boolean, confidenceThreshold?: number): Promise; run(toolName: string, parameters: any, meta?: Record): Promise; private getOrCreateConnection; /** * New optimized cache loading with profile hash validation * This is the key optimization - skips re-indexing when profile hasn't changed */ private loadFromOptimizedCache; /** * Legacy cache loading (kept for fallback) */ private loadFromCache; private saveToCache; /** * New optimized cache saving with profile hash and structured format */ private saveToOptimizedCache; private getToolSchema; /** * Get tool schema by tool identifier (e.g., "mcp:tool") */ getToolSchemaByIdentifier(toolIdentifier: string): any; /** * Check if a tool requires parameters */ toolRequiresParameters(toolIdentifier: string): boolean; /** * Get tool parameters for interactive prompting */ getToolParameters(toolIdentifier: string): ParameterInfo[]; /** * Validate tool parameters before execution */ private validateToolParameters; /** * Get tool context for parameter prediction */ getToolContext(toolIdentifier: string): string; /** * Find similar tool names using fuzzy matching */ private findSimilarTools; /** * Generate hash for each MCP configuration */ private generateConfigHashes; /** * Get current indexing progress */ getIndexingProgress(): { current: number; total: number; currentMCP: string; estimatedTimeRemaining?: number; } | null; /** * Wait for background initialization to complete * This is useful for operations that need all MCPs to be indexed before proceeding */ waitForInitialization(): Promise; /** * Get MCP health status summary */ getMCPHealthStatus(): { total: number; healthy: number; unhealthy: number; mcps: Array<{ name: string; healthy: boolean; }>; }; /** * Enhance generic error messages with better context */ private enhanceErrorMessage; /** * Get all resources from active MCPs */ getAllResources(): Promise>; /** * Get all prompts from active MCPs */ getAllPrompts(): Promise>; /** * Get resources from a specific MCP */ private getResourcesFromMCP; /** * Get prompts from a specific MCP */ private getPromptsFromMCP; /** * Get a specific prompt from an MCP and execute it * Used when client requests a prefixed prompt like "github:pr-template" */ getPromptFromMCP(mcpName: string, promptName: string, args: Record): Promise; /** * Evict least recently used connection when pool is full * Implements LRU (Least Recently Used) eviction policy */ private evictLRUConnection; /** * Clean up idle connections and enforce pool health */ private cleanupIdleConnections; /** * Disconnect a specific MCP */ private disconnectMCP; cleanup(): Promise; /** * Get server descriptions for all configured MCPs */ getServerDescriptions(): Record; /** * Apply universal term frequency scoring boost with action word weighting * Uses SearchEnhancer for clean, extensible term classification and semantic mapping */ private adjustScoresUniversally; /** * Trigger auto-import from MCP client * Called by MCPServer after it receives clientInfo from initialize request * Re-indexes any new MCPs that were added by auto-import */ triggerAutoImport(clientName: string, elicitationServer?: any, notificationManager?: any): Promise; /** * Add internal MCPs to tool discovery * Called after external MCPs are indexed */ private addInternalMCPsToDiscovery; /** * Get the ProfileManager instance * Used by MCP server for management operations (add/remove MCPs) */ getProfileManager(): ProfileManager | null; /** * Get the InternalMCPManager instance * Used by MCP server to wire up elicitation for credential collection */ getInternalMCPManager(): InternalMCPManager; /** * Get the profile name * Used by MCP server for resource generation */ getProfileName(): string; /** * Read a resource from an MCP by URI * Used by MCP server to handle resources/read requests */ readResource(uri: string): Promise; /** * Get auto-import summary * Returns summary of last auto-import operation (if any) */ getAutoImportSummary(): { count: number; source?: string; profile?: string; timestamp?: string; mcps?: Array<{ name: string; transport: string; }>; skipped?: number; } | null; /** * Set actual client information for transparent passthrough to downstream MCPs * Called by MCPServer after receiving clientInfo from initialize request */ setClientInfo(clientInfo: { name: string; version: string; }): void; /** * Execute TypeScript code with access to all MCPs and Photons as namespaces * Implements UTCP Code-Mode for 60% faster execution, 68% fewer tokens */ executeCode(code: string, timeout?: number): Promise<{ result: any; logs: string[]; error?: string; runId?: string; }>; /** * Hash a string for change detection */ private hashString; /** * Get names of all connected/configured MCP servers * Used by MCPClientFactory to list available servers */ getConnectionNames(): string[]; /** * Check if an MCP server is connected/available * Used by MCPClient to verify connectivity before calls */ isConnected(mcpName: string): boolean; /** * Get tools for a specific MCP server * Used by MCPClient.list() to discover available tools */ getToolsForMCP(mcpName: string): Array<{ name: string; description?: string; inputSchema?: any; }>; } export default NCPOrchestrator; //# sourceMappingURL=ncp-orchestrator.d.ts.map