Skip to main content

bastion

PyPI CI Python License

Your agent can call delete_customer. bastion decides whether it does.

bastion sits between an AI agent and its tools. Every tool call is checked against your policy before it runs: allowed, blocked, or held until a human approves it in Slack. Every decision lands in an audit log, with PII and secrets masked.

flowchart LR
    A[Agent] -->|tool call| B{bastion<br/>policy}
    B -->|allow| T[Tool runs]
    B -->|approve| H[Human in Slack<br/>or dashboard]
    H -->|✅| T
    H -->|❌| X
    B -->|block| X[Agent gets the reason]
    B -.->|every decision| L[(Audit log)]
  • Policies as YAML. Glob on tool names, conditions on arguments (amount over $500, recipient outside your domain, a credit card in the args), first match wins. Reviewable in a PR.
  • Human approval. A ✅ or ❌ reaction in Slack, a queue on the dashboard, or your own channel. Limit who can approve. Nobody answers, nothing runs.
  • Shadow mode. Run a new policy against real traffic and see what it would block before it blocks anything.
  • An audit trail. Every decision and outcome, linked per call, with who approved it. PII and secrets are masked before they're written.
  • A dashboard. Self-hosted audit viewer, approval queue and policy editor.

Two ways in

You have Use Code changes
A Python agent (LangGraph, OpenAI Agents SDK, Claude Agent SDK, plain functions) the SDK one wrapper
An MCP client (Claude Desktop, Cursor, Claude Code) and its MCP servers the MCP proxy none, it's config

Both use the same YAML policies, approvals and audit log.

pip install bastionguard

Python 3.10+. The only dependency is PyYAML; framework support is an extra (pip install "bastionguard[langgraph]", or openai-agents, claude-agent-sdk, slack). The package is bastionguard, the import is bastion.

In code: the Python SDK

from bastion import Action, PolicyEngine, Rule, guard
from bastion.policy import arg_exceeds

policy = PolicyEngine()
policy.add_rule(Rule("delete_*", Action.BLOCK, reason="irreversible"))
policy.add_rule(Rule(
    "refund",
    Action.APPROVE,
    condition=arg_exceeds("amount", 100),
    reason="refunds over $100 need a human",
))

refund = guard(refund, policy=policy)
delete_customer = guard(delete_customer, policy=policy)
>>> refund(order_id="ord_1", amount=40)
'refunded $40 on ord_1'
>>> refund(order_id="ord_2", amount=250)       # reviewer says no
BlockedByPolicy: Tool call 'refund' blocked by policy: approval denied (refunds over $100 need a human)
>>> delete_customer(customer_id="cus_9")
BlockedByPolicy: Tool call 'delete_customer' blocked by policy: irreversible

Framework adapters are under Frameworks.

No code: the MCP proxy

bastion mcp-proxy wraps any stdio MCP server. Point your MCP client at bastion instead of the server, and put the real server command after --:

{
  "mcpServers": {
    "filesystem": {
      "command": "bastion",
      "args": [
        "mcp-proxy", "--policy", "/Users/you/.bastion/policy.yaml",
        "--", "npx", "-y", "@modelcontextprotocol/server-filesystem", "/Users/you/notes"
      ]
    }
  }
}

That's claude_desktop_config.json for Claude Desktop, and the same shape in ~/.cursor/mcp.json for Cursor. Desktop apps often don't see your shell's PATH, so use the full path from which bastion, or skip the install with "command": "uvx" and "args": ["--from", "bastionguard", "bastion", "mcp-proxy", ...]. For Claude Code:

claude mcp add filesystem -- bastion mcp-proxy --policy ~/.bastion/policy.yaml \
  -- npx -y @modelcontextprotocol/server-filesystem ~/notes

with a policy like:

# ~/.bastion/policy.yaml
rules:
  - tool: move_file
    action: block
    reason: files stay where they are
  - tool: write_file
    action: approve          # with --approval slack, someone ✅s it first
    reason: writes need a human

The client sees the server's tools as usual. When the model calls one the policy blocks, the server never gets the call, and the model gets the reason as the tool's result:

Tool call blocked by policy: files stay where they are

Not sure what a server's tools are called? Start with shadow: true in the policy. Every call is logged to ~/.bastion/audit.jsonl with its tool name and what the policy would have done, and nothing is blocked.

Flag
--policy FILE YAML policy
--approval slack ask in Slack: --slack-channel, --slack-approver USER_ID (repeatable), $SLACK_BOT_TOKEN
--approval dashboard queue approvals on the dashboard
--dashboard-url URL send audit events there, and load the policy from it when --policy is omitted ($BASTION_DASHBOARD_API_KEY)
--audit-log FILE default ~/.bastion/audit.jsonl

