Skip to main content
Glama
daffamumtaz2361

safe-mathjs-mcp

safe-mathjs-mcp

A sandboxed math MCP server for Node.js. It gives LLM agents a safe place to evaluate, simplify, and differentiate mathematical expressions — powered by mathjs.

Why "safe"? Untrusted model input is evaluated inside a worker thread against a strict AST allowlist: only pure functions over numbers and number-matrices, no eval, no string processing, no assignments, no accessors, no units, no randomness — with a hard execution timeout.

Tools

Tool

Description

evaluate

Evaluate a numeric expression. Supports variables and configurable precision.

simplify

Symbolic simplification (collect like terms, fold constants). Free symbols stay symbolic.

derivative

Symbolic differentiation with respect to a variable.

Related MCP server: math-mcp

Quick start

Requires Node.js >= 18.

npm install
npm start            # run the stdio server directly
npm run inspect      # interactive testing via the MCP inspector

To connect the server to an agent harness (Claude Desktop, Claude Code, Zed, VS Code, ...), see Installing in agent harnesses.

Installing in agent harnesses

The server speaks MCP over stdio, so every harness works the same way: it spawns node with the entry script. Prerequisites: npm install has been run in the repo, Node.js >= 18 is on PATH, and you use an absolute path to the repo (replace /path/to/safe-mathjs-mcp below). The working directory doesn't matter — the worker script and mathjs resolve relative to the entry file.

The universal entry, reused below in each harness's format:

{
  "mcpServers": {
    "safe-mathjs": {
      "command": "node",
      "args": ["/path/to/safe-mathjs-mcp/src/index.js"]
    }
  }
}

Claude Desktop

Edit the config file — ~/Library/Application Support/Claude/claude_desktop_config.json (macOS), %APPDATA%\Claude\claude_desktop_config.json (Windows), or ~/.config/Claude/claude_desktop_config.json (Linux) — and add the universal mcpServers entry from above. Restart Claude Desktop afterwards.

Claude Code

Add it from the CLI (no config file needed):

claude mcp add safe-mathjs -- node /path/to/safe-mathjs-mcp/src/index.js
claude mcp list          # verify

By default this applies to your user account; use --scope project to scope it to the current project or --scope local for your local machine only. Alternatively, commit a .mcp.json in the project root with the same mcpServers shape.

Zed

Add an mcp key (note: Zed uses mcp, not mcpServers) to ~/.config/zed/settings.json:

{
  "mcp": {
    "safe-mathjs": {
      "command": "node",
      "args": ["/path/to/safe-mathjs-mcp/src/index.js"],
      "enabled": true
    }
  }
}

Zed also accepts an environment object here if you want to pass CALC_TIMEOUT_MS.

VS Code (Copilot)

Create .vscode/mcp.json in your workspace. VS Code uses a servers key and an optional type field, which differs from most other harnesses:

{
  "servers": {
    "safe-mathjs": {
      "type": "stdio",
      "command": "node",
      "args": ["/path/to/safe-mathjs-mcp/src/index.js"]
    }
  }
}

Reload the window after adding it.

Cursor

Create .cursor/mcp.json in the project root with the same mcpServers shape as the Claude Desktop example above.

Cline

Add it through Cline's MCP settings (cline_mcp_settings.json, reachable from the Cline settings UI) — same mcpServers shape as Claude Desktop. Cline lets you set environment variables per server in the same JSON.

Any MCP SDK client

import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";

const transport = new StdioClientTransport({
  command: "node",
  args: ["/path/to/safe-mathjs-mcp/src/index.js"],
});
const client = new Client({ name: "my-app", version: "1.0.0" });
await client.connect(transport);

const { content } = await client.callTool({
  name: "evaluate",
  arguments: { expression: "2^10" },
});

Troubleshooting

  • Restart the harness after editing config files — most clients only load MCP servers at startup.

  • Wrong path / node not found — use the absolute repo path, and make sure node resolves for the harness's shell (check with node --version).

  • Passing env vars — harnesses that support an environment field (Zed, Cline) can set CALC_TIMEOUT_MS there. For clients that don't (e.g. Claude Desktop), wrap the command: env CALC_TIMEOUT_MS=5000 node /path/to/safe-mathjs-mcp/src/index.js.

  • Sanity check first — run npm run inspect in the repo to confirm the server starts and the tools respond before wiring it into a harness.

