Skip to main content
Glama
armorwallet
by armorwallet

calculator

Evaluate mathematical and statistical expressions using Python syntax. Perform operations like arithmetic, list expressions, and use functions such as min, max, mean, and variance. Supports custom variables for advanced calculations in blockchain and crypto strategies.

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

  • The MCP tool handler for the 'calculator' tool. Decorated with @mcp.tool() for registration. Takes expression and variables, calls the calculate helper, and returns the result.
    @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)}
  • The core implementation of the calculator logic. A safe AST-based evaluator for mathematical expressions supporting operators, math/stats functions, variables, lists, and function calls.
    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)
Behavior3/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 mentions 'safely evaluates,' which implies some safety mechanism, but doesn't detail what that entails (e.g., sandboxing, error handling). It lists supported operations and functions, which adds useful context beyond basic functionality, but lacks information on performance, limitations, or output format.

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: the first sentence states the core purpose, followed by supporting details in two concise sentences. Every sentence adds value without redundancy, making it efficient and well-structured for quick understanding.

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

Completeness3/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 output schema, no annotations), the description is somewhat complete but has gaps. It covers purpose, usage, and parameters well, but lacks details on behavioral traits like error handling, safety mechanisms, or return values. Without annotations or output schema, more context on expected results would improve completeness.

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 explains that 'expression' is a 'mathematical or statistical expression string using Python syntax' and that 'variables' is a 'dict' for 'custom variables,' including 'lists for time series data.' This adds meaningful semantics beyond the bare schema, though it could specify format 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: 'Safely evaluates a mathematical or statistical expression string using Python syntax.' It specifies the verb ('evaluates') and resource ('mathematical or statistical expression'), and distinguishes it from sibling tools like calculate_token_conversion by focusing on general mathematical evaluation rather than cryptocurrency-specific calculations.

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

Usage Guidelines4/5

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

The description provides clear context for when to use this tool: for evaluating mathematical expressions with Python syntax, including arithmetic, functions, and custom variables. It doesn't explicitly state when not to use it or name alternatives, but the context is sufficiently clear given the sibling tools are unrelated to mathematical evaluation.

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

Related 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/armorwallet/armor-crypto-mcp'

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