safe-mathjs-mcp
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@safe-mathjs-mcpSimplify the expression (x^2 - 4)/(x - 2)"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
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 a numeric expression. Supports variables and configurable precision. |
| Symbolic simplification (collect like terms, fold constants). Free symbols stay symbolic. |
| 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 inspectorTo 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 # verifyBy 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
noderesolves for the harness's shell (check withnode --version).Passing env vars — harnesses that support an
environmentfield (Zed, Cline) can setCALC_TIMEOUT_MSthere. 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 inspectin 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))^2precision(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.333333333333333333333333333333simplify
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 + 1Note: 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") → 0Other 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 |
|
Trigonometry |
|
Rounding & min/max |
|
Number theory |
|
Statistics |
|
Linear algebra |
|
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:
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.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
No code execution — mathjs is a pure AST interpreter;
eval/new Functionare never used, and the string-processing functions (evaluate,parse,compile,format,print) are not in the allowlist.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 aDisallowed ...error.Result checks — complex numbers (scalar or inside arrays) and NaN are rejected after evaluation.
Bounded input — expressions are capped at 512 characters; variables must be valid identifiers and prototype-polluting names (
__proto__,constructor,prototype) are rejected.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 |
|
| 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, evaluationExtending 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 toolsderivativeSymbolic 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.
| Name | Required | Description | Default |
|---|---|---|---|
| variable | Yes | The variable to differentiate with respect to, e.g. 'x'. | |
| expression | Yes | A mathematical expression to differentiate, e.g. 'x^3 + sin(x)'. |
TDQS
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.
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.
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.
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.
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.
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'
| Name | Required | Description | Default |
|---|---|---|---|
| precision | No | Significant digits for the result (default: 10) | |
| variables | No | Named values to substitute into the expression, e.g. { x: 2, y: 255 }. Keys must be valid variable names. | |
| expression | Yes | A mathematical expression, e.g. '2 * (12 + sqrt(255))^2'. Use * for multiplication and ^ for exponentiation. |
TDQS
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.
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.
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.
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.
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.
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.
| Name | Required | Description | Default |
|---|---|---|---|
| variables | No | Known values to fold into the expression, e.g. { x: 2 }. Keys must be valid variable names. | |
| expression | Yes | A mathematical expression to simplify, e.g. '3*x + 2*x' or 'x^2 + 2*x + 1'. |
TDQS
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.
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.
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.
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.
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.
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.
3 tool updates
v1.0.0- First observed
derivative - First observed
evaluate - First observed
simplify
TDQS
Scored across 3 tools
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.
All tool names are single, lowercase imperative-style verbs (evaluate, simplify, derivative) that accurately describe their actions. The naming pattern is perfectly consistent.
Three tools is an appropriate, well-scoped size for a focused math evaluation server. Each tool provides a meaningful core capability without unnecessary bloat.
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
Related MCP Connectors
Math.js MCP — wraps the mathjs.org API (free, no auth)
Safe scientific calculator MCP for numeric expressions
This MCP server enables users to perform scientific computations regarding linear algebra and vect…
Educational MCP server with 17 math/stats tools, visualizations, and persistent workspace
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceA 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.-
- AlicenseAqualityCmaintenanceA 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.620MIT
- AlicenseBqualityCmaintenanceHigh-precision mathematics server for MCP clients, providing exact integer arithmetic, symbolic derivatives, and numerical calculus via LaTeX-style input.672MIT
- AlicenseNot gradedqualityAmaintenanceEvaluate, simplify, and differentiate mathematical expressions via MCP. Provides a single tool for arithmetic, algebra, and symbolic differentiation with secure sandboxing.851Apache 2.0