Security

Securing AI Agent Ecosystems: Authentication, Authorization, and Privacy in Agentic Systems

A practical security model for agents: prompt injection and the confused deputy, MCP authorization on OAuth 2.1, least-privilege tools, secrets and privacy.

By the APIStack team··9 min read

A brass combination padlock on a white keyboard beside two chip cards

An agent reads content it did not write and then acts with credentials it did not earn. That combination is the security problem, and it is not solved by the model being careful. This article sets out a threat model for agents that call tools, the current state of authorization in the Model Context Protocol (MCP), and the controls that belong in code: token validation, least-privilege tools, approval gates, secrets handling and data retention.

It is for developers who build agents or expose APIs to them. It assumes familiarity with OAuth at the level of access tokens and scopes.

The threat model

A language model receives instructions and data in the same channel. OWASP's entry on prompt injection, first in its 2025 Top 10 for LLM applications, separates the direct form, where the user's own input changes the model's behavior, from the indirect form, where instructions arrive inside a web page, file or tool result the model was asked to process. The indirect form is the one that matters for agents, because the attacker never needs access to the conversation.

OWASP published a separate Top 10 for Agentic Applications in December 2025. Its first three entries describe the chain: agent goal hijack, tool misuse and exploitation, and identity and privilege abuse. Injected text redirects the agent, the agent calls a legitimate tool, and the tool runs with the user's authority.

Two short rules describe when that chain becomes dangerous. Simon Willison's lethal trifecta is the combination of access to private data, exposure to untrusted content, and the ability to communicate externally; an agent with all three can be told to read something private and send it out. Meta's Agents Rule of Two turns it into a design constraint: within one session an agent should have at most two of processing untrustworthy inputs, access to sensitive systems or private data, and the ability to change state or communicate externally. If a task needs all three, it needs human approval or a fresh context.

Willison's post is also clear about what does not work: nobody yet knows how to prevent prompt injection reliably, so filters that catch most attacks are not a boundary. Design as if the model will sometimes follow injected instructions.

The confused deputy

A confused deputy is a program with legitimate authority that is tricked into using it for someone else. An agent is one by construction: the user grants the authority, and whoever writes the content it reads may supply the instructions. The defense is to make each privileged action depend on something the attacker cannot supply, such as a scope the token does not have or an approval the user has not given.

The same problem appears in protocol plumbing. The MCP security best practices describe an MCP server that proxies to a third-party API using one static OAuth client ID. If the third party remembers consent with a cookie, an attacker can register their own client with the proxy, send the user a link, and receive an authorization code without the user ever seeing a consent screen. The required fix is consent stored per client by the proxy, checked before it forwards to the third party, with exact matching of redirect URIs.

MCP authorization today

The current MCP revision is dated 2026-07-28. Its authorization specification is optional, applies to HTTP transports, and is built on the OAuth 2.1 draft plus a small set of RFCs. Servers using the STDIO transport are told not to use it and to take credentials from the environment instead.

The MCP server is an OAuth resource server; the MCP client is an OAuth client; the authorization server may be a separate service. The requirements that matter most in practice are these:

  • Discovery. Servers must publish OAuth protected resource metadata (RFC 9728), and a 401 response points the client to it.
  • Resource indicators. Clients must send the resource parameter (RFC 8707) naming the MCP server in both the authorization request and the token request.
  • Audience validation. Servers must check that a token was issued for them, and must not accept or forward any other token. Passing a client's token through to a downstream API is explicitly forbidden.
  • Client registration. Client ID Metadata Documents, where the client ID is an HTTPS URL to a JSON document, are the recommended mechanism. Dynamic Client Registration is deprecated in this revision and kept for backward compatibility.
  • Issuer check. Clients must validate the iss parameter in the authorization response when it is present, which defends against mix-up attacks between authorization servers.
  • Token transport. Access tokens go in the Authorization header on every request and must not appear in the URL query string.

A request without a token gets a challenge that tells the client where to start and which scope to ask for.

HTTP
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource",
                         scope="files:read"

The 2026-07-28 changelog also removed protocol-level sessions. A server that needs state across calls now issues its own handle and receives it back as a tool argument. The best-practices document is explicit that possession of such a handle is not authentication: bind it to the user from the verified token.

Validate the token on the server

When access tokens are JWTs, validation is a signature check plus two claims that are easy to skip. This example uses the jose library; in production the key set URL comes from the authorization server's metadata.

JavaScript
import { createRemoteJWKSet, jwtVerify } from 'jose'

const ISSUER = 'https://auth.example.com'
const RESOURCE = 'https://mcp.example.com/mcp'
const jwks = createRemoteJWKSet(new URL(`${ISSUER}/.well-known/jwks.json`))

