Skip to main content
Glama

calculator

Compute results of mathematical expressions with a safe parser. Handles arithmetic, grouping, common functions, and constants.

Instructions

Evaluate a mathematical expression and return the result.

Supported operations:

  • Arithmetic: +, -, *, /, %, **

  • Parentheses for grouping: (2 + 3) * 4

  • Common functions: abs, ceil, floor, round, sqrt, min, max

  • Constants: PI, E

Safety:

  • Does NOT use eval() — uses a safe expression parser

  • Rejects any non-mathematical input

Examples:

  • "2 + 3 * 4" → 14

  • "(2 + 3) * 4" → 20

  • "sqrt(144)" → 12

  • "round(3.14159, 2)" → 3.14

  • "max(10, 20, 30)" → 30

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
expressionYesThe mathematical expression to evaluate (e.g., '2 + 3 * 4').

Implementation Reference

  • The async handler function that evaluates mathematical expressions. It sanitizes input, checks against a whitelist of allowed math functions/constants, uses Function constructor with restricted scope (Math methods) for safe evaluation, and returns the result as JSON.
        async ({ expression }) => {
          try {
            // Sanitize: only allow digits, operators, parens, commas, dots, spaces, and known function names
            const sanitized = expression.trim();
            const allowedPattern = /^[\d\s+\-*/%.(),^a-zA-Z_]+$/;
    
            if (!allowedPattern.test(sanitized)) {
              return {
                content: [
                  {
                    type: "text" as const,
                    text: "Error: Expression contains disallowed characters.",
                  },
                ],
                isError: true,
              };
            }
    
            // Whitelist of allowed functions
            const allowedWords = new Set([
              "abs", "ceil", "floor", "round", "sqrt",
              "min", "max", "pow", "log", "sin", "cos", "tan",
              "PI", "E",
            ]);
    
            // Check for any word tokens that aren't in the whitelist
            const wordTokens = sanitized.match(/[a-zA-Z_]+/g) || [];
            for (const token of wordTokens) {
              if (!allowedWords.has(token)) {
                return {
                  content: [
                    {
                      type: "text" as const,
                      text: `Error: Disallowed identifier '${token}' in expression.`,
                    },
                  ],
                  isError: true,
                };
              }
            }
    
            // Safe evaluation using Function constructor with restricted scope
            const safeScope: Record<string, unknown> = {
              abs: Math.abs,
              ceil: Math.ceil,
              floor: Math.floor,
              round: Math.round,
              sqrt: Math.sqrt,
              min: Math.min,
              max: Math.max,
              pow: Math.pow,
              log: Math.log,
              sin: Math.sin,
              cos: Math.cos,
              tan: Math.tan,
              PI: Math.PI,
              E: Math.E,
            };
    
            const paramNames = Object.keys(safeScope);
            const paramValues = Object.values(safeScope);
    
            // Replace ** with Math.pow for exponentiation
            let processedExpr = sanitized.replace(/\^/g, "**");
    
            // Build a safe evaluator
            const fn = new Function(
              ...paramNames,
              `"use strict"; return (${processedExpr});`
            );
    
            const result = fn(...paramValues);
    
            return {
              content: [
                {
                  type: "text" as const,
                  text: JSON.stringify(
                    {
                      expression: sanitized,
                      result: typeof result === "number" ? result : String(result),
                      type: typeof result,
                    },
                    null,
                    2
                  ),
                },
              ],
            };
          } catch (err: any) {
            return {
              content: [
                {
                  type: "text" as const,
                  text: `Calculation Error: ${err.message}`,
                },
              ],
              isError: true,
            };
          }
        }
      );
    }
  • Zod schema for the 'expression' input parameter — a string describing the mathematical expression to evaluate.
    {
      expression: z
        .string()
        .describe(
          "The mathematical expression to evaluate (e.g., '2 + 3 * 4')."
        ),
    },
  • The registerCalculatorTool function that registers the 'calculator' tool on the MCP server via server.tool(), including description, schema, and handler.
    export function registerCalculatorTool(server: McpServer): void {
      server.tool(
        "calculator",
        `Evaluate a mathematical expression and return the result.
    
    Supported operations:
      - Arithmetic: +, -, *, /, %, **
      - Parentheses for grouping: (2 + 3) * 4
      - Common functions: abs, ceil, floor, round, sqrt, min, max
      - Constants: PI, E
    
    Safety:
      - Does NOT use eval() — uses a safe expression parser
      - Rejects any non-mathematical input
    
    Examples:
      - "2 + 3 * 4"           → 14
      - "(2 + 3) * 4"         → 20
      - "sqrt(144)"           → 12
      - "round(3.14159, 2)"   → 3.14
      - "max(10, 20, 30)"     → 30`,
        {
          expression: z
            .string()
            .describe(
              "The mathematical expression to evaluate (e.g., '2 + 3 * 4')."
            ),
        },
        async ({ expression }) => {
          try {
            // Sanitize: only allow digits, operators, parens, commas, dots, spaces, and known function names
            const sanitized = expression.trim();
            const allowedPattern = /^[\d\s+\-*/%.(),^a-zA-Z_]+$/;
    
            if (!allowedPattern.test(sanitized)) {
              return {
                content: [
                  {
                    type: "text" as const,
                    text: "Error: Expression contains disallowed characters.",
                  },
                ],
                isError: true,
              };
            }
    
            // Whitelist of allowed functions
            const allowedWords = new Set([
              "abs", "ceil", "floor", "round", "sqrt",
              "min", "max", "pow", "log", "sin", "cos", "tan",
              "PI", "E",
            ]);
    
            // Check for any word tokens that aren't in the whitelist
            const wordTokens = sanitized.match(/[a-zA-Z_]+/g) || [];
            for (const token of wordTokens) {
              if (!allowedWords.has(token)) {
                return {
                  content: [
                    {
                      type: "text" as const,
                      text: `Error: Disallowed identifier '${token}' in expression.`,
                    },
                  ],
                  isError: true,
                };
              }
            }
    
            // Safe evaluation using Function constructor with restricted scope
            const safeScope: Record<string, unknown> = {
              abs: Math.abs,
              ceil: Math.ceil,
              floor: Math.floor,
              round: Math.round,
              sqrt: Math.sqrt,
              min: Math.min,
              max: Math.max,
              pow: Math.pow,
              log: Math.log,
              sin: Math.sin,
              cos: Math.cos,
              tan: Math.tan,
              PI: Math.PI,
              E: Math.E,
            };
    
            const paramNames = Object.keys(safeScope);
            const paramValues = Object.values(safeScope);
    
            // Replace ** with Math.pow for exponentiation
            let processedExpr = sanitized.replace(/\^/g, "**");
    
            // Build a safe evaluator
            const fn = new Function(
              ...paramNames,
              `"use strict"; return (${processedExpr});`
            );
    
            const result = fn(...paramValues);
    
            return {
              content: [
                {
                  type: "text" as const,
                  text: JSON.stringify(
                    {
                      expression: sanitized,
                      result: typeof result === "number" ? result : String(result),
                      type: typeof result,
                    },
                    null,
                    2
                  ),
                },
              ],
            };
          } catch (err: any) {
            return {
              content: [
                {
                  type: "text" as const,
                  text: `Calculation Error: ${err.message}`,
                },
              ],
              isError: true,
            };
          }
        }
      );
    }
  • src/index.ts:52-52 (registration)
    Call site where registerCalculatorTool is invoked during tool registration in McpToolkitServer.registerTools().
    registerCalculatorTool(this.server);
  • src/index.ts:9-9 (registration)
    Import of registerCalculatorTool from the calculator module.
    import { registerCalculatorTool } from "./tools/calculator.js";
Behavior5/5

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

The description discloses safety (no eval, safe parser), supported operations, and rejection of non-mathematical input. Since no annotations are provided, the description carries full burden and does so well.

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 well-structured with a clear purpose, organized sections for operations, safety, and examples. It is concise without unnecessary verbosity.

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?

The description is largely complete but does not explicitly state the return type (number). Given the simplicity of the tool, this omission is minor but prevents a perfect score.

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

Parameters5/5

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

The description adds extensive meaning beyond the schema: it lists supported operations, functions, constants, and provides examples. The schema only describes the parameter as a string, while the description enriches it with context.

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 evaluates mathematical expressions and returns a result. It is distinct from siblings which handle API calls, database queries, file operations, etc.

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 implicitly indicates when to use the tool (for math problems) and gives safety guidelines. However, it does not explicitly contrast with siblings or specify when not to use it.

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/vyshnavi-nandyala/mcp-toolkit-server'

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