Join our Newsletter — 33% off our NHI Course
Home› Guides› API Design for AI Agent Consumers: Securing APIs…
Guide Web & API Security

API Design for AI Agent Consumers: Securing APIs Agents Call

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, edited by Lalit Choda Updated 8 November 2026 14 min read
On this page

APIs designed for human-driven applications assume a developer read the documentation, a person clicked the button and retries are rare, and AI agents break all three assumptions. An agent chooses operations from their descriptions at run time, chains calls quickly, retries on ambiguous errors and acts for a user who may not be watching. That changes what an API owner must build: how agent clients are identified, how delegated authority is scoped, how retries are made safe, how destructive operations are gated and how abuse is told apart from legitimate automation. This guide is for API product owners, platform engineers and security architects who publish APIs that agents call directly, through MCP servers or through agent frameworks. Web traffic classification for bots and browsing agents is covered in the Bot vs AI Agent Traffic Management Guide, and general API controls in the API Security Guide.

Key takeaways

  • Identify the agent and the user separately. Every call should tell you which agent client made it and on whose behalf, so you can scope, limit and revoke each independently.
  • Scope by task, not by account. Account-wide tokens are the root of most agent incidents; use narrow scopes, audience-restricted tokens and fine-grained authorisation details.
  • Make retries safe by design. Agents retry. Idempotency keys on every non-idempotent operation turn a retry storm into a no-op instead of duplicate orders or payments.
  • Gate destructive operations in the API, not the prompt. Soft deletes, confirmation steps and step-up authorisation must be enforced server-side, because an agent's judgement is not a control.
  • Descriptions are part of the attack surface. Agents act on your operation descriptions and error messages, so write them for safe behaviour and treat them as security-relevant content.

What changes when the consumer is an agent

Assumption in human-era API designWhat agents do insteadDesign consequence
A developer reads the docs once and hard-codes callsThe model selects operations from descriptions at run timeOperation names, descriptions and parameter schemas steer behaviour; ambiguity becomes wrong calls
A human confirms risky actions in the UIThe agent calls the API directly, often unattendedConfirmation and recovery must exist in the API itself
Retries are rare and handled by client codeAgents retry on timeouts, vague errors and their own reasoningIdempotency and duplicate detection on all writes
One token per applicationMany agent instances act for many users through one platformDistinguish client, agent instance and user in every call
Rate limits protect capacityAgents fan out, loop and chain calls at machine speedLimits per user and per agent, cost-aware quotas, loop detection
Error messages are for developersError text is fed back into the model's contextMachine-readable, non-sensitive errors that tell the agent what to do next

The OWASP API Security Top 10 2023 still applies in full. Three entries become sharper with agents: API4:2023 Unrestricted Resource Consumption (agent loops and fan-out), API6:2023 Unrestricted Access to Sensitive Business Flows (automated purchasing, booking and messaging) and API10:2023 Unsafe Consumption of APIs, which now applies to the agent platforms consuming your responses as well as to your own integrations.

Identifying agent clients

An API owner needs three identities on every call: the client software (the agent platform or application), the specific agent or workload instance, and the human or organisation on whose behalf it acts. Collapsing them into one API key makes it impossible to revoke a misbehaving agent without cutting off the user, or to limit one tenant's agents without affecting others.

