Per-Agent Identity for MCP Servers: Scopes, Revocation and Acting for Users with Keycloak
Most teams connect their AI agents to internal tools the quick way: one API key, shared by every agent. It works on day one. Then three things go wrong.
- Every agent can call every tool, including the dangerous ones.
- The log says “someone with the key” did it.
- You cannot cut off one misbehaving agent without breaking all the others.
I wanted to see how far I could get on these problems with tools most companies already run, without writing any custom auth code. The answer: almost all the way, with Keycloak and the official MCP TypeScript SDK. The demo is open source, runs with one docker compose up, and proves every claim with 25 checks in CI: github.com/snigdhasambitak/keycloak-mcp-agents.

What already exists
This is not a new idea, and you should know the good material that is already out there.
Keycloak’s own MCP guide explains how to use Keycloak as the authorization server for MCP.
The MCP security tutorial uses Keycloak too, with a user signing in.
Couchbase’s machine-to-machine tutorial is the closest match: headless agents with client credentials, one scope for read tools and one for write tools.
keycloak-mcp-sample shows a Quarkus server returning 403 insufficient_scope per tool.
What I could not find in one place: a before and after with a shared key, instant revocation of one agent, an audit log that names the agent and the user behind every call, and an automated check that proves each of these. That is what this demo adds, together with the traps I hit on the way.
The setup
One MCP server exposes three tools: list_tickets, list_invoices and refund_invoice. Two agents call it: a support agent and a billing agent.
In Keycloak:
- Each agent is its own confidential client using the client credentials grant. Each has its own secret and gets its own tokens.
- Each tool permission is a client scope:
tickets:read,invoices:read,invoices:refund. The support agent only getstickets:read. The billing agent getsinvoices:read, plusinvoices:refundas an optional scope it has to ask for. - Each scope carries an audience mapper that puts the MCP server’s URL into the token’s
audclaim, so no other service accepts the token.
On the MCP server, the SDK does the work. requireBearerAuth rejects requests without a valid token and serves the protected resource metadata, so clients find Keycloak on their own. Each tool gets a scope check:
server.registerTool('refund_invoice', {
description: 'Refund an invoice in full',
inputSchema: refundInput,
scopeChallenge: requireScopes('invoices:refund'),
}, handler);
A missing scope returns 403 insufficient_scope. The agents use the SDK’s ClientCredentialsProvider, so they fetch and refresh their tokens without any code of mine.
The result, as npm run check prints it:
Before: one shared key
ok shared key lists tickets: allowed
ok shared key refunds an invoice: allowed
After: one identity per agent
ok support agent lists tickets: allowed
ok support agent lists invoices: refused
ok support agent refunds: refused
ok billing agent lists invoices: allowed
ok billing agent refunds: allowed
And the audit log finally says who did what:
{"agent":"support-agent","tool":"refund_invoice","outcome":"denied","reason":"missing scope invoices:refund"}
{"agent":"billing-agent","tool":"refund_invoice","args":{"invoiceId":"INV-1002"},"outcome":"allowed"}
Cutting off one agent
Open the Keycloak admin console, find billing-agent, switch Enabled off. Its next call fails. The support agent keeps working.
This only works because the server asks Keycloak about every token (token introspection) instead of only checking the signature. A disabled client’s tokens become inactive at once. Keycloak also records the refused login as a CLIENT_LOGIN_ERROR event with client_disabled, and the MCP server logs the refused token with the agent it claims to come from.
That has a cost: one round trip to Keycloak per call. So the demo runs a second server that only checks the signature locally against Keycloak’s published keys. The check script takes one token, disables the agent, and sends the same token to both servers:
ok disabled agent's existing token, server asks Keycloak: refused
ok disabled agent's existing token, server checks locally (until it expires): allowed
Neither choice is wrong. Local checks are faster, introspection is instant revocation. Pick per server, and keep token lifetimes short where you check locally.
When the agent works for a person
Agents often act for a user. Then two questions matter: may this agent call the tool, and may this person?

