Sub topic 13
Logging tool calls for detection and review
This chapter assumes you know how LLM tool calling works, can read short Python and JSON snippets, and have seen the earlier controls in this tutorial: allowlists, authorization in code, and human approval. Those controls limit what an agent can do. Audit logging records what it actually did. You need that record to detect abuse, investigate incidents, and find permissions that are too wide or never used.
Why log at the enforcement point
Log where the runtime decides whether a tool call runs, not in the prompt and not in the model's own output. The model's text can be wrong, incomplete, or shaped by injected content. The runtime sees the real tool name, the real arguments, and the real decision.
Log denied calls as well as allowed ones. A denied call is often the best signal you have. If a documentation agent suddenly asks for send_email, something in its input probably told it to.
What to record
Each tool call should produce one structured record. Use JSON lines so the records are easy to search.
| Field | Why it matters |
|---|---|
| `timestamp` | Orders events and supports time-window queries |
| `session_id`, `task_id` | Groups calls from one agent run |
| `user_id` | Shows whose authority the call used |
| `tool` | Which tool was requested |
| `args` | What the model asked for, after redaction |
| `decision` | `allowed`, `denied`, or `approved_by_human` |
| `reason` | Which rule produced the decision |
| `outcome` | Success, error, and result size |
Record the size of a result rather than the result itself. Full results can contain private data, and a log that copies them becomes a second place to leak from.
Wrapping the runtime
This code extends the earlier run_tool_call pattern. It writes a record for every request, including denials and errors.
import json
import logging
import time
audit = logging.getLogger("agent.audit")
audit.setLevel(logging.INFO)
audit.addHandler(logging.StreamHandler())
SENSITIVE_KEYS = {"password", "token", "api_key", "body"}
def redact(args: dict) -> dict:
return {
k: "[REDACTED]" if k in SENSITIVE_KEYS else v
for k, v in args.items()
}
def logged_tool_call(name, args, allowed, tools, session_id, user_id):
record = {
"ts": time.time(),
"session_id": session_id,
"user_id": user_id,
"tool": name,
"args": redact(args),
}
if name not in allowed:
record.update(decision="denied", reason="not in allowlist")
audit.info(json.dumps(record))
raise PermissionError(f"tool {name!r} is not allowed for this task")
try:
result = tools[name](**args)
record.update(decision="allowed", outcome="ok", result_size=len(str(result)))
return result
except Exception as exc:
record.update(decision="allowed", outcome="error", error=type(exc).__name__)
raise
finally:
if record.get("decision") == "allowed":
audit.info(json.dumps(record))
tools = {"search_docs": lambda query: f"results for {query}"}
logged_tool_call("search_docs", {"query": "rotate API keys"},
{"search_docs"}, tools, "s-1", "alice")The finally block means a failing tool still leaves a record.
Protecting the log
Treat the log as sensitive and as evidence.
- Redact secrets and personal data before writing. Never log credentials.
- Send logs to a store the agent's credentials cannot write to or delete from. An agent that can edit its own audit trail defeats the purpose.
- Set a retention period that matches your review and incident needs.
- Escape or encode model-controlled strings. Arguments can contain newlines or markup meant to confuse a reader or a log viewer. Structured JSON handles this better than free text.
Using the log for detection
Logs only help if something reads them. Start with a few simple alerts:
- Any denied call, especially to a high-risk tool.
- A spike in call volume compared with the usual rate for that task.
- A read of private data followed by an outbound call in the same session, which matches the data-flow pattern from the earlier chapter.
- Repeated approval requests that a human rejected.
Using the log for review
Logs also tell you which permissions to remove. If an allowed tool has not been called in months, it is a candidate for removal. If a task always triggers denials for the same tool, either the task needs that tool or the prompt is steering the model wrongly. The next chapter builds on this when it covers permission review and adversarial testing.
Exercise
An agent's log shows an allowed read of a customer file, then a denied call to send_email two seconds later, in the same session. What does this suggest, and which control worked?
Show answer
It suggests the agent may have been steered, for example by injected content, to send private data out. The deterministic allowlist worked because it refused the call. You should still investigate the input that preceded the call and check whether other sessions show the same pattern.
Exercise
Why should the audit log live in a store the agent's credentials cannot modify?
Show answer
If a compromised or misdirected agent could edit or delete its own records, it could hide its actions, and the log would no longer be trustworthy evidence.