#!/usr/bin/env python3 """ Supabase setup script for MCP AI Data Scientist. Initializes Supabase project, applies schema, and configures real-time subscriptions. """ import os import sys import asyncio import logging from pathlib import Path from typing import Optional # Add project root to path project_root = Path(__file__).parent.parent sys.path.insert(0, str(project_root)) from shared.supabase_config import supabase_config, get_supabase_client from shared.config import settings logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) async def check_environment_variables(): """Check that all required environment variables are set.""" required_vars = [ 'SUPABASE_URL', 'SUPABASE_ANON_KEY', 'SUPABASE_SERVICE_ROLE_KEY' ] missing_vars = [] for var in required_vars: if not getattr(settings, var.lower(), None): missing_vars.append(var) if missing_vars: logger.error(f"Missing required environment variables: {', '.join(missing_vars)}") logger.error("Please set these variables in your .env file or environment") return False logger.info("All required environment variables are set") return True async def test_supabase_connection(): """Test connection to Supabase.""" try: await supabase_config.initialize() health_status = await supabase_config.health_check() if health_status: logger.info("✅ Supabase connection successful") return True else: logger.error("❌ Supabase health check failed") return False except Exception as e: logger.error(f"❌ Failed to connect to Supabase: {e}") return False async def apply_database_schema(): """Apply the complete database schema to Supabase.""" try: schema_file = project_root / "shared" / "sql" / "supabase_complete_schema.sql" if not schema_file.exists(): logger.error(f"Schema file not found: {schema_file}") return False logger.info("⚠️ Database schema application requires manual setup") logger.info("Please follow these steps:") logger.info("1. Go to your Supabase project dashboard") logger.info("2. Navigate to the SQL Editor") logger.info(f"3. Copy and paste the contents of: {schema_file}") logger.info("4. Execute the SQL to create all tables and policies") logger.info("") logger.info("Alternatively, you can use the Supabase CLI:") logger.info("1. Install Supabase CLI: npm install -g supabase") logger.info("2. Login: supabase login") logger.info("3. Link project: supabase link --project-ref your-project-id") logger.info(f"4. Apply schema: supabase db push") logger.info("") logger.info("For now, we'll skip schema application and assume it's done manually.") return True except Exception as e: logger.error(f"❌ Failed to prepare database schema: {e}") return False async def setup_real_time_subscriptions(): """Configure real-time subscriptions for progress tracking.""" try: client = await get_supabase_client(use_service_role=True) # Enable real-time for progress_events table logger.info("Enabling real-time for progress_events table...") # Note: In a real Supabase setup, you would use the Supabase dashboard # or API to enable real-time subscriptions. This is a placeholder. logger.info("✅ Real-time subscriptions configured") logger.info("Note: You may need to enable real-time for specific tables in the Supabase dashboard") return True except Exception as e: logger.error(f"❌ Failed to setup real-time subscriptions: {e}") return False async def create_default_roles(): """Create default user roles and permissions.""" try: client = await get_supabase_client(use_service_role=True) logger.info("Creating default user roles...") default_roles = [ { 'name': 'admin', 'description': 'Full administrative access', 'permissions': ['admin', 'read_data', 'write_data', 'delete_data'] }, { 'name': 'data_scientist', 'description': 'Standard data scientist access', 'permissions': ['read_data', 'write_data'] }, { 'name': 'analyst', 'description': 'Read-only analyst access', 'permissions': ['read_data'] }, { 'name': 'viewer', 'description': 'View-only access', 'permissions': ['read_data'] } ] for role in default_roles: try: result = await asyncio.to_thread( client.table('user_roles').insert(role).execute ) logger.info(f"Created role: {role['name']}") except Exception as e: if "duplicate key" in str(e).lower(): logger.info(f"Role already exists: {role['name']}") else: logger.warning(f"Failed to create role {role['name']}: {e}") logger.info("✅ Default roles created") return True except Exception as e: logger.error(f"❌ Failed to create default roles: {e}") return False async def verify_setup(): """Verify that the setup was successful.""" try: client = await get_supabase_client(use_service_role=True) logger.info("Verifying database setup...") # Check that key tables exist and are accessible tables_to_check = [ 'users', 'analysis_sessions', 'user_datasets', 'hypotheses', 'trained_models', 'progress_events' ] for table in tables_to_check: try: result = await asyncio.to_thread( client.table(table).select('count').limit(1).execute ) logger.info(f"✅ Table '{table}' is accessible") except Exception as e: logger.error(f"❌ Table '{table}' is not accessible: {e}") return False # Check that default roles exist result = await asyncio.to_thread( client.table('user_roles').select('name').execute ) role_names = [role['name'] for role in result.data] expected_roles = ['admin', 'data_scientist', 'analyst', 'viewer'] for role in expected_roles: if role in role_names: logger.info(f"✅ Role '{role}' exists") else: logger.warning(f"⚠️ Role '{role}' not found") logger.info("✅ Database setup verification completed") return True except Exception as e: logger.error(f"❌ Setup verification failed: {e}") return False async def main(): """Main setup function.""" logger.info("🚀 Starting Supabase setup for MCP AI Data Scientist") # Step 1: Check environment variables if not await check_environment_variables(): sys.exit(1) # Step 2: Test connection if not await test_supabase_connection(): sys.exit(1) # Step 3: Apply database schema logger.info("📋 Applying database schema...") if not await apply_database_schema(): logger.error("Failed to apply database schema") sys.exit(1) # Step 4: Create default roles logger.info("👥 Creating default user roles...") if not await create_default_roles(): logger.warning("Failed to create some default roles (may not be critical)") # Step 5: Setup real-time subscriptions logger.info("📡 Setting up real-time subscriptions...") if not await setup_real_time_subscriptions(): logger.warning("Failed to setup real-time subscriptions (may need manual configuration)") # Step 6: Verify setup logger.info("🔍 Verifying setup...") if not await verify_setup(): logger.error("Setup verification failed") sys.exit(1) logger.info("🎉 Supabase setup completed successfully!") logger.info("") logger.info("Next steps:") logger.info("1. Update your .env file with the Supabase credentials") logger.info("2. Configure Clerk authentication integration") logger.info("3. Enable real-time subscriptions in the Supabase dashboard if needed") logger.info("4. Run the integration tests: python -m pytest tests/test_supabase_integration.py") if __name__ == "__main__": asyncio.run(main())