Skip to main content
Glama
msaelices

WhatsApp MCP Server

by msaelices

get_chats

Retrieve a paginated list of WhatsApp chats using specified limit and offset parameters. Ideal for managing and organizing chat data efficiently within the WhatsApp Business API.

Instructions

Get a list of chats.

Parameters:
- limit: Maximum number of chats to return (default: 50)
- offset: Offset for pagination (default: 0)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
limitNo
offsetNo

Implementation Reference

  • MCP tool handler and registration for get_chats via @mcp.tool() decorator. Checks authentication, fetches chats from helper module, and returns JSON response.
    @mcp.tool()
    async def get_chats(ctx: Context, limit: int = 50, offset: int = 0) -> str:
        """
        Get a list of chats.
    
        Parameters:
        - limit: Maximum number of chats to return (default: 50)
        - offset: Offset for pagination (default: 0)
        """
        try:
            if not auth.auth_manager.is_authenticated():
                return "Error: No active session"
    
            chats = await message.get_chats(limit=limit, offset=offset)
            return json.dumps({"chats": chats})
        except Exception as e:
            logger.error(f"Error getting chats: {e}")
            return f"Error: {str(e)}"
  • Pydantic model defining the input schema for the get_chats tool, including limit and offset parameters.
    class GetChatsModel(BaseModel):
        """Input schema for get_chats tool."""
    
        limit: int = Field(50, description="Maximum number of chats to return")
        offset: int = Field(0, description="Offset for pagination")
  • Helper function implementing the core get_chats logic, retrieves WhatsApp client, applies pagination to mock chat data, and handles errors.
    async def get_chats(limit: int = 50, offset: int = 0) -> List[Dict[str, Any]]:
        """Get a list of chats."""
        logger.info("Getting chats for session")
    
        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:
            # Note: This API might not directly support listing chats
            # Implement based on what the API supports
    
            # For APIs that don't support chat listing, we can implement a workaround:
            # 1. Store chat IDs in a local cache when messages are sent/received
            # 2. Return those cached chats here
    
            # In some WhatsApp API implementations, there may be a way to fetch conversations
            # Here we'll make a placeholder for when such API becomes available
    
            # If direct API not available, return mock data or cached data
            chats = [
                {
                    "id": "123456789@c.us",
                    "name": "John Doe",
                    "is_group": False,
                    "last_message": "Hello there!",
                    "timestamp": datetime.now().isoformat(),
                },
                {
                    "id": "987654321@g.us",
                    "name": "Family Group",
                    "is_group": True,
                    "participant_count": 5,
                    "last_message": "When are we meeting?",
                    "timestamp": datetime.now().isoformat(),
                },
            ]
    
            # Apply pagination
            start = offset
            end = offset + limit
    
            return chats[start:end]
    
        except Exception as e:
            logger.error(f"Failed to get chats: {e}")
            raise ValueError(f"Failed to get chats: {str(e)}")
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions parameters for pagination but does not describe key traits like whether this is a read-only operation, potential rate limits, authentication needs, or what the output looks like (e.g., format, fields). For a list tool with no annotation coverage, this leaves significant gaps in understanding its 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 appropriately sized and front-loaded, starting with the main purpose followed by parameter details in a clear list format. Every sentence adds value, with no redundant or wasted words. However, the structure could be slightly improved by integrating the purpose and parameters more seamlessly, but it remains efficient.

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 (a list tool with 2 parameters), lack of annotations, and no output schema, the description is incomplete. It covers basic purpose and parameters but misses critical context like output format, error handling, or how it fits with sibling tools. For adequate agent use, it should provide more behavioral and contextual details beyond the minimal information given.

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

Parameters4/5

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

The description adds meaningful semantics beyond the input schema, which has 0% description coverage. It explains that 'limit' is the 'Maximum number of chats to return' with a default of 50, and 'offset' is for 'pagination' with a default of 0, clarifying their purposes. Since there are only 2 parameters and the schema lacks descriptions, this compensates well, though it could detail constraints like min/max values.

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

Purpose3/5

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

The description states 'Get a list of chats,' which clearly indicates the verb ('Get') and resource ('chats'), providing a basic purpose. However, it lacks specificity about what 'chats' entails (e.g., types, scope) and does not differentiate from sibling tools like 'get_group_participants' or 'open_session,' leaving room for ambiguity. This is a minimal viable description but vague in context.

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 does not mention any context, prerequisites, or exclusions, such as how it relates to sibling tools like 'get_group_participants' for participant details or 'open_session' for active chats. Without such information, the agent must infer usage, which reduces effectiveness.

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