Docker MCP Sandbox
Provides secure, ephemeral Docker container sandboxes via the Docker Engine API, including sandbox creation with CPU/memory limits, file read/write operations through in-memory tar streams, shell command execution with timeout enforcement, and lifecycle management (list/destroy) of running containers.
Provides Git workflow automation inside sandbox containers, with tools to initialize repositories, check status, generate diffs, create commits, and view commit logs.
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., "@Docker MCP Sandbox spin up a sandbox, run npm test, and show the output"
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.
π³ Docker MCP Sandbox
An enterprise-ready Model Context Protocol (MCP) server providing secure, disposable, and resource-bounded Docker container sandboxes for AI agents. Designed for autonomous LLM systems (such as Claude Desktop, Cursor IDE, and custom agent orchestration engines), this server allows agents to create files, inspect code, run shell commands with execution timeouts, and perform Git operations without endangering the host environment.
π Table of Contents
Related MCP server: Secure Grid Genesis Execution
π Overview
Autonomous AI coding agents frequently require terminal access, filesystem manipulation, and dependency installation. Allowing untrusted agentic actions directly on a developer workstation or production host introduces severe risks:
Accidental deletion or overwrite of host files and system paths.
Unconstrained execution loops consuming memory and CPU.
Host environment contamination through rogue background processes.
Accidental disclosure of local environment variables and developer credentials.
Docker MCP Sandbox solves this by establishing a secure boundary between the agent and host. Every workspace is provisioned inside an ephemeral Docker container bounded by strict CPU and memory limits. Files are ingested and extracted via memory-buffered tar streams, and shell commands are demuxed in real-time with configurable millisecond timeout limits.
ποΈ System Architecture
The following diagram illustrates the complete execution pipeline from AI prompt to containerized isolation:
flowchart TD
subgraph HostEnvironment["Host Machine"]
Agent["AI Agent / LLM Orchestrator<br/>(Claude Desktop / Cursor / Custom Agent)"]
subgraph MCPServer["Docker MCP Sandbox Server (Node.js + TypeScript)"]
Transport["Stdio Transport<br/>(JSON-RPC 2.0 Protocol)"]
Router["MCP Request Router<br/>(Tools Schema Validation via Zod)"]
Logger["Stdio-Safe Logger<br/>(Writes to server.log & stderr)"]
subgraph ToolsModule["Exposed MCP Toolsets"]
SBoxTools["Sandbox Tools<br/>β’ create_sandbox<br/>β’ write_file<br/>β’ read_file<br/>β’ execute_command<br/>β’ destroy_sandbox<br/>β’ list_sandboxes"]
GitTools["Git Tools<br/>β’ git_init<br/>β’ git_status<br/>β’ git_diff<br/>β’ git_commit<br/>β’ git_log"]
end
SandboxMgr["SandboxManager<br/>(Dockerode Engine Client)"]
StreamDemuxer["Docker Stream Demuxer<br/>(Separates stdout & stderr buffers)"]
TarStreamer["Tar Stream Pack/Extract<br/>(In-Memory File Ingestion)"]
end
DockerSocket["Docker Daemon Socket / Pipe<br/>(Windows: //./pipe/docker_engine)<br/>(POSIX: /var/run/docker.sock)"]
end
subgraph DockerEngine["Docker Runtime (Containerized Execution)"]
subgraph ContainerInstance["Ephemeral Container (mcp-sandbox)"]
cgroups["Kernel cgroups Constraints<br/>(RAM: 128MB-4GB | NanoCPUs: 0.2-4.0)"]
Workspace["Isolated Directory: /workspace"]
SubProcess["Command Runner (/bin/sh -c)<br/>(Enforces Timeout: default 30s)"]
GitWorkspace["Internal Git Repo (/workspace/.git)"]
end
end
Agent <-->|"JSON-RPC (stdio)"| Transport
Transport --> Router
Router --> ToolsModule
ToolsModule --> SandboxMgr
SandboxMgr --> Logger
SandboxMgr <-->|"Docker Engine API"| DockerSocket
DockerSocket <-->|"Container Lifecycle & Streams"| ContainerInstance
SandboxMgr --> TarStreamer
TarStreamer <-->|putArchive / getArchive| Workspace
SandboxMgr --> StreamDemuxer
StreamDemuxer <-->|demuxStream| SubProcess
Workspace --- SubProcess
Workspace --- GitWorkspaceβ‘ Core Engineering Highlights
1. Pure Stdio Protocol Safety
MCP servers rely strictly on process.stdout for JSON-RPC frame serialization. Unchecked console.log() statements from libraries or diagnostics will instantly corrupt framing, severing connection to the client. Docker MCP Sandbox incorporates a dedicated Stdio-safe logger that directs all operational diagnostics to server.log (resolved relative to the project root) and mirrors warnings to process.stderr, guaranteeing absolute protocol integrity.
2. Native Cross-Platform Socket Resolution
Seamlessly interoperates with Docker on all operating systems without manual socket mapping:
Windows: Automatically binds to the named pipe
//./pipe/docker_engine.macOS / Linux: Automatically connects to
/var/run/docker.sock.Remote / Custom: Respects explicit
DOCKER_HOSTenvironment configurations.
3. Path Traversal & Escape Prevention
Every file access operation (read_file, write_file, and working directory selection) undergoes strict path sanitization. Relative path normalizations reject path traversal sequences (..), leading slashes, null byte injections (\0), and Windows drive letter patterns (C:), enforcing containment within /workspace.
4. Tar-Stream Memory Multiplexing
File uploads and downloads do not mount host directories or generate temporary files on the host disk. Instead, files are packaged as in-memory POSIX tar streams using tar-stream and streamed directly via the Docker Engine API putArchive and getArchive endpoints.
5. Stream Demuxing & Command Timeout Enforcement
Commands executed inside containers run under an active watch timer. If a command runs past its allocated duration (default 30 seconds), execution aborts with standard POSIX timeout exit code 124. Output streams are demultiplexed via docker.modem.demuxStream, reliably separating stdout from stderr.
6. Orphan Container Sweeping & Graceful Teardown
Each container is provisioned with custom metadata labels (mcp-sandbox=true and mcp-sandbox-id). The server registers lifecycle hooks for SIGINT, SIGTERM, uncaughtException, and unhandledRejection, automatically inspecting the daemon and destroying active or orphaned sandboxes upon exit.
π οΈ Technical Stack
Category | Technology | Purpose |
Runtime | Node.js (v20+ LTS) | Primary server runtime utilizing modern ES Modules ( |
Language | TypeScript (v5.8+) | End-to-end type safety, declaration generation, and static validation |
Protocol |
| Official MCP implementation for server-client JSON-RPC communication |
Containerization |
| Programmatic Docker Engine API client for container orchestration |
Archival Streaming |
| In-memory streamable tar packing/extracting for file I/O |
Schema Validation |
| Runtime schema enforcement for all incoming tool parameters |
Testing Harness |
| Full end-to-end integration and security test suite |
π§° Available MCP Tools
The server exposes 11 specialized tools split across core sandbox execution and version control:
Sandbox Management & Execution
Tool | Parameters | Default | Description |
|
|
| Provisions an isolated Docker container with a |
|
| (required)(required)(required) | Writes text or code to |
|
| (required)(required) | Reads file contents and byte length from |
|
| (required)(required) | Executes a shell command inside the container; returns |
|
| (required) | Immediately terminates and removes the container, reclaiming host resources. |
| none | none | Returns a listing of all currently running sandbox containers and their metadata. |
Git Workflow Automation
Tool | Parameters | Default | Description |
|
| (required) | Initializes a Git repository in |
|
| (required) | Inspects working directory state and uncommitted/untracked files. |
|
| (required) | Returns unified diffs for unstaged changes, or staged changes if |
|
| (required)(required) | Stages specified files and commits with the provided message and author attributes. |
|
| (required) | Retrieves recent commit history formatted as structured JSON objects ( |
π Docker Sandbox Execution Workflow
Here is a typical interaction pattern executed by an AI agent:
[Agent] ββ> create_sandbox({ image: "node:20-alpine", memoryLimitMb: 512 })
βββ Returns: { sandboxId: "8dfa723f-ed58-434d-9960-8c755964cf1a" }
[Agent] ββ> write_file({ sandboxId, path: "calc.js", content: "console.log(10 * 5);" })
βββ Returns: { success: true, bytesWritten: 25, path: "calc.js" }
[Agent] ββ> execute_command({ sandboxId, command: "node calc.js" })
βββ Returns: { stdout: "50\n", stderr: "", exitCode: 0, executionTimeMs: 120 }
[Agent] ββ> git_init({ sandboxId })
βββ Returns: { initialized: true, stdout: "Initialized empty Git repository..." }
[Agent] ββ> git_commit({ sandboxId, message: "feat: add initial math script" })
βββ Returns: { success: true, output: "[main (root-commit)] feat: add initial..." }
[Agent] ββ> destroy_sandbox({ sandboxId })
βββ Returns: { success: true, message: "Sandbox successfully destroyed." }π‘οΈ Security Model & Resource Controls
What This Sandbox Guarantees
Host Filesystem Isolation: Container processes run inside isolated container layers. The host filesystem is never mounted into the container.
Resource Quotas: Hard RAM thresholds (
Memory) prevent Out-Of-Memory (OOM) lockups on the host machine. NanoCPUs throttles compute consumption.Execution Containment: Infinite loops or hung commands are halted automatically when
timeoutMsexpires.Path Confinement: Path traversal checks reject attempts to manipulate paths outside
/workspace.
Honest Security Disclosures & Production Considerations
Shared Kernel Architecture: Docker containers share the host Linux kernel (or WSL2 VM on Windows). Containerization provides practical process isolation, but is not an impenetrable security sandbox against sophisticated kernel-level privilege escalation or zero-day kernel exploits.
Network Access: Containers currently default to Docker
bridgenetworking, permitting outgoing HTTP/HTTPS calls (useful fornpm install,pip install, orapk add). For ultra-high-security environments requiring air-gapped sandboxes, NetworkMode can be configured tonone.Root inside Container: The container runtime runs under default image users (often root within the container namespace). While confined from host root privileges, running untrusted compiled binary executables should be evaluated carefully in multi-tenant environments.
π Getting Started
Prerequisites
Node.js:
v20.0.0or highernpm:
v10.0.0or higherDocker: Docker Desktop (Windows/macOS) or Docker Engine (Linux) running locally
Installation & Compilation
# 1. Clone the repository
git clone https://github.com/thedailyhub31-blip/docker-mcp-sandbox.git
cd docker-mcp-sandbox
# 2. Install dependencies
npm install
# 3. Compile TypeScript code
npm run buildThe compiled JavaScript output and type declarations will be placed into the dist/ directory.
Automated Verification Harness
A full end-to-end verification script is included to validate the entire workflow (container lifecycle, file I/O, path traversal defenses, timeouts, and Git tools):
npm run test:clientSample successful verification output:
======================================================
MCP DEV SANDBOX - AUTOMATED VERIFICATION SUITE
======================================================
β Connected to MCP Server over Stdio transport.
β Found 11 available tools.
β create_sandbox: container running with node:20-alpine
β write_file: wrote 240 bytes to /workspace/src/app.js
β read_file: successfully verified content integrity
β execute_command: exitCode: 0, executionTime: 1012ms
β Command timeout: sleep 10 correctly aborted after 2000ms (exit code 124)
β Path traversal defense: blocked malicious relative traversal
β Git tools: initialized, tracked, committed, and extracted log history
β destroy_sandbox: container cleanly removed
======================================================
ALL MCP DEV SANDBOX VERIFICATIONS PASSED SUCCESSFULLY!
======================================================βοΈ Client Integration Configurations
Claude Desktop
To connect Docker MCP Sandbox to Claude Desktop:
Open your Claude configuration file:
Windows:
%APPDATA%\Claude\claude_desktop_config.jsonmacOS:
~/Library/Application Support/Claude/claude_desktop_config.json
Add
docker-mcp-sandboxto themcpServersobject:
{
"mcpServers": {
"docker-mcp-sandbox": {
"command": "node",
"args": [
"<PATH_TO_PROJECT>/dist/index.js"
]
}
}
}(Replace <PATH_TO_PROJECT> with your absolute local repository path, e.g. C:/Users/username/Desktop/docker-mcp-sandbox)
Cursor IDE
To use Docker MCP Sandbox in Cursor:
Create or open
.cursor/mcp.jsoninside your project or home directory:
{
"mcpServers": {
"docker-mcp-sandbox": {
"command": "node",
"args": [
"${workspaceFolder}/dist/index.js"
]
}
}
}Restart Cursor or reload MCP servers to enable the sandbox tools in agent mode.
π Project Layout
docker-mcp-sandbox/
βββ src/
β βββ index.ts # MCP Server bootstrap, Stdio transport, shutdown lifecycle
β βββ docker/
β β βββ sandboxManager.ts # Dockerode client, container management, tar streaming, timeouts
β βββ tools/
β β βββ sandboxTools.ts # Core sandbox MCP tools (create, write, read, exec, destroy, list)
β β βββ gitTools.ts # Git workflow MCP tools (init, status, diff, commit, log)
β βββ utils/
β βββ logger.ts # Stdio-safe logger writing to server.log and mirroring to stderr
βββ scripts/
β βββ test-client.ts # Automated end-to-end integration test harness
βββ dist/ # Compiled production code (generated by build)
βββ package.json # Project dependencies, scripts, and package metadata
βββ tsconfig.json # TypeScript compiler configuration (NodeNext, ES2022)
βββ .gitignore # Exclusions for build artifacts, node_modules, and secrets
βββ LICENSE # MIT Open-Source License
βββ README.md # Engineering documentation and architectural guideπΊοΈ Roadmap & Future Enhancements
Configurable Network Policies: Toggle network isolation mode (
bridgevsnone) dynamically per sandbox.Pre-Warmed Container Pools: Maintain warm container standby pools to reduce startup latency under heavy multi-agent workloads.
Custom Volume Cache Mounts: Allow controlled read-only package caching (e.g. shared
npm-cacheorpip-cache) across ephemeral runs.WebAssembly / MicroVM Backend: Support pluggable hypervisor backends (Firecracker or gVisor) for enhanced multi-tenant security isolation.
π License
Distributed under the MIT License. Free for commercial and private open-source use.
Available Tools
11 toolscreate_sandboxB
Spawns a new isolated Docker container sandbox with a dedicated /workspace directory, resource quotas, and bash/sh environment.
Inputs: env, image, cpuLimit, memoryLimitMb.
destroy_sandboxA
Stops and permanently removes an ephemeral Docker sandbox container and frees associated resources.
Inputs: sandboxId (required).
execute_commandA
Executes a shell command inside the sandbox container at /workspace with timeout enforcement (default 30s) and captures demuxed stdout, stderr, and exitCode.
Inputs: command (required), sandboxId (required), timeoutMs, workingDir.
git_commitC
Stages specified files and creates a Git commit in the sandbox.
Inputs: message (required), sandboxId (required), addFiles, authorName, +1 more.
git_diffC
Shows changes between commits, commit and working tree, etc.
Inputs: sandboxId (required), file, cached.
git_initB
Initializes a Git repository in the sandbox workspace and sets default author configs.
Inputs: sandboxId (required), userName, userEmail, initialBranch.
git_logC
Returns recent commit history in the sandbox repository.
Inputs: sandboxId (required), maxCount.
git_statusB
Shows the working tree status in the sandbox repository.
Inputs: sandboxId (required).
list_sandboxesA
Lists all active Docker sandbox instances managed by this MCP server.
Inputs: no named parameters.
read_fileA
Safely reads the contents of a file inside the sandbox /workspace directory. Enforces path traversal security checks.
Inputs: path (required), sandboxId (required).
write_fileA
Safely creates or overwrites a file at a relative path inside the sandbox /workspace directory. Includes path traversal security checks.
Inputs: path (required), content (required), sandboxId (required).
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelogβ¦
TDQS
Scored across 11 tools
Each tool maps to a distinct resource+action pair: sandbox lifecycle (create/list/destroy), workspace file IO (read/write), command execution, and a clearly delimited git_* family. The only soft overlap is that execute_command can perform anything the git_* tools do, so an agent may bypass the structured git wrappers, but the intent of each tool is still clear.
Ten tools follow a clean verb_noun snake_case pattern (create_sandbox, write_file, read_file, execute_command, destroy_sandbox, list_sandboxes), and the git group consistently uses a shared git_ prefix. The git_ prefix group is noun_verb rather than verb_noun, a minor convention shift but internally predictable and readable.
Eleven tools is well within a comfortable range and each earns its place: five sandbox/file primitives plus five git operations that provide structured, safer alternatives to raw shell calls. No redundant or filler tools are present.
Sandbox lifecycle is fully covered (create, list, destroy) and the git surface covers init/status/diff/commit/log, which handles the core workflow. File handling lacks delete_file and list_directory/preview operations, and git lacks branching/checkout, but an agent can work around these via execute_command.
Maintenance
Related MCP Connectors
Persistent cloud workspaces for AI agents: run commands, edit files, use git and a browser.
Cloud Linux VMs for your agent: run code, Docker, files and HTTPS previews in a Sandboxer microVM.
Run AI agent tasks in isolated sandboxes with a cost cap, saved workflows and scoped connections.
Linux microVM sandboxes for AI agents: run commands, files, processes, pause and wake.
Related MCP Servers
- AlicenseNot gradedqualityNot gradedmaintenanceProvides AI coding agents with a secure, sandboxed environment for executing coding tasks including file operations, command execution, and testing. Features session management, policy enforcement, and Docker-based sandboxing for safe code execution and development workflows.MIT
- FlicenseNot gradedqualityDmaintenanceEnables AI agents to safely execute Python, JavaScript, and Bash code in an isolated Docker sandbox with strict security constraints.1-
- AlicenseNot gradedqualityCmaintenanceProvides a restricted Docker-based sandbox for LLM agents, enabling file operations, command execution, and local Git within an isolated runtime.9 npmMIT
- AlicenseAqualityBmaintenanceEnables AI coding agents to safely execute commands, run tests, and modify project files inside disposable, policy-enforced Docker sandboxes that are isolated from the host machine and its credentials.15MIT