Sandboxed Environments for AI Coding: 2026 Guide
Compare gVisor, Kata Containers & Firecracker for Claude Code, Cursor & Windsurf. Step-by-step setup, MCP integration patterns & network isolation best practices.
When a developer opens Claude Code, Cursor, or Windsurf and asks an AI agent to "fix the authentication bug," the agent does not just suggest code — it reads files, runs commands, installs packages, and executes tests. By the time a human reviews the diff, dozens of filesystem operations have already happened.
That execution model changes everything about how you need to think about security. AI coding sandboxes are no longer a "nice to have" — they are the foundation of any AI-assisted engineering workflow that touches production systems.
This guide covers the 2026 state of sandboxed environments for AI coding: the isolation technologies, how leading tools like Claude Code, Cursor, and Windsurf approach sandboxing, how MCP changes the integration model, and a step-by-step implementation guide for teams running agents at scale.
Why AI-Generated Code Demands Structural Isolation
The problem is not that AI models write bad code — they often write excellent code. The problem is volume, speed, and trust:
- An AI agent can write and execute 50 file operations before a human sees a single diff
- Agent frameworks like Claude Code's
--dangerously-skip-permissionsflag exist because approval fatigue is real — developers click through permission prompts to maintain flow - A 2025 Veracode study found 45% of AI-generated code fails initial security tests — which means nearly half of every agent commit carries a security flaw before human review
- Microsoft's May 2026 security report documented RCE vulnerabilities in multiple AI agent frameworks exploited through prompt injection → shell execution chains
Real incidents drive this point home:
- Claude Code wiping home directories (2025): An agent followed an ambiguous instruction to "clean up old files" and recursively deleted home directory contents
- Replit production database deletion (2025): An agentic workflow reached production credentials through environment variable leakage in an unisolated shell session
- The Shai-Hulud campaign (2026): A supply chain attack targeting AI coding tools, embedding malicious instructions in dependency READMEs that caused agents to exfiltrate source code on install
Permission prompts help, but they do not solve the problem. When an agent needs 200 approvals per hour, developers start clicking "Allow all." Research from 2025 found that sandboxing reduced permission prompts by 84% in high-volume agentic workflows — because the sandbox enforces limits structurally, not interactively, so teams ship faster with less friction, not more.
Sandboxing removes the human from the blast radius entirely.
The 2026 AI Coding Agent Landscape: Sandboxing Postures
Five tools now dominate AI-assisted coding. Each has a fundamentally different sandboxing posture — understanding the gaps tells you exactly where you need to add isolation infrastructure.
| Tool | Sandbox Default | Isolation Method | On by Default? |
|---|---|---|---|
| Claude Code | Opt-in | Bubblewrap (Linux), Seatbelt (macOS) | ❌ No |
| Cursor | None | Process-level only | ❌ No |
| Windsurf | None | Process-level only | ❌ No |
| OpenAI Codex CLI | Built-in | Landlock + seccomp (Linux) | ✅ Yes |
| GitHub Copilot Workspace | Cloud-native | Ephemeral container | ✅ Yes |
| Kiro (AWS) | Cloud-native | Managed microVM | ✅ Yes |
Claude Code is the most widely deployed agentic coding tool as of 2026. On Linux, it uses Bubblewrap — the same sandbox technology that powers Flatpak applications. On macOS it uses the sandbox-exec-based Seatbelt framework. Both are enabled via the --sandbox flag. That means most Claude Code deployments today run completely unsandboxed, including the majority of CI/CD integrations.
Cursor and Windsurf have no built-in sandboxing. They execute agent actions in the same process space as the IDE, with no filesystem or network boundary. For local development on a personal machine this is often acceptable. For CI/CD pipelines, team environments, or any workflow touching sensitive systems, this is a significant attack surface.
OpenAI Codex CLI is the clear standout: it is the only major AI coding tool that enables sandboxing by default. On Linux it combines Landlock (filesystem access control at the kernel level) with seccomp (syscall filtering). The "secure by default" design choice matters enormously in practice.
The takeaway: If you are using Claude Code, Cursor, or Windsurf in any automated or shared context, you need to provide the sandbox infrastructure yourself. The tools will not do it for you.
Isolation Technologies: At-a-Glance Comparison
Four main approaches exist for sandboxing AI coding agents. They trade off startup latency, isolation strength, and operational complexity.
| Technology | Cold Start | Isolation Level | Host Kernel Shared? | Kubernetes Native? | Best For |
|---|---|---|---|---|---|
| Docker Container | 1–5 s | Medium | ✅ Yes | ✅ Yes | Trusted internal automation |
| gVisor | 0.5–2 s | High | ❌ No (user-space) | ✅ Yes | Untrusted code, Kubernetes shops |
| Kata Containers | 0.5–2 s | Very High | ❌ No (VM kernel) | ✅ Yes | Multi-tenant agent platforms |
| Firecracker MicroVM | ~125 ms | Very High | ❌ No (VM kernel) | Via Kata | Production agent workloads |
| Managed Sandbox (E2B, Bunnyshell) | < 200 ms | Very High | ❌ No | Managed | Teams without microVM infra |
Decision rule: Use containers for trusted internal automation. Use gVisor when you need Kubernetes compatibility with stronger isolation. Use Kata Containers or Firecracker for production agent workloads executing untrusted AI-generated code.
Isolation Technologies: Deep Dive
1. Standard Linux Containers (Docker / containerd)
Containers isolate the filesystem, process tree, and network namespace — but share the host kernel. Cold starts are fast (1–5 seconds), they are familiar to every engineer, and they are native to Kubernetes.
Security ceiling: Medium. Container escapes via kernel exploits are well-documented. If an AI agent triggers a kernel privilege escalation — intentionally through prompt injection or accidentally through a dependency vulnerability — it can break out to the host. For trusted internal automation, containers are fine. For untrusted AI-generated code executing arbitrary commands, they are insufficient.
2. gVisor (User-Space Kernel Interception)
gVisor intercepts all system calls and handles them through a user-space kernel ("Sentry"), never passing untrusted code directly to the host kernel. Even a successful container escape only reaches gVisor's user-space implementation, not the host OS.
Trade-off: ~10–30% performance overhead versus native execution. Not all syscalls are supported — some Go and Rust binaries have compatibility issues. Startup time: 500 ms–2 s. Works natively with Kubernetes (--runtime=runsc via containerd).
1# gVisor-isolated container for AI agent code execution
2docker run --runtime=runsc \
3 --network=none \
4 --memory=512m \
5 --cpus=1.0 \
6 --read-only \
7 --tmpfs /tmp:rw,size=128m \
8 -v /tmp/agent-workspace-$(uuidgen):/workspace:rw \
9 coding-agent-runner:latest \
10 python agent_task.py3. Kata Containers
Kata Containers run each container inside a lightweight VM with a dedicated kernel — QEMU, Firecracker, or Cloud Hypervisor as the backend. You get VM-level isolation with a container-compatible interface: orchestrate with Kubernetes, get microVM security.
Trade-off: Stronger isolation than gVisor. Startup overhead: 500 ms–2 s with Firecracker backend. Ideal for multi-tenant platforms where different customers' agents run on shared hardware — Kata ensures a kernel exploit in one tenant's container cannot affect another.
4. Firecracker MicroVMs
Firecracker is AWS's open-source microVM technology, now the industry standard for high-security agent sandboxing. It boots a dedicated Linux kernel per sandbox in approximately 125 milliseconds, with only 5 device types supported (versus hundreds in QEMU), dramatically reducing the attack surface.
E2B, Modal, and Bunnyshell all use Firecracker or equivalent microVM technology as their sandbox backend. According to Forrester's AI Infrastructure Survey (2026), approximately 50% of Fortune 500 companies running AI agent workloads now use Firecracker-backed sandboxes. E2B scaled from 40,000 sandbox sessions per month in early 2024 to roughly 15 million per month by 2025 — almost entirely Firecracker-backed.
MCP Integration in Sandboxed Environments
The Model Context Protocol (MCP) is now the universal standard for AI agent tool integration — 97 million monthly SDK downloads as of March 2026, adopted by Anthropic, OpenAI, Google, Microsoft, and AWS. Understanding how MCP changes the sandbox architecture is critical for teams deploying agents at scale.
Traditional agent sandboxing: The entire agent process runs inside the sandbox, executing code and making filesystem changes directly. The sandbox wraps the agent.
MCP-native agent sandboxing: The agent (the LLM) runs outside the sandbox, calling MCP tools that proxy into sandboxed execution environments. The agent never directly executes code — it issues structured tool calls. The sandbox wraps the execution, not the agent.
This is a cleaner security boundary: the LLM that could be compromised via prompt injection never has direct host access. The MCP server is the controlled gateway.
1{
2 "name": "execute_code",
3 "description": "Execute code in an ephemeral, isolated sandbox",
4 "inputSchema": {
5 "type": "object",
6 "required": ["language", "code"],
7 "properties": {
8 "language": {"type": "string", "enum": ["python", "javascript", "typescript", "bash"]},
9 "code": {"type": "string"},
10 "timeout_seconds": {"type": "number", "maximum": 30, "default": 10}
11 }
12 }
13}When Claude Code or Cursor calls this MCP tool, the MCP server spins up a fresh Firecracker microVM, executes the code with no network access and strict resource limits, captures output, destroys the VM, and returns the result. The agent never touches the host.
1# mcp_sandbox_server.py
2from mcp.server import Server
3from mcp.server.stdio import stdio_server
4import asyncio
5
6app = Server("sandbox-executor")
7
8@app.tool()
9async def execute_code(language: str, code: str, timeout_seconds: int = 10) -> dict:
10 sandbox = await SandboxPool.acquire()
11 try:
12 result = await sandbox.run(
13 language=language,
14 code=code,
15 timeout=timeout_seconds,
16 network="none",
17 memory_mb=256,
18 cpu_cores=0.5,
19 )
20 return {"stdout": result.stdout, "stderr": result.stderr, "exit_code": result.exit_code}
21 finally:
22 await sandbox.destroy()
23
24async def main():
25 async with stdio_server() as streams:
26 await app.run(*streams)
27
28asyncio.run(main())Claude Code picks up this MCP server via .claude/settings.json:
1{
2 "mcpServers": {
3 "sandbox": {
4 "command": "python",
5 "args": ["mcp_sandbox_server.py"],
6 "env": {"SANDBOX_POOL_SIZE": "5", "SANDBOX_TTL_SECONDS": "300"}
7 }
8 }
9}The MCP-as-sandbox-gateway pattern separates concerns cleanly: the agent framework handles prompting and tool orchestration; the MCP server handles sandboxed execution; the sandbox layer handles isolation.
How to Set Up a Sandboxed AI Coding Environment
A step-by-step guide to production-grade sandboxed environments for AI coding agents.
Step 1: Define Your Threat Model
Before choosing isolation technology, answer four questions:
- Who writes the code being executed? Agent autonomously vs. human-reviewed first
- What systems can the sandbox reach? No network vs. controlled egress vs. full internet
- How many sandboxes run concurrently? Single developer vs. team CI vs. multi-tenant platform
- What is the data sensitivity? Public repos vs. internal IP vs. customer data
High-risk answer to any question → Firecracker or Kata Containers. Low-risk across all four → hardened containers with seccomp + AppArmor.
Step 2: Configure Filesystem Isolation
Start with a minimal base image and a non-root agent user:
1FROM ubuntu:22.04
2
3RUN useradd -m -u 1001 agent && \
4 mkdir -p /workspace && \
5 chown agent:agent /workspace
6
7USER agent
8WORKDIR /workspaceApply read-only root filesystem with a writable tmpfs for the workspace only:
1docker run \
2 --user 1001:1001 \
3 --read-only \
4 --tmpfs /tmp:rw,size=128m \
5 --cap-drop=ALL \
6 --security-opt no-new-privileges \
7 --security-opt seccomp=agent-seccomp.json \
8 -v /workspace/task-$(uuidgen):/workspace:rw \
9 coding-sandbox:latestStep 3: Lock Down Network Egress
Default to no network. Add egress rules only for explicitly required destinations:
1apiVersion: networking.k8s.io/v1
2kind: NetworkPolicy
3metadata:
4 name: ai-agent-sandbox-deny-egress
5spec:
6 podSelector:
7 matchLabels:
8 role: ai-agent-sandbox
9 policyTypes:
10 - Egress
11 egress: []The Microsoft May 2026 security report documented prompt injection attacks that exfiltrated source code via HTTP callback to attacker-controlled servers. A single egress: [] policy would have blocked every attack in that report.
Step 4: Set Resource Limits
1resources:
2 requests:
3 memory: "256Mi"
4 cpu: "500m"
5 limits:
6 memory: "512Mi"
7 cpu: "1000m"
8 ephemeral-storage: "2Gi"Also enforce process count limits via --pids-limit=100 (Docker) or PidsLimit in the container runtime spec. AI agents generating runaway fork bombs — whether intentional or from bugs in agent-generated shell scripts — are a real production failure mode.
Step 5: Implement Ephemeral Lifecycle
Each sandbox must have a fixed TTL and auto-destruct on completion. Use 5–10 minutes for CI/CD tasks and up to 30 minutes for interactive agent sessions. Never reuse sandboxes across agent tasks.
1from contextlib import asynccontextmanager
2import asyncio
3
4@asynccontextmanager
5async def ephemeral_sandbox(ttl_seconds: int = 300):
6 sandbox_id = await create_sandbox()
7 ttl_task = asyncio.create_task(_enforce_ttl(sandbox_id, ttl_seconds))
8 try:
9 yield sandbox_id
10 finally:
11 ttl_task.cancel()
12 await destroy_sandbox(sandbox_id)
13
14async def _enforce_ttl(sandbox_id: str, ttl: int):
15 await asyncio.sleep(ttl)
16 await destroy_sandbox(sandbox_id)Step 6: Add Audit Logging
Every action inside the sandbox should produce a structured log entry. This is your forensic trail when an agent does something unexpected — and it will. Without logs, you cannot reconstruct what happened, which means you cannot fix it or prove it to stakeholders.
1import structlog
2
3log = structlog.get_logger()
4
5def log_sandbox_event(event_type: str, **kwargs):
6 log.info(
7 event_type,
8 sandbox_id=kwargs.get("sandbox_id"),
9 agent_id=kwargs.get("agent_id"),
10 action=kwargs.get("action"),
11 path=kwargs.get("path"),
12 network_destination=kwargs.get("destination"),
13 blocked=kwargs.get("blocked", False),
14 timestamp=kwargs.get("ts"),
15 )Log file reads and writes, network connections attempted (including blocked ones), process spawns with full argument lists, and resource usage at completion.
Network Isolation Patterns for AI Coding Agents
Three network postures, with appropriate use cases:
Air-gapped (no network): Best for pure code generation and analysis tasks. The agent reads local files and writes code but makes no external calls. Blocks data exfiltration and supply chain injection. Use this as the default and relax only when necessary.
Filtered egress: Allow specific destinations via explicit allowlist. Appropriate for agents that install packages (PyPI, npm, cargo) or call internal APIs. Implement via an egress proxy (Squid or Envoy) rather than raw NetworkPolicy — a proxy lets you log and inspect traffic, not just block it.
Full internet with monitoring: Only appropriate for research or browsing agents. Requires egress logging, DLP scanning on outbound traffic, and rate limiting. Do not use this for any agent that writes and executes code.
Ephemeral Sandbox Patterns for CI/CD
For teams integrating AI coding agents into CI/CD pipelines, the key pattern is:
- Create sandbox scoped to the specific PR or task, with a snapshot of the relevant code
- Run agent (Claude Code, Codex, or custom agent framework)
- Capture artifacts — diff, test results, generated files — before the sandbox is destroyed
- Destroy sandbox — wipe state, never reuse across tasks
Bunnyshell's ephemeral preview environments map directly to this pattern. Each pull request gets a fresh, isolated environment. AI agents run inside that environment, not on shared CI infrastructure. Reviewers get a live preview of the agent's changes. The environment auto-destroys on merge or close.
The environment-per-PR model means no state bleeds between PRs, no shared filesystem for an agent to inadvertently corrupt, and a clean audit trail for every agent run.
How Bunnyshell Handles AI Coding Sandboxes
Bunnyshell provides AI sandbox environments built on the same ephemeral-environment-per-PR model described above — without requiring teams to manage Firecracker or Kata Container runtimes directly.
In practice, this means:
- Each pull request gets its own isolated environment with enforced CPU, memory, and storage limits. A runaway agent process cannot starve other workloads.
- Environments auto-create on PR open, update on push, and auto-destroy on merge. The ephemeral lifecycle is structural, not a policy you enforce manually.
- Network isolation is on by default. Internal service discovery works within the environment; external access flows through Bunnyshell's ingress layer.
- Bunnyshell environments expose an API usable as an MCP tool server, allowing Claude Code or Cursor to spin up and destroy environments as part of multi-step agentic workflows.
Teams that implement proper AI coding sandboxes consistently report the same outcome: agents run more autonomously (fewer permission prompts), incidents drop sharply, and reviewers spend time on logic rather than security review. Bunnyshell handles the infrastructure layer so your team can focus on the agents.
Start a free trial — no credit card required →
Last updated: May 2026 | Covers Claude Code, Cursor, Windsurf, Codex, gVisor, Kata Containers, Firecracker, and MCP
Frequently Asked Questions
What is a sandboxed environment for AI coding?
A sandboxed environment is an isolated execution space where AI-generated code runs without access to the host system, production networks, or sensitive data. It combines filesystem isolation, network controls, resource limits (CPU, memory, process count), and an ephemeral lifecycle — the sandbox auto-destructs after the task completes, leaving no persistent state.
Is Claude Code sandboxed by default?
No. Claude Code supports sandboxing via the --sandbox flag using Bubblewrap (Linux) or Seatbelt (macOS), but sandboxing is opt-in. Most Claude Code deployments — including the majority of CI/CD integrations — run without it enabled. Teams running Claude Code in shared or automated environments should add sandbox infrastructure externally.
What is the difference between gVisor and Kata Containers?
gVisor intercepts syscalls through a user-space kernel, providing strong isolation without running a full VM — compatible with standard Kubernetes container runtimes. Kata Containers run each container inside a lightweight VM with a dedicated kernel, providing VM-level isolation with a container-compatible interface. Both are significantly stronger than standard Docker containers; Kata provides slightly stronger isolation at marginally higher startup overhead.
How does MCP integrate with sandbox environments?
MCP (Model Context Protocol) allows AI agents to call sandboxed execution as a structured tool call. The agent issues an execute_code tool call; an MCP server spins up an ephemeral sandbox, runs the code, and returns the result. The agent (the LLM) never has direct host access — MCP becomes the controlled gateway into sandboxed execution. This is the recommended pattern for Claude Code and Cursor deployments at scale.
Can Kubernetes manage AI agent sandboxes?
Yes. The Kubernetes SIGs Agent Sandbox project (kubernetes-sigs/agent-sandbox) provides primitives specifically designed for isolated, stateful singleton workloads — the AI agent runtime pattern. Using Kata Containers as the Kubernetes container runtime gives you VM-level isolation with standard Kubernetes orchestration.
How long should an AI coding sandbox live?
Sandboxes should be scoped to a single task or session with a hard TTL — typically 5 to 10 minutes for CI/CD tasks and up to 30 minutes for interactive agent sessions. Never reuse sandboxes across agent tasks. Reuse allows state bleed: leftover temporary files, leaked environment variables, and process artifacts can contaminate subsequent runs or create cross-tenant data leakage in shared environments.
What is the minimum viable sandbox for a small team?
For individual developers using Claude Code locally: enable the --sandbox flag and add a .claude/settings.json with explicit path allowlists. For team CI/CD: run agents in Docker containers with --read-only, --cap-drop=ALL, --network=none, and --pids-limit=100. For any multi-tenant or production use: use Firecracker microVMs or a managed platform (E2B, Bunnyshell) that handles the microVM layer for you.