Your auth check passed. Now prove what the agent did.
An AI agent with a valid token can still do something nobody asked for. How to scope it and prove what it did.

An AI agent calls your API with a valid token. Authentication passes. The token’s scopes allow the call. The handler runs, the write lands, the response is a clean 201.
Nobody asked for it.
That’s the failure mode people are running into as agents get tool access to real APIs. A recent dev.to write-up put it plainly: “Authentication answers who. Authorization answers what they’re allowed to do. Neither one answers whether this specific action was actually intended.” In the author’s demo, a paraphrased prompt injection got past injection detection, the model tried the tool call, and the only thing that stopped the database write was an allow-list inside the tool’s own execute().
And it isn’t only about intent. Agents retry. In a separate crash test of agent tool execution on Node 24, 100 logical operations with a worker killed after every tenth effect produced 110 side effects: the 100 intended ones plus 10 duplicates, because the provider had already applied the action when the worker died, and the retry sent it again. With the completion marker written before the call instead, the same test came out the other way: 90 effects and 10 operations silently lost. (The crashes were injected on purpose, so these are not production failure rates. They show the shape of the bug, not how often it happens.)
So there are two questions you need to answer about any agent hitting your API:
- Should this action have been allowed to happen at all?
- When something odd happens anyway, can you reconstruct exactly what the agent did, in order?
The first is authorization design. The second is an audit trail. This post covers both, in that order, because logging is how you find out what went wrong. It is not how you stop it.
1. Fix authorization first
Give the agent its own identity
If an agent acts with the user’s session token, every request it makes looks exactly like the user clicked something. You can’t scope it, rate-limit it or tell it apart in a log.
Issue agents their own credentials, linked to the user they act for. The token should carry both: who the agent is, and on whose behalf it’s acting.
// Illustrative claims for an agent token
{
sub: 'agent:support-bot',
act_for: 'user_19',
scope: ['orders:read', 'refunds:create'],
run: 'run_7f2c' // one id per agent session or conversation
}
Scope to the job, not the user
A user might be allowed to delete orders. The support agent probably shouldn’t be. Give the agent token the smallest set of scopes the task needs, and check them in the handler, not just at the gateway.
Put a deterministic check right before the side effect
A tool call is a proposal from the model. Treat it like untrusted input. For anything that moves money, deletes data, changes permissions or sends a message to the outside world, add an application-level check at the point where the side effect happens:
// Illustrative: a gate in front of a destructive action
const DESTRUCTIVE = new Set(['DELETE /v1/orders/:id', 'POST /v1/refunds']);
function requireConfirmation(req, res, next) {
const action = `${req.method} ${req.route.path}`;
if (req.auth.sub.startsWith('agent:') && DESTRUCTIVE.has(action)) {
if (!req.get('x-user-confirmation')) {
return res.status(403).json({ error: 'confirmation_required', action });
}
}
next();
}
The point is that the decision doesn’t depend on the model behaving. If the check denies the call, test that no write happened, not just that a denial was logged.
Make writes idempotent
The 110-from-100 result is a retry problem, and the crash test’s fix is the standard one: generate an operation id once, persist it before execution, send it as an idempotency key on every retry, and have the receiving side return the stored result instead of acting twice.
// Illustrative: idempotent POST handler
app.post('/v1/refunds', async (req, res) => {
const key = req.get('idempotency-key');
if (!key) return res.status(400).json({ error: 'idempotency_key_required' });
const prior = await db.idempotency.find(req.auth.sub, key);
if (prior) {
if (prior.bodyHash !== hash(req.body)) {
return res.status(422).json({ error: 'key_reused_with_different_body' });
}
return res.status(prior.status).json(prior.response);
}
const refund = await refunds.create(req.body);
await db.idempotency.save(req.auth.sub, key, hash(req.body), 201, refund);
res.status(201).json(refund);
});
Two details from the crash test are worth keeping: don’t generate a fresh key per attempt (that’s just a retry with extra steps), and reject a reused key with different parameters instead of running a different action under it.
2. Then build the audit trail
Here’s the useful part: every agent tool call that touches your API is an HTTP request. You don’t need a separate agent-tracing system to see what an agent did. You need your request log to know which requests belong to which agent session.
Tag every request with three things:
- The user the agent acted for
- The agent that made the call
- The run (session or conversation id), so one session reads back in order
Then “what did the agent do in run_7f2c?” is a single filter, and the answer is a timeline: what it read, what it wrote, what got denied, and what it retried.
That timeline is what makes the failures above visible. A duplicate refund is two POST /v1/refunds with the same body, five seconds apart, under the same run id. An unrequested action is a write that doesn’t match anything the user asked for in that conversation. Without the run id, both look like normal traffic from a valid token.
3. What to alert on
Once requests are tagged, these become queries rather than guesses:
- Write bursts from one agent token. An agent stuck in a loop looks like a burst of
POST/PUT/DELETEfrom one credential in a short window. - Actions outside an agent’s normal set. If the support agent has only ever called
GET /v1/orders/*andPOST /v1/refunds, aDELETEfrom it is worth a look even when it’s denied. Denials are signal. - Retries that create duplicates. The same method, endpoint and body under the same run id, both returning
2xx. If you added idempotency keys, a reused key with a different body is also worth flagging. - A run that touches far more records than the task needed. One refund request shouldn’t read 400 customers.
4. Doing this with ApiTraffic
If you run ApiTraffic on a Node API, most of the audit layer is a few lines. (Authorization, scoping and idempotency are still your code. That part doesn’t come from a logging tool.)
Tag requests from middleware. Register ApiTraffic before your routes, then call tag() once your auth middleware knows who’s calling:
const express = require('express');
const apitraffic = require('@apitraffic/node');
const app = express();
app.use(express.json()); // body parsers first
app.use(apitraffic.express()); // then ApiTraffic, before your routes
app.use(authMiddleware); // sets req.auth
app.use((req, res, next) => {
apitraffic.tag('userId', req.auth?.act_for ?? req.auth?.sub);
apitraffic.tag('agentId', req.auth?.sub?.startsWith('agent:') ? req.auth.sub : undefined);
apitraffic.tag('runId', req.auth?.run);
next();
});
tag() never throws, and a null or undefined value just means no tag. Tags are searchable, so one agent session is a filter in the request log:
tag:runId == "run_7f2c"
tag:agentId == "agent:support-bot" AND method == "DELETE"
See the agent’s own outbound calls. If the agent runtime lives in your Node service, the SDK also records the outbound calls it makes (http/https, global fetch, and clients built on them like axios), linked to the inbound request that triggered them. So a tool call that hits a third-party API shows up under the request that started it.
Rate-limit per agent credential. Firewall rate limits can key by a header value instead of IP. Key by the header that carries the agent’s token and a looping agent gets a 429 with Retry-After instead of a burst of refunds. Header values are hashed, not stored.
Optionally, inspect what the agent sends out. Outbound protection can inspect payloads headed to AI providers and agent-tool destinations, and refuse ones carrying credentials or bulk personal data. The managed rule set also has Prompt Injection & AI Abuse and Agent & Tool Abuse categories. Run them in Monitor mode first and see what they’d catch before you enforce anything.
Alert on the queries. Save a query as a stream view and attach a workflow, and matching requests start it, for example a DELETE from any agentId.
Checklist: an agent-ready API
- [ ] Agents use their own credentials, linked to the user they act for
- [ ] Agent tokens carry only the scopes the task needs, checked in the handler
- [ ] Destructive actions need a deterministic check at the point of the side effect, not the model’s judgment
- [ ] Denied calls are tested to produce no write
- [ ] Every write accepts an idempotency key, persisted before execution and reused on retry
- [ ] A reused key with different parameters is rejected
- [ ] Every request is tagged with user, agent and run id
- [ ] You can pull one agent session as an ordered list of requests
- [ ] Alerts exist for write bursts, unusual actions and duplicate writes
- [ ] Per-agent rate limits, so a loop hits a
429before it hits your database
A 201 tells you the write worked. It doesn’t tell you anyone wanted it. That takes authorization you can reason about, and a request log that can show you the whole session.
See what’s hitting your API: apitraffic.io
Keep reading
API key security for Node APIs: prefixes, hashing, scopes and rotation
A customer just pushed their API key to a public repo. Can you tell if anyone used it, and could a database leak expose every key? Design API key security in Node properly: prefixes, hashing, scopes and rotation.
BOLA vulnerability in Node APIs: how to fix IDOR and catch it in your logs
Change one digit in a URL and get another customer's invoice. Here is how to fix BOLA and IDOR structurally and spot someone probing for it before they find a gap.
What small Node teams should log in the AI-attack era
Bots are now more than half of web traffic, and 27% of attacks target APIs and identity systems. You don't need a security team to see it, just the right fields on every request. Here's the minimum to capture, five patterns to watch, and when to block.