Acting as the User: Delegated Identity for Agents and MCP Tools

You add a remote MCP server to an agent platform, say one that exposes a project tracker or a quoting system, and it works in testing with your own credentials. Then the real question arrives: when a colleague uses the agent, should the tool see your identity, a shared service account, or the colleague's own permissions? People building agents in enterprise platforms ask this constantly, usually in the form "how do I set up on-behalf-of auth for my MCP server?"
This article explains the concept for developers who build or connect remote MCP servers: what on-behalf-of means, how it differs from service accounts and API keys, how token exchange works at a high level, the mistakes that create security holes, and when a simpler approach is good enough. It does not replace your identity provider's documentation, which you should follow for the exact configuration.
Frequently asked questions
What does on-behalf-of mean in authentication?
It describes a flow where a service receives a token proving a user signed in, and exchanges it for a new token to call another service as that same user. Downstream systems then apply the user's own permissions, not those of the middle service.
How does on-behalf-of differ from a service account?
A service account is one identity shared by every caller, so the tool sees the same permissions for everyone. On-behalf-of keeps each user's identity, so a person can only reach data they are already allowed to see.
Is passing the user's token straight through to the backend fine?
Generally no. Forwarding a token issued for one audience to a different service is a known anti-pattern, and the MCP authorization guidance discourages it. Exchange it for a token meant for the downstream API instead.
Which is better for a hobby MCP server: OAuth or an API key?
For a personal server used only by you, a scoped API key stored safely is often enough. Once several people use the same server with different permissions, OAuth with delegated identity becomes worth the setup.
Does the language model ever see the tokens?
It should not. Tokens belong in the client and server plumbing. The model only sees tool names, arguments and results, so a prompt injection cannot read or leak credentials it never received.
What is token exchange?
It is a standard OAuth pattern in which a service presents one token to the authorization server and receives another with a different audience or scope. On-behalf-of flows are a common use of it.
Does the free API on this site need any of this?
No. It is keyless and stateless, with limits per IP. It is useful as the model behind an agent, but any identity handling for your tools must be built on your side.
- Why identity gets complicated with agents
- The basic on-behalf-of flow
- Validating incoming tokens on the MCP server
- Common mistakes that create holes
- Keeping credentials away from the model
- When simpler approaches are good enough
- Testing the flow without production data
- Where this fits in a broader agent design
Why identity gets complicated with agents
In a classic web app, a user signs in, and the backend calls APIs with credentials it controls. Agents add a layer: the user talks to an agent, the agent decides to call a tool, and the tool is a remote MCP server that calls yet another backend. There are now three or four hops, and each one needs to know who the request is really for.
Getting this wrong has visible consequences. If every call uses the developer's own token, every user of the agent effectively has the developer's permissions. If every call uses a powerful service account, a single prompt injection could reach data that no individual user should see. Delegated identity solves both problems by carrying the real user's rights through the chain.
The confused deputy
A server with broad rights that acts on requests from less privileged callers can be tricked into doing things those callers could not do themselves. Agents are classic deputies because they act on natural-language requests.
Audit trails
When actions are recorded under a shared account, you cannot tell later which person triggered them. Delegated tokens keep audit logs meaningful.
The basic on-behalf-of flow
The flow is easier to follow in steps. The user signs in to the agent platform with the organisation's identity provider. The platform obtains an access token whose audience is your MCP server. When the agent calls a tool, the platform sends that token to the server. The server validates it, then asks the identity provider to exchange it for a token whose audience is the downstream API. Finally the server calls the API with the new token, and the API applies the user's permissions.
Every token in this chain is short-lived, scoped and issued for a specific audience. No component holds a long-lived secret that grants access to everything.
Why not reuse token A?
Token A was issued for your server. Sending it to a different API breaks the audience rule, and if that API accepted it, any service receiving token A could impersonate the user everywhere.
- Token A: issued to the agent platform, audience is your MCP server, proves the user's identity.
- Validation: your server checks signature, issuer, audience, expiry and scopes on token A.
- Exchange: your server presents token A plus its own client credentials to the identity provider.
- Token B: audience is the downstream API, scopes limited to what the tool needs.
- Call: the downstream API sees the user's identity via token B and enforces their rights.

