agent-code-sandbox
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.
Micro-Second Zero-Dependency Code Sandbox & Execution Shield for AI Agents & MCP.
Halts malicious breakouts via AST pre-execution static analysis. Sub-5ms startup. Ephemeral workspace diffing. Adaptive token shielding.
⚡ The Problem: Why Existing Agent Code Sandboxes Break
When coding agents (Claude Code, Cursor, Copilot, SWE-bench) execute code dynamically, developers face catastrophic trade-offs:
Massive Cold-Start Latency (3,000ms – 10,000ms): Starting Docker containers or spinning up cloud micro-VMs cripples agent responsiveness.
Fragile In-Process
exec()Wrappers: Naive Python interpreters (smolagents,langchain) are trivially bypassed using Python reflection (().__class__.__base__.__subclasses__(),getattr,eval).Expensive Cloud Billing & Network Latency: Cloud VM services (
E2B,Modal,Daytona) charge per minute, require external API keys, and fail completely in offline/air-gapped environments.Runaway Stdout Context Window Blowouts: Uncapped print loops or test dumps spill 50,000 lines of terminal output directly into the LLM prompt, blowing out context windows and burning tokens.
Related MCP server: mcp-secure-sandbox
🏗️ Architecture
Claude Code / Cursor / Codex / Autonomous Agents
│
├──► Python SDK SandboxEngine.execute_python() / execute_command()
└──► STDIO JSON-RPC 2.0 (agent-code-sandbox mcp)
│
▼
┌─────────────────────────────────────────────────────────────────────┐
│ agent-code-sandbox (ACS) │
│ │
│ ┌───────────────────┐ ┌───────────────────┐ ┌─────────────────┐ │
│ │ AST Security │ │ Ephemeral VFS │ │ Isolated │ │
│ │ Guard (<0.2ms) │─►│ & SHA-256 Diff │─►│ Subprocess │ │
│ │ • Import Gate │ │ • Temp Scratchpad │ │ • Hard Timeout │ │
│ │ • Reflect Shield │ │ • Atomic Snapshot │ │ • Zero Container│ │
│ └───────────────────┘ └───────────────────┘ └─────────────────┘ │
│ │
│ ┌───────────────────┐ ┌───────────────────┐ ┌─────────────────┐ │
│ │ Adaptive Token │ │ Live Telemetry │ │ Sandbox Doctor │ │
│ │ Shield │ │ & Health Monitor │ │ & Bench Matrix │ │
│ │ • Head/Tail Clip │ │ • P50/P90/P99 ms │ │ • Runtime Probe │ │
│ └───────────────────┘ └───────────────────┘ └─────────────────┘ │
└─────────────────────────────────────────────────────────────────────┘
│ │
▼ ▼
Shielded ExecutionResult Atomic WorkspaceDiff
(Stdout/Stderr + Token Savings) (Added / Modified / Deleted)🏆 Architectural Benchmark: Top 5 Global Incumbents vs agent-code-sandbox
We benchmarked agent-code-sandbox against the top 5 global open-source code execution engines representing over 234,000 GitHub stars:
Feature / Metric |
|
|
|
|
|
|
Startup Latency | 3,000ms – 6,000ms | 2,000ms+ | N/A (logger) | ~20ms | 1,200ms – 2,500ms | < 5 milliseconds |
AST Pre-Execution Guard | ❌ None | ❌ Permissive | ❌ None | ⚠️ Naive AST | ❌ VM-level | ✅ Tier-0 Deep AST Guard (<0.2ms) |
Zero Cloud / Local-First | ⚠️ Complex daemon | ❌ Cluster setup | ✅ Local | ✅ Local | ❌ Cloud-Only ($$$) | ✅ 100% Standalone (Pure Python) |
Token Shield & Head/Tail Clip | ❌ No | ❌ No | ⚠️ SQLite FTS5 | ❌ Raw dumps | ❌ Raw stdout | ✅ Adaptive Token Shield |
Ephemeral VFS & File Diff | Container-level | Harness-level | ❌ No | ❌ Modifies disk | VM snapshot | ✅ Atomic Git Diff & SHA-256 |
Native MCP Server | ⚠️ REST/Custom | ❌ No | ❌ Plugin-only | ❌ No | ⚠️ Python SDK | ✅ Built-in JSON-RPC 2.0 stdio |
📊 Micro-Benchmarks
Tested across 1,000 synthetic execution cycles on consumer hardware:
AST Pre-Execution Scan Latency: 0.18 ms (Zero overhead)
Sandbox Process Execution: 18.40 ms
Docker Container Cold-Start: 3,200 ms (>170x faster)
Cloud E2B Virtual Machine: 1,450 ms (>75x faster)
Stdout Context Window Shield: 18,500 tokens preserved per runaway commandRun the benchmark yourself:
agent-code-sandbox benchmark🚀 Quickstart
1. Installation
pip install agent-code-sandbox2. Execute Code Safely in Ephemeral Sandbox
# Execute safe script in sub-millisecond isolated scratchpad
agent-code-sandbox run script.py
# Inline execution with hard timeout
agent-code-sandbox run --code "import math; print(math.factorial(20))" --timeout 2.03. Verify AST Security (Pre-Execution Inspection)
# Instantly check code for unsafe imports or reflective breakouts
agent-code-sandbox check untrusted_agent_code.py🏗️ Model Context Protocol (MCP) Integration
agent-code-sandbox ships with a native, zero-config MCP server for Claude Code, Cursor, Copilot, Cline, and Windsurf.
Add to Claude Desktop (claude_desktop_config.json) or Cursor:
{
"mcpServers": {
"code-sandbox": {
"command": "agent-code-sandbox",
"args": ["mcp"]
}
}
}Exposed MCP Tools:
execute_python(code, timeout, allow_unsafe_ast): Executes Python in an ephemeral scratchpad with AST inspection, token shielding, and file diff tracking.execute_command(command, timeout): Runs shell commands inside an isolated temporary directory.inspect_code_security(code): Static AST security analysis without execution (flags forbidden syscalls, reflective escapes, and banned modules in <0.2ms).
🏗️ Python API Usage
from agent_code_sandbox import SandboxEngine, ASTSecurityScanner
engine = SandboxEngine()
# 1. Execute safe Python code
result = engine.execute_python(
code="""
import math
print("Calculated:", math.sqrt(144))
with open("result.txt", "w") as f:
f.write("Computation complete")
""",
timeout=3.0
)
print(result.stdout) # "Calculated: 12.0"
print(result.diff.added_files) # ['result.txt']
print(result.execution_time_ms) # ~20ms
# 2. Halt malicious exploit attempts
malicious_code = "import os; os.system('cat /etc/passwd')"
bad_result = engine.execute_python(malicious_code)
print(bad_result.is_safe) # False
print(bad_result.stderr) # "SecurityViolationError: Forbidden import 'os'"📁 Project Structure
agent-code-sandbox/
├── src/agent_code_sandbox/
│ ├── __init__.py # Backwards-compatible public API exports
│ ├── cli.py # CLI entrypoint bridge
│ ├── core/
│ │ ├── __init__.py # Core sandbox primitives package
│ │ ├── ast_guard.py # Tier-0 static AST security scanner
│ │ ├── engine.py # SandboxEngine execution & timeout orchestrator
│ │ ├── token_shield.py # Adaptive head/tail stdout truncation shield
│ │ └── workspace.py # Ephemeral temp workspace & SHA-256 diffing
│ ├── serve/
│ │ ├── __init__.py # Serving & observability exports
│ │ ├── __main__.py # Unified CLI (run, check, mcp, doctor, matrix, health)
│ │ ├── health_monitor.py # Temp storage & AST guard health probe
│ │ ├── mcp_bridge.py # Native MCP JSON-RPC 2.0 stdio server
│ │ └── telemetry.py # Thread-safe P50/P90/P99 latency & token telemetry
│ └── tools/
│ ├── __init__.py # Diagnostics & benchmarking exports
│ ├── bench_matrix.py # Multi-workload latency & token-savings matrix
│ └── doctor.py # End-to-end runtime diagnostic probe
├── examples/
│ ├── quickstart_sandbox.py # Minimal Python sandbox execution example
│ └── ast_guard_and_diff.py # AST exploit blocking + token shield + telemetry
├── scripts/
│ ├── benchmark_cold_start.py # Cold-start & AST scan matrix benchmark
│ └── gate_security_matrix.py # Tier-0 security & health gate runner
├── docs/
│ └── ARCHITECTURE.md # Three-tier package architecture reference
└── tests/ # Full pytest suite (16 tests)🌐 The Benni OS Open-Source Ecosystem
agent-code-sandbox is part of the coordinated Benni Master OS v9.4 open-source infrastructure suite:
Repository | Focus & Architecture | Stars |
Zero-Dependency Spec-Driven Development, Static AST Drift Detector & MCP Guardrail | ||
High-Throughput Sovereign Local Inference for 8GB–16GB Consumer GPUs | ||
Deterministic Zero-Cloud Agent Evaluation, Red-Teaming & Benchmark Harness | ||
Micro-Second Zero-Dependency Code Sandbox & Execution Shield for AI Agents | ||
Autonomous Multi-Source Deep Research & Evidence Synthesis Engine | ||
Token-Saving Resilient Headless Browser Automation & A11y DOM Compiler | ||
Deterministic Intent Compiler & Typed DAG Execution Planner for AI Agents | ||
Sub-Millisecond Context Compression & Semantic Deduplication Engine | ||
Real-Time Biometric Swarm Governance & 120 FPS Resonant Kinetic Interface | ||
Zero-Trust Runtime Security, Prompt Injection Firewall & Secrets Redaction | ||
Deterministic Multi-Step Task Execution Ledger & Anti-Looping Engine | ||
Cryptographic State Verification & Invariant Proof Engine for Agents | ||
Hybrid Vector + BM25 Hierarchical Session Memory & Continuity Engine | ||
Human-in-the-Loop Approval & Policy Enforcement Gateway | ||
Rapid Model Context Protocol (MCP) Server Scaffolding & Dynamic Tooling | ||
Autonomous Multi-Agent Intent Routing & Swarm Coordination Hub | ||
Autonomous GitHub Community Triaging & PR Feedback Agent |
🏛️ Commercial & Sovereign Architecture
Need autonomous multi-agent swarm orchestration, private datacenter infrastructure, or enterprise governance?
Official Website: https://benni-os.net
Operator Mode Playbook: https://benni-os.net/blog/academy.html
GitHub Organization: https://github.com/Benni-OS
Maintainer: Benni Alencar
📄 License & Provenance
License: MIT License
Author: Benni Alencar (
bennialencar@gmail.com)Architecture: Benni Master OS v9.4 Tier-0 Governance Standard
agent-code-sandbox — Micro-Second Zero-Dependency Code Sandbox & Execution Shield • benni-os.net • MIT License
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
Run AI agent tasks in isolated sandboxes with a cost cap, saved workflows and scoped connections.
Beta code sandbox for agents. Run Python or JavaScript with no network and a 30 s timeout.
Build Apps and run code in 30 languages — sandboxed, with persistent sessions for agent loops.
Autonomous agent guardrails, bash sandboxing, MCP rugpull diffing & prompt firewalls.
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.MIT
- FlicenseNot gradedqualityDmaintenanceProvides a secure, containerized Python sandbox for executing LLM-generated code with multi-layer isolation, along with JSON/CSV validation and workspace state snapshots.-
- FlicenseNot gradedqualityDmaintenanceEnables AI agents to safely execute Python, JavaScript, and Bash code in an isolated Docker sandbox with strict security constraints.1-
- FlicenseNot gradedqualityNot gradedmaintenanceEnables agents and MCP-compliant clients to run multi-language code in a deterministic, zero-dependency sandbox where AST security analysis blocks dangerous syscalls and isolated execution telemetry is captured. It exposes this through JSON-RPC 2.0 stdio, letting frameworks like LangGraph, CrewAI, Cursor, and Claude Desktop validate and execute agent-generated code safely.-