keycloak-mcp
Keycloak admin investigation server — reads (and a few writes) against the Keycloak Admin REST API via a service account, aimed at user/session/MFA/security-event triage and morning health patrols.
Users —
count_users,search_users(partial match),get_user(exact username),set_user_enabled, plusget_user_sessionsandlogout_user(session termination across LB nodes).Password operations —
reset_passwordfor one user andreset_passwords_batchfrom CSV (blank password ⇒ generated and returned); both requiremanage-users, otherwise read-only.MFA status —
get_user_credentials(anotpcredential = TOTP/HOTP) and realm-wideget_totp_usersadoption with percentage (N+1, capped bymax_users).Groups —
list_user_groupsandlist_users_by_group(read-only; no group-write tools are registered here).Event search —
get_events(type/username/client/IP/date),get_password_update_events,get_login_stats,get_login_stats_by_hour,get_login_stats_by_client,detect_login_loops.Admin events —
get_admin_eventsandget_user_attribute_historyfor service-account/admin-driven changes invisible to user-event endpoints.Security forensics —
get_brute_force_status,get_realm_security_defenses(is brute-force detection on, thresholds, password policy, headers),get_login_failures_by_ip, exhaustiveget_ip_activityfor one IP, andspray_check(password-spray detection with breach candidates, evidence tuples, and high/low confidence to separate shared egress from real spray).Config drift —
get_config_changesdiffs current realm config against a stored daily snapshot (secrets redacted).Sessions & clients —
get_session_stats(sessions per client),get_client_sessions,list_clients,get_client(flow overrides; secrets/attributes omitted),get_realm_roles.Morning patrol —
health_check(version + backend/auth reachability) anddaily_brief(one-shot Markdown summary flagging brute-force IPs, sprays,[CONFIG]and[PRIVILEGE]changes as WARNING/CRITICAL).
Provides tools for managing Keycloak users, groups, security, events, sessions, and clients through the Keycloak Admin REST API via service account authentication.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@keycloak-mcp search for user john.doe"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
keycloak-mcp
English | 日本語
An MCP (Model Context Protocol) server for the KeyCloak Admin REST API.
Documentation: https://shigechika.github.io/keycloak-mcp/
Authenticates via a Service Account (Client Credentials Grant), so no human password or TOTP is involved. Also Infinispan-safe — it never creates user sessions and never hits the userinfo endpoint.
Features
Users
Tool | Description |
| Total user count in the realm |
| Partial-match search (username / email / name) |
| Full detail for an exact username |
| Reset one user's password |
| Bulk reset from CSV ( |
| Active sessions for one user, timestamps in local time |
| Kill all active sessions for one user |
| Enable or disable one user; disabling blocks all logins (custom attributes preserved) |
MFA / Credentials
Tool | Description |
| Credential types configured for one user; an |
| Realm-wide TOTP adoption: how many users have an |
Groups
Tool | Description |
| Which groups a user belongs to |
| Members of a group |
Security
Tool | Description |
| Whether a user is currently locked by brute-force detection |
| Realm-level security policy: whether brute-force detection is enabled and its thresholds, the password policy, and browser security headers |
| What changed in the realm configuration since a stored daily snapshot (see Configuration snapshots). Read-only; |
| Failure breakdown by source IP (site-labeled when |
| Exhaustive investigation of one source IP: success/failure counts, affected users/clients, timeline. Returns structured JSON. |
| Password-spray detection with the breach list built in: every external IP with ≥ 10 distinct users and < 20 % login success is a spray source, and its successful logins (evidence tuple |
| Flag users who logged in too many times in a short window (redirect loops) |
Events
Tool | Description |
| Filter by type, username, client, IP, and date range. Username is resolved to user ID internally. Failure events include KeyCloak's |
| Login success/failure totals, paginated across all results |
| Logins bucketed by hour of day (local time) |
| Logins bucketed by client / SP |
|
|
Admin Events
get_events only sees user events. Actions driven by an admin — or by a service account writing custom attributes — don't show up there. The admin-event endpoint fills that gap.
Tool | Description |
| Filter by operation (CREATE / UPDATE / DELETE / ACTION), resource type (USER / CLIENT / ROLE / GROUP / …), resource path, and date range |
| UPDATE/ACTION events scoped to one user — handy for tracking when a custom attribute (e.g. |
Both tools accept max_repr to control the representation payload: positive = truncate to N chars (default 500), 0 = omit, negative = include in full.
Sessions & Clients
Tool | Description |
| Active session count per client |
| Active sessions for one client (SP) |
| SAML and OIDC clients in the realm |
| One client's configuration, including its authentication flow overrides (the per-SP MFA switch). Omits |
| Realm-level roles |
Morning Patrol
Tool | Description |
| Report the running server version and verify the KeyCloak backend is reachable and the service account can authenticate. Lightweight (one token request; no user/event/session scans). Returns a fixed-shape dict with |
| One-shot morning health check: login stats, brute-force IPs, spray check (same rule as |
Related MCP server: mcp-keycloak
Setup
# uv
uv pip install keycloak-mcp
# pip
pip install keycloak-mcpFrom source:
git clone https://github.com/shigechika/keycloak-mcp.git
cd keycloak-mcp
# uv
uv sync
# pip
pip install -e .Configuration
Variable | Description | Default |
| Base URL, e.g. | required |
| Realm name |
|
| Service Account client ID | required |
| Client secret | required |
| INI file for IP-to-site labeling (see below) | unset |
| Comma-separated CIDRs of known shared egress points (VDI, VPN concentrators, partner proxies). | unset |
| Default look-back window for event tools when |
|
| Per-call wall-clock budget (seconds) for the heavy event/TOTP tools. When a wide window / large realm would exceed it, the tool stops and returns a disclosed partial (⚠️ warning) instead of running past the client's ~60s gateway timeout and hammering KeyCloak. Each request's timeout is also capped at the time left, and nothing is retried past the deadline, so one slow page cannot run a call past it. |
|
| Per-pagination cap on events fetched by the event tools (also bounds how deep the slow high-offset pagination goes). Over the cap the result is a disclosed partial. |
|
| Default cap on users scanned by |
|
| Comma-separated custom user-attribute keys that | unset |
| Enables the opt-in group-change tools ( | unset |
|
| unset |
| Maximum rows per group-change call. |
|
|
|
|
| Directory for the daily configuration snapshots ( | unset |
| Time budget (seconds) for the group-change tools. A batch of 30 users needs more than the default 45 s; raise it where nothing with a ~60 s timeout sits in front of the server (for example a client that spawns it directly). Unset: | unset |
| Separate connections whose session listings |
|
|
|
|
| Upper bound on |
|
KeyCloak client setup
Create a new client in the KeyCloak admin console.
Turn on Client authentication and Service account roles.
Give it
view-users,view-events,view-clients, and — only if you need password reset —manage-users.
Write operations
Four tools change state by default. Everything else only reads. With group changes
enabled (below), apply_group_changes is a fifth.
Tool | Admin API call |
|
|
| the same call, once per CSV row |
|
|
|
|
All four need manage-users on the Service Account. Leave that role off and the
server is read-only: those four tools fail with 403 and every other tool keeps
working, so a realm can be handed to an AI assistant for investigation without granting any
ability to modify it. Grant manage-users only when account recovery or
containment is part of the job.
Group changes (opt-in)
plan_group_changes and apply_group_changes move users between groups (for example
staff transfers). They exist only when KEYCLOAK_GROUP_WRITE_ROOT is set, so a
deployment that shares the binary without an approval step never exposes them.
Tool | Admin API call |
| read-only: |
|
|
plan_group_changesresolves every user and group by exact name/path and returns, per row, the current direct groups, the operations that would run and a status. Itsdigestcovers the resolved IDs, each user's current groups and the policy.apply_group_changesre-plans and changes nothing unless every row is still executable and the digest equals the approved one, so a membership changed by anyone since the plan aborts the whole batch. It adds before it removes, vets the destination again right before adding, re-reads memberships before each write and reads them back after it, and stops at the first mismatch, error or exhausted time budget (KEYCLOAK_GROUP_DEADLINE). It does not start a user whose operations cannot all finish in the time left, so a stop does not split an add from its remove.appliedisyes,no,partialorunknown(a write that could not be read back).With
KEYCLOAK_GROUP_MODE=singlea move is one add: the server drops the old group itself, so no DELETE is sent and the read-back must show the destination alone. A row must name the group to add (a remove-only row would leave the user in no group). An omittedremoveis filled in with the user's current group so the approver sees what is left, and that group is vetted like aremoveat plan time and again right before the add. A user in more than one group breaks the server's rule and is refused (fix them by hand). Users whose previous state a plan cannot restore (they had no group, or the server turned out not to replace) are listed inmanual_restoreinstead ofreverse. Set it when your KeyCloak behaves this way; inmultimode such a server makes every move stop as a concurrent change, and insinglemode a server that keeps the old group makes the move stop with a message that the mode does not match.Refused targets: anything outside the root, the root itself, and protected groups and their descendants.
A group that carries roles is not refused: moving someone into a department's admin group is an ordinary transfer when the approver can do the same in the admin console. Each plan row lists
gained_rolesandlost_roles: the difference the move makes to the roles the user holds through all their group memberships (a role kept through a shared ancestor or another group is neither; roles mapped to the user directly are not read).add_rolesandremove_rolesare the roles membership in each named group carries. Realm roles appear by name and client roles asclient:role; roles inherited from ancestor groups and the contents of composite roles (any depth) are included. Show the gains and losses to the person approving. They are part of thedigest, and the destination's roles are read again before each add (at most once every 5 seconds per group within one call), so a role attached (or added to a composite) after the approval stops the run. A row whose role change cannot be shown (a current group that does not resolve by path, such as one with/in its name) is refused. Changed in 1.3.0: earlier versions refused any group with role mappings. If you relied on that, list those groups inKEYCLOAK_PROTECTED_GROUPSbefore upgrading.Membership can grant access without any role (a SAML/OIDC group mapper that a service provider checks, an authorization-services group policy). List the groups that must never be written by these tools, whatever their roles, in
KEYCLOAK_PROTECTED_GROUPS. Every protected path must exist in KeyCloak: if one does not resolve (renamed, moved, different case), every plan is refused until the configuration is fixed.The
digestshows that nothing changed since the plan. It does not prove that a person approved the plan: any caller ofplan_group_changesgets a valid digest. Put the approval in front ofapply_group_changes, for example a client that keeps the digest itself and asks a person before each call. Treat each approval as single-use: if the memberships return to the planned state (for example afterreverse), the old digest matches again.The result includes
reverse, the changes that would undo what took effect. It is a proposal for a new plan and approval, never applied automatically. Restoring a membership does not undo access that happened while it was wrong.
Writes need manage-users. Depending on the KeyCloak version, reading groups and their
role mappings may also need query-groups. Expanding composite roles reads realm roles
(view-realm) and naming client roles reads clients (view-clients). Run
plan_group_changes once to confirm.
Configuration snapshots (optional)
With KEYCLOAK_STATE_DIR set, the first daily_brief of each day stores a snapshot of the
realm configuration, and every daily_brief compares the current configuration with the
latest snapshot from an earlier day. Changes are a [CONFIG] warning with the changed
fields; get_config_changes lists all of them.
Covered: realm settings (brute-force detection, password and OTP policies, session and token lifespans, flow bindings), event settings, realm roles and what each composite role contains, authentication flows and their executions, required actions, clients (redirect URIs, allowed flows, flow overrides, attributes, protocol mappers), client scopes, default client scopes, components, and identity providers when the service account may read them. Group role mappings and client roles are not in the snapshot; their admin events are reported instead.
Group memberships are not configuration and are not in the snapshot. Instead the brief lists the additions in its look-back window to groups that carry a role (their own or an ancestor's, through composites), with the roles, the user, and who added them. An addition is
[PRIVILEGE]when the group grants arealm-managementrole other thanquery-*/view-*(realm-admin,manage-users, ...); in the master realm also a<realm>-realmadmin-client role or theadminrealm role. The group is read by its ID as it is now and its roles are followed throughparentId, so a rename or move since the event does not hide it. An addition whose group cannot be read is a[CONFIG]warning of its own; the check has at most 8 s of the Configuration section's budget.Secrets are not stored: string values under keys containing
secret,password,privateKey,apiKey,credential,tokenand similar (the markersget_useralso uses) are replaced with<redacted>, so a changed secret does not show as a change.true/falseand numbers under such keys are settings and stay visible, except under a field that is itself a secret (...password,...secret). This is a safety net for the common names, not a guarantee. Long values (certificates, public keys) are stored as a hash.Only a complete read is stored. When the time budget runs out, the brief says the comparison was skipped and the previous baseline stays.
Snapshots are written only by
daily_brief, and only the first one of a day, so a change made during the day is reported again the next morning. The last 30 are kept.Reading the configuration needs
view-realmandview-clients; identity providers also needview-identity-providers. Without it that section is left out of the comparison and the brief says so.
Verify your setup
After setting the environment variables, run --check to confirm authentication works before wiring it into an MCP client:
export KEYCLOAK_URL=https://keycloak.example.com
export KEYCLOAK_REALM=my-realm
export KEYCLOAK_CLIENT_ID=keycloak-mcp
export KEYCLOAK_CLIENT_SECRET=your-secret
keycloak-mcp --check
# HTTP Request: POST https://keycloak.example.com/realms/my-realm/protocol/openid-connect/token "HTTP/1.1 200 OK"
# OK: authenticated to https://keycloak.example.com/admin/realms/my-realmExit codes: 0 success, 1 configuration error (missing variable), 2 authentication error.
IP-to-site labeling (optional)
Point KEYCLOAK_SITES_INI at an INI file if you want IP addresses in tool output to be tagged with your site names. Tools like get_user_sessions, get_events, and get_login_failures_by_ip pick it up automatically; anything outside your declared ranges is labeled external. Leave the variable unset and IPs are shown as-is.
See sites.ini.example. A minimal file:
[hq]
name = HQ (Tokyo)
ipv4 = 192.0.2.0/24, 198.51.100.0/24
ipv6 = 2001:db8:1::/48
[vpn]
name = VPN
ipv4 = 10.0.0.0/8, 172.16.0.0/12One site per [section]. name is the display label (falls back to the section name). ipv4 / ipv6 take comma-separated CIDRs; a single host is /32 or /128. Matching is first-match in file order — put specific ranges before broad ones.
Usage
Claude Code (plugin)
This repository doubles as a single-plugin marketplace, so Claude Code can install the server for you:
/plugin marketplace add shigechika/keycloak-mcp
/plugin install keycloak-mcp@keycloak-mcpThe plugin launches uvx keycloak-mcp and reads the same environment variables
described in Configuration; export them before starting Claude
Code. KEYCLOAK_REALM falls back to master and KEYCLOAK_SITES_INI may stay
unset.
uvx must be on the PATH of the process that runs Claude Code — a login
shell usually has it, but a GUI-launched app may not; install
uv system-wide if the plugin fails to start.
Claude Code (manual)
In .mcp.json:
{
"mcpServers": {
"keycloak-mcp": {
"type": "stdio",
"command": "keycloak-mcp",
"env": {
"KEYCLOAK_URL": "https://keycloak.example.com",
"KEYCLOAK_REALM": "my-realm",
"KEYCLOAK_CLIENT_ID": "keycloak-mcp",
"KEYCLOAK_CLIENT_SECRET": ""
}
}
}
}Claude Desktop
In claude_desktop_config.json:
{
"mcpServers": {
"keycloak-mcp": {
"command": "keycloak-mcp",
"env": {
"KEYCLOAK_URL": "https://keycloak.example.com",
"KEYCLOAK_REALM": "my-realm",
"KEYCLOAK_CLIENT_ID": "keycloak-mcp",
"KEYCLOAK_CLIENT_SECRET": ""
}
}
}
}Codex
codex mcp add keycloak-mcp \
--env KEYCLOAK_URL=https://keycloak.example.com \
--env KEYCLOAK_REALM=my-realm \
--env KEYCLOAK_CLIENT_ID=keycloak-mcp \
--env KEYCLOAK_CLIENT_SECRET=your-secret \
-- keycloak-mcpAny other MCP client that launches stdio servers works the same way: give it
keycloak-mcp as the command and set the KEYCLOAK_* variables in its
environment.
From a shell
export KEYCLOAK_URL=https://keycloak.example.com
export KEYCLOAK_REALM=my-realm
export KEYCLOAK_CLIENT_ID=keycloak-mcp
export KEYCLOAK_CLIENT_SECRET=your-secret
keycloak-mcpCLI
keycloak-mcp --version # Print version and exit
keycloak-mcp --help # Show usage and required environment variables
keycloak-mcp --check # Verify env vars and authentication, then exit
keycloak-mcp # Run the MCP STDIO server (default)No-argument mode is the normal one — that's how MCP clients launch it.
Daily spray report (batch)
spray_check looks at a rolling window ending now, which is right for a patrol but cannot be archived day by day. For that, run the same analysis over one calendar day from a scheduled job:
keycloak-mcp spray-report --date 2026-09-17 --tz Asia/Tokyo > 2026-09-17.jsonThe window is
[DATE 00:00, DATE+1 00:00)in--tz(default: the host's zone). Use the zone the KeyCloak server logs in, becausedateFrom/dateToare interpreted there. Events are cut to the window by timestamp on both ends.One JSON document goes to stdout; errors go to stderr with a non-zero exit (2 = configuration, 1 = fetch/auth), and nothing is written to stdout in that case.
The output is the
spray_checkshape with every external IP that has at least one event carrying a username inexternal_ips(min_report_users=1), plusexternal_totals, which counts LOGIN / LOGIN_ERROR for every external IP — including IPs whose failures carry no username at all and therefore have no row,fetch_complete,resolve_complete,coverage(first_event,last_event,head_gap_seconds,tail_gap_seconds),schema,keycloak_mcp_versionandsites_ini_sha256. Treat a day as final only when both*_completeflags are true and neither gap is large; a gap at one end usually means--tzdiffers from the KeyCloak server's zone.It refuses to run when
KEYCLOAK_SITES_INIyields no ranges (every IP would count as external) unless--allow-no-sitesis given, and whenKEYCLOAK_KNOWN_EGRESShas an entry that is not a CIDR.Its own limits apply (
--deadline 900,--max-events 1000000,--max-resolves 2000), notKEYCLOAK_DEADLINE/KEYCLOAK_MAX_EVENTS, which are sized for a tool call behind an HTTP gateway.The output contains source IPs and usernames. Keep it out of anything published.
Development
git clone https://github.com/shigechika/keycloak-mcp.git
cd keycloak-mcp
# uv
uv sync --dev
uv run pytest -v
uv run ruff check .
# pip
python3 -m venv .venv
.venv/bin/pip install -e . && .venv/bin/pip install pytest pytest-cov respx ruff
.venv/bin/pytest -v
.venv/bin/ruff check .Live smoke test
pytest checks logic against fixtures; it cannot tell you that a tool has
stopped returning real data. scripts/smoke_test.py runs every registered
tool against the configured realm and fails on empty, malformed or error
answers:
# needs KEYCLOAK_URL / KEYCLOAK_CLIENT_ID / KEYCLOAK_CLIENT_SECRET
uv run python scripts/smoke_test.py
uv run python scripts/smoke_test.py --only login_stats --tracebackRead-only. Every state-changing tool (
reset_password,logout_user,set_user_enabled,reset_passwords_batch) is skipped by name, and a test enforces that. The report prints tool names and statuses only — never payloads, and server-authored error text is redacted too (KeyCloak quotes the username it was asked about);--tracebackstill shows the full text on the operator's own terminal.Arguments that would identify real users, groups or IPs are discovered at run time, never written into
scripts/smoke_probes.py.CI enforces the cheap half: a tool registered without a probe spec fails the build (
tests/test_smoke_probes.py), so adding a tool forces the question "how would we know it works?".scripts/smoke_harness.pyis the engine and holds no KeyCloak knowledge: it is kept identical across the servers that share it, so fix engine bugs once and sync the file rather than patching this copy.
License
MIT
Available Tools
33 toolscount_usersA
Get total user count in the realm.
Inputs: no named parameters. Returns: result
daily_briefA
Run a morning Keycloak health check.
Checks (all scoped to the last since_hours hours):
Login statistics (success / failure totals, top failing IPs)
Active sessions by client
Password update events
Admin events (CREATE/UPDATE/DELETE on USER/CLIENT resources)
Configuration: admin events that change roles, role mappings, flows, client scopes, protocol mappers, components or the realm, and (when KEYCLOAK_STATE_DIR is set) what changed since the last daily snapshot. The first run of each day records that day's snapshot;
get_config_changeslists every change.
A single IP with login failures >= ip_failure_threshold is flagged
as WARNING (possible brute-force). Independently, the same login events
are run through the spray_check rule (external IP, >= 10 distinct
users, success rate < 20%); a match is a [SPRAY] WARNING and the
"Spray check" section lists the breached accounts with their evidence
tuples (time / ip / username / client). Only accounts in that list may be
called breached — see spray_check for the full row shape and to widen
the window or tune the thresholds.
since_hours defaults to 18 (≈ previous 15:00 for a 09:00 morning run).
Output tiers:
CRITICAL — API connection failure
WARNING — anomalies detected
OK — clean
Args: since_hours: Look-back window in hours (default 18). ip_failure_threshold: Login failures from a single IP that triggers a WARNING (default 50).
Inputs: since_hours, ip_failure_threshold. Returns: result
detect_login_loopsA
Detect users with rapid repeated logins (possible redirect loops).
Scans all LOGIN events and finds users who logged in more than threshold
times within window_seconds.
Time-bounded: this call stops after KEYCLOAK_DEADLINE seconds (default 45) and returns what it has; the counts are then a lower bound. The result then starts with a "PARTIAL RESULT" warning. Call again with a narrower window instead of retrying the same call. A wide window on a busy day is what triggers it.
Args: date_from: Start date (YYYY-MM-DD). Defaults to last 24h when omitted (KEYCLOAK_DEFAULT_DATE_FROM_HOURS). date_to: End date (YYYY-MM-DD). Empty for all. threshold: Minimum logins within the window to flag (default 10). window_seconds: Time window in seconds (default 60). top: Number of top users to show (default 20). Use 0 for all.
Inputs: top, date_to, date_from, threshold, +1 more. Returns: result
get_admin_eventsA
Get KeyCloak admin events (changes performed via the Admin REST API).
Admin events record operations performed by service accounts or admin users
— e.g. custom user attribute updates (provisioning_flag), role / group
assignments, client configuration changes. These are distinct from user
events (login / password change). Use this when UPDATE_PROFILE in
get_events is empty but an attribute is known to have changed.
Args: operation_types: Comma-separated list of CREATE, UPDATE, DELETE, ACTION. resource_types: Comma-separated list of USER, CLIENT, ROLE, GROUP, REALM_ROLE, etc. resource_path: Filter by resource path (e.g. "users/{userId}"). date_from: Start date (YYYY-MM-DD). Defaults to last 24h when omitted (KEYCLOAK_DEFAULT_DATE_FROM_HOURS). date_to: End date (YYYY-MM-DD). max_results: Maximum results (default 50). max_repr: Max chars of the representation field. 0 = omit, -1 = full.
Inputs: date_to, max_repr, date_from, max_results, +3 more. Returns: result
get_brute_force_statusA
Check if a user is temporarily locked due to brute force detection.
Args: username: Exact username (email).
Inputs: username (required). Returns: result
get_clientA
Show one client's configuration, including its authentication flow overrides.
Reports an explicit allowlist of fields rather than the raw client
representation. A client representation can carry secret,
registrationAccessToken and, for SAML clients, signing material under
attributes; attributes and protocolMappers are therefore omitted
entirely rather than filtered, so nothing credential-shaped reaches tool
output, hence LLM context.
The headline is authenticationFlowBindingOverrides: pinning one client
to a non-default browser flow is how a single SP is made to require OTP
while the realm default stays untouched. KeyCloak stores those overrides as
flow IDs, so they are resolved to flow aliases here.
Args: client_id: The clientId (not the internal UUID).
Inputs: client_id (required). Returns: result
get_client_sessionsA
Get active sessions for a specific client (SP).
Args: client_id: Client ID (e.g., 'xflow', 'shadowserver'). max_results: Maximum results (default 100).
Inputs: client_id (required), max_results. Returns: result
get_config_changesA
Compare the realm configuration now with a stored daily snapshot (read-only).
Covers realm settings (brute force detection, password and OTP policies, session and
token lifespans, flow bindings), event settings, realm roles and the contents of
composite roles, authentication flows and their executions, required actions,
clients (redirect URIs, flows allowed, flow overrides, protocol mappers), client
scopes, default client scopes, components and, when readable, identity providers.
Values under credential-named keys (secret, password, privateKey,
apiKey, ...) are replaced with <redacted> before anything is compared or stored,
so a changed secret does not show as a change.
The snapshots are written by daily_brief (the first run of each day); this tool
never writes one. Use it to see the full list when daily_brief reports [CONFIG]
changes, or to compare against an older day.
Args: baseline_date: Snapshot to compare against (YYYY-MM-DD). Default: the latest snapshot before today.
Inputs: baseline_date. Returns: result
get_eventsA
Get KeyCloak events with optional filters.
Args: event_type: Event type filter (e.g., LOGIN, LOGIN_ERROR, UPDATE_PASSWORD). username: Filter by exact username (email). Resolved to user ID internally. client_id: Filter by client ID (SP name). ip_address: Filter events by source IP (client-side filter). date_from: Start date (YYYY-MM-DD). Defaults to last 24h when omitted (KEYCLOAK_DEFAULT_DATE_FROM_HOURS). date_to: End date (YYYY-MM-DD). max_results: Maximum results (default 50).
Inputs: date_to, username, client_id, date_from, +3 more. Returns: result
get_ip_activityA
Exhaustive investigation of all activity from one source IP address.
Unlike get_events(ip_address=...), which filters a single page and can
miss activity outside the most recent max_results events, this tool
fully paginates every requested event type (via get_events_all) before
filtering by IP, so the result is exhaustive over the requested date
range. Use this for brute-force / credential-stuffing / shared-workstation
investigations where get_login_failures_by_ip told you which IP to
look at and you now need the full picture for that one IP.
Returns a fixed-shape dict (JSON), not formatted text — every key below is always present, even when zero events match.
Returns:
error: None on success. Set to a descriptive message if event_types
resolved to no event types (e.g. empty or all-whitespace/commas);
every other key is still present, with an empty/zero result in
that case (no data was fetched).
ip_address: Echoes the input.
site: Site name from KEYCLOAK_SITES_INI, or null if unmatched or
unconfigured (see sites_configured to tell those apart).
sites_configured: True if KEYCLOAK_SITES_INI was loaded at all.
date_from / date_to: The resolved date range actually scanned.
event_types: The event types scanned (echoes the input, split).
summary: total_events, login_success, login_failure, unique_users,
unique_clients, first_seen/last_seen (ISO 8601, null if no match).
login_success/login_failure classify EVERY scanned event type by
whether its type ends in "_ERROR" (matching the users/clients
breakdown below), not just literal LOGIN/LOGIN_ERROR — so widening
event_types always keeps these numbers reconciled with the
per-user/per-client totals. Always computed over the FULL matched
set, unaffected by max_timeline truncation.
users: Per-user breakdown (success/failure counts, distinct error
codes), sorted by total activity descending. Note: successful
LOGIN events often carry only a userId (UUID) while LOGIN_ERROR
carries details.username — this tool keys on
username-or-userId-or-"unknown", so the same human can
legitimately appear under two different keys across success vs.
failure events.
clients: Per-client (SP) breakdown, same shape, sorted descending.
timeline: Chronological event list, capped at max_timeline (most
recent kept on overflow — see truncated). max_timeline<=0 returns
an empty timeline.
truncated: True if timeline was capped; summary/users/clients are
never affected by this cap.
events_capped: True if event pagination itself was cut short by the
wall-clock deadline (KEYCLOAK_DEADLINE) or the per-type cap
(KEYCLOAK_MAX_EVENTS) — i.e. the window was too wide and the WHOLE
result (summary/users/clients/timeline) is incomplete. Distinct from
truncated, which only trims the timeline of an otherwise-complete
scan. Narrow date_from when this is true.
Time-bounded: this call stops after KEYCLOAK_DEADLINE seconds (default 45) and
returns what it has; the counts are then a lower bound. The returned dict then has
events_capped: true (no warning text); narrow date_from / date_to.
Call again with a narrower window instead of retrying the same call. A wide window
on a busy day is what triggers it.
Args: ip_address: Source IP to investigate. Compared against KeyCloak's recorded ipAddress field after normalizing both sides through Python's ipaddress module (so equivalent IPv6 notations like "::1" and "0:0:0:0:0:0:0:1" match); falls back to a raw string compare if either side doesn't parse as an IP. event_types: Comma-separated KeyCloak event types to scan (default "LOGIN,LOGIN_ERROR"). Widen with e.g. "LOGIN,LOGIN_ERROR,LOGOUT,UPDATE_PASSWORD,CLIENT_LOGIN,CLIENT_LOGIN_ERROR" for a broader sweep. Must resolve to at least one type. date_from: Start date (YYYY-MM-DD). Defaults to last 24h when omitted (KEYCLOAK_DEFAULT_DATE_FROM_HOURS). Widening the window means fully paginating every event type over that window before filtering — expect it to be slower on large realms. date_to: End date (YYYY-MM-DD). Empty for open-ended. max_timeline: Cap on the number of most-recent timeline entries returned (default 200; <=0 means no timeline entries). Does not affect summary/users/clients.
Inputs: ip_address (required), date_to, date_from, event_types, +1 more.
get_login_failures_by_ipA
Get login failure statistics broken down by source IP.
Time-bounded: this call stops after KEYCLOAK_DEADLINE seconds (default 45) and returns what it has; the counts are then a lower bound. The result then starts with a "PARTIAL RESULT" warning. Call again with a narrower window instead of retrying the same call. A wide window on a busy day is what triggers it.
Args: date_from: Start date (YYYY-MM-DD). Defaults to last 24h when omitted (KEYCLOAK_DEFAULT_DATE_FROM_HOURS). date_to: End date (YYYY-MM-DD). Empty for all. top: Number of top IPs to show (default 20).
Inputs: top, date_to, date_from. Returns: result
get_login_statsA
Get login success/failure statistics with full pagination.
Time-bounded: this call stops after KEYCLOAK_DEADLINE seconds (default 45) and returns what it has; the counts are then a lower bound. The result then starts with a "PARTIAL RESULT" warning. Call again with a narrower window instead of retrying the same call. A wide window on a busy day is what triggers it.
Args: date_from: Start date (YYYY-MM-DD). Defaults to last 24h when omitted (KEYCLOAK_DEFAULT_DATE_FROM_HOURS). date_to: End date (YYYY-MM-DD). Empty for all.
Inputs: date_to, date_from. Returns: result
get_login_stats_by_clientA
Get login statistics broken down by client (SP).
Time-bounded: this call stops after KEYCLOAK_DEADLINE seconds (default 45) and returns what it has; the counts are then a lower bound. The result then starts with a "PARTIAL RESULT" warning. Call again with a narrower window instead of retrying the same call. A wide window on a busy day is what triggers it.
Args: date_from: Start date (YYYY-MM-DD). Defaults to last 24h when omitted (KEYCLOAK_DEFAULT_DATE_FROM_HOURS). date_to: End date (YYYY-MM-DD). Empty for all.
Inputs: date_to, date_from. Returns: result
get_login_stats_by_hourA
Get login statistics broken down by hour (local time).
Time-bounded: this call stops after KEYCLOAK_DEADLINE seconds (default 45) and returns what it has; the counts are then a lower bound. The result then starts with a "PARTIAL RESULT" warning. Call again with a narrower window instead of retrying the same call. A wide window on a busy day is what triggers it.
Args: date_from: Start date (YYYY-MM-DD). Defaults to last 24h when omitted (KEYCLOAK_DEFAULT_DATE_FROM_HOURS). date_to: End date (YYYY-MM-DD). Empty for all.
Inputs: date_to, date_from. Returns: result
get_password_update_eventsA
Get password update events.
Args: date_from: Start date (YYYY-MM-DD). Defaults to last 24h when omitted (KEYCLOAK_DEFAULT_DATE_FROM_HOURS). date_to: End date (YYYY-MM-DD). max_results: Maximum results (default 100).
Inputs: date_to, date_from, max_results. Returns: result
get_realm_rolesA
List all realm-level roles.
Inputs: no named parameters. Returns: result
get_realm_security_defensesA
Show the realm's security-defense settings (read-only).
Reports the realm-level security configuration that the admin console groups under "Security defenses":
Brute force detection: whether it is enabled, the lockout strategy, and the thresholds (max login failures, wait increments, reset window).
Password policy.
Browser security headers.
Use this to verify that brute-force protection is actually turned on and
how aggressively it locks accounts — the per-user get_brute_force_status
only reflects runtime state, not whether the policy itself is configured.
Inputs: no named parameters. Returns: result
get_session_statsA
Get active session count per client.
Inputs: no named parameters. Returns: result
get_totp_usersA
Report how many users have TOTP (OTP) configured across the realm.
Enumerates users and inspects each one's credentials for an otp entry.
KeyCloak has no bulk credential endpoint, so this makes one credential
request per user (N+1) — expect it to be slow on large realms; bound it with
max_users (which also short-circuits the user enumeration). Users whose
credential lookup fails are counted separately and skipped, so a single
transient error does not abort the whole scan.
Args:
enabled_only: Only scan enabled users (default True).
list_users: Include the list of usernames with TOTP (default True).
max_users: Cap the number of users scanned. 0 (default) falls back to
KEYCLOAK_MAX_USERS (default 5000) rather than the whole realm.
The N+1 credential loop is also bounded by KEYCLOAK_DEADLINE, so
a large realm returns a disclosed sample. When capped, the
percentage covers only the sample, not the realm.
Inputs: max_users, list_users, enabled_only. Returns: result
get_userA
Get detailed user information by exact username (email).
If KEYCLOAK_USER_ATTRIBUTE_WHITELIST names any custom attribute keys, this
also does one extra by-ID lookup and appends whichever of those keys are
present on the user (the search endpoint used to resolve the username
returns a brief representation that omits attributes entirely). A
whitelisted key whose name looks credential-shaped (contains "password",
"secret", "token", etc. — see _looks_like_credential_key) is reported as
blocked rather than shown, as a safety net on top of the whitelist itself.
Args: username: Exact username (e.g., user@example.com).
Inputs: username (required). Returns: result
get_user_attribute_historyA
Get admin-side attribute change history for a single user.
Queries admin events scoped to users/{userId} with UPDATE / ACTION
operations. Intended for tracking custom attribute changes such as
provisioning_flag which are written by admin API and do not surface in
get_events (which only shows user-driven events like LOGIN /
UPDATE_PASSWORD).
Args: username: Exact username (email). date_from: Start date (YYYY-MM-DD). Defaults to last 24h when omitted (KEYCLOAK_DEFAULT_DATE_FROM_HOURS). date_to: End date (YYYY-MM-DD). max_results: Maximum results (default 100). max_repr: Max chars of the representation field. 0 = omit, -1 = full.
Inputs: username (required), date_to, max_repr, date_from, +1 more. Returns: result
get_user_credentialsA
List the credential types configured for one user (password, otp, webauthn, …).
Use this to check a single user's MFA status: an otp credential means
TOTP/HOTP is configured. Reads /users/{id}/credentials (read-only; does
not create a session).
Args: username: Exact username (email).
Inputs: username (required). Returns: result
get_user_sessionsA
Get active sessions for a user.
Sessions are listed over several separate connections and merged, because behind a load balancer a KeyCloak node that does not share sessions with the others lists only its own (KEYCLOAK_SESSION_PROBES, default 8).
Args: username: Exact username (email).
Inputs: username (required). Returns: result
health_checkA
Report server version and KeyCloak backend connectivity / authentication.
Call this at session start (or after a tool-call timeout) to confirm the MCP is up, see which version is running, and verify the KeyCloak Admin API is reachable and the service account can authenticate. Lightweight: it acquires an admin access token via the Client Credentials Grant (reusing the cached client) and does NOT enumerate users, events, or sessions.
Always returns the same keys: status (healthy / degraded / error),
service, version, keycloak_url (configured base URL, empty if
unset), realm (configured realm), keycloak_version (None — not exposed
by a cheap call), and auth (ok / error / missing-env). On a degraded or
error result, detail carries the reason.
This description is the only place those value sets are written down. The READMEs used to repeat them, which is three copies to keep in step and two that an LLM never reads — it is handed this text.
Inputs: no named parameters.
list_clientsA
List all SAML/OIDC clients in the realm.
Inputs: no named parameters. Returns: result
list_user_groupsA
List groups a user belongs to.
Args: username: Exact username (email).
Inputs: username (required). Returns: result
list_users_by_groupA
List all users in a group.
Args: group_name: Group name (partial match). max_results: Maximum results (default 100).
Inputs: group_name (required), max_results. Returns: result
logout_userA
Force logout a user by removing all their active sessions.
Each probe opens its own connection, lists the user's sessions and logs the
user out on the node it reached when that node lists a session. Until one
logout has gone through it is sent even when the node lists nothing: it also
sets the user's notBefore in the database, so tokens issued before it are
rejected by every node. Probing goes
on until no session is seen on KEYCLOAK_LOGOUT_CLEAN_PROBES probes in a row
(default 10), at most KEYCLOAK_LOGOUT_MAX_PROBES (default 40), so that nodes
that do not share sessions behind a load balancer are all reached. The
resulting notBefore is reported. The whole run is bounded by
KEYCLOAK_DEADLINE; when it runs out or a request fails, the result says
verification is incomplete, with what was done so far.
Args: username: Exact username (email).
Inputs: username (required). Returns: result
reset_passwordA
Reset a user's password.
Args: username: Exact username (email). password: New password to set. temporary: If True, user must change password on next login.
Inputs: password (required), username (required), temporary. Returns: result
reset_passwords_batchA
Reset passwords for multiple users from CSV text.
Each line should be: username,password If password column is empty, a random 12-char password is generated and included in the response (the caller cannot recover it otherwise). Caller-supplied passwords are never echoed back.
Args: csv_text: CSV text with username,password per line (header optional). temporary: If True, users must change password on next login.
Inputs: csv_text (required), temporary. Returns: result
search_usersA
Search users by username, email, first name, or last name.
Args: query: Search string (partial match). max_results: Maximum results to return (default 20).
Inputs: query (required), max_results. Returns: result
set_user_enabledA
Enable or disable a user account.
Disabling blocks all authentication (SSO logins) for the user — the
containment action for a compromised or decommissioned account. Only the
enabled flag is changed; custom attributes are preserved.
Disabling does not terminate existing sessions (an already-issued token
stays valid until it expires), so when disabling this reports how many
sessions remain and to run logout_user to end them immediately.
Args: username: Exact username (email). enabled: True to enable, False to disable.
Inputs: enabled (required), username (required). Returns: result
spray_checkA
Detect password-spray sources and name the accounts they breached — one rule, one call.
For every EXTERNAL source IP (anything outside the ranges declared in
KEYCLOAK_SITES_INI) seen in LOGIN / LOGIN_ERROR events during the last
hours, compute distinct users and success rate. An IP is a spray source
when unique_users >= min_users AND success_rate < max_success_rate.
Its successful logins are the breach CANDIDATES; whether they may be
called breached depends on the row's confidence.
The breach list is built ONLY from LOGIN events whose source IP is the
flagged IP, inside the window. Every entry carries the evidence tuple
{time, ip, username, user_id, client_id}. A compromised account can
therefore never be reported without an actual login event from the spray
source — do not add names that are not in spray[].breached.
confidence separates a spray from a shared egress (school NAT, home
line, VDI) that merely looks like one by volume. It is "low" — treat the
successes as "verify with the owner", never publish them as breached —
when any of these signals holds: user_success_rate (distinct
users that logged in at least once ÷ distinct users) >=
max_user_success_rate (real sprays sit at 0.0–0.06; a school NAT
with students retyping a mistyped domain sat at 0.47), or
failure_concentration (share of failures on the single most-failing
username) >= max_failure_concentration (one locked-out user retrying
from a shared line produced 0.91), or the IP is in KEYCLOAK_KNOWN_EGRESS.
Only confidence: high rows are a breach verdict. Read
top_failed_users and not_found_domains (domains of usernames that
do not exist — typos of the real domain are humans, not a scraped list)
before writing anything up.
Returns a fixed-shape dict:
window: {hours, since, until} actually scanned.
complete: False if event pagination was cut short (KEYCLOAK_DEADLINE /
KEYCLOAK_MAX_EVENTS). When False, treat the result as a lower bound
and do NOT publish a definitive verdict; narrow hours and retry.
spray: flagged IPs (see external_ips for the row shape), each with
breached = list of evidence tuples; confidence: high rows
first.
external_ips: every external IP with at least min_report_users
distinct users, flagged or not, sorted flagged-first, then
high-confidence first, then by ascending success rate — so
near-misses (e.g. 8 users at 14%) are visible without a second
rule. Row: ip, known_egress, flagged, confidence ("high"/"low"),
signals (list of the reasons for "low"), unique_users,
users_with_success, user_success_rate, failure_concentration,
top_failed_users (up to 5 {username, failures}),
not_found_domains (domain -> count for user_not_found
usernames), attempts, successes, failures, success_rate, errors
(error-code counter; user_not_found mixed with
invalid_user_credentials on many DIFFERENT names indicates a
scraped username list — on the same few names it is a human
retyping), first_seen, last_seen, unresolved_user_ids, breached.
breached_total: number of evidence tuples across all flagged IPs.
breached_low_confidence: how many of those sit on confidence: low
rows (candidates to verify, not breaches).
internal_events_excluded: events dropped because the IP is internal.
resolves_used / resolve_capped: how many GET /users/{id} lookups were
spent resolving success userIds, and whether max_resolves (or
the shared deadline) stopped further lookups. A row's
unresolved_user_ids counts successes keyed by bare userId; if
that is non-zero on a flagged row, unique_users may be
slightly over-counted and breached[].username is the id.
known_egress_configured: whether KEYCLOAK_KNOWN_EGRESS is set. IPs in
those ranges are LABELED known_egress: true, never excluded —
a shared VDI/VPN/proxy egress with many real users is expected to
show a high success rate and usually is not flagged anyway.
Users are keyed by lowercased username on both sides: LOGIN_ERROR carries
details.username; LOGIN usually carries only userId. userIds are
mapped from the fetched events first (any event carrying both fields),
then via GET /users/{id} — only for IPs below the success-rate ceiling
(the only ones that can be flagged), at most max_resolves times, and
never past the shared KEYCLOAK_DEADLINE.
Time-bounded: this call stops after KEYCLOAK_DEADLINE seconds (default 45) and
returns what it has; the counts are then a lower bound. The returned dict then has
complete: false (no warning text); use a smaller hours.
Call again with a narrower window instead of retrying the same call. A wide window
on a busy day is what triggers it.
Args:
hours: Look-back window (default 24 — sized for a once-a-day patrol).
min_users: Distinct users an IP must touch to count as a spray (default 10).
max_success_rate: Success-rate ceiling for a spray (default 0.2).
min_report_users: Distinct users an IP needs to appear in
external_ips at all (default 3; clamped to min_users).
max_resolves: Cap on GET /users/{id} lookups per call (default 200).
max_user_success_rate: user_success_rate at or above this marks
the row confidence: low (default 0.3).
max_failure_concentration: failure_concentration at or above this
marks the row confidence: low (default 0.5).
Inputs: hours, min_users, max_resolves, max_success_rate, +3 more.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 33 tools
Most tools target a distinct resource+action (users, sessions, clients, events, config), and descriptions actively differentiate look-alikes (e.g. get_ip_activity vs get_events, get_admin_events vs get_events). The only soft overlap is among the IP-centric investigation tools (get_login_failures_by_ip, get_ip_activity, spray_check) and the several login-stat variants, but descriptions make the boundaries navigable.
Nearly all tools follow a consistent get_/list_/search_/reset_/set_ verb_noun snake_case pattern (get_user, list_clients, reset_passwords_batch, search_users). The few noun-forward names (health_check, spray_check, daily_brief) still read as verb+noun and don't break the convention.
33 tools is above the comfortable range and feels heavy, though the domain is genuinely broad (user admin, sessions, MFA, events, security analytics, config drift, health). Each tool appears to earn its place, but the surface is crowded and some analytics tools could be consolidated behind parameters.
User lifecycle is partial: read/search/count/enable/disable/reset-password exist but there is no create_user, update_user, or delete_user, and groups/roles/clients are read-only with no create/update/delete. For an observability-plus-ops surface this is workable, but a full Keycloak admin domain has notable gaps.
Maintenance
Related MCP Connectors
Managed Keycloak from any MCP client: clusters, realms, apps, SSO, users, domains, audit events.
MCP server for mandates, delegation, policy-gated execution, credential grants, and audit.
An MCP server that provides an API to LLMs to manage their JumpCloud resources.
Related MCP Servers
- AlicenseBqualityDmaintenanceA Model Context Protocol server that enables management of Keycloak users and realms through a standardized interface, providing tools for user creation, deletion, role assignment, and group management.9102 npm13MIT
- AlicenseNot gradedqualityDmaintenanceA Model Context Protocol (MCP) server that provides a natural language interface for managing Keycloak identity and access management through its REST API.MIT
- AlicenseAqualityDmaintenanceAn MCP server that lets an AI assistant inspect and modify Keycloak realm, client, and protocol-mapper configuration across multiple Keycloak hosts.7102 npmMIT
- AlicenseNot gradedqualityDmaintenanceEnables administration of Keycloak identity and access management through MCP, allowing management of realms, clients, users, roles, groups, identity providers, and sessions from any MCP client.39 npmApache 2.0