Without --approval, approve rules deny: the terminal can't prompt, because stdin is the MCP connection. Everything besides tools/call (resources, prompts, sampling) passes through untouched, on both pre-2026 sessions and the stateless 2026-07-28 protocol.

Policies

A policy is an ordered list of rules. Each rule matches a tool name (glob pattern) and, optionally, a condition on the call's arguments. The first matching rule decides; if nothing matches, default_action applies (allow unless you set it).

Action Effect
allow the tool runs
block the tool doesn't run; the agent gets the reason
approve an approval handler asks a human; runs only if approved

Policies can live in YAML, so they can be reviewed without reading Python:

# policy.yaml
default_action: allow

rules:
  - name: no-deletes
    tool: "delete_*"
    action: block
    reason: irreversible

  # Allow-list by ordering: internal mail goes through, anything else needs a human.
  - tool: send_email
    action: allow
    condition: { type: arg_matches_regex, arg: to, pattern: '^[^@\s]+@yourco\.com$' }
  - tool: send_email
    action: approve
    reason: external recipient

  - tool: "*"
    action: block
    reason: arguments contain PII or credentials
    condition: { type: contains_pii, categories: [ssn_us, credit_card, aws_secret_access_key] }
from bastion import load_policy_from_yaml
policy = load_policy_from_yaml("policy.yaml")

Built-in conditions:

YAML type Python Matches when
arg_exceeds arg_exceeds(arg, threshold) the argument is a number above threshold
arg_matches_regex arg_matches_regex(arg, pattern) the argument matches pattern
any_arg_contains any_arg_contains(substrings) any argument contains one of substrings (case-insensitive)
contains_pii contains_pii(categories) any argument contains a detected PII/secret

In Python, a condition is any Callable[[dict], bool] over the arguments.

Shadow mode

Run a policy against real traffic before it's allowed to block anything. Shadow rules are evaluated and logged as would_block, would_approve or would_allow, but not enforced, and they never ask a human.

shadow: true          # the whole policy
rules:
  - tool: "send_*"
    action: approve
    shadow: true      # or a single rule inside an enforced policy

A shadow rule can't change what's enforced: evaluation moves past it to the rules behind it.

Frameworks

LangGraph — a drop-in replacement for ToolNode. A blocked call comes back as an error ToolMessage, so the agent can react instead of the graph crashing. Sync and async tools are both covered.

from bastion.integrations.langgraph import guarded_tool_node

tool_node = guarded_tool_node([search_docs, send_email], policy=policy)

OpenAI Agents SDK — wraps @function_tool tools. A blocked call returns "Tool call blocked by policy: <reason>" as the tool result. The SDK turns tool exceptions into a result string by default, so those are audited as completed; use @function_tool(failure_error_function=None) to have them raise and be audited as failed.

from bastion.integrations.openai_agents import guarded_tools

agent = Agent(name="support", tools=guarded_tools([search_docs, send_email], policy=policy))

Claude Agent SDK — SDK hooks. The PreToolUse hook sees every tool call, built-in (Bash, Write, ...) and MCP alike, including tools pre-allowed by allowed_tools and under permission_mode="bypassPermissions". A blocked call is denied with the reason; an allowed one is left to the SDK's normal permission checks. If the hook itself fails, the call is blocked.

from bastion.integrations.claude_agent_sdk import guarded_hooks

options = ClaudeAgentOptions(hooks=guarded_hooks(policy=policy))

Keep the hook's timeout (default 600s) above your approval handler's, or the SDK stops waiting before the reviewer answers.

Anything else — guard(fn, policy=...) wraps any callable, sync or async, and raises BlockedByPolicy.

Runnable versions of each are in examples/.

Approvals

approve rules call an ApprovalHandler. The default prompts in the terminal. The Slack and dashboard handlers deny if nobody answers before the timeout. Who decided is recorded on the audit event (approver): slack:U024BE7LH, console:alice, or dashboard:ui.

from bastion.approval.slack import SlackApprovalHandler

# Posts to the channel and waits for a ✅ or ❌ reaction; a ❌ wins if both
# appear. Needs a bot token with chat:write and reactions:read; no webhook
# server. Only the listed user ids can decide; leave approvers out to let
# anyone in the channel.
approvals = SlackApprovalHandler(
    token="xoxb-...",
    channel="#agent-approvals",
    approvers=["U024BE7LH", "U0G9QF9C6"],
    timeout=300,
)
guarded = guard(refund, policy=policy, approval_handler=approvals)

The dashboard provides an approval queue as well (DashboardApprovalHandler). It records where a decision was made, not who, since the dashboard has one shared login.

For your own channel, subclass ApprovalHandler:

from bastion import ApprovalDecision, ApprovalHandler, ApprovalRequest

