File size: 5,628 Bytes
56c063a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
"""

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())