Agent Guardrail

io.github.rudimentall1由 GitHub 帳號 rudimentall1 發布v1.0.2更新於 Oct 24, 2026

Deterministic policy firewall for AI agent tool calls - YAML rules, not a fuzzy risk score.

已驗證STDIO僅桌面開發者工具安全與監控

概覽

AI 產生的概覽

本機 MCP 伺服器,依 YAML 原則規則檢查 AI 代理的工具呼叫,回傳放行、警告或封鎖的判定。

可以做什麼
依 YAML 原則檢查擬執行的工具呼叫,回傳判定、命中的規則與白話原因,涵蓋工具黑名單、參數正規表達式、數值上限、網域規則與速率限制。記錄動作的真實結果,讓失敗時暫計的額度被退回。從 SQLite 稽核日誌查詢某個代理的歷史呼叫。建議式 MCP 伺服器只是多種整合方式之一;Python 裝飾器與強制式 MCP 伺服器變體可讓檢查無法繞過。
適用情境
當代理可能執行不可逆動作(例如 shell 指令、寄信、HTTP 請求、刪除檔案、寫入資料庫或轉帳),而你想要可稽核的確定性規則而非風險評分時使用。最適合單一開發者電腦或你自己掌控的自訂代理迴圈。
執行需求
以本機 Python 程序執行,可從 guardrail-mcp 的 PyPI 套件或程式碼倉庫安裝。需要一個原則 YAML 檔案,透過 GUARDRAIL_POLICY 環境變數指定,或使用內附的預設原則。不需帳號或 API 金鑰。速率限制與稽核日誌使用本機 SQLite 檔案。
安裝前請注意
建議式 MCP 伺服器無法阻止模型跳過檢查或以其他方式直接呼叫真實工具;只有裝飾器或強制式伺服器才提供保證。預設原則只是起點,並非完整威脅模型。確認用網頁介面沒有身分驗證,任何能本機存取該連接埠的人都能核准或拒絕。稽核遮蔽採啟發式規則,可能漏掉敏感值。

安裝

在 SourceWeft 中

  1. 開啟 儀表板中的 Agent Guardrail,將其新增到工作區。
  2. 為需要使用其工具的對話啟用該服務。

Desktop only,透過 STDIO。 STDIO 服務會啟動本機處理程序,因此需要 SourceWeft 桌面主機。

其他 MCP 客戶端

參照 儲存庫 中的啟動說明。

README

Guardrail

[agent-guardrail MCP server]

📄 Read the white paper

Put a policy firewall between an AI agent and every irreversible action.

Your agent wants to run a shell command, send an email, or move money. Guardrail checks that request against rules you wrote, before it happens, and either lets it through, asks a human, or blocks it — with a plain- English reason every time.

60-second quickstart

bash
git clone <this repo> && cd agent-guardrailpip install -r requirements.txt
python3 cli.py check --agent trading-agent-001 --tool wallet.transfer \  --args '{"amount": 9999, "to": "0xabc"}'

