Skip to main content
Glama

agent-sandbox

Lo construí para permitir que un agente de codificación de IA ejecute comandos reales de infraestructura contra un clúster real de Kubernetes, sin tener nunca una credencial permanente y sin poder destruir nada sin supervisión.

Tres herramientas MCP. Cada llamada se ejecuta dentro de un Job de Kubernetes con sandbox de gVisor, con una credencial de corta duración y alcance limitado que Vault emite para esa única acción. Cualquier cosa destructiva se detiene en una puerta de aprobación humana.

AI Agent (Claude Desktop / Cursor)
        │  MCP protocol (stdio)
        ▼
┌──────────────────────────────────────────┐
│  MCP Server            src/agent_sandbox │
│    3 tools -> guardrails -> broker ->    │
│    sandbox -> audit                      │
└───────┬──────────────────────┬───────────┘
        │                      │
        ▼                      ▼
┌────────────────┐   ┌──────────────────────────┐
│ Credential     │   │ Sandbox Runner           │
│ Broker (Vault) │   │ K8s Job + gVisor         │
│ 10-min leases  │   │ restricted PSS           │
│ per-action     │   │ default-deny NetworkPolicy│
│ scope          │   │ cpu/mem limits, deadline │
└────────────────┘   └──────────────────────────┘
        │                      │
        └──────────┬───────────┘
                   ▼
        ┌──────────────────────┐
        │ Guardrails + Approval│
        │ policy.yaml, SQLite, │
        │ agent-sandbox CLI    │
        └──────────────────────┘

Por qué lo construí

Una herramienta de IA que estaba usando propuso una vez un cambio de Terraform contra infraestructura de producción que habría forzado el reemplazo de un recurso en vivo. El plan parecía rutinario. El modo de fallo no era que el modelo estuviera equivocado, sino que nada se interponía entre un plan de apariencia plausible y un apply destructivo.

Construí este proyecto como la capa que faltaba, en código funcional:

  • el agente nunca tiene una credencial que pueda reutilizar

  • todo se ejecuta en un lugar donde no puede dañar el host

  • los cambios destructivos se detienen y esperan a una persona

  • cada acción queda registrada

make demo reproduce el escenario exacto con el que me encontré. Una edición de etiqueta de una línea fuerza el reemplazo de un Deployment en ejecución, y la puerta lo detecta.

Related MCP server: safe-runbook-mcp

Inicio rápido

Requiere Docker, kind, kubectl, vault, terraform y Python 3.11+.

brew install kind kubectl hashicorp/tap/vault terraform
make up      # ~5 minutes from cold: cluster, CNI, gVisor, Vault, image, verify
make demo    # the forces-replacement guardrail demo
make down    # tear it all down

make up es idempotente. Termina ejecutando make verify, que prueba las afirmaciones de aislamiento en lugar de asumirlas (ver más abajo).

Apuntar un agente hacia él

cp examples/claude_desktop_config.json \
   ~/Library/Application\ Support/Claude/claude_desktop_config.json

Cursor: copia examples/cursor_mcp.json en .cursor/mcp.json. Luego pide al agente que "compruebe el estado de los pods en demo-app" o que "planifique el terraform de k8s-demo".

Las tres herramientas

Herramienta

Riesgo

Comportamiento

k8s_get_pod_status(namespace)

bajo

Se ejecuta inmediatamente. Credencial limitada a get/list/watch pods en un solo namespace.

terraform_plan(working_dir)

bajo

Se ejecuta inmediatamente. Guarda el plan para que un apply posterior ejecute exactamente el diff revisado.

terraform_apply(working_dir, approval_id?)

alto

Sin approval_id: calcula el plan, registra una aprobación pendiente, no aplica nada. Con uno: consume la aprobación y aplica el plan guardado.

Los cuatro componentes

1. Ejecución con sandbox — src/agent_sandbox/sandbox.py

Un Job desechable por llamada de herramienta. Cada control está ahí por una razón específica:

Control

Previene

runtimeClassName: gvisor

Las syscalls llegan al centinela de gVisor, no al kernel del host

PSS restricted, aplicado por el servidor de API

root, escalada de privilegios, capabilities, rootfs escribible

automountServiceAccountToken: false

Cualquier identidad de clúster ambiental dentro del sandbox

