Skip to main content
Glama

calculator

Evaluate mathematical expressions and perform statistical calculations using Python syntax. Supports arithmetic operations, math functions, and custom variables for cryptocurrency data analysis.

Instructions

Safely evaluates a mathematical or statistical expression string using Python syntax.

Supports arithmetic operations (+, -, *, /, **, %, //), list expressions, and a range of math and statistics functions: 
abs, round, min, max, len, sum, mean, median, stdev, variance, sin, cos, tan, sqrt, log, exp, floor, ceil, etc.

Custom variables can be passed via the 'variables' dict, including lists for time series data.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
expressionYes
variablesYes

Implementation Reference

  • MCP tool handler for 'calculator': decorated with @mcp.tool() for registration and executes by calling the calculate helper function.
    @mcp.tool()
    async def calculator(expression:str, variables:dict[str, Any]):
        """
        Safely evaluates a mathematical or statistical expression string using Python syntax.
    
        Supports arithmetic operations (+, -, *, /, **, %, //), list expressions, and a range of math and statistics functions: 
        abs, round, min, max, len, sum, mean, median, stdev, variance, sin, cos, tan, sqrt, log, exp, floor, ceil, etc.
    
        Custom variables can be passed via the 'variables' dict, including lists for time series data.
        """
        return {'result': calculate(expression, variables)}
  • Core helper function that implements safe evaluation of mathematical expressions using AST parsing, supporting variables, operators, math/stats functions.
    def calculate(expr: str, variables: dict = None) -> float:
        """
        Evaluate a math/stat expression with support for variables and common functions.
        """
        variables = variables or {}
        # Allowed names from math and statistics
        safe_names = {
            k: v for k, v in vars(math).items() if not k.startswith("__")
        }
        safe_names.update({
            'mean': statistics.mean,
            'median': statistics.median,
            'stdev': statistics.stdev,
            'variance': statistics.variance,
            'sum': sum,
            'min': min,
            'max': max,
            'len': len,
            'abs': abs,
            'round': round
        })
    
        # Safe operators
        ops = {
            ast.Add: operator.add,
            ast.Sub: operator.sub,
            ast.Mult: operator.mul,
            ast.Div: operator.truediv,
            ast.FloorDiv: operator.floordiv,
            ast.Mod: operator.mod,
            ast.Pow: operator.pow,
            ast.USub: operator.neg
        }
        def _eval(node):
            if isinstance(node, ast.Num):
                return node.n
            elif isinstance(node, ast.Constant):  # Python 3.8+
                return node.value
            elif isinstance(node, ast.BinOp):
                return ops[type(node.op)](_eval(node.left), _eval(node.right))
            elif isinstance(node, ast.UnaryOp):
                return ops[type(node.op)](_eval(node.operand))
            elif isinstance(node, ast.Name):
                if node.id in variables:
                    return variables[node.id]
                elif node.id in safe_names:
                    return safe_names[node.id]
                else:
                    raise NameError(f"Unknown variable or function: {node.id}")
            elif isinstance(node, ast.Call):
                func = _eval(node.func)
                args = [_eval(arg) for arg in node.args]
                return func(*args)
            elif isinstance(node, ast.List):
                return [_eval(elt) for elt in node.elts]
            else:
                raise TypeError(f"Unsupported expression type: {type(node)}")
    
        parsed = ast.parse(expr, mode="eval")
        return _eval(parsed.body)
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It effectively describes key traits: it 'safely evaluates' expressions (implying error handling or security), supports specific operations and functions, and allows custom variables via a dict. However, it lacks details on error messages, performance limits, or output format, leaving some behavioral aspects unclear.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately sized and front-loaded, starting with the core purpose and following with supported operations and parameter details. Every sentence adds value without redundancy, making it efficient and easy to scan for key information.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's moderate complexity (2 parameters, no annotations, no output schema), the description is mostly complete. It covers purpose, behavior, and parameter semantics well, but lacks details on output format (e.g., result type or error handling). For a calculation tool, this is a minor gap, as the core functionality is clearly described.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must compensate. It adds significant meaning beyond the schema by explaining that 'expression' is a 'mathematical or statistical expression string using Python syntax' and 'variables' is a 'dict' for 'custom variables... including lists for time series data'. This clarifies parameter purposes and usage, though it could provide more examples or constraints.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose with specific verbs ('evaluates a mathematical or statistical expression string') and resources ('using Python syntax'), distinguishing it from sibling tools focused on cryptocurrency operations like wallet management and trading. It explicitly mentions the types of operations supported, making its function unambiguous.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage for mathematical or statistical expressions, but does not explicitly state when to use this tool versus alternatives (e.g., other calculation tools or manual computation). It provides context on supported operations but lacks explicit guidance on exclusions or comparisons with sibling tools, which are unrelated to calculation.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/emmaThompson07/armor-crypto-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server