Skip to main content

guardrail-middleware

Runtime authorization for AI agent tool calls. GuardRail sits between an AI agent and its tools: every proposed action is checked against a policy before it executes — and every decision is written to a tamper-evident audit log.

An agent that can call tools can also be talked into misusing them — by a prompt injection in an email, a poisoned webpage, or its own overconfidence. GuardRail is the checkpoint that asks, deterministically and in under a millisecond: is this role allowed to do this, to this resource, with these parameters, on the say-so of this source?

pip install guardrail-middleware            # core, zero dependencies
pip install guardrail-middleware[fastapi]   # + FastAPI/Starlette middleware

Quick start — framework-agnostic

from guardrail_middleware import Guardrail

guard = Guardrail()  # built-in default policy

decision = guard.evaluate({
    "tool": "payments",
    "operation": "payment",
    "target_resource": "vendor/acme",
    "parameters": {"amount": 42000},
    "agent_role": "support",
})

decision.verdict   # Verdict.BLOCK — role 'support' may not run payments
decision.allowed   # False
decision.explanation

Works anywhere an agent proposes an action: LangChain/LangGraph tool wrappers, MCP servers, custom agent loops, job queues.

Quick start — FastAPI / Starlette middleware

from fastapi import FastAPI
from guardrail_middleware import Guardrail, AuditLog
from guardrail_middleware.fastapi import GuardrailMiddleware

app = FastAPI()
app.add_middleware(
    GuardrailMiddleware,
    guard=Guardrail(audit_log=AuditLog("audit.jsonl")),
    paths=["/tools/execute"],
)

Requests to guarded paths are read as actions. Blocked or escalated actions never reach your handler — the client gets HTTP 403 with the full decision as JSON. Allowed actions pass through with X-Guardrail-Verdict and X-Guardrail-Risk headers set.

Quick start — decorator

from guardrail_middleware.fastapi import guard_tool, GuardrailBlocked

@guard_tool(guard, tool="payments", operation="payment", agent_role="support")
def send_payment(amount: int, to: str):
    ...  # only runs if GuardRail approves

try:
    send_payment(amount=42_000, to="vendor/acme")
except GuardrailBlocked as stopped:
    print(stopped.decision.explanation)

Verdicts

Verdict Meaning
APPROVE No policy issues — execute.
APPROVE_WITH_CONDITIONS Execute only with the attached conditions (batch it, back up first, dry-run).
ESCALATE_TO_HUMAN A person must approve first (over-limit payment, untrusted source, unbounded delete).
BLOCK Never execute (injection, unauthorized role, PII exfiltration, hard money ceiling).

Priority is fail-safe: any block finding wins, then escalate, then conditions.

What it checks — 7 deterministic detectors

No LLM in the decision path: the same action under the same policy always gets the same verdict, reproducibly and fast.

  1. Injection — instruction-override / role-hijack / secret-extraction / policy-bypass patterns in untrusted content (email, webpage, tool output). Untrusted content is data, never instructions.
  2. Authorization — role × operation-class permissions (an intern role cannot delete, a support role cannot pay).
  3. Financial limits — per-class auto-approve and block thresholds, plus a hard ceiling no role can exceed; a payment with no verifiable amount escalates.
  4. Bulk operations — record-count thresholds: conditions (batch + dry-run) above the auto-approve max, escalation above the bulk ceiling.
  5. Taint / exfiltration — PII or secret fields flowing to an external destination is blocked; secrets inside tool-call parameters are blocked outright.
  6. Destructive actions — irreversible operations without a backup/confirmation marker get conditions; a delete with no target escalates.
  7. Untrusted source — money movement, deletion, or external sends triggered by email/webpage/tool-output content escalate to a human.

Policy

Every threshold lives in one policy dict — tune it without touching code, or load it from YAML:

from guardrail_middleware import Guardrail, Policy

policy = Policy.from_yaml("policy.yaml")   # see policy.example.yaml
guard = Guardrail(policy=policy)

# …or inline
guard = Guardrail(policy={"approval_limits": {"payment": {"auto_approve_max": 500}}})

Audit log

Pass an AuditLog and every decision is appended as one JSON line, hash-chained with SHA-256: each entry commits to the previous entry's hash, so editing, deleting, or reordering history breaks the chain.

from guardrail_middleware import AuditLog
AuditLog("audit.jsonl").verify()   # {'ok': True, 'entries': 128, 'broken_at': None}

Demo & tests

python examples/demo.py     # 5 scenarios, all four verdicts, audit verification
pytest                      # 18 tests: engine, detectors, middleware, decorator, audit tampering

Where this comes from

guardrail-middleware is the reusable enforcement core extracted from GuardRail — a runtime action-authorization and behavioral-safety layer for agentic AI built at Infosys Ignite EngNext 2026 (special recognition), where the full system adds multi-step plan validation, an action-passport execution gateway, and a 42-scenario adversarial red-team benchmark. This package packages the single-action checkpoint from that system so any agent stack can adopt it in minutes.

Status & honesty notes

  • v0.1.0, alpha. The API may still move.
  • Detectors are deterministic heuristics, not a proof of safety — pair them with least-privilege credentials and human review for high-impact tools.
  • Plan-level (multi-step) validation lives in the main GuardRail project, not in this package yet.

License

MIT © Niraj Sanjay Karnawat

Metadata

Release files for guardrail-middleware 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for guardrail-middleware 0.1.0
File Size Uploaded Provenance Actions
guardrail_middleware-0.1.0.tar.gz 19.6 kB With provenance Details for guardrail_middleware-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for guardrail-middleware 0.1.0
File Interpreter ABI Platform Actions
guardrail_middleware-0.1.0-py3-none-any.whl Python 3 none any Details for guardrail_middleware-0.1.0-py3-none-any.whl

Total release size: 38.4 kB

Release files / guardrail_middleware-0.1.0.tar.gz

Download URL guardrail_middleware-0.1.0.tar.gz
Size 19.6 kB
Tags Source
SHA-256 checksum
How to use checksums
d643fcd0ec67c4fed1999823755685dd607519b13f2692a0bd8761f39741d151
BLAKE2b-256 checksum
How to use checksums
6b4f8825eb6719a99efbb6f0d00d3603c8d8ad23879f497dd1311b2164e5c44f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.

Transparency log

Release files / guardrail_middleware-0.1.0-py3-none-any.whl

Download URL guardrail_middleware-0.1.0-py3-none-any.whl
Size 18.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d75810f1a362519a1534d4e954d2c72b855e95c3277d99f04c9293f0bc3a2f5d
BLAKE2b-256 checksum
How to use checksums
ad38241bee572631cc48d65b975e268b2db9ec6e874d591494b9b33f209ad38a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.

Transparency log

Security for guardrail-middleware 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for guardrail_middleware-0.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page