NetworkPolicy de denegación por defecto + lista blanca del servidor de API

Salida a Internet, movimiento lateral, endpoints de metadatos

resources.limits, activeDeadlineSeconds

Un Job descontrolado que agota el nodo o se cuelga para siempre

backoffLimit: 0

Una acción destructiva fallida que se reintenta silenciosamente

La credencial se monta como archivo, nunca como variable de entorno — las variables de entorno se filtran a través de kubectl describe, /proc y volcados de memoria.

2. Broker de credenciales — src/agent_sandbox/broker.py

cred = broker.issue_scoped_credential("k8s_get_pod_status")
# -> Vault mints a ServiceAccount + Role + RoleBinding, 10-minute lease
# -> revoked immediately after the Job finishes
  • El agente nunca elige su propio alcance. El alcance se deriva de la acción.

  • Denegación por defecto. Una acción sin alcance mapeado no obtiene credencial.

  • El radio de explosión está controlado. Se rechaza solicitar cualquier namespace que no sea el objetivo.

  • El token nunca sale del módulo. Credential.__repr__ imprime token=<redacted>, de modo que incluso un registro accidental no puede filtrarlo.

Lo verifiqué manualmente: un token pod-reader lista pods en demo-app, se le deniega en kube-system, se le deniega en secrets, y deja de funcionar en el momento en que se revoca su lease — sin dejar ningún ServiceAccount detrás.

3. Salvaguardas — policy/policy.yaml, src/agent_sandbox/guardrails.py

Denegación por defecto: registrar una herramienta MCP no es suficiente para que sea invocable. Una herramienta ausente de la política es rechazada, por lo que agregar capacidad requiere una decisión deliberada de nivel de riesgo.

Las aprobaciones están endurecidas contra los ataques obvios:

  • de un solo uso — se consumen dentro de una transacción SQLite, por lo que dos applies concurrentes no pueden gastar la misma aprobación

  • vinculadas a parámetros — vinculadas a un hash de la herramienta exacta + parámetros, por lo que una aprobación para k8s-demo no puede reproducirse contra prod-cluster

  • con expiración — 30 minutos por defecto

  • fuera de banda — se otorgan mediante un proceso CLI separado. No hay herramienta MCP para aprobar nada; el agente no tiene ruta de código para aprobar su propia solicitud.

4. Servidor MCP — src/agent_sandbox/server.py

Construido sobre el SDK oficial de Python (mcp 2.0, MCPServer). La capa de transporte es deliberadamente delgada y no otorga autoridad propia — un error allí no puede ampliar lo que el agente puede hacer, porque la política y la admisión de seguridad de Pods del servidor de API son los controles reales.

Registro de auditoría

Cada llamada emite un rastro de eventos correlacionado a var/audit.jsonl:

tool.request -> guardrail.decision -> credential.issued -> sandbox.started
   -> sandbox.completed -> credential.revoked -> tool.result
make audit
./.venv/bin/agent-sandbox audit --request-id req-4239b8bb5459 --json

Los valores de credenciales se eliminan recursivamente antes de escribir; se conservan el alcance, el ID de lease y el TTL. Una prueba afirma que ninguna cadena con forma de JWT llega al registro.

Verificado, no asumido

Dos cosas en este proyecto son fáciles de afirmar y no tenerlas realmente, así que no las di por sentadas. make verify prueba ambas contra el clúster en vivo:

== 1. gVisor kernel check ==
     kernel reported: Linux version 4.19.0-gvisor
  PASS: sandbox runs on the gVisor sentry kernel
== 2. NetworkPolicy egress enforcement check ==
  PASS: baseline connectivity works (got PONG)
  PASS: default-deny egress enforced (traffic blocked)

Esto detectó un problema real mientras lo construía. El CNI predeterminado de kind (kindnet) acepta objetos NetworkPolicy y los ignora silenciosamente — apliqué una política de denegación de salida por defecto y el tráfico pod-a-pod aún pasaba. El sandbox habría parecido bloqueado mientras tenía acceso completo a la red. Lo arreglé deshabilitando kindnet e instalando Calico, que aplica de verdad. Ver scripts/install-calico.sh.

