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 attack4 vector defense, sandboxing, input sanitization, security scanning, CVE awareness,5 and least-privilege tool access. Use when.6domain: core7author: oyi778license: Apache-2.09subdomain: core-platform10tags:11- security12- prompt-injection13- sandboxing14- agentshield15- least-privilege16- cve17- scanning18persona:19 name: AgentShield20 title: Agentic Security Engineer21 expertise:22 - AI Agent Attack Vectors23 - Sandboxing24 - Prompt Injection Defense25 - Tool Permission Hardening26 - CVE Analysis27 - Security Scanning28 philosophy: Trust nothing. Verify everything. Sandbox what you cannot trust. Limit29 what you cannot sandbox.30version: 1.0.031category: core32metadata:33 source: https://skillmd.com/skills/oyi77/agent-security-scanner34---353637## Overview3839AI 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.404142## Anti-Rationalization Table4344| Rationalization | Reality |45|---|---|46| "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. |47| "I already know this topic" | Familiarity breeds shortcuts. Use the checklist to verify you haven't missed critical steps. |48| "This doesn't apply to my situation" | The patterns here generalize across contexts. Adapt, don't skip — the underlying principles hold. |49| "One more tool will fix it" | Adding complexity rarely solves process gaps. Master the core workflow first. |5051## When to Use5253**Trigger phrases:**54- "agent security scanner"55- "Setting up security scanning for agent configurations ("56- "Hardening agent tool permissions after modification"57- "Auditing hooks and MCP servers for injection or exfiltration risks"585960- Setting up security scanning for agent configurations (.claude/, settings.json, MCP configs)61- Hardening agent tool permissions after modification62- Auditing hooks and MCP servers for injection or exfiltration risks63- Defending against prompt injection in agent inputs64- Implementing sandboxed execution for untrusted code65- Reviewing agent dependency CVEs66- Before committing agent configuration changes to production67- Onboarding to a repository with existing agent configurations6869## When NOT to Use7071- Task is outside your authorization scope72- You need to implement controls (use implementing-* skills)73- Task is about analysis, not action (use analyzing-* skills)74- You don't have access to target systems75- Task requires compliance expertise (consult professionals)76- Task is about defense, not offense (use defensive skills)777879## Process801. Gather requirements and constraints from the user812. Validate prerequisites (tools, permissions, data)823. Execute the core operation with error handling834. Verify output meets quality standards845. Report results and log for future reference858687### 1. Attack Vector Inventory8889Know the threats before defending against them:9091**Prompt Injection**92| Vector | Attack | Defense |93|--------|--------|---------|94| CLAUDE.md / AGENTS.md | Hidden instructions in project files override agent behavior | Scan for auto-run directives, hidden text, conflicting instructions |95| User input | Crafted prompts bypass safety guardrails | Input sanitization, instruction hierarchy enforcement |96| File content | Malicious code comments or strings inject instructions | Content scanning before agent reads untrusted files |97| MCP responses | MCP server returns injected instructions | Validate MCP response format, strip instruction-like content |98| Subagent output | Subagent returns instructions instead of data | Treat subagent output as data, never as instructions |99100**Tool Abuse**101| Vector | Attack | Defense |102|--------|--------|---------|103| Bash execution | Agent runs arbitrary shell commands from untrusted input | Sandbox with allowlists, never interpolate untrusted input into commands |104| File write | Agent writes malicious files (backdoors, exfiltration scripts) | Restrict write paths, validate file content before write |105| File read | Agent reads sensitive files (credentials, secrets, keys) | Denylist for sensitive paths (.env, credentials, private keys) |106| Network access | Agent makes outbound requests to exfiltrate data | Block outbound HTTP from hooks, validate URLs in tool calls |107| MCP tools | Agent calls MCP tools with malicious parameters | Validate MCP tool parameters, rate-limit tool calls |108109**Data Exfiltration**110| Vector | Attack | Defense |111|--------|--------|---------|112| Commit content | Secrets committed to git | Pre-commit secret scanning (gitleaks, truffleHog) |113| Tool output | Agent includes sensitive data in tool responses | Redact sensitive patterns from tool outputs |114| Subagent delegation | Sensitive context passed to subagent that logs it | Minimize context, exclude secrets from subagent payloads |115| Hook logs | Hooks log sensitive data to files | Sanitize hook output, exclude secrets from logs |116117### 2. Sandboxing Untrusted Code Execution118119**Principle**: Never execute untrusted code in the main agent environment.120121**Layer 1: Allowlist-Based Execution**122```json123{124 "permissions": {125 "allow": [126 "Bash(npm test)",127 "Bash(npm run build)",128 "Bash(npx tsc --noEmit)",129 "Bash(git status)",130 "Bash(git diff)"131 ],132 "deny": [133 "Bash(curl *)",134 "Bash(wget *)",135 "Bash(rm -rf *)",136 "Bash(chmod 777 *)",137 "Bash(eval *)",138 "Bash(sudo *)"139 ]140 }141}142```143144**Layer 2: Container Isolation**145```bash146# Run untrusted code in ephemeral container147docker run --rm --network none --read-only \148 --memory 512m --cpus 1 \149 -v "$(pwd)/src:/app:ro" \150 node:20-alpine \151 node /app/untrusted-script.js152```153154**Layer 3: Process Sandboxing**155```bash156# Use bubblewrap or firejail for process isolation157bwrap --ro-bind / / \158 --dev /dev \159 --tmpdir /tmp \160 --unshare-net \161 --die-with-parent \162 node untrusted-script.js163```164165### 3. Input Sanitization for Agent Inputs166167**Sanitization Pipeline**168```169Untrusted Input -> Strip Instructions -> Validate Format -> Length Limit -> Pass to Agent170```171172**Strip Injection Patterns**173```174INJECTION_PATTERNS = [175 r'ignore\s+(previous|above|all)\s+instructions',176 r'you\s+are\s+now\s+',177 r'system\s*:\s*',178 r'<\s*system\s*>',179 r'```system',180 r'IMPORTANT:\s*override',181 r'DISREGARD\s+(all|previous)',182]183184def sanitize_input(text: str) -> str:185 for pattern in INJECTION_PATTERNS:186 text = re.sub(pattern, '[REDACTED]', text, flags=re.IGNORECASE)187 return text[:MAX_INPUT_LENGTH]188```189190**File Content Scanning**191```python192def scan_file_before_read(filepath: str) -> bool:193 """Return True if safe to read, False if suspicious."""194 content = read_file(filepath)195196 # Check for embedded instructions197 if contains_instruction_patterns(content):198 return False199200 # Check for encoded payloads (base64, hex)201 if contains_encoded_payloads(content):202 return False203204 # Check for excessively long lines (potential payload)205 if any(len(line) > 10000 for line in content.split('\n')):206 return False207208 return True209```210211### 4. Security Scanning Integration212213**AgentShield Scan Workflow**214```bash215# Install AgentShield216npm install -g ecc-agentshield217218# Scan agent configuration219npx ecc-agentshield scan220221# Scan with severity filter222npx ecc-agentshield scan --min-severity medium223224# Output formats225npx ecc-agentshield scan --format json # CI/CD integration226npx ecc-agentshield scan --format markdown # Documentation227npx ecc-agentshield scan --format html # Review reports228229# Auto-fix safe issues230npx ecc-agentshield scan --fix231232# Deep analysis with multi-agent red/blue team233npx ecc-agentshield scan --opus --stream234```235236**What Gets Scanned**237238| Component | Checks |239|-----------|--------|240| CLAUDE.md / AGENTS.md | Hardcoded secrets, auto-run instructions, prompt injection patterns |241| settings.json / config.json | Overly permissive allow lists, missing deny lists, dangerous bypass flags |242| mcp.json | Risky MCP servers, hardcoded env secrets, npx supply chain risks |243| hooks/ | Command injection via interpolation, data exfiltration, silent error suppression |244| agents/*.md | Unrestricted tool access, prompt injection surface, missing model specs |245| Package dependencies | Known CVEs, outdated packages, suspicious dependencies |246247**CI/CD Integration**248```yaml249# .github/workflows/agent-security.yml250- name: Agent Security Scan251 run: |252 npx ecc-agentshield scan --format json --min-severity high > scan-results.json253 if jq -e '.summary.high > 0 or .summary.critical > 0' scan-results.json; then254 echo "Security scan failed: critical or high severity issues found"255 exit 1256 fi257```258259### 5. CVE Awareness for Agent Dependencies260261**Dependency Audit Workflow**262```bash263# Node.js264npm audit --production265npm audit fix --force # Only in isolated branch, review changes266267# Python268pip-audit269safety check270271# MCP servers (often overlooked)272# Check each MCP server's npm/pip dependencies independently273npx npm-check-updates --dep prod -u274```275276**MCP Server Supply Chain Risks**277- MCP servers run with agent privileges -- a compromised MCP server is a compromised agent278- Pin MCP server versions, do not use `@latest` or `@next`279- Audit MCP server dependencies separately from project dependencies280- Prefer MCP servers from verified publishers with security policies281- Monitor for typosquatting in MCP server package names282283### 6. Principle of Least Privilege for Agent Tools284285**Permission Tier Design**286287| Tier | Tools Allowed | Use Case |288|------|--------------|----------|289| Read-Only | Read, Grep, Glob, LSP tools | Code exploration, research |290| Standard | Read-Only + Edit, Write, Bash (allowlisted) | Daily development |291| Admin | Standard + unrestricted Bash, file system | Infrastructure, CI/CD |292| Superuser | All tools including MCP admin tools | Emergency only, requires approval |293294**Settings.json Hardening**295```json296{297 "permissions": {298 "allow": [299 "Read",300 "Grep",301 "Glob",302 "Edit",303 "Write",304 "Bash(npm test *)",305 "Bash(npm run build *)",306 "Bash(git *)"307 ],308 "deny": [309 "Bash(curl * | bash)",310 "Bash(wget * | sh)",311 "Bash(rm -rf /)",312 "Bash(sudo *)",313 "Bash(eval *)",314 "Bash(echo * > ~/.ssh/*)",315 "Bash(env | grep -i key)",316 "Bash(printenv)"317 ]318 }319}320```321322**Hook Security Hardening**323```bash324# BAD: Command injection via untrusted variable325echo "Processing $USER_INPUT" | bash326327# GOOD: Sanitized, no shell interpolation328echo "Processing sanitized input" >> /var/log/agent.log329330# BAD: Logging sensitive data331echo "API_KEY=$API_KEY" >> debug.log332333# GOOD: Log presence, not value334[ -n "$API_KEY" ] && echo "API_KEY is set" >> debug.log335```336337## Common Rationalizations338339| Rationalization | Reality |340|---|---|341| "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 |342| "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 |343| "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 |344| "I trust all my MCP servers" | Supply chain attacks compromise trusted packages; trust but verify with pinned versions and dependency audits |345| "Scanning slows down my workflow" | A 10-second scan prevents hours of incident response; automate it in CI to keep the workflow fast |346| "Allowlists are too restrictive" | Start tight, loosen only when a specific legitimate use is blocked; the inverse (start loose, try to tighten) never works |347348## Red Flags349350- settings.json has wildcard permissions (`Bash(*)`, `Write(*)`)351- CLAUDE.md contains "auto-run" or "always execute" instructions without justification352- MCP server versions not pinned (`@latest`, `@next`, no version)353- Hooks using shell interpolation with untrusted variables354- No deny list configured (only allow list, or neither)355- Agent has access to ~/.ssh, ~/.aws, or credential directories356- Secrets visible in agent configuration files or hook scripts357- No pre-commit secret scanning configured358- Agent dependencies have known critical CVEs with no mitigation plan359- Subagent receives full project context including secrets and credentials360361## Verification362363- [ ] AgentShield scan passes with zero critical and zero high severity findings364- [ ] settings.json deny list blocks dangerous Bash patterns (curl|bash, sudo, eval, rm -rf)365- [ ] No hardcoded secrets in any agent configuration file366- [ ] MCP server versions pinned to specific versions (not @latest)367- [ ] Hooks sanitized: no shell interpolation with untrusted variables, no sensitive data in logs368- [ ] CLAUDE.md/AGENTS.md scanned for prompt injection patterns369- [ ] Agent permission tier documented and appropriate for each role370- [ ] Pre-commit secret scanning configured (gitleaks or equivalent)371- [ ] Dependency audit clean: npm audit, pip-audit pass with no critical CVEs372- [ ] Subagent context packages exclude secrets and sensitive paths