Spaces:
Paused
Paused
Download shared/mcp_base.py from VAH6002/ai_data_scientist: direct link, hf CLI and curl.
- Browser
- Download file 20.2 kB
-
https://huggingface.co/spaces/VAH6002/ai_data_scientist/resolve/main/shared/mcp_base.py
- Command line
-
hf download hf://spaces/VAH6002/ai_data_scientist/shared/mcp_base.py
-
curl -L -o mcp_base.py https://huggingface.co/spaces/VAH6002/ai_data_scientist/resolve/main/shared/mcp_base.py
20.2 kB
| """ | |
| Base MCP server class with common functionality. | |
| Provides MCP protocol handlers, tool registration, and shared utilities. | |
| """ | |
| import asyncio | |
| import logging | |
| import time | |
| from abc import ABC, abstractmethod | |
| from typing import Any, Callable, Dict, List, Optional, Union | |
| from uuid import uuid4 | |
| from datetime import datetime | |
| from mcp.server import Server | |
| from mcp.server.models import InitializationOptions | |
| from mcp.server.stdio import stdio_server | |
| from mcp.types import ( | |
| CallToolRequest, | |
| CallToolResult, | |
| ListToolsRequest, | |
| ListToolsResult, | |
| Tool, | |
| TextContent, | |
| ImageContent, | |
| EmbeddedResource | |
| ) | |
| from .models import UserContext, MCPToolResult, MCPServerHealth | |
| from .database import get_database, SupabaseManager, DatabaseError, UserIsolationError | |
| from .config import settings | |
| from .error_handling import ( | |
| error_handler, ErrorContext, ApplicationError, ValidationError, | |
| retry_with_backoff, RetryConfig, DataCorruptionDetector | |
| ) | |
| from .validation import InputValidator, RequiredRule, TypeRule, UUIDRule | |
| logger = logging.getLogger(__name__) | |
| class MCPToolError(Exception): | |
| """Custom MCP tool execution error.""" | |
| pass | |
| class AuthenticationError(Exception): | |
| """Authentication related error.""" | |
| pass | |
| class BaseMCPServer(ABC): | |
| """ | |
| Base class for all MCP servers in the system. | |
| Provides common functionality including: | |
| - MCP protocol handling | |
| - Tool registration and execution | |
| - Database connectivity with user isolation | |
| - Error handling and logging | |
| - Health monitoring | |
| """ | |
| def __init__(self, server_name: str, port: int): | |
| self.server_name = server_name | |
| self.port = port | |
| self.server = Server(server_name) | |
| self.db: Optional[SupabaseManager] = None | |
| self.tools: Dict[str, Callable] = {} | |
| self.tool_schemas: Dict[str, Tool] = {} | |
| self._health_status = MCPServerHealth( | |
| server_name=server_name, | |
| is_healthy=False, | |
| response_time_ms=0.0 | |
| ) | |
| # Setup MCP server handlers | |
| self._setup_handlers() | |
| logger.info(f"Initialized {server_name} MCP server on port {port}") | |
| def _setup_handlers(self): | |
| """Setup MCP protocol handlers.""" | |
| async def list_tools() -> ListToolsResult: | |
| """List all available tools.""" | |
| return ListToolsResult(tools=list(self.tool_schemas.values())) | |
| async def call_tool(request: CallToolRequest) -> CallToolResult: | |
| """Execute a tool with the given arguments.""" | |
| start_time = time.time() | |
| try: | |
| # Extract user context from arguments | |
| user_context = self._extract_user_context(request.params.arguments) | |
| # Validate tool exists | |
| if request.params.name not in self.tools: | |
| raise MCPToolError(f"Unknown tool: {request.params.name}") | |
| # Execute the tool | |
| tool_func = self.tools[request.params.name] | |
| result = await self._execute_tool_safely( | |
| tool_func, | |
| user_context, | |
| request.params.arguments | |
| ) | |
| execution_time = (time.time() - start_time) * 1000 | |
| # Update health status | |
| self._health_status.is_healthy = True | |
| self._health_status.response_time_ms = execution_time | |
| self._health_status.last_check = datetime.utcnow() | |
| return CallToolResult( | |
| content=[ | |
| TextContent( | |
| type="text", | |
| text=str(result.data) if result.success else f"Error: {result.error_message}" | |
| ) | |
| ], | |
| isError=not result.success | |
| ) | |
| except Exception as e: | |
| execution_time = (time.time() - start_time) * 1000 | |
| error_msg = f"Tool execution failed: {str(e)}" | |
| # Update health status | |
| self._health_status.is_healthy = False | |
| self._health_status.response_time_ms = execution_time | |
| self._health_status.last_check = datetime.utcnow() | |
| self._health_status.error_message = error_msg | |
| logger.error(f"Tool {request.name} failed: {e}") | |
| return CallToolResult( | |
| content=[TextContent(type="text", text=error_msg)], | |
| isError=True | |
| ) | |
| def _extract_user_context(self, arguments: Dict[str, Any]) -> UserContext: | |
| """Extract and validate user context from tool arguments.""" | |
| # Validate user_id presence and format | |
| validator = InputValidator() | |
| validator.add_rule("user_id", RequiredRule("user_id")) | |
| validator.add_rule("user_id", TypeRule("user_id", str)) | |
| try: | |
| validator.validate_and_raise(arguments) | |
| except ValidationError as e: | |
| raise AuthenticationError(f"Invalid user context: {str(e)}") | |
| user_id = arguments.get('user_id') | |
| # Additional validation for user_id format if needed | |
| if not user_id.strip(): | |
| raise AuthenticationError("user_id cannot be empty") | |
| return UserContext( | |
| user_id=user_id, | |
| email=arguments.get('user_email'), | |
| permissions=arguments.get('user_permissions', []) | |
| ) | |
| async def _execute_tool_safely( | |
| self, | |
| tool_func: Callable, | |
| user_context: UserContext, | |
| arguments: Dict[str, Any] | |
| ) -> MCPToolResult: | |
| """Execute a tool function with comprehensive error handling and user isolation.""" | |
| error_context = ErrorContext( | |
| user_id=user_context.user_id, | |
| component=self.server_name, | |
| operation=tool_func.__name__, | |
| additional_data={"arguments_keys": list(arguments.keys())} | |
| ) | |
| start_time = time.time() | |
| try: | |
| # Ensure database connection with retry | |
| if not self.db: | |
| retry_config = RetryConfig(max_attempts=3, base_delay=1.0) | |
| self.db = await retry_with_backoff( | |
| get_database, | |
| retry_config=retry_config, | |
| context=error_context | |
| ) | |
| # Set user context for database operations | |
| await self.db.set_user_context(user_context) | |
| # Execute the tool function with retry for transient errors | |
| retry_config = RetryConfig( | |
| max_attempts=2, | |
| base_delay=0.5, | |
| retryable_exceptions=[ConnectionError, TimeoutError, DatabaseError] | |
| ) | |
| result = await retry_with_backoff( | |
| tool_func, | |
| user_context, | |
| arguments, | |
| retry_config=retry_config, | |
| context=error_context | |
| ) | |
| execution_time = (time.time() - start_time) * 1000 | |
| return MCPToolResult( | |
| success=True, | |
| data=result, | |
| execution_time_ms=execution_time | |
| ) | |
| except ValidationError as e: | |
| execution_time = (time.time() - start_time) * 1000 | |
| await error_handler.handle_error(e, error_context) | |
| return MCPToolResult( | |
| success=False, | |
| error_message=e.user_message, | |
| execution_time_ms=execution_time | |
| ) | |
| except UserIsolationError as e: | |
| execution_time = (time.time() - start_time) * 1000 | |
| await error_handler.handle_error(e, error_context) | |
| logger.error(f"User isolation error in {tool_func.__name__}: {e}") | |
| return MCPToolResult( | |
| success=False, | |
| error_message="Access denied: You don't have permission to access this resource", | |
| execution_time_ms=execution_time | |
| ) | |
| except DatabaseError as e: | |
| execution_time = (time.time() - start_time) * 1000 | |
| await error_handler.handle_error(e, error_context) | |
| logger.error(f"Database error in {tool_func.__name__}: {e}") | |
| return MCPToolResult( | |
| success=False, | |
| error_message="Database operation failed. Please try again later.", | |
| execution_time_ms=execution_time | |
| ) | |
| except ApplicationError as e: | |
| execution_time = (time.time() - start_time) * 1000 | |
| await error_handler.handle_error(e, error_context) | |
| return MCPToolResult( | |
| success=False, | |
| error_message=e.user_message, | |
| execution_time_ms=execution_time | |
| ) | |
| except Exception as e: | |
| execution_time = (time.time() - start_time) * 1000 | |
| error_info = await error_handler.handle_error(e, error_context) | |
| logger.error(f"Unexpected error in {tool_func.__name__}: {e}") | |
| return MCPToolResult( | |
| success=False, | |
| error_message=error_info.user_message, | |
| execution_time_ms=execution_time | |
| ) | |
| def register_tool( | |
| self, | |
| name: str, | |
| description: str, | |
| parameters: Dict[str, Any], | |
| func: Callable | |
| ): | |
| """Register a tool with the MCP server.""" | |
| # Create tool schema | |
| tool_schema = Tool( | |
| name=name, | |
| description=description, | |
| inputSchema={ | |
| "type": "object", | |
| "properties": { | |
| "user_id": { | |
| "type": "string", | |
| "description": "User ID for authentication and data isolation" | |
| }, | |
| **parameters | |
| }, | |
| "required": ["user_id"] + parameters.get("required", []) | |
| } | |
| ) | |
| # Store tool and schema | |
| self.tools[name] = func | |
| self.tool_schemas[name] = tool_schema | |
| logger.debug(f"Registered tool: {name}") | |
| async def initialize_database(self): | |
| """Initialize database connection.""" | |
| try: | |
| self.db = await get_database() | |
| logger.info(f"{self.server_name}: Database connection initialized") | |
| except Exception as e: | |
| logger.error(f"{self.server_name}: Failed to initialize database: {e}") | |
| raise | |
| async def health_check(self) -> MCPServerHealth: | |
| """Perform health check and return status.""" | |
| start_time = time.time() | |
| try: | |
| # Check database connectivity | |
| if self.db: | |
| db_healthy = await self.db.health_check() | |
| else: | |
| db_healthy = False | |
| # Check tool availability | |
| tools_available = len(self.tools) > 0 | |
| response_time = (time.time() - start_time) * 1000 | |
| is_healthy = db_healthy and tools_available | |
| self._health_status = MCPServerHealth( | |
| server_name=self.server_name, | |
| is_healthy=is_healthy, | |
| response_time_ms=response_time, | |
| last_check=datetime.utcnow(), | |
| error_message=None if is_healthy else "Health check failed" | |
| ) | |
| except Exception as e: | |
| response_time = (time.time() - start_time) * 1000 | |
| self._health_status = MCPServerHealth( | |
| server_name=self.server_name, | |
| is_healthy=False, | |
| response_time_ms=response_time, | |
| last_check=datetime.utcnow(), | |
| error_message=str(e) | |
| ) | |
| return self._health_status | |
| async def get_detailed_health_status(self) -> Dict[str, Any]: | |
| """Get detailed health status including metrics and diagnostics.""" | |
| health_status = await self.health_check() | |
| # Additional diagnostics | |
| diagnostics = { | |
| "server_name": self.server_name, | |
| "port": self.port, | |
| "tools_registered": len(self.tools), | |
| "tool_names": list(self.tools.keys()), | |
| "database_connected": self.db is not None, | |
| "uptime_seconds": time.time() - getattr(self, '_start_time', time.time()), | |
| "last_health_check": health_status.last_check.isoformat() if health_status.last_check else None | |
| } | |
| # Database health details | |
| if self.db: | |
| try: | |
| db_health = await self.db.health_check() | |
| diagnostics["database_health"] = { | |
| "connected": db_health, | |
| "connection_info": "Supabase connection active" if db_health else "Connection failed" | |
| } | |
| except Exception as e: | |
| diagnostics["database_health"] = { | |
| "connected": False, | |
| "error": str(e) | |
| } | |
| return { | |
| "health_status": { | |
| "server_name": health_status.server_name, | |
| "is_healthy": health_status.is_healthy, | |
| "response_time_ms": health_status.response_time_ms, | |
| "last_check": health_status.last_check.isoformat() if health_status.last_check else None, | |
| "error_message": health_status.error_message | |
| }, | |
| "diagnostics": diagnostics, | |
| "timestamp": datetime.utcnow().isoformat() | |
| } | |
| async def start_server(self): | |
| """Start the MCP server.""" | |
| try: | |
| # Record start time for uptime calculation | |
| self._start_time = time.time() | |
| # Initialize database connection | |
| await self.initialize_database() | |
| # Register server-specific tools | |
| await self.register_server_tools() | |
| logger.info(f"Starting {self.server_name} MCP server on port {self.port}") | |
| # Start the server | |
| async with stdio_server() as (read_stream, write_stream): | |
| await self.server.run( | |
| read_stream, | |
| write_stream, | |
| InitializationOptions( | |
| server_name=self.server_name, | |
| server_version="1.0.0", | |
| capabilities=self.server.get_capabilities( | |
| notification_options=None, | |
| experimental_capabilities=None | |
| ) | |
| ) | |
| ) | |
| except Exception as e: | |
| logger.error(f"Failed to start {self.server_name}: {e}") | |
| raise | |
| async def register_server_tools(self): | |
| """ | |
| Register server-specific tools. | |
| Must be implemented by each MCP server subclass. | |
| """ | |
| pass | |
| def validate_required_params(self, arguments: Dict[str, Any], required: List[str]): | |
| """Validate that required parameters are present.""" | |
| missing = [param for param in required if param not in arguments] | |
| if missing: | |
| raise MCPToolError(f"Missing required parameters: {missing}") | |
| def sanitize_input(self, value: Any, param_type: str = "string") -> Any: | |
| """Sanitize input parameters.""" | |
| if value is None: | |
| return None | |
| if param_type == "string": | |
| return str(value).strip() | |
| elif param_type == "integer": | |
| return int(value) | |
| elif param_type == "float": | |
| return float(value) | |
| elif param_type == "boolean": | |
| return bool(value) | |
| else: | |
| return value | |
| async def log_tool_execution( | |
| self, | |
| user_context: UserContext, | |
| tool_name: str, | |
| arguments: Dict[str, Any], | |
| result: Any, | |
| execution_time_ms: float | |
| ): | |
| """Log tool execution for monitoring and debugging.""" | |
| log_entry = { | |
| "server_name": self.server_name, | |
| "tool_name": tool_name, | |
| "user_id": user_context.user_id, | |
| "execution_time_ms": execution_time_ms, | |
| "success": result is not None, | |
| "timestamp": datetime.utcnow().isoformat() | |
| } | |
| logger.info(f"Tool execution: {log_entry}") | |
| def get_server_info(self) -> Dict[str, Any]: | |
| """Get server information and status.""" | |
| return { | |
| "server_name": self.server_name, | |
| "port": self.port, | |
| "tools_count": len(self.tools), | |
| "tools": list(self.tools.keys()), | |
| "health_status": self._health_status.model_dump(), | |
| "database_connected": self.db is not None | |
| } | |
| class MCPServerManager: | |
| """ | |
| Manager for multiple MCP servers. | |
| Handles server lifecycle and health monitoring. | |
| """ | |
| def __init__(self): | |
| self.servers: Dict[str, BaseMCPServer] = {} | |
| self.health_monitor_task: Optional[asyncio.Task] = None | |
| def register_server(self, server: BaseMCPServer): | |
| """Register an MCP server.""" | |
| self.servers[server.server_name] = server | |
| logger.info(f"Registered MCP server: {server.server_name}") | |
| async def start_all_servers(self): | |
| """Start all registered MCP servers.""" | |
| tasks = [] | |
| for server in self.servers.values(): | |
| task = asyncio.create_task(server.start_server()) | |
| tasks.append(task) | |
| # Start health monitoring | |
| self.health_monitor_task = asyncio.create_task(self._health_monitor_loop()) | |
| # Wait for all servers to start | |
| await asyncio.gather(*tasks, return_exceptions=True) | |
| async def stop_all_servers(self): | |
| """Stop all MCP servers.""" | |
| if self.health_monitor_task: | |
| self.health_monitor_task.cancel() | |
| # Additional cleanup can be added here | |
| logger.info("All MCP servers stopped") | |
| async def get_all_health_status(self) -> Dict[str, MCPServerHealth]: | |
| """Get health status for all servers.""" | |
| health_status = {} | |
| for name, server in self.servers.items(): | |
| health_status[name] = await server.health_check() | |
| return health_status | |
| async def _health_monitor_loop(self): | |
| """Background health monitoring loop.""" | |
| while True: | |
| try: | |
| await asyncio.sleep(30) # Check every 30 seconds | |
| health_status = await self.get_all_health_status() | |
| # Log unhealthy servers | |
| for name, status in health_status.items(): | |
| if not status.is_healthy: | |
| logger.warning(f"Server {name} is unhealthy: {status.error_message}") | |
| except asyncio.CancelledError: | |
| break | |
| except Exception as e: | |
| logger.error(f"Health monitor error: {e}") | |
| # Global server manager instance | |
| server_manager = MCPServerManager() |