Skip to main content
Glama
simple-sage-mcp

simple-sage-mcp

by JGCoelho

simple-sagemath-mcp

simple-sagemath-mcp

An MCP server that gives an agent a persistent SageMath kernel — one warm Sage process, one namespace, five tools — and runs .py and .sage files in it.

Before you start: you need SageMath

This server does not bundle, download, or install SageMath. It drives a SageMath already on the machine and cannot work without one; if you work with Sage, you almost certainly have it. Check with sage --version; what actually matters is that Sage's python can import sage.all.

Everything targets the python of that Sage: the server imports Sage's preparser (sage.repl.preparse) to validate code, and the kernel it starts is that python, which imports sage.all. So sage -pip is the only pip that can install it; pipx, uvx, and a plain pip install into an unrelated venv cannot be used: they build an environment on another python, where the Sage import fails.

Related MCP server: MCP SageMath Server

Install

Three routes, from fewest lines to most; each ends with a config block for your host.

One line — install from git with Sage's pip:

sage -pip install git+https://github.com/JGCoelho/simple-sagemath-mcp

Three lines — clone, then install from the checkout; add --upgrade later:

git clone https://github.com/JGCoelho/simple-sagemath-mcp.git
cd simple-sagemath-mcp
sage -pip install .          # later: sage -pip install --upgrade .

Four lines, no pip — let the script in this repo do the checks: it finds Sage, installs the dependencies it is missing, and prints the block ready to paste. It installs no package and changes no config file.

sage --version
git clone https://github.com/JGCoelho/simple-sagemath-mcp.git
cd simple-sagemath-mcp
./install.sh

If sage is not on PATH, name it: SAGE_BIN=/opt/sage/sage ./install.sh. On an externally managed (Debian/Ubuntu, PEP 668) sagemath, use sage -pip install --user ., which puts the console script in ~/.local/bin instead of next to sage. The third route installs nothing: the config names the python of your Sage and the repo's server.py. Stuck? Paste this README to your coding agent and ask it to install the server and write the config.

Configure your host

Point the host at the absolute path of the console script, because many hosts run MCP servers with a sanitized environment:

{"mcpServers": {"sage": {
  "command": "/path/to/sageenv/bin/simple-sagemath-mcp",
  "args": ["--directory", "/path/to/your/work"]}}}

The code is the sagemcp package under src/; both pip routes install it and create that script. When the scripts directory is not on the host's PATH, name the interpreter instead:

{ "command": "/path/to/sageenv/bin/python3", "args": ["-m", "sagemcp"] }

From a checkout, name server.py itself ("args": ["/path/to/repo/server.py"]); python -m server works there too. --directory changes the server's working directory before the kernel starts, so a relative path in the agent's code points at your work.

Other hosts

Same command; only the file and the top-level key differ. Codex (~/.codex/config.toml):

[mcp_servers.sage]
command = "/path/to/sageenv/bin/simple-sagemath-mcp"
args = ["--directory", "/path/to/your/work"]

VS Code (.vscode/mcp.json, note servers):

{"servers": {"sage": {"type": "stdio", "command": "/path/to/sageenv/bin/simple-sagemath-mcp", "args": ["--directory", "/path/to/your/work"]}}}

What differs across hosts

  • Hidden PATH. Use the absolute path to the console script (or server.py); optionally "env": {"SAGE_BIN": "/path/to/sage"}. The server also looks for sage next to the interpreter running it, so a script in Sage's bin finds Sage unaided.

  • One kernel per server process. Each session gets its own namespace; a restart, a crash, or a recycled process loses it, so keep code you want again in a .py or .sage file and run it with run_file, not only in variables.

  • Client-side timeouts. Hosts often time out a call before the default 2400 s wait. Pass a timeout below the host's limit: the call returns status: running with a job_id, the job keeps running, and job_status reports it until it ends.

  • Remote-only hosts need a local bridge: this is stdio, and it starts a local kernel.

Tools

Tool

Purpose

exec

Run Sage code in the kernel namespace and return its output

run_file

Run a .py or .sage file in the same namespace and return its output

job_status

Read a job that exec or run_file started: its status and output so far

interrupt

Stop the running computation; the kernel keeps its state

restart

Restart the kernel and wipe the namespace

exec and run_file run as jobs. A call that outlasts its timeout (default 2400 s) returns status: running, a job_id, elapsed and the output so far, and the job keeps the kernel. The timeout bounds the wait, not the job: nothing stops a job for running long. Poll job_status with the id until it reports done, error or interrupted. While a job holds the kernel, other calls return kernel_busy; they are not queued. The server keeps the running job and the latest finished job; an older id returns unknown_job, and a restart drops every record.

interrupt keeps the namespace; the job it stopped ends with execution_failed and KeyboardInterrupt. restart ends a running job as interrupted, with kernel_died as its error. run_file resolves a relative path against --directory and accepts only those two suffixes. It reads the file once, as UTF-8 with a leading byte-order mark dropped; other bytes are invalid_source, and a traceback names the file.

