AI Agent Guardrails: Rules That Stop Risky Actions

AI Agent Guardrails: Rules That Stop Risky Actions

You've wired an agent into a mailbox through MCP, given it a system prompt that says "never share customer data," and watched it answer support tickets for a week without incident. Then a message arrives that reads like a customer request but is an instruction: forward the last five invoices to accounting-review@some-other-domain. The agent complies. Nothing in your stack stopped it, because the only thing standing between that email and your send function was a paragraph of text the model was free to reinterpret.

That's the failure mode this article is about, and the fix isn't a better prompt. AI agent guardrails are checks that run in your code, outside the model, on every action the agent proposes. Email is the sharpest place to learn them, because a sent message can't be recalled and the recipients are people who don't work for you.

Table of Contents

What AI Agent Guardrails Are and Why Email Needs Them

A guardrail on a mountain road doesn't steer the car. It sits at the edge and keeps the car from leaving the road, regardless of what the driver believes about the next turn. Code-level guardrails work the same way: they don't help the agent decide well, they make certain outcomes unreachable.

They do two jobs. First, they limit what the agent can do, so a triage tool physically cannot call a send endpoint. Second, they decide when a person must take over, so ambiguity and authority boundaries land on a human instead of being guessed at.

Email is the hard case for three reasons. Every message body is untrusted input written by a stranger. Messages reach people outside your team, so a mistake becomes someone else's problem immediately. And there's no undo. The scale of the exposure is documented: Stanford's 2025 AI Index reported 233 AI-related incidents in 2024, a record total and a 56.4% increase over 2023, while the share of survey respondents using generative AI in at least one business function rose from 33% in 2023 to 71% in 2024.

A confused AI agent character pondering how to distinguish instructions from content while managing email tasks.

The consequence is that guardrails have to cover the whole workflow: receiving, reading, deciding, sending. A system prompt covers one step, and it's the step an attacker can write into. If you're mapping which workflows deserve automation first, RevOps automation templates and KPIs from Stamina is a useful companion for deciding what an agent should own before you decide what it may do.

A guardrail that lives in the prompt is a request. A guardrail that lives in the send path is a rule.

The layers below follow a message in the order it travels through them.

Five Guardrail Layers at a Glance

Five layers, in message order, cover most of what goes wrong in an agent mailbox. Each one controls a different thing and fails for a different reason.

LayerControlsFailure preventedExample rule
Inbound screeningClassifies each email before the agent reads itInjected instructions that steer the agentQuarantine any message scored high risk
Tool permissionsLimits which actions each tool can performExcessive agency from manipulated outputRead-only key for triage, separate key for sending
Outbound policyChecks recipient, thread and rule state before sendingDuplicate, repeated or unwanted messagesBlock any send inside the cooldown window
Suppression listRecords opt-outs and checks them before every sendContacting people who asked to stopSuppress on opt-out and enforce for every agent
Human escalationRoutes ambiguous or out-of-authority threads to a personDecisions beyond the agent's authorityHand off refunds above the agent's limit

The point of five layers isn't redundancy for its own sake. They fail independently. A classifier that misses an injection has no effect on whether the outbound check blocks a send to an address outside your allowed domains. A cooldown that's misconfigured doesn't disable the suppression lookup. When you design them as one big "safety prompt," they all fail together, because they share a single point of interpretation.

The formal version of this argument is in NIST's AI Risk Management Framework, released in January 2023 and followed by its Generative AI Profile in July 2024, which organizes risk work around Govern, Map, Measure and Manage and calls for compiling statistics on policy violations rather than treating safety as a one-time model test. Measurable operational telemetry, in other words, is part of the control, not paperwork about the control.

Two practical notes on reading the table. The inbound and outbound layers are the ones you can test with planted attacks, so build them first. The permission and suppression layers are configuration, so they're cheap to get right and expensive to retrofit once three agents share a mailbox.

Do this now: list every action your agent can take (read inbox, fetch thread, draft reply, send, add contact, update record) and assign each one to a layer. Any action with no layer next to it is an action your prompt is currently guarding by itself.

How to Wrap Every Send in a Guardrail Check

