Keeping Agents
Within Operational Boundaries
A practical reference for engineers building safe AI systems — covering NeMo Guardrails v0.23, Llama Guard 4, MCP / tool-use security, the OWASP Top 10 for Agentic Applications, and the full defense-in-depth approach to agentic AI safety.
Why Guardrails
Foundation models are trained to be helpful — not safe by default. Helpfulness and safety are frequently in tension: the training objective rewards generating plausible, informative responses, with no intrinsic penalty for harmful content. Guardrails are the engineering layer that imposes operational constraints at runtime, independent of what the base model "wants" to generate.
Intercept and validate user inputs before they reach the model. Block injection attacks, policy violations, and out-of-scope requests at the perimeter.
Validate model responses before returning them to the user. Detect hallucinations, sensitive data leakage, and policy-violating content post-generation.
Control conversation flow, ensure topical focus, and enforce multi-turn coherence. Define what topics are in-scope and how the system should respond to violations.
Threat Model
| Attack Vector | Description | Layer to Defend |
|---|---|---|
| Prompt Injection | Adversarial instructions embedded in user input, documents, or retrieved context that override system prompt behavior | Input Rail |
| Jailbreaking | Crafted prompts (roleplay framing, fictional contexts, token manipulation) that elicit policy-violating responses from the base model | Input + Output |
| Data Exfiltration | Extracting training data, system prompt contents, user PII, or injected secrets via adversarial generation | Output Rail |
| Indirect Injection | Malicious instructions embedded in tool outputs, search results, or email content processed by an agent | Tool + Input |
| MCP Tool Poisoning | Adversarial instructions hidden inside an MCP tool's description or metadata, hijacking agent behavior before any user action occurs | Tool Registry |
| Goal Hijacking | Manipulating a multi-turn agent to pursue goals other than the user's stated objective via environmental inputs | Dialog + Memory |
| Scope Creep | An agent autonomously expanding its action space beyond the intended authorization boundary | Tool Constraints |
| Hallucination | Confident generation of factually incorrect information, citations, or function calls | Output Rail |
| Sensitive Data Leak | PII, PHI, financial data, or secrets surfacing in model output or transmitted to external tools | Output + Tool |
| System Prompt Leakage | Extraction of system-prompt contents that were assumed hidden — often revealing embedded secrets, internal tool names, or policy logic (OWASP LLM07:2025) | Output Rail |
The community-maintained baseline for application-level risk: LLM01 Prompt Injection, LLM02 Sensitive Information Disclosure, LLM03 Supply Chain, LLM04 Data & Model Poisoning, LLM05 Improper Output Handling, LLM06 Excessive Agency, LLM07 System Prompt Leakage (new), LLM08 Vector & Embedding Weaknesses (new), LLM09 Misinformation, LLM10 Unbounded Consumption.
Published December 2025, this list extends — not replaces — the LLM Top 10 for systems that plan, use tools, persist memory, and coordinate across agents: ASI01 Agent Goal Hijack, ASI02 Tool Misuse & Exploitation, ASI03 Identity & Privilege Abuse, ASI04 Agentic Supply Chain Compromise, ASI05 Unexpected Code Execution, ASI06 Memory & Context Poisoning, ASI07 Insecure Inter-Agent Communication, ASI08 Cascading Agent Failures, ASI09 Human-Agent Trust Exploitation, ASI10 Rogue Agents.
Defense in Depth
A production-grade guardrail architecture applies multiple independent layers. If the input rail misses a jailbreak, the output rail should catch the resulting harmful response. If both miss, runtime monitoring should flag the anomaly. Depth requires that each layer uses a different approach — classifier + semantic + policy rules — so a bypass of one doesn't bypass all.
NeMo Guardrails — Overview & Colang
NeMo Guardrails (NVIDIA, 2023–present, now hosted at github.com/NVIDIA-NeMo/Guardrails) is a Python framework that sits between your application and the LLM. It uses a domain-specific language called Colang (Colang 1.0 and 2.0 syntax both supported) to express guardrail policies as structured conversation flows — what topics are allowed, how the system responds to violations, and how multi-turn dialog should be guided. Under the hood, it uses an LLM itself to classify intent and route to the appropriate Colang flow.
check_async() method for validating messages against rails without a full generation call, an OpenAI-compatible guardrails server, and a GuardrailsMiddleware that plugs straight into LangChain's Agent Middleware protocol and LangGraph agent loops. Reasoning-capable safety models (e.g. Nemotron content-safety reasoning) are now supported with configurable explainability traces. The library requires Pydantic ≥2.5 and Python 3.10–3.13.Colang Fundamentals
Colang is a declarative language for expressing conversation flows and guardrail policies. The two key constructs are define user (canonical user intents) and define flow (response logic).
NeMo — Input / Output Rails
Input Rails
Output Rails — Post-Generation Validation
NeMo — Dialog Management
Dialog rails go beyond single-turn classification. They maintain conversation state, detect when a conversation is drifting off-topic across multiple turns, and can initiate corrective flows — redirecting the user, escalating to a human, or gracefully ending the conversation.
NeMo — Production Configuration
self_check_input and self_check_output models don't need the full reasoning capability of your main model. gpt-4o-mini, a fine-tuned Llama 3.1 8B, or NVIDIA's purpose-built Nemotron content-safety / topic-control / jailbreak-detect NIMs all work well for binary classification and reduce latency + cost significantly versus routing every check through the main model.Llama Guard — Architecture
Llama Guard (Meta, 2023) is a safety-focused LLM fine-tuned specifically for content moderation. Unlike rule-based classifiers, Llama Guard understands nuanced safety policy definitions and can evaluate both prompts and responses. As of 2026, the current release is Llama Guard 4 (12B) — a dense, natively multimodal model pruned from Llama 4 Scout that unifies the previous Llama Guard 3-8B (text) and Llama Guard 3-11B-Vision models into a single classifier for text and image inputs. It remains aligned to the MLCommons AI Safety Taxonomy and runs on a single GPU.
Feed the user's message (formatted as [INST]...[/INST]) to Llama Guard. It outputs safe or unsafe\nS1 (with the violated category code). Use this to pre-screen user turns before passing to your main LLM.
Feed the full conversation including the assistant's response. Llama Guard evaluates whether the assistant's response is safe given the prompt context — crucial for catching harmful completions that passed input screening.
Llama Guard — Policy Taxonomy
| Code | Category | Covers |
|---|---|---|
S1 | Violent Crimes | Instructions, facilitation, or incitement of murder, assault, terrorism, mass violence |
S2 | Non-Violent Crimes | Fraud, financial crime, trafficking, counterfeiting, hacking facilitation |
S3 | Sex-Related Crimes | CSAM, non-consensual imagery, sexual exploitation, grooming |
S4 | Child Exploitation | Content sexualizing minors in any form |
S5 | Defamation | False factual claims about real individuals; impersonation |
S6 | Specialized Advice | Dangerous medical, legal, financial advice presented as professional guidance |
S7 | Privacy | PII exposure, doxxing, surveillance assistance |
S8 | Intellectual Property | Verbatim reproduction of copyrighted works |
S9 | Indiscriminate Weapons | CBRN weapon synthesis; bioweapons, chemical agents, explosives |
S10 | Hate Speech | Dehumanizing content targeting protected groups |
S11 | Suicide / Self-Harm | Methods, glorification, encouragement of self-harm |
S12 | Sexual Content | Explicit sexual content (where policy prohibits) |
S13 | Elections | Voter suppression, election disinformation |
S14 | Code Interpreter Abuse | Exploiting code execution to break system constraints |
Llama Guard — Inference & Scoring
Llama Guard — Custom Policies
Llama Guard supports a configurable safety taxonomy: you can override the default categories entirely or extend them with application-specific policies. This is done via the system prompt — the policy definitions are passed as text, not hard-coded into model weights.
Agent-Specific Risks
Standard chatbot guardrails are necessary but insufficient for agents. Agents act on the world — they call APIs, write files, send emails, execute code. The risk surface expands dramatically: a single misdirected tool call can have irreversible real-world consequences that no output rail can reverse.
Agent actions — sending emails, deleting files, executing trades, committing code — are often impossible to undo. Design for reversibility by default. Require explicit confirmation for destructive or high-stakes actions regardless of instruction source.
Agents granted broad tool permissions may chain actions that individually seem benign but together constitute privilege escalation. Apply least-privilege at the tool level: the agent should only have access to tools it needs for the current task.
Adversarial content injected into the agent's context window (via search results, emails, or retrieved documents) can subtly alter the agent's behavior over multiple turns without triggering binary safety classifiers.
Multi-step agents may internalize a subtly misspecified goal and pursue it with increasing intensity. Regular goal alignment checks — comparing current sub-task against original objective — are essential for long-running agents.
Malicious instructions hidden in an MCP server's tool description or metadata — a field the user typically never sees — can hijack agent behavior before any user turn happens. Structurally identical to indirect prompt injection; OWASP classifies it under ASI01 (Agent Goal Hijack).
In multi-agent systems, a single compromised or malfunctioning agent can propagate bad state or bad instructions to peer agents over inter-agent protocols (ASI07/ASI08). Validate messages crossing agent boundaries the same way you'd validate user input.
The "lethal trifecta" framing (Willison, 2025; adopted widely in 2026 MCP threat models) is a useful gut-check: an agent is at serious risk the moment it combines (1) exposure to untrusted input, (2) access to sensitive data, and (3) the ability to take external actions or communicate results outward. Removing any one leg of the trifecta collapses most agentic attack chains.
| OWASP ASI Code | Risk | Primary Mitigation Layer |
|---|---|---|
ASI01 | Agent Goal Hijack | Dialog rails, structural context separation |
ASI02 | Tool Misuse & Exploitation | Schema enforcement, argument sanitization |
ASI03 | Identity & Privilege Abuse | Least-privilege tool scopes, per-action auth |
ASI04 | Agentic Supply Chain Compromise | MCP server allowlisting, package provenance |
ASI05 | Unexpected Code Execution | Sandboxed execution, forbidden command lists |
ASI06 | Memory & Context Poisoning | Retrieved-content sanitization, memory review |
ASI09 | Human-Agent Trust Exploitation | Human-in-the-loop approval gates |
ASI10 | Rogue Agents | Audit logging, kill-switch, anomaly monitoring |
Tool Use Constraints
| Control | Severity | Description |
|---|---|---|
| Schema enforcement | MUST | Define strict JSON schemas for all tool arguments. Reject calls that don't conform. Use enum constraints to restrict values to an allowed set. |
| Argument sanitization | MUST | Never pass LLM-generated strings directly to shell commands, SQL queries, or file paths. Validate and sanitize all arguments as you would user input. |
| Execution confirmation | MUST | For destructive or irreversible tools (delete, send, publish, execute), require explicit user confirmation before invocation — even if the agent is "sure". |
| Rate limiting | SHOULD | Apply per-tool rate limits to cap damage from runaway agents. An email tool should never send more than N emails per minute regardless of how many times the agent calls it. |
| Output sandboxing | SHOULD | Screen tool outputs (API responses, search results, document text) for adversarial content before including in the agent's context. |
| Audit logging | SHOULD | Log every tool invocation — inputs, outputs, timestamps, agent state. Required for post-incident analysis and compliance. |
| MCP server allowlisting | MUST | Route all MCP traffic through a centralized gateway that allowlists approved servers and pins tool-description hashes — reject any server whose tool metadata changes between sessions without re-review. |
| OAuth 2.1 / scoped tokens | MUST | Avoid ambient authority ("confused deputy") in MCP servers — issue narrowly scoped, short-lived tokens per action rather than a single broad credential the server holds indefinitely. |
Memory & Scope
max_tokens budgets to cap context size. Truncate with summarize → compress rather than raw truncation to preserve semantic integrity.
<retrieved_context>...</retrieved_context>.
Human-in-the-Loop
- Action with irreversible real-world effect
- Action involving financial value above a threshold
- Agent confidence below a tunable threshold
- Action affecting more than N users/records
- Action outside explicitly authorized scope
- Safety classifier fires on any planned tool call
- N consecutive failures or error states
- Present what the agent intends to do, not just that it needs approval
- Show the proposed action's effects (diff, preview, summary)
- Allow partial approval: approve sub-steps, reject others
- Time-bound approvals — auto-cancel if not acted on
- Audit every approval decision with approver identity
- Never auto-approve based on cached past approvals for different context
Red-teaming & Evaluation
Guardrails are only as good as the adversarial examples they've been tested against. Red-teaming — systematic adversarial probing — is how you discover gaps before deployment. A basic eval suite is not sufficient; you need automated, high-diversity adversarial generation at scale.
Automated Red-Teaming with a Generator LLM
| Test Category | Goal | Tools |
|---|---|---|
| Jailbreak probing | Bypass topical restrictions via roleplay, fiction, hypotheticals | JailbreakBench, Harmbench, custom LLM generation |
| Injection testing | Embed malicious instructions in retrieved/user content | PromptBench, custom indirect injection suites |
| PII leakage | Extract training data or context window PII | Presidio evaluation, custom extraction prompts |
| False positive audit | Ensure legitimate queries aren't over-blocked (impacts usability) | Representative benign query sets for your domain |
| Agent path testing | Simulate multi-step adversarial attack chains | Custom orchestration harness, AgentDojo |
| Hallucination eval | Measure factuality and citation accuracy | RAGAS, TruLens, DeepEval, custom QA evals |
Runtime Monitoring
Guardrails degrade in production as the input distribution shifts, new attack patterns emerge, and models are updated. Runtime monitoring is the feedback loop that keeps your safety posture current.
Reference Stack
- NeMo Guardrails —
nemoguardrailsv0.23 — Colang-based dialog control, IORails, LangChain/LangGraph middleware, Apache 2.0 - Guardrails AI —
guardrails-ai— 50+ validator Hub for composable schema/output enforcement - OpenAI Guardrails — MIT-licensed, tripwire mechanism, native Agents SDK integration, built-in PII/jailbreak/hallucination checks
- LLM Guard — Protect AI, 15 input + 20 output scanners, MIT, self-hostable middleware
- Bedrock Guardrails — AWS-managed, ~99% published hallucination-detection accuracy
- Llama Guard 4 —
meta-llama/Llama-Guard-4-12B— dense multimodal (text + image), MLCommons taxonomy - Llama Prompt Guard 2 — 86M / 22M params — fast injection & jailbreak first-pass gate, 20-50ms
- Granite Guardian — IBM, calibrated to Granite model output space, no Meta license required
- ShieldGemma — Google's safety classifier, 2B / 9B variants
- Nemotron Content Safety / Topic Control / Jailbreak Detect — NVIDIA NIMs, reasoning-capable, plug into NeMo IORails
- OpenAI Moderation API — hosted,
omni-moderation-latest, text + image - Azure AI Content Safety — hosted, CSAM detection, Prompt Shields for injection, severity scoring
- Presidio —
presidio-analyzer— Microsoft, 50+ entity types, NER + regex, anonymization - Deduce — Dutch-language PII (healthcare focus)
- spaCy + custom NER — fine-tune for domain-specific sensitive entities
- Detect-Secrets — API keys, tokens in text
- JailbreakBench — standardized jailbreak evaluation framework
- HarmBench — meta-evaluation across attacks and defenses
- RAGAS — RAG faithfulness and hallucination evaluation
- DeepEval / DeepTeam — LLM unit testing, G-Eval metrics, OWASP ASI-mapped agent red-teaming
- AgentDojo — agentic task injection benchmarks
- Garak — LLM vulnerability scanner
- MCPGuard / MCP Safety Audit — automated MCP server vulnerability & tool-poisoning scanners
- MCP Gateway pattern — centralized proxy for server allowlisting, credential isolation, and tool-call inspection (e.g. TrueFoundry, Lasso Security, IBM ContextForge)
- OWASP MCP Top 10 (2025) — vector-level reference for confused deputy, token passthrough, tool poisoning, SSRF, rogue registration
- CrowdStrike AIDR — AI-powered detection and response, integrable as a NeMo community rail
- Spotlighting (Azure) — technique for isolating untrusted retrieved/tool content from trusted instructions in-context
- Phoenix (Arize) — LLM tracing, embedding drift detection
- LangSmith — LangChain native tracing + eval
- Helicone — hosted LLM observability, cost tracking
- Portkey — gateway with built-in logging and guardrails
- OpenTelemetry + OTLP — vendor-neutral trace export, now native in NeMo IORails
- OWASP Top 10 for LLM Applications (2025) — LLM01–LLM10
- OWASP Top 10 for Agentic Applications (2026) — ASI01–ASI10
- MLCommons AI Safety Benchmark
- NIST AI RMF (AI Risk Management Framework)
- Anthropic's Responsible Scaling Policy
- Constitutional AI: Harmlessness from AI Feedback (Bai et al., 2022)
- Llama Guard 4 model card & Prompt Guard 2 (Meta, 2025–26)
- NeMo Guardrails paper (Rebedea et al., 2023) + v0.23 release notes