agent-sandbox
agent-sandbox
Ich habe das gebaut, damit ein KI-Coding-Agent echte Infrastruktur-Befehle gegen einen echten Kubernetes-Cluster ausführen kann – ohne jemals ein dauerhaftes Zugangsdaten zu besitzen und ohne in der Lage zu sein, unbeaufsichtigt etwas zu zerstören.
Drei MCP-Tools. Jeder Aufruf läuft in einem gVisor-sandboxed Kubernetes-Job mit einer kurzlebigen, eng begrenzten Berechtigung, die Vault für genau diese einzelne Aktion ausstellt. Alles Destruktive stoppt an einem menschlichen Genehmigungs-Gate.
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 │
└──────────────────────┘Warum ich das gebaut habe
Ein KI-Tool, das ich benutzte, schlug einmal eine Terraform-Änderung an Produktionsinfrastruktur vor, die den Austausch einer laufenden Ressource erzwungen hätte. Der Plan sah routinemäßig aus. Der Fehlermodus war nicht, dass das Modell falsch lag – sondern dass nichts zwischen einem plausibel aussehenden Plan und einem destruktiven Apply stand.
Ich habe dieses Projekt als die fehlende Schicht gebaut, in funktionierendem Code:
der Agent hält nie eine Berechtigung, die er wiederverwenden könnte
alles läuft an einem Ort, an dem es dem Host nicht schaden kann
destruktive Änderungen stoppen und warten auf eine Person
jede Aktion ist dokumentiert
make demo reproduziert das genaue Szenario, auf das ich gestoßen bin. Eine einzeilige Label-Änderung erzwingt den Austausch eines laufenden Deployments, und das Gate fängt es ab.
Related MCP server: safe-runbook-mcp
Schnellstart
Erfordert Docker, kind, kubectl, vault, terraform und 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 downmake up ist idempotent. Es endet mit make verify, das die Isolationsbehauptungen beweist, statt sie nur zu behaupten (siehe unten).
Einen Agenten darauf ausrichten
cp examples/claude_desktop_config.json \
~/Library/Application\ Support/Claude/claude_desktop_config.jsonCursor: Kopiere examples/cursor_mcp.json nach .cursor/mcp.json. Dann frage den Agenten, "Pod-Status in demo-app zu prüfen" oder "das k8s-demo Terraform zu planen".
Die drei Tools
Tool | Risiko | Verhalten |
| niedrig | Läuft sofort. Berechtigung beschränkt auf |
| niedrig | Läuft sofort. Speichert den Plan, sodass ein späteres Apply exakt den überprüften Diff ausführt. |
| hoch | Ohne |
Die vier Komponenten
1. Sandbox-Ausführung – src/agent_sandbox/sandbox.py
Ein Wegwerf-Job pro Tool-Aufruf. Jede Kontrolle existiert aus einem bestimmten Grund:
Kontrolle | Verhindert |
| Syscalls treffen den gVisor-Sentry, nicht den Host-Kernel |
PSS | root, Privilege Escalation, Capabilities, beschreibbares Rootfs |
| Jede Umgebungs-Cluster-Identität innerhalb der Sandbox |
Default-Deny- | Internet-Egress, laterale Bewegung, Metadaten-Endpunkte |
| Ein außer Kontrolle geratener Job, der den Node aushungert oder ewig hängt |
| Ein fehlgeschlagener destruktiver Vorgang, der stillschweigend wiederholt wird |
Die Berechtigung wird als Datei gemountet, nie als Umgebungsvariable – Umgebungsvariablen leaken durch kubectl describe, /proc und Crash-Dumps.
2. Berechtigungs-Broker – 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 finishesDer Agent wählt nie seinen eigenen Umfang. Der Umfang wird aus der Aktion abgeleitet.
Standardmäßig verweigern. Eine Aktion ohne zugeordneten Umfang erhält keine Berechtigung.
Blast-Radius wird erzwungen. Das Anfordern eines anderen Namespace als des Ziels wird verweigert.
Das Token verlässt das Modul nie.
Credential.__repr__gibttoken=<redacted>aus, sodass selbst ein versehentliches Log es nicht leaken kann.
Ich habe das von Hand verifiziert: Ein pod-reader-Token listet Pods in demo-app, wird in kube-system verweigert, wird bei Secrets verweigert und funktioniert nicht mehr, sobald sein Lease widerrufen wird – ohne ein ServiceAccount zurückzulassen.
3. Schutzmechanismen – policy/policy.yaml, src/agent_sandbox/guardrails.py
Standardmäßig verweigern: Das Registrieren eines MCP-Tools reicht nicht aus, um es aufrufbar zu machen. Ein Tool, das nicht in der Policy steht, wird verweigert. Das Hinzufügen von Fähigkeiten erfordert also eine bewusste Risiko-Einstufungs-Entscheidung.
Genehmigungen sind gegen die offensichtlichen Angriffe gehärtet:
Einmalig – in einer einzigen SQLite-Transaktion verbraucht, sodass zwei gleichzeitige Applies nicht dieselbe Genehmigung ausgeben können
Parametergebunden – an einen Hash des exakten Tools + Parameter gebunden, sodass eine Genehmigung für
k8s-demonicht gegenprod-clusterwiederverwendet werden kannAblaufend – standardmäßig 30 Minuten
Out-of-Band – über einen separaten CLI-Prozess gewährt. Es gibt kein MCP-Tool, um etwas zu genehmigen; der Agent hat keinen Codepfad, um seine eigene Anfrage zu genehmigen.
4. MCP-Server – src/agent_sandbox/server.py
Basiert auf dem offiziellen Python-SDK (mcp 2.0, MCPServer). Die Transportschicht ist bewusst dünn und gewährt selbst keine Autorität – ein Fehler dort kann nicht erweitern, was der Agent tun kann, weil die Policy und die Pod-Security-Zulassung des API-Servers die eigentlichen Kontrollen sind.
Audit-Log
Jeder Aufruf erzeugt eine korrelierte Ereignisspur in var/audit.jsonl:
tool.request -> guardrail.decision -> credential.issued -> sandbox.started
-> sandbox.completed -> credential.revoked -> tool.resultmake audit
./.venv/bin/agent-sandbox audit --request-id req-4239b8bb5459 --jsonBerechtigungswerte werden vor dem Schreiben rekursiv bereinigt; Umfang, Lease-ID und TTL werden beibehalten. Ein Test stellt sicher, dass nie ein JWT-förmiger String ins Log gelangt.
Verifiziert, nicht angenommen
Zwei Dinge in diesem Projekt sind leicht zu behaupten und stillschweigend nicht zu haben, also habe ich sie nicht auf Treu und Glauben genommen. make verify testet beide gegen den Live-Cluster:
== 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)Das hat ein echtes Problem gefangen, während ich es gebaut habe. kind's Standard-CNI (kindnet) akzeptiert NetworkPolicy-Objekte und ignoriert sie stillschweigend – ich habe eine Default-Deny-Egress-Policy angewendet und Pod-zu-Pod-Verkehr kam trotzdem durch. Die Sandbox hätte wie abgesichert ausgesehen, während sie vollen Netzwerkzugriff hatte. Ich habe es behoben, indem ich kindnet deaktiviert und Calico installiert habe, das wirklich durchsetzt. Siehe scripts/install-calico.sh.
Ich bin auf eine verwandte Falle gestoßen, als ich den API-Server auf die Allowlist setzte: Die ClusterIP funktioniert nicht, weil kube-proxy vor der Calico-Egress-Bewertung zum echten Endpunkt DNATet. Das Symptom war eine Sandbox, die einfach hing, ohne ein Policy-Denied-Ereignis, das es erklärt. Dokumentiert in scripts/apply-sandbox-policy.sh.
Ehrliche Einschränkungen
gVisor läuft, aber das ist immer noch kind. Ich habe
runscim kind-Node (ein Container in der Linux-VM von Docker Desktop) installiert und verifiziert, dass es aktiv ist. Das ist eine echte gVisor-Sandbox, kein produktionsgehärteter Node.Der AWS/STS-Pfad ist bedingt.
scripts/vault-setup.shkonfiguriert Vaults AWS-Secrets-Engine nur, wenn echte AWS-Zugangsdaten vorhanden sind; ohne sie wird es übersprungen und sagt das. Ich wollte diesen Pfad nicht faken, nur um die Demo vollständig aussehen zu lassen. Der live, demonstrierbare Berechtigungspfad ist der Kubernetes-Pfad, der vollständig real ist: dynamische ServiceAccounts, echtes RBAC, echte Leases, echte Widerrufe.Vault läuft im Dev-Modus – im Speicher, Root-Token
root, kein Seal. Für ein lokales Projekt in Ordnung, nicht etwas, das ich so deployen würde.Die Erkennung destruktiver Signale ist String-Matching auf Plan-Ausgabe. Es ist eine Oberflächen-Hilfe für den Menschen, keine Sicherheitsgrenze –
terraform_applyist bereits hoch eingestuft und unabhängig davon, was der Scan findet, gegated.Einzelner Node-Cluster, daher ist das PVC, das den Terraform-State hält,
ReadWriteOnceauf einem Node.
Layout
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 checkTesten
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 clusterAvailable Tools
3 toolsk8s_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.
| Name | Required | Description | Default |
|---|---|---|---|
| namespace | No | demo-app |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
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.
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.
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.
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.
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.
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.
| Name | Required | Description | Default |
|---|---|---|---|
| approval_id | No | ||
| working_dir | Yes |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
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.
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.
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.
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.
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.
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.
| Name | Required | Description | Default |
|---|---|---|---|
| working_dir | Yes |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
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.
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.
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.
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.
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.
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.
3 tool updates
v0.1.0- First observed
k8s_get_pod_status - First observed
terraform_apply - First observed
terraform_plan
TDQS
Scored across 3 tools
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.
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.
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.
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
Related MCP Connectors
Fail-closed policy guardrails for AI agents running kubectl, terraform, helm, and argocd.
Security gateway for AI agents: policy, approval, and audited execution, no secrets shared.
Security reviews for coding agents: diffs checked against your org policy and live infrastructure.
- emisarOAuthdev.emisar
Let AI operate servers without SSH. Choose actions, approve risky changes, and audit every step.
Related MCP Servers
- FlicenseNot gradedqualityBmaintenanceGive 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-
- AlicenseAqualityBmaintenanceEnables AI agents to safely inspect and execute version-controlled operational runbooks with policy checks, dry-run planning, and out-of-band approvals.3MIT
- AlicenseAqualityBmaintenanceEnables AI coding agents to plan, policy-check, and cost-estimate Terraform changes while requiring human approval through Slack or CLI before any terraform apply can execute.98 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