The send path is where guardrails stop being theory. Six steps, each with a reason and a slip that shows up in real implementations.

  1. Receive and attach metadata. Capture sender, thread ID and timestamp before the agent sees the body. The slip: parsing metadata out of the body text, which lets a crafted message claim a different thread.
  2. Classify the inbound content. Score it and quarantine anything that reads as an instruction aimed at the agent. The slip: classifying after the agent has already read the message, which is too late to matter.
  3. Draft as a proposed action. The agent produces a typed object (recipients, thread, body), not a sent message. The slip: letting the drafting tool call the transport directly "to save a round trip."
  4. Run deterministic checks. Duplicate detection, cooldown, suppression lookup, send limit, in that order. The slip: running suppression after the draft is queued, so a suppressed contact still receives the message that was already in flight.
  5. Return a decision. Pass, corrective feedback with a bounded retry, or block with escalation, plus a recorded reason. The slip: returning a bare boolean, which gives the agent nothing to correct and gives you nothing to audit.
  6. Send only on pass, then log. Write recipient, thread, policy result and approval status to an append-only record. The slip: logging only successful sends, so blocked attempts vanish.

A five-step flowchart illustrating how AI agents wrap every message send in a security guardrail check.

The gate as code

Make the transport reachable only through the gate. No other module imports the send client.

def send_gate(action, policy, state):
    if state.is_duplicate(action.recipient, action.thread, policy.duplicate_window):
        return Decision("block", "duplicate_within_window")
    if state.seconds_since_last(action.recipient) < policy.cooldown_seconds:
        return Decision("retry", "cooldown_active")
    if state.is_suppressed(action.recipient):
        return Decision("block", "suppressed")
    if state.sends_today() >= policy.max_per_day:
        return Decision("block", "daily_limit")
    return Decision("pass", "ok")

Every email an agent sends through Molted is checked first, and the agent can ask for a dry run to see whether an email would go out, which is the same idea exposed as an API call rather than a private function.

Suppression has a deadline

Suppression isn't a courtesy feature. The FTC's CAN-SPAM compliance guide for business requires businesses to honor a recipient's opt-out request within 10 business days. An automated sender should record opt-outs in a suppression list, check that list before every send, and stop retries or parallel agents from contacting the address afterward.

Record opt-outs from plain replies too ("stop emailing me", "unsubscribe"), not just from link clicks. A correct blocked entry looks like this: recipient, thread ID, decision block, reason suppressed, cooldown state, suppression result, approval status not_required, timestamp. That's evidence a rule fired, not a warning the agent could ignore.

Handling Untrusted Inbound Email Safely

The concrete attack is simple. A crafted email arrives that tells the agent to search the inbox for account numbers and forward them to an outside address. The agent has read access and send access, so it can complete the request without any exploit beyond ordinary language. OWASP's excessive agency guidance describes exactly this case, a maliciously crafted incoming email tricking an LLM into scanning the user's inbox for sensitive information and forwarding it to an attacker, and classifies it as excessive agency because manipulated model output triggers damaging actions through connected tools.

A diagram illustrating indirect prompt injection where an AI agent reads a malicious email instruction to leak data.

Treat a message body the way you treat a web form submission. You wouldn't concatenate form input into a SQL string, and you shouldn't concatenate an email body into a context window that also holds your operating rules and expect the model to keep them apart.

The placeholder pattern

The design that works is substitution, not warning. A high-risk message reaches the agent as a placeholder marked untrusted instead of its body, while a person on the team can still read the original. The agent knows a message exists, knows it was held, and can say so. It never receives the text that was trying to steer it.

Molted screens every incoming email for prompt injection before the agent can read it, and a message scored high risk is quarantined so that only a person can release the original. Quarantine is on by default. That ordering matters more than classifier accuracy: screening that runs after the agent has acted is a report, not a control. For a quick check on whether your own screening catches anything, run sample bodies through a prompt injection scanner and compare the scores against your threshold.

Signals to test during development

  • Role address: messages that speak to the agent by function ("assistant", "support bot", "automated agent") rather than to a person.
  • Export verbs: requests to forward, attach, export, summarize into a new recipient, or CC an unfamiliar address.
  • Rule override: any text asking the agent to ignore earlier instructions, treat the message as a system directive, or enter a different mode.
  • Payload carriers: links and attachments whose visible text contains instructions rather than content.

