calculate
Evaluate mathematical expressions safely to get calculation results. Use this tool to perform basic arithmetic operations like addition, multiplication, and division.
Instructions
Evaluate a mathematical expression safely.
Args: expression: A mathematical expression to evaluate (e.g., "2 + 2", "10 * 5")
Returns: The result of the calculation as a string
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| expression | Yes |
Implementation Reference
- src/mcp_server/main.py:65-77 (handler)The primary handler function for the 'calculate' MCP tool, registered with the @mcp.tool() decorator. It delegates execution to the internal _calculate helper.@mcp.tool() def calculate(expression: str) -> str: """ Evaluate a mathematical expression safely. Args: expression: A mathematical expression to evaluate (e.g., "2 + 2", "10 * 5") Returns: The result of the calculation as a string """ return _calculate(expression)
- src/mcp_server/main.py:28-49 (helper)Internal helper function implementing the core logic of the calculate tool, performing safe evaluation of mathematical expressions with character validation and error handling.def _calculate(expression: str) -> str: """ Evaluate a mathematical expression safely. Args: expression: A mathematical expression to evaluate (e.g., "2 + 2", "10 * 5") Returns: The result of the calculation as a string """ try: # Simple evaluation for basic math operations # In production, you'd want a more secure math parser allowed_chars = set("0123456789+-*/.() ") if not all(c in allowed_chars for c in expression): return f"Error: Invalid characters in expression '{expression}'" result = eval(expression) return f"The result of '{expression}' is {result}" except Exception as e: return f"Error calculating '{expression}': {str(e)}"
- src/mcp_server/main.py:15-19 (schema)Pydantic model defining the input schema for the calculate tool, specifying the 'expression' parameter.class CalculateRequest(BaseModel): """Request model for calculate tool.""" expression: str
- src/mcp_server/main.py:65-65 (registration)The @mcp.tool() decorator registers the 'calculate' function as an MCP tool.@mcp.tool()