simple-sage-mcp
Use it to run and manage Sage/Python code and files in persistent, session-based kernel jobs.
Execute Sage or raw Python in named kernel sessions; state persists per session and Sage preparsing is optional.
Start long-running
execjobs with non-cancellingtimeout_s, then collect incremental output withpollusingsince/wait_s.Reset a session's namespace, drop idle sessions, and inspect kernel/session/job status, errors, PID, uptime, and logs.
Interrupt a runaway computation with SIGINT while keeping session state, or force-stop the whole kernel when necessary, losing all sessions.
Run existing files inline with
run_fileusing auto/bash/python/sage/exec interpreters, args, stdin, cwd, and timeout; receive exit code, duration, stdout, and stderr.Jobs run one at a time per kernel; additional jobs may queue or be refused when the kernel is busy.
Provides a persistent SageMath kernel that agents can use to execute Sage code, poll long-running computations, interrupt or reset sessions, inspect kernel status, run script files, and process SageMath/Jupyter notebooks.
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., "@simple-sage-mcp factor 2^128 - 1 and show me the result"
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.

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-mcpThree 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.shIf 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 (orserver.py); optionally"env": {"SAGE_BIN": "/path/to/sage"}. The server also looks forsagenext to the interpreter running it, so a script in Sage'sbinfinds 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
.pyor.sagefile and run it withrun_file, not only in variables.Client-side timeouts. Hosts often time out a call before the default 2400 s wait. Pass a
timeoutbelow the host's limit: the call returnsstatus: runningwith ajob_id, the job keeps running, andjob_statusreports it until it ends.Remote-only hosts need a local bridge: this is stdio, and it starts a local kernel.
Tools
Tool | Purpose |
| Run Sage code in the kernel namespace and return its output |
| Run a |
| Read a job that |
| Stop the running computation; the kernel keeps its state |
| 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:execandrun_filereject them asinvalid_source. One kernel and one lock, so one job runs at a time; a second call getskernel_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, andipykernelin the python of your Sage. The pip routes install all three;install.shinstallsfastmcp(jupyter_clientandipykernelcome 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-inSPEC.md covers the architecture, the concurrency model, the constants and the test layout.
License
MIT. See LICENSE.
Available Tools
7 toolsdropA
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
Scored across 7 tools
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.
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.
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.
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
Related MCP Connectors
Build Apps and run code in 30 languages — sandboxed, with persistent sessions for agent loops.
Persistent cloud workspaces for AI agents: run commands, edit files, use git and a browser.
Operate Linux, macOS and Windows from your LLM. Every action runs through an auditable allowlist.
On-demand GPU nodes for agents: create nodes, run commands, and submit jobs, billed by the minute.
Related MCP Servers
- FlicenseAqualityDmaintenanceAllows LLMs to execute Wolfram Language code in a secure, session-based environment by providing an interface to interact with a Wolfram Mathematica kernel.34-
- AlicenseBqualityDmaintenanceEnables execution of SageMath mathematical computations through a local SageMath installation. Provides tools to check SageMath version and evaluate SageMath scripts with configurable timeouts and error handling.311MIT
- AlicenseAqualityDmaintenanceEnables AI agents to create, read, edit, and execute Jupyter notebook cells, manage kernels, and connect to remote Jupyter servers.2128 PyPIMIT
- AlicenseAqualityDmaintenanceEnables AI agents to execute Python, TypeScript, and JavaScript code in persistent Jupyter kernels with stateful variables and imports across interactions.791 PyPI4MIT