""" Integration Coordinator for MCP AI Data Scientist Manages the integration between all system components and provides centralized coordination. """ import asyncio import logging from typing import Dict, Any, Optional, List from datetime import datetime, timezone from contextlib import asynccontextmanager from .config import settings from .monitoring import monitoring_system, get_logger, record_metric, time_operation from .error_handling import error_handler, ErrorContext, ApplicationError, ErrorCategory from .database import get_database_connection, test_database_connection class IntegrationCoordinator: """Coordinates integration between all system components.""" def __init__(self): self.logger = get_logger("integration_coordinator") self.components_status = {} self.initialization_complete = False async def initialize_system(self) -> bool: """Initialize all system components in the correct order.""" self.logger.info("๐Ÿš€ Starting system initialization...") try: # Step 1: Initialize monitoring system await self._initialize_monitoring() # Step 2: Test database connectivity await self._initialize_database() # Step 3: Initialize error handling await self._initialize_error_handling() # Step 4: Verify MCP server configurations await self._verify_mcp_configurations() # Step 5: Initialize orchestrator components await self._initialize_orchestrator_components() # Step 6: Initialize Streamlit components await self._verify_streamlit_components() # Step 7: Run integration tests await self._run_integration_tests() self.initialization_complete = True self.logger.info("โœ… System initialization completed successfully") # Record successful initialization record_metric("system.initialization_success", 1) return True except Exception as e: self.logger.error(f"โŒ System initialization failed: {e}") # Record failed initialization record_metric("system.initialization_failure", 1) # Handle initialization error await error_handler.handle_error( e, ErrorContext( component="integration_coordinator", operation="initialize_system" ) ) return False async def _initialize_monitoring(self): """Initialize monitoring system.""" self.logger.info("๐Ÿ“Š Initializing monitoring system...") try: await monitoring_system.start_monitoring() self.components_status["monitoring"] = "initialized" self.logger.info("โœ… Monitoring system initialized") except Exception as e: self.components_status["monitoring"] = f"failed: {str(e)}" raise ApplicationError( f"Failed to initialize monitoring system: {e}", category=ErrorCategory.SYSTEM ) async def _initialize_database(self): """Initialize and test database connectivity.""" self.logger.info("๐Ÿ—„๏ธ Testing database connectivity...") try: # Test database connection connection_ok = await test_database_connection() if not connection_ok: raise ApplicationError( "Database connection test failed", category=ErrorCategory.DATABASE ) # Verify required tables exist await self._verify_database_schema() self.components_status["database"] = "initialized" self.logger.info("โœ… Database connectivity verified") except Exception as e: self.components_status["database"] = f"failed: {str(e)}" raise ApplicationError( f"Database initialization failed: {e}", category=ErrorCategory.DATABASE ) async def _verify_database_schema(self): """Verify that all required database tables exist.""" required_tables = [ 'users', 'analysis_sessions', 'user_datasets', 'hypotheses', 'trained_models', 'preprocessing_operations', 'feature_engineering_results', 'business_recommendations' ] async with get_database_connection() as conn: existing_tables = [] for table in required_tables: exists = await conn.fetchval( "SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_name = $1)", table ) if exists: existing_tables.append(table) missing_tables = set(required_tables) - set(existing_tables) if missing_tables: self.logger.warning(f"Missing database tables: {missing_tables}") # Don't fail initialization for missing tables - they might be created later self.logger.info(f"Database schema check: {len(existing_tables)}/{len(required_tables)} tables found") async def _initialize_error_handling(self): """Initialize error handling system.""" self.logger.info("โš ๏ธ Initializing error handling...") try: # Register recovery handlers self._register_recovery_handlers() self.components_status["error_handling"] = "initialized" self.logger.info("โœ… Error handling initialized") except Exception as e: self.components_status["error_handling"] = f"failed: {str(e)}" raise ApplicationError( f"Error handling initialization failed: {e}", category=ErrorCategory.SYSTEM ) def _register_recovery_handlers(self): """Register error recovery handlers.""" from .error_handling import register_recovery_handler, ErrorCategory async def database_recovery_handler(error_info): """Recovery handler for database errors.""" self.logger.info(f"Attempting database recovery for error {error_info.error_id}") # Implement database reconnection logic here async def mcp_server_recovery_handler(error_info): """Recovery handler for MCP server errors.""" self.logger.info(f"Attempting MCP server recovery for error {error_info.error_id}") # Implement MCP server reconnection logic here # Register handlers register_recovery_handler(ErrorCategory.DATABASE, database_recovery_handler) register_recovery_handler(ErrorCategory.MCP_SERVER, mcp_server_recovery_handler) async def _verify_mcp_configurations(self): """Verify MCP server configurations.""" self.logger.info("๐Ÿ”Œ Verifying MCP server configurations...") try: required_servers = [ 'data_cleaning', 'hypothesis_testing', 'preprocessing', 'feature_engineering', 'model_training', 'action_generation' ] configured_servers = list(settings.mcp_servers.keys()) missing_servers = set(required_servers) - set(configured_servers) if missing_servers: raise ApplicationError( f"Missing MCP server configurations: {missing_servers}", category=ErrorCategory.MCP_SERVER ) # Validate each server configuration for server_name, config in settings.mcp_servers.items(): required_keys = ['host', 'port'] missing_keys = [key for key in required_keys if key not in config] if missing_keys: raise ApplicationError( f"MCP server {server_name} missing configuration: {missing_keys}", category=ErrorCategory.MCP_SERVER ) self.components_status["mcp_servers"] = "configured" self.logger.info(f"โœ… MCP server configurations verified: {len(configured_servers)} servers") except Exception as e: self.components_status["mcp_servers"] = f"failed: {str(e)}" raise ApplicationError( f"MCP server configuration verification failed: {e}", category=ErrorCategory.MCP_SERVER ) async def _initialize_orchestrator_components(self): """Initialize orchestrator components.""" self.logger.info("๐ŸŽผ Initializing orchestrator components...") try: # Import orchestrator components from orchestrator.mcp_client_manager import MCPClientManager from orchestrator.sse_manager import SSEManager from orchestrator.session_manager_simple import SessionManager from orchestrator.health_monitor import HealthMonitor from orchestrator.analysis_orchestrator import AnalysisOrchestrator # Test component initialization mcp_client = MCPClientManager() sse_manager = SSEManager() session_manager = SessionManager() health_monitor = HealthMonitor(mcp_client) orchestrator = AnalysisOrchestrator(mcp_client, sse_manager, session_manager) # Verify components have required methods required_methods = { 'mcp_client': ['call_tool', 'get_server_health'], 'sse_manager': ['broadcast_to_user', 'create_event_stream'], 'session_manager': ['create_session', 'get_session'], 'orchestrator': ['start_analysis', 'get_analysis_results'] } components = { 'mcp_client': mcp_client, 'sse_manager': sse_manager, 'session_manager': session_manager, 'orchestrator': orchestrator } for component_name, methods in required_methods.items(): component = components[component_name] missing_methods = [ method for method in methods if not hasattr(component, method) ] if missing_methods: raise ApplicationError( f"Orchestrator component {component_name} missing methods: {missing_methods}", category=ErrorCategory.SYSTEM ) self.components_status["orchestrator"] = "initialized" self.logger.info("โœ… Orchestrator components initialized") except Exception as e: self.components_status["orchestrator"] = f"failed: {str(e)}" raise ApplicationError( f"Orchestrator initialization failed: {e}", category=ErrorCategory.SYSTEM ) async def _verify_streamlit_components(self): """Verify Streamlit components.""" self.logger.info("๐ŸŽจ Verifying Streamlit components...") try: # Test component imports components_to_test = [ ('streamlit_app.components.auth', 'AuthManager'), ('streamlit_app.components.file_upload', 'FileUploadComponent'), ('streamlit_app.components.business_context', 'BusinessContextForm'), ('streamlit_app.components.progress_monitor', 'ProgressMonitor'), ('streamlit_app.components.results_viewer', 'ResultsViewer'), ('streamlit_app.utils.api_client', 'APIClient'), ('streamlit_app.utils.sse_client', 'SSEClient') ] import_failures = [] for module_name, class_name in components_to_test: try: module = __import__(module_name, fromlist=[class_name]) component_class = getattr(module, class_name) except Exception as e: import_failures.append(f"{module_name}.{class_name}: {str(e)}") if import_failures: self.logger.warning(f"Streamlit component import issues: {import_failures}") # Don't fail initialization for Streamlit issues in non-UI contexts self.components_status["streamlit"] = "verified" self.logger.info("โœ… Streamlit components verified") except Exception as e: self.components_status["streamlit"] = f"failed: {str(e)}" # Don't fail system initialization for Streamlit issues self.logger.warning(f"Streamlit verification failed: {e}") async def _run_integration_tests(self): """Run basic integration tests.""" self.logger.info("๐Ÿงช Running integration tests...") try: # Test 1: Database CRUD operations await self._test_database_operations() # Test 2: Error handling system await self._test_error_handling() # Test 3: Monitoring system await self._test_monitoring_system() self.components_status["integration_tests"] = "passed" self.logger.info("โœ… Integration tests passed") except Exception as e: self.components_status["integration_tests"] = f"failed: {str(e)}" raise ApplicationError( f"Integration tests failed: {e}", category=ErrorCategory.SYSTEM ) async def _test_database_operations(self): """Test basic database operations.""" test_user_id = f"test_integration_{int(datetime.now().timestamp())}" async with get_database_connection() as conn: # Test insert await conn.execute( "INSERT INTO users (clerk_user_id, email) VALUES ($1, $2) ON CONFLICT DO NOTHING", test_user_id, f"{test_user_id}@test.com" ) # Test select user_record = await conn.fetchrow( "SELECT * FROM users WHERE clerk_user_id = $1", test_user_id ) if not user_record: raise Exception("Database CRUD test failed: record not found") # Test cleanup await conn.execute( "DELETE FROM users WHERE clerk_user_id = $1", test_user_id ) self.logger.info("โœ… Database operations test passed") async def _test_error_handling(self): """Test error handling system.""" try: # Generate a test error test_error = ValueError("Integration test error") # Handle the error error_info = await error_handler.handle_error( test_error, ErrorContext( component="integration_test", operation="test_error_handling" ), attempt_recovery=False ) # Verify error was handled if not error_info or not error_info.error_id: raise Exception("Error handling test failed: no error info returned") except Exception as e: if "Integration test error" not in str(e): raise Exception(f"Error handling test failed: {e}") self.logger.info("โœ… Error handling test passed") async def _test_monitoring_system(self): """Test monitoring system.""" # Test metric recording record_metric("integration_test.metric", 1.0, tags={"test": "true"}) # Test timing operation async with time_operation("integration_test"): await asyncio.sleep(0.01) # Small delay # Verify metrics were recorded latest_values = monitoring_system.metrics_collector.get_latest_values() if "integration_test.metric" not in latest_values: raise Exception("Monitoring test failed: metric not recorded") self.logger.info("โœ… Monitoring system test passed") async def shutdown_system(self): """Gracefully shutdown all system components.""" self.logger.info("๐Ÿ›‘ Starting system shutdown...") try: # Stop monitoring system await monitoring_system.stop_monitoring() self.logger.info("โœ… System shutdown completed") except Exception as e: self.logger.error(f"Error during system shutdown: {e}") def get_system_status(self) -> Dict[str, Any]: """Get comprehensive system status.""" return { "initialization_complete": self.initialization_complete, "components_status": self.components_status, "timestamp": datetime.now(timezone.utc).isoformat(), "monitoring_active": monitoring_system.monitoring_active } @asynccontextmanager async def system_context(self): """Context manager for system lifecycle.""" try: # Initialize system success = await self.initialize_system() if not success: raise ApplicationError("System initialization failed") yield self finally: # Shutdown system await self.shutdown_system() # Global integration coordinator instance integration_coordinator = IntegrationCoordinator()