Alice signs in to a chat app and gets a token meant for the agents. The agent swaps it for a token meant for the MCP server, using Keycloak’s standard token exchange. The new token carries Alice as the subject, the agent as azp, the agent’s own scopes, and only the user roles the agent is allowed to see.
Two layers then guard the refund. In Keycloak, the invoices:refund scope has a role mapping to refund-approver, and Keycloak only grants that scope to someone who holds the role, so Bob cannot even get it. On the server, refund_invoice checks the role again before it moves any money.
ok billing agent for alice refunds: allowed
ok billing agent for bob refunds (bob may not approve refunds): refused
ok support agent for alice refunds (agent lacks the scope): refused
{"agent":"billing-agent","user":"alice","tool":"refund_invoice","args":{"invoiceId":"INV-1003"},"outcome":"allowed"}
{"agent":"billing-agent","user":"bob","tool":"refund_invoice","outcome":"denied","reason":"user lacks role refund-approver"}
Real AI clients, no registration

Claude Code and VS Code can sign a user in to this server too. Keycloak supports client ID metadata documents: the client’s ID is a URL, and Keycloak fetches the client’s metadata from it. The realm trusts only metadata on claude.ai and vscode.dev, and only issues those tokens for this one MCP server. An untrusted URL gets “Client not found”.
The check script walks the whole browser flow with curl, the same steps Claude Code takes: login form, consent, code for token. It then calls the tools with the token it gets back:
ok Claude Code signed in as alice lists invoices: allowed
ok Claude Code signed in as alice refunds: allowed
ok Claude Code signed in as bob refunds: refused
Both Keycloak features involved are experimental today, so treat this part as a preview.
The traps
These cost me the most time, and none of them is obvious from the docs.
Keycloak only lets a client introspect tokens issued for it. My MCP server’s client was called mcp-server, and every introspection came back active: false. Keycloak checks that the introspecting client is in the token’s audience. The fix: name the server’s client after its URL, so the audience the SDK checks and the audience Keycloak checks are the same value.
A URL as client ID breaks HTTP basic auth. The colon in http:// splits the username. Send client_id and client_secret as form fields instead.
The MCP client asks for every scope the server advertises. If the protected resource metadata lists scopes_supported, the SDK’s client credentials provider requests all of them, even when you pass your own scope. Keycloak refuses with invalid_scope because no agent has all of them. Leave the list out.
A scope with a role mapping needs the role. Keycloak drops a client scope from the token when the subject holds none of the roles mapped to it, service accounts included. That is how Bob is kept away from the refund scope, and it is also why the billing agent’s own service account needs the role.
For token exchange, the user’s token must name the agent as audience. Otherwise Keycloak rejects the exchange. The chat app gets audience mappers for each agent.
The SDK client checks that the server is who its metadata says. A server on another port that advertises the first server’s URL is refused. Good behaviour, but surprising when you run two copies side by side.
Re-enabling a client brings its tokens back. Unexpired tokens become valid again. To cut an agent off for good, leave it disabled or delete it.
Consent is remembered. The first sign-in by a new client shows a consent page. After that, Keycloak redirects straight back with a code. A script that expects the consent page breaks on the second run.
Limits
This is a demo. It runs Keycloak in dev mode over plain HTTP with secrets in the realm file. Users sign in with a password straight to the chat app so the demo runs without a browser; a real app uses the authorization code flow. Revoking a user’s token does not revoke a token already exchanged from it, according to Keycloak’s docs, so keep lifetimes short. Cross-app access (ID-JAG) is not covered yet.
Try it
git clone https://github.com/snigdhasambitak/keycloak-mcp-agents
cd keycloak-mcp-agents
docker compose up -d --build
npm install
npm run check
You need Docker and Node 24 or later. Issues and pull requests are welcome, especially from people running agents against real tools: I would like to know which of these problems you hit first.