Tool reference

evaluate

  • expression (required) — math expression, max 512 chars. Example: 2 * (12 + sqrt(255))^2

  • precision (optional) — significant digits for the result, 1–100 (default 10)

  • variables (optional) — named numeric values, e.g. { x: 2 }

evaluate("5! + mean([1,2,3]) + det([[1,2],[3,4]])")   → 120
evaluate("x^2 + 1", { variables: { x: 3 } })           → 10
evaluate("1/3", { precision: 30 })                     → 0.333333333333333333333333333333

simplify

  • expression (required)

  • variables (optional) — known values folded in as constants

simplify("3*x + 2*x")       → 5 * x
simplify("x/x")             → 1
simplify("x^2 + 2*x + 1")   → x ^ 2 + 2 * x + 1

Note: simplification is heuristic — it collects like terms and folds constants but does not expand products or factor polynomials. Free symbols are treated as unknowns; e.g. x/x simplifies to 1, dropping the x != 0 case.

derivative

  • expression (required)

  • variable (required) — variable to differentiate with respect to, e.g. x

derivative("x^3 + sin(x)", "x")   → 3 * x ^ 2 + cos(x)
derivative("a*x^2 + b", "x")      → 2 * a * x
derivative("x^2", "y")            → 0

Other symbols in the expression are treated as free constants; the result is simplified.

Supported surface

Operators: + - * / ^ % ! and unary plus/minus

Constants: pi, e, tau

Functions (pure math over numbers and number-matrices):

Category

Functions

Arithmetic & roots

sqrt, cbrt, abs, pow, exp, log, ln, log10, log2, nthRoot, gcd, lcm, factorial, sign, hypot, mod

Trigonometry

sin, cos, tan, asin, acos, atan, atan2, sinh, cosh, tanh

Rounding & min/max

floor, ceil, round, min, max

Number theory

isPrime, combinations, permutations

Statistics

mean, median, std, sum, prod, variance, mode

Linear algebra

det, inv, transpose, norm, dot, cross

Array literals like [1,2,3] and matrices like [[1,2],[3,4]] are supported for statistics and linear algebra.

Note: elementwise application of scalar functions to matrices (e.g. sqrt([4,9])) is not supported — write [sqrt(4), sqrt(9)] instead.

Security model

Expressions are untrusted model input, so evaluation happens in a dedicated worker thread behind layered guards:

  1. Worker isolation — evaluation runs in a worker thread; if an expression ever hangs, the thread is terminated (2 s timeout, configurable via CALC_TIMEOUT_MS). If the worker crashes, the next call respawns it.

  2. AST allowlist, not blocklist — the expression is parsed and every node validated before evaluation. Only these node types pass:

    • ConstantNode (numbers only — string/boolean/null literals are rejected)

    • SymbolNode (pi, e, tau, or declared variables)

    • OperatorNode (allowlisted operators)

    • FunctionNode (allowlisted functions)

    • ParenthesisNode, ArrayNode

  3. No code execution — mathjs is a pure AST interpreter; eval/new Function are never used, and the string-processing functions (evaluate, parse, compile, format, print) are not in the allowlist.

  4. Structural exclusions — assignments (x = 5), object literals, indexing (A[1]), conditionals (a ? b : c), ranges (1:5), multi-statement blocks, comparison/logical/bitwise operators, units, and randomness are all rejected with a Disallowed ... error.

  5. Result checks — complex numbers (scalar or inside arrays) and NaN are rejected after evaluation.

  6. Bounded input — expressions are capped at 512 characters; variables must be valid identifiers and prototype-polluting names (__proto__, constructor, prototype) are rejected.

  7. BigNumber precision — all math runs on BigNumber with configurable significant digits (default 10), avoiding float artifacts.

Anything outside this surface fails loudly with a descriptive error — nothing is silently coerced.

Configuration

Env var

Default

Purpose

CALC_TIMEOUT_MS

2000

Max wall-clock time for a single evaluation before the worker is terminated

Project layout

src/
  index.js              MCP server: tool registration, worker lifecycle, timeouts
  evaluator-worker.js   Sandbox: parsing, AST validation, whitelists, evaluation

Extending the whitelist

