Skip to content

Add tool call governance audit records - #684

Open
mindbomber wants to merge 1 commit into
lastmile-ai:mainfrom
mindbomber:codex/mcp-agent-tool-governance-audit
Open

Add tool call governance audit records#684
mindbomber wants to merge 1 commit into
lastmile-ai:mainfrom
mindbomber:codex/mcp-agent-tool-governance-audit

Conversation

@mindbomber

@mindbomber mindbomber commented May 7, 2026

Copy link
Copy Markdown

Summary

  • add a vendor-neutral tool-call audit record for governance decisions
  • hash tool arguments before audit storage and reject raw arguments in metadata
  • add docs for governance/audit-trail usage and focused tests for allow, deny, modify, and review cases

Tests

  • PYTHONPATH=src python -m pytest tests\governance\test_tool_call_audit.py
  • python -m py_compile src\mcp_agent\governance\tool_call_audit.py tests\governance\test_tool_call_audit.py
  • python -m json.tool docs\docs.json
  • python -m ruff check src\mcp_agent\governance\tool_call_audit.py tests\governance\test_tool_call_audit.py

Closes #654.

Summary by CodeRabbit

  • New Features

    • Added governance framework for auditing agent tool call decisions with support for allow, deny, modify, and needs review states.
    • Implemented validation to ensure audit records contain decision metadata while preventing exposure of sensitive arguments.
  • Documentation

    • Added comprehensive guide on governance and audit trails for policy decisions around agent tool calls.
  • Tests

    • Added test coverage for governance audit functionality.

@coderabbitai

coderabbitai Bot commented May 7, 2026

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

A 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.

Changes

Tool-Call Governance and Audit Layer

Layer / File(s) Summary
Data Model
src/mcp_agent/governance/tool_call_audit.py (lines 1–41)
New ToolCallDecision enum (ALLOW, DENY, MODIFY, NEEDS_REVIEW) and ToolCallAuditRecord Pydantic model with schema versioning, event/tool/decision tracking, SHA-256 argument hashes, policy references, evaluation timestamp, and decision metadata.
Validation & Hashing
src/mcp_agent/governance/tool_call_audit.py (lines 44–94)
hash_tool_arguments() computes deterministic SHA-256 hashes via canonical JSON serialization; validate_tool_call_audit_record() enforces decision-specific rules (reason required for DENY/NEEDS_REVIEW, modified_args_hash required for MODIFY, metadata cannot contain raw argument payloads); _contains_raw_arguments() recursively scans for leaked raw arguments.
Module Initialization
src/mcp_agent/governance/__init__.py, tests/governance/__init__.py
Packages are initialized with module docstrings.
Documentation
docs/mcp-agent-sdk/advanced/governance.mdx, docs/docs.json
New governance guide documents the audit record schema, provides a Python usage example, and clarifies storage best practices (hashes and metadata only, no raw prompts/arguments/credentials). Navigation entry added to docs.json.
Tests
tests/governance/test_tool_call_audit.py
Five test cases verify deterministic hashing, ALLOW record validation, mandatory reason for DENY, mandatory modified_args_hash for MODIFY, and rejection of raw tool arguments in metadata.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • StreetLamb
  • saqadri

Poem

🐰 A trail of decisions, hashed clean and true,
No secrets in metadata, no leaks to pursue—
Governance records that tell the whole tale,
Of what agents intended, and never shall fail. 🔐

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Add tool call governance audit records' accurately and concisely summarizes the main change: introducing audit record structures and functionality for governance decisions on tool calls.
Linked Issues check ✅ Passed The PR successfully addresses all key objectives from issue #654: implements a vendor-neutral audit record schema for governance decisions, enables policy enforcement by supporting decision states (ALLOW/DENY/MODIFY/NEEDS_REVIEW), provides audit trails for compliance visibility, and includes documentation and tests.
Out of Scope Changes check ✅ Passed All changes are directly scoped to the governance audit feature: new modules for tool-call audit records and decision enums, comprehensive documentation, and focused test coverage. No unrelated modifications detected.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
tests/governance/test_tool_call_audit.py (1)

51-79: ⚡ Quick win

Add tests for the two key guardrail edge cases.

Current tests miss: (1) MODIFY with 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

📥 Commits

Reviewing files that changed from the base of the PR and between f62d849 and cb462c7.

📒 Files selected for processing (6)
  • docs/docs.json
  • docs/mcp-agent-sdk/advanced/governance.mdx
  • src/mcp_agent/governance/__init__.py
  • src/mcp_agent/governance/tool_call_audit.py
  • tests/governance/__init__.py
  • tests/governance/test_tool_call_audit.py

Comment on lines +49 to +51
if not value.startswith("sha256:") or len(value) != 71:
raise ValueError("hashes must use the sha256:<hex-digest> format")
return value

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

Suggested change
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.

Comment on lines +88 to +89
if key in {"args", "arguments", "raw_args", "raw_arguments"}:
return True

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

Suggested change
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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add governance layer for agent tool calls and decisions

1 participant