Spaces:
Paused
Download shared/README.md from VAH6002/ai_data_scientist: direct link, hf CLI and curl.
- Browser
- Download file 11.1 kB
-
https://huggingface.co/spaces/VAH6002/ai_data_scientist/resolve/main/shared/README.md
- Command line
-
hf download hf://spaces/VAH6002/ai_data_scientist/shared/README.md
-
curl -L -o README.md https://huggingface.co/spaces/VAH6002/ai_data_scientist/resolve/main/shared/README.md
A newer version of the Streamlit SDK is available: 1.68.0
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
- BaseMCPServer (
mcp_base.py) - Abstract base class for all MCP servers - SupabaseManager (
database.py) - Database connection and user isolation utilities - Data Models (
models.py) - Shared Pydantic models and validation schemas - 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
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
- Always accept UserContext: Every tool must accept
user_contextas the first parameter - Validate inputs: Use
self.validate_required_params()andself.sanitize_input() - Handle errors gracefully: Let the framework handle exceptions or raise specific error types
- Use database safely: The framework automatically sets user context for database operations
- Log important operations: Use
self.log_tool_execution()for monitoring
Example Tool Implementation
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
# 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 permissionsDatasetInfo- Dataset metadata and file informationAnalysisSession- Analysis session trackingHypothesis- Statistical hypothesis definitionsModelResults- Machine learning model resultsBusinessRecommendations- Business insights and actions
Usage Example
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 errorsUserIsolationError- User access or permission errorsMCPToolError- Tool execution errorsAuthenticationError- Authentication failures
Error Handling Best Practices
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:
# 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:
# 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
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:
# 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:
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
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
- Keep tools focused: Each tool should have a single, well-defined responsibility
- Validate all inputs: Always validate and sanitize user inputs
- Use type hints: Leverage Python type hints for better code quality
- Handle errors gracefully: Provide meaningful error messages to users
- Log important operations: Use structured logging for debugging and monitoring
- Test thoroughly: Write comprehensive tests for all tools and edge cases
- Document your tools: Provide clear descriptions and parameter documentation
- Follow naming conventions: Use consistent naming for tools and parameters
Troubleshooting
Common Issues
- Database connection errors: Check Supabase credentials and network connectivity
- User isolation failures: Ensure RLS policies are properly configured
- Tool registration errors: Verify tool function signatures and parameter schemas
- Import errors: Check Python path and module dependencies
Debug Mode
Enable debug logging for detailed information:
import logging
logging.basicConfig(level=logging.DEBUG)
Health Checks
Use health checks to diagnose server issues:
health = await server.health_check()
if not health.is_healthy:
print(f"Server unhealthy: {health.error_message}")
Contributing
When contributing to the framework:
- Follow the existing code style and patterns
- Add comprehensive tests for new functionality
- Update documentation for any API changes
- Ensure backward compatibility when possible
- 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.