Spaces:
Paused
Paused
Download shared/example_mcp_server.py from VAH6002/ai_data_scientist: direct link, hf CLI and curl.
- Browser
- Download file 5.63 kB
-
https://huggingface.co/spaces/VAH6002/ai_data_scientist/resolve/main/shared/example_mcp_server.py
- Command line
-
hf download hf://spaces/VAH6002/ai_data_scientist/shared/example_mcp_server.py
-
curl -L -o example_mcp_server.py https://huggingface.co/spaces/VAH6002/ai_data_scientist/resolve/main/shared/example_mcp_server.py
5.63 kB
| """ | |
| Example MCP server implementation demonstrating how to use the base framework. | |
| This serves as a template for creating new MCP servers. | |
| """ | |
| import asyncio | |
| import logging | |
| from typing import Any, Dict | |
| from .mcp_base import BaseMCPServer | |
| from .models import UserContext | |
| logger = logging.getLogger(__name__) | |
| class ExampleMCPServer(BaseMCPServer): | |
| """ | |
| Example MCP server that demonstrates the base functionality. | |
| This server provides simple echo and calculation tools. | |
| """ | |
| def __init__(self, port: int = 3007): | |
| super().__init__("example_mcp", port) | |
| async def register_server_tools(self): | |
| """Register example tools.""" | |
| async def echo_tool(user_context: UserContext, arguments: Dict[str, Any]): | |
| """Echo back the provided message with user information.""" | |
| message = arguments.get("message", "Hello World") | |
| # Log tool execution | |
| await self.log_tool_execution( | |
| user_context, | |
| "echo_tool", | |
| arguments, | |
| message, | |
| 0.0 | |
| ) | |
| return { | |
| "echo": message, | |
| "user_id": user_context.user_id, | |
| "timestamp": "2024-01-01T00:00:00Z" | |
| } | |
| async def calculate_tool(user_context: UserContext, arguments: Dict[str, Any]): | |
| """Perform simple calculations.""" | |
| # Validate required parameters | |
| self.validate_required_params(arguments, ["operation", "a", "b"]) | |
| # Sanitize inputs | |
| operation = self.sanitize_input(arguments["operation"], "string") | |
| a = self.sanitize_input(arguments["a"], "float") | |
| b = self.sanitize_input(arguments["b"], "float") | |
| # Perform calculation | |
| if operation == "add": | |
| result = a + b | |
| elif operation == "subtract": | |
| result = a - b | |
| elif operation == "multiply": | |
| result = a * b | |
| elif operation == "divide": | |
| if b == 0: | |
| raise ValueError("Division by zero is not allowed") | |
| result = a / b | |
| else: | |
| raise ValueError(f"Unsupported operation: {operation}") | |
| # Store calculation in database (example) | |
| if self.db: | |
| calculation_data = { | |
| "operation": operation, | |
| "operand_a": a, | |
| "operand_b": b, | |
| "result": result, | |
| "user_id": user_context.user_id | |
| } | |
| # In a real implementation, you would store this in the database | |
| logger.info(f"Calculation performed: {calculation_data}") | |
| return { | |
| "operation": operation, | |
| "operands": [a, b], | |
| "result": result | |
| } | |
| async def user_info_tool(user_context: UserContext, arguments: Dict[str, Any]): | |
| """Get information about the current user.""" | |
| return { | |
| "user_id": user_context.user_id, | |
| "email": user_context.email, | |
| "permissions": user_context.permissions, | |
| "server_name": self.server_name | |
| } | |
| # Register the tools | |
| self.register_tool( | |
| name="echo", | |
| description="Echo back a message with user information", | |
| parameters={ | |
| "message": { | |
| "type": "string", | |
| "description": "Message to echo back" | |
| } | |
| }, | |
| func=echo_tool | |
| ) | |
| self.register_tool( | |
| name="calculate", | |
| description="Perform basic mathematical calculations", | |
| parameters={ | |
| "operation": { | |
| "type": "string", | |
| "description": "Operation to perform (add, subtract, multiply, divide)", | |
| "enum": ["add", "subtract", "multiply", "divide"] | |
| }, | |
| "a": { | |
| "type": "number", | |
| "description": "First operand" | |
| }, | |
| "b": { | |
| "type": "number", | |
| "description": "Second operand" | |
| }, | |
| "required": ["operation", "a", "b"] | |
| }, | |
| func=calculate_tool | |
| ) | |
| self.register_tool( | |
| name="user_info", | |
| description="Get information about the current user", | |
| parameters={}, | |
| func=user_info_tool | |
| ) | |
| logger.info(f"Registered {len(self.tools)} tools for {self.server_name}") | |
| async def main(): | |
| """Main function to run the example MCP server.""" | |
| # Setup logging | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' | |
| ) | |
| # Create and start the server | |
| server = ExampleMCPServer() | |
| try: | |
| logger.info("Starting Example MCP Server...") | |
| await server.start_server() | |
| except KeyboardInterrupt: | |
| logger.info("Server stopped by user") | |
| except Exception as e: | |
| logger.error(f"Server error: {e}") | |
| raise | |
| if __name__ == "__main__": | |
| asyncio.run(main()) |