Skip to main content
Glama
msaelices

WhatsApp MCP Server

by msaelices

create_group

Create a new WhatsApp group by specifying a group name and participant phone numbers using the WhatsApp MCP Server.

Instructions

Create a new WhatsApp group.

Parameters:
- group_name: Name of the group to create
- participants: List of participant phone numbers

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
group_nameYes
participantsYes

Implementation Reference

  • MCP tool handler for 'create_group', decorated with @mcp.tool() which registers it with the server. Calls into the group module for execution.
    @mcp.tool()
    async def create_group(ctx: Context, group_name: str, participants: list[str]) -> str:
        """
        Create a new WhatsApp group.
    
        Parameters:
        - group_name: Name of the group to create
        - participants: List of participant phone numbers
        """
        try:
            if not auth.auth_manager.is_authenticated():
                return "Error: No active session"
    
            group_result = await group.create_group(
                group_name=group_name,
                participants=participants,
            )
            return json.dumps(group_result.model_dump())
        except Exception as e:
            logger.error(f"Error creating group: {e}")
            return f"Error: {str(e)}"
  • Pydantic model defining the input schema for the create_group tool.
    class CreateGroup(BaseModel):
        """Input schema for create_group tool."""
    
        group_name: str = Field(..., description="Name of the group to create")
        participants: List[str] = Field(
            ..., description="List of participant phone numbers"
        )
  • Core helper function implementing the group creation logic, called by the MCP handler. Interacts with WhatsApp client to create the group.
    async def create_group(group_name: str, participants: List[str]) -> Group:
        """Create a new WhatsApp group."""
        logger.info(f"Creating group {group_name} with {len(participants)} participants")
    
        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")
    
        if len(participants) < 1:
            raise ValueError("Need at least one participant to create a group")
    
        try:
            # Format participant phone numbers correctly
            formatted_participants = []
            for phone in participants:
                # Add @c.us suffix if not already present
                if not phone.endswith("@c.us"):
                    formatted_phone = f"{phone}@c.us"
                else:
                    formatted_phone = phone
                formatted_participants.append(formatted_phone)
    
            # Prepare the request data for group creation
            # Note: The exact API format may vary depending on the WhatsApp API being used
            group_data = {"group_name": group_name, "participants": formatted_participants}
    
            logger.debug(f"Creating group with data: {json.dumps(group_data)}")
    
            # Create the group via the WhatsApp API
            # The response format may vary depending on the API
            response = await asyncio.to_thread(
                whatsapp_client.client.create_group, group_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 create group: {error_msg}")
                raise ValueError(f"Failed to create group: {error_msg}")
    
            # Extract group information from response
            group_info = response.get("group", {})
            group_id = group_info.get("id", f"{uuid.uuid4().hex[:12]}@g.us")
    
            # Create participant objects
            participant_objects = []
            for i, phone in enumerate(participants):
                contact = Contact(
                    id=formatted_participants[i],
                    name=f"Participant {i + 1}",  # We may not have names initially
                    phone=phone,
                )
                participant = Participant(id=contact.id, is_admin=False, contact=contact)
                participant_objects.append(participant)
    
            # Create the group object
            group = Group(
                id=group_id,
                name=group_name,
                description=group_info.get("description", ""),
                owner=group_info.get("owner", "me"),
                creation_time=datetime.now().isoformat(),
                participants=participant_objects,
            )
    
            logger.info(f"Group created with ID {group_id}")
            return group
    
        except Exception as e:
            logger.error(f"Failed to create group: {e}")
            raise ValueError(f"Failed to create group: {str(e)}")
  • The @mcp.tool() decorator registers the create_group function as an MCP tool.
    @mcp.tool()
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 states the action but doesn't cover critical aspects: whether this requires specific permissions, if it's idempotent, what happens on failure, rate limits, or the expected return format. The description is minimal and lacks necessary operational context.

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 concise with a clear heading and bullet points for parameters. Every sentence adds value, and it's front-loaded with the core purpose. No redundant information is present, though it could benefit from more structured behavioral details.

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

Completeness2/5

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

Given the complexity of a creation tool with no annotations and no output schema, the description is incomplete. It lacks information on success/failure responses, error handling, dependencies (e.g., session requirements), and behavioral traits. For a mutation tool, this leaves significant gaps for an AI agent to operate effectively.

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 both parameters with brief explanations ('Name of the group to create', 'List of participant phone numbers'), adding basic meaning beyond the schema's titles. However, it doesn't specify format constraints (e.g., phone number format, group name length limits), leaving gaps in parameter understanding.

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 verb 'Create' and resource 'new WhatsApp group', making the purpose unambiguous. However, it doesn't explicitly distinguish this from sibling tools like 'get_chats' or 'send_message', though the creation action is inherently different from retrieval/messaging operations.

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?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention prerequisites (e.g., needing an active session via 'open_session'), exclusions, or comparative context with sibling tools like managing existing groups versus creating new ones.

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

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