The allowlists live at the top of src/evaluator-worker.js (ALLOWED_FUNCTIONS, ALLOWED_OPERATORS, ALLOWED_SYMBOLS, ALLOWED_NODES). When adding a function, keep to the rule: pure, deterministic, numbers and number-matrices only. Functions that take strings, return units, or accept function-valued arguments (e.g. map, format, unit) do not fit the model. Verify the function exists in the installed mathjs version before adding (e.g. solve and nextPrime were removed in mathjs 13).

License

MIT

Available Tools

3 tools
derivativeSymbolic DerivativeA

Compute the symbolic derivative (differentiation) of a math expression with respect to a variable. Example: expression 'x^3 + sin(x)' with variable 'x' yields '3 * x ^ 2 + cos(x)'. Other symbols in the expression are treated as free constants; the result is simplified.

ParametersJSON Schema
NameRequiredDescriptionDefault
variableYesThe variable to differentiate with respect to, e.g. 'x'.
expressionYesA mathematical expression to differentiate, e.g. 'x^3 + sin(x)'.

TDQS

A4.5/5.0
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. It discloses key behaviors: differentiation with respect to a specified variable, treating other symbols as free constants, and simplifying the result. An example concretely illustrates the behavior.

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 plus an example, front-loaded with the core purpose. Every sentence adds value: the main definition, the example, and the behavioral note on constants/simplification. No wasted words.

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

Completeness5/5

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

For a simple two-parameter differentiation tool with no output schema and no annotations, the description is remarkably complete. It explains the purpose, gives an example, and discloses edge-case behavior (free constants, simplification). The absence of an output schema is compensated by the illustrative yield.

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?

The input schema already describes both parameters with 100% coverage, so the baseline is 3. The description adds meaning by explaining the role of the variable ('with respect to') and providing a full example that maps parameters to an input/output pair.

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 computes symbolic derivatives of a mathematical expression with respect to a variable, with a concrete example. This specific verb+resource pairing differentiates it from sibling tools like evaluate and simplify.

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 the tool—when a derivative is needed—through the example and explanation. It doesn't explicitly mention alternatives or when not to use it, but the purpose is unambiguous.

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

evaluateEvaluate ExpressionB

Evaluate a mathematical expression in one call. Supports + - * / ^ % ! and parentheses; array literals like [1,2,3] for statistics and [[1,2],[3,4]] for linear algebra. Functions: sqrt, cbrt, abs, pow, exp, log, ln, log10, log2, nthRoot, gcd, lcm, factorial, sign, hypot, mod, sin, cos, tan, asin, acos, atan, atan2, sinh, cosh, tanh, floor, ceil, round, min, max, isPrime, combinations, permutations, mean, median, std, sum, prod, variance, mode, det, inv, transpose, norm, dot, cross. Constants: pi, e, tau. Pass named values via 'variables' (e.g. { x: 2 }) to reference them in the expression. Example: '2 * (12 + sqrt(255))^2'

ParametersJSON Schema
NameRequiredDescriptionDefault
precisionNoSignificant digits for the result (default: 10)
variablesNoNamed values to substitute into the expression, e.g. { x: 2, y: 255 }. Keys must be valid variable names.
expressionYesA mathematical expression, e.g. '2 * (12 + sqrt(255))^2'. Use * for multiplication and ^ for exponentiation.

TDQS

B3.3/5.0
Behavior3/5

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

With no annotations, the description carries the full burden of behavioral disclosure. It reveals supported operations, array literals, and variable-passing mechanics, but omits the return format (e.g., number vs array), error behavior for invalid expressions, and how precision affects the result.

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

Conciseness4/5

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

The description is a single dense paragraph with no wasted words; the first sentence states purpose, followed by operators, functions, constants, variables, and an example. While the long function list could be better structured with bullet points, it is still efficient and front-loaded.

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?

For a tool with three parameters and no output schema, the description thoroughly covers input syntax and capabilities. However, it does not explain the return value shape (especially for array operations) or edge-case behavior, leaving some gaps for a complex tool.

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% for all three parameters, providing a baseline of 3. The description adds meaningful semantics by explaining how to use the 'variables' parameter (e.g., { x: 2 }) and by detailing valid expression syntax with an example, exceeding the baseline.

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

Purpose4/5

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

States 'Evaluate a mathematical expression in one call' with a clear verb and resource. The extensive list of operators, functions, and constants further clarifies the tool's exact scope. However, it does not explicitly differentiate from sibling tools simplify and derivative, so it stops short of a perfect score.

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

