codecalc
codecalc is an offline, self-hosted MCP server that lets an AI agent execute code, perform exact and symbolic math, solve logic problems, and verify correctness claims.
Execute code in 31 languages in a sandbox, with stdout/stderr, exit codes, timing, memory usage, verdicts (OK/TLE/MLE/OLE/RTE), and optional network blocking.
Run persistent sessions for stateful Python/Node REPL use, multi-file programs, workspace file management, artifacts, and workspace snapshots.
Run background jobs with submit/inspect/cancel, and stream execution progress and partial output.
Do exact arithmetic including rationals, thresholds, percentages, percent change, statistics, percentiles, collision probability, byte sizes, durations, epoch times, and unit conversion.
Inspect numbers in programmer mode: bit analysis, bit operations, integer widths, base representation, radix conversion, and binary64 float representation.
Do symbolic math: evaluate expressions, solve equations/systems, simplify/factor/expand, compute limits and calculus forms, compare algebraic equivalence, and perform matrix operations.
Solve logic problems: build truth tables and check SMT-LIB2 satisfiability with Z3, including models and proof grades.
Analyze and benchmark code: estimate Big-O statically, measure growth empirically, trace Python execution line by line, and determine branch reachability with Z3.
Verify claims: prove translations behave identically, prove optimizations are correct and significantly faster, compare languages on edge cases, and extract/run functions standalone.
Manage the environment: list languages/providers, install packages, check runtime status, and optionally update runtimes.
Enables running Bun JavaScript/TypeScript code with sandboxing, resource limits, and stdout/stderr capture.
Enables compiling and running C++ code with sandboxing, resource limits, and output capture.
Enables running Deno TypeScript/JavaScript code with sandboxing, resource limits, and output capture.
Enables running Elixir code with sandboxing, resource limits, and output capture.
Enables running Erlang code with sandboxing, resource limits, and output capture.
Enables compiling and running Fortran code with sandboxing, resource limits, and output capture.
Enables running Haskell code with sandboxing, resource limits, and output capture; scaffolds a temporary Nix project.
Enables compiling and running Kotlin code with sandboxing, resource limits, and output capture.
Enables running Lua code with sandboxing, resource limits, and output capture.
Enables running Perl code with sandboxing, resource limits, and output capture.
Enables running PHP code with sandboxing, resource limits, and output capture.
Enables running Python code with sandboxing, resource limits, output capture, and a persistent REPL session.
Enables running Ruby code with sandboxing, resource limits, and output capture.
Enables compiling and running Rust code with sandboxing, resource limits, and output capture.
Enables running SQLite SQL scripts with sandboxing, resource limits, and output capture.
Enables compiling and running Swift code with sandboxing, resource limits, and output capture.
Enables running TypeScript code (via the TypeScript compiler) with sandboxing, resource limits, and output capture.
Enables compiling and running Zig code with sandboxing, resource limits, and output capture.
Enables running Zsh shell scripts with sandboxing, resource limits, and output capture.
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., "@codecalc what is 0.1 + 0.2 exactly?"
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.
codecalc — universal code & logic calculator for AI models
codecalc is an offline, self-hosted MCP server that gives an AI agent a calculator, a code runner, and a logic checker — so it gets a correct answer instead of a guessed one. It runs code in 31 languages, does exact symbolic math, solves SMT/logic problems, and measures complexity, all exposed as 51 MCP tools.
Fastest path: uvx 'codecalc[full]' setup --write registers codecalc with your MCP client automatically. New to MCP, or want more detail first? See QUICKSTART.md, or the Install section below.
Three things nobody else offers together cleanly:
Offline-core — ships no model, no API key, no gateway, no telemetry. The core opens no sockets; network access is opt-in and only where a specific tool's job needs it (the Piston provider,
install_package, the runtime-update tools, executed code unlessno_net, and a one-time in-process grammar download on firstanalyze_complexity— full breakdown in the network-boundary table below).Safe execution of untrusted code — an opt-in strict isolation boundary (gVisor+Docker on Linux, AppContainer on Windows) layered above the default rlimit sandbox, fail-closed and attested.
Verification tools —
verify_translationproves a port to another language behaves identically,verify_optimizationproves an optimization preserved behavior, andz3_checkproves or refutes logic with an SMT solver.
When to use codecalc
Use it when you want a free, local, private, hardened code-runner and verifier that an MCP agent can call directly — no vendor account, no cloud spend, nothing leaving the machine except where a tool's job explicitly requires it.
Reach for something else when you want managed cloud scale instead of self-hosting (a hosted sandbox like E2B or Modal), or when you're not self-hosting at all and the model vendor's built-in code interpreter already covers what you need.
Related MCP server: Alexandria MCP
codecalc vs. the alternatives
codecalc is not a general cloud sandbox and not a vendor code interpreter. It overlaps with several things and beats them in only one narrow place — forcing a model to measure a claim instead of asserting it. Where that isn't what you need, one of these is the better tool, and this table says so plainly.
You want… | Better fit | Why |
To just run some Python/JS quickly, zero setup | Your model vendor's built-in interpreter | Already there, already sandboxed, nothing to install. Anthropic's code-execution tool has internet access "completely disabled" and cannot install packages at runtime; OpenAI's hosted containers have no outbound network access by default, with an org-level |
Heavy or multi-tenant workloads, managed scale | A cloud sandbox (E2B, Modal, Daytona) | Per-tenant Firecracker/gVisor isolation codecalc does not claim by default |
Pure arithmetic or symbolic math, nothing else | A small calculator or SymPy MCP | Lower token cost; none of the 31-language runtime machinery |
A model to stop guessing numbers, equivalence, and speedups — locally, privately, with graded evidence | codecalc | Exact rationals, |
Do not reach for codecalc if you need multi-tenant or network-exposed isolation (its threat model is explicitly single-operator, local, stdio), if zero-setup convenience matters more than measurement, or if a hosted interpreter already covers your case. It earns its keep only when the correctness of the claim — not just "it ran" — is the point.
Install
Quickstart with codecalc setup
The fastest path to a working MCP connection, without reading the rest of this section:
uvx 'codecalc[full]' setup # prints what it would do — nothing on disk changes
uvx 'codecalc[full]' setup --write # applies it: merges your client's config, copies the skillIt detects which MCP client is installed (Claude Desktop, Claude Code,
Cursor, VS Code, Zed — pass --client=NAME if none or several are found),
reuses codecalc doctor's own backend/extras/grammar-cache checks, prints the
exact config block in that client's own JSON shape with absolute paths
already filled in, runs two real canaries (execute_code, evaluate_expression)
to prove the connection would work, and ends in one verdict: ready /
degraded / not-ready. --write is the only mode that changes anything —
it MERGES the codecalc entry into your existing client config (every other
server stays exactly as it was) and backs up the original to
<path>.codecalc-bak first. codecalc --help lists every subcommand.
Published ascodecalc 0.13.0 on PyPI (pip install codecalc) and the
codecalc-exec 0.13.0 executor on crates.io
(#91). Every release
artifact carries a keyless sigstore build-provenance attestation — verify
one with gh attestation verify <file> --repo The-40-Thieves/codecalc; PyPI
wheels additionally carry PEP 740 attestations.
Where to find codecalc
Where | What you get | Link |
PyPI |
| |
crates.io | the | |
GitHub Releases | wheels for every platform, the executor binaries, the | |
MCP registry (official) | the | |
Smithery | hosted listing and one-click client config | |
Glama | hosted listing and the score badge above | |
MCPB (Claude Desktop) | the drag-and-drop bundle, attached to every GitHub Release | see GitHub Releases, above |
Docker MCP Catalog | the | submitted as docker/mcp-registry#5025; listed at hub.docker.com/mcp/server/codecalc once merged |
Not yet listed: PulseMCP and mcp.so do not carry a codecalc entry yet; the Docker MCP Catalog entry is pending review. PulseMCP's own submission page (checked 2026-09-08) says it is not accepting new submissions and that publishing to the official MCP registry — already done, row above — is what it indexes from once submissions reopen, so there is nothing to submit there today. mcp.so takes a submission through its own form. See docs/distribution.md for the exact steps, kept there rather than here because submitting is an action for whoever runs it, not a fact about the current release.
The published install (simplest — no build step, and what most people want):
uvx 'codecalc[full]' # run it directly, no environment to manage
# or
pip install 'codecalc[full]' # into your own virtualenvFrom source, if you would rather build the executor yourself:
git clone https://github.com/The-40-Thieves/codecalc
cd codecalc
uv sync --all-extras # or: pip install -e '.[full]'
cargo build --release --manifest-path executor/Cargo.toml
mkdir -p bin # bin/ is gitignored, so a fresh clone has none
cp executor/target/release/codecalc-exec bin/
uv run codecalc doctor # verify: backend should read `rust`Without the cargo build, everything still runs on the pure-Python fallback —
doctor will say so, and the network table below says what that costs.
Why [full]. The base install is the MCP surface and the sandbox executor:
31 language runtimes, sessions, packages, ~32 MB. The symbolic half — sympy and
z3 — is 88.6 MB measured, and a caller who only runs code should not download an
SMT solver to do it. So it is an extra:
install | size | what you get |
| ~32 MB | execute_code, sessions, packages, complexity-free tools |
| +83 MB | evaluate_expression, solve, limits, truth tables, z3, units |
| +5 MB installed, +89 MB fetched on first use | analyze_complexity via tree-sitter |
| ~120 MB | everything |
Nothing fails silently: a tool whose extra is missing returns
{"ok": false, "error": "sympy is not installed. It ships in the 'symbolic' extra: pip install 'codecalc[symbolic]' ..."}, and codecalc doctor lists
which extras are present before you make a call.
Editions
Four names for the capability sets above, plus the two that live outside
pyproject.toml entirely — a Docker image and an opt-in isolation boundary.
The invariant that makes "edition" a meaningful word here: in the edition
that lists a tool, that tool is functional — never listed-but-missing-its-extra.
A tool an edition doesn't have returns the dependency_missing contract error
naming the extra that provides it (see above), not a silent failure or a
tool that appears to exist and doesn't work.
Edition | Install | What you get |
Full |
| The recommended local product: the native (Rust) executor, symbolic tools ( |
Core |
| Execution + non-symbolic tools only — the base install in the table above. Every symbolic/parsing tool is still listed by |
Docker |
| The MCP server itself, packaged to run as an ordinary container. Core-shaped by default: ships |
Strict Host | opt-in; | Not an install, a boundary: the gVisor |
codecalc doctor reports which of these you're actually running (backend,
extras present, strict_runtime prerequisites) — read it before assuming a
capability rather than after a tool call surprises you.
.github/workflows/release.yml publishes a platform-tagged wheel per target
(Linux x86_64/aarch64 musl, macOS x86_64/aarch64, Windows x86_64), each
carrying the matching codecalc-exec binary and — where the platform has
one — its --no-net shim, so executor.backend() == "rust" on install
without a manual build step. No wheel for your platform, or installed from
source instead? Everything still runs; see the network table above for what
falls back and to unenforced in that case.
Point an MCP client at the installed command. The key differs by client —
mcpServers for most, servers for VS Code, context_servers for Zed — so
these are given separately rather than as one snippet to adapt:
Claude Desktop — ~/Library/Application Support/Claude/claude_desktop_config.json
(macOS), %APPDATA%\Claude\claude_desktop_config.json (Windows) · Cursor
(.cursor/mcp.json) and Claude Code (.mcp.json) use the same shape:
{ "mcpServers": { "codecalc": { "command": "uvx", "args": ["codecalc[full]"] } } }VS Code — .vscode/mcp.json, top-level key is servers:
{ "servers": { "codecalc": { "command": "uvx", "args": ["codecalc[full]"] } } }Zed — ~/.config/zed/settings.json, key is context_servers:
{ "context_servers": { "codecalc": { "command": "uvx", "args": ["codecalc[full]"], "env": {} } } }Windows paths need doubled backslashes in JSON. If you installed into a venv
rather than using uvx, point at the interpreter directly:
{ "mcpServers": { "codecalc": {
"command": "C:\\path\\to\\venv\\Scripts\\python.exe",
"args": ["-m", "codecalc"] } } }Run codecalc doctor to print a config block with the absolute paths of your
install already filled in.
Install the skill too. The tools cannot help a model that never reaches for
them — a model confident about 0.1 + 0.2 does not feel uncertain, it feels
finished. codecalc/SKILL.md ships inside the package and says when calling is
mandatory (any non-integer, any comparison you will state, anything past 2^53,
any number stated as a claim), when it is noise (2 + 3 + 4 needs no tool), and
how results must be reported — passed: true means "equivalent on N inputs",
never "verified". codecalc doctor prints its path; copy it into your client's
skills directory. check_claims.py gates it, so it cannot name a tool that does
not exist or a field no tool returns.
Not sure what your install actually resolved? Ask it, rather than finding out from a tool call later:
codecalc doctor # or: python -m codecalc doctorThis is the install verification step. It exits 0 when the install can
execute — a writable workspace and a resolved backend — and 1 when it cannot,
so it works unchanged in a Dockerfile, a provisioning script or a CI job. A
missing optional extra or an uninstalled Haskell does not fail it: those are
facts about the host, not a broken install, and a check that goes red for them
is one people learn to ignore.
It prints the execution backend and the binary behind it, whether installs are
confined, the status of every one of the 31 runtimes, whether the workspace is
writable, and a client config block with absolute paths filled in. All of that
is otherwise discoverable only by making a tool call and reading backend,
unenforced, or a failure.
codecalc doctor --json # the same report, for scripts
codecalc doctor --deep # actually RUN each runtime, and read its version--json emits the report and nothing else, against a published schema
(docs/contract/doctor-v1.schema.json)
carrying the same contract_version and the same policy as a tool result.
Each runtime reports one of four states, and the difference between two of them is which measurement was actually taken:
state | means |
| codecalc knows the language; nothing for it resolves here |
| its command resolves and is executable — not run |
| resolves but cannot run, or was run and failed |
| actually executed here and answered — |
status_basis says which pass produced them. Without --deep nothing is ever
reported available, because nothing was executed, and claiming otherwise for a
binary that was merely found on PATH would be a stronger measurement than was
taken.
--deep is capped by one 180 s wall-clock budget shared across every runtime
probe and hello-world run; runtimes the budget cuts short stay installed and
are reported as not probed, never unhealthy.
Under --deep, a runtime whose version probe fails to spawn is unhealthy;
a version probe that times out is reported as not measured, not broken. A
nonzero exit alone only counts
when the flag used is one confirmed correct for that command (go version,
lua -v, zig version — none of them speak GNU --version, so a bare
nonzero exit there is reported as merely unmeasured, not broken). A captured
failure lands in probe_error, never in version, which holds a version
string or nothing. A compile-then-run language whose run step needs a
SECOND, different tool (kotlin: kotlinc compiles, but run launches
java directly) reports installed only when BOTH resolve; detail names
whichever half is missing.
Building the Rust core yourself, or running from a checkout? See "Build the Rust core" and "Run the server" below.
Use it from an MCP client
One-click install: both buttons register uvx codecalc[full] (the
recommended Full edition) and require uv to be installed.
The shortest version of the config above — this registers codecalc as a
stdio MCP server. The console entry point is codecalc, so uvx codecalc
launches it directly:
{
"mcpServers": {
"codecalc": { "command": "uvx", "args": ["codecalc"] }
}
}Installed with pip install codecalc instead? Point at the resolved
command with no args:
{
"mcpServers": {
"codecalc": { "command": "codecalc" }
}
}Network boundary
CodeCalc's core opens no sockets. No model gateway or telemetry is built
in. tests/test_offline.py asserts this for the top-level core modules. The
opt-in Piston provider is the deliberate exception: its wire client lives under
codecalc/provider_adapters/ and is registered only when
CODECALC_PISTON_URL is configured.
That is a claim about the package, not about every tool call, and the difference is worth stating rather than leaving a reader to discover:
layer | reaches the network? |
CodeCalc core | No HTTP client, model gateway, or telemetry. One dependency exception: |
configured Piston provider | Yes, explicitly. Calls only the operator-supplied |
| Yes, by design. It runs uv / npm / gem / cargo, which fetch from their registries. Installer hooks also run outside the sandbox — see SECURITY.md |
| Yes. They shell out to mise / rustup / swiftly / npm, which check remote versions |
code you execute | Yes, unless |
| Yes, before the sandboxed step, through the confined |
These distinctions are stated precisely on purpose: a guarantee described more broadly than it is enforced is exactly the failure mode this project works to avoid, so "offline-core" is scoped to what the structural test can actually support rather than claimed as a blanket "no network calls".
A PEP 723 block alone, with no dependencies argument, can trigger the
install above. execute_code/session_run read the block out of the source
text itself — a caller who passes no dependencies argument at all still gets
a confined uv/npm subprocess and real egress if the code they submit
happens to carry a # /// script block, whenever the refusal rule above does
not apply. This is logged distinctly (dependency_install_implicit in the
audit trail, alongside install_denied) so an operator can tell "source text
alone triggered this" from an explicit install_package/dependencies= call.
To disable it: no_net=True on the call, or a deny-network/strict
CODECALC_CAPABILITY_POLICY — either one refuses before any fetch, block or
no block. execute_code_stream and run_submit read the block the same way
execute_code does. compare_execution is the one holdout: it fans out
across several languages with no per-language install plumbing behind it, so
it REJECTS an explicit dependencies argument with a validation error
rather than approximating one, and DISCLOSES rather than silently drops an
inline PEP 723 block it finds in a snippet — that row's result carries
dependencies: {"status": "unsupported", "reason": ...} instead of
installing from it.
Two ceilings govern a dependency-bearing run, not one. The run's own
timeout bounds the sandboxed step; it says nothing about installing
dependencies FIRST, outside the sandbox. A separate, fixed budget
(codecalc.dependencies.DEFAULT_DEPENDENCY_INSTALL_BUDGET_SECONDS, 120s,
aggregate across every dependency of one run) bounds that step instead —
exceeding it refuses the run with a stamped timeout naming the budget,
before the run's own timeout clock even starts. A sessionless run's
dependency workdir is also held to a disk quota — reusing
CODECALC_SESSION_DISK_QUOTA_MB (below), the same cap a session workspace
already has — and a run that grows past it after a successful install is
refused with a stamped resource_exhausted naming the measured size and the
cap.
The grammar download, stated plainly, because it is the one that is easy to
miss. The other three paths above go through a CHILD PROCESS, which is what
tests/test_offline.py says it cannot see. This one does not:
tree-sitter-language-pack ships a ~5 MB extension and fetches each grammar on
first use, in-process, into a local cache — 28 grammars, 89 MB, about 15
seconds on a cold cache. So the first analyze_complexity call for a given
language opens a socket from inside the server.
It is verified (the pack checks a signature and raises on a checksum mismatch), it is cached, and it never happens again for that language. So the offline-core claim is scoped to steady state: this first-use grammar fetch is the one in-process exception, which is why it is called out here rather than glossed over.
For an offline or egress-restricted install, warm the cache first — it is one
command, and afterwards nothing here reaches the network. If you installed
codecalc (pip install/uvx, not a source checkout), scripts/ did not come
with it, so use the shipped console script instead:
codecalc-prefetch-grammars # installed: fetch all 28 grammars
codecalc-prefetch-grammars --print-cache-dir # installed: the directory to copyBuilding from source? The script still works and calls the same code:
python scripts/prefetch_grammars.py # fetch all 28 grammars
python scripts/prefetch_grammars.py --print-cache-dir # the directory to copycodecalc doctor reports whether that cache is populated, so this is
discoverable before it matters rather than after a tool call degrades.
Architecture (language-per-strength)
Layer | Language | Why |
Executor core ( | Rust | Sandbox + rlimits + process-group kill + JSON CLI. No |
Logic layer ( | Python | sympy (symbolic math, equation solving) and z3 (SMT) have no Rust equivalents |
MCP server ( | Python | the official |
Python orchestrates; Rust executes; sympy/z3 reason. Each layer does what it's best at. The Rust binary is preferred automatically; a pure-Python executor is the fallback if the binary is missing.
Older-computer support
No modern instruction-set requirements — rustc targets a generic CPU by default and nothing overrides it. (
executor/.cargo/config.tomlexplains why-C target-cpu=genericis deliberately NOT written there: it would be a no-op that reads like a guarantee.)Static musl builds run on any Linux regardless of glibc version:
bin/codecalc-exec-x86_64-musl,bin/codecalc-exec-aarch64-musl(~430K each; the exact size moves with every toolchain bump, so it is not pinned here)Size-optimized profile (
opt-level="z", LTO, panic=abort, stripped) — measured, not assumed: against an otherwise identicalopt-level=3build,zcame out 1.02 ± 0.26 times faster on the executor's own path (i.e. no detectable difference) while being 16% smaller. The executor spends its time in syscalls, not arithmetic, so there was nothing for a higher optimisation level to speed up.Lazy sympy/z3 imports. Both are imported on first use, so a session that only executes code never pays for them. This claimed "~40ms, not ~600ms" for a long time while being wrong in both directions: the server took 1.9s to start, and sympy was not actually lazy —
units.pyimported it at module scope andserver.pyimportsunits, so every start paid 437ms for it. Deferring that took spawn-to-first-response from 1888ms to 1243ms (measured, median of 7). The remaining ~870ms is themcpSDK's own import, which is not ours to remove.The fork-bomb measurement is taken once, and only when it is needed. Sizing
RLIMIT_NPROCmeans reading/proc/<pid>/statusfor every process on the machine. That walk used to run during argument parsing and again for every step: a C compile-and-run opened 1767 status files on a 590-process box to answer one question three times, and--lang notalanguagepaid the full cost to produce a one-line error. Measured lazily and cached, an error costs 1.1ms instead of 13.3ms and a compiled run 78ms instead of 104ms.list_languagesprobes runtime availability and reports which languages actually work on the machine (graceful degradation on minimal installs)
Build the Rust core
cd executor
cargo build --release # native
cargo zigbuild --release --target x86_64-unknown-linux-musl # static x86_64 (uses zig)
cargo zigbuild --release --target aarch64-unknown-linux-musl # static arm64
# Copy the executable AND its --no-net shim together. build.rs rebuilds the
# shim whenever blocknet.c changes, but the executor looks for it beside the
# BINARY, so installing only the binary leaves the previous shim in place — and
# a stale shim silently enforces the old policy while every "is it there?"
# check still passes. Copy both or neither.
mkdir -p ../bin # bin/ is gitignored, so a fresh clone has none
cp target/release/codecalc-exec target/release/blocknet.so ../bin/Requires: Rust 1.97+, a C compiler for the --no-net shim (the build warns and
carries on without one; on macOS, or a Linux kernel without seccomp support,
--no-net then reports itself in unenforced rather than pretending — a
Linux kernel with seccomp support enforces it in-kernel either way), and
cargo-zigbuild
for the static cross-builds (zig is used as the linker; no x86_64 GCC needed).
MCP tools (51) + MCP resources
Every session file is also exposed as an MCP resource:
codecalc://session/<session_id>/files/<path> — images render inline for the
model, text returns as text, other files download.
Graphical results in MCP Apps hosts: verify_translation and
verify_optimization also carry an MCP Apps
ui:// view (ui://verify-translation/view.html,
ui://verify-optimization/view.html) — a per-case diff table and a per-size
timing chart, respectively, rendered inline by a host that supports the
extension. Both are self-contained (inline CSS/JS, no network, no external
assets); a host without MCP Apps support sees exactly today's text/structured
result, unchanged.
Exact arithmetic & programmer-mode: exact rationals, threshold checks, bit analysis, binary64 introspection.
Tool | Description |
| EXACT arithmetic: |
| Exact threshold verdict with shortfall: |
| Exact share and percentage of PART/TOTAL (rationals accepted) |
| Exact percent change FROM_VALUE→TO_VALUE, relative to |
| mean, median, sample stdev, CV (CV > 0.2 = noise swamps the effect) |
| p50/p90/p95/p99 by nearest-rank AND interpolation; warns n<100 |
| Birthday-bound hash collision: 1e5 items/32 bits ≈ 0.69, 1e6/64 ≈ 2.7e-8 |
| Byte sizes both ways: KiB/MiB (binary) AND KB/MB (decimal) |
| Humanised duration + per-day/per-30d rates |
| Epoch s/ms/µs/ns → ISO 8601 UTC, implausible readings suppressed |
| Any base 2..36, fractions included, non-termination flagged ( |
| What binary64 actually stores: exact value, raw bits, ULP, neighbours, representable-or-not |
| Programmer-mode integer facts and operations, selected by |
| Are |
| Symbolic algebra, selected by |
Core tools
Tool | Description |
| 31 languages with extension, compile flag, runtime availability |
| Execution-provider identity, interface version, host class, and machine-readable capabilities |
| Run code in any language → stdout/stderr/exit_code/verdict (OK/TLE/MLE/OLE/RTE)/cpu_ms/peak_memory_kb; per-call limits ( |
| Provider-selected execution using the same canonical limits as |
| python3 only. Runs the same sandboxed executor |
| python3 only. Decides, with z3, which if/elif/else arms and while/for(range, static bounds) loops in ONE function can ever be taken for ANY input — |
| Submit code for background execution; returns a |
| Poll a background run: status while running, the full |
| Cancel a background run; idempotent on an already-terminal run, honest about providers that cannot cancel mid-flight |
| Persistent session; python3/node get a stateful REPL worker (variables/imports persist across calls), other languages a workspace dir |
| Session lifecycle |
| Workspace file tools, jailed to the session dir; listings support |
| Multi-file programs: execute an entry file that imports other session files (helper.py, data/...) in the workspace |
| List files created by executed code (results, images, CSVs) |
| Archive a session's workspace to a snapshot stored OUTSIDE the jailed workspace ( |
| Install packages (uv pip/npm/gem/go/cargo...) into a session or shared cache |
| Prove a port is equivalent: you write the translation, the executor runs both versions on the same inputs and reports match / diverged / inconclusive per input. A pass is graded |
| Prove an optimisation: you write the candidate, the executor confirms it still agrees with the original AND times both — accepted only if equivalent and measurably faster. Accepted is graded |
| Pull a named function + its dependency closure (imports, referenced helpers) into a standalone program and run it (ast-exact for python3, best-effort elsewhere) |
| Run the same logic in N languages on edge-case inputs (empty, zero, negative, float precision) and flag behavioral divergence |
| Dimensional unit conversion via sympy: length, mass, time, speed, energy, power, force, pressure, temperature (°C/°F/K), volume, area, data, frequency |
| 22 physical constants with values (c, h, N_A, k_B, G, g, m_e, R, ...) |
| All 140+ unit aliases for convert_units |
| Symbolic math: |
| Boolean algebra: |
| SMT-LIB2 satisfiability + model. An |
| Structured matrix ops: det/inverse/eigenvalues/transpose/rank/trace on a |
| Static Big-O estimate from code structure, parsed with tree-sitter (every supported language). Reports |
| Empirical Big-O: runs code at increasing N, fits growth curve |
| Same code across N languages side-by-side |
| Non-mutating update check: current vs latest for every language runtime, which package manager owns it, and the command that would run |
| Update runtimes. Dry-run by default ( |
Retired tool aliases
The 2026-09-08 merge (0.11.0) folded two lexically-overlapping clusters — flagged by Glama's public review as indistinguishable from a description alone — into one enum-selected tool each, keeping every mode's own parameters, annotations and result shape. The eight old names stayed registered as thin aliases for one minor release so nothing broke mid-upgrade, then were removed in 0.12.0 (CHANGELOG.md). Calling one of them now gets the MCP SDK's own unknown-tool error, not a result:
Retired name | Replacement |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Grade vocabulary
verify_translation, verify_optimization and z3_check return grade +
grade_basis (+ grade_rules_version) on top of their own result. The grade
names how strong the evidence for a success actually is; it is derived from
evidence those tools already emit, in codecalc/grades.py — the verifiers
never assign their own grade.
Grade | Means | Emitted by |
| Two independently authored programs were both actually run and their outputs agreed. |
|
| Z3 returned |
|
| Reserved: the claimed computation ran and produced the reported result, with no independent second opinion. Not currently emitted by any tool above — every one of them also clears the | — |
| Explicit non-grade for a mismatch, an inconclusive comparison, a rejected optimisation candidate, a measurement failure, a Z3 | any of the above, on a non-success |
z3_check's sat verdicts are graded ungraded, not solver_proven, even
though sat is just as decisive a verdict as unsat. The ticket's motivating
pattern is proving a property P by asserting not-P and checking unsat; a
caller running that pattern who gets sat back has learned P is FALSE, and
solver_proven on that result would let a reader who skims grade without
result mistake a counterexample for a proof. sat's grade_basis says so
explicitly: satisfiability was decided, but solver_proven is reserved for
unsat so a counterexample can never wear a proof grade. Widening sat back
into solver_proven later is additive; narrowing it after callers depend on
the wider behaviour would not be, so this ships narrow now. Full reasoning:
codecalc/grades.py's module docstring.
algebraic_equiv is deliberately NOT graded: it compares two expressions via
sympy.simplify(a - b) == 0, a CAS transformation rather than a decision
procedure with a checkable certificate, and it is one simplifier's opinion
rather than two independent implementations agreeing. None of the three
grades describes that evidence honestly.
Runtime self-update
Every language is mapped to its package manager, and codecalc can update its own runtimes:
Manager | Languages | Update command |
mise | python3, node, bun, deno, ruby, go, erlang, elixir, gleam, zig, java, kotlin, sqlite, duckdb, gradle |
|
rustup | rust (stable/nightly toolchains) |
|
swiftly | swift |
|
apt | c, c++, fortran, csharp, php, perl, lua, tcl, r, jq, bash, zsh |
|
npm | typescript/tsc |
|
uv | mojo |
|
nix | haskell (on-demand) | nothing persistent |
runtimes_status is always safe. update_runtimes refuses to mutate unless
apply=True is passed explicitly — and it only touches the package manager
that owns each language (never the Rust sandbox, which has no update powers).
One of those managers is elevated: apt updates system packages, so its command
starts with sudo. apply=True is an argument a connected model controls, so
that branch takes a second key the model does not have — the host must set
CODECALC_ALLOW_RUNTIME_APPLY=1. Without it the apt command is reported as
skipped with ok: false and the variable named, while the unprivileged managers
still run. sudo -n already fails closed where a password is required; this
covers the passwordless-sudo rule common on developer machines and CI images,
which is exactly where -n does not stop it.
Run the server
cd /path/to/codecalc && .venv/bin/python -m codecalc.server
# stdio transport — register with any MCP client
# The identical tool/resource registry over stateless Streamable HTTP:
.venv/bin/python -m codecalc.server serve-http --host 127.0.0.1 --port 8000Streamable HTTP binds to loopback by default. Bearer-token auth
(CODECALC_HTTP_TOKEN) is required for any non-loopback bind — serve-http
refuses to start on a routable address if neither it nor --oauth-issuer (below)
is set, and the static-token comparison is constant-time — and optional on
loopback, where an MCP client spawning the process is already inside the trust
boundary. Setting a token does not change the single-operator threat model: put
an authenticating reverse proxy and the stronger process/container isolation
described in SECURITY.md in front of it before exposing it beyond one
operator's own machine.
For hosted use only, serve-http also accepts --oauth-issuer URL (or
CODECALC_OAUTH_ISSUER) as an alternative to the static token — off by
default; the static-token path above is unchanged when it is unset, and
setting the variable costs nothing outside serve-http itself: doctor,
--help, serve-strict, and the bare stdio server never touch the network
over it, only serve-http's own startup does. The issuer and JWKS URLs must
be https:// unless the host is loopback (for local testing); an issuer that
is plain http:// on a real host, or cannot be reached at all, fails
serve-http's startup outright with a message on stderr rather than starting
a server no token could ever pass. Given a reachable issuer, serve-http
validates each bearer token as a JWT against that issuer's own JWKS
(RS256/ES256; the JWKS URL is discovered once from
<issuer>/.well-known/openid-configuration, or pinned with
--oauth-jwks-url) and checks its issuer, audience, expiry, and
not-before. It also serves RFC 9728 Protected Resource Metadata at
/.well-known/oauth-protected-resource/mcp, and a request with a missing or
invalid token gets WWW-Authenticate: Bearer resource_metadata="..." pointing
at it, per the MCP authorization spec (2025-06-18 and later). --oauth-audience
defaults to this server's own resource URL; --oauth-scopes "s1 s2" requires
every named scope on the token, checked by the SDK's own auth middleware. If
both a static token and an issuer end up configured at once, the issuer
wins — a request bearing the static token's exact value is rejected like any
other invalid bearer value, and a warning naming both settings is printed to
stderr at startup. codecalc runs no /authorize or /token endpoint of its
own (it is a resource server only, never an authorization server), so there is
no dynamic client registration surface here either; a 2026-07-28-era client
that needs one uses a Client ID Metadata Document against its OWN
authorization server, not against codecalc.
Point an MCP client at it:
{ "mcpServers": { "codecalc": { "command": "/path/to/codecalc/.venv/bin/python",
"args": ["-m", "codecalc.server"],
"env": {
"PYTHONPATH": "/path/to/codecalc",
"CODECALC_RUNTIME_PATH": "/path/to/mise/shims:/usr/local/bin:/usr/bin:/bin"
} } } }MCP protocol
Protocol revision 2026-07-28, on the official mcp SDK 2.0. Not fastmcp:
fastmcp 3.x pins mcp>=1.24,<2.0 and so cannot reach this revision at all.
Verifying that is less obvious than it looks. mcp.types.LATEST_PROTOCOL_VERSION
reads 2026-07-28 regardless of what a given connection negotiated, and the
same server answers on either protocol depending only on how you connect:
client | negotiated | cache hints |
|
| dropped |
|
| applied |
So tests/test_mcp_protocol.py asserts the negotiated value from a real
connection. The legacy path still works — backward compatibility is a feature —
it just must not be mistaken for the new protocol.
Worth noting for anyone reading the spec's headline change: 2026-07-28 removes
protocol-level sessions, and directs servers needing cross-call state to use
"explicit, server-minted handles passed as ordinary tool arguments". That is
exactly what codecalc's session_id already is.
The result contract
Every result carries contract_version, currently 1.6.0. The published
schema is docs/contract/result-v1.schema.json
and the policy behind it — what MAJOR/MINOR/PATCH may change, the twelve-month
deprecation window, worked success/failure/timeout examples, and the migration
path from unversioned servers — is in
docs/contract/README.md.
For in-process Python use, the supported protocol-neutral service boundary—and
the session/storage internals that are deliberately not public—is documented in
docs/embedding.md.
Two things a caller should know before reading anything else:
okmeans "ran and exited 0". A program that behaves exactly as intended and exits 3 comes backok: false,exit_code: 3,verdict: "RTE". To tell a failed program from a failed request, readverdict— a request that never reached a runtime has noverdictat all, and has acodeinstead.codeis the branch target, noterror. Eight stable values; the prose inerroris free to improve and is not a contract. An unrecognisedcodemust be treated asinternal— that is what lets a1.xclient survive a2.0.0server, though adding a code is still a MAJOR change, because the published enum is closed and a strict validator rejects the result first.Truncation reports a size, not just a flag.
output_truncatedsays output was cut;stdout_bytes/stderr_bytessay by how much — the bytes the program actually produced, before the cap. A 200 000-characterprintundermax_output_kb=1returns 1 039 bytes ofstdoutandstdout_bytes: 200001, so a caller can size a retry instead of guessing.nullthere means not measured (nothing ran); a program that printed nothing reports0.max_output_kbis one combined cap on stdout and stderr together, split fairly: each stream keeps up to half of it, and what one stream leaves unused goes to the other. A cut stream ends in a marker outside the cap:\n…[truncated]from the Python backends (the fallback and Piston), or\n...[truncated](three dots) from the Rust executor.
The schema is JSON Schema 2020-12 — the dialect MCP 2026-07-28 defaults tool
outputSchema to — so a client can validate our results with it directly.
scripts/check_contract.py regenerates it from codecalc/contract.py and fails
on a diff, and separately re-derives both backends' verdict vocabularies from
main.rs and executor.py: check_parity.py compares the two backends' key
sets and is structurally blind to a new verdict value, which would leave the
published enum short and make a strictly validating client reject a good result.
Configuration
All optional. codecalc runs with none of these set.
Variable | Default | What it does |
| (unset) | Bearer token for the Streamable HTTP transport ( |
|
| What the HTTP transport's auth metadata advertises as its own URL. Only consulted when |
| (unset) | Same as |
| this server's own resource URL ( | Same as |
| (unset) — discovered from | Same as |
| (unset) | Same as |
| the server's own | The |
|
| Override the sandbox binary. Without one, codecalc falls back to a pure-Python executor — |
| (unset) | Fail-closed: refuse to start if no usable |
|
| Default execution-provider ID. Explicit |
| (unset) | Register the non-local open-source Piston v2 provider at this absolute HTTP(S) base URL. No public service is contacted by default. |
| (unset) | Exact value for Piston's |
| (unset) | Activate the current OS's |
| (unset) | Exact value for the strict service's |
|
| Durable metadata-only journal backing |
|
| Admission cap for |
| (unset) | Permit |
|
| Where session workspaces live. Keep this codecalc-private. |
|
| How old (and untouched) a marker-less, session-shaped directory must be before |
| (unset) | Deny-by-default allowlist for |
| (unset) | Idle-expiry for stateful (python3/node) session workers: a session untouched for longer than this is reaped — worker killed via the same teardown |
|
| Per-session ceiling on total workspace disk. |
|
| Global ceiling on disk summed across every session workspace on this host — closes the gap where staying under the per-session quota by opening many sessions would otherwise be unbounded. Same enforcement points and |
|
| Per-write size ceiling for anything a session write path creates — independent of the total quotas above, so one runaway file cannot hide under a generous session/global total. A WRITE-time cap; distinct from |
|
| Per-session ceiling on the number of artifact files — catches a session writing one byte at a time into thousands of tiny files, a shape no byte-sized cap alone bounds. Only a write that creates a NEW file is checked; overwriting an existing one always succeeds regardless of the count. |
|
| Refuse a session write when the HOST's free disk space drops below this — protects the host even when every quota above is generous, since a shared host can be driven low by something that is not a codecalc session at all. Measured with |
|
|
|
|
| Per-session ceiling on the number of snapshots kept at once — catches many small snapshots the byte cap alone would not, the same "count cap alongside the byte cap" shape |
| (unset) | Capability broker. Unset, no brokering — a job's capabilities run as requested (today's behaviour); the execution receipt still discloses them under |
|
| Append-only JSON-lines audit stream for broker decisions and security-relevant side effects (denied capability, refused install, cleanup). Each event carries a source-safe timestamp, the run/session id, the decision and reason, and never the executed source or a credential. Set to a path to relocate it; set empty to disable. Best effort — a write failure never fails a run. |
|
| Fork-bomb guard. |
| (unset) | Escape hatch: pin |
The strict service runs on Linux x86_64 or ARM64 with Docker Engine, cgroup v2,
and an explicitly registered gVisor runsc runtime. Its executor image must be
pinned by @sha256: digest on the execution path. That image is published to
GHCR (ghcr.io/the-40-thieves/codecalc-exec, multi-arch amd64+arm64) by the
publish-executor-image workflow, which an operator dispatches
(workflow_dispatch); the workflow commits the immutable digest into
docker/executor-image.lock, and published_strict_image() resolves it as the
production default. Until that first dispatch no digest is pinned and the
execution path fails closed — it never falls back to the mutable local
diagnostic tag (codecalc-exec:strict), which doctor and the conformance
suite keep using. The default systrap platform works without KVM, so the same
authenticated service can be used from Linux, macOS, and Windows; strict clients
never fall back to native local execution.
Provisioning and running any of the three strict backends in production —
the gVisor+Docker host, Windows AppContainer hardening, and the macOS/Windows
remote-client configuration — is covered in
docs/deployment/README.md, separate from the
provider interface itself in
docs/contract/provider-v1.md.
Both backends resolve CODECALC_RUNTIME_PATH identically, and
scripts/check_parity.py fails CI if the Rust and Python copies of that
contract ever drift — including if a machine-specific home directory finds its
way back into the default.
Tool-definition token cost
codecalc's tools/list returns 51 definitions. Measured with o200k_base as a
proxy on the served JSON, that is 78,586 bytes / 20,630 tokens of descriptions
and input schemas (up from 64,643 bytes / 17,277 tokens at the same 51 tools),
and every client pays it before the first user message. The number
has grown with the descriptions, not the count: the disambiguation sentences
and the per-mode text on bits/symbolic are what a selection-accuracy-first
server spends its tokens on. The latest jump (+13,943 bytes, +3,353 tokens) is
every one of the 152 tool PARAMETERS gaining its own description in the
input schema (Annotated[<type>, Field(description=...)]) — the docstrings
above did not change, so scripts/tool_select_eval.py's selection-accuracy
numbers (it scores only name + docstring, never the input schema) are
unaffected by this change.
A follow-up pass then edited the DOCSTRINGS themselves, now that every
parameter's own syntax/default/range lives in its schema description and no
longer needs restating in prose: measured with the same o200k_base proxy
(a mcp.Client.list_tools() dump, by_alias=True, exclude_none=True, one
tool per JSON object), 77,237 bytes / 20,439 tokens — down from the
152-parameter figure above (-1,576 bytes, -412 tokens), short of the
~19,000-token target this pass aimed for. What moved which way: the
execute_code/execute_code_stream/run_submit/session_run cluster and six
other tools (truth_table, session_files, algebraic_equiv,
compare_threshold, percentage, percentiles) each gained one
disambiguation/usage sentence naming a sibling tool, verify_optimization's
docstring was cut to about 60% of its length, and pure schema-restating
sentences ("languages = comma-separated subset", explicit default/range
call-outs, repeated operation lists) were removed across the file — but
several of THOSE removals had to be partly reverted once
scripts/tool_select_eval.py showed they deleted discriminating
vocabulary BM25 actually leans on (see scripts/data/tool_select_baseline.json,
regenerated by this pass: full 151→150/234, dev 128→130/184, core
79→78/116 top-1 hits, every surface within the eval's own
DEFAULT_EPSILON_HITS), which is most of why the net reduction is smaller
than the additions alone would suggest.
A per-tool icons field (2025-11-25+) was tried and measured, not assumed:
one tiny inline data:image/svg+xml;base64,... glyph per tool GROUP, under
300 bytes even for the largest of six — small per icon, but Tool.icons is a
per-TOOL field, so each of the tools repeats its group's full base64
payload on the wire, and base64 tokenizes far worse than prose under a BPE
encoder. Measured on the full served tools/list payload: +11,540 bytes,
+6,665 tokens (o200k_base) — real and non-trivial on a server whose whole
pitch (see "Reducing the tool surface" below and docs/design/ 2026-08-10-tool-facade.md) is that tool SELECTION accuracy matters more than
saving a few tokens elsewhere. Removed. codecalc's MCPServer still carries
one SERVER-level icon plus a website_url — both ride on initialize, once
per connection, not once per tool, so they do not touch tools/list
at all: measured before/after, the served tools/list payload is
byte-identical (59,902 bytes / 15,952 tokens either way, as measured at the
time on the then 52-tool surface) — +0 on the
number this section exists to track.
codecalc does not hide its tools behind a discovery facade, and that is
deliberate: the tool surface is where per-operation approval prompts, audit
names and typed schemas live, and collapsing 51 tools into one dispatcher makes
install_package and percentage look like the same permission to a client
that approves by tool name. The cost is real, but the client is the better place
to solve it, because the client can defer definitions without giving up the
schemas or the per-tool boundary.
If you are paying too much for codecalc's definitions:
Claude Code defers every MCP tool by default — tool search is on by default, with no token floor codecalc needs to clear.
autoloads a server's tools upfront only while their definitions total under 10% of the context window and defers all of them once that 10% is reached;falseloads everything upfront regardless of size (Claude Code MCP docs, https://code.claude.com/docs/en/mcp, retrieved 2026-09-07).calc_exact,execute_code,verify_translation,verify_optimization, andlist_languagescarry_meta["anthropic/alwaysLoad"](per that same doc, "your 3-5 most frequently used tools") so they stay loaded even when a client defers everything else;install_packageandupdate_runtimescarry_meta["anthropic/requiresUserInteraction"], which forces a permission prompt on every call regardless of the session's permission mode — both change the host and both fetch from a registry.execute_code,execute_code_stream,session_run,compare_execution, andrun_inspectcarry_meta["anthropic/maxResultSizeChars"] = 499520(2 * 240 KiB + 8_000), the truncation hint for the one tool family whose output can legitimately approach it —run_inspectcarries it because its terminal reply, once arun_submit-started run finishes, is the same envelopeexecute_codereturns. This bounds the serialized TEXTcontentblock only — the JSON result as the string a client renders as the tool's reply — not the whole MCP response: every one of these five tools exceptsession_runalso declaresoutputSchema, so the SDK additionally attachesstructuredContentwith the same JSON ("MCP server developers can configure custom output limits for individual tools by specifying_meta['anthropic/maxResultSizeChars']in the tool's listing, up to a hard maximum of 500,000 characters", same doc as above, describes the text result specifically) — so a typed tool's total wire payload approaches twice this hint.session_run's inlined artifact content blocks (image/text/link, up to 8 within a 4 MiB encoded budget — see its own docstring) are likewise separate blocks outside this bound. 240 KiB combined (stdout and stderr together) is a hard CEILINGmax_output_kbis clamped to on every tool that accepts it (execute_code,execute_code_stream,run_submit), separate from the 64 KiB DEFAULT0selects — chosen as the largest round-KiB ceiling that keeps the TEXT-block hint under that 500,000-char limit; there is no other ceiling on that parameter today, and raising it further would push the hint over that limit. A run whose real output needs more than 240 KiB belongs in a session instead: leavingmax_output_kbat its default withsession_idset spills oversized output to a full-fidelity file, readable in full viasession_read_file, rather than truncating it.compare_executiontakes nomax_output_kbof its own, but accepts an unbounded number ofsnippets, so a many-language comparison can still legitimately exceed the hint.Claude API, via the MCP connector, takes
defer_loadingonce on the toolset'sdefault_config, or per tool inconfigs. Deferred definitions stay out of the system-prompt prefix, prompt caching is preserved, and a matching tool is expanded into its full definition when the model searches for it.OpenAI's Responses API has the same knob under a different name:
defer_loading: trueon an MCP server tool definition (OpenAI Responses MCP tool guide, https://developers.openai.com/api/docs/guides/tools-connectors-mcp, retrieved 2026-09-07).VS Code caps a single chat request at 128 enabled tools and groups excess tools behind "virtual tools" above a configurable threshold (VS Code agent tools docs, dated 2026-09-02, https://code.visualstudio.com/docs/copilot/agents/agent-tools). Windsurf / Cascade caps at 100 total tools (Cascade MCP docs, https://docs.devin.ai/desktop/cascade/mcp, retrieved 2026-09-07).
The MCP specification itself has no deferral mechanism — no tool search, grouping, tags, or toolsets; a server can only publish
ttlMs/cacheScopehints and paginatetools/list(MCP spec 2026-07-28, https://modelcontextprotocol.io/specification/2026-07-28/server/tools, retrieved 2026-09-07). A client without one of the mechanisms above pays the full cost regardless of what codecalc does.Any client can filter which of the 51 tools it exposes to the model. Nothing here requires codecalc to change.
A server-side facade remains under consideration for clients with no such
mechanism (docs/design/2026-08-10-tool-facade.md), and is not implemented.
Trimming a description to cut this cost is exactly the change
scripts/tool_select_eval.py exists to gate: an offline, labeled eval of
whether a deterministic lexical (BM25) selector still picks the right tool
for a plain-language ask, scored against the live tools/list text.
Measured v1 baseline (196 hand-labeled prompts, none containing their own
target tool's name — see the script's own docstring): 60.71% top-1 /
75.51% top-3 accuracy on the full surface (62.75% / 63.0% top-1 on dev /
core respectively). It is a lexical proxy, not a model — see the script's
module docstring for exactly what a green run does and does not prove.
The checked-in baseline PINS the exact labeled corpus by content hash
(prompt_set_sha256); a --baseline compare against a corpus that no
longer hashes to it fails with a distinct "corpus changed" error rather than
silently scoring a smaller, easier prompt set against the old numbers. And
because a tool can be top-1-wrong against full's 51 distractors (zero
headroom to lose) while still having real headroom against core's much
smaller distractor set, both the regression compare and the ablation
self-check (replacing real descriptions with a generic stub, one tool at a
time, across every candidate tool — no sampling) run separately against all
three of full/dev/core, wired into CI via
tests/test_tool_select_eval.py so the gate is proven live, on every
surface, on every run — not just at the PR that added it.
BM25 is a lexical proxy, not a model — scripts/tool_select_llm_eval.py is
the model-driven half, calling a real chat model over a live gateway with
the identical tool catalog and labeled corpus; it is opt-in (workflow_dispatch,
advisory rather than a hard gate) rather than wired into every PR, and its
measured numbers live in docs/tool-selection-eval.md next to BM25's own.
Reducing the tool surface
For an operator who would rather not configure every client, codecalc also has
a first-party knob: CODECALC_TOOLS registers only a chosen slice of the
51-tool surface, so a client that never enables tool search still pays for a
smaller tools/list.
On a client with no deferral mechanism of its own, the client's own allow-list
does the same job from the other end — OpenAI's allowed_tools, Gemini CLI's
includeTools/excludeTools, or Codex CLI's enabled_tools/disabled_tools
all narrow what a given session sees without touching the server.
Every tool also now carries a ToolAnnotations hint (readOnlyHint,
destructiveHint, idempotentHint, openWorldHint — see
codecalc/server.py's GROUP_ANNOTATIONS/TOOL_ANNOTATION_OVERRIDES tables
for the value on each of the 51). Codex CLI's writes approval mode
(v0.144.0+) reads readOnlyHint directly: a tool marked readOnlyHint: true
skips the approval prompt, everything else still asks. That covers the whole
calculator group (20/20 pure) plus the read-only members of the mixed
groups — list_languages/list_execution_providers/runtimes_status/
branch_reachability in execution, z3_check/algebraic_equiv in
verification,
session_list/session_files/session_read_file/session_artifacts/
run_inspect in sessions, and analyze_complexity in analysis — without
codecalc doing anything client-specific; the annotation is the same hint
every MCP client reads, writes just happens to be the mode that consumes it.
This is not the facade the section above declines to build. Every tool a
group activates keeps its own name, its own typed input schema and its own
per-tool approval prompt — a group that is not active simply never registers
its tools with the MCP SDK at all, so they are absent from tools/list and
rejected by tools/call, not merely hidden behind a dispatcher a client could
still invoke by guessing the name.
Every tool belongs to exactly one group:
Group | Tools |
|
|
|
|
|
|
|
|
|
|
|
|
CODECALC_TOOLS takes a comma-separated list of group names, preset names, or
both:
Preset | Expands to |
|
|
|
|
| every group (the default) |
CODECALC_TOOLS=calculator # just the calculator (20 tools)
CODECALC_TOOLS=core # same thing, by preset name
CODECALC_TOOLS=calculator,execution # two groups, unioned
CODECALC_TOOLS=dev # a coding-assistant slice (36 tools)Unset or empty registers every group — 51 tools, same as today —
so nothing changes for an operator who does not set this. An unknown group or
preset name is a loud startup failure naming the bad value and every known
group/preset, never a silent fallback to "everything" or "nothing": either
direction would turn a typo into a footgun nobody notices until it matters.
codecalc doctor prints the active groups, the full group→tools mapping, and
how many tools this process actually registered, whatever CODECALC_TOOLS is
set to.
Client-side deferred loading (the section above) and this env var compose
cleanly: point a client with no deferred-loading mechanism at a
CODECALC_TOOLS-restricted process, or use both — a smaller declared surface
still benefits from being deferred.
Test
Each file is a standalone script that prints one PASS/FAIL line per
assertion and exits non-zero if any failed — no test runner, no plugins.
cd /path/to/codecalc
# everything. `|| break` used to be `|| break` alone, which stopped at the
# first failure AND left the loop exiting 0 — a red suite reported success to
# anything wrapping this command. This form runs them all and carries the
# failure out.
fail=0
for f in tests/test_*.py; do PYTHONPATH=. .venv/bin/python "$f" || { echo "FAILED: $f"; fail=1; }; done
for f in scripts/*.py; do PYTHONPATH=. .venv/bin/python "$f" || { echo "FAILED: $f"; fail=1; }; done
[ "$fail" -eq 0 ] # the exit status of the whole run
# or individually
PYTHONPATH=. .venv/bin/python tests/test_smoke.py # every language, via the Rust executor
PYTHONPATH=. .venv/bin/python tests/test_mcp_all.py # every tool over MCP stdio, answers checked
PYTHONPATH=. .venv/bin/python tests/test_executor_sweep.py # sandbox regressions76 test files and 19 CI-invoked scripts, 2453 assertions. "CI-invoked"
means referenced by path (scripts/<name>.py) from a job in
.github/workflows/*.yml — scripts/check_claims.py derives the count that
way and gates it, so a script wired into a workflow without this sentence
changing, or this sentence bumped without a workflow change, fails the build.
Nothing in the suite
needs the internet, so none of it is ever skipped for lack of a network.
It can skip for lack of a capability, and that is correct rather than a regression: a machine without a symlink privilege, without a given language runtime, or without a built native executor cannot exercise the cases that need them. The suite reports three distinct outcomes — the property holds, the property is broken, and this machine cannot exercise it — and every skip names its real cause. A nonzero skip count on Windows or in fallback mode is the healthy result; what would be wrong is a skip reading as a pass.
This paragraph previously claimed zero skips unconditionally. That became
false the moment the suite learned to distinguish the third outcome, and
nothing gated it: check_claims.py gates the counts below, not the prose
around them. The counts are gated by
scripts/check_claims.py: they were written by hand once and were stale within
three pull requests, which is exactly the failure the rest of that script
exists to prevent. Four of the files are regression suites named after the
sweep that produced them — test_bug_sweep, test_executor_sweep,
test_python_sweep, test_network_modules — and each one's docstring states
the defect it locks out and how it was reproduced, because a regression test
whose reason has been forgotten is the first one deleted.
Two rules the suite holds itself to, learned from breaking both:
Assert the value, not the shape. Three of these files once had no assertions at all: they called tools, printed the output and exited 0. They caught a crash and never a wrong answer — a
runtimes_statustotal replaced with-999passed, printingtotal = -999.Don't pin what varies.
benchmarkandcompare_executionrank by measured time, so their winner moves under load; their structure is asserted and their timing is not.runtimes_statusis checked against itself — the summary must agree with the data it summarises — so it holds on any machine rather than describing this one.
Benchmarks
benchmarks/ is a separate, real pytest suite measured by
CodSpeed on every pull request
(.github/workflows/codspeed.yml, CPU simulation instrument). It covers exact
arithmetic, the SymPy/z3 tool bodies, the expression screen, spec hashing and
the tree-sitter complexity analyser. pytest stays out of the manifests; it is
added ad hoc, as in the mutation lane:
uv sync --locked --all-extras
PYTHONPATH=. uv run --no-sync --with pytest-codspeed pytest benchmarks/ --codspeedPlatform support
Linux, macOS and Windows. The three do not offer the same primitives, and the
executor reports which ones it could not apply in an unenforced array on
every result rather than letting a caller assume they all held.
The native table below describes the local provider and is not a hostile-code
security boundary. On macOS, <host>-strict instead uses the explicitly
configured Linux strict service: the macOS binary performs provider selection,
attestation, supervision, and result validation, while untrusted code executes
inside the remote cgroup/namespace/seccomp/Landlock boundary. A missing or
incomplete service fails before source leaves the Mac and never falls back to
native execution.
Symbolic evaluation carries the same idea. Every symbolic tool runs SymPy in
a forked child under CPU and memory ceilings with a wall clock the parent
enforces, so an expression nobody anticipated is still bounded — SymPy's own
maintainers abandoned their attempt at a safe= flag as "security theater", so
the screen in safe_expr.py buys time and the child buys the bound. Where
there is no fork, the result reports expression_bound_not_enforced_without_fork
rather than implying a guarantee.
A second field, output_error, covers the other way a result can be wrong:
absent means stdout/stderr are what the program produced, present means at
least one of them is not, and names which stream and the OS error. That
distinction did not exist until #80
— an output file that could not be read came back as a program that printed
nothing, on a run reported as successful. ok now accounts for it on both
backends.
Guarantee | Linux | macOS | Windows |
Wall-clock timeout | yes | yes | yes |
Kill the whole process tree |
|
|
|
Fork-bomb guard |
|
| Job |
Memory ceiling |
| reported unenforced¹ | Job |
CPU-time ceiling |
|
| Job |
Open-file ceiling |
|
| reported unenforced |
Output cap | yes | yes | yes (on read) |
| seccomp-bpf filter⁶ (falls back to |
| reported unenforced |
Stateful sessions | yes | yes | yes |
¹ Darwin accepts setrlimit(RLIMIT_AS) but does not enforce address space the
way Linux does, so setting it would buy an illusion.
² Dynamically-linked programs only — a statically linked binary (Go, by default)
ignores it.
⁴ Applied via JOB_OBJECT_LIMIT_PROCESS_TIME, which Windows has supported
since XP — this was reported as cpu_limit_unavailable_on_windows until
2026-08-08, and the table said the same, so code and docs agreed with each other
and disagreed with Windows. It is not identical to RLIMIT_CPU and the
difference is reported rather than glossed: it counts user-mode time only, so
a process burning kernel time is not capped by it, and the system checks
periodically rather than immediately. Runs on Windows carry
cpu_limit_counts_user_time_only_on_windows in unenforced to say so.
³ Weaker still on macOS, in two ways. SIP and the hardened runtime strip
DYLD_INSERT_LIBRARIES for protected and hardened-signed binaries (most signed
interpreters), and dyld interposing does not reach calls made inside the
shared cache where libSystem lives — a program's own connect() is intercepted,
a system framework opening a connection internally is not. Treat macOS no_net
as a speed bump, never as isolation.
⁶ Linux only. The executor installs a seccomp-bpf filter in the sandboxed
child that refuses the socket(AF_INET/AF_INET6) SYSCALL in-kernel — not a
libc symbol, so ctypes/dlsym and raw syscall() calls cannot route around
it the way they can around the LD_PRELOAD shim. AF_UNIX still works. Falls
back to the shim (with its symbol-level bypass, disclosed in unenforced as
no_net_best_effort_shim) when the kernel refuses the filter.
Both are exercised by the suite on every platform. The fork-bomb probe measures
the EAGAIN boundary precisely but needs os.fork, so it is POSIX-only; a second
probe SPAWNS processes instead, which is the portable operation, and pins the
ceiling low through CODECALC_MAX_PROCESSES so it costs two dozen short-lived
processes rather than walking up to the fallback. Verified to track the limit
rather than something incidental: a headroom of 24 bounds it at 22 children and
a headroom of 300 bounds it at 298.
⁵ Windows' ActiveProcessLimit is scoped to the job rather than to the uid,
so it avoids the failure mode that broke 14 of 31 runtimes on Linux. CodeCalc
now supplies that job at process creation, makes it non-nestable with the
minimal JOB_OBJECT_UILIMIT_EXITWINDOWS restriction, and allowlists only the
three standard I/O handles inherited by the child.
Measured on Windows 11 Pro: 400 of 400 spawns succeeded against a ceiling of
24, reproduced from two unrelated launchers including Task Scheduler. This is
not a failed API call — SetInformationJobObject and AssignProcessToJobObject
both return success and the correct limit reaches the job. It is topology.
ActiveProcessLimit is not one of the limits combined across a nested job
chain; those take the most restrictive value, while this one comes from the
process's immediate job. A post-creation AssignProcessToJobObject places
the child somewhere in that chain rather than at its end: measured, the child's
immediate job reported 0x3000 / APL 0 while codecalc's reported
0x230A / APL 24, so codecalc's ceiling was never consulted.
No parent-side Win32 call returns another process's immediate job or its
effective ActiveProcessLimit, so this cannot be closed by inspection. Every
compatibility run that assigns the child after creation therefore carries
process_limit_enforcement_unverified_on_windows in unenforced. Four further
strings can each positively prove a failure; none can prove success, so their
silence does not imply enforcement.
Creation-time assignment is the default. It was verified on Windows 11 Pro with
a direct Python runtime: 23 children succeeded against a total limit of 24 and
the next spawn failed with WinError 1816. Runtime launchers that require an
inner job now fail rather than silently escaping the limit; configure a direct
runtime executable. CODECALC_WIN_JOB_AT_CREATION=0 retains the old path only
as an explicitly unverified compatibility escape hatch.
AppContainer security isolation is a DIFFERENT guarantee from the Job Object's
resource limits. The Job Object above caps resources — memory, process count,
user-mode CPU — and each run names in unenforced which of those did not bind.
The optional AppContainer backend adds a security boundary layered on the same
creation-time topology: a least-privilege AppContainer profile
(CreateAppContainerProfile, no capability SIDs, so no network), launched with
SECURITY_CAPABILITIES in the same STARTUPINFOEX attribute list as the job
assignment. Access is granted two ways, deliberately split. The sandbox
workdir is granted to the run's own AppContainer SID — per-run, so
concurrent runs cannot reach each other's workdirs, and it vanishes with the
ephemeral directory. The interpreter directory is granted read+execute to the
fixed ALL APPLICATION PACKAGES SID (S-1-15-2-1) as an explicit,
non-inheritable ACE applied per file across the tree — because a real
interpreter's pre-existing files are inheritance-protected and no inheritable
grant reaches them. That interpreter grant is persistent and cached (a marker
in codecalc's own state dir; the several-thousand-file walk runs once per
interpreter): a deliberate trade-off that leaves a read-only ACE, readable by any
AppContainer on the machine, on a public interpreter — rather than re-walking
every run. The intended property is that a payload cannot read the user profile,
write outside its workdir, or reach the network. It is OFF by default (opt in
with CODECALC_WIN_APPCONTAINER=1) and fails closed — if profile creation,
SID derivation or an ACL grant fails, the launch is refused rather than dropped
to an unconfined process. The isolation has been verified on a Windows 11 box
(AppContainer SID present, user-profile secrets unreadable, writes confined to
the workdir, network denied, ambient privileges reduced to the two benign ones
Windows keeps), yet every run that takes this path still emits
appcontainer_isolation_unverified_on_windows: a Server-SKU CI runner cannot
exhibit AppContainer behaviour, and the guarantee ultimately depends on the
deployment's OS and configuration, so the shipped default stays conservatively
disclosed rather than claiming a universal proof.
Two things degrade rather than fail on a given platform: languages whose runtime
is absent (list_languages reports available: false), and the shell-wrapped
plans — gleam and haskell — which need a POSIX shell to scaffold a project
and report available: false on Windows outright rather than resolving through
a bash that cannot run them. csharp left that set: .NET 10 runs a single .cs
file directly, so it is shell-free on every platform.
Reliability tiers
available/status above is a claim about resolution: did this machine
find the command on PATH. It is not a claim about reliability: has
codecalc's own CI ever actually run this language and checked the output. The
two are orthogonal, and they disagree in practice — a review's own smoke test
found the rust and csharp host toolchains failing on a machine where both
rustc and dotnet resolved cleanly. list_languages, runtimes_status, and
codecalc doctor all report a tier alongside resolution to make that gap
visible instead of silent:
Tier | Meaning |
| A CI job genuinely executes this language and asserts on its real output, on every PR. Currently |
| Declared, with a local smoke fixture ( |
| A registry entry never validated on any runner, anywhere, not even locally. None today. |
codecalc doctor's text output prints both axes side by side rather than
folding tier into the resolution summary, so a best_effort runtime that
happens to be installed on your machine reads as exactly what it is:
resolved, unverified by codecalc, may be broken.
Sandbox guarantees
Fresh temp dir per run, deleted on exit (source + binaries + outputs). The deletion is identity-checked: the directory's device and inode are recorded at creation and re-checked before removal, because executed code runs with that directory as its cwd and can rename another one into its place. A caller-supplied
--workdiris a session workspace and is never deleted. If the filesystem supplies no file index to identify the directory by, the deletion is refused rather than performed unverified, so temp directories accumulate there instead of the wrong one being removed. That trade is stated because it is the one this guarantee actually makes: it was previously implemented in the Rust executor only, and the Python fallback deleted unconditionally, which CI caught on Windows.rlimits: CPU (timeout+8s), address space 2TiB (V8/JVM need huge VA), file size 256MiB, 256 FDs, core dumps off
The timeout is a total budget: compile and run share it, so
--timeout 10cannot take twenty seconds.duration_msis the run alone;compile_msandtotal_msare reported separately.Wall-clock timeout kills the whole process group (SIGKILL). So does SIGTERM to the executor —
PR_SET_PDEATHSIGreaches only the direct child, so a group kill is what covers its descendants, and the executor is the only participant that knows the group id.Output capped at 64KiB combined (stdout and stderr share one budget, split fairly: each stream keeps up to half, and what one stream leaves unused goes to the other), on every path including stateful sessions. Exceeding the combined cap is reported as
OLE, and the program is not killed for it: it runs to its exit or timeout. The file-size rlimit is kept strictly above the cap so that overflow stays detectable — tying the two together turned a truncated 4MB output into a silentverdict: OK.Fork-bomb guard via
RLIMIT_NPROC, sized from the measured ambient task count plus headroom rather than a fixed number. This is a mitigation, not isolation: the budget is shared with every other process your user owns, so concurrent executions draw on the same pool. cgroup v2pids.maxis the real per-sandbox answer and needs delegated cgroup access a stdio MCP server cannot assume — reach for it when this moves behind a container.no_netblocks the network, not every socket: it refusesAF_INETandAF_INET6and forwards everything else, soAF_UNIXlocal IPC keeps working.No network namespace isolation (single-host tool; containerize for untrusted code). Note, 2026-09-07: this bullet describes the pre-#242 state. Since #242 (2026-08-21), Linux additionally enforces
no_netin-kernel via a seccomp-bpf filter — see theno_netrow inSECURITY.md's "Known limitations" table for the current per-platform breakdown. A full network namespace is still only the strict (gVisor) backend's job; this note does not change that.Every result carries a
backendfield ("rust"or"python") so a caller never has to infer which sandbox actually ran from an absent key — that was possible to confuse with an older build that never reported it at all. The pure-Python fallback cannot provide everything above: it has nono_netshim (reported inunenforced, not silently dropped), andpeak_memory_kbcomes backNonerather than a number, becauseru_maxrssis a process-lifetime high-water mark this path has no way to attribute to one run.CODECALC_REQUIRE_NATIVE=1turns "running on the fallback" into a startup failure instead of a guarantee you have to notice was quietly weaker.
Sessions
A session is a persistent workspace; python3 and node additionally get a
long-lived REPL worker so variables and imports survive between calls. What that
does and does not buy you:
workspace session | stateful worker | |
Fresh sandboxed process per call | yes | no — one worker serves every call |
| applied | reported in |
| per call | applied once, at worker start |
Output cap + | yes | yes |
Per-call wall clock | yes | yes — a worker that blows it is killed |
A worker cannot take a per-call rlimit after the fact, and --no-net is decided
at exec time. Rather than accept those arguments and drop them, the result lists
them in unenforced — the same field the executor already uses to say "asked
for, not applied". Omit session_id, or use a workspace session, when a ceiling
has to be real.
The worker protocol does not share a file descriptor with executed code, and
every response carries the id of the request it answers. Both matter: sys.stdout
is a Python-level rebind that a subprocess writes straight past, and a corrupted
stream that is not resynchronised returns every later call the previous call's
result — a well-formed answer to a different question.
The channel differs by platform and the guarantee does not. POSIX hands the
worker an out-of-band pipe; Windows has neither pass_fds nor preexec_fn, so
the worker appends responses to a file whose path arrives in the environment.
Either way a child spawned with inherited stdio writes to fd 1 and cannot reach
the protocol. Tests force the file-backed channel on every platform, because an
unexercised fallback is one that works until it is needed.
Local operations: status & cleanup
Two CLI-only commands for an operator running a long-lived server, not MCP tools — they don't count toward the tool surface above:
codecalc status # read-only snapshot: sessions, disk usage, quotas, audit log
codecalc status --json # the same report, for scripts
codecalc cleanup # DRY RUN (the default) — marker-based only
codecalc cleanup --write # actually removes marker-based candidates
codecalc cleanup --write --include-unmarked # ALSO sweep old, unmarked, session-shaped dirsstatus reports SESSION_ROOT, how many sessions exist and which of them
are idle-expired (the on-disk .codecalc-session-expired marker the
idle-TTL reaping leaves behind), per-session and global workspace disk
usage, the configured disk quotas and current headroom, the audit log's
path and size, and a one-line runtime reliability-tier summary. It changes
nothing — no session is started, stopped, reaped, or written to.
cleanup reclaims disk from session directories under SESSION_ROOT.
--dry-run is the default — nothing is removed until --write is passed.
Because cleanup runs as a SEPARATE process from any server that may be
using SESSION_ROOT right now, it has none of that server's in-memory
bookkeeping to consult — only what is on disk.
Directory mtime is deliberately NOT trusted as a liveness signal. An
earlier version of this feature did trust it, and an adversarial review
proved that wrong live: a REPL worker doing purely in-memory work touches
no file at all, and even an in-place file overwrite bumps only that file's
own mtime, never its parent directory's — so a genuinely-active worker
session can look, by directory mtime alone, identical to an abandoned one.
The real signal is a per-worker-session liveness lockfile: the server
writes its own pid into the session directory the moment a stateful
(python3/node) worker starts, and removes it the moment that worker is
actually gone (reaped or session_stop). cleanup checks this for every
candidate and refuses outright — regardless of marker, age, or the mtime
floor below — whenever the lockfile names a pid that is still alive. That
is what makes a session any running codecalc server is using is never
deleted true for worker sessions.
By default, cleanup considers ONLY directories carrying the idle-expiry
marker — the risk-free path, since a marker only ever exists after
sessions.py's own idle-TTL reaper has already closed that specific worker
for good (session ids are never reused). --include-unmarked additionally
sweeps old (CODECALC_CLEANUP_ABANDONED_AGE_HOURS, default 24h),
session-shaped, marker-less directories — the one path with real residual
risk, because a workspace-only session (no worker) never gets a
lockfile to check against, so this path falls back to age + a hard
recency floor (nothing modified in the last few minutes is ever touched)
as a heuristic, not a proof. Turn it on deliberately, and never point
CODECALC_SESSION_ROOT at anything but a codecalc-private directory —
the "looks like a session dir" name filter is loose, not strict.
Other safety properties, unconditional on every path: only a direct child
of SESSION_ROOT is ever a candidate (never SESSION_ROOT itself); a
symlink there is refused, never followed; and removal itself is
identity-checked (device/inode, re-verified immediately before the
delete) the same way session_stop's own workspace teardown is, so a
directory swapped out from under a stale scan is refused rather than
deleted.
Language list
python3, node, bun, deno, typescript, ruby, php, perl, lua, tcl, r, elixir, erlang, bash, zsh, mojo, swift, c, cpp/c++, rust, go, fortran, zig, java, kotlin, csharp, gleam, haskell, sqlite, jq, awk — 31 runtimes.
codecalc does not install any of them. It runs whatever is already on
CODECALC_RUNTIME_PATH, and list_languages probes each one and reports which
actually resolved, so a minimal machine degrades to the subset it has rather
than failing opaquely.
Notes
Java uses single-file source launch (JEP 330). Kotlin compiles to a jar.
gleam/haskell scaffold a temp project (gleam new / nix-shell); csharp runs the file directly (.NET 10 file-based apps).
benchmarkuses the stdin-N contract: code reads N from stdin, work sized by N.
CI
Five workflows, each documented inline with what it gates and — where a tool was considered and rejected — why it is not there.
Workflow | Gates |
| clippy |
|
|
|
|
|
|
|
|
Two conventions run through all of them, both borrowed from harder-won experience:
Actions are pinned by commit SHA and downloaded tools by SHA-256. A tag is mutable; a digest is not.
Every scan asserts it scanned something. A linter pointed at a renamed directory, a dependency scanner with no lockfile to read, and a clean repo all produce the same output — exit 0. Each gate counts its inputs first and fails if the count is implausible.
Licence
Apache-2.0. See LICENSE.
Contributions require a DCO sign-off (git commit -s); dco.yml enforces it.
Available Tools
51 toolsalgebraic_equivAlgebraic EquivARead-onlyIdempotent
Are two expressions algebraically identical? 'is (ab)/c the same as a(b/c)?' answered exactly. Use symbolic(op="simplify"), not this, to see one expression's own simplified/factored/expanded forms rather than compare two; use verify_translation to compare running PROGRAMS, not expressions. Caveat: symbolic identity says nothing about float rounding, integer truncation or modular overflow.
Inputs: a (required), b (required). Returns: object
analyze_complexityAnalyze ComplexityARead-onlyIdempotent
Estimate the asymptotic (Big-O) time complexity of a code snippet via structural analysis.
Inputs: code (required), language. Returns: object
benchmarkBenchmarkA
Empirically measure time complexity by running code at increasing input sizes.
Contract: the code must read an integer N from stdin (first line) and do work
sized by N. codecalc runs it at each size in sizes and fits the growth
curve to estimate Big-O (O(1), O(log n), O(n), O(n log n), O(n^2)...). 3
sizes (the accepted minimum) can only return noise-floor O(1) or
"inconclusive" — never a growth class, not even exponential; 4+ sizes are
needed to trust the curve fit, 5+ doubling sizes for a robust ratio
median — estimate_basis names which estimator decided.
Example python: 'import sys\nn=int(sys.stdin.readline()); s=0\nfor i in range(n): s+=i\nprint(s)'
Inputs: code (required), sizes, timeout, language. Returns: object
bitsBitsARead-onlyIdempotent
Programmer-mode integer facts and operations, selected by mode —
replaces the four former standalone tools bit_analysis, bitop,
int_widths and base_repr, retired in 0.12.0 (CHANGELOG.md). Every mode
returns exactly its former tool's own result, plus mode (additive).
mode="analysis" (was bit_analysis) — facts about a single N: popcount,
bit length, trailing zeros, power-of-two check, next power of two. Used
by this mode: n (required), align (optional).
mode="op" (was bitop) — combine two integers a/b with
and/or/xor/nand/nor/xnor/not/shl/shr/sar/rol/ror at a fixed width
(8/16/32/64). Every result shows unsigned,
signed (two's complement), hex, octal and binary. shr is logical
(zero-fill); sar is arithmetic (sign-propagating) — 0x80 shr 1 = 0x40
(+64) but 0x80 sar 1 = 0xC0 (-64); rol/ror rotate bits around the width
instead of shifting them out. A left shift that drops bits says
OVERFLOW and shows the unbounded answer. Used by this mode: a, op
(required), b (required unless op="not"), width (optional).
mode="widths" (was int_widths) — which widths (i8..i64/u8..u64) hold
n, and the wrapped value where they do not; flags anything past 2^53
as unable to round-trip through a JS number or JSON float. Used by this
mode: n (required).
mode="repr" (was base_repr) — hex/oct/bin of n; with width, two's
complement and signed-overflow detection. Used by this mode: n
(required), width (optional).
Inputs: mode (required), a, b, n, +3 more. Returns: object
branch_reachabilityBranch ReachabilityARead-onlyIdempotent
Which if/elif/else arms and while/for loops of this python3 function can ever run, which are dead code, and what inputs reach each — decided with z3, without running the program.
Use trace_execution instead to see what happened on one run. Use z3_check, not this, when you already have an SMT-LIB2 script to solve directly rather than Python source to translate.
Unannotated parameters default to int. Each branch reports
verdict (reachable/dead/unknown), a witness when reachable, and
boundary_inputs (min/max/equality-edge for each comparison in its own
guard) — every input dict is shaped to drop straight into
compare_edge_cases's test_inputs. Refuses, naming the construct and
line, prior to any z3 call: floats, attribute access, comprehensions,
try/except, imports, data-dependent loop bounds, and anything else
outside + - * // %, and/or/not, == != < <= > >=, and
abs/min/max/len on int/bool/str. A for loop of at most 32
iterations is unrolled exactly; a longer for, or a while, is
checked one iteration at a time — a branch can still come back
reachable there, but never dead, and anything past the loop that
depends on what it computed comes back unknown rather than a guess.
Inputs: code (required), language (required), inputs, timeout, +1 more. Returns: object
calc_exactCalc ExactARead-onlyIdempotent
Use calc_exact, not evaluate_expression, for a literal arithmetic expression with no symbols in it. EXACT arithmetic: 0.1 + 0.2 == 0.3 is True here (False in plain Python).
Everything is an exact rational, integers are arbitrary precision. Supports
/ // % ** comparisons, bitwise ops (& | ^ << >> ~) on integers, and whitelisted math functions (sqrt, log, sin, ...) plus pi/e/tau. Use BEFORE asserting any computed number: thresholds, ratios, overflows, 'X is N% of Y'. Examples: '2**64 - 1', 'comb(52,5)', '0.1+0.2 == 0.3', '0xff & 0x0f'.
Inputs: expr (required). Returns: object
calc_statsCalc StatsARead-onlyIdempotent
Mean, median, sample stdev, and coefficient of variation (CV) for a sample of numbers. Pairs with percentiles for distribution shape (p50/p90/p95/p99) on the same sample, and with benchmark or verify_optimization, which are common sources of the timing samples this tool summarizes. CV > 0.2 flags run-to-run noise that swamps the effect. Returns n/mean/median/stdev/cv plus a cv_note.
Inputs: nums (required). Returns: object
collision_probabilityCollision ProbabilityARead-onlyIdempotent
Birthday-bound hash collision probability: 1 - exp(-n^2 / (2*2^b)).
Sizes hashes: 1e6 items into 64 bits is ~2.7e-8; 1e5 into 32 bits is ~0.69 — the answer to 'can I truncate this to 8 hex chars?' (no).
Inputs: bits (required), items (required). Returns: object
compare_edge_casesCompare Edge CasesA
Run the same logic in N languages on edge-case inputs and flag divergence.
Default inputs cover empty, zero, negative, and float-precision cases: ['', '0', '1', '-1', '10', '100', '0.1\n0.2']. Returns a per-input matrix plus a divergences list where languages disagree on identical input.
Inputs: snippets (required), inputs. Returns: object
compare_executionCompare ExecutionA
Run the same code in multiple languages side by side.
Returns per-language stdout/stderr/exit/duration plus which was fastest. Example: {"python3": "print(67)", "node": "console.log(67)"}
This tool fans out across every language with no per-language install
plumbing behind it; use install_package/execute_code(dependencies=...)
beforehand instead. A # /// script block in a snippet is likewise never
installed, but is DISCLOSED, not dropped: a python3 row that carries one
gets dependencies: {"status": "unsupported", "reason": ...}.
Inputs: snippets (required), stdin, timeout, dependencies. Returns: object
compare_thresholdCompare ThresholdARead-onlyIdempotent
Exact threshold check with a verdict and the shortfall when it fails. Use calc_exact, not this, when you want the computed VALUE rather than a threshold comparison.
a OP b. Both sides are evaluated exactly and printed as fractions — a
threshold comparison written out cannot be gotten backwards. Example:
('1/25', '>', '0.05').
Inputs: a (required), b (required), op (required). Returns: object
convert_unitsConvert UnitsARead-onlyIdempotent
Convert a value between units (dimensional analysis via sympy).
Supports metric/imperial length, mass, time, speed, energy, power, force, pressure, temperature (°C/°F/K), volume, area, data sizes, frequency. Examples: ('60','mph','km/h'), ('100','celsius','fahrenheit'), ('1','gb','mib'). Use list_units for the full alias table.
Inputs: value (required), to_unit (required), from_unit (required). Returns: object
data_sizesData SizesARead-onlyIdempotent
Byte counts for a plain integer, both binary and decimal — the gap
between them is where '291 MB' and '277 MiB' silently disagree by 5%.
For units other than bytes, use convert_units. For a duration, not a
byte count, use human_duration. Returns bytes plus binary and
decimal dicts of unit -> value.
Inputs: n (required). Returns: object
epoch_timeEpoch TimeARead-onlyIdempotent
Epoch seconds/millis/micros/nanos to ISO 8601 UTC (implausible readings suppressed).
Inputs: n (required). Returns: object
evaluate_expressionEvaluate ExpressionARead-onlyIdempotent
Use evaluate_expression, not calc_exact, for something other than plain arithmetic on literal values. Symbolically evaluate to a value or closed form via sympify: 'sqrt(144) + 2**10'. Not simplification — for simplified/factored/expanded forms, use symbolic(op="simplify").
Also reaches calculus forms no other tool exposes: diff(expr, x)
(derivative), integrate(expr, x) / integrate(expr, (x, a, b))
(indefinite/definite), and series(expr, x, x0, n) (Taylor expansion) —
see this parameter's own examples.
Returns value (if the result is a number) or the evaluated
expression, plus type.
Inputs: expression (required). Returns: object
execute_codeExecute CodeA
Execute code in language in a sandbox. Use this, not
execute_code_stream/run_submit/session_run, for one program whose result
you can wait for within a 120s cap.
Returns stdout, stderr, exit_code, duration_ms, cpu_ms, peak_memory_kb, verdict (OK/TLE/MLE/OLE/RTE).
session_id: run inside a session workspace (see session_start); with a stateful session (python3/node) interpreter state persists across calls. Also reportsartifacts_created(files just created/modified) since that workspace outlives the call; a sessionless run has none. Seesession_runfor the same field plus inline content blocks.max_output_kb: the 240 KiB hard ceiling is what theanthropic/maxResultSizeCharsthis tool advertises in its_metaalready assumes — the cap leaves no headroom to raise past it without the real result exceeding that hint. A run whose real output needs more than 240 KiB belongs in a session instead: leavemax_output_kbat its default (0) withsession_idset (below), and oversized output SPILLS to a full-fidelity file readable viasession_read_filerather than truncating — see the spill paragraph further down. An EXPLICITmax_output_kb, even under the 240 KiB ceiling, is honoured as a literal cap with no spill.no_net: Linux enforces in-kernel via a seccomp-bpf filter. macOS / no-seccomp kernel: best-effort symbol shim, disclosed inunenforcedwhen that's the only guarantee that held. See SECURITY.md.compact: never dropsunenforced,output_error,artifacts_created, ordependencies— if a guarantee you asked for was not applied, or a declared install failed, a compact result still says so.dependencies: merged with a PEP 723# /// scriptblock for python3, deduped by normalized name with this argument winning; the only source for node. A block ALONE, with nodependenciesargument, is enough to trigger an install — see SECURITY.md. Installed BEFORE the sandboxed step, through the same confinedinstall_packagepath — never inside the sandbox — and refused (capability_not_requested) without installing anything whenno_net=Trueor the capability policy denies or strictly limits network. Bounded by a fixed install-time budget separate fromtimeout(120s aggregate across every dependency;codecalc.dependencies.DEFAULT_DEPENDENCY_INSTALL_BUDGET_SECONDS) and, session-less, byCODECALC_SESSION_DISK_QUOTA_MBon the run's own workdir — either one exceeded refuses the run with a stamped, coded error naming the ceiling. See thedependenciesfield on the result.
With session_id set and max_output_kb left at its default, output that
would otherwise be truncated is instead SPILLED: the inline
stdout/stderr still carry the same truncated prefix as before, and
stdout_spill/stderr_spill name a codecalc://session/{sid}/files/...
resource carrying the fuller stream (session_read_file or the resource
route reads it back) — capped at 4 MiB, ..._spill_capped: true if even
that was not enough to hold everything. Passing an EXPLICIT
max_output_kb is honoured as a literal ceiling with no spill, same as
before. Session-LESS runs (no session_id) have no workspace to spill
into and keep the old truncate-and-drop behaviour.
Inputs: code (required), language (required), stdin, no_net, +8 more. Returns: object
execute_code_streamExecute Code StreamA
Execute code and STREAM progress + partial output as it runs. Use this, not execute_code/run_submit/session_run, for the same run when you want output while it runs, up to a 300s cap.
Reports progress notifications to the client while the program runs, so agents can see output before the process finishes. Returns the same result shape and applies the SAME ceilings as execute_code: max_memory_mb, max_output_kb and max_cpu are forwarded to the executor exactly as execute_code forwards them, including the same 240 KiB per-stream clamp.
dependencies: same as execute_code's (PEP 723 merge, no_net/policy
refusal, 120s budget, workdir quota) — installed before streaming
starts; a refusal/failed install is the stream's only event.
Inputs: code (required), language (required), stdin, no_net, +6 more. Returns: object
extract_functionExtract FunctionA
Extract a named function (with its imports + referenced helpers) into a standalone program and run it in the sandbox.
python3 gets exact ast extraction; other languages best-effort block
extraction (pass call to execute non-python). Returns the extracted
program and per-input runs.
Inputs: code (required), language (required), function_name (required), call, +1 more. Returns: object
float_reprFloat ReprARead-onlyIdempotent
What binary64 actually stores for X: exact value, raw bits, ULP, both
neighbours, and whether the literal is representable. float_repr(0.1)
shows 0.1000000000000000055511151231257827...; float_repr(0.25) says
EXACT. Above 2^53 warns consecutive integers are indistinguishable.
Inputs: x (required). Returns: object
human_durationHuman DurationARead-onlyIdempotent
Convert a SPAN of elapsed seconds into a humanised duration (e.g.
'2d 3h 4m 5s') plus per-day and per-30d rates. For an epoch timestamp
to a calendar date, use epoch_time instead. For byte counts, not
seconds, use data_sizes. Returns human, per_day, per_30d, and the
echoed seconds.
Inputs: seconds (required). Returns: object
install_packageInstall PackageADestructive
Install a package for a language (uv pip / npm / gem / go get / cargo add...).
Asks the caller to confirm before installing (a protocol-level gate, not
just the anthropic/requiresUserInteraction _meta hint — see
codecalc/confirmation.py); a declined or malformed confirmation refuses
with no install attempted.
With session_id, executed code in that session can import the result.
NETWORK: yes, always. The package manager fetches from its registry (PyPI, npm, rubygems, crates.io). codecalc opens no socket itself; the child process does.
NOT SANDBOXED: the installer runs as a direct subprocess of the server, so install-time hooks (npm postinstall, Python build backends, Cargo build scripts) execute with the server user's filesystem access. The environment is still restricted to the allowlist, so secrets do not leak, but the filesystem is not confined. Do not point this at untrusted input. See SECURITY.md.
Inputs: package (required), language (required), version, session_id. Returns: object
list_execution_providersList Execution ProvidersARead-onlyIdempotent
List execution providers (execution BACKENDS — local subprocess, gVisor-strict, remote) and their machine-readable capabilities.
This is about which BACKEND runs your code, not which LANGUAGE it runs —
a provider's ready/strict fields are resolution facts about the
backend itself. Per-language reliability (how much codecalc's CI has
actually verified a given language's toolchain, vs merely resolved it) is
a separate axis reported by list_languages/runtimes_status/codecalc doctor as tier; a ready provider says nothing about whether a
specific language running through it has ever been execution-tested.
Inputs: no named parameters. Returns: result
list_languagesList LanguagesARead-onlyIdempotent
List every language codecalc can execute, with extension, compile flag, and what this machine resolved. status is installed (its command was found on the sandbox PATH) or supported (nothing for it here); status_basis is resolved, meaning nothing was executed to check. Run codecalc doctor --deep to promote a runtime to available by actually running it.
tier is a DIFFERENT axis from status: status says whether THIS
machine resolved the command (resolution); tier says whether codecalc's
own CI has actually executed this language and asserted on its output
(reliability) — tested, best_effort (declared, plausibly works, never
CI-checked), or plan_only (never validated anywhere). A language can be
installed here and still be best_effort or worse — that combination is
exactly "the toolchain resolved and may still be broken".
Inputs: no named parameters. Returns: result
list_unitsList UnitsARead-onlyIdempotent
List every supported unit alias — all aliases and spellings — for convert_units.
Inputs: no named parameters. Returns: object
matrixMatrixARead-onlyIdempotent
Structured matrix operations: det, inverse, eigenvalues, transpose, rank, trace.
evaluate_expression refuses Matrix([[1,2],[3,4]]) on purpose — [/]
are denied there to block subscript-based RCE escapes, and a matrix
literal is collateral from that (correctly aimed) screen. This tool is
the structured replacement: rows is a JSON array of arrays (row-major),
never a string to parse. Each entry is either a JSON number, used
directly, or a scalar expression string ('1/2', 'sqrt(2)', 'x+1'),
screened per-entry the same way evaluate_expression screens its input
before anything reaches SymPy. Example: rows=[[1,2],[3,4]], op='det' -> -2.
Inputs: op (required), rows (required). Returns: object
percentagePercentageARead-onlyIdempotent
Exact share and percentage of PART / TOTAL. Use calc_exact for a single arithmetic expression, or compare_threshold to check the result against a threshold rather than just compute it.
Inputs: part (required), total (required). Returns: object
percent_changePercent ChangeARead-onlyIdempotent
Exact percent change from FROM_VALUE to TO_VALUE. Use percentage, not this, for PART / TOTAL rather than a before/after change.
(to_value - from_value) / abs(from_value) * 100 — the conventional
finance definition, relative to the MAGNITUDE of the base so a negative
from_value does not flip the sign (see note when it applies). Refuses
from_value=0 (undefined) rather than returning infinity — report the
absolute change instead. Returns percent_exact (exact rational),
percent_decimal (rounded), absolute_change, direction
("increase"/"decrease"/"unchanged"), and multiplier (to_value /
from_value, exact).
Inputs: to_value (required), from_value (required). Returns: object
percentilesPercentilesARead-onlyIdempotent
p50/p90/p95/p99 (the 50th/90th/95th/99th percentile cutoffs) by nearest-rank AND linear interpolation. Pairs with calc_stats, which gives mean/median/stdev/CV on the same sample instead of these distribution points.
Warns when n < 100 that p99 is just the maximum wearing a label.
Inputs: nums (required). Returns: object
physical_constantsPhysical ConstantsARead-onlyIdempotent
Look up a physical constant (speed_of_light, planck, avogadro, gravity, electron_mass, gas_constant, ...) or list all 22 with values.
Inputs: name. Returns: object
radix_convertRadix ConvertARead-onlyIdempotent
Convert a value between ANY bases 2..36, fractions included; bases that
cannot represent the fraction (e.g. 0.1 in base 2) are flagged
non-terminating. radix_convert('zz', 36, 7) is one call.
Inputs: value (required), to_base, from_base. Returns: object
run_cancelRun CancelADestructiveIdempotent
Cancel a background run started with run_submit.
Idempotent: calling this on a run that is already finished/cleaned
reports cancelled: false, state: <its actual terminal state> rather
than erroring — matching execute_code's own "no partial result" rule,
there is nothing partial to hand back either way.
Propagation depends on the SELECTED PROVIDER (see
list_execution_providers' cancel capability). The built-in local
provider does not support stopping a run once it has started; that is
reported honestly here rather than silently pretended to have worked —
the computation keeps running to completion and its result stays
available via run_inspect, so bound it in advance with run_submit's own
timeout instead. A provider that DOES advertise cancel: true reaches
the full spawned process tree the same way execute_code's own
cancellation does — RunSupervisor already owns that; this tool only
calls it.
Inputs: run_id (required). Returns: object
run_inspectRun InspectARead-onlyIdempotent
Poll a background run started with run_submit.
While running: {"ok": True, "state": "running"|"cancelling", "run_id", "provider_id", "started_at", "deadline"}.
Once terminal (state "finished"/"cleaned"/"recovered"), this returns
the SAME result shape execute_code returns — stdout/stderr/exit_code/
verdict/unenforced/provider (the interface_version/provider_id/limits
receipt)/... — merged with a small set of run_* extras (run_id,
provider_id, started_at, deadline, state, cleaned; see server.py's
_RUN_EXTRA_KEYS). This terminal reply carries the same
anthropic/maxResultSizeChars _meta execute_code advertises (see
server.py's _LARGE_RESULT_TOOLS) — it is the same envelope, once the
run started with run_submit has finished, and run_submit's own
max_output_kb is clamped the same way execute_code's is so that value
stays true here too. Read ok and verdict on a terminal result to tell
a clean finish from a failure; a run stopped by run_cancel is only
reflected there for a provider that actually supports cancellation (see
run_cancel's own docstring) — check the result the same way you would
any other run.
Retention: a finished run's result stays inspectable for the life of this server process — call this as many times as you like; nothing is consumed by reading it. What IS released on the first terminal read is the PROVIDER's own resources for that run (RunSupervisor.cleanup(), idempotent on repeat calls) — the in-memory record of the run itself is not evicted; there is no cap or TTL on it here, deliberately: the durable state machine, leases and TTL-based eviction are out of this residual's scope (see run_supervisor.py's own docstring). A long-lived server that calls run_submit very many times will grow this table; the on-disk crash-recovery journal underneath it is already bounded (RunSupervisor.max_completed), independent of this.
Inputs: run_id (required). Returns: object
run_submitRun SubmitA
Submit code for BACKGROUND execution; returns a run_id immediately. Use this, not execute_code/execute_code_stream/session_run, when you do not want to hold the call open — poll run_inspect(run_id), and run_cancel(run_id) to stop it early.
Same request shape as execute_code minus session_id (a run is a
standalone process, not a session workspace). timeout bounds the WORK
itself, not how long you wait to collect it.
This call's own reply carries no output — a small run_id handle — so
the anthropic/maxResultSizeChars hint lives on run_inspect instead,
which returns the full envelope, same shape execute_code returns,
once the run lands.
Admission is capped (CODECALC_MAX_ACTIVE_RUNS, default 64): past that many runs still running/cancelling at once, this returns a resource_exhausted error rather than growing without bound — call run_inspect/run_cancel to make room, or wait for one to finish.
Retention: see run_inspect.
dependencies: same semantics as execute_code's own. A refusal is
returned directly with no run created. Otherwise this call still
returns immediately: the install itself runs on the background worker,
ahead of the code, and a failed install becomes the run's own terminal
error — readable via run_inspect(run_id) like any other outcome.
Inputs: code (required), language (required), stdin, no_net, +6 more. Returns: object
runtimes_statusRuntimes StatusARead-onlyIdempotent
Check every language runtime for available updates (NON-MUTATING).
Reports current vs latest version per language, which package manager owns it (mise/rustup/swiftly/apt/npm/uv), and the exact command that would run.
Each entry also carries tier (registry.RELIABILITY_TIERS) — see
list_languages for what tested/best_effort/plan_only mean. A
current, up-to-date toolchain can still be best_effort: tier is
orthogonal to whether the update check below found a newer version.
NETWORK: yes. Non-mutating refers to this machine's runtimes, not to traffic — each package manager is asked what the latest version is, and they answer by contacting their own remote index.
Inputs: languages. Returns: object
session_artifactsSession ArtifactsARead-onlyIdempotent
List files created by executed code in a session (excluding runner internals like main.py/run.out).
Inputs: session_id (required). Returns: object
session_delete_fileSession Delete FileADestructiveIdempotent
Delete one file (or symlink entry — never the directory or symlink's target) from a session workspace. This is the recovery path when a session is refused for being over CODECALC_MAX_ARTIFACT_COUNT: neither session_write_file (creates/overwrites, never removes) nor session_run/ execute_code (refused by the same cap) can shrink the count, so this is the only in-session way to get back under it short of session_stop discarding the whole workspace. Refuses runner-internal paths (the same ones session_artifacts excludes) and directories.
Inputs: path (required), session_id (required). Returns: object
session_filesSession FilesARead-onlyIdempotent
List workspace files, optionally using a bounded cursor page. Use session_artifacts, not this, for only the files executed code produced; use session_read_file for one file's contents.
Inputs: session_id (required), path, cursor, page_size. Returns: object
session_listSession ListARead-onlyIdempotent
List active sessions and their languages/state.
Inputs: no named parameters. Returns: object
session_read_fileSession Read FileARead-onlyIdempotent
Read a file from a session workspace.
Text files return content. With as_image=True (or for image files), the file is returned as an inline image the model can see. Use session_files to discover paths; session_artifacts lists what executed code produced.
Inputs: path (required), session_id (required), as_image, max_bytes.
session_runSession RunA
Run a multi-file program already written into a session workspace
(via session_write_file). Use this, not
execute_code/execute_code_stream/run_submit, when entry_file may
import other files already in that workspace (helper.py, data/...).
Runs as a fresh process in the session workdir (not the REPL worker), so
relative imports and data files resolve. Returns stdout/stderr/verdict
plus the entry file's path. Oversized output spills into the session
workspace the same way execute_code's does — see its docstring for
stdout_spill/stderr_spill.
Reports artifacts_created and inlines small ones as extra content
blocks (image/text/link), capped at 8 blocks / 4 MiB encoded;
truncated_inline: true past either cap. dependencies installs
packages before running, same rule as execute_code's — see its docstring.
This tool takes no max_output_kb (its inline stdout/stderr stay at the
64 KiB default and spill past that, same as execute_code's session
branch) but the anthropic/maxResultSizeChars _meta it advertises
covers only that text envelope — the JSON result serialized as the
reply's content text block. The inlined artifact blocks above
(image/text/link, up to 8 of them within the 4 MiB encoded budget) are
SEPARATE MCP content blocks, outside the text block this hint bounds.
Every run copies entry_file's own source into the runner's private
scratch subdirectory before executing it — never into a root-level
main.<ext> file a session's own files could collide with. A session's
own main.py (or the equivalent for another language) at the session
root is never touched by running a different entry file.
Inputs: entry_file (required), session_id (required), stdin, timeout, +2 more.
session_snapshotSession SnapshotADestructive
Archive or restore a session's workspace files. action:
"save": tar.gz the session's current files (same rules as session_artifacts: .codecalc-run/ excluded, symlinks/hardlinks refused) into a snapshot stored OUTSIDE the workspace, so sandboxed code can never read or tamper with it. Returns snapshot_id.
"restore": extract snapshot_id's files into a brand-new session (default) or, with replace=True, wipe and recreate session_id's OWN workspace first. Only files are restored — a python3/node session's REPL variables/imports are never part of a snapshot.
"list": snapshots saved for session_id, oldest first.
"delete": remove one snapshot (snapshot_id required).
Snapshots are deleted when their session is stopped (session_stop(keep_snapshots=True) to keep them).
Inputs: session_id (required), label, action, replace, +1 more. Returns: object
session_startSession StartA
Start a persistent session. python3/node get a stateful REPL worker (variables/imports persist across execute_code calls); other languages get a persistent workspace directory. Returns session_id.
Inputs: language. Returns: object
session_stopSession StopADestructiveIdempotent
Stop a session: kill its REPL worker (if any) and delete its workspace. Also deletes every session_snapshot saved for it, unless keep_snapshots=True.
Inputs: session_id (required), keep_snapshots. Returns: object
session_write_fileSession Write FileADestructiveIdempotent
Write a file into a session workspace (relative path, no escapes). Use this to seed input data for executed code.
Inputs: path (required), content (required), session_id (required). Returns: object
symbolicSymbolicARead-onlyIdempotent
Symbolic algebra, selected by op — replaces the four former
standalone tools solve_expression, solve_linear, simplify_expression
and limit_expression, retired in 0.12.0 (CHANGELOG.md). Every op
returns exactly its former tool's own result, plus op (additive).
op="solve" (was solve_expression) — the roots of one equation:
'x**2 - 4 = 0', '2*x + 1 = 7'. For a system of several equations, use
op="solve_linear". For general constraint satisfiability (inequalities,
boolean constraints, multiple solvers), use z3_check. Returns
solutions as a list of strings alongside the parsed equation and
variable. Used by this op: expr (required), var (optional).
op="solve_linear" (was solve_linear) — a system of equations sharing
variables; despite the name, non-linear systems work too (e.g.
'x2 + y2 = 5; x - y = -1'). Example: system='x + y = 10; x - y = 2',
variables='x, y'. Used by this op: system, variables (both
required).
op="simplify" (was simplify_expression) — simplify, factor, and expand
an expression — algebraic forms, not solving (use op="solve") and not a
numeric value (use calc_exact). Returns simplified, factored, and
expanded as strings alongside the parsed original. Used by this op:
expr (required).
op="limit" (was limit_expression) — asymptotic behaviour: limit of
expr as var -> point. 'symbolic("limit", "n*log(n)/n**2", "n")'
returns 0 — settles complexity arguments faster than arguing. Used by
this op: expr (required), var (optional), point (optional).
Inputs: op (required), var, expr, point, +2 more. Returns: object
trace_executionTrace ExecutionA
Debug WHY, line by line, for the ONE input you actually ran it on: which statements fired, in what order, with what variable values at each step, and which if/elif/while/for/try branch was taken versus never taken. Want just the printed output instead? Use execute_code.
Returns events: ordered {step, line, event, func, locals}, one entry
per traced line/call/return/exception in YOUR code only (library
internals excluded). locals on each entry is only the names that
changed since the previous step in that same call — not a full dump
every line. A return entry also carries return_value; an
exception entry carries exception_type/exception_message.
Also returns branches (hit count per if/elif/while/for/try line),
lines_executed / lines_never_executed (coverage from a static parse),
and truncated/truncated_reason when max_events or an internal
size ceiling stopped RECORDING early (the underlying stdout/exit code
are unaffected either way). truncated_reason is also
"event_detail_over_cap" when one event's OWN detail (e.g. a call with
more than 200 changed locals) was too large to admit — that ONE event is
still present in events, as a bounded stub (locals: {},
detail_dropped: true), so its real step/line/func still count
toward lines_executed/branches exactly like any other event; only
its own detail, never the rest of the trace, was dropped.
TRUST: the trace is produced BY the traced program at its OWN privilege
— a debugging aid, not an attestation of behaviour, exactly as
trustworthy as that program's own stdout. discarded_events /
events_consistent are a best-effort tamper/corruption signal (never a
guarantee) computed independently of the file's own content —
events_consistent requires discarded_events == 0 among its
conditions, since an honest run never produces one.
unenforced may additionally note "only the main thread is traced"
(sys.settrace is per-thread) or, fallback backend only, an OLE
exit_code race.
For a structural Big-O guess with nothing executed, use analyze_complexity.
Inputs: code (required), language (required), stdin, no_net, +6 more. Returns: object
truth_tableTruth TableARead-onlyIdempotent
Build the truth table for a boolean expression over and/or/not/xor/ implies/iff (plus true/false constants and variables): 'a and b or not c', 'p xor q', 'a implies b'. Use z3_check, not this, for satisfiability over inequalities or non-boolean variables; use evaluate_expression for symbolic (non-boolean) math.
Returns variables (sorted names) and rows (one dict per assignment,
each variable name -> bool plus result), plus row_count,
satisfiable (any row true), and tautology (every row true).
Inputs: expression (required). Returns: object
update_runtimesUpdate RuntimesADestructive
Update language runtimes. SAFE BY DEFAULT: with apply=False this is a dry run — it returns the update commands that WOULD run without changing anything. Pass apply=True to actually execute them (mise up, rustup update, swiftly update, apt-get upgrade of language packages, npm -g update, uv tool upgrade).
apply=True asks the caller to confirm first (a protocol-level gate, not
just the anthropic/requiresUserInteraction _meta hint — see
codecalc/confirmation.py); apply=False is never gated, since nothing runs.
PRIVILEGE: the apt manager updates system packages and its command begins
with sudo. Those commands do NOT run unless the HOST has set
CODECALC_ALLOW_RUNTIME_APPLY=1; without it they are reported as skipped
with ok: false and the variable named, and the rest still run. Every
entry carries an elevated flag either way. mise/rustup/swiftly/npm/uv
touch user-owned toolchains and are never gated.
NETWORK: yes, on both paths. apply=False still asks each manager what the latest version is, which is a remote lookup; apply=True additionally downloads and installs. "Dry run" bounds what changes on disk, not what is sent.
Inputs: apply, timeout, languages. Returns: object
verify_optimizationVerify OptimizationA
PROVE an optimisation: same outputs, measurably AND SIGNIFICANTLY faster.
Two gates, in order. Correctness: runs candidate against original on
shared inputs — a faster-but-wrong candidate fails here and is never
timed. Speed: times both at increasing sizes; accepts only when the
median ratio clears min_speedup AND a one-sided Mann-Whitney U test
rejects "not faster" at every counted size (2-3), or a
Bonferroni-corrected majority above that — one size never accepts alone.
See inference for the per-size U statistic, p-value, effect size.
A rejection names which gate failed and by how much, e.g. "correct, 1.3x median, but only 1/4 sizes significant."
Accepted grades cross_checked; any rejection — wrong, not faster
enough, not significant — grades ungraded: correctness alone earns no
grade for the speed claim this tool answers.
Inputs: language (required), original (required), candidate (required), sizes, +2 more. Returns: object
verify_translationVerify TranslationA
PROVE that a port is equivalent: run both programs, compare their output.
You write the translation — you are the language model. This runs your source and your port on the same inputs and reports, per input, whether they matched, diverged, or could not be compared (a runtime that is missing or a program that failed on both sides is INCONCLUSIVE, never a pass).
Use it after porting anything: python3 -> go, node -> rust, a rewritten function against the original. Pair with compare_edge_cases to find the inputs worth testing.
Matching tolerates only line-ending/trailing-whitespace noise; stdout_raw carries what actually ran.
A pass is graded cross_checked (two independent implementations, run
and agreeing — see grade_basis for which runtimes). A non-pass is
graded ungraded: never a softer positive grade.
Inputs: source_code (required), target_code (required), source_language (required), target_language (required), +1 more. Returns: object
z3_checkZ3 CheckARead-onlyIdempotent
Use z3_check, not symbolic(op="solve"), for satisfiability over inequalities, boolean combinations, or several variables at once: sat/ unsat/unknown plus a model. Example: '(declare-const x Int)(assert (> x 5))(check-sat)'.
unsat is graded solver_proven — see grade_basis for the engine
version and timeout bound it was decided within. sat is graded
ungraded: it's a real decided answer, just not a proof — reserving
solver_proven for unsat means a counterexample can never wear a
proof grade. unknown carries no proof either way and is also graded
ungraded.
Inputs: smt2 (required). Returns: object
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 51 tools
Most tools have clearly distinct resource/action targets, and many docstrings explicitly say 'use this, not X' to steer selection. The main risk is in the execution/comparison clusters (execute_code vs execute_code_stream vs run_submit vs session_run; compare_execution vs compare_edge_cases vs verify_translation), which are separable only by careful reading.
Names are uniformly snake_case and there are coherent families (session_*, execute_*, run_*, compare_*, verify_*, list_*), but conventions are mixed: some are verb_noun (list_languages), some noun_verb (session_list, radix_convert), and several are bare nouns/adjectives (bits, symbolic, matrix, percentage). This is readable but not a consistent pattern.
At 51 tools this is well past the 25+ threshold for 'too many,' even for a broad code-execution-plus-math server. Several clusters (e.g., the many compare/verify tools, or the numerous unit/format converters) could plausibly be consolidated further despite the existing bits/symbolic mode merges.
The surface covers execution (sync/stream/background/session), file management, snapshots, package/runtime management, tracing/verification, and a wide math/unit library, so agents can complete most workflows. Minor gaps remain, such as no run_list for active background runs and no uninstall_package, but these are workaroundable rather than blocking.
Maintenance
Related MCP Connectors
MCP server for your apps' tools and custom tools, plus hosted AI agents and approval-gated workflows
MCP server for progressive tool usage at any scale (see https://klavis.ai)
214 tools for AI agents over one MCP endpoint: image, video, audio, 3D, data, storage, mail, GPUs.
Nifty's MCP server — exposes tasks, projects, messages, and files as tools for AI agents.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceA transport-agnostic MCP server that integrates multiple AI coding agents (Claude Code, Gemini, and Codex) with built-in tools for command execution, calculations, and streaming capabilities. Supports both STDIO and HTTP transports for flexible deployment.20 npm1MIT
- AlicenseAqualityBmaintenanceProvides access to 61 public digital libraries through a single unified interface, enabling users to search and retrieve information from academic papers, books, legal records, and more using natural language.1160 npm3MIT

multivon-mcpofficial
AlicenseAqualityBmaintenanceMCP server that gives AI coding agents direct access to evaluation tools.23Apache 2.0- AlicenseAqualityDmaintenanceMCP server that gives small LLMs verified symbolic-math & logic tools.62Apache 2.0