Sub topic 13
Logging Tool Calls for Detection and Review
This chapter covers audit logging of tool calls. It assumes you know how LLM tool calling works, how API tokens and roles work, and that you can read short Python and JSON snippets. It builds on the earlier chapters on enforcing authorization in code and on human approval. Those controls decide what an agent may do. Logging records what it did, so you can notice misuse and reconstruct events afterward.
Why logging belongs in a least-privilege design
Least privilege reduces what an agent can do. It never reduces the chance of error to zero. A prompt injection may still steer the agent toward an allowed tool with allowed but harmful arguments. A permission may be broader than you intended. A new tool may be added without a review.
Logging serves three purposes:
- Detection. Spot unusual behavior while it happens, such as a documentation agent suddenly reading hundreds of files.
- Review. Answer "what did the agent do, and why?" after an incident or complaint.
- Improvement. Find permissions that are never used (candidates for removal) and denials that show the agent reaching for tools it should not have.
Logging is a detective control. It does not block anything. It is useful only when the log is complete, trustworthy, and actually read.
What to record for each tool call
Log at the point where your runtime executes tools, which is the same place where the allowlist and argument checks run. Do not rely on the model to report its own actions. A model can be wrong or manipulated, and its text output is not a record.
A useful event answers who, what, when, with what, and with what outcome.
| Field | Purpose |
|---|---|
| `timestamp` | Order events and correlate with other systems. |
| `session_id`, `task_id` | Group all calls from one agent run. |
| `user_id` | The person on whose behalf the agent acted. Essential for confused-deputy investigations. |
| `tool` | Which tool was requested. |
| `args` (redacted) | The arguments, with secrets and sensitive values removed or hashed. |
| `decision` | `allowed`, `denied`, `approved`, or `rejected_by_human`. |
| `reason` | Why a call was denied, such as `tool_not_in_allowlist` or `path_outside_workspace`. |
| `approver` | Who approved a high-risk call, if anyone. |
| `result_status` | Success, error type, or timeout. |
| `result_size` | Bytes or rows returned. Useful for spotting bulk reads. |
| `duration_ms` | Latency, which helps find hangs and abuse. |
Log denied calls as well as allowed ones. A denial is often the most valuable signal. If a task that only answers documentation questions repeatedly requests send_email, something is wrong with the prompt, the input, or the model.
A structured logging wrapper
Write one wrapper around the tool dispatcher so that no call can skip logging. The example below extends the allowlist pattern from earlier chapters. It emits one JSON object per line, which is easy to ship to a log service and to query.
import json
import time
import uuid
SENSITIVE_KEYS = {"password", "token", "api_key", "authorization"}
def redact(args: dict) -> dict:
return {
k: "[REDACTED]" if k.lower() in SENSITIVE_KEYS else v
for k, v in args.items()
}
def audit(event: dict) -> None:
# In production, send this to an append-only log store.
print(json.dumps(event, sort_keys=True))
def search_docs(query: str) -> str:
return f"results for {query}"
TOOLS = {"search_docs": search_docs}
def run_logged(name, args, allowed, user_id, session_id):
event = {
"event_id": str(uuid.uuid4()),
"timestamp": time.time(),
"session_id": session_id,
"user_id": user_id,
"tool": name,
"args": redact(args),
}
start = time.monotonic()
try:
if name not in allowed:
event.update(decision="denied", reason="tool_not_in_allowlist")
raise PermissionError(f"tool {name!r} is not allowed")
event["decision"] = "allowed"
result = TOOLS[name](**args)
event.update(result_status="ok", result_size=len(str(result)))
return result
except PermissionError:
event["result_status"] = "denied"
raise
except Exception as exc:
event.update(result_status="error", error_type=type(exc).__name__)
raise
finally:
event["duration_ms"] = round((time.monotonic() - start) * 1000, 2)
audit(event)
run_logged("search_docs", {"query": "rotate API keys"},
allowed={"search_docs"}, user_id="u-1042", session_id="s-77")
try:
run_logged("send_email", {"to": "[email protected]"},
allowed={"search_docs"}, user_id="u-1042", session_id="s-77")
except PermissionError:
passThe finally block is the key detail. It writes an event whether the call succeeded, failed, or was denied. A wrapper that logs only on success leaves gaps exactly where you most need evidence.
Protecting the log itself
Logs are a data store, so they need least privilege too.
- Redact secrets. Tool arguments and results can contain API keys, passwords, personal data, or the private documents the agent read. Redact by key name as shown above, and also scan values for token-like patterns. Prefer logging a hash or a size over logging full content.
- Limit who can read logs. A log that holds customer data is as sensitive as the database it came from.
- Make logs tamper-resistant. The agent's own credentials must not be able to write to, edit, or delete the audit log, other than appending through a narrow path. If a compromised agent can erase its tracks, the log is worth little. Use an append-only or write-once store and send events to a separate account or service.
- Set retention deliberately. Keep logs long enough for investigations and compliance, and delete them on a schedule so you are not holding sensitive data forever.
The IAM idea is the same as for tools. Give the agent runtime permission only to add records:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "logs:PutLogEvents",
"Resource": "arn:aws:logs:us-east-1:123456789012:log-group:/agent/audit:*"
}
]
}This grants no permission to read, delete, or change retention on the log group. Those actions belong to a separate security role.
Following one task across events
A single agent run produces many events. Correlation identifiers let you rebuild the sequence. Use the same session_id for every call in a run, and add a parent_id or step number if tools can trigger other tools. If the agent runs on behalf of a user, always record that user.
The diagram shows where events are emitted in the runtime.
Notice that the log receives events from every branch, including refusals and approval decisions.
Turning logs into detection
Raw logs do nothing until someone or something looks at them. Start with a few simple rules that map to the threats in earlier chapters.
| Signal | What it may indicate |
|---|---|
| A denied call to a tool outside the task's allowlist | Prompt injection or a misconfigured prompt |
| Repeated `path_outside_workspace` denials | Path traversal attempts |
| Spike in call count or `result_size` in one session | Bulk data collection or a loop |
| A read of private data followed by an outbound call such as `send_email` | Possible exfiltration |
| Calls at unusual hours or from a user who normally never uses the agent | Misuse of an account or a session |
| Many human rejections of one tool | The agent keeps proposing actions people do not want |
| Tool that has not been called in 90 days | A permission to remove |
Here is a small detector for one rule: a session that has read private data and then makes an outbound call.
PRIVATE_READS = {"read_file"}
OUTBOUND = {"send_email", "http_post"}
def find_exfil_risk(events: list[dict]) -> list[str]:
risky = set()
saw_private = {}
for e in sorted(events, key=lambda e: e["timestamp"]):
sid = e["session_id"]
if e["tool"] in PRIVATE_READS and e.get("result_status") == "ok":
saw_private[sid] = True
elif e["tool"] in OUTBOUND and saw_private.get(sid):
risky.add(sid)
return sorted(risky)
events = [
{"timestamp": 1, "session_id": "s-1", "tool": "read_file", "result_status": "ok"},
{"timestamp": 2, "session_id": "s-1", "tool": "send_email", "result_status": "denied"},
{"timestamp": 3, "session_id": "s-2", "tool": "send_email", "result_status": "ok"},
]
print(find_exfil_risk(events)) # ['s-1']Session s-1 is flagged even though the email was denied, because the attempt matters. Session s-2 is not flagged because it read nothing private first.
Common mistakes
- Logging only successes. You lose the denied attempts that reveal attacks.
- Trusting model-written summaries. Record what the runtime executed, not what the model says it did.
- Logging secrets in arguments. A credential in a log file is a new leak path.
- Letting the agent write to the log with broad rights. It should append only.
- No owner and no alerts. Logs nobody reads give false comfort. Assign a person or team, and route high-signal rules to an alert.
- Alert fatigue. Alert on a small set of high-confidence rules first. Review lower-confidence signals in a periodic report.
- Missing user identity. Without it, you cannot tell whose authority a call used.
- Logs on the same host the agent can reach. A sandbox escape then reaches the evidence too.
Exercise
An agent that answers documentation questions has an allowlist of search_docs and read_file. Your log shows one session with these events in order: read_file (ok), read_file (ok), send_email (denied, reason tool_not_in_allowlist). Name two things this tells you, and one change you would make to the logging or alerting setup.
Show answer
The denial shows the model asked for a tool outside its task, which suggests prompt injection or a bad prompt, and the allowlist stopped it. The earlier reads show the session had touched private data before the outbound attempt, which matches an exfiltration pattern, so the session deserves review. A reasonable change is to alert on any denied call to an outbound tool that follows a private read in the same session. Also check that the reads were within the expected workspace and that the log records the user on whose behalf the agent acted.
Exercise
Why should the agent runtime's credentials be unable to delete or modify entries in the audit log?
Show answer
If the agent is compromised, for example through prompt injection, an attacker could use its credentials to erase or alter the record of what it did. An append-only permission keeps the evidence intact, so the log remains reliable for detection and review.