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)}")

Tool Definition Quality

Score is being calculated. Check back soon.

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