Skip to main content
Glama

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_code tool 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 attack

From 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 attack

doctor 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 start

Related 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 --json

Without --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

ok

true when the program completed with exit code 0

status

completed, timeout, output_limit, memory_limit or sandbox_error

exitCode

the program's exit code, null when codecage stopped the run

timedOut

true when the wall clock limit stopped the run

limitHit

null, time, output or memory

stdout, stderr

the output, each capped (1 MiB by default)

stdoutTruncated, stderrTruncated

whether a cap was reached

durationMs

wall clock time of the whole container run

language, image, runtime, container, limits

what ran where, with which limits

error

only for sandbox_error, the runtime's own message

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

--network none

reaching the internet, the local network or the runtime's TCP API, sending data out

--read-only

changing the system or leaving a file anywhere but /work

--read-only-tmpfs=false (podman only)

podman's default writable tmpfs on /tmp, /var/tmp and /run under --read-only

--tmpfs /work:...,size=64m,noexec,nosuid,nodev

filling the disk; the only writable place, gone after the run

--memory N with --memory-swap N

a memory bomb, including escaping into swap

--pids-limit 64

a fork bomb

--cpus 1

starving the host of cpu

wall clock timeout, then kill and rm -f by name

an endless loop, and a container that outlives its client

--cap-drop ALL

mount, raw sockets, mknod, changing file owners and other root powers

--security-opt no-new-privileges

gaining root through a setuid binary

--user 65534:65534

running as root inside the container

only --env KEY=VALUE pairs, and an allowlisted env for the runtime client

reading API keys and tokens from your environment

no -v, --mount or --volumes-from, input as a tar stream on stdin

reading .env, SSH keys, the runtime socket or any other host file

--ipc none

writing to shared memory outside /work

--ulimit nofile=256:256, --ulimit core=0

exhausting file descriptors, core dumps

--log-driver none plus the output cap

an output flood that fills the host disk or memory

--rm, --name codecage-<random>, --label codecage=1

leftover containers, stopping the wrong one

--pull never

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_code takes language, code, and optionally stdin, files (name, content, encoding utf8 or base64), env, timeout_seconds, memory_mb, cpus, pids, work_dir_mb and output_bytes. It returns the result as JSON text and as structured content.

  • describe_sandbox lists 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 it

A 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

openai

api-key

OPENAI_API_KEY, --model, optional CODECAGE_OPENAI_BASE_URL for any compatible endpoint (local servers included)

anthropic

api-key

ANTHROPIC_API_KEY, --model, optional CODECAGE_ANTHROPIC_BASE_URL

openai or anthropic

oauth

an OAuth config (below), then codecage auth login

claude-cli

subscription

the official claude CLI, signed in

codex-cli

subscription

the official codex CLI, signed in

fake

none

CODECAGE_FAKE_RESPONSES, a JSON file with scripted answers, for tests

--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 secret

codecage 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

CODECAGE_RUNTIME

docker or podman, otherwise docker first, then podman

CODECAGE_DOCKER_BIN, CODECAGE_PODMAN_BIN

path to the runtime client

CODECAGE_OCI_RUNTIME

passed as --runtime to the runtime, for a stronger isolation runtime you installed

CODECAGE_MCP_MAX_TIMEOUT_S, CODECAGE_MCP_MAX_MEMORY_MB, CODECAGE_MCP_MAX_CPUS, CODECAGE_MCP_MAX_PIDS, CODECAGE_MCP_MAX_WORKDIR_MB, CODECAGE_MCP_MAX_OUTPUT_BYTES

MCP maximums

CODECAGE_PROVIDER, CODECAGE_AUTH, CODECAGE_MODEL, CODECAGE_MAX_TOKENS, CODECAGE_TIMEOUT_MS

demo model settings

CODECAGE_CLAUDE_BIN, CODECAGE_CODEX_BIN, CODECAGE_MAX_BUDGET_USD

vendor CLI paths, a cost cap for the claude CLI

CODECAGE_CONFIG_DIR

overrides the per user config dir

CODECAGE_INTEGRATION

tests only, 0 skip, 1 require a runtime

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

docker.io/library/python:3.14.10-alpine3.24@sha256:5862d971d1f0ae26b258cefa4e893556b1d3aba81bd2ff30888704ad378bab67

python3 -u -B main.py

node

docker.io/library/node:24.22.3-alpine3.24@sha256:116b800c3754b440ee0aa3ed2f20f5bf3d99a554bfd9adeea09ea8017f6e85f5

node main.js

sh

docker.io/library/alpine:3.24.4@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf

sh main.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

  1. The request is validated (language, sizes, file names, env pairs, limits).

  2. A ready runtime is chosen from info; it must report Linux and enforced limits.

  3. The pinned image is pulled if missing.

  4. The code, input files and stdin are packed into a tar archive in memory.

  5. <runtime> run starts with the hardening flags, /bin/sh -c unpacks the archive from stdin into the tmpfs /work and execs the program with its stdin from the archive.

  6. stdout and stderr are collected up to the cap. On a timeout or a full cap the container is stopped with kill and rm -f by name, then the client.

  7. 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_HOST or a runtime context points at another machine, the code runs there.

  • codecage trusts what info reports. A daemon with a changed default seccomp profile or other settings that info does 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…

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      C
      maintenance
      Provides 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 PyPI
      MIT
    • F
      license
      Not graded
      quality
      D
      maintenance
      Enables AI agents to safely execute Python, JavaScript, and Bash code in an isolated Docker sandbox with strict security constraints.
      1
      -
    • A
      license
      A
      quality
      B
      maintenance
      Enables 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.
      15
      MIT