Metadata-Version: 2.4
Name: bastionguard
Version: 0.2.0
Summary: Runtime policy enforcement for AI agent tool calls — block, approve, or log unsafe actions before they execute.
Author-email: Rayaan Sheikh <rayaansheikh442@gmail.com>
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/rayaan2003/bastion
Project-URL: Repository, https://github.com/rayaan2003/bastion
Project-URL: Issues, https://github.com/rayaan2003/bastion/issues
Project-URL: Changelog, https://github.com/rayaan2003/bastion/blob/master/CHANGELOG.md
Keywords: ai-safety,ai-agents,llm,guardrails,langgraph,security,compliance
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: PyYAML>=6.0
Provides-Extra: claude-agent-sdk
Requires-Dist: claude-agent-sdk>=0.1; extra == "claude-agent-sdk"
Provides-Extra: langgraph
Requires-Dist: langchain-core>=0.3; extra == "langgraph"
Requires-Dist: langgraph>=0.2; extra == "langgraph"
Provides-Extra: openai-agents
Requires-Dist: openai-agents>=0.1; extra == "openai-agents"
Provides-Extra: slack
Requires-Dist: slack_sdk>=3.27; extra == "slack"
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: ruff>=0.6; extra == "dev"
Requires-Dist: mypy>=1.11; extra == "dev"
Requires-Dist: types-PyYAML>=6.0; extra == "dev"
Requires-Dist: mcp>=2.3; extra == "dev"
Dynamic: license-file

# bastion

[![PyPI](https://img.shields.io/pypi/v/bastionguard.svg)](https://pypi.org/project/bastionguard/)
[![CI](https://github.com/rayaan2003/bastion/actions/workflows/ci.yml/badge.svg)](https://github.com/rayaan2003/bastion/actions/workflows/ci.yml)
[![Python](https://img.shields.io/pypi/pyversions/bastionguard.svg)](https://pypi.org/project/bastionguard/)
[![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](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.

```mermaid
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](#in-code-the-python-sdk) | one wrapper |
| An MCP client (Claude Desktop, Cursor, Claude Code) and its MCP servers | the [MCP proxy](#no-code-the-mcp-proxy) | none, it's config |

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

```bash
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

```python
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)
```

```text
>>> 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](#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 `--`:

```json
{
  "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:

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

with a policy like:

```yaml
# ~/.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:

```text
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) |
| `--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:

```yaml
# 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] }
```

```python
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](#piisecrets-scanning) |

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.

```yaml
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.

```python
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`.

```python
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.

```python
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/`](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`.

```python
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](#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`:

```python
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`:

```json
{
  "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](#piisecrets-scanning).
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]`:

```python
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:

```python
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/`](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:

```python
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](dashboard/README.md).

## Status

Pre-1.0: the API may still change between minor versions, and changes are
listed in [CHANGELOG.md](CHANGELOG.md). Next up is in
[docs/roadmap.md](docs/roadmap.md), and how it's built is in
[docs/architecture.md](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](CONTRIBUTING.md). Report
security issues privately as described in [SECURITY.md](SECURITY.md).

## License

[Apache 2.0](LICENSE)
