# SageMath [Health: Active]

**Category:** 👨‍💻 Code Execution  
**Repository:** https://github.com/XBP-Europe/sagemath-mcp  
**GitHub Stars:** 18  
**Views:** 1  
**Installs:** 0  
**Upvotes:** 0  
**Directory Page:** https://allmcps.com/mcp/sagemath

## Description
Stateful SageMath MCP server with 33 symbolic math tools and a sandboxed Sage session per client.

## Tools
Capabilities this server exposes over MCP:

- **solve_equation** — Solve an equation or system of equations
- **matrix_multiply** — Multiply two matrices and return the result as nested lists
- **matrix_operation** — Linear algebra on one matrix: determinant, inverse, eigenvalues, rank, reduced row echelon form, transpose. Prefer this over evaluate_sage.
- **boolean_algebra_operation** — Boolean polynomials over GF(2): evaluate, list variables, degree, and zero/one tests. Prefer this over evaluate_sage for boolean algebra.
- **polynomial_ring_operation** — Polynomial ring operations: construct rings and compute Groebner bases, ideals, quotients
- **differentiate_expression** — Differentiate an expression with respect to a variable
- **integrate_expression** — Integrate an expression (indefinite or definite with bounds)
- **limit_expression** — Compute the limit of an expression
- **series_expansion** — Compute a Taylor/Laurent series expansion
- **solve_ode** — Solve an ordinary differential equation of any order, returning the general solution with arbitrary constants. Prefer this over evaluate_sage.
- **symbolic_sum** — Closed form of a symbolic sum or product over an index variable, including infinite series. Prefer this over evaluate_sage for summations.
- **vector_calculus_operation** — Vector calculus operations: gradient, divergence, curl, laplacian
- **evaluate_sage** — Run SageMath code in a persistent session; variables persist across calls. Caller code is deny-by-default -- ordinary mathematics is allowed, but imports, external CAS interfaces and file/display/persistence calls are refused.

LAST RESORT for a single self-contained calculation: a dedicated tool exists for most of those and should be preferred, because it validates arguments and returns a typed result instead of a repr string. One exception overrides that steer -- the dedicated tools evaluate in a FRESH namespace and cannot see variables you defined here, so any multi-step workflow that builds an object once and then explores it (a graph and its invariants, a number field, a matrix decomposition) belongs in evaluate_sage across as many calls as it takes. For a one-off, reach for one of these first:

- calculus: differentiate_expression, integrate_expression, limit_expression, series_expansion, symbolic_sum, solve_ode
- algebra: solve_equation, simplify_expression, expand_expression, factor_expression, find_root
- linear algebra: matrix_operation (determinant, inverse, eigenvalues, rank, rref, transpose), matrix_multiply
- discrete: number_theory_operation, combinatorics_operation (binomial, partitions, catalan, fibonacci, bell), graph_operation, group_operation
- specialised: elliptic_curve_operation, coding_theory_operation, polynomial_ring_operation, boolean_algebra_operation, geometry_operation, vector_calculus_operation
- data: statistics_summary, distribution_operation
- plots: plot_expression, plot3d_expression, plot_multi_expression

Use evaluate_sage only for what those do not cover, for example:

Transforms: var('t s'); laplace(sin(t), t, s); inverse_laplace(1/(s^2+1), s, t)
Modular arithmetic: Mod(17, 5); power_mod(3, 100, 97)
Recurrences: var('n'); f = function('f'); desolve_rec(f(n+2)-f(n+1)-f(n), f, [0, 1])
Continued fractions: continued_fraction(pi).convergents()[:10]
Number fields: K.<a> = NumberField(x^3 - 2); K.class_number()
Any multi-step work that builds on values defined earlier in the same session, since the dedicated tools cannot see them.