Usage Guidelines2/5

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

The description provides rich 'how-to' guidance (supported operators, functions, variables, and an example) but no 'when-to-use' guidance. It does not mention alternatives like simplify or derivative or indicate scenarios where evaluation is preferred over them.

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

simplifySimplify ExpressionA

Simplify a mathematical expression algebraically (collect like terms, fold constants). Free variables stay symbolic; values passed in 'variables' are folded in as known constants. Note: simplification is heuristic — e.g. 'x/x' simplifies to 1 (dropping x != 0) — and it does not expand products or factor polynomials.

ParametersJSON Schema
NameRequiredDescriptionDefault
variablesNoKnown values to fold into the expression, e.g. { x: 2 }. Keys must be valid variable names.
expressionYesA mathematical expression to simplify, e.g. '3*x + 2*x' or 'x^2 + 2*x + 1'.

TDQS

A4.7/5.0
Behavior5/5

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

With no annotations provided, the description fully carries the transparency burden. It discloses heuristic behavior, the edge case of dropping constraints like x != 0 in 'x/x' simplifying to 1, and the tool's limitations (no expansion/factoring). This is rich behavioral context beyond the schema.

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 concise, front-loaded with the action, and uses every sentence meaningfully. The note with a concrete example ('x/x' simplifies to 1) and explicit non-behaviors is efficient and well-structured.

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

Completeness5/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 and no output schema, the description is complete. It covers purpose, behavior, limitations, and parameter semantics, and it distinguishes itself from sibling tools. No critical information is missing for an agent to select and invoke it correctly.

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 100%, so baseline is 3. The description adds meaning beyond the schema by explaining that free variables stay symbolic while values in 'variables' are folded in as constants, clarifying the intended interaction of the two parameters. This goes slightly beyond the schema's existing descriptions.

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 function: 'Simplify a mathematical expression algebraically (collect like terms, fold constants).' It specifies the resource (mathematical expression) and the operation, and distinguishes it from siblings like 'evaluate' and 'derivative' by indicating it does not expand products or factor polynomials.

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 on when to use the tool (for algebraic simplification) and what not to expect ('does not expand products or factor polynomials'). It implies behavior with variables ('values passed in 'variables' are folded in as known constants') but does not explicitly name alternatives like 'use evaluate for numeric results,' so it stops short of explicit when/when-not guidance.

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

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

  1. 3 tool updatesv1.0.0
    • First observedderivative
    • First observedevaluate
    • First observedsimplify

TDQS

A4.1/5.0

Scored across 3 tools

Disambiguation5/5

Each tool has a clearly distinct purpose: evaluate computes numeric results, simplify performs algebraic simplification, derivative computes symbolic derivatives. There is no overlap or ambiguity between them.

Naming Consistency5/5

All tool names are single, lowercase imperative-style verbs (evaluate, simplify, derivative) that accurately describe their actions. The naming pattern is perfectly consistent.

Tool Count5/5

Three tools is an appropriate, well-scoped size for a focused math evaluation server. Each tool provides a meaningful core capability without unnecessary bloat.

Completeness4/5

The set covers evaluation, simplification, and differentiation, which are the most common symbolic math operations. It lacks symbolic integration, equation solving, or advanced algebraic manipulation, but these are reasonable gaps for a 'safe' math server.

Maintenance

ActivityMaintained
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • F
    license
    Not graded
    quality
    D
    maintenance
    A simple Model Context Protocol server that evaluates mathematical expressions like 'sqrt(25) + 2**3' sent by MCP clients, with secure evaluation that only allows math functions/constants.
    -
  • A
    license
    A
    quality
    C
    maintenance
    A secure MCP server for evaluating mathematical expressions with grammar validation, function whitelisting, and sandboxed execution. It provides tools for expression evaluation, variable management, and resources for grammar and function documentation.
    6
    20
    MIT
  • A
    license
    B
    quality
    C
    maintenance
    High-precision mathematics server for MCP clients, providing exact integer arithmetic, symbolic derivatives, and numerical calculus via LaTeX-style input.
    6
    7
    2
    MIT
  • A
    license
    Not graded
    quality
    A
    maintenance
    Evaluate, simplify, and differentiate mathematical expressions via MCP. Provides a single tool for arithmetic, algebra, and symbolic differentiation with secure sandboxing.
    85
    1
    Apache 2.0