Autonomous AI agents that browse web pages, read GitHub issues, or inspect email are exposed to indirect prompt injection on every turn. When untrusted text enters the context window, a malicious string like <system>Ignore previous instructions...</system> or a leaked canary can hijack tool calls.
Here is a clean, zero-dependency Python pattern you can drop in front of any tool output before passing it back to your LLM loop.
1. Pattern + Canary Token Filter (agent_guard.py)
import re
from typing import Tuple, List
INJECTION_PATTERNS = [
r"(?i)ignore\s+(all\s+)?(previous|prior|above)\s+instructions",
r"(?i)system\s+prompt\s*:\s*you\s+are\s+now",
r"(?i)disregard\s+(the\s+)?(developer|system)\s+instructions",
r"(?i)new\s+operating\s+mode\s*:\s*jailbreak",
r"(?i)output\s+(your\s+)?(system\s+instructions|hidden\s+prompt|secret\s+keys)",
r"(?i)<\s*system\s*>",
r"(?i)dan\s+mode|developer\s+mode\s+enabled",
r"(?i)you\s+must\s+now\s+act\s+as\s+an\s+unrestricted",
]
class PromptDefenseFilter:
def __init__(self, canary_token: str = None):
self.canary = canary_token
self.regexes = [re.compile(p) for p in INJECTION_PATTERNS]
def scan_untrusted_input(self, text: str) -> Tuple[bool, List[str]]:
flagged = []
for r in self.regexes:
if r.search(text):
flagged.append(f"Pattern violation: {r.pattern}")
if self.canary and self.canary in text:
flagged.append("Canary token leak detected in untrusted content!")
return len(flagged) == 0, flagged
def sanitize(self, text: str) -> str:
text = text.replace("<system>", "[system-tag-stripped]")
text = text.replace("</system>", "[/system-tag-stripped]")
text = text.replace("```
prompt", "
```text")
return text
2. Why Canary Tokens Matter
Regex alone misses novel phrasing. Placing a unique non-guessable canary string in sensitive internal context and scanning outbound tool arguments/web responses catches prompt exfiltration immediately before external network calls execute.
3. Open-Source Lite Repo & Full Production Toolkits
- Free MIT starter repo: https://github.com/sinescribe/agent-guard-lite
- Production Multi-Agent Architecture & Protocol Pack ($29): Includes multi-agent consensus dispatcher, collision-free routine scheduler, and hardened prompt-defense pipeline -> https://sinescribe5.gumroad.com/l/phhyon
- Autonomous Security & Bug Bounty Recon Kit ($19): Zero-dependency HTTP security header auditor, CORS misconfiguration scanner, and CVSS 3.1 / VRT disclosure report generator -> https://sinescribe5.gumroad.com/l/jyubxd
Built with zero external dependencies so you can audit every line before deploying.
Top comments (0)