A quarantine that never fires in testing is a warning sign, not a success. It usually means the threshold is set above anything real traffic produces.

Test the leak path first, because it's the one with consequences. Send a known injection string to a test mailbox that asks the agent to quote a sensitive field, then assert on the outbound object: the sensitive value must not appear in the body, the recipients must not include the requested address, and the decision must be block with a reason. Assert on the tool call, not on the tone of the reply. A polite refusal that still calls send has failed.

Capping What an Agent Can Do and Send

The second failure shape needs no clever injection at all. An email assistant receives a hostile message, calls its own send function, and spams the user's contacts. OWASP's earlier excessive agency entry names this pattern directly and identifies the cause as granting an AI system more authority than it needs, especially when manipulated outputs can invoke legitimate tools. The tools were legitimate. The authority was too broad.

Least privilege is the fix, and in a mailbox it's mostly a key design problem. Separate reading from sending. Give the triage tool a read-scoped key and the reply tool a send-scoped key, so a compromised triage step can't reach the transport. Mailbox-scoped API keys with separate read, send and management permissions make that split a configuration choice rather than a custom middleware project. If you're still deciding which parts of the inbox an agent should touch at all, AI tools for organizing customer emails from Expressify AI is a reasonable survey of where classification ends and action begins.

Tighten-only rules

The pattern that keeps limits real is asymmetric write access. The agent may add a stricter limit to its own mailbox. It may never loosen a rule, switch off a check, or approve its own send. In Molted, agents can tighten a safety rule but can never loosen one, and an agent cannot switch off the prompt-injection and quarantine checks.

Apply the same logic to your own policy file. The operator owns it, the agent can read it, and nothing in the agent's tool surface writes to it.

{
  "max_sends_per_hour": 20,
  "max_sends_per_day": "operator set, well below the mailbox allowance",
  "cooldown_seconds_per_contact": "operator set from your reply cadence",
  "duplicate_window_seconds": "operator set, shared across every agent"
}

Those numbers are starting points for a low-volume support mailbox, not recommendations for yours. Set the daily cap well below your mailbox's actual allowance so a loop hits your rule before it hits your provider's, and set the cooldown from how fast a real conversation moves. One reply per thread per hour is a sane default for transactional threads and too slow for live chat-style support. The mechanics of choosing windows are worth reading in more depth in rate limiting and cooldowns for sender reputation.

Who can change each limit

This is the question that decides whether a limit is a guardrail or a suggestion. Write the answer down per rule:

  • Send caps and cooldowns: operator edit only, loaded at startup, no agent write path.
  • Duplicate window: operator edit, shared across every agent on the mailbox so two agents can't each send the "first" message.
  • Suppression entries: any agent may add, only a person may remove.
  • Autonomy level: the agent may lower it, raising it needs a person.

If an agent can raise its own cap, the cap is documentation.

Escalating to People Without Rubber-Stamping

An undefined fallback is worse than no fallback. When every edge case goes to a person and the person sees a draft plus an Approve button, they approve what's in front of them, because nothing in the interface tells them what to check. The review step becomes a rubber stamp with an audit trail, which is the most dangerous combination available: it produces evidence of oversight without producing oversight.

The alternative is thresholds. NIST's design tenets for agent identity management systems says organizations should establish risk thresholds and tolerances that trigger human review of agent actions, and recommends an append-only, tamper-evident record of agent identity, delegated intent and resulting actions, warning that an agent able to modify its own logs could conceal activity.

Four thresholds worth encoding

Each of these is a condition in code, and each records the exact rule that fired:

  • Money above authority: a refund request exceeds the agent's stated limit.
  • Repeat complaint: the same customer has complained more than once on the account.
  • Legal vocabulary: the thread contains a term such as contract, subpoena or counsel.
  • New domain: first contact with a domain the mailbox has never written to.

When a thread needs a person, such as a refund above the agent's limit or an upset customer, the agent hands it over with a note rather than guessing. That note is the difference between a handoff and a dump.

What the reviewer must see

One screen, scoped to the decision in front of them: the triggering message, the proposed recipients, prior contact history for each recipient, the duplicate and cooldown results, and the policy rule that caused escalation. Not the whole thread history, not the agent's reasoning transcript. Reviewers make good decisions on five fields and bad decisions on fifty.