MechanismWhat it identifiesStrengthsLimits
Static API keyAn account or projectSimple to issueBearer secret, usually account-wide, no user context, often leaked. See the API Keys vs OAuth Tokens Guide
OAuth client credentialsThe agent client acting as itselfStandard, revocable, scopedNo end-user context; suits autonomous back-office agents. See the Machine-to-Machine OAuth (Client Credentials) Guide
OAuth authorisation code with PKCEClient plus consenting userDelegated, user-scoped, user can revokeNeeds an interactive consent step
Token exchange (RFC 8693)Subject plus actor (the agent acting for the user)Expresses delegation chains with the act claimRequires authorisation server support and policy for allowed exchanges. See the OAuth Token Exchange and Delegation Guide
Sender-constrained tokens (mTLS RFC 8705, DPoP RFC 9449)Holder of a keyStolen tokens cannot be replayed without the keyKey management on the agent runtime. See the DPoP Guide
Signed HTTP requests from agent platformsThe operator of a browsing or calling agentVerifiable without shared secretsSpecifications still maturing; covered in the bot traffic guide
  • Register agent clients deliberately: if you allow dynamic client registration, apply policy to it (allowed redirect URIs, software statements, rate limits on registration). See the OAuth Dynamic Client Registration Security Guide.
  • Carry agent context: require a stable agent or client identifier in the token and log it on every request, alongside the user subject.
  • Avoid user-agent strings as identity: they are self-asserted and trivially copied.

Where identity fits

Each agent is a non-human identity with an owner, a purpose and a lifecycle. Issue credentials per agent, not per team; record the human owner; expire unused agent clients; and make revocation of one agent possible without affecting the user's other sessions. See the Agent Identity and Access Guide.

Delegated scopes and authorisation

RFC 9700, the OAuth 2.0 Security Best Current Practice (BCP 240, January 2025), recommends restricting token privileges to the minimum required, restricting tokens to specific resources and actions with scope or authorization_details (RFC 9396), audience-restricting tokens to a specific resource server that checks the audience on every request, and using sender-constrained tokens. Each recommendation matters more when the client is an agent that can be steered by injected content.

  • Design scopes around tasks: invoices:read, invoices:draft and invoices:send rather than one invoices scope. Agents rarely need send or delete, and splitting them lets users grant drafting without sending. See the OAuth Scope Design Guide.
  • Use rich authorisation requests for high-value actions: an authorization_details object can bind a token to one payment amount, one recipient or one record set. See the OAuth Rich Authorization Requests (RAR) Guide.
  • Enforce audience: reject tokens not issued for your API. The MCP authorization specification (version 2025-06-18) requires MCP clients to send the RFC 8707 resource parameter, requires MCP servers to validate that tokens were issued for them, and forbids passing a received token through to upstream APIs. Apply the same rules if your API sits behind an MCP server. See the MCP Authorisation Specification Guide.
  • Keep tokens short-lived: minutes for access tokens, rotation or sender-constraint for refresh tokens.
  • Authorise every object: agents will try identifiers they find in context. Object-level checks (API1:2023 Broken Object Level Authorization) must hold regardless of how the caller learned the ID.
  • Step up for sensitive actions: return an authorisation challenge that requires fresh user approval, through the OAuth step-up pattern or an out-of-band approval such as OIDC CIBA. See the OAuth Step-Up Authentication Challenge Guide and the OIDC CIBA Guide.

Idempotency and safe retries

RFC 9110 defines GET, HEAD, OPTIONS, PUT and DELETE as idempotent; POST and PATCH are not. The IETF HTTPAPI working group's Idempotency-Key header draft (draft-ietf-httpapi-idempotency-key-header-08, an Internet-Draft dated 22 October 2026, checked 8 November 2026) standardises a header that makes non-idempotent requests safe to retry. Because it is still a draft, treat details as subject to change, but the core behaviour is stable and widely implemented in payment APIs.

SituationDraft guidanceWhy agents need it
Required header missing400 Bad Request, pointing to documentationForces agent frameworks to send keys
Same key, different payload422 Unprocessable ContentCatches an agent reusing a key after changing its mind
Retry while original is still processing409 ConflictStops parallel duplicate execution from fan-out
Retry after completionRespond consistently with the original outcomeThe agent learns the action already happened rather than repeating it
  • Require keys on every operation with side effects: payments, orders, messages, provisioning.
  • Fingerprint payloads server-side so a reused key with a changed body is detected.
  • Publish the key expiry policy and scope keys per client and per user, so one tenant cannot collide with another.
  • Return the operation status and a resource identifier the agent can poll, instead of forcing it to guess whether a timed-out call succeeded.

