Audit logs for AI agent tool calls – record enough to answer “why did it do that?”

By Abheesht Tripathi · Published

Risk: an agent sent an email, deleted a record or leaked data, and nobody can say which input caused it, who approved it, or what else it did

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

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

More in AI agent and LLM app security · all guides