agent-tool-call-gate 0.1.0__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.
@@ -0,0 +1,126 @@
1
+ Metadata-Version: 2.4
2
+ Name: agent-tool-call-gate
3
+ Version: 0.1.0
4
+ Summary: Deterministic policy enforcement for agent tool calls
5
+ Author-email: Waseem Mushtaq <waseemmushtaq045@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/waseem1302-x/agent-tool-call-gate
8
+ Project-URL: Source, https://github.com/waseem1302-x/agent-tool-call-gate
9
+ Project-URL: Issues, https://github.com/waseem1302-x/agent-tool-call-gate/issues
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Topic :: Security
15
+ Requires-Python: >=3.12
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: PyYAML==6.0.4
19
+ Requires-Dist: jsonschema==4.26.0
20
+ Dynamic: license-file
21
+
22
+ # agentgate
23
+
24
+ agentgate is a deterministic Python policy gate for agent tool calls. It checks
25
+ proposed calls before execution and records decisions in a hash-chained SQLite
26
+ audit log. It does not use a language model.
27
+
28
+ ## Packaging
29
+
30
+ The install name is `agent-tool-call-gate` (`pip install agent-tool-call-gate`
31
+ after publication); the import name remains `agentgate`. The names differ
32
+ because `agentgate` is already taken on PyPI by an unrelated project. See
33
+ [docs/PYPI_NAME.md](docs/PYPI_NAME.md) for the naming decision.
34
+ The example below uses `policies/default.yaml` from the source checkout;
35
+ provide a policy file when using the installed wheel.
36
+
37
+ ```python
38
+ from pathlib import Path
39
+ from agentgate import Gate
40
+
41
+ gate = Gate(policy_path="policies/default.yaml", db_path="agentgate.db")
42
+ # After creating the file, report its actual result to this same gate instance.
43
+ read = gate.evaluate(tool="read_file", arguments={"path": "/home/agent/private/brief.txt"}, agent_id="session-1")
44
+ if read.verdict == "allow":
45
+ text = Path(read.checked_arguments["path"]).read_text(encoding="utf-8")
46
+ gate.observe(read.call_id, text)
47
+ decision = gate.evaluate(
48
+ tool="write_file",
49
+ arguments={"path": "/tmp/notes.txt", "content": "notes"}, agent_id="session-1",
50
+ )
51
+ if decision.verdict == "allow":
52
+ checked_arguments = decision.checked_arguments
53
+ # Execute the tool with exactly checked_arguments.
54
+ elif decision.verdict == "ask":
55
+ final_verdict = gate.resolve(decision.call_id, approved=True, approver="reviewer")
56
+ # Execute the checked arguments only if final_verdict is "allow".
57
+
58
+ head = gate.audit.head_hash # Store this outside the database.
59
+ assert gate.audit.verify(expected_head=head).ok
60
+ gate.close()
61
+ ```
62
+
63
+ The caller must enforce the verdict and execute exactly the checked arguments.
64
+ `redacted_arguments` is suitable for logging; `checked_arguments` can contain
65
+ sensitive data and must not be logged. A denied call must not execute. Approval
66
+ rechecks both the policy file hash and the available budget. A pending request
67
+ can be resolved once. Budget counters belong to the lifetime of a gate.
68
+
69
+ ## Data flow
70
+
71
+ `flow.restricted_prefixes` and `flow.restricted_tables` mark read sources as
72
+ restricted. Callers must report each successfully executed, allowed `read_file`
73
+ or `query_db` result as a string with `gate.observe(call_id, result)` on the same
74
+ gate instance. Use the same `agent_id` for subsequent calls in that session. The
75
+ gate stores bounded hashes, not the observed text. Matching copies in writes to
76
+ broader paths or tables and uploads are denied; matching email proposals ask for
77
+ approval. Fingerprints and duplicate call IDs persist in the audit database.
78
+ After reopening, stored taint still enforces, but pre-restart reads cannot be
79
+ observed or re-observed (`ValueError`); pending approvals and budgets do not
80
+ survive reopening.
81
+
82
+ The included stdio MCP server reports its own successful allowed reads to its
83
+ gate automatically, without exposing an observation tool to clients. See the
84
+ [MCP instructions](mcp_server/README.md).
85
+
86
+ This is bounded exact-fragment tracking, not semantic understanding: it misses
87
+ paraphrases, base64, fragments under 16 characters, unreported results and data
88
+ beyond its input and fingerprint limits. Re-observing a call adds fingerprints
89
+ to its existing taint without removing old ones, subject to the eviction cap.
90
+
91
+ The gate is not thread safe. Use one gate per thread and one writer per database
92
+ file. `close()` releases the writer lock. Audit write failures raise `AuditError`
93
+ instead of returning a verdict. Use a separately stored head hash when verifying
94
+ an audit log: someone who can rewrite the entire database can otherwise rewrite
95
+ the chain. A hash chain alone does not prevent that attack.
96
+
97
+ The gate only checks calls routed through it. Credential and PII detection uses
98
+ policy regexes, so encoded, split, and novel secrets can be missed. The SQL
99
+ classifier allows SELECT-shaped statements and rejects stacked statements and
100
+ SELECT INTO, but it is not a SQL sandbox: use a read-only database connection.
101
+ Paths are normalized, percent-decoded up to three times and rejected for NUL or
102
+ `..` components; this is lexical, not symlink resolution. The included MCP
103
+ server is local stdio only; HTTP, authentication and an approval endpoint are
104
+ not implemented. There is no LLM judge.
105
+
106
+ The frozen evaluation blocked 40 of 40 attacks and denied 0 of 40 benign calls;
107
+ 9 benign calls required approval. A null-gate baseline allowed 37 of 40 attacks
108
+ (two disguised tool names and one NUL path still deny) and denied none of
109
+ the benign calls. Forty attacks are a small sample: observing no
110
+ permitted attack calls gives a one-sided 95 percent upper bound of about 7.2 percent
111
+ on their true allowance rate under an independent-samples assumption, not a
112
+ guarantee of zero risk. The evaluation checks verdicts; it does not execute the
113
+ attacks or measure data reaching a recipient.
114
+ The 40 cases are curated, not a random sample, so treat the bound as
115
+ illustrative. See [EVAL_RESULTS.md](EVAL_RESULTS.md)
116
+ for family results and latency. The separate [multi-turn benchmark](docs/BENCHMARK_RESULTS.md)
117
+ reports permitted goal calls in a scripted replay, not observed live leaks.
118
+
119
+ Run the checks in the project environment:
120
+
121
+ ```sh
122
+ .venv/bin/python -m pytest -q -s
123
+ .venv/bin/ruff check agentgate tests
124
+ ```
125
+
126
+ License: MIT (see LICENSE).
@@ -0,0 +1,16 @@
1
+ agent_tool_call_gate-0.1.0.dist-info/licenses/LICENSE,sha256=4iVrPRYkvpWTHPDRvDfAmLJC8-Wmh0SLO91GwanLQD8,1092
2
+ agentgate/__init__.py,sha256=zjrKnlciwbaaK4cJBOLF6CBIRBnMUyVRtni1d1W2dAA,295
3
+ agentgate/audit.py,sha256=-ruxxE9PnPolZHbAA9rYrxhl3WVGQwpbeDzAnSa2vGA,10420
4
+ agentgate/gate.py,sha256=IRZ7ELWbZfKBEP4rG-B96sJOrBzKN16Azje30BtfbJc,25659
5
+ agentgate/matching.py,sha256=FLB1uUOqsGuyI9LeL7nttBkOwF8MhY92fOrvXGXnbS0,1642
6
+ agentgate/models.py,sha256=J9GxoB_jHQaN0i0qMl7qKKr8a7vnKbobtYQ-e6TGvXE,694
7
+ agentgate/normalize.py,sha256=1fJugcdAaAEzSZUKyAg9J36IvdJPIWxEOvTtpK1C-iM,2122
8
+ agentgate/policy.py,sha256=PMK4V6zFRAryi1bPVczSnqp9BKnNpBZoFi8Iqp__xAg,18553
9
+ agentgate/redact.py,sha256=89eopP5_PP27SmwQqwR3GEwLY_zCKGHQL84RazTfYIQ,4667
10
+ agentgate/risk.py,sha256=Y3h1jtsjeXO5oj5wpyr1wRQp2k4TQTaNY9hWn6jfx4M,1773
11
+ agentgate/sql.py,sha256=nwkE5W8LtSwVhG6EaVEYxDiXXR1OtjV55LVCumwpIOM,6175
12
+ agentgate/taint.py,sha256=bvMjy6oIdbEiEjuawQYUMofNB0I5BjMuyzHeFwZzqWw,3641
13
+ agent_tool_call_gate-0.1.0.dist-info/METADATA,sha256=CF2TFW8oLSMMxmq2Ril4ggIDeLh45as-lnMqTM0YgGw,6326
14
+ agent_tool_call_gate-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
15
+ agent_tool_call_gate-0.1.0.dist-info/top_level.txt,sha256=qWUC8JQwEvSXwMD-j8F0kB0LIDQhef7EPRPGeosKWb4,10
16
+ agent_tool_call_gate-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Waseem Mushtaq
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ agentgate
agentgate/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """Public API for deterministic agent tool-call policy enforcement."""
2
+
3
+ from .audit import AuditError
4
+ from .gate import Gate
5
+ from .models import Decision, ToolCall
6
+ from .policy import Policy, PolicyError
7
+
8
+ __all__ = ["AuditError", "Decision", "Gate", "Policy", "PolicyError", "ToolCall"]
agentgate/audit.py ADDED
@@ -0,0 +1,274 @@
1
+ """Single-writer SQLite audit log with a verifiable hash chain."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import fcntl
6
+ import hashlib
7
+ import json
8
+ import os
9
+ import sqlite3
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+
15
+ class AuditError(RuntimeError):
16
+ """An audit operation failed; no decision should be returned."""
17
+
18
+
19
+ FIELDS = (
20
+ "seq",
21
+ "entry_type",
22
+ "ts",
23
+ "call_id",
24
+ "agent_id",
25
+ "tool",
26
+ "arguments_redacted",
27
+ "verdict",
28
+ "reasons",
29
+ "risk_score",
30
+ "policy_hash",
31
+ "prev_hash",
32
+ )
33
+ GENESIS = "agentgate-genesis-1"
34
+
35
+
36
+ def _hash(row: dict[str, Any]) -> str:
37
+ payload = {name: row[name] for name in FIELDS}
38
+ canonical = json.dumps(
39
+ payload, ensure_ascii=False, separators=(",", ":"), allow_nan=False
40
+ )
41
+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class Verification:
46
+ ok: bool
47
+ broken_seq: int | None
48
+ head_hash: str
49
+
50
+
51
+ class AuditLog:
52
+ """Own a database file until closed. Only append operations are exposed."""
53
+
54
+ def __init__(self, path: str | Path):
55
+ self._lock_fd = None
56
+ self._connection = None
57
+ try:
58
+ path = str(path)
59
+ if path != ":memory:":
60
+ self._lock_fd = os.open(path, os.O_RDWR | os.O_CREAT, 0o600)
61
+ fcntl.flock(self._lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
62
+ self._connection = sqlite3.connect(path, isolation_level=None)
63
+ self._connection.row_factory = sqlite3.Row
64
+ self._connection.execute("PRAGMA journal_mode=DELETE")
65
+ self._connection.execute("PRAGMA synchronous=NORMAL")
66
+ self._connection.execute("""CREATE TABLE IF NOT EXISTS entries (
67
+ seq INTEGER PRIMARY KEY, entry_type TEXT NOT NULL, ts REAL NOT NULL,
68
+ call_id TEXT NOT NULL, agent_id TEXT NOT NULL, tool TEXT NOT NULL,
69
+ arguments_redacted TEXT NOT NULL, verdict TEXT NOT NULL, reasons TEXT NOT NULL,
70
+ risk_score INTEGER NOT NULL, policy_hash TEXT NOT NULL, prev_hash TEXT NOT NULL,
71
+ row_hash TEXT NOT NULL
72
+ )""")
73
+ self._connection.execute("""CREATE TABLE IF NOT EXISTS seen_calls (
74
+ call_id TEXT PRIMARY KEY, ts REAL NOT NULL
75
+ )""")
76
+ self._connection.execute("""CREATE TABLE IF NOT EXISTS taint (
77
+ agent_id TEXT NOT NULL, call_id TEXT NOT NULL, source TEXT NOT NULL,
78
+ fragment TEXT NOT NULL, ts REAL NOT NULL,
79
+ UNIQUE (agent_id, call_id, fragment)
80
+ )""")
81
+ verification = self.verify()
82
+ if not verification.ok:
83
+ raise AuditError("existing audit chain is invalid")
84
+ row = self._connection.execute(
85
+ "SELECT seq FROM entries ORDER BY seq DESC LIMIT 1"
86
+ ).fetchone()
87
+ self._seq = row[0] if row else 0
88
+ self._head_hash = verification.head_hash
89
+ except (OSError, sqlite3.Error, AuditError, KeyError, IndexError) as exc:
90
+ self.close()
91
+ raise AuditError("cannot open audit log") from exc
92
+
93
+ @property
94
+ def head_hash(self) -> str:
95
+ return self._head_hash
96
+
97
+ def append(
98
+ self,
99
+ *,
100
+ entry_type: str,
101
+ ts: float,
102
+ call_id: str,
103
+ agent_id: str,
104
+ tool: str,
105
+ arguments_redacted: Any,
106
+ verdict: str,
107
+ reasons: list[str],
108
+ risk_score: int,
109
+ policy_hash: str,
110
+ seen_call_id: str | None = None,
111
+ ) -> str:
112
+ if self._connection is None:
113
+ raise AuditError("audit log is closed")
114
+ try:
115
+ row = {
116
+ "seq": self._seq + 1,
117
+ "entry_type": entry_type,
118
+ "ts": float(ts) if ts != 0 else 0.0,
119
+ "call_id": call_id,
120
+ "agent_id": agent_id,
121
+ "tool": tool,
122
+ "arguments_redacted": json.dumps(
123
+ arguments_redacted,
124
+ ensure_ascii=False,
125
+ separators=(",", ":"),
126
+ allow_nan=False,
127
+ ),
128
+ "verdict": verdict,
129
+ "reasons": json.dumps(
130
+ reasons, ensure_ascii=False, separators=(",", ":"), allow_nan=False
131
+ ),
132
+ "risk_score": risk_score,
133
+ "policy_hash": policy_hash,
134
+ "prev_hash": self._head_hash,
135
+ }
136
+ digest = _hash(row)
137
+ self._connection.execute("BEGIN IMMEDIATE")
138
+ last = self._connection.execute(
139
+ "SELECT seq, row_hash FROM entries ORDER BY seq DESC LIMIT 1"
140
+ ).fetchone()
141
+ if (last is None and self._seq != 0) or (
142
+ last is not None and (last[0], last[1]) != (self._seq, self._head_hash)
143
+ ):
144
+ raise AuditError("audit head changed")
145
+ self._connection.execute(
146
+ "INSERT INTO entries VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
147
+ tuple(row[name] for name in FIELDS) + (digest,),
148
+ )
149
+ if seen_call_id is not None:
150
+ self._connection.execute(
151
+ "INSERT OR IGNORE INTO seen_calls (call_id, ts) VALUES (?, ?)",
152
+ (seen_call_id, row["ts"]),
153
+ )
154
+ self._connection.execute("COMMIT")
155
+ self._seq += 1
156
+ self._head_hash = digest
157
+ return digest
158
+ except (
159
+ sqlite3.Error,
160
+ OSError,
161
+ ValueError,
162
+ TypeError,
163
+ OverflowError,
164
+ AuditError,
165
+ ) as exc:
166
+ try:
167
+ if self._connection.in_transaction:
168
+ self._connection.execute("ROLLBACK")
169
+ except sqlite3.Error:
170
+ pass
171
+ raise AuditError("audit append failed") from exc
172
+
173
+ def seen_calls(self) -> set[str]:
174
+ if self._connection is None:
175
+ raise AuditError("audit log is closed")
176
+ try:
177
+ return {
178
+ row[0]
179
+ for row in self._connection.execute("SELECT call_id FROM seen_calls")
180
+ }
181
+ except sqlite3.Error as exc:
182
+ raise AuditError("could not read seen calls") from exc
183
+
184
+ def taint_rows(self) -> list[tuple[str, str, str, str, float]]:
185
+ if self._connection is None:
186
+ raise AuditError("audit log is closed")
187
+ try:
188
+ return [
189
+ tuple(row)
190
+ for row in self._connection.execute(
191
+ "SELECT agent_id, call_id, source, fragment, ts FROM taint ORDER BY ts, rowid"
192
+ )
193
+ ]
194
+ except sqlite3.Error as exc:
195
+ raise AuditError("could not read taint") from exc
196
+
197
+ def replace_taint(
198
+ self, agent_id: str, call_id: str, source: str, fragments: list[str], ts: float
199
+ ) -> None:
200
+ if self._connection is None:
201
+ raise AuditError("audit log is closed")
202
+ try:
203
+ self._connection.execute("BEGIN IMMEDIATE")
204
+ # Observations union taint; correction requires a separate, explicitly
205
+ # audited operation, never silent declassification via observe().
206
+ # The existence check also deduplicates legacy tables without UNIQUE.
207
+ self._connection.executemany(
208
+ "INSERT OR IGNORE INTO taint (agent_id, call_id, source, fragment, ts) "
209
+ "SELECT ?, ?, ?, ?, ? WHERE NOT EXISTS "
210
+ "(SELECT 1 FROM taint WHERE agent_id=? AND call_id=? AND fragment=?)",
211
+ [
212
+ (agent_id, call_id, source, fragment, ts, agent_id, call_id, fragment)
213
+ for fragment in fragments
214
+ ],
215
+ )
216
+ self._connection.execute(
217
+ "DELETE FROM taint WHERE rowid IN (SELECT rowid FROM taint WHERE agent_id=? ORDER BY ts DESC, rowid DESC LIMIT -1 OFFSET 2000)",
218
+ (agent_id,),
219
+ )
220
+ self._connection.execute("COMMIT")
221
+ except (sqlite3.Error, ValueError, TypeError, OverflowError) as exc:
222
+ if self._connection.in_transaction:
223
+ self._connection.execute("ROLLBACK")
224
+ raise AuditError("could not store taint") from exc
225
+
226
+ def read(self) -> list[dict[str, Any]]:
227
+ if self._connection is None:
228
+ raise AuditError("audit log is closed")
229
+ try:
230
+ return [
231
+ dict(row)
232
+ for row in self._connection.execute(
233
+ "SELECT * FROM entries ORDER BY seq"
234
+ )
235
+ ]
236
+ except sqlite3.Error as exc:
237
+ raise AuditError("audit read failed") from exc
238
+
239
+ def verify(self, expected_head: str | None = None) -> Verification:
240
+ if self._connection is None:
241
+ raise AuditError("audit log is closed")
242
+ try:
243
+ previous = GENESIS
244
+ expected_seq = 1
245
+ for row in self._connection.execute("SELECT * FROM entries ORDER BY seq"):
246
+ data = dict(row)
247
+ if (
248
+ data["seq"] != expected_seq
249
+ or data["prev_hash"] != previous
250
+ or _hash(data) != data["row_hash"]
251
+ ):
252
+ return Verification(False, expected_seq, previous)
253
+ previous = data["row_hash"]
254
+ expected_seq += 1
255
+ if expected_head is not None and previous != expected_head:
256
+ return Verification(False, expected_seq, previous)
257
+ return Verification(True, None, previous)
258
+ except (
259
+ sqlite3.Error,
260
+ TypeError,
261
+ ValueError,
262
+ OverflowError,
263
+ KeyError,
264
+ IndexError,
265
+ ) as exc:
266
+ raise AuditError("audit verification failed") from exc
267
+
268
+ def close(self) -> None:
269
+ if self._connection is not None:
270
+ self._connection.close()
271
+ self._connection = None
272
+ if self._lock_fd is not None:
273
+ os.close(self._lock_fd)
274
+ self._lock_fd = None