class TeamsApprovals(ApprovalHandler):
    def request_approval(self, request: ApprovalRequest) -> ApprovalDecision:
        # request has tool_name, args, reason, call_id, session_id
        reviewer, ok = ask_teams(request)
        return ApprovalDecision(approved=ok, approver=f"teams:{reviewer}")

Audit log

Every decision is recorded. By default it's appended to bastion_audit.jsonl:

{
  "id": "5c183b31-6364-4dca-b154-599220c73ba3",
  "timestamp": 1793897709.573623,
  "session_id": "sess_7f3a",
  "tool_name": "delete_customer",
  "args": {"customer_id": "cus_9"},
  "action": "blocked",
  "reason": "irreversible",
  "call_id": "0b7e3f0c-5a1d-4a8e-9c63-2f5e1d7b9a44"
}

action is one of allowed, blocked, approved, denied, or would_* for shadow rules; approved and denied events also carry approver. Once an allowed call has run, a second event records completed (the tool returned) or failed (it raised, with the error). Every event about one call shares a call_id — the framework's own tool-call id where there is one — and the dashboard links them.

PII and secrets in args are masked in the log ("ssn [REDACTED:ssn_us]") using the scanner. Policy rules and the tool itself still get the real values. Pass AuditLogger(redact_args=False) to log args as-is.

To send events elsewhere, pass any Callable[[AuditEvent], None]:

from bastion import AuditLogger
audit = AuditLogger(session_id="run-42", sink=my_sink)
guarded = guard(refund, policy=policy, audit=audit)

PII/secrets scanning

Regex detectors for email, phone_us, ssn_us, credit_card (Luhn checked), aws_access_key_id, aws_secret_access_key, generic_api_key (OpenAI, GitHub, Slack token formats) and private_key_block. Use them as a policy condition (contains_pii, above), or directly on any text such as a model response:

from bastion import enforce_text_policy

safe = enforce_text_policy(llm_output, categories=["email", "ssn_us"], on_detect="redact")
# "contact [REDACTED:email]"

These are patterns, not a DLP classifier: they catch the common, expensive leaks and will miss things.

Dashboard

dashboard/ is a self-hosted Next.js + Postgres app with an audit log viewer, an approval queue and a policy editor. The SDK talks to it over HTTP with an API key:

from bastion.dashboard import (
    DashboardApprovalHandler,
    dashboard_audit_sink,
    load_policy_from_dashboard,
)

url, key = "https://bastion.yourco.internal", "..."
policy = load_policy_from_dashboard(url, key)
audit = AuditLogger(sink=dashboard_audit_sink(url, key))
approvals = DashboardApprovalHandler(url, key)

Audit events are sent on a background thread, so a slow or unreachable dashboard doesn't hold up tool calls. Setup and deployment: dashboard/README.md.

Status

Pre-1.0: the API may still change between minor versions, and changes are listed in CHANGELOG.md. Next up is in docs/roadmap.md, and how it's built is in docs/architecture.md.

Known limitations:

  • The dashboard has one shared login and one API key; there are no users or projects yet.
  • The MCP proxy speaks stdio, so it covers local MCP servers; remote (Streamable HTTP) servers aren't covered yet.

Contributing

Issues and PRs are welcome — see CONTRIBUTING.md. Report security issues privately as described in SECURITY.md.

License

Apache 2.0

Metadata

Release files for bastionguard 0.2.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 bastionguard 0.2.0
File Size Uploaded Provenance Actions
bastionguard-0.2.0.tar.gz 56.4 kB With provenance Details for bastionguard-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for bastionguard 0.2.0
File Interpreter ABI Platform Actions
bastionguard-0.2.0-py3-none-any.whl Python 3 none any Details for bastionguard-0.2.0-py3-none-any.whl

Total release size: 96.6 kB

Release files / bastionguard-0.2.0.tar.gz

Download URL bastionguard-0.2.0.tar.gz
Size 56.4 kB
Tags Source
SHA-256 checksum
How to use checksums
268bb187763fc0df4ca45b62d04011fbd2ac9f6cdc8936461fd4292bc71595fe
BLAKE2b-256 checksum
How to use checksums
9f9dc590e4631c8bbd2c13ab905ea991e7d32b0570a16154cebc102bf742fcec
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 6, 2026.

Transparency log

Release files / bastionguard-0.2.0-py3-none-any.whl

Download URL bastionguard-0.2.0-py3-none-any.whl
Size 40.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e321f2dc6b72340426da8c1c100617b3fc1c187c08d860df420fe3f40cb687e9
BLAKE2b-256 checksum
How to use checksums
b2f0b3d0c38a55d8394e127915c4426edbbca63dc66b2339b7910159d5a72cf0
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 6, 2026.

Transparency log

Security for bastionguard 0.2.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 bastionguard-0.2.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 6, 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.2.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