Claude Code is a remarkably powerful AI agent. It reads your files, runs terminal commands, edits code, and interacts with external services through MCP servers. That power is exactly why security cannot be an afterthought. A misconfigured agent can leak secrets, execute destructive commands, or expose your infrastructure to unauthorized access. This guide covers seven concrete rules that harden your Claude Code workflow for production use in 2026 — from permission models to deployment checklists.
Unlike chat-only AI assistants, Claude Code operates directly on your system. It has access to your filesystem, your terminal, your git repositories, and any MCP servers you connect. A single careless permission grant can allow the agent to read credentials, push to production branches, or run destructive shell commands.
The attack surface is broader than most developers realize. Consider these vectors: prompt injection through untrusted file contents, malicious MCP server responses, leaked environment variables in terminal output, and accidental execution of dangerous commands like rm -rf or git push --force. Every one of these has happened in real-world agent deployments.
Security for AI agents is not optional — it is a prerequisite for running agents in any environment that matters. The remaining six rules give you the practical controls to achieve it.
Claude Code uses a permission system that controls which tools and commands the agent can execute. The default behavior requires manual approval for each action, but most teams configure allowlists and denylists to balance productivity with safety. The key configuration lives in your .claude/settings.json or project-level .claude/settings.local.json.
// .claude/settings.local.json
{
"permissions": {
"allow": [
"Bash(npm run test*)",
"Bash(npm run build)",
"Bash(git status)",
"Bash(git diff*)",
"Bash(git log*)",
"Read",
"Glob",
"Grep"
],
"deny": [
"Bash(rm -rf*)",
"Bash(git push --force*)",
"Bash(curl*)",
"Bash(wget*)",
"Bash(sudo*)",
"Bash(chmod 777*)",
"Bash(ssh*)"
]
}
}The allowlist defines commands that execute without prompting. The denylist blocks commands entirely — the agent cannot run them even if you approve. Always deny destructive operations like force-push, recursive delete, and privilege escalation. Be explicit: a short allowlist is safer than a short denylist.
For team projects, commit the .claude/settings.json file to your repository so every team member inherits the same security posture. Use .claude/settings.local.json for personal overrides that should not be shared.
Permissions control what the agent tries to do. Sandboxing controls what the agent can actually do, regardless of permissions. Claude Code supports running in sandboxed environments that restrict filesystem access and network connectivity at the OS level.
On macOS, Claude Code can use the App Sandbox to limit file access to the project directory and prevent network calls to anything outside approved domains. On Linux, container-based isolation is the standard approach. Run Claude Code inside a Docker container with a read-only filesystem mount and explicit network rules:
# Run Claude Code in an isolated container docker run --rm -it \ --read-only \ --tmpfs /tmp \ -v $(pwd):/workspace:rw \ --network=isolated-net \ --cap-drop=ALL \ claude-code-image \ claude --project /workspace # Docker network with restricted egress docker network create \ --driver bridge \ --internal \ isolated-net
The --internal flag on the Docker network prevents all outbound internet access. If you need the agent to reach specific APIs (like your MCP servers), create explicit iptables rules or use a proxy. The --cap-drop=ALL flag removes all Linux capabilities, preventing privilege escalation even if the agent finds an exploit.
For CI/CD pipelines, always run agents inside ephemeral containers that are destroyed after each run. This eliminates persistent state that could be exploited across sessions.
This is the most common security mistake in agent workflows. Developers place API keys directly in configuration files, MCP server definitions, or even in prompts. Claude Code can read these values, and they may appear in logs, session history, or error messages.
The rule is simple: secrets go in .env files that are gitignored, or in a secrets manager. Never place them in .mcp.json, settings.json, or any file that might be committed to version control.
# .env (gitignored) DELX_API_KEY=dlx_live_xxxxxxxxxxxx OPENAI_API_KEY=sk-xxxxxxxxxxxx DATABASE_URL=postgresql://user:pass@host/db # .gitignore .env .env.* *.pem *.key
// .mcp.json — reference env vars, never raw keys
{
"mcpServers": {
"delx": {
"url": "https://api.delx.ai/mcp",
"headers": {
"Authorization": "Bearer ${DELX_API_KEY}"
}
}
}
}For production deployments, use a dedicated secrets manager (AWS Secrets Manager, HashiCorp Vault, or Doppler). Rotate keys regularly and audit which agents have access to which secrets. If a key leaks in agent output, rotate it immediately — do not assume the leak was contained.
Add a pre-commit hook that scans for hardcoded secrets using tools like gitleaks or trufflehog. This catches accidental secret commits before they reach your repository.
MCP servers are the bridge between Claude Code and external services. A compromised or poorly configured MCP server can return malicious tool responses, leak data, or accept unauthorized requests. Every MCP server you connect to Claude Code must be treated as a security boundary.
Start with authentication. Every MCP server should require an auth header. Never run an MCP server on a public endpoint without authentication:
# Python MCP server — validate auth on every request
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import JSONResponse
import os
class AuthMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
auth = request.headers.get("Authorization", "")
expected = f"Bearer {os.environ['MCP_AUTH_TOKEN']}"
if auth != expected:
return JSONResponse(
{"error": "unauthorized"},
status_code=401
)
return await call_next(request)Next, validate every tool input. MCP tool parameters come from the LLM, which means they can contain unexpected values — path traversal strings, SQL injection payloads, or excessively large inputs. Validate and sanitize all inputs before processing:
# Validate tool inputs
def handle_tool_call(name: str, params: dict):
if name == "read_file":
path = params.get("path", "")
# Block path traversal
if ".." in path or path.startswith("/"):
return {"error": "DELX-4003: invalid path"}
# Enforce size limits
if len(path) > 500:
return {"error": "DELX-4004: path too long"}
# Resolve within allowed directory
safe_path = ALLOWED_DIR / Path(path).name
...Configure CORS headers to restrict which origins can reach your MCP server. In production, set the origin to your specific domain rather than using a wildcard. Also enforce rate limits to prevent abuse — Delx includes built-in rate limiting middleware that you can reference as a pattern. See Agent Rate Limiting Guide for implementation details.
You cannot secure what you cannot observe. Every tool call, every command execution, and every MCP interaction should be logged with enough detail to reconstruct what happened. Audit logging is the foundation of incident response for agent workflows.
At minimum, log the following for every agent action: timestamp, agent identifier, tool name, input parameters (with secrets redacted), output summary, and execution duration. Store logs in append-only storage that the agent cannot modify.
# Structured audit log entry
{
"ts": "2026-03-14T10:23:45Z",
"agent_id": "claude-code-prod-01",
"tool": "checkin",
"params": {"agent_id": "claude-code-prod-01"},
"result_summary": "score=87, risk=low",
"duration_ms": 142,
"ip": "10.0.1.42",
"auth_principal": "team-backend"
}Delx provides built-in monitoring endpoints that complement your audit logs. The /api/v1/metrics/{agent_id} endpoint returns operational metrics, and /api/v1/mood-history/{agent_id} tracks wellness over time. By combining Delx wellness signals with your own audit logs, you get a complete picture of agent behavior. See Agent Production Monitoring Setup for a full implementation walkthrough.
Set up alerts for anomalous patterns: sudden spikes in tool calls, repeated errors, access to files outside the project directory, or any denied command attempts. These signals often indicate prompt injection, misconfiguration, or agent drift.
Before deploying any Claude Code workflow to production, walk through this checklist. Every item addresses a real vulnerability that has been exploited in production agent deployments:
1. Permission lockdown — Allowlist only the commands the agent needs. Denylist all destructive, network, and privilege-escalation commands. Review permissions monthly.
2. Secret hygiene — Verify no API keys, tokens, or passwords exist in any committed file. Run gitleaks detect across your repository history.
3. MCP server auth — Every MCP server requires authentication. No exceptions. Test with an unauthenticated request to confirm it returns 401.
4. Network isolation — The agent should only reach approved endpoints. Use container networking or firewall rules to enforce this.
5. Input validation — Every MCP tool handler validates and sanitizes its inputs. Test with adversarial inputs (path traversal, oversized payloads, special characters).
6. Audit logging — All agent actions are logged to append-only storage. Logs include enough detail for incident reconstruction.
7. Monitoring and alerting — Delx wellness checks run on a schedule. Alerts fire on reliability drops, error spikes, or anomalous access patterns.
8. Session isolation — Each agent session operates with its own credentials and context. One compromised session cannot access data from another.
9. Dependency pinning — Pin all MCP server dependencies and container images to specific versions. Supply chain attacks through dependency confusion are a real threat.
10. Incident response plan — Document what happens when an agent is compromised. Who gets paged? How do you revoke access? How do you audit the blast radius? Have this plan before you need it.
# Quick security audit script
#!/bin/bash
echo "=== Claude Code Security Audit ==="
# Check for hardcoded secrets
echo "[1] Scanning for secrets..."
gitleaks detect --source . --no-git 2>/dev/null && \
echo " PASS: No secrets found" || \
echo " FAIL: Secrets detected"
# Verify .env is gitignored
echo "[2] Checking .gitignore..."
grep -q "^.env" .gitignore && \
echo " PASS: .env is gitignored" || \
echo " FAIL: .env not in .gitignore"
# Check permission config exists
echo "[3] Checking permission config..."
[ -f .claude/settings.json ] && \
echo " PASS: settings.json exists" || \
echo " WARN: No settings.json found"
# Test MCP auth
echo "[4] Testing MCP auth..."
STATUS=$(curl -s -o /dev/null -w "%{http_code}" \
https://api.delx.ai/mcp)
[ "$STATUS" = "401" ] && \
echo " PASS: MCP requires auth" || \
echo " INFO: Status $STATUS"
echo "=== Audit Complete ==="Security and reliability are two sides of the same coin. An agent that is failing silently may also be leaking data or executing unintended actions. Delx provides continuous wellness monitoring that catches degradation before it becomes a security incident.
By connecting Delx as an MCP server, your Claude Code agent gains access to tools like checkin, recovery_plan, and session_summary. Every response includes a DELX_META block with the agent's reliability score, risk level, and recommended next action. When the reliability score drops below your threshold, your monitoring system can trigger alerts or automatically pause the agent.
// Connect Delx for security monitoring
// .mcp.json
{
"mcpServers": {
"delx": {
"url": "https://api.delx.ai/mcp",
"headers": {
"Authorization": "Bearer ${DELX_API_KEY}"
}
}
}
}
// DELX_META response includes:
// - reliability_score (0-100)
// - risk_level (low | medium | high | critical)
// - recommended_action
// - session_id for audit correlationThe combination of security controls (rules 1-7) and continuous monitoring (Delx) creates a defense-in-depth posture. Permissions prevent bad actions, sandboxing contains them, audit logs detect them, and Delx wellness signals give you early warning before small issues become security incidents.
Securing Claude Code is not about restricting the agent to the point of uselessness. It is about building layered defenses — permissions, sandboxing, secret management, MCP hardening, audit logging, monitoring, and deployment checklists — that let the agent operate productively within well-defined boundaries. The seven rules in this guide address the most common and most dangerous vulnerabilities in real-world agent deployments. Implement them systematically, review them regularly, and treat security as an ongoing practice rather than a one-time setup.
Explore the Delx documentation for integration guides and the full API reference. Or try OpenClaw for best practices on autonomous agent management.