Skip to main content
Glama

keycloak-mcp-agents

check License

Give each AI agent its own identity and its own permissions when it calls your MCP tools, using only what Keycloak and the MCP SDK already provide.

The problem

Most teams connect agents to internal tools with one shared API key. Then:

  • 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.

Related MCP server: secure-mcp-agent-starter

What this demo shows

Two agents call the same MCP server with three tools.

Shared key

Keycloak

Support agent lists tickets

allowed

allowed

Support agent lists invoices

allowed

refused

Support agent refunds an invoice

allowed

refused

Billing agent refunds an invoice

allowed

allowed

Log says who did it

"shared-key"

support-agent, billing-agent

Cut off one agent

rotate the key for everyone

disable it in Keycloak, the next call fails

Agent acts for Alice, who may approve refunds

no idea who the user is

allowed, log says billing-agent for alice

Agent acts for Bob, who may not

no idea who the user is

refused

No custom auth code: Keycloak issues and checks the tokens, the MCP SDK enforces them.

Run it

Needs Docker and Node 24 or later.

docker compose up -d --build
npm install
npm run check

npm run check runs every row of the table above, plus the revocation and sign-in checks below, against the running containers and prints ok or FAIL for each. It restarts the MCP servers first, so the demo data starts fresh on every run.

Call a tool as a given agent:

npm run agent -- support-agent list_tickets
npm run agent -- support-agent refund_invoice INV-1002
npm run agent -- billing-agent refund_invoice INV-1002
MCP_URL=http://localhost:8092/mcp npm run agent -- shared refund_invoice INV-1001

See who did what:

docker compose logs mcp-server
{"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"}

Act for a signed-in user

An agent often works for a person. Then two questions matter: may this agent call the tool, and may this person?

ON_BEHALF_OF=alice npm run agent -- billing-agent refund_invoice INV-1003
ON_BEHALF_OF=bob npm run agent -- billing-agent refund_invoice INV-1004
ON_BEHALF_OF=alice npm run agent -- support-agent refund_invoice INV-1004

The first works. Bob's is refused because he lacks the refund-approver role. The support agent is refused for Alice too, because the agent itself has no refund scope. The log shows both identities:

{"agent":"billing-agent","user":"alice","tool":"refund_invoice","args":{"invoiceId":"INV-1003"},"outcome":"allowed"}
{"agent":"billing-agent","user":"bob","tool":"refund_invoice","args":{"invoiceId":"INV-1004"},"outcome":"denied","reason":"user lacks role refund-approver"}

How: Alice signs in to chat-app and gets a token meant for the agents. The agent swaps it for a token meant for the MCP server with Keycloak's standard token exchange. The new token carries Alice as the subject, the agent as azp, the agent's scopes, and only the user roles the agent is allowed to see (scopeMappings in the realm).

Connect a real AI client

Keycloak can let Claude Code or VS Code sign a user in with no client registered up front: the client's ID is the URL of its client metadata document, and Keycloak fetches it. The realm trusts only metadata on claude.ai and vscode.dev, and only issues their tokens for this MCP server (resource indicators). Both features are experimental in Keycloak and switched on in docker-compose.yml.

claude mcp add --transport http helpdesk http://localhost:8091/mcp

Then run /mcp in Claude Code, choose helpdesk, and sign in as alice (password alice) or bob (password bob). The log names the client by its metadata URL, with the user next to it. npm run check proves that Keycloak serves the login page for Claude Code and refuses an untrusted metadata URL. The browser sign-in itself is not part of the automated check.

Cut off one agent

Start an agent that calls a tool every 3 seconds:

REPEAT_EVERY=3 npm run agent -- billing-agent list_invoices

Open http://localhost:8080/admin (user admin, password admin), go to the agents realm, Clients, billing-agent, and switch Enabled off. Its next call is refused. The support agent keeps working. Keycloak records every agent login, and the refusal (CLIENT_LOGIN_ERROR, client_disabled), on the Events page of the agents realm. The MCP server logs the refused token too, with the agent the token claims to be from:

{"agent":"billing-agent (claimed, unverified)","tool":"-","outcome":"token refused","reason":"Token is not active"}

Asking Keycloak or checking locally

The main server (port 8091) asks Keycloak about every token. A second server (port 8093, TOKEN_CHECK=local) only checks the token's signature against Keycloak's published keys. It saves a round trip per call, but a disabled agent's existing token keeps working there until it expires. npm run check proves both: the same token is refused on 8091 and accepted on 8093 after the agent is disabled. Choose per server: short token lifetimes make local checks safer.

How it works

Keycloak (keycloak/agents-realm.json):

  • Each agent is a confidential client using the client credentials grant, so each agent has its own secret and its own tokens.

  • Each tool permission is a client scope (tickets:read, invoices:read, invoices:refund). An agent only gets the scopes assigned to it. Asking for any other scope is refused with invalid_scope.

  • Every scope carries an audience mapper that puts the MCP server's URL in the token's aud claim, so other services that check the audience reject it.

  • The MCP server is itself a client whose client ID is its URL. Keycloak only lets a client introspect tokens issued for it, and this makes the audience the SDK checks and the audience Keycloak checks the same value.

MCP server (server/server.ts), using the official MCP TypeScript SDK v2:

  • requireBearerAuth rejects requests without a valid token and serves the protected resource metadata, so clients find Keycloak on their own.

  • The token check asks Keycloak's introspection endpoint on every request (server/tokens.ts). That is what makes disabling an agent take effect immediately. TOKEN_CHECK=local verifies the signature with jose instead.

  • Each tool has a scopeChallenge (requireScopes). A missing scope returns 403 insufficient_scope and is written to the audit log.

  • refund_invoice also checks the user's role when a user is present. Scopes say what the agent may do, roles say what the person may do.

Agents (agents/agent.ts) use the SDK's ClientCredentialsProvider, or token exchange when ON_BEHALF_OF is set. They are scripted, not language models, so the demo is free and repeatable. Any MCP client that supports client credentials works the same way.

Limits

  • Demo only: start-dev, plain HTTP, and secrets in the realm file.

  • Re-enabling a client makes its unexpired tokens valid again. To cut an agent off for good, leave it disabled or delete the client.

  • Users sign in with a password straight to chat-app (direct access grant) so the demo runs without a browser. A real app uses the authorization code flow.

  • Token exchange here is delegation without an act claim: the token names the agent in azp. Keycloak's act claim support is a preview feature and not used.

  • Revoking the user's token does not revoke a token already exchanged from it, per Keycloak's docs. Keep lifetimes short.

  • Cross-app access (ID-JAG) is not covered.

Contributing

See CONTRIBUTING.md. Security reports: SECURITY.md.

License

Apache-2.0. See LICENSE.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables autonomous AI agents to securely access and execute external tools, such as GitHub REST API operations, with per-user authentication, authorization, audit logging, and observability.
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables production-hardened MCP tool serving with OAuth 2.1 audience-restricted tokens, purpose-bound tools, human-in-the-loop approvals, containment, and audit trails for AI agents.
      Apache 2.0
    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables AI agents to access corporate HR and CRM APIs on behalf of a specific user through OAuth 2.1 token verification, deny-by-default RBAC, token exchange, audit logging, PII masking, and untrusted-output envelopes.
      MIT