Validating incoming tokens on the MCP server
Your server is a resource server in OAuth terms: it receives tokens and must decide whether to trust them. Use a maintained library from your identity provider or a well-known JWT library rather than parsing tokens by hand. Fetch signing keys from the provider's published key set, and cache them sensibly.
The checks are always the same, and skipping any one of them opens a hole. The most commonly forgotten is the audience: a token that is valid but meant for another service must be rejected.
Scopes per tool
Map each MCP tool to the scopes it needs. A read-only lookup tool should not run with a token that also allows writes.
Clock skew and expiry
Allow a small leeway for clock differences, but never accept expired tokens. Short lifetimes limit the damage of any leak.
import jwt # PyJWT
from jwt import PyJWKClient
ISSUER = "https://login.example.com/tenant-id/v2.0"
AUDIENCE = "api://my-mcp-server"
jwks = PyJWKClient("https://login.example.com/tenant-id/discovery/v2.0/keys")
def validate(bearer_token: str) -> dict:
signing_key = jwks.get_signing_key_from_jwt(bearer_token)
claims = jwt.decode(
bearer_token,
signing_key.key,
algorithms=["RS256"],
audience=AUDIENCE,
issuer=ISSUER,
)
if "quotes.read" not in claims.get("scp", "").split():
raise PermissionError("missing scope quotes.read")
return claims # contains the user's id, used for logging and exchangeCommon mistakes that create holes
Most incidents with agent tools come from shortcuts taken during prototyping and never removed. A developer hardcodes their own token to get a demo working, the demo becomes the product, and months later every user is acting with that developer's rights.
Another common shortcut is giving the MCP server a broad service account "temporarily" because delegated auth looked complicated. If the agent then reads untrusted text, such as a customer email containing hidden instructions, the attacker's request runs with that broad account.
Never let the model pick identity
Identity must come from the authenticated session, not from text the model produces. A tool argument like user_id is an invitation to impersonation via prompt injection.
- Forwarding the incoming token to downstream APIs unchanged.
- Skipping audience validation because the signature was valid.
- Storing refresh tokens in logs, error messages or tool results.
- Returning raw API errors that include tokens or internal URLs to the model.
- Letting the model choose which user to act as through a tool argument.

Keeping credentials away from the model
Language models should never see access tokens, client secrets or refresh tokens. The agent platform and your server exchange them in headers and configuration; the model sees only tool descriptions, arguments and sanitised results. This separation means even a fully hijacked conversation cannot exfiltrate a credential it never had.
Sanitise tool results as well. If a downstream API returns an error that echoes headers, strip it before it reaches the model. Return short, meaningful messages like "permission denied for this project" rather than stack traces.
Treat tool results as untrusted input
Data returned by tools can contain instructions planted by others. The model may follow them, so the less power the current token has, the less harm such instructions can do.
When simpler approaches are good enough
Delegated auth is the right answer for multi-user tools that touch permissioned data. It is overkill for a personal MCP server that wraps a public dataset or a tool only you use on your own laptop. A local server over standard input and output, or a remote server protected by a single scoped API key that only you hold, is perfectly reasonable there.
The decision rule is simple: if two people with different rights will use the tool, carry their identities. If everyone has the same rights to the same public data, a service credential with minimal scope is acceptable, as long as it can only reach that public data.
Public data servers
Servers that expose things like version diffs of open-source frameworks or public reference data often need no user identity at all, only rate limiting and abuse protection.
Niche business data
Servers for quoting, property records or customer data almost always involve per-user rights and contracts, so plan for delegated identity from the start.

Testing the flow without production data
Build the auth plumbing against a test tenant of your identity provider with a few test users who have different permissions. Write tests that confirm each user sees only their own data through the tool, and that a token for the wrong audience is rejected. These tests are worth more than any amount of manual clicking.
For the model side, any OpenAI-compatible endpoint can drive the agent during development. The keyless API on this site is handy for that, with limits of one request per second and two in parallel per IP. This site is not affiliated with Anthropic, and the model behind it, free-ai, is an independent open-weight model, not Claude. Keep in mind it is text only and has no SLA, so use it for testing flows, not for production traffic.
Negative tests first
Write the tests that should fail before the ones that should pass: an expired token, a token for another audience, a user without the right scope, a tool argument naming someone else's record. If any of these succeed, the flow is not ready, however smooth the happy path looks in a demo.
Where this fits in a broader agent design
Identity is one layer of agent safety. The others include limiting which tools exist at all, requiring confirmation for destructive actions, and logging every call. Our guide on why agents keep asking permission discusses where confirmations belong. And if you are tempted to authenticate tools with session cookies copied from a vendor's app, read the risks of building on undocumented endpoints first.
Getting delegated identity right early is far cheaper than retrofitting it after an incident. Once it is in place, adding new tools becomes safer, because each one inherits the same rule: act as the real user, with only the rights that user already has.
Log who, what and with which scope
For every tool call, record the user identity from the token, the tool name, a summary of arguments and the scopes used. That log is your evidence if something goes wrong.

Send a first prompt from the chat box on the home page: no key, no account and no card, just your browser.
Read also
- One Giant Prompt vs Small Steps: Which Builds Better Apps With AI?
- Why Are So Many 'Free Claude' Videos and Tutorials Misleading?
- Why Do Different AI Models Seem to Have Different Moods?
- Can a Non-Programmer Really Ship an MVP With AI Coding Help?
- How to Call a Chat API From a Word Add-in Task Pane Yourself