- **calculate_expression** — Evaluate a SageMath expression and return numeric/string forms
- **simplify_expression** — Simplify a mathematical expression
- **expand_expression** — Expand a mathematical expression
- **factor_expression** — Factor a mathematical expression or integer
- **find_root** — Find a numeric root of an expression or equation in a given interval
- **evaluate_sage_streaming** — Execute SageMath code and stream intermediate print() output line by line. Final result is returned as usual.
- **check_sage_health** — Probe whether SageMath evaluation works right now: starts (or reuses) the workspace's worker, evaluates 1+1, and reports readiness and latency. Reports failure in the result instead of erroring, so it is always safe to call
- **lookup_sage_doc** — Documentation links for a SageMath name, plus whether this server offers that name to evaluate_sage caller code
- **number_theory_operation** — Number theory: primality testing, integer factorisation, the next prime above n, gcd and lcm. Prefer this over evaluate_sage for any of these.
- **combinatorics_operation** — Combinatorics: binomial coefficients, permutations, combinations, integer partitions, factorial, Catalan, Fibonacci and Bell numbers. Prefer this over evaluate_sage for any of these.
- **graph_operation** — Graph theory: create named graphs and compute properties (chromatic_number, is_connected, diameter, etc.)
- **group_operation** — Group theory: construct groups and query properties (order, is_abelian, center, etc.)
- **elliptic_curve_operation** — Elliptic curves over Q: rank, torsion order, discriminant, j-invariant, conductor and generators, from Weierstrass coefficients. Prefer this over evaluate_sage for curve invariants.
- **coding_theory_operation** — Error-correcting codes: length, dimension, minimum distance, rate and generator matrix for Hamming and generalized Reed-Solomon codes. Prefer this over evaluate_sage for code parameters.
- **plot3d_expression** — Plot a 3D surface of a two-variable expression as a rendered image
- **plot_multi_expression** — Plot multiple expressions overlaid on a single 2D graph, as a rendered image
- **plot_expression** — Plot an expression and return it as a rendered image (PNG or SVG)
- **geometry_operation** — Computational geometry on point sets: euclidean distance, polygon area, polytope volume, convex hull vertices and convexity tests. Prefer this over evaluate_sage for these.
- **reset_sage_session** — Reset the SageMath session state for the current MCP session
- **interrupt_sage_session** — Interrupt a running Sage computation while keeping variables defined so far
- **cancel_sage_session** — Cancel any running Sage computation and restart the worker
- **start_sage_session** — Start a named Sage workspace with its own independent variables
- **list_sage_sessions** — List the named Sage workspaces belonging to this client
- **stop_sage_session** — Stop a named Sage workspace and release its worker
- **statistics_summary** — Descriptive statistics for a list of numbers: mean, median, population and sample variance and standard deviation, min and max. Prefer this over evaluate_sage for summary statistics.
- **distribution_operation** — Probability distribution operations: PDF, CDF, quantile, mean, variance, sampling
- **verify_claim** — Independently re-check a stated mathematical claim and report how far the evidence goes: proved, refuted, supported or undecided.

Use this to verify your own algebra before presenting it. The claim is a single comparison in Sage syntax -- an equality, an inequality, or anything that evaluates to True/False:

  integral(x^2/(e^x-1), x, 0, oo) == 2*zeta(3)
  sin(x)^2 + cos(x)^2 == 1
  pi < 22/7
  e^pi != pi^e

The check climbs a ladder: Sage's symbolic prover, the exact difference ((lhs-rhs).simplify_full().is_zero()), exact arithmetic over QQbar/AA when the claim is constant, then certified interval arithmetic and numeric sampling over the free variables. Verdicts are honest by construction: 'proved' and 'refuted' are exact decisions ('refuted' always exhibits its counterexample or certified enclosure); 'supported' means the numeric evidence is consistent with the claim without proving it, and says how many samples at what precision; 'undecided' means every rung was inconclusive -- it never means false.

Exactness is never assumed. Decimal literals are read exactly (0.1 means 1/10, never the 53-bit double), and a comparison whose operands are machine floats (RR/RDF/CC, an .n() result) is reported as 'supported' over inexact numbers, never as an exact proof -- state it over ZZ/QQ/QQbar or symbolically for an exact verdict. The session's active assumptions (assume(x > 0), assume(x, 'integer')) are honored: a sampled counterexample must lie inside the stated domain, and any verdict that relied on an assumption names it in the evidence.