También me encontré con una trampa relacionada al permitir el servidor de API: el ClusterIP no funciona, porque kube-proxy hace DNAT al endpoint real antes de que Calico evalúe la salida. El síntoma era un sandbox que simplemente se colgaba sin ningún evento de denegación de política que lo explicara. Documentado en scripts/apply-sandbox-policy.sh.

Limitaciones honestas

  • gVisor se ejecuta, pero esto sigue siendo kind. Instalé runsc dentro del nodo de kind (un contenedor en la VM Linux de Docker Desktop) y verifiqué que está activo. Eso es un sandbox real de gVisor, no un nodo endurecido para producción.

  • La ruta AWS/STS es condicional. scripts/vault-setup.sh solo configura el motor de secrets de AWS de Vault cuando hay credenciales reales de AWS presentes; sin ellas, se omite y lo dice. No quise falsificar esa ruta solo para que la demo pareciera completa. La ruta de credenciales en vivo y demostrable es la de Kubernetes, que es completamente real: ServiceAccounts dinámicos, RBAC real, leases reales, revocación real.

  • Vault se ejecuta en modo dev — en memoria, token root root, sin sellado. Está bien para un proyecto local, no algo que desplegaría tal cual.

  • La detección de señales destructivas es coincidencia de cadenas en la salida del plan. Es una ayuda de superficie para el humano, no un límite de seguridad — terraform_apply ya es de nivel alto y está controlado independientemente de lo que encuentre el escaneo.

  • Clúster de un solo nodo, por lo que el PVC que contiene el estado de Terraform es ReadWriteOnce en un nodo.

Estructura

cluster/      kind config, RuntimeClass, namespaces, RBAC, network policy
images/       sandbox runner image (terraform + kubectl, providers vendored)
policy/       guardrail policy: risk tiers and destructive signals
scripts/      up/down, gVisor + Calico install, verification, demo
src/          the package: broker, sandbox, guardrails, approvals, audit, MCP
terraform/    demo module managed by the agent
tests/        56 unit tests + a real-stdio MCP integration check

Pruebas

make test       # 56 unit tests, no cluster required
make test-mcp   # drives the server over real MCP stdio (needs the stack up)
make verify     # proves gVisor + NetworkPolicy enforcement on the live cluster

Available Tools

3 tools
k8s_get_pod_statusGet pod statusA

Read-only. Lists pods and their phase in the target namespace, executed inside a gVisor sandbox with a credential scoped to get/list/watch pods in that one namespace. Runs immediately; no approval needed.

ParametersJSON Schema
NameRequiredDescriptionDefault
namespaceNodemo-app

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A3.5/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries the full disclosure burden and does it well: it states read-only semantics, gVisor sandbox isolation, the exact credential scope (get/list/watch on one namespace), and that no approval gate exists. It stops short of pagination or error behavior, but the safety and permission profile is unusually well covered for an annotation-free tool.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Three short sentences, front-loaded with the safety-critical 'Read-only.' qualifier followed by scope, environment, and approval status. Every sentence adds information; no filler or repetition.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

An output schema exists, so return-format explanation is unnecessary, and the description covers read-only status, execution environment, credential scope, and approval behavior for a single-parameter tool. The one remaining gap is that the namespace default and format are never mentioned in either the description or the schema.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must compensate for the lone parameter. It only gestures at 'the target namespace' without naming the parameter, giving the default value ('demo-app'), or indicating accepted namespace formats. The agent must open the schema to learn anything actionable about the input.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description gives a specific verb and resource ('Lists pods and their phase') plus an explicit scope ('in the target namespace'), so the agent knows exactly what is returned. It does not differentiate from siblings, but the siblings (terraform_plan/terraform_apply) are an unrelated domain, so no routing confusion exists. Minor tension: the name says 'pod status' (singular) while the description lists pods (plural).

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

'Read-only' and 'Runs immediately; no approval needed' imply when this is safe to call, and the namespace scoping implies the context. There is no explicit when-to-use/when-not statement or named alternative, so usage is only implied rather than stated.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

terraform_applyTerraform applyA

HIGH RISK -- mutates real infrastructure. Calling without approval_id does NOT apply anything: it computes the plan, records a pending approval, and returns an approval id for a human to review out-of-band. Once a human has approved, call again with that approval_id to execute the reviewed plan. Approvals are single-use, expiring, and bound to these exact parameters.

