Skip to main content Switch to mobile version raven-shield 1.0.2 Deterministic, fail-closed runtime policy gateway and security guardrails for LLM tool calling
pip install raven-shield Copy PIP instructions
Deterministic, fail-closed runtime policy gateway and security guardrails for LLM tool calling.
raven-shield is a lightweight, zero-heavyweight-dependency Python SDK extracted from the RAVEN automated AI red-teaming framework. It acts as the final runtime defense layer for agentic systems, stopping prompt injection, excessive agency (OWASP LLM08), IDOR, and parameter smuggling before untrusted tool calls can execute.
When an LLM agent is jailbroken or injected via adversarial prompts, indirect RAG poisoning, or untrusted user input, prompt-based guardrails fail. raven-shield enforces deterministic mathematical and cryptographic invariants at runtime:
Fail-Closed by Default: Unknown tools or undeclared capabilities are blocked immediately.
Cross-Field Context Claims: Validates arguments against verified session claims (e.g. arguments.customer_id == context.user_id) to prevent Confused Deputy and IDOR attacks.
Parameter Bounds & Schema Invariants: Restricts financial parameters (e.g. amount <= 100.0, amount > 0), string regexes, and allowed roles.
Human Approval Escalation: Distinguishes between fatal policy violations and high-value actions requiring explicit human approval (ApprovalRequiredError).
Dynamic Hot-Reloading: Automatically reloads updated policies compiled by RAVEN without restarting your services.
Framework Native: Plug-and-play integrations for FastAPI, Starlette, LangChain, LangGraph, and OpenTelemetry.
Install core raven-shield (only requires pyyaml):
pip install raven-shield Optional Extras
Install framework-specific extras as needed:
# FastAPI / Starlette middleware pip install "raven-shield[fastapi]" # LangChain & LangGraph agent tool interceptors pip install "raven-shield[langchain]" # OpenTelemetry distributed security tracing pip install "raven-shield[opentelemetry]" # All integrations pip install "raven-shield[all]" 📋 Policy Definition (raven-policy.yaml)
Policies can be compiled automatically by RAVEN's red-teaming engine or authored by hand in YAML or JSON:
version: "hardened-gateway-v1" description: "RAVEN runtime enforcement policy for customer operations." fail_closed: true tools: issue_refund: description: "Issue refund to customer wallet or payment method." conditions: - "verified_order_id_present" - "verified_user_present" - "amount_below_threshold" - "claims_match:customer_id==user_id" high_value_action: "human_approval_required" amount_threshold: 100.0 context_claims: customer_id: "user_id" on_violation: "deny_and_log" lookup_order: description: "Look up order details." conditions: - "verified_order_id_present" - "claims_match:customer_id==user_id" context_claims: customer_id: "user_id" on_violation: "deny_and_log" 🛠️ Integration Recipes
Recipe 1: Standalone Python Policy Gateway
Instantiate the gateway directly from a YAML file or string, evaluate calls, and register custom validation conditions:
from raven_shield import PolicyGateway, SecurityContext # Load policy directly from file gateway = PolicyGateway.from_yaml("raven-policy.yaml") # Context represents authenticated identity (e.g., from your auth session) context = SecurityContext( user_id="cust_42", verified_user=True, verified_order_id=True, claims={"user_id": "cust_42", "role": "customer"}, ) # 1. Authorize benign request decision = gateway.authorize( tool="lookup_order", arguments={"order_id": "ORD-999", "customer_id": "cust_42"}, context=context, ) if decision.allowed: print("Execution authorized!") # 2. Prevent IDOR (model manipulated to access another customer's order) idor_decision = gateway.authorize( tool="lookup_order", arguments={"order_id": "ORD-999", "customer_id": "victim_user"}, context=context, ) assert not idor_decision.allowed print(f"Blocked IDOR attempt: {idor_decision.reason}") # Output: Blocked IDOR attempt: context_claims_mismatch:customer_id(victim_user)!=user_id(cust_42) # 3. Dynamic Hot-Reloading gateway.start_auto_reload(interval_seconds=2.0) Recipe 2: Python Function Decorators (@gateway.protect)
Decorate your sync or async tool functions. raven-shield intercepts calls before execution:
@gateway.protect(tool="lookup_order") async def async_lookup_order(customer_id: str, order_id: str): return await db.fetch_order(order_id) Recipe 3: FastAPI & Starlette Middleware
Automatically extract claims from incoming JWT Bearer tokens or security headers, bind them to the asynchronous execution context, and reject policy violations with HTTP 403:
from fastapi import FastAPI, Depends from raven_shield import PolicyGateway, SecurityContext, get_current_context from raven_shield.integrations.fastapi import RavenShieldMiddleware app = FastAPI(title="Secure Agent Service") gateway = PolicyGateway.from_yaml("raven-policy.yaml") # Attach middleware: extracts JWT claims & headers and binds to security_context app.add_middleware( RavenShieldMiddleware, gateway=gateway, exclude_paths=["/docs", "/openapi.json", "/healthz"], enforce_routes=True, # Automatically return HTTP 403 on PolicyViolationError ) @app.post("/api/refund") @gateway.protect(tool="issue_refund") async def handle_refund(payload: dict): # JWT Bearer token claims are already validated in context! ctx: SecurityContext = get_current_context() return {"status": "processed", "customer": ctx.user_id, "amount": payload["amount"]} When an attacker passes an invalid refund or mismatched customer ID, RavenShieldMiddleware immediately returns:
{ "error": "policy_violation", "detail": "Policy violation on 'issue_refund': context_claims_mismatch", "tool": "issue_refund", "reason": "context_claims_mismatch:customer_id!=user_id", "violations": ["context_claims_mismatch"] } Recipe 4: LangChain & LangGraph Tool Interceptors
Drop RavenShieldToolNode into your LangGraph StateGraph, or attach RavenShieldCallbackHandler to your LangChain agent. Any tool calls hallucinated or manipulated by the LLM are evaluated against raven-policy.yaml before execution:
LangGraph StateGraph
from langgraph.graph import StateGraph, MessagesState, START, END from raven_shield import PolicyGateway from raven_shield.integrations.langchain import RavenShieldToolNode gateway = PolicyGateway.from_yaml("raven-policy.yaml") # Wrap your tools in RavenShieldToolNode tool_node = RavenShieldToolNode( tools=[issue_refund, lookup_order], gateway=gateway, on_violation="return_message", # Returns error message to LLM to self-correct ) workflow = StateGraph(MessagesState) workflow.add_node("agent", call_model) workflow.add_node("tools", tool_node) workflow.add_edge(START, "agent") # ... app = workflow.compile() LangChain Callback Interceptor
from langchain.agents import create_tool_calling_agent from raven_shield import PolicyGateway from raven_shield.integrations.langchain import RavenShieldCallbackHandler gateway = PolicyGateway.from_yaml("raven-policy.yaml") interceptor = RavenShieldCallbackHandler(gateway=gateway) # Attach to agent executor result = agent_executor.invoke( {"input": "Transfer $1,000 to account X"}, config={"callbacks": [interceptor]}, ) Recipe 5: OpenTelemetry Distributed Security Tracing
Enrich your active OpenTelemetry spans with security policy decisions, violation details, and audit events:
You can register custom deterministic validators dynamically:
def check_business_hours(arguments, context, tool_policy) -> tuple[bool, str]: if not is_market_open(): return False, "market_closed" return True, "allowed" gateway.register_condition("business_hours_only", check_business_hours) 🛡️ Security Architecture
┌───────────────────────────────┐ │ Untrusted LLM Tool Call │ └───────────────┬───────────────┘ │ ▼ ┌─────────────────────────────┐ │ raven-shield Gatekeeper │ └──────────────┬──────────────┘ │ ┌───────────────────────┴───────────────────────┐ │ │ [Fail Conditions] [Pass Conditions] │ │ ▼ ▼ ┌──────────────────────────┐ ┌───────────────────────────┐ │ • Disallowed Tool │ │ • Cryptographic Claims │ │ • Parameter Smuggling │ │ • Verified Parameters │ │ • Unapproved Threshold │ │ • In-Bounds Arguments │ │ • Confused Deputy IDOR │ └─────────────┬─────────────┘ └─────────┬────────────────┘ │ │ ▼ ▼ ┌───────────────────────────┐ ┌──────────────────────────┐ │ Safe Tool Implementation │ │ Raise / HTTP 403 / Log │ └───────────────────────────┘ │ • Telemetry Audit Event │ │ • OpenTelemetry Span Err│ └──────────────────────────┘ 📄 License
Licensed under the MIT License. Maintained by the RAVEN Frontier AI Security Team.
Released: Dec 1, 2026
Author: RAVEN Security Team
Maintainer: RAVEN Open Source Contributors
Both files in this release have provenance metadata.
View provenance details
MIT View SPDX License List
all dev fastapi langchain opentelemetry
ai-agent fastapi guardrails langchain langgraph llm-security opentelemetry owasp-llm-top-10 policy-gateway prompt-injection
Development Status 3 - Alpha
Intended Audience Developers
Information Technology
License OSI Approved :: MIT License
Programming Language Python :: 3
Software Development :: Libraries :: Python Modules
Release files for raven-shield 1.0.2
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
Built distribution (wheel)
Total release size: 59.8 kB
Release files / raven_shield-1.0.2.tar.gz
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 Dec 1, 2026.
Release files / raven_shield-1.0.2-py3-none-any.whl
Security for raven-shield 1.0.2
Both files in this release have been uploaded with provenance metadata.
With provenance raven_shield-1.0.2.tar.gz Dec 1, 2026
With provenance raven_shield-1.0.2-py3-none-any.whl Dec 1, 2026
Attestation for raven_shield-1.0.2.tar.gz
Attestation for raven_shield-1.0.2-py3-none-any.whl
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
Dec 1, 2026 2 release files Full provenance
"PyPI", "Python Package Index", and the blocks logos are registered trademarks of the Python Software Foundation.
© 2026 Python Software Foundation
Deployed from b524974











