/** * MCP Server Registry and Tools Integration - Clean Implementation with Runtime AI SDK Patch * * Logger Categories: mcp.lifecycle, mcp.connection, mcp.tools, mcp.execution * Purpose: MCP server management and tool execution * * Enable with: * - LOG_MCP_LIFECYCLE=info - Server start/stop/ready events * - LOG_MCP_CONNECTION=debug - Connection establishment details * - LOG_MCP_TOOLS=debug - Tool discovery and caching * - LOG_MCP_EXECUTION=debug - Tool execution and results * - LOG_MCP=debug - Enable all MCP logs * * Recent Changes: * - 2026-03-17: Tightened remote MCP header validation so world config JSON accepts only string-to-string HTTP header maps. * - 2026-03-06: Removed `world.currentChatId` fallback from retry-status routing; MCP retry status emits only when `context.chatId` is explicit. * * What you'll see: * - Server lifecycle: start, stop, ready, shutdown * - Connection: transport creation, connection attempts * - Tools: discovery, caching, schema validation * - Execution: tool calls, results, performance metrics * * Comprehensive MCP (Model Context Protocol) management system providing: * - Server lifecycle management with reference counting and connection pooling * - Configuration-based server identification and sharing across worlds * - Flexible configuration: Supports both 'servers' and 'mcpServers' field names * - AI-compatible tool conversion with schema validation * - Transport support for stdio, SSE, and streamable HTTP connections * - Health monitoring, error handling, and graceful shutdown * - Thread-safe registry operations with world-server mapping * - Consolidated logging under LOG_LLM_MCP for unified debugging * - Enhanced debug logging for MCP communication data flows * * Key Features: * - Azure OpenAI compatibility: Uses runtime AI SDK patch (core/ai-sdk-patch.ts) for schema corruption fix * - Function names use underscores, clean schema structures for tool definitions * - Smart server sharing: Multiple worlds can share the same server configuration * - Automatic cleanup: Servers shut down when no longer referenced (30s delay) * - Error resilience: Comprehensive error handling with fallback mechanisms * - Schema validation: Creates well-formed, Azure-compatible schemas for all MCP tools * - Performance tracking: Tool execution duration and result analysis * - Sequence tracking: Tool call dependencies and execution relationships * - Data flow debugging: Complete request/response payload logging * * Connection Resilience & Lifecycle Management (November 2025): * - Automatic reconnection: Detects connection-level errors and attempts reconnection * - Retry strategy: Up to 2 attempts for transient network failures * - Connection error patterns: ECONNRESET, EPIPE, socket hang up, transport errors * - Race condition protection: Prevents concurrent reconnection attempts via reconnecting flag * - Client lifecycle management: ClientRef pattern for tracking active connections * - Proper resource cleanup: Ensures clients are closed on cache eviction and shutdown * - Memory leak prevention: Cache entries deleted even if disposal fails * - MCP error response detection: Handles both isError and type: 'error' formats * * Reconnection Logic: * - Triggered automatically on connection-level errors during tool execution * - First attempt: Try to reconnect and retry the operation * - Second attempt: Fail and propagate error if reconnection unsuccessful * - Concurrent calls: Wait for in-progress reconnection instead of creating new ones * - Cache refresh: Update cache timestamp after successful reconnection * - Logging: Detailed tracking of reconnection attempts and outcomes * * MCP Communication Debug Logging (LOG_LLM_MCP=debug): * - Server connection attempts with transport and configuration details * - Tool list requests and responses with full payload data * - Tool execution requests with complete argument structures * - Tool execution responses with full result content and metadata * - Request/response data size and structure analysis * - Raw JSON payloads for deep debugging of MCP communication * - Connection establishment and transport creation logging * - Server registration configuration details * - Reconnection attempts and retry logic execution * * MCP Tool Execution Logging (LOG_LLM_MCP=debug): * - Tool execution performance metrics with millisecond precision * - Tool result content analysis including size and type identification * - Tool call sequence tracking with unique sequence IDs * - Success/failure status with detailed error information * - Parent-child tool call relationship tracking * - Argument validation and presence checking * - Result preview for debugging without exposing full content * - Complete request/response payload logging for troubleshooting * - Retry attempt tracking with attempt number and max attempts * * Schema Approach: * - Uses simplified property types (string, number, boolean, array with string items) * - Includes additionalProperties: false to prevent schema expansion * - Maintains required fields but simplifies complex nested structures * - Works with runtime AI SDK patch to prevent schema corruption in Azure OpenAI calls * * LLM Argument Type Correction: * - Automatically fixes common LLM type errors in tool arguments * - String to array conversion: "value" -> ["value"] * - String to number conversion: "5" -> 5 * - Empty/invalid enum omission: "" -> (omitted, uses schema default) * - Case-insensitive enum matching: "RELEVANCE" -> "relevance" * - Null/undefined omission for optional params: null -> (omitted when not required) * - Applied transparently during tool execution to prevent MCP validation errors * - Logs all corrections for debugging and monitoring * - Schema preservation: bulletproofSchema preserves enum, items, min/max, required for validation * * Architecture: Function-based design with module-level state management * Consolidated from: mcp-server-registry.ts + mcp-tools.ts (August 2025) * Runtime patch integration: Works with ai-sdk-patch.ts for Azure compatibility (August 2025) * Enhanced debug logging: Complete MCP data flow visibility (August 2025) * Scenario-based logging: Split into lifecycle, connection, tools, execution (October 2025) * Lifecycle management: Connection resilience and automatic reconnection (November 2025) * Explicit execution safety system: Replaced heuristic detection with structured metadata (November 2025) * 2026-02-20: Added built-in `human_intervention_request` tool registration for generic human-in-the-loop prompts. * 2026-02-20: Added built-in `create_agent` tool registration for approval-gated agent creation. * 2026-02-14: Added built-in `load_skill` tool registration for progressive skill instruction loading. * 2026-02-19: Added built-in `create_agent` tool registration with approval-gated agent creation. * 2026-03-04: Added built-in `send_message` tool registration for context-injected batch message dispatch. * 2026-03-05: Hardened MCP tool discovery timeout handling with deterministic timeout errors and timer cleanup. * 2026-03-05: Added bounded MCP execution reconnect retry policy with chat-scoped per-second retry status emissions during retry windows. * 2026-03-05: Switched timeout/retry constants to shared reliability config. */ import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { type World } from './types.js'; /** * Sanitizes tool arguments by redacting sensitive information. * Protects passwords, keys, tokens, and other sensitive data. * * @param args - Tool arguments object * @returns Sanitized copy of arguments */ export declare function sanitizeArgs(args: any): any; type MCPServerDefinition = { command: string; args?: string[]; env?: Record; transport?: 'stdio'; } | { url: string; headers?: Record; transport: 'sse' | 'streamable-http' | 'http'; } | { type: 'http' | 'sse' | 'streamable-http'; url: string; headers?: Record; }; export type MCPConfig = { servers?: Record; mcpServers?: Record; }; export type MCPServerConfig = { name: string; transport: 'stdio' | 'sse' | 'streamable-http' | 'http'; command?: string; args?: string[]; env?: Record; url?: string; headers?: Record; }; type ClientRef = { current: Client | null; reconnecting: Promise | null; }; type ReconnectClient = (reason: string) => Promise; interface ToolExecutionContext { world?: World | null; worldId?: string; chatId?: string | null; agentId?: string; } export interface MCPServerInstance { id: string; config: MCPServerConfig; client: Client | null; status: 'starting' | 'running' | 'stopping' | 'error'; referenceCount: number; startedAt: Date; lastHealthCheck: Date; error?: Error; associatedWorlds: Set; } /** * Tool cache entry for registry-level caching * Caches tools at server level to avoid repeated fetching during ephemeral connections */ export interface ToolCacheEntry { tools: Record; cachedAt: Date; serverConfigHash: string; serverName: string; ttl?: number; clientRef: ClientRef; reconnectClient: ReconnectClient; serverConfig: MCPServerConfig; } export declare function validateToolSchema(schema: any): any; /** * Convert MCP config JSON format to normalized server configs * Supports both 'servers' and 'mcpServers' field names */ export declare function parseServersFromConfig(config: MCPConfig): MCPServerConfig[]; /** * Connect to an MCP server using the specified configuration */ export declare function connectMCPServer(serverConfig: MCPServerConfig): Promise; /** * Convert MCP tools to AI-compatible tool format with bulletproof schema protection */ export declare function mcpToolsToAiTools(clientRef: ClientRef, serverConfig: MCPServerConfig, reconnectClient: ReconnectClient): Promise>; /** * Initialize MCP registry - called on Express app startup */ export declare function initializeMCPRegistry(): void; /** * Register and start an MCP server with reference counting * Returns the server ID for tracking. Reuses existing servers when possible. */ export declare function registerMCPServer(config: MCPServerConfig, worldId: string): Promise; /** * Unregister MCP server for a world - decreases reference count * Schedules shutdown when no more references exist */ export declare function unregisterMCPServer(serverId: string, worldId: string): Promise; /** Get MCP server instance by ID */ export declare function getMCPServer(serverId: string): MCPServerInstance | null; /** List all MCP servers */ export declare function listMCPServers(): MCPServerInstance[]; /** Get server IDs for a specific world */ export declare function getMCPServersForWorld(worldId: string): string[]; /** Shutdown all MCP servers - called on Express app shutdown */ export declare function shutdownAllMCPServers(): Promise; /** Health check for MCP servers - can be called periodically */ export declare function performHealthCheck(): void; /** Get registry statistics */ export declare function getMCPRegistryStats(): { totalServers: number; runningServers: number; errorServers: number; totalWorlds: number; }; /** Validate MCP configuration format and content */ export declare function validateMCPConfig(config: any): config is MCPConfig; /** Parse MCP configuration string safely */ export declare function parseMCPConfig(configString: string): MCPConfig | null; /** Start MCP servers for a world based on its configuration */ export declare function startMCPServersForWorld(worldId: string, mcpConfig: string): Promise; /** Stop MCP servers for a world - decreases reference counts */ export declare function stopMCPServersForWorld(worldId: string): Promise; /** Update MCP servers for a world when configuration changes */ export declare function updateMCPServersForWorld(worldId: string, newMcpConfig: string): Promise; /** * Get MCP tools available for a world with on-demand server startup */ /** * Get MCP tools available for a world with registry-level caching * Uses cache-first strategy to avoid repeated tool fetching during ephemeral connections * Includes built-in tools (`shell_cmd`, `load_skill`, `create_agent`) in addition to MCP server tools */ export declare function getMCPToolsForWorld(worldId: string): Promise>; /** * Execute MCP tool by server ID and tool name * * @param serverId - Server ID from registry * @param toolName - Name of the tool to execute * @param args - Tool arguments (will be validated if schema provided) * @param sequenceId - Optional sequence ID for tracking * @param parentToolCall - Optional parent tool call ID * @param toolSchema - Optional tool input schema for parameter validation. * If provided, applies validateAndCorrectToolArgs to fix * common LLM parameter mistakes (string→array, string→number, * invalid enums, etc.) * * @example * // With validation (recommended for external callers) * const schema = { properties: { limit: { type: 'number' } }, required: [] }; * const result = await executeMCPTool(serverId, 'searchAgents', args, seq, parent, schema); * * // Without validation (legacy behavior) * const result = await executeMCPTool(serverId, 'searchAgents', args); */ export declare function executeMCPTool(serverId: string, toolName: string, args: any, sequenceId?: string, parentToolCall?: string, toolSchema?: any, executionContext?: ToolExecutionContext): Promise; /** * Restart MCP server by ID */ export declare function restartMCPServer(serverId: string): Promise; /** * Clear cached tools for specific server or all servers * Useful for forcing cache refresh when server tools change */ export declare function clearToolsCache(serverName?: string): Promise; /** * Get tools cache statistics for monitoring and debugging */ export declare function getToolsCacheStats(): { totalEntries: number; totalTools: number; cacheSize: number; oldestEntry?: { serverName: string; cachedAt: Date; }; newestEntry?: { serverName: string; cachedAt: Date; }; memoryUsage: { approximate: string; }; }; /** * Refresh cached tools for a specific server (force cache miss on next access) */ export declare function refreshServerToolsCache(serverName: string): Promise; /** Get MCP system health status */ export declare function getMCPSystemHealth(): { status: 'healthy' | 'degraded' | 'unhealthy'; details: { totalServers: number; healthyServers: number; unhealthyServers: number; errors: string[]; }; }; export {};