🤖 AI-Generated Content — The content of this repository, including all source code, documentation, and configuration files, has been generated by an artificial intelligence assistant or created using artificial intelligence assistant. While efforts have been made to ensure correctness and security, the code should be reviewed before use in any production environment.
mcp-sandbox

A Local (stdio-only) MCP server that gives a model-host client (such as
opencode) a safe, isolated environment to run arbitrary commands — a
drop-in replacement for the host shell.
Instead of letting the model use the host shell directly, the model drives
mcp-sandbox: for each session it provisions a per-session, isolated Docker
container with the required directories mounted in, executes arbitrary
commands inside that container, and destroys it via explicit
sandbox_destroy / sandbox_destroy_all (per-session and ephemeral, but
cleanup is explicit — there is no automatic GC). Security is the top
priority — the sandbox is more restrictive than the host, never less.
- MVP scope: the Docker backend. Apple Container and other backends are
designed for but not yet implemented.
- Deployment: Local / stdio-only. No HTTP, no
observability endpoint, no container image.
Features
- Per-session, isolated, ephemeral Docker sandboxes.
- Execute arbitrary commands inside the sandbox (scalar
command executed via
the profile-configured shell — no shell-string concatenation).
- The session
cwd is mounted 1:1 at the same absolute path (read-only by
default; rw opt-in via the profile's cwd.mode); files come from the image,
the host, or the runtime — mount + exec is the core mechanism.
- Operator-authored sandbox profiles (Phase 7): the image, env, mounts,
network, cgroup limits, user and sudo are declared in read-only YAML
profiles under
SANDBOX_PROFILES_DIR, referenced by name on
sandbox_create — no per-request knobs, no profile create/edit/delete tools.
- Hardened by default: read-only rootfs, drop-all capabilities, no-new-
privileges, seccomp, non-root user, bounded resources, tmpfs working dir,
auto-remove.
- Immutable
Isolation policy the caller cannot weaken.
- Secret-safe output: a single redaction layer hides
secret:true fields from
all output and logs.
- Live streaming output: long-running tools (starting with
sandbox_exec)
emit notifications/progress so the model-host sees command output and the
call parameters as they run — additive, redacted and ANSI-sanitized (see
SPEC.md §5.1).
- Self-describing over MCP: server-level
Instructions, discoverable
sandbox://guidance/* playbooks (resources) and enriched tool descriptions
teach a model-host how to use the server directly over the protocol — no
standalone skill file or AGENTS.md pointer needed (see below).
- Per-command timeout:
sandbox_exec accepts an optional timeout (in
seconds); it is applied as a context.WithTimeout cancellation that reaches
both the Docker API calls and the streaming progress channel (timeout == 0
means no deadline, SPEC.md §6.10).
- Human-in-the-loop confirmation for destructive tools (client-side, see below).
Security model
mcp-sandbox is built around a deny-by-default security model with full
shell capability inside the sandbox:
- The model-host gets full permission to run shell commands — but inside
an isolated, ephemeral Docker container, never on the host.
- What is not explicitly allowed is, by default, not available. Access is
granted explicitly: host directories only via
ALLOW_DIRS, network comes from
the operator profile (bridge/none default, host only if the operator
authors it), root inside is a scoped opt-in per SudoPolicy, package install
is opt-in via provisioned images.
- The container is hardened (read-only rootfs, drop-all capabilities,
no-new-privileges, seccomp, non-root user, resource limits) and cannot be
weakened by a caller (immutable
Isolation).
- Everything is ephemeral and per-session. Cleanup is explicit: a sandbox
is destroyed only by
sandbox_destroy / sandbox_destroy_all — there is
no automatic GC (see Sandbox lifecycle).
The practical effect: the model can run any command it needs, safely
confined — so the model-host no longer needs a host shell at all.
Architecture & design
Full architecture, security model, tool surface and conformance are documented
in SPEC.md. Agent working conventions are in
AGENTS.md.
Highlights:
- DDD / Clean architecture with top-level packages
(
cmd/mcp-sandbox/, domain/, application/, infrastructure/) —
no internal/.
- Role-based backend interfaces (
Backend, Lifecycle, Executable,
Introspectable) with capability dispatch via type-assertion
and ErrCapabilityNotSupported — no stubs.
- Constructor-register backend factory; Docker registers in
init() and is
selected lazily on the first create (no outbound calls at startup).
- Declarative tool framework: each tool is a
ToolDef with annotations,
instructions, input/output schema and a redaction contract, wrapped by a
shared handler pipeline (validate → access-log → dispatch → redact →
structured output).
- Session lifecycle:
create → use → destroy, immutable mounts. Cleanup is
explicit only — see Sandbox lifecycle. Automatic
idle-reaping and orphan cleanup are future work (not implemented today).
Requirements
Installation
git clone https://github.com/teran/mcp-sandbox.git
cd mcp-sandbox
make build # produces binaries in dist/
Binary releases are published on GitHub tags (goreleaser).
Configuration
The server is configured via environment variables (Local / stdio server —
auth via environment, no HTTP headers).
| Env |
Default |
Description |
ALLOW_DIRS |
[] (none) |
Permitted host directories for mounts — gates the session cwd and every profile mount source. Empty ⇒ deny all. Still required (Phase 7). |
ALLOW_SYMLINKS |
false |
Allow following symlinks outside ALLOW_DIRS (unsafe; default off). |
DOCKER_HOST |
unix:///var/run/docker.sock |
Docker daemon socket (unix). |
LOG_LEVEL |
(unset ⇒ logging disabled) |
Enable + level. stdio logging is on only when set. |
LOG_FILENAME |
— |
stdio log file path, chmod 600. |
LOG_FORMAT |
text |
text or json. |
SANDBOX_IDLE_TIMEOUT |
15m |
Accepted but not yet effective — the idle reaper is not wired into the running server, so this has no effect today (future work). |
SANDBOX_PROFILES_DIR |
~/.config/sandbox/profiles |
Directory of operator-authored, read-only YAML profiles — one <name>.yml per profile (Phase 7). Read on demand on each profile lookup — edits take effect without restarting the server. The source of image, env, mounts, cwd, network, cgroups, user, sudo. |
Removed in Phase 7: SANDBOX_CWD_MODE (→ profile cwd.mode),
SANDBOX_CGROUP_CPU_LIMIT_CORES / SANDBOX_CGROUP_MEMORY_LIMIT_GB
(→ profile cgroups), and TRUSTED_REGISTRIES (→ image comes from the
profile; digest-pinning is the recommended convention, SPEC.md §7.9).
Example:
export ALLOW_DIRS="/Users/me/projects/myapp"
export LOG_LEVEL=info
export LOG_FILENAME=/tmp/mcp-sandbox.log
./mcp-sandbox
Profiles (operator-authored)
Sandboxes are created from operator-authored, read-only YAML profiles — one
<name>.yml per profile under SANDBOX_PROFILES_DIR (default
~/.config/sandbox/profiles). Profiles are read on demand — the server
scans SANDBOX_PROFILES_DIR on each profile lookup, so editing a <name>.yml
takes effect immediately without restarting the server. A profile fully
determines the sandbox runtime:
image, env, mounts, network, cgroup limits, user and sudo. There are no
profile create/update/delete tools; the model references a profile by name
on sandbox_create, and profile_list enumerates what's available.
Example ~/.config/sandbox/profiles/default.yml:
name: default
description: the default profile
image: alpine@sha256:0000000000000000000000000000000000000000000000000000000000000000 # digest-pinning recommended — replace with the real <repo>@sha256:<64 hex>
env:
FOO: bar
mounts:
- source: /data
target: /data
read_only: true
cwd:
target: "" # empty ⇒ mounted 1:1 at the same absolute path (default)
mode: ro # ro (default) | rw
network:
mode: bridge # bridge (default) | none | host
cgroups:
cpu_cores: 1 # human-readable: whole/virtual cores (1.0 = one core)
memory_gb: 1 # human-readable: whole GiB (swap disabled ⇒ memory_swap = memory)
pids_limit: 256
ulimits:
- name: nofile
soft: 1024
hard: 1024
user:
uid: 1000
gid: 1000
sudo: never
The example above is a minimal schema illustration. For a complete,
real-world profile, see examples/profiles/golang.yml — copy it into
SANDBOX_PROFILES_DIR as golang.yml and fill in the <PLACEHOLDER> values
(git identity, host paths). It defaults Go's build caches
(GOCACHE/GOTMPDIR/GOMODCACHE) so go build/go test work out of the
box inside the sandbox.
ALLOW_DIRS still gates every host path — both the session cwd and
every profile mounts.source must be inside it (§7.2).
profile_list returns only name/description — env, mounts, image, user
and sudo are never exposed (S02).
- Full schema and trust model:
SPEC.md §7.11.
Migration from the old sandbox_create
sandbox_create is breaking in Phase 7: the per-request parameters
image, env, mounts, nano_cpus, memory, pids_limit, uid, gid,
sudo are removed and now come from a profile. profile and cwd are now
both required (with session_id). To migrate:
- Author a profile capturing the desired image/env/mounts/limits/user/sudo in
SANDBOX_PROFILES_DIR (see above).
- Call
sandbox_create with { "profile": "default", "session_id": "...", "cwd": "...", "secrets": [...] } — no other runtime knobs.
- Any un-migrated caller that passes the old parameters is rejected with
InvalidParams.
Transport, auth & TLS notes
- Transport: STDIO only. The server is spawned as a local child process by
the model-host; it opens no network listener.
- Auth: environment variables only. No OAuth2 — there is no upstream
HTTP API to authorize against (see
SPEC.md §3.3).
- TLS: never implemented in-server (S01). The server has no HTTP
listener, so there is no in-server TLS surface. If the server is ever placed
behind a network-facing gateway, TLS termination is the reverse proxy's job.
Sandbox lifecycle
Sandboxes follow create → use → destroy:
sandbox_create provisions a per-session container.
sandbox_exec and the read tools operate on it.
sandbox_destroy destroys one sandbox; sandbox_destroy_all destroys every
sandbox.
Cleanup is explicit only — there is no automatic GC. A sandbox is removed
only when the model-host calls sandbox_destroy / sandbox_destroy_all;
otherwise it persists until then. There is no idle reaper and no orphan
reclamation. An automatic idle reaper and orphan cleanup are future work
(see TODO.md).
OpenCode setup
Use mcp-sandbox as the execution environment for opencode instead of the
host shell.
1. Disable the host shell
In your opencode config (opencode.jsonc), deny the built-in shell tool:
{
"$schema": "https://opencode.ai/config.json",
"permissions": [
{ "action": "shell", "resource": "*", "effect": "deny" }
]
}
This removes the host bash/shell tool; the model then uses the sandbox MCP
for command execution.
2. Register the mcp-sandbox MCP server
mcp-sandbox is a Local / stdio server, so register it as a local MCP
server:
{
"mcp": {
"servers": {
"mcp-sandbox": {
"type": "local",
"command": ["mcp-sandbox"],
"environment": {
"ALLOW_DIRS": "{env:PWD}",
"LOG_LEVEL": "info"
}
}
}
}
}
command launches the mcp-sandbox binary (put it on PATH or use an
absolute path).
ALLOW_DIRS scopes which host directories the sandbox may reach; it gates the
session working directory (mounted 1:1 at the same absolute path) and
every profile mount source (see SPEC.md §7.2).
- opencode passes its session id as a required
session_id parameter to
sandbox_create; the server records it as a container label so each sandbox
is traceable to the OpenCode session that created it. sandbox_create also
takes a required profile name (from SANDBOX_PROFILES_DIR) and
required cwd. The session cwd is mounted 1:1 read-only by default (see
SPEC.md §7.2, §7.11).
- Use
opencode mcp list / /mcps to check the server is connected.
HITL note: because mcp-sandbox is Local/stdio (no HTTP UI), destructive
tools (sandbox_destroy, sandbox_destroy_all) require confirmation
client-side by the operator — see SPEC.md §4.4.
Grouped read → write → delete (S03):
- Read (
readOnlyHint: true): sandbox_list, sandbox_info,
sandbox_stats, profile_list (lists operator-authored profiles as
name/description — read-only, no leakage).
- Write/update (
readOnlyHint: false, destructiveHint: false):
sandbox_create (requires profile — the profile name from
SANDBOX_PROFILES_DIR, session_id — the OpenCode client session id recorded
as a container label for traceability, and cwd; optional secrets; session
cwd mounted 1:1 read-only by default per the profile's cwd.mode),
sandbox_exec (requires id and command — a scalar string with the full
command line, executed via the profile-configured shell as a fixed
[<shell>,"-c",command] wrapper; optional env — a map[string]string of
per-exec KEY=VALUE environment entries, literal, no shell evaluation —
and optional summary — a short human-readable description of the command,
e.g. "run unit tests", used to display the command in the tool-call header by
MCP clients; purely presentational and not passed to execution; also optional
working_dir, timeout and user; write-classified; ANSI-sanitized;
redacted command; streams live output via notifications/progress when a
progress token is passed, §5.1; optional timeout in seconds applied as a
context.WithTimeout cancellation, §6.10).
- Delete (
destructiveHint: true): sandbox_destroy, sandbox_destroy_all.
Files come from the image, the host, or the runtime — never via MCP
file-write tools. The session cwd is mounted 1:1, so the model-host writes
files on the host and the container reads/executes them at the same path;
runtime artifacts live in the writable tmpfs /tmp (executable where the
daemon honours exec; on daemons that force noexec — e.g. Docker Desktop —
compilation goes into the writable bind-mounted cwd per the profile's
cwd.mode). There are no
sandbox_read_file / sandbox_write_file / sandbox_copy_in /
sandbox_copy_out / sandbox_install_package tools — mount + exec is the
core mechanism (SPEC.md §4.2, §7.2).
All tools are openWorldHint: false and carry per-tool annotations +
instructions (SPEC.md §4).
Human-in-the-loop (HITL) for destructive tools: because this is a
Local / stdio-only server with no HTTP UI (S12), destructive confirmation
is implemented client-side — the model-host (opencode) obtains human
confirmation before invoking sandbox_destroy / sandbox_destroy_all.
Self-describing MCP server
mcp-sandbox is self-describing over the MCP protocol: a model-host client
can discover everything it needs without any external file (SPEC.md §5.2).
- Server-level
Instructions — a short paragraph carrying the redirect
invariant ("The host shell is restricted — route commands through this
sandbox server."), tool grouping (read → write → delete), a secrets warning
(never put secrets in a command or env — use tmpfs 0600 secret files on
sandbox_create), and an index of the guidance resources.
resources capability — six read-only markdown playbooks are
registered under sandbox://guidance/* and appear in the MCP catalog:
overview, shell-restricted-redirect, sandbox-create, sandbox-exec,
filesystem-mounts (incl. the GOCACHE/GOTMPDIR recipe for compile-in-
sandbox), and security. This is the only use of resources — file I/O
still never goes through MCP resources (files come from the image, the host,
or the runtime via mount + exec).
- Enriched tool descriptions —
sandbox_create / sandbox_exec carry a
redirect note and a pointer to the relevant guidance resource, directing the
model away from the host shell exactly where those tools are invoked.
There is no standalone skill file and no AGENTS.md pointer — the
self-description travels with the server over the protocol, so it stays in sync
with the implementation automatically.
Security
The sandbox replaces the host shell, so security is enforced by the server
and cannot be weakened by a caller (SandboxSpec.Isolation is immutable):
- Read-only rootfs; drop-all capabilities (minimal re-add); no-new-
privileges; seccomp (default MVP profile; custom profile is mandatory
roadmap); non-root user inside.
- Bounded
PidsLimit, Memory/MemorySwap, NanoCPUs, Ulimits (from the
profile's cgroups, §7.11).
- Network comes from the operator profile —
bridge (default) or none;
host is permitted only when the operator authors it into a profile, never
implicitly.
- tmpfs mounts:
/run (rw,noexec,nosuid,nodev, sandbox-user-owned, holds the /run/sandbox secrets dir) and /tmp (rw,nosuid,nodev, writable; some daemons like Docker Desktop force noexec on tmpfs, so runtime compilation uses the writable bind-mounted cwd); AutoRemove=true.
- Host filesystem access only via
ALLOW_DIRS, read-only by default,
symlink-safe (EvalSymlinks + open-then-verify); this gates the
session cwd and every profile mount source; the session cwd is the
sanctioned bind-mount (read-only default).
- Single redaction layer hides
secret:true fields from all output and
logs; secrets delivered as tmpfs 0600 files under /run/sandbox, never
command-line/image.
- No shell-string concatenation/interpolation (S11/N21):
sandbox_exec
takes a scalar command passed as one element of a fixed
[<shell>,"-c",command] wrapper (shell from the profile, default bash,
§7.11) — no user string is interpolated into a shell string; the only other
sh -c is the server-authored fixed secret-writer script.
- Sessions use opaque
crypto/rand ids with label-based Docker ownership.
- Operator-authored profiles (Phase 7): the image, env, mounts, network,
limits, user and sudo are declared in read-only YAML files the model
references by name; a profile can never weaken the immutable
Isolation
block (§7.11).
- Supply chain: sandbox images come from the operator profile with parse-only
validation; digest-pinning is the recommended operator convention
(§7.9), and dependencies are pinned to latest stable, signed packages.
Docker socket access (known limitation)
The Docker socket (/var/run/docker.sock) is effectively root on the host.
The server mitigates this by preferring a rootless Docker daemon or running
in an isolated environment with socket access confined to the server process.
Review and choose the socket access model appropriate to your host. See
SPEC.md §7.6.
Development
TDD workflow
All fixes/features are done TDD-style (T01): @qa writes tests first
(isolated context), @developer writes the implementation (isolated context).
Tests are never weakened to make the implementation pass.
- Unit tests:
make test — go test -race + coverage ≥ 95% gate
(fails below).
- Mutation testing: gremlins as a hard gate (80/80) — dedicated CI job.
- e2e: out of scope for this Local server (no e2e suite, no
make e2e —
a real e2e would need Docker-in-Docker, conflicting with the immutable
sandbox hardening; the handler→backend path is covered by unit tests).
Quality gates
CI (GitHub Actions) binds to the make interface (R07) and enforces:
make lint (golangci-lint, gosec, govulncheck, go-arch-lint), make test
(race + coverage ≥ 95%), make build (goreleaser), plus hard-gate
jobs for gremlins (mutation) and gitleaks (secret scan). Findings are
fixed, not suppressed. CI never mutates repository state.
License
See LICENSE.