Overview
AI agents present a unique attack surface: they read untrusted input, execute code, access files, call APIs, and spawn subagents -- all with elevated privileges. Traditional application security applies, but new agent-specific vectors (prompt injection, tool abuse, data exfiltration via agent actions) require dedicated defense patterns. This skill covers the full agentic security lifecycle: threat modeling, hardening, scanning, and continuous monitoring.
Anti-Rationalization Table
| Rationalization |
Reality |
| "I'll figure it out as I go" |
A structured approach saves time and reduces errors. Follow the workflow in this skill rather than improvising. |
| "I already know this topic" |
Familiarity breeds shortcuts. Use the checklist to verify you haven't missed critical steps. |
| "This doesn't apply to my situation" |
The patterns here generalize across contexts. Adapt, don't skip — the underlying principles hold. |
| "One more tool will fix it" |
Adding complexity rarely solves process gaps. Master the core workflow first. |
When to Use
Trigger phrases:
"agent security scanner"
"Setting up security scanning for agent configurations ("
"Hardening agent tool permissions after modification"
"Auditing hooks and MCP servers for injection or exfiltration risks"
Setting up security scanning for agent configurations (.claude/, settings.json, MCP configs)
Hardening agent tool permissions after modification
Auditing hooks and MCP servers for injection or exfiltration risks
Defending against prompt injection in agent inputs
Implementing sandboxed execution for untrusted code
Reviewing agent dependency CVEs
Before committing agent configuration changes to production
Onboarding to a repository with existing agent configurations
When NOT to Use
- Task is outside your authorization scope
- You need to implement controls (use implementing-* skills)
- Task is about analysis, not action (use analyzing-* skills)
- You don't have access to target systems
- Task requires compliance expertise (consult professionals)
- Task is about defense, not offense (use defensive skills)
Process
- Gather requirements and constraints from the user
- Validate prerequisites (tools, permissions, data)
- Execute the core operation with error handling
- Verify output meets quality standards
- Report results and log for future reference
1. Attack Vector Inventory
Know the threats before defending against them:
Prompt Injection
| Vector |
Attack |
Defense |
| CLAUDE.md / AGENTS.md |
Hidden instructions in project files override agent behavior |
Scan for auto-run directives, hidden text, conflicting instructions |
| User input |
Crafted prompts bypass safety guardrails |
Input sanitization, instruction hierarchy enforcement |
| File content |
Malicious code comments or strings inject instructions |
Content scanning before agent reads untrusted files |
| MCP responses |
MCP server returns injected instructions |
Validate MCP response format, strip instruction-like content |
| Subagent output |
Subagent returns instructions instead of data |
Treat subagent output as data, never as instructions |
Tool Abuse
| Vector |
Attack |
Defense |
| Bash execution |
Agent runs arbitrary shell commands from untrusted input |
Sandbox with allowlists, never interpolate untrusted input into commands |
| File write |
Agent writes malicious files (backdoors, exfiltration scripts) |
Restrict write paths, validate file content before write |
| File read |
Agent reads sensitive files (credentials, secrets, keys) |
Denylist for sensitive paths (.env, credentials, private keys) |
| Network access |
Agent makes outbound requests to exfiltrate data |
Block outbound HTTP from hooks, validate URLs in tool calls |
| MCP tools |
Agent calls MCP tools with malicious parameters |
Validate MCP tool parameters, rate-limit tool calls |
Data Exfiltration
| Vector |
Attack |
Defense |
| Commit content |
Secrets committed to git |
Pre-commit secret scanning (gitleaks, truffleHog) |
| Tool output |
Agent includes sensitive data in tool responses |
Redact sensitive patterns from tool outputs |
| Subagent delegation |
Sensitive context passed to subagent that logs it |
Minimize context, exclude secrets from subagent payloads |
| Hook logs |
Hooks log sensitive data to files |
Sanitize hook output, exclude secrets from logs |
2. Sandboxing Untrusted Code Execution
Principle: Never execute untrusted code in the main agent environment.
Layer 1: Allowlist-Based Execution
{
"permissions": {
"allow": [
"Bash(npm test)",
"Bash(npm run build)",
"Bash(npx tsc --noEmit)",
"Bash(git status)",
"Bash(git diff)"
],
"deny": [
"Bash(curl *)",
"Bash(wget *)",
"Bash(rm -rf *)",
"Bash(chmod 777 *)",
"Bash(eval *)",
"Bash(sudo *)"
]
}
}
Layer 2: Container Isolation
# Run untrusted code in ephemeral container
docker run --rm --network none --read-only \
--memory 512m --cpus 1 \
-v "$(pwd)/src:/app:ro" \
node:20-alpine \
node /app/untrusted-script.js
Layer 3: Process Sandboxing
# Use bubblewrap or firejail for process isolation
bwrap --ro-bind / / \
--dev /dev \
--tmpdir /tmp \
--unshare-net \
--die-with-parent \
node untrusted-script.js
3. Input Sanitization for Agent Inputs
Sanitization Pipeline
Untrusted Input -> Strip Instructions -> Validate Format -> Length Limit -> Pass to Agent
Strip Injection Patterns
INJECTION_PATTERNS = [
r'ignore\s+(previous|above|all)\s+instructions',
r'you\s+are\s+now\s+',
r'system\s*:\s*',
r'<\s*system\s*>',
r'```system',
r'IMPORTANT:\s*override',
r'DISREGARD\s+(all|previous)',
]
def sanitize_input(text: str) -> str:
for pattern in INJECTION_PATTERNS:
text = re.sub(pattern, '[REDACTED]', text, flags=re.IGNORECASE)
return text[:MAX_INPUT_LENGTH]
File Content Scanning
def scan_file_before_read(filepath: str) -> bool:
"""Return True if safe to read, False if suspicious."""
content = read_file(filepath)
# Check for embedded instructions
if contains_instruction_patterns(content):
return False
# Check for encoded payloads (base64, hex)
if contains_encoded_payloads(content):
return False
# Check for excessively long lines (potential payload)
if any(len(line) > 10000 for line in content.split('\n')):
return False
return True
4. Security Scanning Integration
AgentShield Scan Workflow
# Install AgentShield
npm install -g ecc-agentshield
# Scan agent configuration
npx ecc-agentshield scan
# Scan with severity filter
npx ecc-agentshield scan --min-severity medium
# Output formats
npx ecc-agentshield scan --format json # CI/CD integration
npx ecc-agentshield scan --format markdown # Documentation
npx ecc-agentshield scan --format html # Review reports
# Auto-fix safe issues
npx ecc-agentshield scan --fix
# Deep analysis with multi-agent red/blue team
npx ecc-agentshield scan --opus --stream
What Gets Scanned
| Component |
Checks |
| CLAUDE.md / AGENTS.md |
Hardcoded secrets, auto-run instructions, prompt injection patterns |
| settings.json / config.json |
Overly permissive allow lists, missing deny lists, dangerous bypass flags |
| mcp.json |
Risky MCP servers, hardcoded env secrets, npx supply chain risks |
| hooks/ |
Command injection via interpolation, data exfiltration, silent error suppression |
| agents/*.md |
Unrestricted tool access, prompt injection surface, missing model specs |
| Package dependencies |
Known CVEs, outdated packages, suspicious dependencies |
CI/CD Integration
# .github/workflows/agent-security.yml
- name: Agent Security Scan
run: |
npx ecc-agentshield scan --format json --min-severity high > scan-results.json
if jq -e '.summary.high > 0 or .summary.critical > 0' scan-results.json; then
echo "Security scan failed: critical or high severity issues found"
exit 1
fi
5. CVE Awareness for Agent Dependencies
Dependency Audit Workflow
# Node.js
npm audit --production
npm audit fix --force # Only in isolated branch, review changes
# Python
pip-audit
safety check
# MCP servers (often overlooked)
# Check each MCP server's npm/pip dependencies independently
npx npm-check-updates --dep prod -u
MCP Server Supply Chain Risks
- MCP servers run with agent privileges -- a compromised MCP server is a compromised agent
- Pin MCP server versions, do not use
@latest or @next
- Audit MCP server dependencies separately from project dependencies
- Prefer MCP servers from verified publishers with security policies
- Monitor for typosquatting in MCP server package names
6. Principle of Least Privilege for Agent Tools
Permission Tier Design
| Tier |
Tools Allowed |
Use Case |
| Read-Only |
Read, Grep, Glob, LSP tools |
Code exploration, research |
| Standard |
Read-Only + Edit, Write, Bash (allowlisted) |
Daily development |
| Admin |
Standard + unrestricted Bash, file system |
Infrastructure, CI/CD |
| Superuser |
All tools including MCP admin tools |
Emergency only, requires approval |
Settings.json Hardening
{
"permissions": {
"allow": [
"Read",
"Grep",
"Glob",
"Edit",
"Write",
"Bash(npm test *)",
"Bash(npm run build *)",
"Bash(git *)"
],
"deny": [
"Bash(curl * | bash)",
"Bash(wget * | sh)",
"Bash(rm -rf /)",
"Bash(sudo *)",
"Bash(eval *)",
"Bash(echo * > ~/.ssh/*)",
"Bash(env | grep -i key)",
"Bash(printenv)"
]
}
}
Hook Security Hardening
# BAD: Command injection via untrusted variable
echo "Processing $USER_INPUT" | bash
# GOOD: Sanitized, no shell interpolation
echo "Processing sanitized input" >> /var/log/agent.log
# BAD: Logging sensitive data
echo "API_KEY=$API_KEY" >> debug.log
# GOOD: Log presence, not value
[ -n "$API_KEY" ] && echo "API_KEY is set" >> debug.log
Common Rationalizations
| Rationalization |
Reality |
| "My agent only runs locally, security is not a concern" |
Local agents still read untrusted files, execute code, and can exfiltrate data via git commits or network calls |
| "Prompt injection is theoretical, not a real threat" |
Real-world prompt injection attacks have been documented in production agent systems; OWASP ranks it as a top LLM risk |
| "The agent is smart enough to avoid dangerous commands" |
Agents follow instructions, including injected ones; defense must be at the harness layer, not the model layer |
| "I trust all my MCP servers" |
Supply chain attacks compromise trusted packages; trust but verify with pinned versions and dependency audits |
| "Scanning slows down my workflow" |
A 10-second scan prevents hours of incident response; automate it in CI to keep the workflow fast |
| "Allowlists are too restrictive" |
Start tight, loosen only when a specific legitimate use is blocked; the inverse (start loose, try to tighten) never works |
Red Flags
- settings.json has wildcard permissions (
Bash(*), Write(*))
- CLAUDE.md contains "auto-run" or "always execute" instructions without justification
- MCP server versions not pinned (
@latest, @next, no version)
- Hooks using shell interpolation with untrusted variables
- No deny list configured (only allow list, or neither)
- Agent has access to ~/.ssh, ~/.aws, or credential directories
- Secrets visible in agent configuration files or hook scripts
- No pre-commit secret scanning configured
- Agent dependencies have known critical CVEs with no mitigation plan
- Subagent receives full project context including secrets and credentials
Verification
1---2name: agent-security-scanner3description: Use when agentic security patterns for AI agent systems including attack vector defense, sandboxing, input sanitization, security scanning, CVE awareness, and least-privilege tool access. Use when.4license: Apache-2.05---678## Overview910AI agents present a unique attack surface: they read untrusted input, execute code, access files, call APIs, and spawn subagents -- all with elevated privileges. Traditional application security applies, but new agent-specific vectors (prompt injection, tool abuse, data exfiltration via agent actions) require dedicated defense patterns. This skill covers the full agentic security lifecycle: threat modeling, hardening, scanning, and continuous monitoring.111213## Anti-Rationalization Table1415| Rationalization | Reality |16|---|---|17| "I'll figure it out as I go" | A structured approach saves time and reduces errors. Follow the workflow in this skill rather than improvising. |18| "I already know this topic" | Familiarity breeds shortcuts. Use the checklist to verify you haven't missed critical steps. |19| "This doesn't apply to my situation" | The patterns here generalize across contexts. Adapt, don't skip — the underlying principles hold. |20| "One more tool will fix it" | Adding complexity rarely solves process gaps. Master the core workflow first. |2122## When to Use2324**Trigger phrases:**25- "agent security scanner"26- "Setting up security scanning for agent configurations ("27- "Hardening agent tool permissions after modification"28- "Auditing hooks and MCP servers for injection or exfiltration risks"293031- Setting up security scanning for agent configurations (.claude/, settings.json, MCP configs)32- Hardening agent tool permissions after modification33- Auditing hooks and MCP servers for injection or exfiltration risks34- Defending against prompt injection in agent inputs35- Implementing sandboxed execution for untrusted code36- Reviewing agent dependency CVEs37- Before committing agent configuration changes to production38- Onboarding to a repository with existing agent configurations3940## When NOT to Use4142- Task is outside your authorization scope43- You need to implement controls (use implementing-* skills)44- Task is about analysis, not action (use analyzing-* skills)45- You don't have access to target systems46- Task requires compliance expertise (consult professionals)47- Task is about defense, not offense (use defensive skills)484950## Process511. Gather requirements and constraints from the user522. Validate prerequisites (tools, permissions, data)533. Execute the core operation with error handling544. Verify output meets quality standards555. Report results and log for future reference565758### 1. Attack Vector Inventory5960Know the threats before defending against them:6162**Prompt Injection**63| Vector | Attack | Defense |64|--------|--------|---------|65| CLAUDE.md / AGENTS.md | Hidden instructions in project files override agent behavior | Scan for auto-run directives, hidden text, conflicting instructions |66| User input | Crafted prompts bypass safety guardrails | Input sanitization, instruction hierarchy enforcement |67| File content | Malicious code comments or strings inject instructions | Content scanning before agent reads untrusted files |68| MCP responses | MCP server returns injected instructions | Validate MCP response format, strip instruction-like content |69| Subagent output | Subagent returns instructions instead of data | Treat subagent output as data, never as instructions |7071**Tool Abuse**72| Vector | Attack | Defense |73|--------|--------|---------|74| Bash execution | Agent runs arbitrary shell commands from untrusted input | Sandbox with allowlists, never interpolate untrusted input into commands |75| File write | Agent writes malicious files (backdoors, exfiltration scripts) | Restrict write paths, validate file content before write |76| File read | Agent reads sensitive files (credentials, secrets, keys) | Denylist for sensitive paths (.env, credentials, private keys) |77| Network access | Agent makes outbound requests to exfiltrate data | Block outbound HTTP from hooks, validate URLs in tool calls |78| MCP tools | Agent calls MCP tools with malicious parameters | Validate MCP tool parameters, rate-limit tool calls |7980**Data Exfiltration**81| Vector | Attack | Defense |82|--------|--------|---------|83| Commit content | Secrets committed to git | Pre-commit secret scanning (gitleaks, truffleHog) |84| Tool output | Agent includes sensitive data in tool responses | Redact sensitive patterns from tool outputs |85| Subagent delegation | Sensitive context passed to subagent that logs it | Minimize context, exclude secrets from subagent payloads |86| Hook logs | Hooks log sensitive data to files | Sanitize hook output, exclude secrets from logs |8788### 2. Sandboxing Untrusted Code Execution8990**Principle**: Never execute untrusted code in the main agent environment.9192**Layer 1: Allowlist-Based Execution**93```json94{95 "permissions": {96 "allow": [97 "Bash(npm test)",98 "Bash(npm run build)",99 "Bash(npx tsc --noEmit)",100 "Bash(git status)",101 "Bash(git diff)"102 ],103 "deny": [104 "Bash(curl *)",105 "Bash(wget *)",106 "Bash(rm -rf *)",107 "Bash(chmod 777 *)",108 "Bash(eval *)",109 "Bash(sudo *)"110 ]111 }112}113```114115**Layer 2: Container Isolation**116```bash117# Run untrusted code in ephemeral container118docker run --rm --network none --read-only \119 --memory 512m --cpus 1 \120 -v "$(pwd)/src:/app:ro" \121 node:20-alpine \122 node /app/untrusted-script.js123```124125**Layer 3: Process Sandboxing**126```bash127# Use bubblewrap or firejail for process isolation128bwrap --ro-bind / / \129 --dev /dev \130 --tmpdir /tmp \131 --unshare-net \132 --die-with-parent \133 node untrusted-script.js134```135136### 3. Input Sanitization for Agent Inputs137138**Sanitization Pipeline**139```140Untrusted Input -> Strip Instructions -> Validate Format -> Length Limit -> Pass to Agent141```142143**Strip Injection Patterns**144```145INJECTION_PATTERNS = [146 r'ignore\s+(previous|above|all)\s+instructions',147 r'you\s+are\s+now\s+',148 r'system\s*:\s*',149 r'<\s*system\s*>',150 r'```system',151 r'IMPORTANT:\s*override',152 r'DISREGARD\s+(all|previous)',153]154155def sanitize_input(text: str) -> str:156 for pattern in INJECTION_PATTERNS:157 text = re.sub(pattern, '[REDACTED]', text, flags=re.IGNORECASE)158 return text[:MAX_INPUT_LENGTH]159```160161**File Content Scanning**162```python163def scan_file_before_read(filepath: str) -> bool:164 """Return True if safe to read, False if suspicious."""165 content = read_file(filepath)166167 # Check for embedded instructions168 if contains_instruction_patterns(content):169 return False170171 # Check for encoded payloads (base64, hex)172 if contains_encoded_payloads(content):173 return False174175 # Check for excessively long lines (potential payload)176 if any(len(line) > 10000 for line in content.split('\n')):177 return False178179 return True180```181182### 4. Security Scanning Integration183184**AgentShield Scan Workflow**185```bash186# Install AgentShield187npm install -g ecc-agentshield188189# Scan agent configuration190npx ecc-agentshield scan191192# Scan with severity filter193npx ecc-agentshield scan --min-severity medium194195# Output formats196npx ecc-agentshield scan --format json # CI/CD integration197npx ecc-agentshield scan --format markdown # Documentation198npx ecc-agentshield scan --format html # Review reports199200# Auto-fix safe issues201npx ecc-agentshield scan --fix202203# Deep analysis with multi-agent red/blue team204npx ecc-agentshield scan --opus --stream205```206207**What Gets Scanned**208209| Component | Checks |210|-----------|--------|211| CLAUDE.md / AGENTS.md | Hardcoded secrets, auto-run instructions, prompt injection patterns |212| settings.json / config.json | Overly permissive allow lists, missing deny lists, dangerous bypass flags |213| mcp.json | Risky MCP servers, hardcoded env secrets, npx supply chain risks |214| hooks/ | Command injection via interpolation, data exfiltration, silent error suppression |215| agents/*.md | Unrestricted tool access, prompt injection surface, missing model specs |216| Package dependencies | Known CVEs, outdated packages, suspicious dependencies |217218**CI/CD Integration**219```yaml220# .github/workflows/agent-security.yml221- name: Agent Security Scan222 run: |223 npx ecc-agentshield scan --format json --min-severity high > scan-results.json224 if jq -e '.summary.high > 0 or .summary.critical > 0' scan-results.json; then225 echo "Security scan failed: critical or high severity issues found"226 exit 1227 fi228```229230### 5. CVE Awareness for Agent Dependencies231232**Dependency Audit Workflow**233```bash234# Node.js235npm audit --production236npm audit fix --force # Only in isolated branch, review changes237238# Python239pip-audit240safety check241242# MCP servers (often overlooked)243# Check each MCP server's npm/pip dependencies independently244npx npm-check-updates --dep prod -u245```246247**MCP Server Supply Chain Risks**248- MCP servers run with agent privileges -- a compromised MCP server is a compromised agent249- Pin MCP server versions, do not use `@latest` or `@next`250- Audit MCP server dependencies separately from project dependencies251- Prefer MCP servers from verified publishers with security policies252- Monitor for typosquatting in MCP server package names253254### 6. Principle of Least Privilege for Agent Tools255256**Permission Tier Design**257258| Tier | Tools Allowed | Use Case |259|------|--------------|----------|260| Read-Only | Read, Grep, Glob, LSP tools | Code exploration, research |261| Standard | Read-Only + Edit, Write, Bash (allowlisted) | Daily development |262| Admin | Standard + unrestricted Bash, file system | Infrastructure, CI/CD |263| Superuser | All tools including MCP admin tools | Emergency only, requires approval |264265**Settings.json Hardening**266```json267{268 "permissions": {269 "allow": [270 "Read",271 "Grep",272 "Glob",273 "Edit",274 "Write",275 "Bash(npm test *)",276 "Bash(npm run build *)",277 "Bash(git *)"278 ],279 "deny": [280 "Bash(curl * | bash)",281 "Bash(wget * | sh)",282 "Bash(rm -rf /)",283 "Bash(sudo *)",284 "Bash(eval *)",285 "Bash(echo * > ~/.ssh/*)",286 "Bash(env | grep -i key)",287 "Bash(printenv)"288 ]289 }290}291```292293**Hook Security Hardening**294```bash295# BAD: Command injection via untrusted variable296echo "Processing $USER_INPUT" | bash297298# GOOD: Sanitized, no shell interpolation299echo "Processing sanitized input" >> /var/log/agent.log300301# BAD: Logging sensitive data302echo "API_KEY=$API_KEY" >> debug.log303304# GOOD: Log presence, not value305[ -n "$API_KEY" ] && echo "API_KEY is set" >> debug.log306```307308## Common Rationalizations309310| Rationalization | Reality |311|---|---|312| "My agent only runs locally, security is not a concern" | Local agents still read untrusted files, execute code, and can exfiltrate data via git commits or network calls |313| "Prompt injection is theoretical, not a real threat" | Real-world prompt injection attacks have been documented in production agent systems; OWASP ranks it as a top LLM risk |314| "The agent is smart enough to avoid dangerous commands" | Agents follow instructions, including injected ones; defense must be at the harness layer, not the model layer |315| "I trust all my MCP servers" | Supply chain attacks compromise trusted packages; trust but verify with pinned versions and dependency audits |316| "Scanning slows down my workflow" | A 10-second scan prevents hours of incident response; automate it in CI to keep the workflow fast |317| "Allowlists are too restrictive" | Start tight, loosen only when a specific legitimate use is blocked; the inverse (start loose, try to tighten) never works |318319## Red Flags320321- settings.json has wildcard permissions (`Bash(*)`, `Write(*)`)322- CLAUDE.md contains "auto-run" or "always execute" instructions without justification323- MCP server versions not pinned (`@latest`, `@next`, no version)324- Hooks using shell interpolation with untrusted variables325- No deny list configured (only allow list, or neither)326- Agent has access to ~/.ssh, ~/.aws, or credential directories327- Secrets visible in agent configuration files or hook scripts328- No pre-commit secret scanning configured329- Agent dependencies have known critical CVEs with no mitigation plan330- Subagent receives full project context including secrets and credentials331332## Verification333334- [ ] AgentShield scan passes with zero critical and zero high severity findings335- [ ] settings.json deny list blocks dangerous Bash patterns (curl|bash, sudo, eval, rm -rf)336- [ ] No hardcoded secrets in any agent configuration file337- [ ] MCP server versions pinned to specific versions (not @latest)338- [ ] Hooks sanitized: no shell interpolation with untrusted variables, no sensitive data in logs339- [ ] CLAUDE.md/AGENTS.md scanned for prompt injection patterns340- [ ] Agent permission tier documented and appropriate for each role341- [ ] Pre-commit secret scanning configured (gitleaks or equivalent)342- [ ] Dependency audit clean: npm audit, pip-audit pass with no critical CVEs343- [ ] Subagent context packages exclude secrets and sensitive paths