Note: This project is a fork of M0-AR/keycloak-mcp-server explicitly modified to secure the server using Keycloak as the Identity Provider (IdP). It implements the official MCP Authorization architecture: CIMD (Client ID Metadata Document) is the preferred path, with DCR (Dynamic Client Registration) explicitly configured as a legacy fallback.
β Validated with: Built-in VS Code MCP Client and Claude Code CLI.
π Sources & Specifications:
A powerful Model Context Protocol (MCP) server that allows AI models to manage Keycloak realms, users, clients, and groups securely using Keycloak's own authentication mechanisms. It provides 80+ tools to manage users, realms, clients, roles, groups, sessions, events, organizations, protocol mappers, user attributes, client scopes, and identity providers directly from AI assistants like Claude Code CLI or VS Code.
- β Create, update, and delete users (including email verified status)
- β List, search, and get user details
- β Reset user passwords
- β Logout user sessions
- β Manage user roles and groups
- β NEW: User attributes management (critical for organization data)
- β List, create, update, and delete realms
- β Get detailed realm settings and configurations
- β Manage realm-level security policies
- β Register, update, and delete clients/applications
- β List all clients in realms
- β Configure client settings and redirect URIs
- β NEW: Protocol mappers management (critical for JWT claims)
- β Create, update, and delete roles (realm and client-level)
- β Assign and remove roles from users and groups
- β List all roles and user role assignments
- β NEW: Composite roles and role hierarchies
- β NEW: Advanced role operations by ID
- β NEW: Find users with specific roles
- β Create, update, and delete user groups
- β Add and remove users from groups
- β Manage hierarchical group structures
- β NEW: Group attributes management
- β NEW: Child groups and subgroup management
- β NEW: Group member listing and management
- β Create, update, and delete organizations
- β Add and remove organization members
- β List organizations and members
- β Organization attributes management
- β Create, update, and delete identity providers (SSO)
- β Identity provider mapper management
- β SAML and OIDC provider configuration
- β External user attribute mapping
- β Create, update, and delete client scopes
- β Protocol mappers for client scopes
- β Token scope management
- β List active user sessions
- β Monitor authentication and admin events
- β Clear event logs and manage session lifecycles
- β Bulletproof authentication with fresh client instances
- β Comprehensive error handling with detailed logging
- β Cross-platform support (Windows, macOS, Linux)
- β Production-ready with TypeScript and robust architecture
- β Organization JWT Claims - Solve organization visibility in tokens
- β 80+ Tools - Complete Keycloak administration coverage
- Node.js 18 or higher
- Running Keycloak instance (local or remote)
- Keycloak admin credentials (Service Account) with appropriate permissions
- VS Code or Claude Code CLI
git clone https://github.com/2nistechworld/keycloak-mcp-server.git
cd keycloak-mcp-server
npm install
npm run buildYou must create a .env file in the root directory to configure the server (see Environment Variables below).
After configuring your .env, start the server:
npm start| Variable | Description | Default | Required |
|---|---|---|---|
KEYCLOAK_URL |
The base URL of your Keycloak instance | http://localhost:8080 |
β |
KEYCLOAK_ADMIN |
Admin username (Service Account) for backend API calls | "" |
β (Required if KEYCLOAK_AUTH_MODE=service-account) |
KEYCLOAK_ADMIN_PASSWORD |
Admin password (Service Account) for backend API calls | "" |
β (Required if KEYCLOAK_AUTH_MODE=service-account) |
KEYCLOAK_REALM |
The Keycloak realm to authenticate the admin client against | master |
β |
KEYCLOAK_AUTH_MODE |
Backend auth mode (service-account or delegated-token) |
service-account |
β |
PORT |
The port for the Streamable HTTP / SSE server | 3000 |
β |
HOST |
The host for the Streamable HTTP / SSE server | localhost |
β |
MCP_TRANSPORT |
Set to sse to start the HTTP/Streamable server instead of stdio |
undefined |
β |
OAUTH_ISSUER_URL |
Keycloak realm URL (e.g., http://localhost:8080/realms/master) |
undefined |
β |
OAUTH_CLIENT_ID |
Client ID in Keycloak used by the MCP Server to introspect tokens | undefined |
β |
OAUTH_CLIENT_SECRET |
Client Secret for the OAUTH_CLIENT_ID to perform introspection |
"" |
β |
OAUTH_SCOPES |
Comma-separated list of OAuth scopes required for the server | undefined |
β |
OAUTH_AUDIENCE |
Additional expected aud claim in the client's access token |
undefined |
β |
MCP_DANGEROUSLY_ALLOW_INSECURE_ISSUER_URL |
Bypasses HTTPS requirements for OAUTH_ISSUER_URL in development |
false |
β |
MCP_DEBUG |
Set to true to print raw access tokens to the console for debugging |
false |
β |
This MCP server strictly implements the official Model Context Protocol Authorization Specification (OAuth 2.1) to secure tools and resources. Rather than relying on simple offline JWT verification, this server uses Online Token Introspection (RFC 7662) via Keycloak. This means if an administrator kills a user's session in Keycloak, their MCP access is revoked instantly!
The server supports the modern Streamable HTTP transport on the root / endpoint, as well as legacy SSE on /sse and /message.
This server implements the official MCP Authorization flow decision tree:
- CIMD (Default/Preferred): If both the client and server support it, they will use Client ID Metadata Documents (e.g.
client_id=https://claude.ai/...). - DCR (Fallback): If CIMD is not supported, the server explicitly advertises its
registration_endpoint, allowing the client to fall back to Dynamic Client Registration to get a randomclient_idassigned by Keycloak. Note: You must configure your Keycloak realm to allow dynamic client registration (e.g. via Initial Access Tokens or anonymous DCR policies) for this fallback to work.
Below is the complete sequence of how an MCP Client (like VS Code or Claude Code) securely authenticates with Keycloak via the preferred CIMD path:
sequenceDiagram
participant C as MCP Client (VS Code / Claude Code)
participant S as MCP Server
participant K as Keycloak
participant M as CIMD Endpoint
%% Initial Connection & Discovery
C->>S: 1. Connect (No Token)
S-->>C: 2. 401 Unauthorized + WWW-Authenticate header
note over C,S: PRM Discovery
C->>S: 3. Fetch /.well-known/oauth-protected-resource
S-->>C: 4. Returns PRM Document (Issuer URL)
note over C,K: Authentication using CIMD (No DCR!)
C->>K: 5. Auth Request: client_id=https://host/client-metadata.json
K->>M: 6. Fetch https://host/client-metadata.json
M-->>K: 7. Returns Client Metadata Document JSON
Note over K: Validates client_id & PKCE (No secret needed)
C->>K: 8. Open browser for User Login
K-->>C: 9. Issues access_token & refresh_token
%% Authenticated MCP Request
C->>S: 10. Connect (Bearer access_token)
Note over S,K: Online Token Introspection (RFC 7662)
S->>K: 11. POST /token/introspect (Using pre-configured client secret)
K-->>S: 12. Token valid? (Checks expiry & audience)
S-->>C: 13. Accept Connection & Execute Tools
Because this server strictly enforces CIMD, your client must support connecting via the metadata document flow.
VS Code uses CIMD by default (client_id=https://vscode.dev/oauth/client-metadata.json), so you can connect directly:
{
"mcpServers": {
"keycloak-mcp-server": {
"type": "http",
"url": "http://localhost:3000"
}
}
}You can add the Keycloak MCP Server to Claude Code directly from the CLI using the http transport:
claude mcp add --transport http keycloak-mcp-server http://localhost:3000Keycloak supports CIMD starting in version 26.6.0. You must start Keycloak with the feature flag enabled:
bin/kc.[sh|bat] start --features=cimdBecause both Claude Code and VS Code desktop clients use localhost (or 127.0.0.1) for OAuth redirects rather than their primary metadata domains, they violate Keycloak's default "Restrict same domain" security rule. You must explicitly configure Keycloak Client Profiles and Policies to allow them.
- Go to Realm Settings -> Client Policies -> Profiles tab. Create a new Profile named
claude-code-cimd-profile. - Add the client-id-metadata-document executor to the profile and configure it:
- Trusted domains:
claude.ai,localhost,127.0.0.1 - Restrict same domain:
OFF - Only Allow Confidential Client:
OFF
- Trusted domains:
- Go to the Policies tab and create a new Policy named
claude-code-cimd-policy. - Add a Condition of type client-id-uri and configure it:
- URI scheme:
https - Trusted domains:
claude.ai
- URI scheme:
- Under Associated client profiles, link this policy to your
claude-code-cimd-profile.
- Go to Realm Settings -> Client Policies -> Profiles tab. Create a new Profile named
vscode-cimd-profile. - Add the client-id-metadata-document executor to the profile and configure it:
- Allow http scheme:
OFF - Trusted domains:
vscode.dev,127.0.0.1,code.visualstudio.com - Restrict same domain:
OFF - Only Allow Confidential Client:
OFF
- Allow http scheme:
- Go to the Policies tab and create a new Policy named
vscode-cimd-policy. - Add a Condition of type client-id-uri and configure it:
- URI scheme:
https - Trusted domains:
vscode.dev
- URI scheme:
- Under Associated client profiles, link this policy to your
vscode-cimd-profile.
To securely validate the access tokens, the MCP server needs its own dedicated client in Keycloak:
- In the Keycloak Admin Console, go to Clients -> Create client.
- Client ID: Set this to your desired client ID, and explicitly export it as the
OAUTH_CLIENT_IDenvironment variable. - Ensure Client authentication is turned ON (required for token introspection).
- Click Save, navigate to the Credentials tab, and copy the Client Secret to your
.envfile.
Because Keycloak strictly enforces token audiences during introspection, the tokens issued to your AI clients (like Claude Code CLI) must include the proper audiences:
- In Keycloak, create a new Client Scope named
mcp-admin(Type: Optional). - Go to the Scope tab, disable Full Scope Allowed, and assign the specific
realm-managementroles you want the AI to have access to. - Go to the Mappers tab and click Configure a new mapper -> Audience.
- Name it
mcp-server-audienceand set the Included Client Audience tomcp-server. (This allows the MCP server to inspect the token). - Add another Audience Mapper named
mcp-url-audienceand set the Included Custom Audience to your server URL (e.g.,http://localhost:3000). (This allows the MCP SDK to accept the token).
Provide the necessary environment variables to start the server in protected mode:
export OAUTH_ISSUER_URL="http://localhost:8080/realms/master"
export OAUTH_CLIENT_ID="mcp-server"
export OAUTH_CLIENT_SECRET="your-copied-client-secret"
# If developing locally without HTTPS, the start/dev scripts automatically handle this:
npm run devWhen an MCP Client connects to http://localhost:3000, it will automatically receive a 401 Unauthorized with a WWW-Authenticate header pointing to /.well-known/oauth-protected-resource. The client will perform the OAuth flow and seamlessly reconnect with a valid access token!
Creates a new user in a specified realm.
Create a user in "master" realm: username "john.doe", email "john@example.com", first name "John", last name "Doe"
Updates user information (email, names, enabled status, email verified status).
Update user "user-id-123" in "master" realm to change email to "newemail@example.com"
Deletes a user from a realm.
Delete user with ID "user-id-123" from "master" realm
Lists all users in a realm.
List all users in the "master" realm
Search users with filters (username, email, firstName, lastName).
Search for users with email containing "wateen.io" in "master" realm, limit 10 results
Get detailed information about a specific user.
Get details for user ID "user-id-123" in "master" realm
Reset a user's password.
Reset password for user "user-id-123" in "master" realm to "newPassword123", make it temporary
Logout all sessions for a specific user.
Logout all sessions for user "user-id-123" in "master" realm
Set user attributes (critical for organization data storage).
Set organization attribute for user "user-id-123" in "master" realm: {"organization": ["wateen-corp"]}
Get user attributes including unmanaged attributes.
Get all attributes for user "user-id-123" in "master" realm
Lists all available realms.
Show me all available realms in Keycloak
Creates a new realm with configurable settings.
Create a new realm called "company" with display name "Company Realm", enabled
Updates realm settings and configurations.
Update realm "company" to change display name to "Updated Company"
Deletes an existing realm.
Delete the realm "test-realm"
Retrieves detailed settings of a realm.
Get detailed settings for the "master" realm
Registers a new client/application in a realm.
Create client "my-app" in "master" realm with redirect URIs ["http://localhost:3000/*"]
Updates client settings (redirect URIs, protocol mappers, etc.).
Update client "my-app" in "master" realm to add new redirect URI "https://app.example.com/*"
Removes a client from a realm.
Delete client "old-app" from "master" realm
Lists all clients in a realm.
List all clients in the "master" realm
Create protocol mappers for clients (critical for JWT organization claims).
Create organization group mapper for client "my-app" in "master" realm to include "organization" claim in JWT
Update existing protocol mappers.
Update protocol mapper "mapper-id-123" for client "my-app" in "master" realm
Delete protocol mappers from clients.
Delete protocol mapper "mapper-id-123" from client "my-app" in "master" realm
List all protocol mappers for a client.
List all protocol mappers for client "my-app" in "master" realm
Create a new client scope for managing token scopes.
Create client scope "organization-scope" in "master" realm for organization claims
Update existing client scope.
Update client scope "scope-id-123" in "master" realm to change description
Delete a client scope.
Delete client scope "scope-id-123" from "master" realm
List all client scopes in a realm.
List all client scopes in the "master" realm
Get details of a specific client scope.
Get details for client scope "scope-id-123" in "master" realm
Create protocol mappers for client scopes.
Create organization mapper for client scope "organization-scope" in "master" realm
Update protocol mappers in client scopes.
Update protocol mapper "mapper-id-123" in client scope "scope-id-456" in "master" realm
Delete protocol mappers from client scopes.
Delete protocol mapper "mapper-id-123" from client scope "scope-id-456" in "master" realm
List protocol mappers for a client scope.
List all protocol mappers for client scope "scope-id-123" in "master" realm
Create a new organization.
Create organization "wateen-corp" with description "Wateen Corporation" in "master" realm
Update existing organization.
Update organization "org-id-123" in "master" realm to change name to "Updated Corp"
Delete an organization.
Delete organization "org-id-123" from "master" realm
List all organizations in a realm.
List all organizations in "master" realm with search "wateen", limit 10
Get details of a specific organization.
Get details for organization "org-id-123" in "master" realm
Add a user to an organization.
Add user "user-id-123" to organization "org-id-456" in "master" realm
Remove a user from an organization.
Remove user "user-id-123" from organization "org-id-456" in "master" realm
List all members of an organization.
List all members of organization "org-id-123" in "master" realm, limit 20
Creates roles at realm or client level.
Create a realm role "manager" with description "Manager role" in "master" realm
Modifies role attributes.
Update role "manager" in "master" realm to change description to "Updated manager role"
Deletes roles.
Delete role "old-role" from "master" realm
Lists all roles in a realm.
List all roles in the "master" realm
Assigns a role to a user.
Assign role "manager" to user "user-id-123" in "master" realm
Removes a role from a user.
Remove role "manager" from user "user-id-123" in "master" realm
Gets all roles assigned to a user.
Get all roles for user "user-id-123" in "master" realm
Create composite roles (role hierarchies).
Create composite role from "parent-role-id" with child roles ["child-role-1", "child-role-2"] in "master" realm
Get composite roles for a role.
Get composite roles for role "role-id-123" in "master" realm, limit 10
Delete composite roles from a role.
Remove composite roles ["child-role-1", "child-role-2"] from role "parent-role-id" in "master" realm
Get role details by ID.
Get role details for role ID "role-id-123" in "master" realm
Update role by ID.
Update role "role-id-123" in "master" realm to change name to "new-role-name"
Delete role by ID.
Delete role with ID "role-id-123" from "master" realm
Find users with a specific role.
Find all users with role "manager" in "master" realm, limit 20
Assign a role to a group.
Assign role "developer" to group "group-id-123" in "master" realm
Remove a role from a group.
Remove role "developer" from group "group-id-123" in "master" realm
Get roles assigned to a group.
Get all roles for group "group-id-123" in "master" realm
List available roles for a group.
List available roles for group "group-id-123" in "master" realm
List composite roles for a group.
List composite roles for group "group-id-123" in "master" realm
Creates user groups.
Create a group called "developers" in "master" realm
Updates group attributes.
Update group "group-id-123" in "master" realm to change name to "senior-developers"
Deletes groups.
Delete group "group-id-123" from "master" realm
Lists all groups in a realm.
List all groups in the "master" realm
Adds or removes users from groups.
Add user "user-id-123" to group "group-id-456" in "master" realm
Set group attributes (organization metadata).
Set organization attributes for group "group-id-123" in "master" realm: {"department": ["engineering"]}
Get group attributes.
Get all attributes for group "group-id-123" in "master" realm
Create a child group (subgroup).
Create child group "junior-devs" under parent group "group-id-123" in "master" realm
List subgroups of a parent group.
List subgroups of parent group "group-id-123" in "master" realm, limit 10
List members of a group.
List all members of group "group-id-123" in "master" realm, limit 20
Create a new identity provider for SSO integration.
Create SAML identity provider "company-saml" in "master" realm with SSO URL and certificate
Update an existing identity provider.
Update identity provider "company-saml" in "master" realm to change display name
Delete an identity provider.
Delete identity provider "old-saml" from "master" realm
List all identity providers in a realm.
List all identity providers in "master" realm
Get details of a specific identity provider.
Get details for identity provider "company-saml" in "master" realm
Create a mapper for identity provider (external user mapping).
Create user attribute mapper for identity provider "company-saml" in "master" realm
Update an identity provider mapper.
Update mapper "mapper-id-123" for identity provider "company-saml" in "master" realm
Delete an identity provider mapper.
Delete identity provider mapper "mapperId" for "alias" in "realm" realm
Get an identity provider mapper by ID.
Get identity provider mapper "mapperId" for "alias" in "realm" realm
Import an identity provider from a URL.
Import identity provider from URL "providerUrl" with ID "providerId" in "realm" realm
List available identity provider mapper types.
List available identity provider mapper types for "alias" in "realm" realm
List all mappers for an identity provider.
List all mappers for identity provider "alias" in "realm" realm
Lists all active sessions in a realm.
List all active sessions in "master" realm
Lists active sessions for a specific user.
Get active sessions for user "user-id-123" in "master" realm
Retrieves authentication and admin events.
List last 10 events in "master" realm
Clears event logs.
Clear all events in "master" realm
If you decide to deactivate CIMD on Keycloak (by removing --features=cimd), but you later see this java.lang.IllegalStateException in Keycloak logs during client registration:
This happens because you still have the CIMD Client Policy active in your Keycloak database, but you removed the underlying Java code feature (client-id-uri) that the policy relies on.
To fix:
- Re-enable the
--features=cimdflag temporarily and restart Keycloak so it stops crashing. - Go to Realm Settings > Client Policies > Policies and Delete the CIMD policy you created.
- Remove the
--features=cimdflag and restart Keycloak. DCR will now work normally.
If you enable KEYCLOAK_AUTH_MODE=delegated-token and get a 403 Permission Denied error when the MCP client tries to run a tool, even though the user has admin roles, this is because of Keycloak's strict Audience validation.
When you log in manually using client_id=admin-cli, Keycloak automatically adds the realm-management audience to your token. However, when an MCP client like Claude Code logs in using Dynamic Client Registration (DCR), Keycloak does not add the realm-management audience to its token by default, causing the Keycloak Admin API to reject it.
To fix this in Keycloak:
- Open the Keycloak Admin Console and go to your realm.
- Go to Client Scopes -> Create client scope (if it doesn't already exist). Name it
mcp-admin, set Type to Default, and save. (The MCP server automatically requests this scope during OAuth). - Go to the Mappers tab of the
mcp-adminscope -> Configure a new mapper -> Audience. Name itrealm-management-aud, set Included Client Audience torealm-management, make sure Add to access token is ON, and save. - CRITICAL STEP (Role Scoping): Go to the Scope tab of the
mcp-adminscope. Turn OFF "Full Scope Allowed" if it is on. Click Assign role, filter by clients, find therealm-managementclient, and assign the roles the MCP needs (e.g.,view-users,manage-users,query-users,manage-clients). - Run a command to force Claude Code to fetch a fresh token (or run
claude logoutand reconnect).
Why step 4 is required: Dynamically registered clients have "Full Scope Allowed" turned OFF by default for security. Even if you map the audience, Keycloak will actively strip your admin roles from the token because the DCR client isn't "allowed" to ask for them! Adding them to the Scope tab explicitly whitelists those roles for any client requesting the mcp-admin scope.
npx @modelcontextprotocol/inspector npx keycloak-mcp-serverVisit http://localhost:6274 to test all 80+ tools interactively.
npm run watch # Auto-rebuild on changes
npm run dev # Test server directlyThe server has been stress-tested with 80+ consecutive operations without authentication failures, demonstrating production-level reliability.
- Fresh Client Instances: Creates new KcAdminClient for every request
- Retry Logic: Exponential backoff with 2 attempts maximum
- Connection Management: 15-second timeout with proper cleanup
- Error Handling: Comprehensive error messages for all scenarios
- Type Safety: Full TypeScript coverage with proper interfaces
- Error Handling: Detailed error messages and logging
- Modular Design: Clean separation of concerns
This package has been extensively tested and validated:
- β 80+ consecutive operations without authentication failures
- β Cross-realm operations working seamlessly
- β Parallel tool execution supported
- β Complex search queries with multiple filters
- β Error recovery and detailed logging
- β TypeScript compilation with zero errors
- β Complete Keycloak API coverage with organization management
This package specifically addresses the common JWT organization problem:
- β User Attributes: Store organization data in user attributes
- β Protocol Mappers: Create mappers to include organization in JWT tokens
- β Client Scopes: Manage token scopes for organization claims
- β Organizations: Full organization lifecycle management
- β Group Attributes: Store organization metadata in groups
Example workflow:
- Create organization using
create-organization - Set user organization attribute using
set-user-attributes - Create protocol mapper using
create-protocol-mapperto include organization in JWT - Add user to organization using
add-organization-member
- Use environment variables for credentials
- Enable HTTPS for production Keycloak instances
- Use strong admin passwords
- Regularly rotate credentials
- Monitor admin events and sessions
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Commit changes:
git commit -m 'Add amazing feature' - Push to branch:
git push origin feature/amazing-feature - Open a Pull Request
MIT License - see LICENSE file for details.
- GitHub Issues: Create an issue
- Documentation: Check this README for comprehensive examples
- MCP Documentation: Model Context Protocol
- Claude Desktop - AI assistant supporting MCP
- VS Code - Code editor with MCP support
- Model Context Protocol - Protocol specification
- Keycloak - Open source identity and access management
- 80+ Tools: Complete Keycloak administration coverage
- Production Ready: Extensively tested and validated
- TypeScript: Full type safety and modern development experience
- Cross-Platform: Windows, macOS, and Linux support
- Zero Dependencies Issues: Robust dependency management
- Organization Management: Solve JWT organization visibility problems
- Advanced Features: Protocol mappers, client scopes, identity providers
Made with β€οΈ for the Keycloak and AI community