Skip to main content
Glama

calculate

Evaluate any mathematical expression from basic arithmetic to advanced functions including trigonometry, matrices, unit conversions, complex numbers, and statistics.

Instructions

Evaluate a mathematical expression using MathJS. Supports arithmetic, algebra, trigonometry, matrices, units, complex numbers, statistics and all other MathJS built-in functions.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
expressionYesMath expression to evaluate, e.g. "sin(pi/4)", "2 km to mile", "det([1,2;3,4])"

Implementation Reference

  • The async handler function for the 'calculate' tool. It calls evaluate(expression) and returns the result as text content, or an error message with isError flag.
    async ({ expression }) => {
      try {
        const text = await evaluate(expression);
        return {
          content: [{ type: 'text', text }],
        };
      } catch (err: unknown) {
        const message = err instanceof Error ? err.message : String(err);
        return {
          content: [{ type: 'text', text: `Error: ${message}` }],
          isError: true,
        };
      }
    },
  • Input schema for the 'calculate' tool. Defines a single 'expression' string parameter (min length 1) with a description of supported MathJS features.
    inputSchema: {
      expression: z
        .string()
        .min(1)
        .describe(
          'Math expression to evaluate, e.g. "sin(pi/4)", "2 km to mile", "det([1,2;3,4])"',
        ),
    },
  • src/index.ts:73-101 (registration)
    Registration of the tool named 'calculate' using server.registerTool() with its schema and handler.
    server.registerTool(
      'calculate',
      {
        description:
          'Evaluate a mathematical expression using MathJS. Supports arithmetic, algebra, trigonometry, matrices, units, complex numbers, statistics and all other MathJS built-in functions.',
        inputSchema: {
          expression: z
            .string()
            .min(1)
            .describe(
              'Math expression to evaluate, e.g. "sin(pi/4)", "2 km to mile", "det([1,2;3,4])"',
            ),
        },
      },
      async ({ expression }) => {
        try {
          const text = await evaluate(expression);
          return {
            content: [{ type: 'text', text }],
          };
        } catch (err: unknown) {
          const message = err instanceof Error ? err.message : String(err);
          return {
            content: [{ type: 'text', text: `Error: ${message}` }],
            isError: true,
          };
        }
      },
    );
  • The evaluate() helper function that runs math.evaluate() inside a Worker thread with a timeout. Used by the calculate handler to safely compute expressions.
    function evaluate(expression: string): Promise<string> {
      return new Promise<string>((resolve, reject) => {
        const worker = new Worker(WORKER_PATH, {
          workerData: { expression, maxMatrixSize: MAX_MATRIX_SIZE },
          execArgv: isTsNode ? ['-r', 'ts-node/register'] : [],
        });
    
        const timer = setTimeout(() => {
          void worker.terminate();
          reject(new Error(`Calculation timed out after ${TIMEOUT_MS} ms`));
        }, TIMEOUT_MS);
    
        worker.once('message', (msg: WorkerMessage) => {
          clearTimeout(timer);
          if (msg.ok) {
            resolve(msg.value);
          } else {
            reject(new Error(msg.error));
          }
        });
    
        worker.once('error', (err) => {
          clearTimeout(timer);
          void worker.terminate();
          reject(err);
        });
      });
    }
  • The worker thread implementation that actually calls math.evaluate(expression) and checks matrix size limits before posting the result back.
    const { expression, maxMatrixSize } = workerData as WorkerInput;
    
    try {
      const result = math.evaluate(expression);
      checkSize(result, maxMatrixSize);
      parentPort!.postMessage({ ok: true, value: math.format(result, { precision: 14 }) });
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : String(err);
      parentPort!.postMessage({ ok: false, error: message });
    }
Behavior3/5

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

With no annotations, the description must disclose behavioral traits. It mentions the library (MathJS) and supported capabilities, but does not specify whether the operation is read-only, error behavior, or side effects. For a calculation tool, it is likely safe, but the description could be more transparent about return values and error handling.

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 two sentences long, front-loads the core purpose, and includes a concise list of supported features without unnecessary elaboration. Every sentence is informative and contributes to 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?

The tool is simple with one parameter, but it lacks an output schema. The description does not mention the return format or potential errors. For a calculation tool, completeness could be improved by noting the result type or error handling, so a score of 3 is appropriate.

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 coverage is 100%, providing baseline 3. The description adds value by explaining that the expression is evaluated using MathJS and listing supported mathematical domains, which enriches the parameter meaning beyond the schema's examples.

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 using MathJS, with a specific verb ('Evaluate') and resource ('mathematical expression'). It lists supported areas (arithmetic, algebra, trigonometry, etc.) and distinguishes itself from potential siblings by mentioning MathJS's full capabilities, which is helpful even in the absence of sibling tools.

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 any mathematical expression evaluation but does not explicitly state when to use this tool vs alternatives, nor does it mention when not to use it. Since there are no sibling tools, this is a minor gap, but the lack of explicit guidance results in a score of 3.

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/bangbang93/mcp-calculator'

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