Every tool returns one envelope, with error: null on success. SPEC.md §12 has the per-tool behaviour and the full table of error codes.

Limits

  • No magics and no ! shell escapes: exec and run_file reject them as invalid_source. One kernel and one lock, so one job runs at a time; a second call gets kernel_busy, it is not queued.

  • This is not a sandbox. The kernel runs the code the agent sends, with your user permissions and access to your files.

Requirements

  • SageMath 10.x (tested with 10.8 on Linux); the server code itself needs Python 3.10+.

  • fastmcp, jupyter_client, and ipykernel in the python of your Sage. The pip routes install all three; install.sh installs fastmcp (jupyter_client and ipykernel come with Sage).

Tests

Run from this directory with the python of your Sage:

PY=/path/to/sage/env/bin/python3
PATH="$(dirname "$PY"):$PATH" "$PY" -m unittest discover -s test -v
SAGE_BIN=/path/to/sage "$PY" -m unittest discover -s test -v   # sage not on PATH
PYTHONPATH=test "$PY" -m unittest test_packaging -v             # one file (no __init__.py)
SAGE_MCP_LONG=1 PATH="$(dirname "$PY"):$PATH" "$PY" test/test_long_exec.py -v  # opt-in

SPEC.md covers the architecture, the concurrency model, the constants and the test layout.

License

MIT. See LICENSE.

Available Tools

7 tools
dropA

Free idle sessions; refuses one with a queued/running job (kept, and the job id is reported). all=true drops every idle session.

Inputs: all, sessions.

execA

Run Sage/Python in the long-lived kernel: stdout, then the repr of the last expression (or '(no output)'). Code runs on the kernel's main thread, one job at a time, so cysignals Sage code works; state persists per session. timeout_s is NOT a computation limit: on expiry you get the partial output and a job id, and the job keeps running (collect it with poll). timeout_s=0 returns at once. A submitted job waits behind the running one ("[queued: another job is running]"); if that one holds the GIL the submit itself is refused after ~10 s ("[kernel busy ...]", the job was not submitted) -- check status or interrupt, then retry.

Inputs: code (required), session, preparse, timeout_s.

interruptA

SIGINT the running computation: the job fails with KeyboardInterrupt and the session KEEPS its state -- the first thing to try for a runaway job. Refused when the running job belongs to another MCP client; a no-op when idle: SIGINT can never kill the kernel. force=true is the last resort instead: stop the whole kernel (graceful shutdown, then SIGTERM, then SIGKILL), losing every session's variables -- for a computation that ignores SIGINT, e.g. a wedged C-level loop. The next exec starts a fresh kernel and says so; if the signal fails the state files are kept and the pid reported, so a live kernel is never orphaned.

Inputs: force.

pollA

Collect a job started by exec. since = the offset the previous call printed (0 to start), so you get only new output. wait_s blocks until the job finishes or that many seconds pass (0 = return immediately, the default).

Inputs: job_id (required), since, wait_s.

resetA

Empty a session's namespace but keep the session (see drop).

Inputs: session.

run_fileA

Run a file that already exists and return its output inline: exit code, duration, stdout and stderr. Nothing is copied or stored -- the file you name is the file that runs, with cwd = its own directory. lang=auto guesses from the extension and honours a #! for executables; lang=python uses Sage's own interpreter (so from sage.all import * works) and lang=sage shells out to sage. A non-zero exit or a timeout is an error, with the output attached; the timeout kills the whole process group.

Inputs: path (required), cwd, args, lang, +2 more.

statusB

Kernel state (running / busy / not running) with pid and uptime, one line per session with its name count, active jobs, the last error, the log path.

Inputs: no named parameters.

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    A3.9/5.0

    Scored across 7 tools

    Disambiguation4/5

    Most tools map to distinct lifecycle operations: interrupt vs. drop, reset vs. drop, and poll vs. status are well separated. The main overlap is that exec and run_file both execute code, so an agent must rely on the descriptions to choose the right context.

    Naming Consistency4/5

    All names are lowercase and terse, with no casing inconsistency. However, the set mixes imperative verbs, one compound name (run_file), an abbreviation (exec), and a noun (status), so it is not a fully predictable verb_noun pattern.

    Tool Count5/5

    Seven tools is well within the healthy range for a kernel/session management server. Each tool earns its place by covering a distinct role: execute, run file, collect output, interrupt, inspect status, reset namespace, and drop sessions.

    Completeness4/5

    Core lifecycle coverage is strong: execution, async polling, interruption/kill, status, namespace reset, session drop, and file execution are all present. Minor gaps exist, such as no explicit session-creation or queued-job-cancel operation, but agents can work around them with exec, interrupt, and status.

    Maintenance

    ActivityMaintained
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers