{
  "markdown": "# Guardrail\n<!-- mcp-name: io.github.rudimentall1/agent-guardrail -->\n[![agent-guardrail MCP server](https://glama.ai/mcp/servers/rudimentall1/agent-guardrail/badges/card.svg)](https://glama.ai/mcp/servers/rudimentall1/agent-guardrail)\n\n📄 [Read the white paper](docs/whitepaper.pdf)\n\n**A policy firewall for AI agent tool calls.**\n\nYour agent wants to run a shell command, send an email, or move money.\nGuardrail checks that request against rules you wrote, before it happens,\nand either lets it through, asks a human, or blocks it — with a plain-\nEnglish reason every time.\n\n## 60-second quickstart\n\n```bash\ngit clone <this repo> && cd agent-guardrail\npip install -r requirements.txt\n\npython3 cli.py check --agent trading-agent-001 --tool wallet.transfer \\\n  --args '{\"amount\": 9999, \"to\": \"0xabc\"}'\n```\n\nOr `pip install guardrail-mcp` gives you a `guardrail`\ncommand directly — same output, no repo checkout required (falls back to\nthe policy bundled in the package if you don't point `--policy` at your\nown file):\n\n```bash\nguardrail check --agent trading-agent-001 --tool wallet.transfer \\\n  --args '{\"amount\": 9999, \"to\": \"0xabc\"}'\n```\n\n```json\n{\n  \"decision\": \"BLOCK\",\n  \"matched_rules\": [\n    {\"rule\": \"numeric_cap_exceeded\", \"severity\": \"BLOCK\",\n     \"message\": \"amount=9999.0 exceeds cap 5 for 'wallet.transfer' (unknown agent)\"}\n  ]\n}\n```\n\nThat's it — no server, no account, no API key. `policies/default.yaml` is\nthe file that decided this; open it and change the numbers to match your\nown rules.\n\n---\n\n## Why this, not another \"AI risk scoring\" tool\n\nMost \"AI agent security\" projects (including an earlier project of mine)\nlean on statistical risk scores computed from data nobody can actually\nverify at build time — wallet age, \"reputation,\" contract \"risk\" — which\neither requires paid data feeds you don't have yet, or quietly becomes\nmock data pretending to be real. Fine for prototyping, dishonest to ship.\n\nGuardrail only makes claims it can back up. Every check is a deterministic\nrule — a blocklist entry, a regex match, a numeric cap, a rate limit —\nevaluated against a policy file you write and can audit yourself, backed\nby a real, persistent audit log (SQLite) you can query. Nothing here\npretends to know something it doesn't.\n\nIt's also **not blockchain-specific**. Shell execution, email, HTTP\nrequests, file deletion, database writes, crypto transactions — same\nengine, same policy file, same rules.\n\n---\n\n## Four ways to use it\n\n### 1. CLI — for testing a policy by hand\nShown above. No setup, instant feedback while you write rules.\n\n### 2. MCP server (`mcp_server.py`) — the easy on-ramp, advisory\n\nExposes `guardrail_check`, `guardrail_record_outcome`, and\n`guardrail_agent_history` as MCP tools any MCP-compatible agent (Claude\nDesktop, Claude Code, custom MCP clients) can call.\n\n```json\n{\n  \"mcpServers\": {\n    \"guardrail\": {\n      \"command\": \"python3\",\n      \"args\": [\"/absolute/path/to/agent-guardrail/mcp_server.py\"],\n      \"env\": { \"GUARDRAIL_POLICY\": \"/absolute/path/to/agent-guardrail/policies/default.yaml\" }\n    }\n  }\n}\n```\n\nThen tell your agent (in its system prompt) to always call\n`guardrail_check` before spending money, deleting data, messaging someone\nexternally, or running code.\n\n**Be clear-eyed about its limit:** like any MCP tool, nothing stops the\ncalling model from just not invoking it. This only helps if the agent is\ninstructed to always check first — for a guarantee it can't skip, see #3.\n\n### 3. `guardrail.decorator.enforce` — the real guarantee\n\nWraps the actual Python function that performs a tool's side effect. The\ncheck runs in your code, before that function executes — the model never\ngets a chance to call the real function directly.\n\n```python\nfrom guardrail.decorator import enforce, BlockedActionError\n\n@enforce(engine, tool_name=\"send_email\")\ndef send_email(agent_id: str, to: str, subject: str, body: str):\n    ...  # only runs if the decision is ALLOW, or WARN-and-confirmed\n```\n\nUse this if you're building your own agent loop (LangChain, CrewAI, a\ncustom MCP host, a Slack bot with tool access). Run `python3\nexamples/example_agent_usage.py` to see it block a real function call.\n\n### 4. `guardrail.mcp_enforced_server.EnforcedGuardrailMCPServer` — the real guarantee, over MCP\n\nThe MCP server in #2 above is honest about being advisory: the model\ngets a `guardrail_check` tool, but nothing stops it from calling the\n*actual* tool (exposed by some other MCP server, or by the model's own\ndirect access) without checking first, or checking one thing and doing\nanother. If the model talks to your infrastructure only over MCP - no\nPython decorator possible - this is the same #3 guarantee for that case:\nthe operator registers real action executors (the code that holds real\ncredentials and performs the real side effect) as the *only* way the\nmodel can invoke that action at all.\n\n```python\nfrom guardrail.mcp_enforced_server import EnforcedGuardrailMCPServer\n\ndef do_transfer(request):\n    wallet = get_wallet_for(request.agent_id)  # real credentials, held here - never exposed to the model\n    tx_hash = wallet.transfer(to=request.arguments[\"to\"], amount=request.arguments[\"amount\"])\n    return {\"tx_hash\": tx_hash}\n\nserver = EnforcedGuardrailMCPServer(policy_path=\"policies/default.yaml\")\nserver.register_action(\n    \"wallet.transfer\", \"Transfer funds from the agent's wallet.\",\n    input_schema={\"type\": \"object\", \"properties\": {\"to\": {\"type\": \"string\"}, \"amount\": {\"type\": \"number\"}}, \"required\": [\"to\", \"amount\"]},\n    executor=do_transfer,\n)\nserver.serve_stdio()\n```\n\nThe model is given exactly one MCP tool named `wallet.transfer` - there\nis no separate, unguarded way to move funds through this server. A BLOCK\ndecision means `do_transfer` never runs. Both this and `enforce()` share\none implementation of \"check, maybe route WARN to a human, run only if\nnot blocked, report the real outcome back\" (`guardrail/enforcement.py`) -\nnot two independently-maintained copies of the same guarantee.\n\n---\n\n## Getting a human to actually confirm a WARN\n\n`on_warn` is the hook — Guardrail ships two ready-made implementations:\n\n**Local web UI** (`guardrail/confirmation/web_ui.py`) — a tiny built-in\nserver (stdlib only, no Flask) with Approve/Reject buttons. The wrapped\nfunction blocks until someone clicks one, or times out (fails **closed** —\ntimeout means reject, not \"allow by default\").\n\n```python\nfrom guardrail.confirmation.web_ui import ConfirmationServer\n\nconfirmation = ConfirmationServer(port=8787, timeout_seconds=300)\nconfirmation.start(open_browser=True)\n\n@enforce(engine, tool_name=\"wallet.transfer\", on_warn=confirmation.request_confirmation)\ndef transfer(...): ...\n```\n\nTry it live: `python3 examples/example_web_confirmation.py`, then open\nhttp://localhost:8787.\n\n**Terminal prompt** (`guardrail/confirmation/cli_ui.py`) — for scripts and\nlocal testing where a browser is overkill:\n\n```python\nfrom guardrail.confirmation.cli_ui import cli_confirm\n\n@enforce(engine, tool_name=\"wallet.transfer\", on_warn=cli_confirm)\ndef transfer(...): ...\n```\n\nNeither is required — `on_warn` is just a function `(decision) -> bool`,\nso a Slack message, a ticket, or anything else you already use works too.\n\n---\n\n## Writing a policy\n\nPolicies are plain YAML — see `policies/default.yaml` for a real, working\nstarting point (11 confirmation-gated tools, 10 destructive-pattern\nchecks, numeric caps, domain rules, rate limits, all commented).\n\n| Rule type | What it checks |\n|---|---|\n| `blocked_tools` | Tool names that are never allowed |\n| `confirmation_required_tools` | Tool names that always produce `WARN` |\n| `argument_patterns` | Regex against the JSON-serialized call arguments — destructive shell commands, SQL, leaked credentials, path traversal, SSRF, force-pushes, regardless of which tool carries them |\n| `numeric_caps` | Per-tool numeric field caps, tighter for agents with no history |\n| `aggregate_caps` | A cap shared across *several* tools, tracked as one running total per agent — see below |\n| `domain_rules` | Allow/deny lists on a URL or email-recipient field, per tool |\n| `rate_limits` | Sliding-window call limits per (agent, tool), backed by SQLite |\n\n`numeric_caps` limits each tool independently — `wallet.transfer` capped\nat 1000/day and `wallet.approve` capped at 1000/day separately means an\nagent using both can still move 2000/day combined. `aggregate_caps`\ncloses that: every tool listed in the same group draws from one shared\nrunning total, e.g.\n\n```yaml\naggregate_caps:\n  daily_money_movement:\n    tools:\n      wallet.transfer: amount\n      wallet.approve: amount\n    window_seconds: 86400\n    max_unknown_agent: 5\n    max_known_agent: 1000\n```\n\nOnly *confirmed* spend counts toward the total: a `BLOCK`ed request never\nadds anything, and a request that's provisionally recorded (because its\nown check passed) is refunded if the real action later turns out not to\nhave succeeded — `engine.record_outcome(request_id, \"error\")`, called\nautomatically by both `enforce()` and the enforced MCP server (they\nshare one implementation of this, `guardrail/enforcement.py`) when the\nreal executor raises, or when a `WARN` a human rejects results in a\n`BlockedActionError`. Real enforcement of this therefore has the same\ncaveat as everything else that depends on `record_outcome` being called:\nit works fully under `enforce()` and the enforced MCP server (see\nbelow); under the *advisory-only* MCP server (#2 above), a\nprovisionally-recorded amount just stays recorded, since nothing ever\nreports back whether the action actually happened. See\n`guardrail/storage/aggregate_spend.py`'s module docstring for the full\npicture.\n\nNo code changes needed to adjust any of this — edit the YAML, restart the\nprocess (or the MCP server).\n\n---\n\n## Running the tests\n\n```bash\npip install -r requirements.txt\nPYTHONPATH=. python3 -m unittest discover -s tests -v\n```\n\n134 tests: rule evaluation, the full engine pipeline (real SQLite-backed\nrate limiting, aggregate spend tracking, and audit persistence), the\n`enforce` decorator and the enforced MCP server (both proving a `BLOCK`\ngenuinely prevents the real action from running, sharing one\nimplementation of that guarantee), the advisory MCP server's JSON-RPC\nhandling, the confirmation web UI over real HTTP requests against a\nlive server, and a dedicated suite that checks the *shipped*\n`policies/default.yaml` — not just synthetic test policies — actually\ncatches what it claims to.\n\n---\n\n## What's honestly still missing\n\n- **Single-process SQLite by default.** Fine for one agent process; for\n  multiple replicas sharing rate limits/audit history, point every\n  process at the same file on shared storage, or swap in a real database\n  (the storage classes are small and easy to re-target).\n- **Secrets/PII redaction in the audit log is on by default.**\n  `AuditLog` redacts values whose key looks sensitive (`password`,\n  `api_key`, `authorization`, ...) and a couple of high-confidence value\n  shapes (PEM private key blocks, JWT-shaped strings) regardless of key\n  name, recursing into nested dicts/lists - see\n  `guardrail/storage/redaction.py` for exactly what is and isn't caught,\n  and why general-purpose entropy heuristics were deliberately left out\n  (too many false positives on ordinary UUIDs/hashes). Pass\n  `AuditLog(redact=False)` to store arguments as-submitted, or\n  `extra_sensitive_keys={...}` to redact additional field names specific\n  to your tools.\n- **The default policy is a reasonable starting point, not a complete\n  threat model.** It catches well-known destructive shell/SQL patterns\n  and obvious credential formats — extend `argument_patterns` for\n  whatever your agents actually touch.\n- **The confirmation web UI has no auth.** It binds to `127.0.0.1` by\n  design (not exposed on the network), but anyone with local access to\n  that port can approve/reject. Fine for a single developer's machine;\n  put it behind your own auth if multiple people share the host.\n\nNone of these are mocked or faked — they're just not built yet, and\nthey're the honest next steps if you adopt this.\n\n---\n\n## Publishing this / getting people to actually use it\n\nSee `PUBLISHING.md` for a concrete checklist: MCP directories to submit\nto, what a listing needs, and what \"done\" looks like.\n\n---\n\n## Related projects\n\nSame author, same principle applied elsewhere:\n\n- [agentic-wallet-guardian-v3](https://github.com/rudimentall1/agentic-wallet-guardian-v3) -\n  a security decision layer for AI agents transacting on-chain. MIT,\n  112 tests.\n- [x402-attest](https://github.com/rudimentall1/x402-attest) -\n  cryptographically signed (Ed25519), independently verifiable\n  attestations for agent-to-agent payment policy decisions. Early\n  proof of concept.\n- [open-agent-attestation](https://github.com/rudimentall1/open-agent-attestation) -\n  vendor-neutral open spec (JWT+EdDSA) for signing agent policy\n  decisions, verifiable by anyone. x402-attest above uses a custom\n  format; this is the generalized version. Draft v0.1.\n\n---\n\n## Project layout\n\n```\nguardrail/\n    __main__.py            CLI implementation — also the `guardrail` console command\n    mcp_server.py            MCP stdio server — also the `guardrail-mcp-server` console command\n    core/\n        models.py               ActionRequest, RuleMatch, GuardrailDecision (stdlib only)\n        policy.py                 Policy loader (the one place PyYAML is used)\n    rules.py                    Deterministic rule evaluators\n    storage/\n        rate_limiter.py           SQLite-backed sliding-window rate limiter\n        audit.py                    SQLite-backed persistent audit log\n    engine.py                    GuardrailEngine — orchestrates rules + rate limit + audit\n    decorator.py                 enforce() — the unbypassable integration point\n    confirmation/\n        web_ui.py                    Local web UI for human approve/reject (stdlib http.server)\n        cli_ui.py                      Terminal-prompt confirmation\n    policies/default.yaml           Copy of the default policy bundled into the installed package\npolicies/default.yaml       Canonical, editable default policy (git-clone workflow)\ncli.py                      Thin shim -> guardrail/__main__.py (for `python3 cli.py`)\nmcp_server.py                Thin shim -> guardrail/mcp_server.py (for `python3 mcp_server.py`)\npyproject.toml               Package metadata — `pip install .` gives you `guardrail` + `guardrail-mcp-server`\n.github/workflows/ci.yml      Runs the test suite + policy validation + package build on every push\nexamples/\n    example_agent_usage.py       Decorator basics\n    example_web_confirmation.py    Real browser-based approve/reject, live\ntests/                       46 unit tests, all runnable with just PyYAML installed\nCONTRIBUTING.md              How to add a rule type, ground rules\nCHANGELOG.md                  Version history\nPUBLISHING.md                 How to actually get this in front of people\nlanding/index.html             Static one-page site (open directly or host on GitHub Pages)\n```\n",
  "bytes": 15040,
  "sha": "64a68d844fd5dfca1f33b3a61cb61d7d81505ce70d99c1e749c600fc15e55b50",
  "repo_slug": "rudimentall1/agent-guardrail",
  "fonte": "repo",
  "truncated": false,
  "api": "https://agentalog.com/api/listings/mcp_io_github_rudimentall1_agent_guardrail_67c7f75c/readme"
}