agent-tool-guardrails 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of agent-tool-guardrails might be problematic. Click here for more details.

Files changed (40) hide show
  1. agent_tool_guardrails-0.1.0/.gitignore +25 -0
  2. agent_tool_guardrails-0.1.0/CHANGELOG.md +42 -0
  3. agent_tool_guardrails-0.1.0/CITATION.cff +16 -0
  4. agent_tool_guardrails-0.1.0/LICENSE +201 -0
  5. agent_tool_guardrails-0.1.0/NOTICE +6 -0
  6. agent_tool_guardrails-0.1.0/PKG-INFO +277 -0
  7. agent_tool_guardrails-0.1.0/README.md +248 -0
  8. agent_tool_guardrails-0.1.0/docs/architecture.md +40 -0
  9. agent_tool_guardrails-0.1.0/docs/policy-language.md +78 -0
  10. agent_tool_guardrails-0.1.0/examples/guard_demo.py +83 -0
  11. agent_tool_guardrails-0.1.0/examples/mcp_proxy_demo.md +45 -0
  12. agent_tool_guardrails-0.1.0/examples/policies/finance.yaml +49 -0
  13. agent_tool_guardrails-0.1.0/examples/policies/healthcare.yaml +32 -0
  14. agent_tool_guardrails-0.1.0/pyproject.toml +92 -0
  15. agent_tool_guardrails-0.1.0/src/typed_rails/__init__.py +105 -0
  16. agent_tool_guardrails-0.1.0/src/typed_rails/_version.py +2 -0
  17. agent_tool_guardrails-0.1.0/src/typed_rails/cli.py +201 -0
  18. agent_tool_guardrails-0.1.0/src/typed_rails/compiler.py +747 -0
  19. agent_tool_guardrails-0.1.0/src/typed_rails/engine.py +389 -0
  20. agent_tool_guardrails-0.1.0/src/typed_rails/evidence.py +227 -0
  21. agent_tool_guardrails-0.1.0/src/typed_rails/guard.py +44 -0
  22. agent_tool_guardrails-0.1.0/src/typed_rails/mcp_proxy.py +348 -0
  23. agent_tool_guardrails-0.1.0/src/typed_rails/metrics.py +125 -0
  24. agent_tool_guardrails-0.1.0/src/typed_rails/model.py +438 -0
  25. agent_tool_guardrails-0.1.0/src/typed_rails/predicates.py +651 -0
  26. agent_tool_guardrails-0.1.0/src/typed_rails/py.typed +0 -0
  27. agent_tool_guardrails-0.1.0/src/typed_rails/redaction.py +175 -0
  28. agent_tool_guardrails-0.1.0/src/typed_rails/sharding.py +186 -0
  29. agent_tool_guardrails-0.1.0/src/typed_rails/trust.py +177 -0
  30. agent_tool_guardrails-0.1.0/tests/conftest.py +63 -0
  31. agent_tool_guardrails-0.1.0/tests/fake_mcp_server.py +108 -0
  32. agent_tool_guardrails-0.1.0/tests/test_cli.py +81 -0
  33. agent_tool_guardrails-0.1.0/tests/test_compiler.py +197 -0
  34. agent_tool_guardrails-0.1.0/tests/test_engine.py +288 -0
  35. agent_tool_guardrails-0.1.0/tests/test_guard_langchain.py +46 -0
  36. agent_tool_guardrails-0.1.0/tests/test_mcp_proxy.py +277 -0
  37. agent_tool_guardrails-0.1.0/tests/test_model_evidence.py +147 -0
  38. agent_tool_guardrails-0.1.0/tests/test_predicates.py +101 -0
  39. agent_tool_guardrails-0.1.0/tests/test_redaction.py +43 -0
  40. agent_tool_guardrails-0.1.0/tests/test_trust_sharding_metrics.py +182 -0
