Skip to main content
Glama
idoyudha

mcp-keycloak

by idoyudha

assign_realm_role_to_user

Assign Keycloak realm roles to users to manage access permissions. Specify user ID, role names, and optional realm for role assignment.

Instructions

Assign realm roles to a user.

Args:
    user_id: User ID
    role_names: List of role names to assign
    realm: Target realm (uses default if not specified)

Returns:
    Status message

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
user_idYes
role_namesYes
realmNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The handler function for the 'assign_realm_role_to_user' tool. Decorated with @mcp.tool() for automatic registration. Fetches realm role representations and assigns them to the specified user via Keycloak's role-mappings API endpoint.
    @mcp.tool()
    async def assign_realm_role_to_user(
        user_id: str, role_names: List[str], realm: Optional[str] = None
    ) -> Dict[str, str]:
        """
        Assign realm roles to a user.
    
        Args:
            user_id: User ID
            role_names: List of role names to assign
            realm: Target realm (uses default if not specified)
    
        Returns:
            Status message
        """
        # Get role representations
        roles = []
        for role_name in role_names:
            role = await client._make_request("GET", f"/roles/{role_name}", realm=realm)
            roles.append(role)
    
        await client._make_request(
            "POST", f"/users/{user_id}/role-mappings/realm", data=roles, realm=realm
        )
        return {
            "status": "assigned",
            "message": f"Roles {role_names} assigned to user {user_id}",
        }
  • The _make_request method of KeycloakClient, used by the tool to perform authenticated HTTP requests to Keycloak Admin REST API endpoints.
    async def _make_request(
        self,
        method: str,
        endpoint: str,
        data: Optional[Dict] = None,
        params: Optional[Dict] = None,
        skip_realm: bool = False,
        realm: Optional[str] = None,
    ) -> Any:
        """Make authenticated request to Keycloak API"""
        if skip_realm:
            url = f"{self.server_url}/auth/admin{endpoint}"
        else:
            # Use provided realm or fall back to configured realm
            target_realm = realm if realm is not None else self.realm_name
            url = f"{self.server_url}/auth/admin/realms/{target_realm}{endpoint}"
    
        try:
            client = await self._ensure_client()
            headers = await self._get_headers()
    
            response = await client.request(
                method=method,
                url=url,
                headers=headers,
                json=data,
                params=params,
            )
    
            # If token expired, refresh and retry
            if response.status_code == 401:
                await self._get_token()
                headers = await self._get_headers()
                response = await client.request(
                    method=method,
                    url=url,
                    headers=headers,
                    json=data,
                    params=params,
                )
    
            response.raise_for_status()
    
            if response.content:
                return response.json()
            return None
    
        except httpx.RequestError as e:
            raise Exception(f"Keycloak API request failed: {str(e)}")
  • Import statement that loads the role_tools module, triggering the evaluation of decorators like @mcp.tool() which register the tool.
    from . import role_tools
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries full burden. It states the action is 'assign' (implying mutation) and mentions a return value, but doesn't disclose critical behavioral traits: whether this requires admin permissions, if it overwrites existing roles or adds to them, what happens with invalid role names, rate limits, or error conditions. For a mutation tool with zero annotation coverage, this is inadequate.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately sized with a clear purpose statement followed by structured parameter and return sections. Every sentence earns its place, though the 'Args' and 'Returns' labels could be more natural. It's front-loaded with the core functionality.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given this is a mutation tool with no annotations, 3 parameters, and an output schema exists (so return values are documented elsewhere), the description is moderately complete. It covers what the tool does and parameters at a basic level, but lacks crucial behavioral context for safe invocation, especially around permissions, idempotency, and error handling.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must compensate. It provides basic semantic meaning for all three parameters (user_id, role_names, realm) and notes the default behavior for realm. However, it doesn't explain format expectations (e.g., UUID for user_id, valid role names), constraints, or provide examples. The value added beyond schema is minimal but covers all parameters.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('Assign realm roles') and target ('to a user'), providing specific verb+resource. It distinguishes from siblings like 'assign_client_role_to_user' by specifying 'realm roles', but doesn't explicitly contrast with other role/user management tools like 'remove_realm_role_from_user' or 'get_user_realm_roles'.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No guidance on when to use this tool versus alternatives is provided. The description doesn't mention prerequisites, when this operation is appropriate, or what happens if roles are already assigned. With many sibling tools for role/user management, this lack of differentiation is a significant gap.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/idoyudha/mcp-keycloak'

If you have feedback or need assistance with the MCP directory API, please join our Discord server