ParametersJSON Schema
NameRequiredDescriptionDefault
approval_idNo
working_dirYes

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.8/5.0
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden and does so well: it flags HIGH RISK mutation, explains that the no-approval path is non-destructive (computes plan, records pending approval), and discloses approval lifecycle traits (single-use, expiring, parameter-bound). This is far beyond what a bare 'apply' would convey.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Four tight sentences with the risk warning and the two-phase contract front-loaded; no filler. Dense but readable, and every clause adds operational information.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Output schema exists so return-value documentation is unnecessary, and the description still names the key return (approval id). Combined with the risk warning and approval lifecycle, an agent has everything needed to call this correctly and safely.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 0%, so the description must compensate; it fully explains approval_id semantics (optional, single-use, expiring, must match exact parameters, absence means no apply). working_dir is never explained, which is the one remaining gap, but the high-risk parameter is covered.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

States a specific verb and resource ('mutates real infrastructure', Terraform apply) and immediately clarifies its two-phase nature, which separates it from terraform_plan's pure-preview role. An agent can tell what this does and when it would fire without opening the schema.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Explicit conditional workflow: call without approval_id to compute a plan and register a pending approval, then call again with the returned approval_id to execute. It also states the human review happens out-of-band, so the agent knows not to wait on this call for the mutation to occur.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

terraform_planTerraform planA

Computes a Terraform diff for a module under the terraform/ root. Runs immediately in the sandbox and persists the plan so a subsequent apply can execute exactly the reviewed diff. Output is annotated when the plan contains destructive changes such as forced replacement.

ParametersJSON Schema
NameRequiredDescriptionDefault
working_dirYes

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.2/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries the full burden and does well: it discloses immediate sandbox execution (no confirmation gate), that the plan is persisted as durable state, and that output is annotated on destructive changes like forced replacement. It omits auth/permission requirements and failure behavior, which keeps it out of 5 territory.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Three tight sentences with no filler, front-loaded with what the tool does before the sandbox/persistence and destructive-change details.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

An output schema exists, so return values need not be explained, and the description covers execution model, persistence, and destructive-change signaling. The main residual gap is parameter semantics for working_dir, which neither schema nor description pins down.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0% for the single working_dir parameter, so the schema adds nothing. The description hints that the module lives 'under the terraform/ root', which weakly constrains the path, but it never states whether working_dir is absolute, relative, or relative to that root.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

States a specific verb and resource ('Computes a Terraform diff for a module'), and scopes it to the terraform/ root. It also implicitly distinguishes itself from the sibling terraform_apply by framing itself as the review step that a 'subsequent apply' consumes.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Gives clear context for use: it runs immediately and produces a persisted plan that a later apply executes, which tells the agent this belongs before terraform_apply. It stops short of explicit when-not-to-use guidance or naming the alternative tool directly.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

  1. 3 tool updatesv0.1.0
    • First observedk8s_get_pod_status
    • First observedterraform_apply
    • First observedterraform_plan

TDQS

A3.9/5.0

Scored across 3 tools

Disambiguation5/5

Each tool has a clearly distinct purpose: read-only Kubernetes pod status, a Terraform plan diff, and a gated Terraform apply. The plan/apply pair is explicitly differentiated by the approval workflow, so an agent can reliably choose the right tool.

Naming Consistency4/5

Names use consistent snake_case with a domain prefix and a verb (k8s_get_pod_status, terraform_plan, terraform_apply). The k8s tool adds an object noun while the Terraform tools do not, a minor deviation but still predictable.

Tool Count3/5

Three tools across two distinct domains (Kubernetes and Terraform) is thin for an agent sandbox. Each tool earns its place, but the surface feels minimal relative to the apparent infrastructure-management scope.

Completeness3/5

Kubernetes coverage is limited to reading pod phase with no logs, events, describe, or any mutating operation, and Terraform lacks init/validate, destroy, and state inspection. The core plan-then-apply lifecycle is well covered, but notable gaps remain for a sandbox meant to work with real infrastructure.

Maintenance

ActivitySlowing
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • F
    license
    Not graded
    quality
    B
    maintenance
    Give AI agents Zero-Trust access to production infrastructure without the risks of granting them shell access. Actions are bounded by policy and an on-host runner.
    337
    -
  • A
    license
    A
    quality
    B
    maintenance
    Enables 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.
    15
    MIT