Add tool call governance audit records - #684
Conversation
📝 WalkthroughWalkthroughA new governance module has been added to track and validate agent tool-call decisions through audit records. The implementation includes a decision enum, a Pydantic-based audit record schema with SHA-256 argument hashing, decision-specific validation, documentation, and test coverage. ChangesTool-Call Governance and Audit Layer
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Tip 💬 Introducing Slack Agent: The best way for teams to turn conversations into code.Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.
Built for teams:
One agent for your entire SDLC. Right inside Slack. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
tests/governance/test_tool_call_audit.py (1)
51-79: ⚡ Quick winAdd tests for the two key guardrail edge cases.
Current tests miss: (1)
MODIFYwith unchanged hash, and (2) metadata key casing variants (e.g.,Arguments) for raw-arg rejection.Suggested test additions
def test_modify_record_requires_modified_args_hash() -> None: @@ ToolCallAuditRecord( @@ ) +def test_modify_record_rejects_unchanged_hash() -> None: + original_hash = hash_tool_arguments({"limit": 1000}) + record = ToolCallAuditRecord( + event_id="evt_005", + tool_name="web_search", + decision=ToolCallDecision.MODIFY, + args_hash=original_hash, + modified_args_hash=original_hash, + policy_id="default-tool-policy", + policy_version="2026-05-07", + evaluated_at="2026-05-07T00:00:00Z", + reason="rewritten args", + ) + + with pytest.raises(ValueError, match="must change the argument hash"): + validate_tool_call_audit_record(record) + +def test_rejects_raw_arguments_in_metadata_case_insensitive_key() -> None: + record = ToolCallAuditRecord( + event_id="evt_006", + tool_name="send_email", + decision=ToolCallDecision.NEEDS_REVIEW, + args_hash=hash_tool_arguments({"recipient": "user@example.com"}), + policy_id="default-tool-policy", + policy_version="2026-05-07", + evaluated_at="2026-05-07T00:00:00Z", + reason="external communication requires review", + metadata={"Arguments": {"recipient": "user@example.com"}}, + ) + + with pytest.raises(ValueError, match="raw tool arguments"): + validate_tool_call_audit_record(record)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/governance/test_tool_call_audit.py` around lines 51 - 79, Add tests covering two edge cases: (1) ensure a ToolCallAuditRecord with decision ToolCallDecision.MODIFY and either missing modified_args_hash or modified_args_hash equal to args_hash raises a ValidationError (use ToolCallAuditRecord, ToolCallDecision.MODIFY, and hash_tool_arguments to construct the record); and (2) ensure validate_tool_call_audit_record rejects raw arguments in metadata regardless of casing by adding a record whose metadata contains keys like "Arguments" or mixed-case variants with the raw args and asserting validate_tool_call_audit_record raises a ValueError about "raw tool arguments".
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/mcp_agent/governance/tool_call_audit.py`:
- Around line 88-89: The key check that currently compares key against the exact
set {"args", "arguments", "raw_args", "raw_arguments"} is bypassable by casing
variants; update the guard in the routine that inspects keys (the `key` variable
and that set) to perform a case-insensitive comparison (e.g., normalize the
inspected key with key.lower() or key.casefold() and ensure the set contains
lowercased entries) so keys like "Arguments" or "RAW_Arguments" are detected as
raw-argument keys; also guard that key is a str before normalizing to avoid
attribute errors.
- Around line 49-51: The current validation only checks prefix and length for
the "value" variable (the block that tests if not value.startswith("sha256:") or
len(value) != 71) but doesn't enforce that the 64-character digest is
hexadecimal; update that validation to also verify the substring after "sha256:"
is 64 hex characters (e.g., with a regex like r"^sha256:[0-9a-fA-F]{64}$" or by
attempting int(digest, 16) and catching ValueError) and raise the same
ValueError message when it fails so only properly formatted sha256:<hex-digest>
strings are accepted.
---
Nitpick comments:
In `@tests/governance/test_tool_call_audit.py`:
- Around line 51-79: Add tests covering two edge cases: (1) ensure a
ToolCallAuditRecord with decision ToolCallDecision.MODIFY and either missing
modified_args_hash or modified_args_hash equal to args_hash raises a
ValidationError (use ToolCallAuditRecord, ToolCallDecision.MODIFY, and
hash_tool_arguments to construct the record); and (2) ensure
validate_tool_call_audit_record rejects raw arguments in metadata regardless of
casing by adding a record whose metadata contains keys like "Arguments" or
mixed-case variants with the raw args and asserting
validate_tool_call_audit_record raises a ValueError about "raw tool arguments".
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 024692b9-1691-4310-aadd-da995da7701a
📒 Files selected for processing (6)
docs/docs.jsondocs/mcp-agent-sdk/advanced/governance.mdxsrc/mcp_agent/governance/__init__.pysrc/mcp_agent/governance/tool_call_audit.pytests/governance/__init__.pytests/governance/test_tool_call_audit.py
| if not value.startswith("sha256:") or len(value) != 71: | ||
| raise ValueError("hashes must use the sha256:<hex-digest> format") | ||
| return value |
There was a problem hiding this comment.
Strengthen hash validation to enforce hexadecimal digest.
On Line 49, format validation checks prefix/length but not that the digest is valid hex. Values like sha256:zzzz... currently pass.
Suggested fix
import hashlib
import json
+import re
from enum import Enum
from typing import Any
@@
class ToolCallAuditRecord(BaseModel):
@@
+ _SHA256_RE = re.compile(r"^sha256:[0-9a-f]{64}$")
+
`@field_validator`("args_hash", "modified_args_hash")
`@classmethod`
def validate_hash(cls, value: str | None) -> str | None:
if value is None:
return value
- if not value.startswith("sha256:") or len(value) != 71:
+ if not cls._SHA256_RE.fullmatch(value):
raise ValueError("hashes must use the sha256:<hex-digest> format")
return value📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if not value.startswith("sha256:") or len(value) != 71: | |
| raise ValueError("hashes must use the sha256:<hex-digest> format") | |
| return value | |
| import hashlib | |
| import json | |
| import re | |
| from enum import Enum | |
| from typing import Any | |
| # ... (other code) | |
| class ToolCallAuditRecord(BaseModel): | |
| _SHA256_RE = re.compile(r"^sha256:[0-9a-f]{64}$") | |
| `@field_validator`("args_hash", "modified_args_hash") | |
| `@classmethod` | |
| def validate_hash(cls, value: str | None) -> str | None: | |
| if value is None: | |
| return value | |
| if not cls._SHA256_RE.fullmatch(value): | |
| raise ValueError("hashes must use the sha256:<hex-digest> format") | |
| return value |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/mcp_agent/governance/tool_call_audit.py` around lines 49 - 51, The
current validation only checks prefix and length for the "value" variable (the
block that tests if not value.startswith("sha256:") or len(value) != 71) but
doesn't enforce that the 64-character digest is hexadecimal; update that
validation to also verify the substring after "sha256:" is 64 hex characters
(e.g., with a regex like r"^sha256:[0-9a-fA-F]{64}$" or by attempting
int(digest, 16) and catching ValueError) and raise the same ValueError message
when it fails so only properly formatted sha256:<hex-digest> strings are
accepted.
| if key in {"args", "arguments", "raw_args", "raw_arguments"}: | ||
| return True |
There was a problem hiding this comment.
Raw-argument key detection is bypassable via casing variants.
On Line 88, matching only exact lowercase keys allows metadata like {"Arguments": {...}} to evade the raw-argument guard.
Suggested fix
def _contains_raw_arguments(value: Any) -> bool:
if isinstance(value, dict):
for key, nested_value in value.items():
- if key in {"args", "arguments", "raw_args", "raw_arguments"}:
+ key_normalized = str(key).strip().lower()
+ if key_normalized in {"args", "arguments", "raw_args", "raw_arguments"}:
return True
if _contains_raw_arguments(nested_value):
return True📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if key in {"args", "arguments", "raw_args", "raw_arguments"}: | |
| return True | |
| def _contains_raw_arguments(value: Any) -> bool: | |
| if isinstance(value, dict): | |
| for key, nested_value in value.items(): | |
| key_normalized = str(key).strip().lower() | |
| if key_normalized in {"args", "arguments", "raw_args", "raw_arguments"}: | |
| return True | |
| if _contains_raw_arguments(nested_value): | |
| return True |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/mcp_agent/governance/tool_call_audit.py` around lines 88 - 89, The key
check that currently compares key against the exact set {"args", "arguments",
"raw_args", "raw_arguments"} is bypassable by casing variants; update the guard
in the routine that inspects keys (the `key` variable and that set) to perform a
case-insensitive comparison (e.g., normalize the inspected key with key.lower()
or key.casefold() and ensure the set contains lowercased entries) so keys like
"Arguments" or "RAW_Arguments" are detected as raw-argument keys; also guard
that key is a str before normalizing to avoid attribute errors.
Summary
Tests
PYTHONPATH=src python -m pytest tests\governance\test_tool_call_audit.pypython -m py_compile src\mcp_agent\governance\tool_call_audit.py tests\governance\test_tool_call_audit.pypython -m json.tool docs\docs.jsonpython -m ruff check src\mcp_agent\governance\tool_call_audit.py tests\governance\test_tool_call_audit.pyCloses #654.
Summary by CodeRabbit
New Features
Documentation
Tests