export async function authenticate(request) {
  const header = request.headers.get('authorization') || ''
  if (!header.startsWith('Bearer ')) return null
  try {
    const { payload } = await jwtVerify(header.slice(7), jwks, {
      issuer: ISSUER,
      audience: RESOURCE
    })
    return { subject: payload.sub, scopes: (payload.scope || '').split(' ').filter(Boolean) }
  } catch {
    return null
  }
}

The audience option is the line that stops a token issued for another service from working here. A null result becomes the 401 challenge shown above. Opaque tokens need a call to the authorization server's introspection endpoint instead.

Least privilege for tools

Scopes limit what a stolen or misused token can do. The MCP guidance on scope minimization recommends a small initial scope covering low-risk read operations, with privileged scopes requested only when a privileged tool is first called. The server signals this with a 403 and error="insufficient_scope" naming the scope needed, and the client runs a step-up authorization. It lists the mistakes to avoid: wildcard scopes, publishing every scope as the default set, and trusting the scopes in a token without server-side checks.

Apply the same idea to the tool list itself. Split read tools from write tools, give each agent only the tools its task needs, and deny by default. OWASP's mitigations for prompt injection include handling privileged functions in code and requiring human approval for high-risk actions, which is where the Rule of Two becomes a few lines of policy.

Python
READ_ONLY = {"search_docs", "get_invoice", "check_url_safety"}
NEEDS_APPROVAL = {"send_email", "issue_refund", "http_post"}

def authorize_tool_call(session, tool, approved_by_user=False):
    if tool in READ_ONLY:
        return True
    if tool not in NEEDS_APPROVAL:
        return False  # unknown tools are denied
    if session["saw_untrusted_content"] and session["has_private_data"]:
        return approved_by_user
    return True

Set saw_untrusted_content the first time the session ingests a web page, an inbound email or a third-party tool result, and never clear it. The check runs in your code, outside the model, so injected text cannot argue with it.

Read tools need limits too. A fetch tool is a server-side request forgery risk: block private and link-local address ranges, require HTTPS, and validate each redirect, as the MCP best practices set out. Links found in untrusted content can be scored before the agent opens them; the URL safety check is one such tool.

Secrets and tokens

The model's context is not a secret store. Anything in it can be repeated in output, written to a transcript, or sent to a tool. Keep credentials in the tool layer and let the model refer to a connection by name.

RiskControlEnforced by
Token replay at another serviceAudience-restricted tokens, validated on every requestResource server
Stolen long-lived credentialShort-lived access tokens; refresh tokens rotated or sender-constrainedAuthorization server
Authorization code interceptionPKCE and exact redirect URI matchingClient and authorization server
Secret leaked through the modelCredentials injected by the tool runtime, never placed in promptsAgent host
Secret leaked through logsNo tokens in URLs; redact headers and tool arguments before loggingServer and observability pipeline

Audience restriction, refresh token protection, PKCE and exact redirect matching are set out in RFC 9700, the IETF's best current practice for OAuth 2.0 security, which the MCP documents build on.

Privacy and data retention

Everything an agent places in context is sent to the model provider, and usually stored in your own traces as well. Three questions decide the privacy posture.

The first is what reaches the model at all. Return only the fields a task needs from each tool. Anthropic's post on code execution with MCP describes a stronger form: data moves between tools inside a sandbox, and the model sees only what the code chooses to return.

The second is what the provider keeps. Retention is set per feature, not per vendor. Anthropic's API and data retention page lists which features qualify for a zero data retention arrangement and which do not; batch processing, for example, stores results for 29 days and is not eligible. Check the equivalent table for every feature your agent uses.

The third is what you keep. Agent transcripts contain user data, tool results and sometimes credentials. Give them a retention period, restrict access, and redact before storage. Record who authorized each state-changing action, so that an audit can separate what the user asked for from what the agent decided.

Standards for agent identity are still forming. NIST's National Cybersecurity Center of Excellence published a draft concept paper on software and AI agent identity and authorization in February 2026, covering identification, authorization, auditing and prompt injection controls. It is a consultation document, not final guidance.

Summary

  • Assume injected instructions will sometimes be followed; do not let one session combine untrusted input, private data and external actions without approval.
  • An agent is a confused deputy by default. Make privileged actions depend on scopes and approvals checked in code.
  • For MCP over HTTP, follow the 2026-07-28 authorization specification: protected resource metadata, the resource parameter, audience validation, and no token passthrough.
  • Grant minimal scopes and tools, step up on demand, and deny unknown tools.
  • Keep secrets out of the context, and set retention for both the provider's copy of the data and your own transcripts.

Build with APIStack

One API key for validation, dates and holidays, web checks and reference data, over REST or as MCP tools for your AI agents. The free plan includes 1,000 calls a month.

Keep reading