Skip to main content
Glama
idoyudha

mcp-keycloak

by idoyudha

add_user_to_group

Assign a user to a group in Keycloak identity management by specifying user ID, group ID, and optional realm to manage access permissions.

Instructions

Add a user to a group.

Args:
    user_id: User ID
    group_id: Group ID
    realm: Target realm (uses default if not specified)

Returns:
    Status message

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
user_idYes
group_idYes
realmNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The core handler function for the 'add_user_to_group' tool. It is decorated with @mcp.tool() which serves as the registration. The function makes a PUT request to the Keycloak API endpoint /users/{user_id}/groups/{group_id} using the KeycloakClient to add the user to the group and returns a success message.
    @mcp.tool()
    async def add_user_to_group(
        user_id: str, group_id: str, realm: Optional[str] = None
    ) -> Dict[str, str]:
        """
        Add a user to a group.
    
        Args:
            user_id: User ID
            group_id: Group ID
            realm: Target realm (uses default if not specified)
    
        Returns:
            Status message
        """
        await client._make_request(
            "PUT", f"/users/{user_id}/groups/{group_id}", realm=realm
        )
        return {"status": "added", "message": f"User {user_id} added to group {group_id}"}
  • Supporting helper method _make_request in KeycloakClient class, used by the tool handler to perform authenticated HTTP requests to the Keycloak Admin API, handling token refresh and realm targeting.
    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)}")
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It mentions the operation but doesn't specify whether this requires admin permissions, what happens if the user is already in the group, or any rate limits. The description is minimal and lacks critical behavioral context for a mutation tool.

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 and front-loaded with the core purpose. The Args/Returns sections are structured but could be more integrated. Every sentence serves a purpose, though some could be more informative.

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, 0% schema description coverage, but with an output schema (which handles return values), the description is minimally adequate. It covers the basic operation and parameters but lacks important context about permissions, error conditions, and behavioral details that would be needed for safe usage.

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 lists all three parameters with brief explanations, adding meaning beyond the bare schema. However, it doesn't provide format details (e.g., UUID format for IDs) or clarify what 'default' realm means, leaving some semantic gaps.

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 ('Add a user to a group') with specific verb and resources. It distinguishes itself from sibling tools like 'remove_user_from_group' by specifying the opposite operation, though it doesn't explicitly differentiate from other user-group management tools.

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 is provided on when to use this tool versus alternatives like 'assign_client_role_to_user' or 'assign_realm_role_to_user'. The description lacks context about prerequisites, permissions needed, or typical scenarios for this operation.

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