codecage
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
codecage
The safe place to run code an AI agent wrote.
When an agent writes a script and starts it with exec or a subprocess, that script runs as
you. It can read your API keys from the environment, your .env files and SSH keys from disk,
and it can reach the internet. codecage runs the script in a locked down container instead. Each
door is closed by a specific runtime flag, and codecage attack runs a suite of real attack
programs inside the same sandbox to prove that every door is shut.
Python, Node.js and sh, each on a small image pinned by digest.
No network, no host files, no host environment, a read only system, a small writable
/work.Memory, swap, process, cpu, disk, output and wall clock limits. A timeout stops the container itself, not only the client process.
A CLI, an MCP server with a
run_codetool for agents, and a small library.Zero dependencies. Node.js 22.5 or newer, docker or podman, Windows, macOS and Linux hosts.
Quick start
You need docker or podman running Linux containers, and Node.js 22.5 or newer.
npx github:kalmardani/codecage doctor
npx github:kalmardani/codecage pull
npx github:kalmardani/codecage run --code 'print("hello")' --language python
npx github:kalmardani/codecage attackFrom a local clone:
git clone https://github.com/kalmardani/codecage
cd codecage
node bin/codecage.js doctor
node bin/codecage.js run examples/hello.py
node bin/codecage.js attackdoctor tells you which runtime codecage will use and why another one is refused. On a machine
without a runtime it looks like this (real output):
codecage 0.1.0 on darwin x64, node v24.22.1
docker not found
fix: install docker, or point CODECAGE_DOCKER_BIN at its client
podman not found
fix: install podman, or point CODECAGE_PODMAN_BIN at its client
no usable runtime, codecage run and codecage attack will refuse to startRelated MCP server: E2B MCP Server
Running code
codecage run job.py
codecage run job.py --file data.csv --stdin input.txt --timeout 5 --memory 128
codecage run --code 'console.log(6 * 7)' --language node
cat script.sh | codecage run - --language sh
codecage run job.py --jsonWithout --json the program's stdout and stderr are printed, with terminal control characters
removed (--raw keeps them), and a one line summary goes to stderr. With --json you get the
result object.
Field | Meaning |
|
|
|
|
| the program's exit code, |
|
|
|
|
| the output, each capped (1 MiB by default) |
| whether a cap was reached |
| wall clock time of the whole container run |
| what ran where, with which limits |
| only for |
memory_limit is inferred from exit code 137 when codecage did not stop the run itself. A
program that kills itself with SIGKILL is reported the same way.
Exit codes of codecage run are the program's own exit code, 124 for a timeout, 123 for the
output cap, 137 for the memory limit and 125 for a codecage or runtime error. The other commands
exit 0 on success, 1 when something failed (an attack got through, a demo was not solved), 2 on
a usage error, 3 when the model failed and 4 when no runtime can be used.
Input files are copied in, never mounted. --file data.csv puts data.csv next to the program,
--file in/x.csv=../data.csv renames it. --env KEY=VALUE sets a variable inside the sandbox;
codecage never copies a value from your environment. --image <ref> swaps the image for a
language (the command stays the same, for example python3); such an image is not pinned by
codecage.
What each flag stops
Flag | Attack it stops |
| reaching the internet, the local network or the runtime's TCP API, sending data out |
| changing the system or leaving a file anywhere but |
| podman's default writable tmpfs on |
| filling the disk; the only writable place, gone after the run |
| a memory bomb, including escaping into swap |
| a fork bomb |
| starving the host of cpu |
wall clock timeout, then | an endless loop, and a container that outlives its client |
| mount, raw sockets, mknod, changing file owners and other root powers |
| gaining root through a setuid binary |
| running as root inside the container |
only | reading API keys and tokens from your environment |
no | reading |
| writing to shared memory outside |
| exhausting file descriptors, core dumps |
| an output flood that fills the host disk or memory |
| leftover containers, stopping the wrong one |
| a run fetching some other image than the pinned digest |
The default seccomp profile of the runtime stays on. codecage refuses to run when the runtime reports that memory, swap, pids or cpu limits are not supported (for example rootless podman on cgroup v1), because the flags would then be silently ignored.
The attack suite
codecage attack runs each program below inside the sandbox with the normal flags. The host side
plants random fake keys in the environment, a fake .env in a project folder and a fake secret
file, and judges each run from its status, measured numbers and the markers the program prints.
A row passes only when the attack was stopped. The command exits 1 if anything got through.
$ codecage attack --list
host-env-key node read a planted fake API key from the host environment (door clean environment, client env allowlist)
host-dotenv python read a planted .env file from the host project folder (door no host mounts, input copied in as a tar stream)
internet python reach the internet (TCP, UDP, DNS, interfaces) (door --network none)
write-outside-workdir sh write outside the work dir (door --read-only, tmpfs only at /work, --ipc none, non root user)
memory-bomb python allocate four times the memory limit (door --memory equal to --memory-swap)
infinite-loop node run forever (door wall clock timeout, kill and rm -f by name, --cpus)
fork-bomb python fork until the process table is full (door --pids-limit)
host-paths python read host files by absolute path, find host mounts (door no host mounts)
privilege-escalation python become root or hold capabilities (door --user 65534:65534, --cap-drop ALL, no-new-privileges)
runtime-socket python reach the container runtime API (door no socket mount, --network none)
disk-exhaustion python fill the disk with eight times the work dir size (door tmpfs size limit on /work, read only root)
kernel-interfaces python write kernel controls, read raw devices, mknod, mount (door --cap-drop ALL, default seccomp, read only /proc/sys, non root user)
output-flood node flood stdout without end (door output cap with kill, --log-driver none)The programs are plain files in src/attacks/programs/, so you can read exactly what is tried.
They never print the content of a real credential file, only whether it exists. The run prints a
table with attack, result (blocked, GOT THROUGH or ERROR), time, door and evidence, and a
summary line. --json gives the same as JSON, --only id,id runs a subset. The CI workflow of
this repository runs the full suite against docker on every push.
MCP server
codecage mcp starts an MCP server on stdio (JSON-RPC 2.0). Point your agent at it and let it
call run_code instead of a shell tool.
{
"mcpServers": {
"codecage": {
"command": "npx",
"args": ["-y", "github:kalmardani/codecage#v0.1.0", "mcp", "--max-timeout", "30", "--max-memory", "512"]
}
}
}The server has two tools.
run_codetakeslanguage,code, and optionallystdin,files(name, content, encoding utf8 or base64),env,timeout_seconds,memory_mb,cpus,pids,work_dir_mbandoutput_bytes. It returns the result as JSON text and as structured content.describe_sandboxlists the languages with their images, the defaults and the maximums.
There is no image, mount, network or privilege argument. An agent can lower a limit, never raise
it above the operator's maximum; a request above it comes back as an error that names the field
and the maximum. The maximums default to 60 s, 512 MiB, 2 cpus, 128 processes, 128 MiB work dir
and 64 KiB output per stream, and the default output cap for an agent is 16 KiB per stream so the
result fits its context. Set them with --max-timeout, --max-memory, --max-cpus,
--max-pids, --max-workdir, --max-output or the CODECAGE_MCP_MAX_* env vars below.
An example of the error an agent sees (real output):
{"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"invalid request: timeoutMs 120000 is above the maximum 30000 ms set by the operator"}],"isError":true}}Library
import { runCode } from 'codecage';
const result = await runCode({
language: 'python',
code: 'import sys\nprint(sum(int(x) for x in sys.stdin.read().split()))',
stdin: '1 2 3 4',
limits: { timeoutMs: 5000, memoryMb: 128 },
});
console.log(result.status, result.stdout);runCode(request, options) validates the request, picks a ready runtime once per process,
pulls a missing pinned image and runs the code. It throws SpecError for an invalid request and
RuntimeUnavailableError when no runtime can be used; every finished run, including timeouts and
limits, comes back as a result. Options are runtime (docker or podman), pull (default
true), policy ({ defaults, max } for limits) and ociRuntime. runAttacks, selectRuntime,
LANGUAGES and DEFAULT_LIMITS are exported too. See examples/library.mjs.
Demo, a model writes the code
codecage demo "<task>" is a tiny agent loop. A model writes a program for the task, codecage
runs it in the sandbox, and if the run fails the model sees the code and the capped output once
and may correct it. At most two model calls. The model controls only the program text and its
language; flags, limits and the image are fixed by code, and its answer must match a closed JSON
shape.
codecage demo "print the first ten prime numbers, one per line" --provider claude-cli
codecage demo "..." --provider openai --model <id>
codecage demo "..." --provider anthropic --model <id>
codecage demo "..." --dry-run # show the program, do not run itA real run with --dry-run --json and the claude-cli adapter on 2026-11-27 (shortened):
{
"status": "dry_run",
"provider": "claude-cli",
"model": "claude-fable-5-2",
"calls": [{ "model": "claude-fable-5-2", "ms": 5566, "inputTokens": 12354, "outputTokens": 135 }],
"rounds": [
{
"language": "python",
"code": "def first_primes(n):\n primes = []\n candidate = 2\n while len(primes) < n:\n if all(candidate % p != 0 for p in primes if p * p <= candidate):\n primes.append(candidate)\n candidate += 1\n return primes\n\n\nfor prime in first_primes(10):\n print(prime)\n",
"result": null
}
]
}Connecting a model
Provider | Auth | What you set |
|
|
|
|
|
|
|
| an OAuth config (below), then |
|
| the official |
|
| the official |
| none |
|
--provider, --auth and --model can also be set with CODECAGE_PROVIDER, CODECAGE_AUTH and
CODECAGE_MODEL. CODECAGE_API_KEY_ENV names another env var for the key. Keys are never
printed or logged.
OAuth works with any endpoint that accepts bearer tokens, with three grants: client credentials
(for example an enterprise gateway), authorization code with PKCE on a loopback redirect, and the
device grant. The config is a JSON file at <config dir>/codecage/oauth.json or env vars
CODECAGE_OAUTH_TOKEN_URL, CODECAGE_OAUTH_AUTH_URL, CODECAGE_OAUTH_DEVICE_URL,
CODECAGE_OAUTH_CLIENT_ID, CODECAGE_OAUTH_SCOPE, CODECAGE_OAUTH_GRANT, with the client secret
only from CODECAGE_OAUTH_CLIENT_SECRET. Tokens are cached with mode 0600 in the per user config
dir (%APPDATA% on Windows, ~/Library/Application Support on macOS, $XDG_CONFIG_HOME or
~/.config on Linux) and refreshed before they expire.
Use your own subscription
codecage auth login claude # uses the official claude CLI, starts its sign in if needed
codecage auth login chatgpt # uses the official codex CLI (codex login)
codecage auth status # every connection type, ready or not, never a secretcodecage uses a subscription only by starting the vendor's official CLI, from an empty temporary folder, and never reads, copies or reuses the tokens that CLI stores.
Configuration
Variable | Meaning |
|
|
| path to the runtime client |
| passed as |
| MCP maximums |
| demo model settings |
| vendor CLI paths, a cost cap for the claude CLI |
| overrides the per user config dir |
| tests only, |
Default limits are 10 s, 256 MiB memory and swap together, 1 cpu, 64 processes, 64 MiB work dir and 1 MiB output per stream.
Images
Language | Image | Command |
python |
|
|
node |
|
|
sh |
|
|
The digests are multi platform index digests (amd64 and arm64 included), read from the registry
on 2026-11-27. codecage hands the runtime repo@digest, so a moved tag cannot change what runs, and the
run itself uses --pull never. To update, read the new index digest for a tag, change
src/sandbox/languages.js, and let CI run the attack suite on it. Only the standard library of
each language is available; there is no network to install packages.
How it works
The request is validated (language, sizes, file names, env pairs, limits).
A ready runtime is chosen from
info; it must report Linux and enforced limits.The pinned image is pulled if missing.
The code, input files and stdin are packed into a tar archive in memory.
<runtime> runstarts with the hardening flags,/bin/sh -cunpacks the archive from stdin into the tmpfs/workandexecs the program with its stdin from the archive.stdout and stderr are collected up to the cap. On a timeout or a full cap the container is stopped with
killandrm -fby name, then the client.The result is classified and returned as JSON.
Limits
Containers share the host kernel. codecage is a strong default for running code that your own
agent wrote on your own machine or CI runner, where the main risks are mistakes, overreach and
prompt injected instructions. It is not a boundary for hostile code from many tenants on one
host, because a kernel bug or a runtime bug can break out of any container. For that case a sandbox
built on hardware virtualisation, one small virtual machine per run, is the right layer, and
codecage can sit on top of a container runtime that provides it through CODECAGE_OCI_RUNTIME.
Other limits of 0.1.0:
The runtime daemon is root equivalent. Whoever can run codecage can run containers anyway.
If
DOCKER_HOSTor a runtime context points at another machine, the code runs there.codecage trusts what
inforeports. A daemon with a changed default seccomp profile or other settings thatinfodoes not show is not detected.Only stdout and stderr come back; files the program writes are deleted with the container.
Each run starts a fresh container, about one second of overhead on a warm Linux host.
The memory limit includes the work dir, because tmpfs lives in memory.
Creating a user namespace inside the sandbox may be allowed by the runtime's seccomp profile. The suite reports it as information; it gives no host access by itself.
Container behaviour is verified in CI on docker and on podman, both on Linux runners.
Licence
MIT, see LICENSE. Copyright (c) 2026 Kalmár Dániel.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
Beta code sandbox for agents. Run Python or JavaScript with no network and a 30 s timeout.
Run AI agent tasks in isolated sandboxes with a cost cap, saved workflows and scoped connections.
Build Apps and run code in 30 languages — sandboxed, with persistent sessions for agent loops.
Cloud Linux VMs for your agent: run code, Docker, files and HTTPS previews in a Sandboxer microVM.
Related MCP Servers
- AlicenseNot gradedqualityCmaintenanceProvides sandboxed code execution for AI agents with support for Python, JavaScript, and shell commands. Includes comprehensive safety features like destructive pattern blocking, timeout protection, and restricted file access for secure production use.28 PyPIMIT
- AlicenseAqualityDmaintenanceEnables AI assistants to securely execute Python and JavaScript code in sandboxed environments, with file management and package installation.7MIT
- FlicenseNot gradedqualityDmaintenanceEnables AI agents to safely execute Python, JavaScript, and Bash code in an isolated Docker sandbox with strict security constraints.1-
- AlicenseAqualityBmaintenanceEnables AI coding agents to safely run commands, install dependencies, test, and modify code inside disposable, policy-enforced Docker sandboxes isolated from the host, returning results and diffs.15MIT