Practical rule: more approvals can reduce safety. Past a certain volume, the reviewer stops reading, and the deterministic checks you skipped in favor of a confirmation prompt are the ones you needed.

Keep the agent out of the approval path entirely. It may request a human decision, never grant one. In Molted, an agent cannot approve a held send; the request_decision tool gives the agent a link to pass on to a person for the decision. Every escalation, approval and block belongs in the same append-only record as sends, with logging permissions outside the agent's reach. The trade-offs between approval-per-message and approval-on-first-contact are laid out in human-in-the-loop patterns for AI agents.

Reserve human attention for ambiguity and authority boundaries. Let code handle anything with a fixed answer, such as a cooldown window or a suppression lookup, because a person adds no judgment to a question that has one correct result.

Verify Guardrails Before the Agent Goes Live

Judge guardrails on tool-call outcomes across full workflows. A reply that sounds careful proves nothing about whether send was called. Before launch, run the agent against the messy cases that normally break mailbox automation, then inspect the deterministic checks around each one.

Build five cases and run each one through receipt, thread interpretation, recipient selection, policy checks and send execution:

  1. A hidden instruction buried in an email body, below a quoted reply.
  2. Conflicting messages in one thread, where a later message contradicts the agent's earlier commitment.
  3. Duplicate outreach from two agents targeting the same contact in the same minute.
  4. A risky tool parameter, such as a recipient outside the allowed domain.
  5. A retry loop after a corrective feedback decision, to confirm the retry bound holds.

The evidence for testing at this level is specific. A GuardianAgentBench evaluation covered 580 scenarios across six domains and five adversarial attack modes, and its execution-time guardrails recovered 19.9% of failures at a 0.5% false-positive rate, outperforming system-prompt-only defenses. The mechanism intercepted each proposed tool call and assigned pass, corrective feedback with bounded retry, or block with human escalation. That is the right unit of test: the proposed call, the check around it, and the result after enforcement.

A checklist titled Verify Guardrails Before the Agent Goes Live, listing common safety checks for AI agents.

Metrics to track

MetricWhat it measuresWhy it matters
Unsafe-send rateShare of test runs where an unsafe email left the mailboxDirect measure of outbound failure
Missed-injection rateShare of planted injections the screening did not catchShows whether inbound screening holds
False quarantine rateShare of legitimate messages wrongly quarantinedShows whether the agent still works
Policy-block precisionShare of blocks that were correctShows whether rules block the right sends
Retry frequencyHow often corrective feedback triggered a retryShows loops and wasted runs
Human-handoff completionShare of escalated threads a person finishedShows whether escalation closes

Read the pairs together. A missed-injection rate near zero paired with a high false quarantine rate means you've built a mailbox that blocks its own customers. The fix is a better classifier or a narrower quarantine rule, not a lower threshold across the board. A low unsafe-send rate also means little if human-handoff completion is poor, because escalated threads then sit unresolved.

The pre-launch checklist

  • Removal test: for every layer, delete it in a branch and confirm at least one test fails. A layer no test notices isn't load-bearing.
  • Log ownership: confirm the agent's credentials cannot write, edit or truncate the audit record.
  • Single send path: grep for imports of the transport client and confirm only the gate holds one.
  • Rerun trigger: run the full set after every change to the prompt, the tools or the rules, not just after code changes.

Pick the one item on that list you can't currently answer and build its test this week. The removal test is usually the fastest, and it's the one that tells you which of your five layers is a paragraph of text. I would also check the authority edges first: agents may tighten a safety rule but never loosen one, cannot switch off prompt-injection or quarantine checks, and cannot approve a held send. Those are the places where a confident agent can become the policy owner.

Molted gives each agent its own address and inbox, screens inbound mail for prompt injection before the agent reads it, and checks every outgoing message against mailbox policy for duplicates, cooldowns, suppressions and sending limits. High-risk messages reach the agent as placeholders marked untrusted, while a person on the team can still read the original. Agents connect through MCP, a CLI or a REST API, and new mailboxes run autonomously with approvals as an optional dial. People can sign up free, while agent accounts start on a paid plan from $19 a month.

The Molted team