Rate limits, quotas and cost controls

Algorithms and enforcement points are covered in the Rate Limiting and API Abuse Guide. For agent consumers, change what you limit on.

  • Partition limits by user, by agent client and by tenant, so one runaway agent does not exhaust a shared key.
  • Limit cost, not only calls: expensive searches, exports and AI-backed endpoints need weighted quotas.
  • Cap business flows: limits per hour on sends, purchases and invitations address API6:2023 directly.
  • Tell the agent the limits: return 429 with Retry-After. The HTTPAPI RateLimit header draft (draft-ietf-httpapi-ratelimit-headers-11, dated 23 May 2026) defines RateLimit-Policy and RateLimit fields with quota, window and partition key parameters; it is still a working group draft, so pin to the version you implement.
  • Detect loops: the same agent repeating an identical failing call is a signal to block that client briefly and alert its owner.

Destructive operations and human approval

The PocketOS Database Deletion 2026 is the reference case: a coding agent found an account-scoped token created for domain management and used it to call a volume deletion mutation that ran immediately with no undo, deleting a production volume; the founder reported that its volume-level backups went with it, while the provider says those backups only appeared unavailable and it restored the data from separate disaster backups. The provider's dashboard already had a 48-hour recovery window for the same action; the API did not. Afterwards the provider made API deletes soft deletes for 48 hours.

  1. Parity first: no API path should be more dangerous than the UI path for the same action.
  2. Soft delete by default with a recovery window, and a separate, more privileged operation for permanent deletion.
  3. Separate scopes for destructive operations, never included in default or broad grants.
  4. Environment binding: tokens bound to one environment or project cannot reach production resources.
  5. Server-enforced confirmation: a two-step pattern (request returns a pending action, a second call with user approval executes it) or a step-up challenge.
  6. Dry-run support: a preview mode that returns what would change lets agents and their users check scope before committing.

See the Human-in-the-Loop for AI Agents Guide for approval design on the agent side.

Descriptions, schemas and error messages

OpenAPI (latest published version 3.2.1, dated 10 September 2026) gives each operation a unique operationId, a summary and a description, and supports security schemes including API keys, HTTP authentication, mutual TLS and OAuth 2.0. Agent frameworks and MCP servers often generate tools directly from these fields, so they now shape run-time behaviour.

  • Name operations by effect: deleteVolumePermanently is safer than volumeDelete, because the model sees the consequence.
  • Declare side effects and scopes in descriptions and in the security requirement for each operation.
  • Constrain parameters: enums, formats, maximum lengths and required fields reduce malformed or over-broad calls and support server-side validation (NIST SP 800-53 SI-10).
  • Use structured errors: RFC 9457 problem details with a stable type URI and a short instruction (retry later, needs approval, not permitted) rather than stack traces or internal identifiers.
  • Treat descriptions as untrusted for consumers: if your platform imports third-party API descriptions as agent tools, review them, because text in a description can carry instructions. See the MCP Security Guide.
  • Do not echo untrusted data into instructions: response fields that contain user-generated content should be clearly marked as data, since agents feed responses back into the model. The Zero Click AI Agent Exploits guide shows how content returned by an API became the injection vector.

Abuse detection and measurement

  • Log per call: client ID, agent identifier, user subject, scopes used, operation, idempotency key, outcome and latency (NIST SP 800-53 AU-2).
  • Alert on: first use of a destructive scope by an agent client; sudden expansion in the number of objects an agent touches; repeated 403s on sequential identifiers; tokens used from new networks; spikes in 409 or 422 idempotency errors.
  • Metrics: share of agent traffic on scoped, audience-restricted tokens rather than static keys; share of side-effect operations requiring idempotency keys; number of destructive operations with soft delete and recovery; median token lifetime for agent clients; time to revoke a single agent client; agent-originated incidents per quarter.

