Skip to main content
Glama
msaelices

WhatsApp MCP Server

by msaelices

get_group_participants

Retrieve a list of participants from a specific WhatsApp group by providing the group ID. This tool helps manage and analyze group membership efficiently.

Instructions

Get the participants of a WhatsApp group.

Parameters:
- group_id: The WhatsApp ID of the group

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
group_idYes

Implementation Reference

  • MCP tool handler function decorated with @mcp.tool(). It checks authentication, calls the group module's get_group_participants helper, serializes participants to JSON, and handles errors.
    @mcp.tool()
    async def get_group_participants(ctx: Context, group_id: str) -> str:
        """
        Get the participants of a WhatsApp group.
    
        Parameters:
        - group_id: The WhatsApp ID of the group
        """
        try:
            if not auth.auth_manager.is_authenticated():
                return "Error: No active session"
    
            participants = await group.get_group_participants(group_id=group_id)
            return json.dumps({"participants": [p.model_dump() for p in participants]})
        except Exception as e:
            logger.error(f"Error getting group participants: {e}")
            return f"Error: {str(e)}"
  • Pydantic BaseModel defining the input schema (group_id parameter) for the get_group_participants tool.
    class GroupParticipants(BaseModel):
        """Input schema for get_group_participants tool."""
    
        group_id: str = Field(..., description="The WhatsApp ID of the group")
  • Helper function in group module that validates input, calls whatsapp_client.client.get_group_participants via asyncio.to_thread, parses the response into list of Participant models, and handles errors.
    async def get_group_participants(group_id: str) -> List[Participant]:
        """Get the participants of a WhatsApp group."""
        logger.info(f"Getting participants for group {group_id}")
    
        whatsapp_client = auth_manager.get_client()
        if not whatsapp_client:
            raise ValueError("Session not found")
    
        if not whatsapp_client.client:
            raise ValueError("WhatsApp client not initialized")
    
        # Validate group ID format
        if not group_id.endswith("@g.us"):
            raise ValueError("Invalid group ID format. Must end with @g.us")
    
        try:
            # Prepare the request data for fetching group participants
            request_data = {"group_id": group_id}
    
            logger.debug(f"Fetching participants for group: {group_id}")
    
            # Get the participants via the WhatsApp API
            response = await asyncio.to_thread(
                whatsapp_client.client.get_group_participants, request_data
            )
    
            # Parse the response
            if not response or not response.get("success", False):
                error_msg = (
                    response.get("error", "Unknown error") if response else "No response"
                )
                logger.error(f"Failed to get group participants: {error_msg}")
                raise ValueError(f"Failed to get group participants: {error_msg}")
    
            # Extract participants information from response
            participants_info = response.get("participants", [])
    
            # Create participant objects
            participants = []
            for p_info in participants_info:
                p_id = p_info.get("id", "")
                p_name = p_info.get("name", "Unknown")
                p_phone = p_info.get("phone", p_id.replace("@c.us", ""))
                p_is_admin = p_info.get("is_admin", False)
    
                contact = Contact(id=p_id, name=p_name, phone=p_phone)
    
                participant = Participant(id=p_id, is_admin=p_is_admin, contact=contact)
    
                participants.append(participant)
    
            return participants
    
        except Exception as e:
            logger.error(f"Failed to get group participants: {e}")
            raise ValueError(f"Failed to get group participants: {str(e)}")
Install Server

Other Tools

Related 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/msaelices/whatsapp-mcp-server'

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