Or pip install guardrail-mcp gives you a guardrail command directly — same output, no repo checkout required (falls back to the policy bundled in the package if you don't point --policy at your own file):

bash
guardrail check --agent trading-agent-001 --tool wallet.transfer \  --args '{"amount": 9999, "to": "0xabc"}'
json
{  "decision": "BLOCK",  "matched_rules": [    {"rule": "numeric_cap_exceeded", "severity": "BLOCK",     "message": "amount=9999.0 exceeds cap 5 for 'wallet.transfer' (unknown agent)"}  ]}

That's it — no server, no account, no API key. policies/default.yaml is the file that decided this; open it and change the numbers to match your own rules.


Why this, not another "AI risk scoring" tool

Most "AI agent security" projects (including an earlier project of mine) lean on statistical risk scores computed from data nobody can actually verify at build time — wallet age, "reputation," contract "risk" — which either requires paid data feeds you don't have yet, or quietly becomes mock data pretending to be real. Fine for prototyping, dishonest to ship.

Guardrail only makes claims it can back up. Every check is a deterministic rule — a blocklist entry, a regex match, a numeric cap, a rate limit — evaluated against a policy file you write and can audit yourself, backed by a real, persistent audit log (SQLite) you can query. Nothing here pretends to know something it doesn't.

It's also not blockchain-specific. Shell execution, email, HTTP requests, file deletion, database writes, crypto transactions — same engine, same policy file, same rules.


Four ways to use it

1. CLI — for testing a policy by hand

Shown above. No setup, instant feedback while you write rules.

2. MCP server (mcp_server.py) — the easy on-ramp, advisory

Exposes guardrail_check, guardrail_record_outcome, and guardrail_agent_history as MCP tools any MCP-compatible agent (Claude Desktop, Claude Code, custom MCP clients) can call.

json
{  "mcpServers": {    "guardrail": {      "command": "python3",      "args": ["/absolute/path/to/agent-guardrail/mcp_server.py"],      "env": { "GUARDRAIL_POLICY": "/absolute/path/to/agent-guardrail/policies/default.yaml" }    }  }}

Then tell your agent (in its system prompt) to always call guardrail_check before spending money, deleting data, messaging someone externally, or running code.

Be clear-eyed about its limit: like any MCP tool, nothing stops the calling model from just not invoking it. This only helps if the agent is instructed to always check first — for a guarantee it can't skip, see #3.

3. guardrail.decorator.enforce — the real guarantee

Wraps the actual Python function that performs a tool's side effect. The check runs in your code, before that function executes — the model never gets a chance to call the real function directly.

python
from guardrail.decorator import enforce, BlockedActionError
@enforce(engine, tool_name="send_email")def send_email(agent_id: str, to: str, subject: str, body: str):    ...  # only runs if the decision is ALLOW, or WARN-and-confirmed

Use this if you're building your own agent loop (LangChain, CrewAI, a custom MCP host, a Slack bot with tool access). Run python3 examples/example_agent_usage.py to see it block a real function call.

4. guardrail.mcp_enforced_server.EnforcedGuardrailMCPServer — the real guarantee, over MCP

The MCP server in #2 above is honest about being advisory: the model gets a guardrail_check tool, but nothing stops it from calling the actual tool (exposed by some other MCP server, or by the model's own direct access) without checking first, or checking one thing and doing another. If the model talks to your infrastructure only over MCP - no Python decorator possible - this is the same #3 guarantee for that case: the operator registers real action executors (the code that holds real credentials and performs the real side effect) as the only way the model can invoke that action at all.

python
from guardrail.mcp_enforced_server import EnforcedGuardrailMCPServer
def do_transfer(request):    wallet = get_wallet_for(request.agent_id)  # real credentials, held here - never exposed to the model    tx_hash = wallet.transfer(to=request.arguments["to"], amount=request.arguments["amount"])    return {"tx_hash": tx_hash}
server = EnforcedGuardrailMCPServer(policy_path="policies/default.yaml")server.register_action(    "wallet.transfer", "Transfer funds from the agent's wallet.",    input_schema={"type": "object", "properties": {"to": {"type": "string"}, "amount": {"type": "number"}}, "required": ["to", "amount"]},    executor=do_transfer,)server.serve_stdio()

The model is given exactly one MCP tool named wallet.transfer - there is no separate, unguarded way to move funds through this server. A BLOCK decision means do_transfer never runs. Both this and enforce() share one implementation of "check, maybe route WARN to a human, run only if not blocked, report the real outcome back" (guardrail/enforcement.py) - not two independently-maintained copies of the same guarantee.


Getting a human to actually confirm a WARN

on_warn is the hook — Guardrail ships two ready-made implementations:

Local web UI (guardrail/confirmation/web_ui.py) — a tiny built-in server (stdlib only, no Flask) with Approve/Reject buttons. The wrapped function blocks until someone clicks one, or times out (fails closed — timeout means reject, not "allow by default").

python
from guardrail.confirmation.web_ui import ConfirmationServer
confirmation = ConfirmationServer(port=8787, timeout_seconds=300)confirmation.start(open_browser=True)
@enforce(engine, tool_name="wallet.transfer", on_warn=confirmation.request_confirmation)def transfer(...): ...

Try it live: python3 examples/example_web_confirmation.py, then open http://localhost:8787.

Terminal prompt (guardrail/confirmation/cli_ui.py) — for scripts and local testing where a browser is overkill:

python
from guardrail.confirmation.cli_ui import cli_confirm
@enforce(engine, tool_name="wallet.transfer", on_warn=cli_confirm)def transfer(...): ...

Neither is required — on_warn is just a function (decision) -> bool, so a Slack message, a ticket, or anything else you already use works too.


Writing a policy

Policies are plain YAML — see policies/default.yaml for a real, working starting point (11 confirmation-gated tools, 10 destructive-pattern checks, numeric caps, domain rules, rate limits, all commented).

Rule typeWhat it checks
blocked_toolsTool names that are never allowed
confirmation_required_toolsTool names that always produce WARN
argument_patternsRegex against the JSON-serialized call arguments — destructive shell commands, SQL, leaked credentials, path traversal, SSRF, force-pushes, regardless of which tool carries them
numeric_capsPer-tool numeric field caps, tighter for agents with no history
aggregate_capsA cap shared across several tools, tracked as one running total per agent — see below
domain_rulesAllow/deny lists on a URL or email-recipient field, per tool
rate_limitsSliding-window call limits per (agent, tool), backed by SQLite

numeric_caps limits each tool independently — wallet.transfer capped at 1000/day and wallet.approve capped at 1000/day separately means an agent using both can still move 2000/day combined. aggregate_caps closes that: every tool listed in the same group draws from one shared running total, e.g.

yaml
aggregate_caps:  daily_money_movement:    tools:      wallet.transfer: amount      wallet.approve: amount    window_seconds: 86400    max_unknown_agent: 5    max_known_agent: 1000

Only confirmed spend counts toward the total: a BLOCKed request never adds anything, and a request that's provisionally recorded (because its own check passed) is refunded if the real action later turns out not to have succeeded — engine.record_outcome(request_id, "error"), called automatically by both enforce() and the enforced MCP server (they share one implementation of this, guardrail/enforcement.py) when the real executor raises, or when a WARN a human rejects results in a BlockedActionError. Real enforcement of this therefore has the same caveat as everything else that depends on record_outcome being called: it works fully under enforce() and the enforced MCP server (see below); under the advisory-only MCP server (#2 above), a provisionally-recorded amount just stays recorded, since nothing ever reports back whether the action actually happened. See guardrail/storage/aggregate_spend.py's module docstring for the full picture.

No code changes needed to adjust any of this — edit the YAML, restart the process (or the MCP server).


Running the tests

bash
pip install -r requirements.txtPYTHONPATH=. python3 -m unittest discover -s tests -v

134 tests: rule evaluation, the full engine pipeline (real SQLite-backed rate limiting, aggregate spend tracking, and audit persistence), the enforce decorator and the enforced MCP server (both proving a BLOCK genuinely prevents the real action from running, sharing one implementation of that guarantee), the advisory MCP server's JSON-RPC handling, the confirmation web UI over real HTTP requests against a live server, and a dedicated suite that checks the shipped policies/default.yaml — not just synthetic test policies — actually catches what it claims to.


What's honestly still missing

  • Single-process SQLite by default. Fine for one agent process; for multiple replicas sharing rate limits/audit history, point every process at the same file on shared storage, or swap in a real database (the storage classes are small and easy to re-target).
  • Secrets/PII redaction in the audit log is on by default. AuditLog redacts values whose key looks sensitive (password, api_key, authorization, ...) and a couple of high-confidence value shapes (PEM private key blocks, JWT-shaped strings) regardless of key name, recursing into nested dicts/lists - see guardrail/storage/redaction.py for exactly what is and isn't caught, and why general-purpose entropy heuristics were deliberately left out (too many false positives on ordinary UUIDs/hashes). Pass AuditLog(redact=False) to store arguments as-submitted, or extra_sensitive_keys={...} to redact additional field names specific to your tools.
  • The default policy is a reasonable starting point, not a complete threat model. It catches well-known destructive shell/SQL patterns and obvious credential formats — extend argument_patterns for whatever your agents actually touch.
  • The confirmation web UI has no auth. It binds to 127.0.0.1 by design (not exposed on the network), but anyone with local access to that port can approve/reject. Fine for a single developer's machine; put it behind your own auth if multiple people share the host.

None of these are mocked or faked — they're just not built yet, and they're the honest next steps if you adopt this.


Publishing this / getting people to actually use it

See PUBLISHING.md for a concrete checklist: MCP directories to submit to, what a listing needs, and what "done" looks like.


Related projects

Same author, same principle applied elsewhere:

  • agentic-wallet-guardian-v3 - a security decision layer for AI agents transacting on-chain. MIT, 112 tests.
  • x402-attest - cryptographically signed (Ed25519), independently verifiable attestations for agent-to-agent payment policy decisions. Early proof of concept.
  • open-agent-attestation - vendor-neutral open spec (JWT+EdDSA) for signing agent policy decisions, verifiable by anyone. x402-attest above uses a custom format; this is the generalized version. Draft v0.1.

Project layout

guardrail/    __main__.py            CLI implementation — also the `guardrail` console command    mcp_server.py            MCP stdio server — also the `guardrail-mcp-server` console command    core/        models.py               ActionRequest, RuleMatch, GuardrailDecision (stdlib only)        policy.py                 Policy loader (the one place PyYAML is used)    rules.py                    Deterministic rule evaluators    storage/        rate_limiter.py           SQLite-backed sliding-window rate limiter        audit.py                    SQLite-backed persistent audit log    engine.py                    GuardrailEngine — orchestrates rules + rate limit + audit    decorator.py                 enforce() — the unbypassable integration point    confirmation/        web_ui.py                    Local web UI for human approve/reject (stdlib http.server)        cli_ui.py                      Terminal-prompt confirmation    policies/default.yaml           Copy of the default policy bundled into the installed packagepolicies/default.yaml       Canonical, editable default policy (git-clone workflow)cli.py                      Thin shim -> guardrail/__main__.py (for `python3 cli.py`)mcp_server.py                Thin shim -> guardrail/mcp_server.py (for `python3 mcp_server.py`)pyproject.toml               Package metadata — `pip install .` gives you `guardrail` + `guardrail-mcp-server`.github/workflows/ci.yml      Runs the test suite + policy validation + package build on every pushexamples/    example_agent_usage.py       Decorator basics    example_web_confirmation.py    Real browser-based approve/reject, livetests/                       46 unit tests, all runnable with just PyYAML installedCONTRIBUTING.md              How to add a rule type, ground rulesCHANGELOG.md                  Version historyPUBLISHING.md                 How to actually get this in front of peoplelanding/index.html             Static one-page site (open directly or host on GitHub Pages)

來源:README.md,提交 9ecea96

工具

0
SourceWeft 尚未在沙箱中啟動過該軟體包,因此其工具未知。

版本歷史

1
  1. v1.0.2最新Sep 16, 2026

評分

已滿足適用檢查項的 50%

該評分衡量此收錄條目的完整程度,依據註冊中心條目、端點與公開來源計算得出。它不是對伺服器本身的評價,也不表示伺服器安全或目前可用:可連通性是帶日期的檢查結果,評分也不包含安裝量或使用者評價。

  • 近 30 天內可連通25 分

    請保持端點能夠回應 MCP 握手;SourceWeft 每 30 天探測一次。

  • 已宣告認證方式10 分

    請在註冊中心條目中宣告憑證請求標頭,或保持端點能夠回應探測,以便判定其認證方式。

  • 已列出工具15 分

    請讓伺服器在無憑證時回應 tools/list,或發布可在沙箱中無憑證啟動的軟體包。

  • 描述必需15 分
  • 圖示10 分
  • 文件15 分
  • 授權條款10 分