Why agents need their own audit trail
Normal request logs show that POST /api/agent returned 200. They don't show that the agent
read an email from a stranger, then called search_files twice and send_email once. When
an agent misbehaves (prompt injection, a bug, a bad model update), you need to reconstruct the chain: which
untrusted content was in context, which tool calls followed, which ones were blocked, and who confirmed the
rest. Logging and monitoring tool use is one of the mitigations OWASP lists for LLM06 Excessive Agency.
What to record for each tool call
- Who and where: user id, tenant, session, and a
trace_idshared by every call in one agent run. - Which agent: agent name, model id and a prompt or config version, so you can tie behaviour changes to deployments.
- What: tool name and arguments, with secrets and personal data redacted.
- Decision: allowed, denied by policy, waiting for confirmation, or confirmed (and by whom).
- Outcome: success or error, result size, latency.
- Provenance: ids of untrusted inputs in the context at that moment (email ids, document ids, URLs). This is what links an action back to an injection.
Don't store full prompts and results by default: they hold user data and make the log a target. Store ids and hashes, and keep full transcripts only where you have a reason and a retention limit.
An append-only table in Postgres
create schema if not exists private;
create table private.agent_audit_log (
id bigint generated always as identity primary key,
at timestamptz not null default now(),
trace_id uuid not null,
user_id uuid,
agent text not null,
model text,
config_version text,
tool text not null,
args jsonb not null,
decision text not null
check (decision in ('allowed', 'denied', 'needs_confirmation', 'confirmed')),
confirmed_by uuid,
status text,
untrusted_sources text[] not null default '{}',
latency_ms int
);
create index on private.agent_audit_log (trace_id);
create index on private.agent_audit_log (user_id, at desc);
revoke all on private.agent_audit_log from public, anon, authenticated;
create or replace function private.audit_log_is_append_only()
returns trigger
language plpgsql
as $$
begin
raise exception 'agent_audit_log is append-only';
end;
$$;
create trigger agent_audit_log_no_change
before update or delete or truncate on private.agent_audit_log
for each statement execute function private.audit_log_is_append_only();The trigger stops accidental or application-level edits. A database owner can still drop it, so for tamper evidence also ship the rows to a separate log store that the application can't delete from.
Log in the dispatcher, not in each tool
Wrap every tool call in one place, so no tool can be called without a record, including denied and failed calls:
const SECRET_KEYS = /pass(word)?|token|secret|api[_-]?key|authorization/i;
function redact(args: Record<string, unknown>) {
return Object.fromEntries(Object.entries(args).map(([k, v]) =>
[k, SECRET_KEYS.test(k) ? '[redacted]' : typeof v === 'string' && v.length > 500 ? v.slice(0, 500) + '…' : v]));
}
export async function dispatch(ctx: AgentContext, tool: string, args: Record<string, unknown>) {
const started = Date.now();
const decision = policy(ctx, tool, args); // 'allowed' | 'denied' | 'needs_confirmation'
let status = decision === 'allowed' ? 'error' : decision;
try {
if (decision !== 'allowed') return { status: decision };
const result = await TOOLS[tool](ctx.user, args);
status = 'ok';
return result;
} finally {
await admin.schema('private').from('agent_audit_log').insert({
trace_id: ctx.traceId, user_id: ctx.user.id, agent: ctx.agent, model: ctx.model,
config_version: ctx.configVersion, tool, args: redact(args), decision, status,
untrusted_sources: ctx.untrustedSources, latency_ms: Date.now() - started,
});
}
}The insert uses a server-only client. Expose the private schema to that client only, or write through a security definer function instead.
Questions the log should answer
-- everything one agent run did, in order
select at, tool, decision, status, untrusted_sources
from private.agent_audit_log where trace_id = $1 order by at;
-- outbound actions taken right after reading untrusted content
select user_id, tool, at, untrusted_sources
from private.agent_audit_log
where tool in ('send_email', 'share_file') and cardinality(untrusted_sources) > 0
order by at desc limit 50;
-- users hitting the policy wall (probing or injection attempts)
select user_id, count(*) as denied_today
from private.agent_audit_log
where decision = 'denied' and at > now() - interval '1 day'
group by user_id order by denied_today desc limit 20;Alert on spikes in denied calls, outbound actions after untrusted input, and tools a user has never used before.
How to verify
Run an agent session with a canary injection in a test email. The log shows every call in that trace, the blocked send_email with decision = 'denied' or 'needs_confirmation', and the email id in untrusted_sources. update private.agent_audit_log set tool = 'x' fails with the append-only error, and no API key appears in args.
Related guides
- LLM tool calls with over-broad permissions – a least-privilege pattern that holds
- Indirect prompt injection in email and calendar agents – one message, full access
- MCP server security basics – untrusted tool descriptions, local code and token scope
- Prompt injection through retrieved documents (RAG) – what it is and how to contain it
More in AI agent and LLM app security · all guides