calculator.py•1.79 kB
"""
Example calculator tool implementation.
"""
from typing import Any, Dict
import mcp.types as types
async def calculator_handler(arguments: Dict[str, Any]) -> str:
"""
Example calculator tool that performs basic arithmetic operations.
Args:
arguments: Tool arguments containing:
- operation: The operation to perform (add, subtract, multiply, divide)
- a: First number
- b: Second number
Returns:
String containing the calculation result
"""
operation = arguments.get("operation")
a = float(arguments.get("a", 0))
b = float(arguments.get("b", 0))
operations = {
"add": lambda x, y: x + y,
"subtract": lambda x, y: x - y,
"multiply": lambda x, y: x * y,
"divide": lambda x, y: x / y if y != 0 else "Error: Division by zero",
}
if operation not in operations:
return f"Error: Unknown operation '{operation}'"
result = operations[operation](a, b)
return f"{a} {operation} {b} = {result}"
# Tool schema definition
CALCULATOR_SCHEMA = types.Tool(
name="example_calculator",
description="Performs basic arithmetic operations (add, subtract, multiply, divide)",
inputSchema={
"type": "object",
"properties": {
"operation": {
"type": "string",
"description": "The operation to perform",
"enum": ["add", "subtract", "multiply", "divide"],
},
"a": {
"type": "number",
"description": "First number",
},
"b": {
"type": "number",
"description": "Second number",
},
},
"required": ["operation", "a", "b"],
},
)