@@ -0,0 +1,25 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ build/
6
+ dist/
7
+ wheels/
8
+ .venv/
9
+ venv/
10
+ # Tooling caches
11
+ .pytest_cache/
12
+ .mypy_cache/
13
+ .ruff_cache/
14
+ .coverage
15
+ coverage.xml
16
+ htmlcov/
17
+ uv.lock
18
+ # Editors / OS
19
+ .vscode/
20
+ .idea/
21
+ *.swp
22
+ .DS_Store
23
+ # Runtime artefacts
24
+ evidence.jsonl
25
+ *.rails.json
@@ -0,0 +1,42 @@
1
+ # Changelog
2
+
3
+ All notable changes to `agent-tool-guardrails` are documented here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses
5
+ [Semantic Versioning](https://semver.org/).
6
+
7
+ ## [Unreleased]
8
+
9
+ ## [0.1.0] - 2026-10-03
10
+
11
+ First release on PyPI: the initial version of 27 September 2026 (*Added*) together with
12
+ the changes made to it before publishing.
13
+
14
+ ### Added
15
+ - Typed Rails data model: `RailType` (risk × capability), `Predicate`, `EvidenceSpec`, `ActionSpec`, selectors with pre/post phases, `CallContext`, `Decision`.
16
+ - Safe predicate expression language (parser + evaluator, no `eval`), PII detection and field redaction.
17
+ - Policy compiler: YAML/JSON requirements and 14 templates (`allowed_tools`, `deny_tools`, `approval_threshold`, `rate_limit`, `trust_gate`, `pii_redaction`, `output_pii_redaction`, `time_window`, `data_residency`, `purpose_limitation`, `sandbox_required`, `max_output_size`, `evidence_required`, `forbidden_patterns`) compiled into a content-addressed `RailSet`.
18
+ - Policy engine with action combination, redaction, rate limiting, approvals, fail-closed predicate errors, static tool denial analysis and a `guard` decorator (sync + async).
19
+ - Tamper-evident Evidence Store (hash chain, HMAC signatures, Merkle root, JSONL persistence) and governance metrics.
20
+ - Trust-scored governance loop (compliance scores, trust evolution, pairwise trust and privilege weights, fusion thresholds, policy adaptation) and policy-driven memory sharding.
21
+ - MCP stdio proxy enforcing rails on `tools/call` (denials as tool errors, in-flight redaction of arguments and results, hidden denied tools, protocol-revision aware).
22
+ - The `typed-rails` CLI (`compile`, `explain`, `check`, `proxy`, `evidence`, `metrics`) and a LangChain tool guard.
23
+
24
+ ### Changed
25
+ - README, `NOTICE`, `CITATION.cff` and the package metadata now describe the software only.
26
+ - `PolicyEngine.guard` and the MCP proxy stamp each `CallContext` with the engine clock
27
+ (new `PolicyEngine.now()`), so `time.*` predicates can be pinned in tests and demos. The
28
+ default clock is still `time.time`.
29
+
30
+ ### Fixed
31
+ - The MCP proxy terminated the server as soon as the client disconnected, before the server could
32
+ exit on its own; on Windows the terminated server reports exit code 1, which became the proxy's exit
33
+ code after a clean session. The proxy now waits for the server (`exit_grace_s`, default 5 s) and only
34
+ then terminates it.
35
+ - CI caches uv by `pyproject.toml` (the lock file is not committed), which newer `setup-uv` releases require.
36
+ - Approving a `require_approval` decision (`PolicyEngine.approve`, an approval handler or the MCP
37
+ proxy) appended the approval note to a `reasons` list that the decision's evidence record still
38
+ referenced, so `EvidenceStore.verify()` reported that record as tampered. Evidence records now
39
+ deep-copy every field they store.
40
+ - `examples/guard_demo.py` produced different output depending on the weekday and time of day
41
+ (business-hours rail) and appended to a previous evidence log on every run; it now pins the
42
+ clock and starts from a fresh log.
@@ -0,0 +1,16 @@
1
+ cff-version: 1.2.0
2
+ message: "If you use agent-tool-guardrails, please cite it as below."
3
+ type: software
4
+ title: "agent-tool-guardrails (Typed Rails): typed policy rails for agent-tool calls with a policy compiler, evidence store and MCP proxy"
5
+ version: 0.1.0
6
+ date-released: "2026-10-03"
7
+ license: Apache-2.0
8
+ repository-code: "https://github.com/nunar-nexus-forge/agent-tool-guardrails"
9
+ authors:
10
+ - name: nunar-nexus-forge
11
+ keywords:
12
+ - guardrails
13
+ - policy compliance
14
+ - multi-agent systems
15
+ - model context protocol
16
+ - audit evidence
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,6 @@
1
+ agent-tool-guardrails
2
+ Copyright 2026 nunar-nexus-forge
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
5
+ this software except in compliance with the License. You may obtain a copy of
6
+ the License at http://www.apache.org/licenses/LICENSE-2.0
@@ -0,0 +1,277 @@
1
+ Metadata-Version: 2.5
2
+ Name: agent-tool-guardrails
3
+ Version: 0.1.0
4
+ Summary: Typed policy rails for agent-tool calls: a policy compiler that turns declarative requirements into executable (Type, Predicate, Evidence, Action) rails, a tamper-evident evidence store, trust-scored governance, and an MCP proxy that enforces it all with zero code changes.
5
+ Project-URL: Homepage, https://github.com/nunar-nexus-forge/agent-tool-guardrails
6
+ Project-URL: Documentation, https://github.com/nunar-nexus-forge/agent-tool-guardrails/tree/main/docs
7
+ Project-URL: Changelog, https://github.com/nunar-nexus-forge/agent-tool-guardrails/blob/main/CHANGELOG.md
8
+ Project-URL: Issues, https://github.com/nunar-nexus-forge/agent-tool-guardrails/issues
9
+ Author: nunar-nexus-forge
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: agent-guardrails,agent-tool-guardrails,agents,audit,compliance,evidence,gdpr,governance,guardrails,hipaa,llm,mcp,model-context-protocol,policy,trust
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: Apache Software License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Security
22
+ Classifier: Topic :: Software Development :: Libraries
23
+ Classifier: Typing :: Typed
24
+ Requires-Python: >=3.10
25
+ Requires-Dist: pyyaml>=6.0
26
+ Provides-Extra: langchain
27
+ Requires-Dist: langchain-core>=0.3; extra == 'langchain'
28
+ Description-Content-Type: text/markdown
29
+
30
+ # agent-tool-guardrails
31
+
32
+ **Typed policy rails for agent-tool calls: compile declarative requirements into executable `⟨Type, Predicate, Evidence, Action⟩` rails, enforce them in-process or through an MCP proxy, and keep a tamper-evident evidence trail.**
33
+
34
+ [![CI](https://github.com/nunar-nexus-forge/agent-tool-guardrails/actions/workflows/ci.yml/badge.svg)](https://github.com/nunar-nexus-forge/agent-tool-guardrails/actions/workflows/ci.yml)
35
+ [![PyPI](https://img.shields.io/pypi/v/agent-tool-guardrails.svg)](https://pypi.org/project/agent-tool-guardrails/)
36
+ [![Python](https://img.shields.io/badge/python-3.10%2B-blue.svg)](pyproject.toml)
37
+ [![License](https://img.shields.io/badge/license-Apache--2.0-green.svg)](LICENSE)
38
+
39
+ Most agent guardrails are filters bolted on after the fact: a prompt classifier here, an
40
+ allow/deny list there, nothing an auditor can trace from a regulation to a blocked call.
41
+ `agent-tool-guardrails` makes governance a **first-class architectural connector** between agents and
42
+ tools - typed rails that sit between every agent and every tool - and adds two things most
43
+ guardrail layers lack:
44
+
45
+ * a **policy compiler** that turns declarative requirements (GDPR anonymisation, approval
46
+ thresholds, data residency, PII redaction, rate limits, trust gates ...) into executable
47
+ rails, from *one configuration file*;
48
+ * a cryptographically verifiable **Evidence Store** so every predicate evaluation, every
49
+ enforcement and every human approval is an append-only, hash-chained, signed record.
50
+
51
+ It ships as an **MCP proxy**: wrap any Model Context Protocol server command and every
52
+ `tools/call` is evaluated with zero changes to the client or the server. Trust-scored
53
+ governance (compliance scores, evolving trust, fusion thresholds, policy-driven memory
54
+ sharding) throttles or isolates agents that keep violating policy.
55
+
56
+ > **Naming:** the distribution is `agent-tool-guardrails`; the enforcement model is called
57
+ > Typed Rails, so the import is `from typed_rails import ...` and the CLI is `typed-rails <command>`.
58
+
59
+ ---
60
+
61
+ ## Install
62
+
63
+ ```bash
64
+ pip install agent-tool-guardrails # PyYAML is the only dependency
65
+ pip install 'agent-tool-guardrails[langchain]' # + guard LangChain tools
66
+ ```
67
+
68
+ ## 60-second tour
69
+
70
+ **1. Write requirements, not code** - `policy.yaml`:
71
+
72
+ ```yaml
73
+ version: 1
74
+ name: finance
75
+ defaults: {on_fail: deny}
76
+ requirements:
77
+ - id: gdpr-anonymised-exports # a raw rule: Type + Predicate + Evidence + Action
78
+ type: privacy
79
+ tools: [export_report]
80
+ predicate: "evidence.anonymised == true"
81
+ evidence: [anonymised]
82
+ on_fail: {action: redact, fields: [args.customer.email, args.customer.name]}
83
+ citation: "GDPR Art. 5(1)(c)"
84
+ - template: approval_threshold # templates capture recurring regulatory patterns
85
+ tool: transfer_funds
86
+ field: args.amount
87
+ threshold: 1000
88
+ - template: pii_redaction
89
+ tools: ["*"]
90
+ - template: trust_gate
91
+ tools: [execute_code]
92
+ min_trust: 0.7
93
+ - template: rate_limit
94
+ tools: [search]
95
+ max_calls: 30
96
+ per_seconds: 60
97
+ - template: deny_tools
98
+ tools: [drop_database]
99
+ ```
100
+
101
+ ```bash
102
+ typed-rails compile policy.yaml -o finance.rails.json # validate + compile (content-addressed policy hash)
103
+ typed-rails explain policy.yaml # Markdown table of every rail
104
+ typed-rails check policy.yaml --tool transfer_funds --args '{"amount": 5000}' # -> REQUIRE_APPROVAL, exit 1
105
+ ```
106
+
107
+ **2. Enforce with zero code changes - the MCP proxy:**
108
+
109
+ ```bash
110
+ typed-rails proxy --policy policy.yaml --evidence evidence.jsonl -- npx -y @modelcontextprotocol/server-filesystem /data
111
+ ```
112
+
113
+ Point Claude Desktop / Cursor / your agent framework at that command instead of the server.
114
+ Denied calls come back as MCP tool errors the model can read and recover from; arguments
115
+ and results are redacted in flight; tools an agent can never call disappear from
116
+ `tools/list`; every decision lands in `evidence.jsonl`.
117
+
118
+ ```bash
119
+ typed-rails evidence evidence.jsonl verify # OK: 42 record(s), chain intact + Merkle root
120
+ typed-rails metrics evidence.jsonl # coverage, safety incident rate, redactions, approvals, per rail / per agent
121
+ ```
122
+
123
+ **3. Or enforce in-process:**
124
+
125
+ ```python
126
+ from typed_rails import compile_policy, PolicyEngine, CallContext, PolicyDenied
127
+
128
+ engine = PolicyEngine(compile_policy("policy.yaml"))
129
+
130
+
131
+ @engine.guard("transfer_funds", agent="treasury-bot") # pre-conditions before, post-conditions after
132
+ def transfer_funds(amount: float, to: str) -> str: ...
133
+
134
+
135
+ decision = engine.evaluate(
136
+ CallContext(tool="export_report", args={"customer": {"email": "a@b.com"}}, agent="analyst")
137
+ )
138
+ print(decision.explain())
139
+ # REDACT analyst -> export_report [pre] (2 rail(s))
140
+ # - gdpr-anonymised-exports [privacy/tool] FAIL -> redact missing evidence: anonymised (GDPR Art. 5(1)(c))
141
+ # - pii-redaction-2 [privacy/tool] FAIL -> redact
142
+ # redacted: args.customer.email, args.customer.name
143
+ print(engine.evidence.verify()) # OK: 1 record(s), chain intact
144
+ ```
145
+
146
+ ## The model
147
+
148
+ | Element | In the code | What it captures |
149
+ |---|---|---|
150
+ | **Type** `T` | `RailType(risk, capability)` | hierarchical types: risk (`safety`, `privacy`, `compliance`, `security`, `cost`, `quality`) × capability (`tool`, `api`, `memory`, `data`, `message`, `code`) |
151
+ | **Predicate** `P` | `Predicate("agent.trust >= 0.7 and not has_pii(args)")` | a safe expression over `tool`, `args`, `agent`, `evidence`, `session`, `env`, `time`, `result` - no `eval`, missing paths are `null` |
152
+ | **Evidence** `E` | `EvidenceSpec(required=[...], capture=[...])` | evidence keys the predicate needs (auth tokens, anonymisation flags, tickets, regions); what to snapshot into the audit record |
153
+ | **Action** `A` | `ActionSpec(action, fields, message, retry_after_s)` | `allow`, `log`, `redact`, `throttle`, `require_approval`, `quarantine`, `deny` on fail (and optionally on pass) |
154
+
155
+ `Allow(agent, action) = 1` iff every applicable rail's predicate holds over its evidence.
156
+ Rails have a **selector** (tool and agent globs, `pre`/`post` phase) and the most severe
157
+ action across applicable rails wins; redactions accumulate. Post-phase rails see the tool
158
+ **result** and can redact or reject it.
159
+
160
+ ### Templates
161
+
162
+ `allowed_tools`, `deny_tools`, `approval_threshold`, `rate_limit`, `trust_gate`,
163
+ `pii_redaction`, `output_pii_redaction`, `time_window`, `data_residency`,
164
+ `purpose_limitation`, `sandbox_required`, `max_output_size`, `evidence_required`,
165
+ `forbidden_patterns`. Each compiles to an ordinary rail (run `typed-rails explain` to see
166
+ the generated predicate), so you can always fall back to a raw rule.
167
+
168
+ ### Predicate language
169
+
170
+ ```
171
+ tool == "transfer_funds" and args.amount > 1000
172
+ evidence.region in ["EU", "UK"] and time.hour >= 8 and time.hour < 18
173
+ matches(args.sql, "(?i)drop\s+table") or args.query contains "rm -rf"
174
+ count_pii(result) == 0
175
+ rate(tool, 60) < 30 # provided by the engine
176
+ len(args.items) <= 100 and all(args.flags)
177
+ ```
178
+
179
+ Operators `and or not == != < <= > >= in "not in" matches contains startswith endswith + - * / %`;
180
+ functions `len lower upper str int float abs min max sum any all exists keys values matches
181
+ contains startswith endswith now age count_pii has_pii pii_kinds round`. Regular expressions
182
+ are bounded and errors fail closed by default.
183
+
184
+ ### Evidence Store
185
+
186
+ ```python
187
+ from typed_rails import EvidenceStore
188
+
189
+ store = EvidenceStore("evidence.jsonl", hmac_key=os.environ["RAILS_KEY"])
190
+ engine = PolicyEngine(rails, evidence=store)
191
+ ...
192
+ store.verify() # hash chain + HMAC signatures
193
+ store.merkle_root() # commit to (or timestamp) the whole log in one hash
194
+ store.query(agent="analyst", action="deny")
195
+ ```
196
+
197
+ Records carry the rail evaluations, the evidence the predicate saw (PII-redacted), digests
198
+ of the raw arguments/results, the redactions applied and the `policy_hash` of the compiled
199
+ rules in force - the traceability an auditor needs from "which rule" to "which call".
200
+
201
+ ### Trust-scored governance
202
+
203
+ ```python
204
+ from typed_rails import GovernanceLoop, GovernanceConfig
205
+
206
+ gov = GovernanceLoop(GovernanceConfig(lam=0.8, alpha=0.5, window=20, throttle_below=0.6, isolate_below=0.4))
207
+ engine = PolicyEngine(rails, governance=gov)
208
+ ```
209
+
210
+ Every decision updates the agent's **compliance score** `C_i` (allowed actions over the
211
+ last *K*) and **trust** `T_i ← λT_i + (1−λ)E_i`; the **fusion** `G_i = αC_i + (1−α)T_i`
212
+ throttles then isolates agents that keep violating policy - automatically, in the same
213
+ engine. Predicates can read the agent's trust (`agent.trust`) and the loop's
214
+ strictness knob (`env.strictness`, driven by `gov.adapt(delta_risk)`), and
215
+ `ShardedMemory` applies the same predicate gating to policy / context / analytics memory
216
+ shards with auditable lineage.
217
+
218
+ ## Architecture
219
+
220
+ ```mermaid
221
+ flowchart LR
222
+ subgraph design["design time"]
223
+ Y[policy.yaml<br/>requirements + templates] --> C[policy compiler] --> RS[(RailSet<br/>policy_hash)]
224
+ end
225
+ subgraph runtime["runtime"]
226
+ A[agent / MCP client] -->|tools/call| PX[MCP proxy<br/>or @engine.guard]
227
+ PX --> E[Policy Engine<br/>predicates · evidence · actions]
228
+ RS --> E
229
+ E -->|allow / redact| T[tool / MCP server]
230
+ E -->|deny · approval · throttle| A
231
+ T -->|result| E
232
+ E --> ES[(Evidence Store<br/>hash chain · HMAC · Merkle)]
233
+ E --> G[Governance loop<br/>compliance · trust · fusion]
234
+ G --> E
235
+ end
236
+ ES --> M[typed-rails metrics<br/>SIR · coverage · approvals]
237
+ ```
238
+
239
+ ## CLI
240
+
241
+ ```
242
+ typed-rails compile policy.yaml [-o rails.json]
243
+ typed-rails explain policy.yaml
244
+ typed-rails check policy.yaml --tool T [--agent A] [--trust 0.8] [--args JSON] [--evidence JSON] [--result JSON] [--json]
245
+ typed-rails proxy --policy policy.yaml [--evidence file.jsonl] [--agent NAME] [--static-evidence JSON] [--hmac-key-env VAR] [--no-hide] -- <server command>
246
+ typed-rails evidence file.jsonl [--hmac-key-env VAR] verify | show [--last N] [--json] | export OUT
247
+ typed-rails metrics file.jsonl [--json]
248
+ ```
249
+
250
+ ## Scope
251
+
252
+ The engine enforces the rules you compile and reports what it measures on your traffic; it
253
+ makes no safety claims of its own. Longer documents live in `docs/`:
254
+ [policy-language.md](docs/policy-language.md) (document schema, templates, predicate
255
+ namespace, action combination) and [architecture.md](docs/architecture.md) (viewpoints,
256
+ enforcement sequence, trust boundary). To cite the software, use [CITATION.cff](CITATION.cff).
257
+
258
+ ## Companion projects
259
+
260
+ - [`multi-agent-observability`](https://github.com/nunar-nexus-forge/multi-agent-observability) - causal tracing, coordination SLOs and deterministic replay for multi-agent systems.
261
+ - [`agent-chaos-engineering`](https://github.com/nunar-nexus-forge/agent-chaos-engineering) - fault injection and self-healing recovery patterns.
262
+
263
+ ## Contributing
264
+
265
+ See [CONTRIBUTING.md](CONTRIBUTING.md). Most wanted: more requirement templates (HIPAA
266
+ minimum-necessary, PCI-DSS scope, SOC 2 change control), Streamable-HTTP MCP proxying, and
267
+ adapters for the OpenAI Agents SDK and Semantic Kernel.
268
+
269
+ ```bash
270
+ git clone https://github.com/nunar-nexus-forge/agent-tool-guardrails && cd agent-tool-guardrails
271
+ make sync && make check # everything lives in ./.venv
272
+ python examples/guard_demo.py
273
+ ```
274
+
275
+ ## License
276
+
277
+ Apache License 2.0 - see [LICENSE](LICENSE) and [NOTICE](NOTICE).