mathematica-wstp
Summary: The schema exposes persistent Wolfram Language evaluation, notebook read/edit/evaluate workflows, headless rendering, kernel/status administration, symbol inspection, batching, and derivation checking, but it does not expose the README-advertised replay, supervisor, recording/finalization, or dependency-verification tools/actions.
Evaluate arbitrary Wolfram Language code in a stateful kernel, with timeout abort that preserves definitions.
Abort a running evaluation or administer the kernel: state, restart, subkernels, reap, and separate
abort.Inspect server, kernel, installation, and orphaned-kernel status.
Open/create/list/info/save/close
.nbnotebook sessions.List/read notebook cells with style filters, pagination, and optional content.
Evaluate one cell, range, or document-order cell span, with detail modes, timeout, and stop-on-error.
Insert/write or delete notebook cells.
Render expressions, cells, or notebooks headlessly, with DPI and group controls; render only, not evaluate.
Inspect/get/set/clear
Globalsymbols, including pattern/list filtering and system-symbol inclusion.Run several server tool calls in one batch round trip.
Read
.nbfiles from disk without opening a notebook session in outline/markdown/Wolfram/plain/JSON modes.Verify a step-by-step derivation chain, with assumptions and timeout.
Read built-in usage guides by topic.
Allows AI agents to execute Wolfram Language code in a persistent Mathematica kernel, manage and replay notebooks, render typeset mathematics and graphics headlessly, abort runaway evaluations without losing state, and verify symbolic derivations.
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., "@mathematica-wstp Integrate that, and stop if it takes more than ten seconds."
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.
DISCLAIMER: The code is LLM generated, so there is always room for improvement. So treat this as a functional implementation of an architecture that enables one to use LLM agents in a fully headless containerised environment, that work with long-duration stateful Wolfram kernels for complex research calculations that may even span days.
P.S. I know the README is a bit verbose, but please remember that this is meant more for the agent than for the user.
Mathematica MCP over WSTP
Auditable execution for agent-driven symbolic computation in Mathematica.
An agent can always ask a computer algebra system for an answer. The harder problem is to figure out what actually happened: which cell ran, in which kernel, whether an interrupt came from the user or the code itself, whether an output followed from this run or another one, and whether work survived when the client disappeared. After all, an agent's own report of what it did is not hard evidence for what actually transpired. Which has to do with the fact that all generative models can, and do lie.
This server is built around that problem.
The motivating workflow
Many research workflows are not centered on one notebook or one long interactive session. A more common pattern is hub-and-spoke work:
┌── computational session A
│
main research ─┼── computational session B
session │
└── computational session CThe hub is the session where the larger research problem is being developed and integrated.
The spokes are short-term computational investigations. They do not need to communicate with one another directly. Each may have its own notebook, kernel state, assumptions, intermediate results, and failure history. Each spoke can be used for investigating specific questions that emerged naturally in the course of research in the hub, and would require a Mathematica-driven workflow to adequately address them.
A harness like Claude Code enables agentic message passing across sessions, and the user can also prompt in any session to read up the transcript of another one, and also look up the artifacts generated therein. One of these sessions could be the hub, and the others can play the role of spokes. The artifacts must be generated in a zero trust manner - they should not change depending on the choice of the harness, model, model-effort, etc.
A typical workflow:
Work in the main research session.
Reach a question that benefits from a separate symbolic calculation.
Open a separate session with its own stateful kernel and notebook.
Perform the calculation there, including exploratory attempts and corrections.
Finalize the result into a durable notebook or artifact.
Return to the main session.
Read the auxiliary session's transcript and inspect its finalized computational record.
Use the result in the larger line of reasoning.
Several such investigations may happen sequentially or concurrently.
Role of the MCP
In this model, the computational system is not primarily a graphical notebook frontend. The primary working surface may be an agent harness, terminal, editor, or research conversation. The notebook is still important, but as a durable scientific record, not necessarily as the place where all interaction happens.
That makes several properties more important than GUI integration:
a long-lived stateful kernel;
explicit ownership of that kernel;
the ability to interrupt runaway work without discarding useful state;
a durable identity for each scientific execution;
clear recovery after a client or session disappears;
notebook records that can be inspected later from another session;
reproducible finalization into a self-contained artifact;
provenance strong enough that one session can rely on results produced in another.
The goal is therefore not merely to let an agent execute code in a computer algebra system. It is closer to let independent computational sessions behave like small scientific laboratories whose results can later be inspected, independently verified, and incorporated into a larger research process.
A computational session can be thought of as a temporary laboratory:
temporary laboratory
= agent session
+ stateful kernel
+ notebook
+ execution record
+ generated artifactsRoles of the transcript and the notebook
The transcript and the notebook serve different purposes.
Transcript
explains what the auxiliary session concluded
and why it considered the result relevant.
Notebook / artifact
records what was actually computed.The transcript is the reasoning-level handoff. The notebook or artifact is the computational evidence. A robust workflow needs both.
This becomes especially important when one session consumes a result produced by another. The receiving session should not have to trust a sentence such as "the other session found that this identity holds." It should be possible to inspect the durable calculation behind that statement.
Related MCP server: jupyter-kernel-mcp
Advantages of a headless design
A GUI-centric workflow is excellent when the human and agent are collaborating inside one visible notebook. A headless MCP becomes attractive when the unit of work is instead:
research session
↕
computational session
↕
stateful kernel
↕
durable notebook / artifactThis makes it natural to run several independent investigations without forcing them into one interface or one global kernel state. Each computational session can remain isolated, while the main research session decides which conclusions and artifacts to bring back.
That separation also reduces accidental state coupling. Rather than sharing invisible kernel state between investigations, results move between sessions explicitly through notebooks, artifacts, transcripts, and recorded execution evidence. Even if sessions stop, the results computed while they were running must be preserved as demanded by the user.
The same architecture could also be useful for a single long-running session. The hub-and-spoke workflow explains why features like persistent kernels, recovery, audit trails, and durable notebook finalization matter, but it is not a requirement for using the server.
The execution model in one minute
There are three levels to keep apart.
A persistent Wolfram kernel. Definitions and package state survive from one tool call to the next.
A notebook replay record.
replayruns executable cells one at a time, giving each one an identity and recording the plan in a durable manifest before execution begins.Optional supervisor ownership. The default server owns its kernel. With the supervisor selected, a separate process owns it, so a client can disappear while the computation continues.
Alongside these, integrity recording turns a session of evaluate calls into a notebook that is checked against a ledger and re-run in a fresh kernel; see Recording a computation.
A few terms appear throughout the documentation:
ordinal: the nth
InputorCodecell, counting only executable cells. It is stable when output cells are inserted or deleted; raw notebook indices are not.manifest: the replay-side record written to disk before the first child runs. It records the intended run and the progress of its cells.
execution token / request id: identities attached to one cell execution.
idempotency key: a stable key for an intended child execution, so a reconnecting client can refer to the existing work rather than accidentally creating a duplicate.
reconcile: inspect a previous replay after interruption and distinguish completed, still-running, never-submitted, changed-source, and output-state cases.
backend: the component that owns execution: either this process's direct kernel or the separate supervisor-owned kernel.
recorder ledger: the on-disk record of a recording: one entry per recorded cell, with its source fingerprint and how its evaluation ended.
The distinction between ordinal and index matters immediately. Evaluating an input can insert an output cell, shifting every later index. "The seventh input cell" remains the seventh input cell.
What a replay buys you
For ordinary one-off evaluation, use evaluate. For a span where cell-by-cell identity does not matter, evaluate_cells is the simpler baseline. For long-running or auditable notebook work, use replay.
A replay provides:
one execution identity per executable cell;
a manifest persisted before the first cell is submitted;
per-child timeout policy and progress;
output-to-execution provenance;
detection when the source cell has changed underneath an existing run;
reconciliation after interruption instead of guessing where to resume.
With the supervisor selected, reconciliation also survives loss of the client that originally submitted the work. The original MCP call does not survive a client/session exit; the scientific computation can. A new client asks the ledger what happened by durable key and continues from there.
Recording a computation
When a calculation is built up through evaluate calls rather than replayed from an existing notebook, recording keeps the evidence:
notebooks(action="create", path="calc.nb", record=True)
evaluate("<< MyPackage`") # each call becomes a cell in calc.nb
evaluate("result = ...")
notebooks(action="save")
notebooks(action="finalize") # re-run in a fresh kernel, check, seal
notebooks(action="close")Every recorded cell is written to the notebook, read back, fingerprinted and entered in the recorder ledger before its code runs, and the notebook file is saved before and after it runs. While recording, every other way to change kernel state is refused, and any failed check stops the run rather than letting an unverifiable cell through. finalize copies the notebook, re-runs it in a fresh kernel, compares the copy with the ledger, and fails if a cell gives a message it did not give when recorded, which usually means it leaned on something outside the record, such as a file that has changed. It also compares each cell's result with the one recorded: a result that differs, or is missing, stops the seal, unless the cell was recorded with volatile=True (a timing, say) or the difference is accepted afterwards, in writing. For now the model can do either by itself; both are planned to need the user's approval. A cell recorded with evaluate(code, expect="True") is a checkpoint, whose fresh result must also match the expectation; a checkpoint can never be accepted. Every recording starts in a fresh kernel: the notebook is saved, the kernel restarted and the notebook reopened, so nothing defined before the recording can reach it. If even the fresh kernel holds definitions or packages, from its own startup files, recording warns and keeps the list in the ledger; with require_fresh_kernel=True it refuses to start instead. A successful finalization seals the run. The finalized notebook shows typeset outputs and formatted Print cells, as a desktop run would.
Later, notebooks(action="verify_record", path=...) checks a finalized file against its ledger and tells an edit to its text or outputs from a change to the recorded code. The ledger sits next to the file, so someone who can edit both can make them agree: a successful finalize therefore returns anchors, fingerprints of the file and the ledger, to keep where the recording session cannot rewrite them (a commit pushed to a remote, or a message to whoever reviews the run). Given back to verify_record, they catch any later edit to either; they cannot help against someone who can also edit the place they were kept.
The details are in docs/agent-guide.md.
Why use WSTP
WSTP provides an evaluation channel and a separate out-of-band message channel. That lets the server interrupt a kernel that is currently busy without destroying the kernel merely to regain control.
That gives four practical properties:
Interrupt a running evaluation and preserve state. A timeout or
abort()targets the evaluation rather than replacing the whole kernel.Distinguish a dead link from a slow computation. Link failure becomes a typed failure rather than an indefinite wait.
Keep process ownership explicit. Subkernels are tracked and can be closed without throwing away the master kernel's definitions.
Observe control separately from scientific output. The execution layer can record that a user requested an abort even when Wolfram code catches that interrupt and returns a normal value.
The architecture and its two channels are described in docs/architecture.md.
Quick start
You need Mathematica 14 or newer (15 recommended) and uv. There is no compiler step and no Wolfram SDK to build; the transport binds to the WSTP library that ships with Mathematica.
git clone https://github.com/sudeepan/mathematica-mcp-wstp.git
cd mathematica-mcp-wstp
uv venv --python 3.12 .venv
uv pip install --python .venv/bin/python -e .
claude mcp add --scope user mathematica-wstp -- "$PWD/.venv/bin/mathematica-wstp"Restart your client and try a small evaluation.
--scope usermatters.claude mcp adddefaults to--scope local, which registers the server for one directory only. Check from somewhere else (cd /tmp && claude mcp list) if a server seems to vanish outside the project.
The installation, kernel and WSTP library are discovered automatically, including relocated installs reachable only through a symlink on PATH. Override them with MATHEMATICA_WSTP_KERNEL, MATHEMATICA_WSTP_INSTALL, or MATHEMATICA_WSTP_LIB.
What it looks like in use
"Integrate that, and stop if it takes more than ten seconds."
evaluate("Integrate[Sqrt[1 + x^4], x]", timeout=10)
=> timed_out: true
kernel: "alive"
kernel_state: "intact - the kernel answered a probe after the abort""Replay this notebook so I can resume if something interrupts us."
notebooks(action="open", path="analysis.nb")
replay(action="run", timeout=300)
=> run_id: ...
executed: 276
failed: 0
execution_timeout_seconds: 300
manifest: .../.mcp-replays/....jsonThe timeout is per executable cell. If one cell is expected to run for hours, set that value explicitly rather than inheriting the default.
"The client died while a long cell was running. What happened?"
With the supervisor selected:
replay(action="reconcile")
=> c1 COMPLETE
c2 STILL_RUNNING
c3 NEVER_SUBMITTEDSTILL_RUNNING is not an error. It means the scientific evaluation is alive without the original client attached.
"Show me what cell 39 looks like."
render(action="cell", index=39)
=> [typeset PNG from a headless front end]Choosing the right notebook path
Use replay when the work is long, interruptible, or needs an audit trail. Use evaluate_cells when you deliberately want one span-level operation and do not need durable per-cell identity.
replay addresses executable cells by ordinal, not raw notebook index. Writing outputs mutates the document, so indices move during the run.
Before replaying an unfamiliar notebook, run notebooks(action="dependencies") to discover which files it reads and writes
and classify them automatically. The fresh-agent procedure in docs/replaying-a-notebook.md is designed for exactly this case.
Work that lasts hours or days
By default, this server owns its kernel. If the owning client/server process is killed, the kernel goes with it. While a call runs, the server sends a progress message every 15 seconds (MATHEMATICA_WSTP_PROGRESS_SECONDS changes this), so a client that ends silent calls keeps waiting for a long one.
For work that must outlive the client, deliberately opt into the supervisor:
supervisor(action="start")
supervisor(action="use")Then open the notebook and start the replay. A notebook belongs to the kernel that opened it, so choose the backend before opening the document.
The supervisor protects against client loss, not against a kernel or machine failure. Domain-level checkpoints are still necessary for work whose recomputation cost is measured in hours or days.
See docs/long-running-work.md.
Tools
Sixteen consolidated tools rather than a wide flat surface:
Tool | Purpose |
| Run Wolfram Language in the persistent kernel |
| Interrupt the running evaluation, keeping all state |
|
|
| Kernel, installation and tracked-process health |
|
|
| List or read cells of an open notebook |
| Replay a span of cells, state carrying between them |
| Per-cell replay with identity and a resumable manifest |
| Insert, replace or delete a cell |
| Typeset an expression, rasterise a cell, export a notebook |
| Inspect, set or clear the kernel's `Global`` symbols |
| A kernel in its own process, outliving this one |
| Run several tools in one round trip |
| Check a chain of expressions step by step: proved, disproved with a numerical witness, or undecided |
| Read a |
| Usage notes by topic |
render drives the Wolfram front end with -platform offscreen: no display and no X server are required. Rendering never owns scientific evaluation; that stays on the kernel link where interrupt and liveness semantics are defined.
For Wolfram Language documentation, use Wolfram's MCP
This server answers questions about your kernel, your state, and your documents. It is not a replacement for Wolfram's reference documentation.
Run Wolfram's own MCP server alongside it and use WolframLanguageContext for questions about built-ins, options, and language behavior. It uses a different kernel and cannot see definitions created here.
What the language means → Wolfram's MCP. What your scientific session contains → this server.
Documentation
Document | Start here when... |
You want to drive the server correctly and efficiently, or record a computation | |
You are replaying a notebook or onboarding a fresh agent | |
A cell may run for hours/days or must survive a dropped client | |
You want the execution, replay and supervisor model | |
You want the observed ways a plausible result can still be wrong | |
You want measured costs and trade-offs | |
You want to run the tests |
guide(topic=...) carries the short form inside the server:
workflow · abort · errors · notebooks · state · parallel · performance.
Requirements
Mathematica 14 or newer, with the WSTP library that ships with it
Python 3.10+
Linux or macOS. Windows is untested.
One third-party Python dependency:
mcp
Not for untrusted input or multi-tenant hosts. An evaluation is arbitrary code execution.
Tests
tests/run_all.sh # every suite; needs Mathematica
tests/run_all.sh --no-kernel # only what runs without itGitHub Actions runs the recorder suites on every push and pull request, on a machine without Mathematica: tests that need a Wolfram kernel are skipped there, with that reason. Run every suite locally before a push. docs/testing.md says what runs where, and why the full suites do not run on GitHub. The suites use their own __main__ runners and do not require pytest. Point MATHEMATICA_WSTP_TEST_NOTEBOOK at any .nb to exercise notebook tools against a real document; those checks are skipped when it is unset.
Available Tools
14 toolsabortA
Interrupt the evaluation the kernel is running right now. The kernel survives with all state intact. Use this instead of kernel(action='restart') for a runaway computation -- restart destroys every definition.
Inputs: no named parameters. Returns: result
batchA
Run several of this server's tools in one round trip. ops: [{"tool": "evaluate", "args": {"code": "1+1"}}, ...]. Stops at the first failure unless stop_on_error is false. Useful for a fixed setup sequence; not a substitute for one compound Wolfram expression.
Inputs: ops (required), stop_on_error. Returns: result
cellsB
List or read cells of an open notebook. Use style to filter (e.g. 'Input'). Cell indices are positions in the document and are what evaluate_cells takes.
Inputs: limit, style, offset, notebook, +1 more. Returns: result
edit_cellsC
Insert or delete a cell. actions: write(content,style,position) | delete(index).
Inputs: action (required), index, style, anchor, +3 more. Returns: result
evaluateA
Evaluate Wolfram Language code in the persistent kernel. State carries between calls. On timeout the evaluation is ABORTED but the kernel and all its definitions survive, so you can retry a smaller piece.
Inputs: code (required), timeout. Returns: result
evaluate_cellsA
Evaluate notebook cells in document order, in the persistent kernel, with state carrying between them. Give either index, or from_+to for a range. A long replay can be interrupted with abort(). Large ranges come back summarised (counts, failures, messages, slowest cells); set detail='full' to force per-cell output, or 'summary' to force the compact form.
Inputs: to, from_, index, detail, +3 more. Returns: result
guideB
Usage notes for this server. topics: workflow | abort | errors | notebooks | performance.
Inputs: topic. Returns: result
kernelA
Kernel administration. actions: state | restart | abort | subkernels | reap. 'restart' clears ALL definitions and closes subkernels properly; prefer abort() for a merely slow evaluation.
Inputs: action. Returns: result
notebooksC
Notebook sessions over .nb files on disk. actions: open(path) | create(title,path) | list | info | save(path) | close. Cells are evaluated from their original stored boxes, so nothing is lost in translation.
Inputs: path, title, action, notebook. Returns: result
read_notebook_fileA
Read a .nb file from disk without opening a kernel session for it. modes: outline (headings only) | markdown | wolfram (code cells only) | plain | json. Use notebooks(action='open') instead when you intend to evaluate anything.
Inputs: path (required), mode, limit, offset. Returns: result
renderA
Render with the Wolfram front end, headlessly: typeset an expression, rasterise a notebook cell, or export a notebook. actions: expression(code) | cell(index) | export(path) | available. This RENDERS only -- it never evaluates through the front end; use evaluate() for that. Export renders what is visible, so collapsed cell groups export collapsed; pass open_groups=True for the whole document.
Inputs: dpi, code, path, index, +3 more.
statusB
Server, kernel and installation status, plus any orphaned kernels.
Inputs: no named parameters. Returns: result
varsB
Inspect or change the kernel's Global` symbols. actions: list | get(name) | set(name,value) | clear(name) | clear_all. Use this to see what a notebook replay actually defined, or to clear one symbol without restarting.
Inputs: name, value, action, pattern, +1 more. Returns: result
verify_derivationB
Check a chain of expressions step by step: each step must equal the one before it. Returns the first step that does not follow. steps are Wolfram expressions as strings, in order.
Inputs: steps (required), timeout, assumptions. Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 14 tools
Most tools map cleanly to different resources or actions: kernel evaluation, notebook/cell access, rendering, variable inspection, and batch orchestration. There are a couple of overlapping boundaries—abort vs kernel(action='abort') and status vs kernel(state)—but the descriptions generally clarify which one is intended.
Names are readable and mostly action-oriented, but the convention is mixed: bare verbs (evaluate, abort, render), bare nouns (kernel, status, notebooks, cells, vars), and underscore compounds (evaluate_cells, read_notebook_file, verify_derivation). It is not chaotic, but there is no single predictable verb_noun pattern.
Fourteen tools is within the well-scoped range and each tool addresses a genuinely distinct part of the server's purpose: persistent evaluation, kernel admin, notebook sessions, cell operations, rendering, symbol inspection, batching, and guidance. The count is substantial but not padded.
The surface covers the main lifecycle for both the persistent kernel (evaluate, abort, restart, vars) and notebooks (open/create/list/save/close, read cells, write/delete cells, evaluate cells), plus rendering and derivation verification. There are no obvious dead ends or missing core operations for this domain.
Related MCP Connectors
Persistent cloud workspaces for AI agents: run commands, edit files, use git and a browser.
Build Apps and run code in 30 languages — sandboxed, with persistent sessions for agent loops.
Persistent Linux computers for AI agents: desktop, signed-in browser, vault, apps and shell.
Hosted runtime for persistent agent teams, durable workflows, memory, schedules, and goals.
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-
- AlicenseAqualityDmaintenanceEnables AI agents to execute Python, TypeScript, and JavaScript code in persistent Jupyter kernels with stateful variables and imports across interactions.763 PyPI4MIT
- AlicenseCqualityCmaintenanceEnables AI agents to run Mathematica code, control live notebooks, and verify results through natural language.8261 PyPI57MIT
- FlicenseNot gradedqualityDmaintenanceEnables AI agents to execute Jupyter notebook cells with persistent kernel state, output persistence, and structured JSON control surface.2-