Metadata-Version: 2.5
Name: rulebound
Version: 0.1.2
Summary: Rules of engagement for AI security agents: scope, autonomy levels, approvals, kill switch and a tamper-evident audit trail, enforced at the tool-call boundary.
Project-URL: Homepage, https://github.com/rajyavardhan01/rulebound
Project-URL: Repository, https://github.com/rajyavardhan01/rulebound
Project-URL: Issues, https://github.com/rajyavardhan01/rulebound/issues
Project-URL: Changelog, https://github.com/rajyavardhan01/rulebound/blob/main/CHANGELOG.md
Author: Rajyavardhan Handa
License-Expression: Apache-2.0
License-File: LICENSE
License-File: NOTICE
Keywords: ai-agents,ai-safety,audit-log,guardrails,llm-security,mcp,penetration-testing,red-team,rules-of-engagement,security
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Information Technology
Classifier: Operating System :: MacOS
Classifier: Operating System :: POSIX
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Security
Classifier: Typing :: Typed
Requires-Python: >=3.11
Provides-Extra: yaml
Requires-Dist: pyyaml>=6; extra == 'yaml'
Description-Content-Type: text/markdown

# rulebound — rules of engagement for AI security agents

[![CI](https://github.com/rajyavardhan01/rulebound/actions/workflows/ci.yml/badge.svg)](https://github.com/rajyavardhan01/rulebound/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/rulebound.svg)](https://pypi.org/project/rulebound/)
[![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/rajyavardhan01/rulebound/badge)](https://scorecard.dev/viewer/?uri=github.com/rajyavardhan01/rulebound)
[![MCP interop](https://github.com/rajyavardhan01/rulebound/actions/workflows/interop.yml/badge.svg)](https://github.com/rajyavardhan01/rulebound/actions/workflows/interop.yml)
[![License: Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](https://github.com/rajyavardhan01/rulebound/blob/main/LICENSE)
![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue.svg)
![Dependencies: none](https://img.shields.io/badge/dependencies-none-brightgreen.svg)

<p align="center"><img src="https://raw.githubusercontent.com/rajyavardhan01/rulebound/main/docs/demo.svg" alt="rulebound allowing an in-scope request, denying an out-of-scope one, escalating an exploit tool and verifying the audit chain" width="860"></p>

**Scope, autonomy levels, approvals, kill switch and a tamper-evident audit trail —
enforced at the tool-call boundary (MCP proxy, CLI wrapper, Python API). Zero dependencies.**

Status: alpha (v0.1.2).

## Why

AI agents are increasingly given security tools: scanners, HTTP clients, exploitation
frameworks, shells. Whatever plans the agent makes, the *rules of engagement* must hold:
only authorized targets, only inside the authorized window, risky actions approved by a
named human, and a reliable way to stop everything — with evidence afterwards that all of
this was true.

rulebound puts those rules in one policy file and enforces them on every action before it
runs:

```
agent ──► tool call ──► rulebound ──► allow ──► tool / MCP server / command
                            │
                            ├──► deny      (out of scope, outside window, prohibited, stopped…)
                            ├──► escalate  (needs a human: tty or file-based approval)
                            └──► audit     (hash-chained JSONL + evidence report)
```

## Quickstart

```bash
pip install rulebound
# or, from a clone (no dependencies needed):
PYTHONPATH=src python3 -m rulebound --help
```

A 30-second offline demo (real output):

```text
$ rulebound init
wrote rulebound.toml — edit the engagement, scope and action classes, then run `rulebound validate rulebound.toml`
$ rulebound validate
rulebound.toml: OK

$ rulebound check --tool http_get --args '{"url": "https://app.staging.example.com/login"}'
ALLOW  http_get  [class=recon risk=low autonomy=semi]
  targets: https://app.staging.example.com/login
  - pre-approved action class 'recon', target(s) in scope

$ rulebound check --tool curl -- -s https://unrelated.example.net/
DENY  curl  [class=recon risk=low autonomy=semi]
  targets: https://unrelated.example.net/
  - target https://unrelated.example.net/ is not in scope

$ rulebound check --tool sqlmap -- -u "https://app.example.com/api/items?id=1"
ESCALATE  sqlmap  [class=exploit risk=high autonomy=semi]
  targets: https://app.example.com/api/items?id=1
  - action class 'exploit' is not pre-approved

$ rulebound exec --tool http_get -- echo https://app.staging.example.com/health
https://app.staging.example.com/health
$ rulebound exec --tool nmap -- echo -sV 10.20.5.0/24
rulebound: blocked nmap: target 10.20.5.0/24 is excluded by scope rule '10.20.5.10'   # exit 126

$ rulebound stop --reason "target latency spike"
kill switch engaged: target latency spike
$ rulebound check --tool http_get --args '{"url": "https://app.staging.example.com/login"}'
DENY  http_get  [class=recon risk=low autonomy=semi]
  targets: https://app.staging.example.com/login
  - engagement is stopped: target latency spike
$ rulebound resume --by jane
kill switch cleared

$ rulebound audit verify
OK: 9 entries, chain intact (head seq=9 hash=b29a38064d2bfc2ded7232bb7de4b87f86cbbecf2c07a4ed7a46d3c76d7df5b1)
$ rulebound report        # Markdown evidence report (or --format json)
```

## Features

- **One policy file** (TOML, JSON or YAML) for the engagement: who authorized it, the
  window, the environment, the scope, action classes and risk, approvals, limits, stop
  conditions, hooks and audit settings. `rulebound validate` reports errors with paths.
- **Scope** — CIDRs (IPv4/IPv6), IPs, hosts with optional port, `*.` wildcards (subdomains
  only), URL prefixes; exclusions always win, on any overlap (scanning a /24 that contains
  an excluded host is denied). Hostnames are never resolved.
- **Graduated autonomy** — `supervised` (every action approved), `semi` (pre-approved
  classes run, others escalate, critical always escalates), `autonomous` (only honored in
  an `isolated` environment). Unknown actions never run unattended.
- **Approvals** — on the controlling terminal (works under MCP stdio) or through files
  (`rulebound pending`, `approve <id>`, `reject <id>`), with named approvers and timeouts.
- **Enforcement points**
  - `rulebound mcp-proxy -- <server command>`: wraps any MCP stdio server; blocked
    `tools/call` requests are answered with an error result and never reach the server.
  - `rulebound exec -- <command>`: authorizes a command line, runs it without a shell, and
    terminates it if the engagement stops.
  - Python API: `Guard.authorize()`, `Guard.run()`, `@guard.wrap("tool")`.
  - `rulebound check`: dry run for CI, tests and policy development.
- **Stop conditions** — kill switch file shared by every process, `stop` / `resume`,
  health checks (status and latency) that suspend the engagement, a breaker that trips after
  repeated denials, and `on_stop` hooks for restore/notify.
- **Rate limits** — global and per action class, persisted through the audit log so they
  hold across separate processes.
- **Tamper-evident audit trail** — append-only JSON Lines, SHA-256 hash chain (or
  HMAC-SHA-256 with a key), redaction of secrets, `audit verify` and `audit head`.
- **Evidence report** — engagement metadata, policy hash, chain status, decisions by
  verdict/class/risk, targets touched, blocked out-of-scope attempts, escalations with
  approver and latency, stop events, operational metrics.

## Usage

### Wrap an MCP server

Point your MCP client at rulebound instead of the server, and put the real server command
after `--` (see [`examples/mcp-client-config.json`](https://github.com/rajyavardhan01/rulebound/blob/main/examples/mcp-client-config.json)):

```json
{
  "mcpServers": {
    "security-tools": {
      "command": "rulebound",
      "args": ["mcp-proxy", "--policy", "/absolute/path/to/policy.toml", "--",
               "python3", "-m", "my_security_tools_server"]
    }
  }
}
```

Each `tools/call` is classified by tool name, its arguments are scanned for targets, and the
call is allowed, denied or escalated. The proxy also records `initialize`, the tool list
(flagging tools that match no action class) and session start/stop.

The server runs in its own process group. When the client disconnects, or the proxy receives
SIGINT or SIGTERM, the whole group is stopped (SIGTERM, then SIGKILL), so wrappers such as
`npx` can't leave the real server running. Set `RULEBOUND_MCP_SHUTDOWN_GRACE` (default `5`
seconds) to control how long each step waits.

### Guard a command

```bash
rulebound exec --policy policy.toml -- nmap -sV 10.20.1.0/24
rulebound exec --policy policy.toml --tool web_scan -- nuclei -u https://web.staging.example.com
```

The action name is the command's basename unless `--tool` is given. Exit status is the
command's own, `126` when blocked, `127` when not found.

### Guard Python tools

```python
from rulebound import ActionBlocked, Guard

guard = Guard.from_file("policy.toml")

@guard.wrap("http_get")
def http_get(url: str) -> str:
    ...

try:
    http_get(url="https://unrelated.example.net/")
except ActionBlocked as exc:
    print(exc.decision.reasons)   # ['target https://unrelated.example.net/ is not in scope']
```

See [`examples/python_agent.py`](https://github.com/rajyavardhan01/rulebound/blob/main/examples/python_agent.py).

### Approvals in file mode

```bash
rulebound pending --policy policy.toml
rulebound approve 3f9c2a1b7e44 --policy policy.toml --by jane --note "change window confirmed"
rulebound reject  3f9c2a1b7e44 --policy policy.toml --by jane
```

### CLI reference

| Command | Purpose |
|---|---|
| `init [PATH]` | write an example policy |
| `validate [POLICY]` | validate a policy (exit 2 on errors) |
| `check --tool T [--args JSON \| -- ARGV…]` | dry-run decision (exit 0 allow, 1 deny, 3 escalate) |
| `exec [--tool T] -- CMD…` | authorize and run a command |
| `mcp-proxy -- SERVER_CMD…` | enforce the policy on an MCP stdio server |
| `pending`, `approve ID`, `reject ID` | file-mode approvals |
| `stop [--reason]`, `resume --by NAME` | kill switch |
| `start`, `end` | record the engagement lifecycle and run hooks |
| `health`, `watch` | probe health checks once / continuously (trips the kill switch) |
| `audit verify [PATH]`, `audit head [PATH]` | verify the hash chain / print the head for anchoring |
| `report [PATH] [--format md\|json] [-o FILE]` | engagement evidence report |

All commands take `--policy/-p` (default `rulebound.toml`). The full policy schema and the
decision order are documented in [`docs/policy.md`](https://github.com/rajyavardhan01/rulebound/blob/main/docs/policy.md).

## Interoperability

The MCP proxy is tested end to end against a real, independently developed MCP server,
[chrome-devtools-mcp](https://github.com/ChromeDevTools/chrome-devtools-mcp) 0.20.2 (29
tools), in the [MCP interop workflow](https://github.com/rajyavardhan01/rulebound/blob/main/.github/workflows/interop.yml). The test checks that:

- the handshake and tool list pass through unchanged;
- an in-scope `new_page` call reaches the server;
- an out-of-scope call is blocked and never reaches the server;
- a tool outside the pre-approved classes is escalated and rejected;
- the audit chain verifies afterwards.

It has also been checked by hand with a production AI-agent CLI as the MCP client, wrapping
the same server through `rulebound mcp-proxy`. The agent's in-scope `new_page` call
succeeded, its out-of-scope call came back as `Blocked by rulebound: target
https://example.org/ is not in scope`, and the audit log recorded the client's `initialize`
handshake and both decisions with the chain intact.

To run the automated check yourself (needs Node.js and Chrome):

```bash
python tests/interop/mcp_server_interop.py -- \
  npx -y chrome-devtools-mcp@0.20.2 --headless --isolated --no-usage-statistics
```

## Output formats

- **Audit log** — one JSON object per line: `seq`, `ts` (UTC), `engagement_id`, `event`,
  `policy_sha256`, event fields (`tool`, `action_class`, `risk`, `targets`, `verdict`,
  `reasons`, `codes`, redacted `args`, `args_sha256`, `approver`, …), `prev_hash`, `alg`,
  `hash`.
- **Report** — Markdown (default) or JSON.
- **`check --format json`** — the decision object.

## CI integration

`rulebound check` is useful in CI to test a policy against the actions an agent is expected
to take:

```bash
rulebound validate policy.toml
rulebound check -p policy.toml --no-audit --tool http_get --args '{"url": "https://app.staging.example.com/"}'
! rulebound check -p policy.toml --no-audit --tool http_get --args '{"url": "https://unrelated.example.net/"}'
```

## Methodology

rulebound implements the safety-constrained autonomy, measurement and governance layer
(§4–§5, Tables 3–4) of:

> R. Handa, "Automating Cyber Offense Simulations with Machine Learning: Advancements in
> AI-Augmented Penetration Testing," *Computer Fraud and Security*, 2025(2), 1944–1951.
> doi:[10.52710/cfs.831](https://doi.org/10.52710/cfs.831)

[`docs/methodology.md`](https://github.com/rajyavardhan01/rulebound/blob/main/docs/methodology.md) maps each feature to the corresponding section
and lists the limits of the approach. rulebound contains no offensive capability; it only
governs and audits actions taken by other tools.

**Limits, in short:** target extraction is heuristic (false positives fail safe;
`require_target` escalates actions with no recognizable target); rulebound is a guardrail,
not a sandbox — run agents with least privilege; hostnames are not resolved.

## Roadmap

- Policy test files (expected verdicts for a list of actions) run by `rulebound test`
- Webhook / chat-ops approver
- Signed policy files and external anchoring of the audit head
- HTTP(S) forward-proxy enforcement point

## Contributing

Issues and pull requests are welcome — see [CONTRIBUTING.md](https://github.com/rajyavardhan01/rulebound/blob/main/CONTRIBUTING.md). Please
report security issues privately as described in [SECURITY.md](https://github.com/rajyavardhan01/rulebound/blob/main/SECURITY.md).

## License

Apache-2.0 — see [LICENSE](https://github.com/rajyavardhan01/rulebound/blob/main/LICENSE) and [NOTICE](https://github.com/rajyavardhan01/rulebound/blob/main/NOTICE).

## Citation

If you use rulebound, please cite it (see [CITATION.cff](https://github.com/rajyavardhan01/rulebound/blob/main/CITATION.cff)) and the paper
above.
