mcp-keycloak
mcp-keycloak
Сервер Model Context Protocol для Keycloak. Он позволяет MCP-совместимому клиенту (Claude Desktop, Claude Code и т. д.) просматривать и управлять realm, пользователями, клиентами, ролями и группами Keycloak — при этом безопасность полностью контролируется флагами.
Цель дизайна — безопасность по умолчанию: сервер запускается в режиме read-only, работает только со списком разрешённых realm (allowlist), защищает чувствительные realm от изменения и допускает деструктивные операции только после явного opt-in.
Возможности
Multi-realm — каждый инструмент принимает аргумент
realm; его область действия можно ограничить с помощью allowlist.Режимы доступа —
read-only→read-write→admin, выстроены по уровням: режим никогда не открывает инструменты выше своего уровня.Флаги безопасности — allowlist realm, защита чувствительных realm, контроль удаления, dry-run и журнал аудита в формате JSON (см. ниже).
Две стратегии аутентификации — сервисный аккаунт конфиденциального клиента (рекомендуется) или имя пользователя и пароль администратора.
Без тяжёлых зависимостей — тонкий Admin REST-клиент на основе fetch, плюс MCP SDK и zod.
Related MCP server: keycloak-mcp
Модель безопасности
Аспект | Флаг | По умолчанию | Эффект |
Что в целом может делать сервер? |
|
|
|
Какие realm входят в зону действия? |
| (все) | Значения через запятую. Когда список задан, любая операция с realm вне списка отклоняется. |
Какие realm навсегда остаются read-only? |
|
| Защищённые realm можно читать, но нельзя изменять или удалять, независимо от режима. |
Можно ли удалять? |
|
| Инструменты |
Предпросмотр без обращения к Keycloak |
|
| Инструменты записи/администрирования проверяют данные и логируют намерение, затем завершаются, не вызывая Keycloak. |
Журнал аудита |
|
| Для каждой контролируемой операции выводит JSON-строку в stderr ( |
Эти слои независимы — например, режим admin с KEYCLOAK_ALLOW_DELETE=false может создавать и обновлять пользователей, но не может их удалять.
Инструменты
Чтение (read-only и выше): list_realms, get_realm, list_users, get_user, count_users, list_clients, list_realm_roles, list_groups
Запись (read-write и выше): create_user, update_user, reset_password, logout_user
Администрирование (admin): delete_user
Работа с вашим MCP-клиентом
Работает с Claude Code, Claude Desktop, Cursor, OpenAI Codex CLI, Windsurf, VS Code (Copilot) и любым другим MCP-клиентом — о настройке каждого клиента см. docs/CLIENTS.md.
Установка
npm install
npm run buildНастройка
Скопируйте .env.example и заполните его, либо задайте переменные напрямую в конфигурации вашего MCP-клиента. Рекомендуемые учётные данные — конфиденциальный клиент (confidential client) с нужными вам ролями realm-management.
Запуск с Claude Desktop / Claude Code
Добавьте в конфигурацию вашего MCP-клиента (claude_desktop_config.json или через claude mcp add):
{
"mcpServers": {
"keycloak": {
"command": "node",
"args": ["/absolute/path/to/mcp-keycloak/dist/index.js"],
"env": {
"KEYCLOAK_URL": "https://keycloak.example.com",
"KEYCLOAK_CLIENT_ID": "admin-cli",
"KEYCLOAK_CLIENT_SECRET": "your-secret",
"KEYCLOAK_MODE": "read-only",
"KEYCLOAK_REALM_ALLOWLIST": "app,customers"
}
}
}
}Повышайте KEYCLOAK_MODE до read-write (а для удалений — admin + KEYCLOAK_ALLOW_DELETE=true) только тогда, когда вы намерены позволить модели вносить изменения.
Разработка
npm run dev # watch mode
npm test # unit tests for the security policy
npm run typecheckПубликация
Сервер поставляется с server.json для официального реестра MCP и со значением mcpName в mcpName для проверки владения пакетом на npm. О публикации на npm и добавлении в список MCP-реестра, Smithery, Glama, Cursor и PulseMCP см. PUBLISHING.md.
Лицензия
MIT
Available Tools
8 toolscount_usersCount usersARead-onlyIdempotent
Return the number of users in a realm, optionally matching a search term.
Inputs: realm (required), search.
get_realmGet realm settingsARead-onlyIdempotent
Fetch the configuration of a single realm. Secrets (SMTP password, codeSecret, identity-provider and LDAP credentials, secret-shaped attributes) are replaced with [REDACTED].
Inputs: realm (required).
get_userGet user by idARead-onlyIdempotent
Fetch a single user representation by their Keycloak id. Secret-shaped attribute values and credentials are replaced with [REDACTED].
Inputs: realm (required), userId (required).
list_clientsList clientsARead-onlyIdempotent
List OAuth/OIDC clients configured in a realm. Client secrets, registration access tokens, rotated secrets, private keys and other secret-shaped fields are replaced with [REDACTED].
Inputs: realm (required), clientId.
list_groupsList groupsBRead-onlyIdempotent
List groups in a realm. Secret-shaped attribute values are replaced with [REDACTED].
Inputs: realm (required), search.
list_realm_rolesList realm rolesARead-onlyIdempotent
List the realm-level roles defined in a realm. Secret-shaped attribute values are replaced with [REDACTED].
Inputs: realm (required).
list_realmsList realmsARead-onlyIdempotent
List all realms visible to the configured credentials. Realms outside the allowlist are filtered out.
Inputs: no named parameters.
list_usersList / search usersARead-onlyIdempotent
List users in a realm. Supports free-text search and pagination. Secret-shaped attribute values and credentials are replaced with [REDACTED].
Inputs: realm (required), max, first, search.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 8 tools
Each tool maps to a distinct resource+action pair: list_realms/get_realm differ by scope, list_users/get_user/count_users differ by granularity and verb, and groups, clients, and realm roles are clearly separate resources. The only near-neighbors (list_groups vs list_realm_roles) are well differentiated by Keycloak's domain semantics and the descriptions reinforce it.
All eight tools follow a strict snake_case verb_noun convention (get_realm, list_users, count_users, list_clients, list_realm_roles). No camelCase or verb-style mixing anywhere in the set.
Eight tools is well within the ideal 3-15 range and each one corresponds to a meaningful inspection target (realms, groups, users, clients, roles). Nothing looks redundant or bolted on.
The surface is purely read-only: there is no way to create, update, or delete users, groups, clients, or roles, nor to assign/remove role mappings, which are core Keycloak admin operations. There are also smaller gaps such as no get_group, get_client, or group-membership listing, so agents needing any mutation will hit a dead end.
Maintenance
Related MCP Connectors
Managed Keycloak from any MCP client: clusters, realms, apps, SSO, users, domains, audit events.
Governed MCP gateway: one endpoint for your tools, with credential custody and audit log.
MCP server for mandates, delegation, policy-gated execution, credential grants, and audit.
One MCP server for all your MCP servers: code mode, per-tool permissions, approvals and audit.
Related MCP Servers
- AlicenseAqualityBmaintenanceAn MCP server for Keycloak Admin REST API, enabling user, group, event, and security management through service account authentication.3362 PyPIMIT
- AlicenseAqualityDmaintenanceAn MCP server that lets an AI assistant inspect and modify Keycloak realm, client, and protocol-mapper configuration across multiple Keycloak hosts.7MIT
- 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.Apache 2.0
- AlicenseCqualityDmaintenanceA comprehensive MCP server for Keycloak administration, offering 80+ tools to manage users, realms, clients, roles, groups, sessions, events, organizations, and more directly from AI assistants.86MIT