Action Guardrails and Policy Engines
Words can be wrong without much harm. Actions change things, so decide each one with rules the model cannot rewrite.
Put a policy decision in front of every consequential tool call: allow, ask or deny, from verified identity, exact parameters and current state. Deny by default, let explicit denials win, refuse on errors and let the target system enforce its own limits as well.
What you will learn: tool guardrails, how policy engines work, safe SQL and code execution, controls for long-running agents and the architecture of runtime enforcement.
Prerequisites: Designing Tool Schemas and Contracts and Tool Permissions, Approvals and Abuse Risks.
The example runs in November 2026 with Python 3.13 and its built-in SQLite module. The policy format is invented for teaching; it is not the language of any policy product.
Layers of a tool guardrail
After the call, check the result too: size, type, sensitive content and whether it is trustworthy enough to influence the next step.
What a decision needs to know
| Fact | Example | Trusted source |
|---|---|---|
| Subject and actor | User u-204 through support-agent | Verified token |
| Action | refund.create | The tool being called |
| Parameters | Amount 2000 in cents, order A-1 | Validated call |
| Resource state | Account open, order delivered | System of record |
| History | Refunded today: 80.00 | Ledger |
| Session context | Read untrusted content | Runtime tracking |
The model supplies a proposal. It should not supply any fact that decides whether the proposal is allowed.
Why not ask the model?
A prompt such as "never refund more than 50" is useful guidance and no guarantee. The model can misread it, forget it in a long context or be talked out of it. A rule in code gives the same answer for the same input and can be tested, reviewed and audited.
| Rule belongs in | Examples |
|---|---|
| Prompt | Tone, preferred approach, when to ask for details |
| Schema | Required fields, types, allowed values |
| Policy engine | Who may do what, up to which limit, under which conditions |
| Target system | Record rights, integrity constraints, balances |
How a decision is made
A policy engine takes a request (who, what, which resource, context) and rules, and returns a decision. Keeping rules separate from agent code lets owners review and change them in one place.
| Term | Meaning |
|---|---|
| Decision point | Evaluates the rules |
| Enforcement point | Asks, then obeys the answer |
| Information source | Supplies facts such as role or account status |
| Policy administration | How rules are written, reviewed and released |
Open projects such as Open Policy Agent and Cedar provide policy languages and evaluators. Cloud and agent platforms offer their own. Compare how they express your rules, how fast they decide and what they do on errors.
Run a small engine and a guarded database
The engine denies by default and lets a matching deny win. The database enforces its own limits even if a query slips through. Save as engine.py and run it.
"""A small policy engine for actions, and a database that enforces its own limits."""
import sqlite3
POLICY = {"version": "2026-11-1", "rules": [
{"id": "P1", "effect": "allow", "tool": "query_orders"},
{"id": "P2", "effect": "allow", "tool": "refund", "max_amount": 50},
{"id": "P3", "effect": "ask", "tool": "refund", "max_amount": 500},
{"id": "P4", "effect": "deny", "tool": "refund", "when": {"account": "frozen"}},
]}
RANK = {"deny": 3, "ask": 2, "allow": 1}
def decide(policy, request):
try:
matched = []
for rule in policy["rules"]:
if rule["tool"] != request["tool"]:
continue
if "max_amount" in rule and not 0 < request["amount"] <= rule["max_amount"]:
continue
if any(request[k] != v for k, v in rule.get("when", {}).items()):
continue
matched.append(rule)
if not matched:
return "deny", "no rule allows it"
strongest = [r for r in matched if r["effect"] == "deny"]
if strongest:
return "deny", strongest[0]["id"]
# Among permissions, the least restrictive matching rule applies.
best = min(matched, key=lambda r: RANK[r["effect"]])
return best["effect"], best["id"]
except (KeyError, TypeError) as error: # unreadable request or policy
return "deny", f"policy error: {type(error).__name__} {error}"
def database():
db = sqlite3.connect(":memory:")
db.executescript("""CREATE TABLE orders(id INTEGER, status TEXT, card TEXT);
INSERT INTO orders VALUES (1,'shipped','4111111111111111');
CREATE TABLE staff(name TEXT);""")
def authorize(action, first, second, *_):
if action == sqlite3.SQLITE_SELECT:
return sqlite3.SQLITE_OK
if action == sqlite3.SQLITE_READ and first == "orders":
return sqlite3.SQLITE_IGNORE if second == "card" else sqlite3.SQLITE_OK
if action == sqlite3.SQLITE_FUNCTION and second in {"count", "upper"}:
return sqlite3.SQLITE_OK
return sqlite3.SQLITE_DENY
db.executemany("INSERT INTO orders VALUES (?,?,?)",
[(n, "shipped", "-") for n in range(2, 400)])
db.set_authorizer(authorize)
db.set_progress_handler(lambda: 1, 100_000) # stop work after a fixed budget
return db
def query(db, sql):
try:
return db.execute(sql).fetchmany(5)
except (sqlite3.Error, sqlite3.Warning) as error:
return f"refused: {error}"
if __name__ == "__main__":
base = {"tool": "refund", "amount": 20, "account": "open"}
for name, change in [("small refund", {}), ("larger", {"amount": 200}),
("too large", {"amount": 900}), ("negative", {"amount": -20}),
("frozen account", {"account": "frozen"}),
("unknown tool", {"tool": "delete_user"}),
("amount as text", {"amount": "20"})]:
print(f"{name:<16}{decide(POLICY, {**base, **change})}")
print(f"{'broken policy':<16}{decide({}, base)}")
db = database()
print()
for sql in ["SELECT id, status, card FROM orders WHERE id = 1",
"SELECT name FROM staff",
"DELETE FROM orders",
"SELECT 1; DROP TABLE orders",
"ATTACH DATABASE 'x.db' AS x",
"SELECT count(*) FROM orders a, orders b, orders c"]:
print(f"{sql[:44]:<46}{query(db, sql)}")
Output:
small refund ('allow', 'P2')
larger ('ask', 'P3')
too large ('deny', 'no rule allows it')
negative ('deny', 'no rule allows it')
frozen account ('deny', 'P4')
unknown tool ('deny', 'no rule allows it')
amount as text ('deny', "policy error: TypeError '<' not supported between instances of 'int' and 'str'")
broken policy ('deny', "policy error: KeyError 'rules'")
SELECT id, status, card FROM orders WHERE id [(1, 'shipped', None)]
SELECT name FROM staff refused: access to staff.name is prohibited
DELETE FROM orders refused: not authorized
SELECT 1; DROP TABLE orders refused: You can only execute one statement at a time.
ATTACH DATABASE 'x.db' AS x refused: not authorized
SELECT count(*) FROM orders a, orders b, ord refused: interrupted
What to notice
- Anything no rule allows is denied, including a negative amount and an unknown tool.
- A frozen account is denied even though the amount would otherwise be allowed.
- A broken policy or a wrong type produced a denial, not a crash that skips the check.
- The database hid the card column, refused other tables and changes, and interrupted an expensive query.
The engine trusts that the request's facts are true, so take them from verified sources. It also assumes validated types: Python treats True as 1, so a Boolean amount would pass these rules unless a schema rejects it first. Use whole minor units or exact decimals for money.
Write rules that stay correct
- Default deny, explicit deny wins, and document how overlapping permissions combine
- Test each rule with a permitted case, a refused case and the exact boundary
- Version rules; record the version with every decision
- Review changes like code, with a second person for sensitive rules
- Run new rules in report-only mode before enforcing
- Make a failed load keep the last good rules or deny, never allow all
Test rules like code
import pytest
from engine import POLICY, decide
@pytest.mark.parametrize("amount, effect", [
(1, "allow"), (50, "allow"), (51, "ask"), (500, "ask"), (501, "deny"), (0, "deny")])
def test_refund_boundaries(amount, effect):
request = {"tool": "refund", "amount": amount, "account": "open"}
assert decide(POLICY, request)[0] == effect
Save this as test_engine.py beside engine.py, run pip install pytest, then python -m pytest test_engine.py. All six boundary cases passed here with pytest 9.1.1.
Keep a set of recorded real requests, with personal data removed, and replay them against a proposed rule change. Show reviewers which decisions would differ. A change that flips many outcomes unexpectedly should not be released.
Guard the results too
| Check on a result | Reason |
|---|---|
| Size and row count | Prevent context flooding and bulk disclosure |
| Expected fields and types | Detect a changed or misbehaving service |
| Permitted data only | Catch a filter that failed upstream |
| Trust label | Mark text that outsiders can write |
| Error text cleaned | Keep secrets and internals out of context |
Safe database access
| Approach | Safety | Flexibility |
|---|---|---|
| Named operations with parameters | Highest | Limited to what you define |
| Query builder over approved fields | High if the builder is strict | Moderate |
| Model-written SQL against restricted views | Depends on database enforcement | High |
| Model-written SQL with broad rights | Unacceptable | Unlimited |
If a model writes queries: connect with a read-only role that sees only approved views, enforce row rules from the user's identity, set time, row and cost limits, use a replica, and log the query. SQLite offers an authorizer callback; server databases have roles, grants and row security. Do not rely on searching the query text for words such as "delete".
Safe code execution
- Run in a disposable sandbox with no secrets and no network unless listed.
- Limit processor time, memory, disk, processes and output.
- Copy in only the files the task may read; check what comes out.
- Never evaluate model text inside your own application process.
Restricting language features inside the same process is hard to get right. Isolate the process instead; see Code Execution and Sandboxing.
Long-running and autonomous agents
| Limit | Protects against | On reaching it |
|---|---|---|
| Steps and tool calls | Loops | Stop and report progress |
| Wall-clock time | Stuck or stale tasks | Pause for review |
| Spend | Runaway cost | Stop; require a new budget |
| Changes made | Gradual large effects | Ask a person |
| Repeated failures | Hammering a system | Back off, then stop |
| Age of approval or token | Acting on old consent | Re-authorize |
Check limits outside the agent loop, so a confused loop cannot skip them. Re-evaluate policy when a task resumes, because rights, prices and records may have changed. Provide pause and cancel that also reach queued work and sub-agents. See Agent Decisions: Confidence, Stopping, Loops and Budgets and Event-Driven and Background Agents.
Runtime policy architecture
| Placement | Advantage | Risk |
|---|---|---|
| Library inside the agent | Simple and fast | Can be skipped or changed with the agent |
| Gateway in front of tools | One consistent point | Direct paths around it; single point of failure |
| Inside each tool service | Cannot be bypassed by callers | Rules may drift between services |
| Sidecar or local engine | Fast with shared rules | Distribution and version control |
Many systems combine a gateway for common rules with checks in each service for record-level rights. Close direct routes to tools, or the gateway protects nothing. Emerging work such as the OWASP Agent Control Standard aims to describe runtime hooks and controls across frameworks.
Check at the moment of effect
Facts can change between decision and action: an account is frozen just after approval. Bind the decision to the record version and let the target apply the change only if that version still matches. For limits on totals, reserve and update in one transaction.
UPDATE accounts
SET refunded_today = refunded_today + :amount, version = version + 1
WHERE id = :id AND version = :seen_version AND status = 'open'
AND refunded_today + :amount <= :daily_limit;
-- exactly one changed row means the reservation succeeded
This statement is a sketch and was not part of the run above. Pair it with an idempotency key when calling an external payment system.
Fail closed
| Failure | Safe response |
|---|---|
| Decision point times out | Deny or hold the action |
| Required fact is missing | Deny and say which fact |
| Unknown tool or parameter | Deny |
| Hook raises an error | Verify the framework blocks; wrap it if it does not |
| Decision cannot be recorded | Hold actions that require a record |
Test failure by actually stopping the service in a test environment. Keep any emergency override narrow, approved, logged and automatically expiring.
Tell the agent about refusals
Return a clear, structured refusal with a reason the agent may share, such as "above automatic limit; approval available". Count repeated attempts; do not let an agent probe for a value that passes. Avoid returning details that help it work around a rule.
Worked design: supplier payments
An agent prepares supplier payments. It has no tool that moves money. It can create a draft, and the policy point allows drafts only for approved suppliers, matching an open invoice, within the buyer's limit. A person releases the draft in the finance system, which repeats its own checks. A changed bank account makes the draft ineligible until the existing verification process completes. An instruction hidden in an invoice can still cause a wrong draft, but it cannot add a supplier, change an account or release funds.
Notice where the limits live: in the finance system and the policy point. The agent's instructions explain the process, so that it proposes sensible drafts, and nothing depends on it obeying them.
Exceptions and overrides
Real work produces cases the rules did not foresee. Handle them openly, or people will build a path around the control.
- An exception names the rule, the exact scope, the reason, the approver and an end time.
- It is applied by the policy system, not by editing the agent or switching checks off.
- Hard denials, such as actions the organization never permits, have no exception path.
- Every use is recorded and reviewed, and repeated exceptions lead to a rule change.
Measures to watch
- Decisions by rule: allowed, asked and denied, with sudden changes.
- Denials caused by errors or missing facts, which point to a broken source.
- Rules that never match, which may be dead or hiding a gap.
- Actions in target systems that have no matching decision record.
- Time added per decision, and timeouts.
Common mistakes
| Mistake | Better practice |
|---|---|
| Limits only in the prompt | Enforce in code and in the target |
| Allow unless a rule denies | Deny unless a rule allows |
| Facts supplied by the model | Fetch them from trusted sources |
| Blocking SQL words by text search | Database roles, views and limits |
| Check once at task start | Check each action and on resume |
| Errors fall through to execution | Deny on error and test it |
Checklist
- Every consequential tool has an enforcement point
- Rules deny by default and have boundary tests
- Targets enforce their own rights and limits
- Long tasks have budgets, pause and cancel
- Failure of each dependency has been rehearsed
Frequently asked questions
Do I need a policy language?
A few rules can live in well-tested code. A policy engine helps when rules are shared, change often or need independent review.
Can a model write the policy?
It can draft rules for people to review and test. The running agent must not be able to change what limits it.
Is a read-only connection enough for model-written SQL?
No. Reading can expose data and exhaust resources, so restrict rows and columns and set limits too.
What happens to work already queued when policy changes?
Evaluate it again at execution, so the new rule applies, and tell owners about tasks that can no longer run.
References and further reading
- Open Policy Agent documentation
- Cedar policy language
- SQLite authorizer callbacks
- OWASP Agent Control Standard
- OWASP authorization cheat sheet
Next steps
PII Redaction and Data Leakage Prevention
Control where personal data may go.
Secure Agent Reference Architecture
See where policy sits in the whole.
Agent Testing: Unit to End-to-End
Test rules and behavior.