Rollout

  1. Inventory agent traffic: find which clients and keys are already used by agents, from logs and customer conversations.
  2. Classify operations into read, write and destructive, and map each to a scope.
  3. Introduce task scopes and audience checks in report-only mode, logging what would fail.
  4. Add idempotency keys as optional, then required for new clients, then required for all after a published deadline.
  5. Ship soft delete and confirmation for destructive operations behind a feature flag per tenant, so you can roll back quickly if a customer workflow breaks.
  6. Deprecate account-wide static keys for agent use with a migration path to OAuth clients.

Decision guidance

  • Autonomous back-office agent, no user: client credentials with narrow scopes and sender-constraint; human approval for anything destructive.
  • Agent acting for a user: authorisation code with PKCE, task scopes and token exchange for downstream calls so the actor is recorded.
  • Agent platform calling on behalf of many customers: per-tenant clients, partitioned limits and a contractual obligation to pass end-user context.
  • Small API teams: start with scope splitting, idempotency keys and soft delete; they deliver most of the benefit. Larger platforms should add RAR, sender-constrained tokens and per-agent identifiers.

Framework mapping

Control areaOWASP API Top 10 2023NIST SP 800-53 Rev. 5NIST CSF 2.0
Agent client identificationAPI2 Broken AuthenticationIA-9 Service Identification and AuthenticationPR.AA-05
Task scopes and object checksAPI1, API5 Broken Function Level AuthorizationAC-3 Access Enforcement, AC-6 Least PrivilegePR.AA-05
Rate and cost limitsAPI4, API6SC-5 Denial-of-service ProtectionDE.CM-09
Input validation from schemasAPI3 Broken Object Property Level AuthorizationSI-10 Information Input ValidationPR.DS-01
Logging and monitoringAPI9 Improper Inventory ManagementAU-2 Event Logging, SI-4 System MonitoringDE.CM-09
Inventory of agent clientsAPI9AC-2 Account ManagementID.AM-02

Common failure patterns

  • Account-wide tokens handed to agents: a token issued for one purpose reaches everything, as in the PocketOS case.
  • API more dangerous than the UI: hard deletes and no confirmation on the API path while the console has guard rails.
  • No idempotency on writes: agent retries after a timeout create duplicate payments, orders or messages.
  • One key, many users: an agent platform uses a single key for all customers, so you cannot limit or revoke one tenant.
  • Token passthrough: an intermediary forwards the user's token to downstream APIs, which then trust a token not issued for them.
  • Verbose errors in model context: stack traces, internal IDs or other users' data in error messages end up in agent transcripts.

Practitioner checklist

  • Require OAuth clients per agent platform and record agent identifier and user subject on every call.
  • Split scopes into read, write and destructive, and keep destructive scopes out of default grants.
  • Validate token audience on every request and refuse passthrough tokens.
  • Require idempotency keys on all side-effect operations and fingerprint payloads.
  • Make deletes soft by default with a recovery window, and enforce confirmation or step-up server-side.
  • Partition rate limits by user, agent client and tenant, with weighted quotas for expensive operations.
  • Write operation names and descriptions that state side effects, and return RFC 9457 problem details.
  • Alert on first use of destructive scopes and on loops, and measure time to revoke one agent client.

Standards and references

Related NHI Mgmt Group resources: Bot vs AI Agent Traffic Management Guide · API Security Guide · Rate Limiting and API Abuse Guide · OAuth Token Exchange and Delegation Guide · Agent Identity and Access Guide

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

NHIMG Editorial Note
Researched and written by the NHI Mgmt Group editorial team using AI tools, under the editorial direction of Lalit Choda. Facts are drawn from the sources listed on this page and checked by our automated quality process. Last updated 8 November 2026. Spotted an error? Use our contact page.
NHI Mgmt Group, the independent authority on Non-Human Identity, IAM and Agentic AI security. nhimg.org

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick the PDF box to continue.