## Claude Desktop Quick Installation
Install path detected from listing signals. Uses `uvx` (confidence: high):

```json
"mcpServers": {
  "sagemath": {
    "command": "uvx",
    "args": ["--python","3.12","--from","sagemath-mcp[passagemath]","sagemath-mcp"]
  }
}
```

## Documentation

## What SageMath MCP server does

SageMath MCP server exposes a mathematical subset of SageMath through the Model Context Protocol. It covers symbolic calculus, equations, polynomial rings, Boolean algebra over GF(2), linear algebra, ordinary differential equations, number theory, combinatorics, graph and group theory, elliptic curves, coding theory, statistics, vector calculus, and rendered 2D or 3D plots.

The server is stateful per MCP client. Values assigned during one Sage evaluation remain available in later calls from that client, which makes it suitable for workflows such as constructing a matrix and then examining several of its properties, or defining a number field before querying its invariants.

## How it works

A client sends tool calls over MCP. Dedicated operation tools validate common mathematical requests and return structured results for tasks such as matrix operations, root finding, integration, graph properties, and code parameters. `evaluate_sage` runs Sage code in the client’s persistent session and returns the result; `evaluate_sage_streaming` additionally sends intermediate `print()` output as it is produced.

The evaluation policy is deny-by-default. Ordinary mathematical Sage code is allowed, while imports, external computer algebra interfaces, and file, display, or persistence operations are refused. `check_sage_health` starts or reuses the worker, evaluates a basic expression, and reports readiness and latency. `lookup_sage_doc` provides documentation links for Sage names and indicates whether a name is available to caller code.

## Setup and configuration

The recommended installation uses Python 3.12 with the `passagemath` extra:

```bash
pip install "sagemath-mcp[passagemath]"
sagemath-mcp
```

The default transport is stdio. Streamable HTTP can be enabled on a local port:

```bash
sagemath-mcp --transport streamable-http --port 8314
```

`uvx --python 3.12 --from "sagemath-mcp[passagemath]" sagemath-mcp` runs the package without a permanent installation. The Python 3.12 requirement is important for the documented wheel-based setup. macOS and Linux are supported; Windows has partial native support, with WSL or the container recommended.

A container image is available for stronger isolation. The documented deployment binds HTTP to loopback, uses a read-only filesystem with temporary filesystems, drops capabilities, enables no-new-privileges, and applies process and memory limits. A separate `-passagemath` image supports both amd64 and arm64. The HTTP server authenticates no clients, so it should not be exposed beyond a trusted environment.

## Tools and capabilities

- Solve equations and ordinary differential equations, and compute derivatives, integrals, limits, series, and symbolic sums.
- Simplify, expand, factor, evaluate, and find numeric roots of expressions.
- Multiply matrices and calculate determinants, inverses, eigenvalues, rank, reduced row echelon form, and transposes.
- Work with polynomial rings, ideals, quotients, Boolean polynomials, number theory, combinatorics, graphs, groups, elliptic curves, and error-correcting codes.
- Compute vector-calculus operations, statistics and distributions, and render single, multiple, or three-dimensional plots.
- Use persistent Sage code for transformations, recurrences, continued fractions, number fields, modular arithmetic, and other multi-step calculations.

## Limitations and notes

Dedicated tools run in fresh namespaces, so they cannot access variables created through `evaluate_sage`. Use the persistent evaluator when later steps depend on earlier definitions. For a single supported calculation, the dedicated operation is generally preferable because it validates arguments and returns a typed result rather than a representation string.

The Sage policy restricts access to non-mathematical capabilities but is not an operating-system security boundary. Running the package with local privileges is intended for trusted use; untrusted input, shared hosts, and multi-tenant deployments should use the hardened container setup. The bundled desktop package installs the Sage runtime through `uv` on first launch and is available for macOS and Linux.

_Full upstream README: https://allmcps.com/mcp/sagemath/readme_

