# MCP AI Data Scientist Framework This directory contains the core framework for building MCP (Model Context Protocol) servers for the AI Data Scientist system. The framework provides a robust foundation for creating specialized AI agents that handle different aspects of the data science pipeline. ## Architecture Overview The framework consists of several key components: ### Core Components 1. **BaseMCPServer** (`mcp_base.py`) - Abstract base class for all MCP servers 2. **SupabaseManager** (`database.py`) - Database connection and user isolation utilities 3. **Data Models** (`models.py`) - Shared Pydantic models and validation schemas 4. **Configuration** (`config.py`) - Centralized configuration management ### Key Features - **User Isolation**: Row-level security ensures users can only access their own data - **Tool Registration**: Simple decorator-based tool registration system - **Error Handling**: Comprehensive error handling with proper exception types - **Health Monitoring**: Built-in health checks and monitoring capabilities - **Database Integration**: Seamless Supabase integration with async operations - **Validation**: Input validation and sanitization for all tool parameters - **Logging**: Structured logging for debugging and monitoring ## Quick Start ### Creating a New MCP Server ```python from shared.mcp_base import BaseMCPServer from shared.models import UserContext from typing import Any, Dict class MyMCPServer(BaseMCPServer): def __init__(self): super().__init__("my_server", 3008) async def register_server_tools(self): async def my_tool(user_context: UserContext, arguments: Dict[str, Any]): # Your tool implementation here return {"result": "success"} self.register_tool( name="my_tool", description="Description of what this tool does", parameters={ "param1": { "type": "string", "description": "Parameter description" } }, func=my_tool ) # Run the server import asyncio server = MyMCPServer() asyncio.run(server.start_server()) ``` ### Tool Implementation Guidelines 1. **Always accept UserContext**: Every tool must accept `user_context` as the first parameter 2. **Validate inputs**: Use `self.validate_required_params()` and `self.sanitize_input()` 3. **Handle errors gracefully**: Let the framework handle exceptions or raise specific error types 4. **Use database safely**: The framework automatically sets user context for database operations 5. **Log important operations**: Use `self.log_tool_execution()` for monitoring ### Example Tool Implementation ```python async def process_data_tool(user_context: UserContext, arguments: Dict[str, Any]): # Validate required parameters self.validate_required_params(arguments, ["dataset_id", "operation"]) # Sanitize inputs dataset_id = self.sanitize_input(arguments["dataset_id"], "string") operation = self.sanitize_input(arguments["operation"], "string") # Get dataset from database (user isolation is automatic) dataset = await self.db.get_dataset(user_context, dataset_id) if not dataset: raise ValueError(f"Dataset not found: {dataset_id}") # Process the data result = perform_operation(dataset, operation) # Store results result_id = await self.db.store_result(user_context, { "dataset_id": dataset_id, "operation": operation, "result": result }) return { "dataset_id": dataset_id, "operation": operation, "result_id": result_id, "summary": result } ``` ## Database Operations The framework provides a `SupabaseManager` that handles all database operations with automatic user isolation: ### Common Database Operations ```python # Create analysis session session_id = await self.db.create_analysis_session(user_context, { "name": "My Analysis", "business_context": "Customer segmentation" }) # Update session status await self.db.update_analysis_session(user_context, session_id, { "status": "completed" }) # Store dataset dataset_id = await self.db.create_dataset(user_context, dataset_info) # Store hypothesis hypothesis_id = await self.db.store_hypothesis(user_context, hypothesis_data) # Store model results model_id = await self.db.store_model_result(user_context, model_data) ``` ### User Isolation All database operations automatically enforce user isolation through: - Row-level security policies in Supabase - Automatic user context setting before operations - User ID validation in all queries ## Data Models The framework provides comprehensive Pydantic models for type safety and validation: ### Core Models - `UserContext` - User authentication and permissions - `DatasetInfo` - Dataset metadata and file information - `AnalysisSession` - Analysis session tracking - `Hypothesis` - Statistical hypothesis definitions - `ModelResults` - Machine learning model results - `BusinessRecommendations` - Business insights and actions ### Usage Example ```python from shared.models import DatasetInfo, Hypothesis, TestType # Create dataset info dataset = DatasetInfo( user_id=user_context.user_id, name="customer_data.csv", file_path="/uploads/customer_data.csv", metadata={"rows": 10000, "columns": 15} ) # Create hypothesis hypothesis = Hypothesis( text="Customer age affects purchase behavior", test_type=TestType.CORRELATION, variables=["age", "purchase_amount"], expected_outcome="Positive correlation", business_relevance="High", dataset_id=dataset.id ) ``` ## Error Handling The framework provides several exception types for different error scenarios: - `DatabaseError` - Database connection or query errors - `UserIsolationError` - User access or permission errors - `MCPToolError` - Tool execution errors - `AuthenticationError` - Authentication failures ### Error Handling Best Practices ```python async def my_tool(user_context: UserContext, arguments: Dict[str, Any]): try: # Tool implementation result = process_data(arguments) return result except ValueError as e: # Let the framework handle validation errors raise MCPToolError(f"Invalid input: {e}") except Exception as e: # Framework will catch and handle unexpected errors raise ``` ## Health Monitoring Each MCP server provides health monitoring capabilities: ```python # Check server health health = await server.health_check() print(f"Server {health.server_name} is {'healthy' if health.is_healthy else 'unhealthy'}") print(f"Response time: {health.response_time_ms}ms") # Get server information info = server.get_server_info() print(f"Server has {info['tools_count']} tools registered") ``` ## Testing The framework includes comprehensive test suites: ```bash # Run all tests python -m pytest tests/ -v # Run specific test files python -m pytest tests/test_models.py -v python -m pytest tests/test_mcp_base.py -v python -m pytest tests/test_database.py -v ``` ### Writing Tests for Your MCP Server ```python import pytest from unittest.mock import AsyncMock from your_server import YourMCPServer from shared.models import UserContext @pytest.fixture def server(): return YourMCPServer() @pytest.fixture def user_context(): return UserContext(user_id="test_user", email="test@example.com") @pytest.mark.asyncio async def test_your_tool(server, user_context): # Mock database server.db = AsyncMock() # Test tool execution result = await server._execute_tool_safely( server.tools["your_tool"], user_context, {"param1": "test_value"} ) assert result.success is True assert result.data["expected_field"] == "expected_value" ``` ## Configuration The framework uses environment variables for configuration. Create a `.env` file: ```env # Supabase Configuration SUPABASE_URL=your_supabase_url SUPABASE_ANON_KEY=your_anon_key SUPABASE_SERVICE_ROLE_KEY=your_service_role_key # MCP Server Ports DATA_CLEANING_MCP_PORT=3001 HYPOTHESIS_TESTING_MCP_PORT=3002 PREPROCESSING_MCP_PORT=3003 FEATURE_ENGINEERING_MCP_PORT=3004 MODEL_TRAINING_MCP_PORT=3005 ACTION_GENERATION_MCP_PORT=3006 # Logging LOG_LEVEL=INFO LOG_FILE=./logs/mcp_servers.log ``` ## Deployment ### Docker Deployment Each MCP server can be containerized: ```dockerfile FROM python:3.11-slim WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt COPY shared/ ./shared/ COPY your_server.py . CMD ["python", "your_server.py"] ``` ### Docker Compose ```yaml version: '3.8' services: your-mcp-server: build: . ports: - "3008:3008" environment: - SUPABASE_URL=${SUPABASE_URL} - SUPABASE_ANON_KEY=${SUPABASE_ANON_KEY} depends_on: - postgres ``` ## Best Practices 1. **Keep tools focused**: Each tool should have a single, well-defined responsibility 2. **Validate all inputs**: Always validate and sanitize user inputs 3. **Use type hints**: Leverage Python type hints for better code quality 4. **Handle errors gracefully**: Provide meaningful error messages to users 5. **Log important operations**: Use structured logging for debugging and monitoring 6. **Test thoroughly**: Write comprehensive tests for all tools and edge cases 7. **Document your tools**: Provide clear descriptions and parameter documentation 8. **Follow naming conventions**: Use consistent naming for tools and parameters ## Troubleshooting ### Common Issues 1. **Database connection errors**: Check Supabase credentials and network connectivity 2. **User isolation failures**: Ensure RLS policies are properly configured 3. **Tool registration errors**: Verify tool function signatures and parameter schemas 4. **Import errors**: Check Python path and module dependencies ### Debug Mode Enable debug logging for detailed information: ```python import logging logging.basicConfig(level=logging.DEBUG) ``` ### Health Checks Use health checks to diagnose server issues: ```python health = await server.health_check() if not health.is_healthy: print(f"Server unhealthy: {health.error_message}") ``` ## Contributing When contributing to the framework: 1. Follow the existing code style and patterns 2. Add comprehensive tests for new functionality 3. Update documentation for any API changes 4. Ensure backward compatibility when possible 5. Use type hints and docstrings for all public methods ## License This framework is part of the MCP AI Data Scientist system and follows the same licensing terms.