Skip to main content
Glama
msaelices

WhatsApp MCP Server

by msaelices

send_message

Send messages directly to WhatsApp contacts using a recipient's phone number and message content. Optionally reply to specific messages with a reply_to parameter.

Instructions

Send a message to a chat.

Parameters:
- phone_number: The phone number of the recipient
- content: The content of the message to send
- reply_to: ID of the message to reply to (optional)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
contentYes
phone_numberYes
reply_toNo

Implementation Reference

  • MCP tool handler for send_message. Decorated with @mcp.tool() for registration. Performs authentication check and delegates to the message module's send_message helper.
    @mcp.tool()
    async def send_message(
        ctx: Context, phone_number: str, content: str, reply_to: Optional[str] = None
    ) -> str:
        """
        Send a message to a chat.
    
        Parameters:
        - phone_number: The phone number of the recipient
        - content: The content of the message to send
        - reply_to: ID of the message to reply to (optional)
        """
        try:
            if not auth.auth_manager.is_authenticated():
                return "Error: No active session"
    
            result = await message.send_message(
                phone_number=phone_number, content=content, reply_to=reply_to
            )
            return json.dumps(result)
        except Exception as e:
            logger.error(f"Error sending message: {e}")
            return f"Error: {str(e)}"
  • Pydantic BaseModel defining the input schema parameters for the send_message tool.
    class SendMessage(BaseModel):
        """Input schema for send_message tool."""
    
        phone_number: str = Field(..., description="The phone number of the recipient")
        content: str = Field(..., description="The content of the message to send")
        reply_to: str | None = Field(None, description="ID of the message to reply to")
  • Supporting function that implements the core logic of sending a message via the WhatsApp client's sendMessage API, including chat ID formatting and response handling.
    async def send_message(
        phone_number: str, content: str, reply_to: Optional[str] = None
    ) -> dict:
        """Send a message to a chat."""
        logger.info(f"Sending message to {phone_number}")
    
        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")
    
        try:
            chat_id = _get_chat_id(phone_number)
            # Send the message via the WhatsApp API
            logger.debug(f"Sending message to {chat_id}: {content}")
    
            # Convert to asyncio to prevent blocking
            response = whatsapp_client.client.sending.sendMessage(chat_id, content)
    
            logger.info(f"Response code {response.code}: {response.data}")
    
            response_data = response.data
    
            message_id = "Not provided"
            # Try to extract message ID from the response if available
            if isinstance(response_data, dict):
                if response_data.get("idMessage"):
                    message_id = response_data.get("idMessage")
                elif response_data.get("id"):
                    message_id = response_data.get("id")
    
            result = {
                "message_id": message_id,
                "status": "sent",
                "timestamp": datetime.now().isoformat(),
                "response": response_data,
            }
    
            logger.info(f"Message sent with ID {message_id}")
            return result
    
        except Exception as e:
            logger.error(f"Failed to send message: {e}")
            raise ValueError(f"Failed to send message: {str(e)}")
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. While 'Send a message' implies a write/mutation operation, the description doesn't address critical behavioral aspects like required permissions, rate limits, whether messages are encrypted, delivery confirmation, or what happens on failure. This leaves significant gaps for an agent to understand the tool's behavior.

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 efficiently structured with a clear purpose statement followed by a bulleted parameter list. Every sentence serves a purpose, though the parameter explanations could be slightly more detailed given the lack of schema descriptions. The formatting is clean and easy to parse.

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?

For a 3-parameter mutation tool with no annotations and no output schema, the description is insufficiently complete. It doesn't explain what the tool returns (success/failure indicators, message ID, etc.), doesn't address error conditions, and provides minimal behavioral context. The parameter explanations help but don't compensate for the overall contextual gaps.

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?

The description explicitly lists all three parameters with brief explanations, adding meaningful context beyond the schema's 0% description coverage. It clarifies that 'reply_to' is optional and identifies what each parameter represents. However, it doesn't provide format details (e.g., phone number format, content length limits) or deeper semantic constraints.

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 ('Send a message') and the target resource ('to a chat'), providing a specific verb+resource combination. However, it doesn't differentiate this tool from potential sibling tools like 'create_group' or 'open_session', which might also involve messaging functionality in some contexts.

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 like 'create_group' for group messaging or 'get_chats' for retrieving messages. There's no mention of prerequisites, appropriate contexts, or exclusions for this messaging 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

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