SageMath MCP Server
Server Configuration
Describes the environment variables required to run the server.
| Name | Required | Description | Default |
|---|---|---|---|
| SAGEMATH_MCP_STARTUP | No | Sage code executed during session bootstrap. | from sage.all import * |
| SAGEMATH_MCP_IDLE_TTL | No | Seconds of inactivity before a session is culled. | 900 |
| SAGEMATH_MCP_MAX_STDOUT | No | Maximum characters of stdout returned per call. | 100000 |
| SAGEMATH_MCP_PURE_PYTHON | No | When set to 1, load math stdlib instead of Sage modules. | unset |
| SAGEMATH_MCP_SAGE_BINARY | No | Path to the sage executable. | sage |
| SAGEMATH_MCP_EVAL_TIMEOUT | No | Per-evaluation timeout in seconds. | 30 |
| SAGEMATH_MCP_SHUTDOWN_GRACE | No | Grace period before a stuck worker is terminated. | 2 |
| SAGEMATH_MCP_SECURITY_ENABLED | No | Enable/disable AST-based code validation. | true |
| SAGEMATH_MCP_FORCE_PYTHON_WORKER | No | Use the pure-Python worker (helpful for tests/CI). | false |
| SAGEMATH_MCP_SECURITY_MAX_SOURCE | No | Maximum source length in characters. | 8000 |
| SAGEMATH_MCP_SECURITY_ALLOW_IMPORTS | No | Permit import statements when set to true. | false |
| SAGEMATH_MCP_SECURITY_FORBID_GLOBAL | No | Block global statements when true. | true |
| SAGEMATH_MCP_SECURITY_MAX_AST_DEPTH | No | Maximum AST depth allowed. | 75 |
| SAGEMATH_MCP_SECURITY_MAX_AST_NODES | No | Maximum AST node count allowed. | 2500 |
| SAGEMATH_MCP_SECURITY_LOG_VIOLATIONS | No | Emit warnings when code is blocked. | true |
| SAGEMATH_MCP_SECURITY_ALLOWED_IMPORTS | No | Comma-separated allowlist of importable modules. | math,cmath,statistics,base64,io,sage,sage.all |
| SAGEMATH_MCP_SECURITY_FORBID_NONLOCAL | No | Block nonlocal statements when true. | true |
| SAGEMATH_MCP_SECURITY_ALLOWED_IMPORT_PREFIXES | No | Comma-separated prefixes treated as safe namespaces. | sage. |
Instructions
Guidance the server publishes about itself, which clients place ahead of the tool catalog so the model reads it before choosing anything.
You are connected to a dedicated SageMath runtime. Each MCP session gets its own
stateful Sage process, so variables, functions, and assumptions persist between calls
to evaluate_sage and the helper tools. Typical workflows include:
General symbolic/numeric computation via
evaluate_sage(supports optional LaTeX).High-level helpers:
calculate_expression,solve_equation,differentiate_expression,integrate_expression,matrix_multiply, andstatistics_summary.Session management:
reset_sage_sessionclears state;cancel_sage_sessionrestarts the worker; monitoring data is exposed viaresource://sagemath/monitoring/metrics.Checking your own algebra:
verify_claimre-checks a stated comparison through a proof ladder and answers proved/refuted/supported/undecided, always with its evidence. Use it before presenting a derived identity as fact.
Guidance for best results:
Always provide explicit Sage code; avoid relying on ambient imports beyond standard Sage libraries. Use
var('x')/matrix(...)etc. inside the code snippet.Chain computations within the same MCP session to reuse definitions (e.g., assign
f =and callevaluate_sageagain to operate onf).Long-running jobs emit progress heartbeat events roughly every 1.5 seconds. You can adjust timeouts via the
timeoutparameter.Capture stdout only when needed; disabling it speeds up large iterations.
The security policy rejects arbitrary imports,
eval/exec, the indirection helpers (getattr,sage_eval), dunder access, and theos/sys/subprocess/shutil/socket/pathlibmodules -- wherever those names are read, not only where they are called. It is defence in depth against accidents, not a boundary against adversarial code; the container is the boundary. If you hit a security violation, rewrite the computation with Sage primitives instead.
Capabilities
Features and capabilities supported by this server
Protocol revision2025-11-25
| Capability | Details |
|---|---|
| tools | {
"listChanged": true
} |
| logging | {} |
| prompts | {
"listChanged": true
} |
| resources | {
"subscribe": false,
"listChanged": true
} |
Tools
Functions exposed to the LLM to take actions
| Name | Description |
|---|---|
| solve_equationB | Solve an equation or system of equations |
| matrix_multiplyB | Multiply two matrices and return the result as nested lists |
| matrix_operationA | Linear algebra on one matrix: determinant, inverse, eigenvalues, rank, reduced row echelon form, transpose. Prefer this over evaluate_sage. |
| boolean_algebra_operationA | Boolean polynomials over GF(2): evaluate, list variables, degree, and zero/one tests. Prefer this over evaluate_sage for boolean algebra. |
| polynomial_ring_operationC | Polynomial ring operations: construct rings and compute Groebner bases, ideals, quotients |
| differentiate_expressionA | Differentiate an expression with respect to a variable |
| integrate_expressionA | Integrate an expression (indefinite or definite with bounds) |
| limit_expressionC | Compute the limit of an expression |
| series_expansionA | Compute a Taylor/Laurent series expansion |
| solve_odeA | Solve an ordinary differential equation of any order, returning the general solution with arbitrary constants. Prefer this over evaluate_sage. |
| symbolic_sumA | Closed form of a symbolic sum or product over an index variable, including infinite series. Prefer this over evaluate_sage for summations. |
| vector_calculus_operationC | Vector calculus operations: gradient, divergence, curl, laplacian |
| evaluate_sageA | 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:
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. = 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_expressionB | Evaluate a SageMath expression and return numeric/string forms |
| simplify_expressionC | Simplify a mathematical expression |
| expand_expressionC | Expand a mathematical expression |
| factor_expressionC | Factor a mathematical expression or integer |
| find_rootA | Find a numeric root of an expression or equation in a given interval |
| evaluate_sage_streamingA | Execute SageMath code and stream intermediate print() output line by line. Final result is returned as usual. |
| check_sage_healthA | 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_docA | Documentation links for a SageMath name, plus whether this server offers that name to evaluate_sage caller code |
| number_theory_operationA | Number theory: primality testing, integer factorisation, the next prime above n, gcd and lcm. Prefer this over evaluate_sage for any of these. |
| combinatorics_operationA | Combinatorics: binomial coefficients, permutations, combinations, integer partitions, factorial, Catalan, Fibonacci and Bell numbers. Prefer this over evaluate_sage for any of these. |
| graph_operationB | Graph theory: create named graphs and compute properties (chromatic_number, is_connected, diameter, etc.) |
| group_operationA | Group theory: construct groups and query properties (order, is_abelian, center, etc.) |
| elliptic_curve_operationA | 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_operationA | 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_expressionB | Plot a 3D surface of a two-variable expression as a rendered image |
| plot_multi_expressionA | Plot multiple expressions overlaid on a single 2D graph, as a rendered image |
| plot_expressionA | Plot an expression and return it as a rendered image (PNG or SVG) |
| geometry_operationA | 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_sessionB | Reset the SageMath session state for the current MCP session |
| interrupt_sage_sessionA | Interrupt a running Sage computation while keeping variables defined so far |
| cancel_sage_sessionA | Cancel any running Sage computation and restart the worker |
| start_sage_sessionA | Start a named Sage workspace with its own independent variables |
| list_sage_sessionsA | List the named Sage workspaces belonging to this client |
| stop_sage_sessionB | Stop a named Sage workspace and release its worker |
| statistics_summaryA | 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_operationB | Probability distribution operations: PDF, CDF, quantile, mean, variance, sampling |
| verify_claimA | 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. |
Prompts
Interactive templates invoked by user choice
| Name | Description |
|---|---|
| prove_and_verify | Prove a mathematical identity or claim, then confirm it independently with the verify_claim tool. |
| solve_and_check | Solve a problem step by step, then sanity-check the result with the tools before presenting it. |
| explore_object | Construct a mathematical object once and explore its properties across calls in one persistent session. |
Resources
Contextual data attached and managed by the client
| Name | Description |
|---|---|
No resources | |
TDQS
Scored across 40 tools
Most tools have distinct domain prefixes (calculus, linear algebra, number theory), but several boundaries blur: evaluate_sage vs evaluate_sage_streaming vs calculate_expression all execute/evaluate Sage code, and factor_expression overlaps with number_theory_operation's integer factorization. The 'operation' suffix on eleven tools makes their exact scope harder to distinguish at a glance.
The majority follow verb_noun (solve_equation, integrate_expression, start_sage_session), but there are notable deviations: the eleven 'X_operation' tools are noun_noun, matrix_multiply is noun_verb, and series_expansion/symbolic_sum are noun phrases. All names are snake_case and readable, so the inconsistency is moderate rather than chaotic.
Forty tools is well above the 25+ threshold and will burden an agent's tool-selection step, even though SageMath's breadth justifies many of them. Several 'operation' tools could be consolidated (e.g., one linear_algebra tool) without losing clarity.
The surface covers calculus, algebra, linear algebra, number theory, combinatorics, graph/group theory, elliptic curves, coding theory, geometry, statistics, distributions, plotting, and session management. Missing dedicated tools like Laplace transforms or matrix addition are reachable through evaluate_sage, so there are no dead ends; only minor gaps remain.