Skip to main content
Glama

get_recent_messages

Retrieve recent messages from a WhatsApp chat using a phone number or chat name to access conversation history.

Instructions

Read recent messages from a chat identified by either a phone number or a chat name.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
phone_numberNo
chat_nameNo
limitNo
countNoAlias for limit.

Implementation Reference

  • The `get_recent_messages` method in `WhatsAppClient` which navigates to the chat and scrapes messages from the DOM.
    async def get_recent_messages(
        self,
        limit: int = 20,
        phone_number: str | None = None,
        chat_name: str | None = None,
    ) -> dict[str, Any]:
        await self._require_ready()
        assert self._page is not None
    
        target = await self._open_target_chat(phone_number=phone_number, chat_name=chat_name)
        await self._wait_for_message_box()
        await self._page.wait_for_timeout(1000)
        await self._load_message_history(limit)
    
        messages = await self._page.evaluate(
            """(limit) => {
                const selectors = [
                    '[data-testid="msg-container"]',
                    'div.message-in, div.message-out',
                    '[role="row"]'
                ];
                const seen = new Set();
                const nodes = [];
    
                for (const selector of selectors) {
                    for (const node of document.querySelectorAll(selector)) {
                        if (!(node instanceof HTMLElement)) continue;
                        if (seen.has(node)) continue;
                        const hasStructuredText = node.querySelector('[data-pre-plain-text]');
                        const hasVisibleText = Boolean(node.innerText && node.innerText.trim());
                        if (!hasStructuredText && !hasVisibleText) continue;
                        seen.add(node);
                        nodes.push(node);
                    }
                }
    
                const extracted = nodes.map((node) => {
                    const structuredText = Array.from(node.querySelectorAll('[data-pre-plain-text]'))
                        .map((el) => el instanceof HTMLElement ? el.innerText.trim() : '')
                        .filter(Boolean);
    
                    let text = structuredText.join('\\n').trim();
                    if (!text) {
                        text = (node.innerText || '').trim();
                    }
    
                    const outgoing =
                        node.matches('.message-out') ||
                        Boolean(node.querySelector('.message-out')) ||
                        Boolean(node.querySelector('[data-testid="msg-outgoing"]')) ||
                        Boolean(node.querySelector('[data-icon="msg-check"], [data-icon="msg-dblcheck"]'));
    
                    const incoming =
                        node.matches('.message-in') ||
                        Boolean(node.querySelector('.message-in')) ||
                        Boolean(node.querySelector('[data-testid="msg-incoming"]'));
    
                    const timestamp = node.querySelector('[data-pre-plain-text]')?.getAttribute('data-pre-plain-text') || null;
    
                    return {
                        direction: outgoing ? 'outgoing' : incoming ? 'incoming' : 'unknown',
                        text,
                        timestamp,
                    };
                }).filter((item) => item.text);
    
                return extracted.slice(-limit);
            }""",
            limit,
        )
        return {
            "target": target,
            "count": len(messages),
            "messages": messages,
        }
  • The `get_recent_messages` tool definition and registration within the `WhatsAppMCPServer._build_tools` method.
    "get_recent_messages": ToolDefinition(
        name="get_recent_messages",
        description="Read recent messages from a chat identified by either a phone number or a chat name.",
        input_schema={
            "type": "object",
            "properties": {
                "phone_number": {"type": "string"},
                "chat_name": {"type": "string"},
                "limit": {"type": "integer", "minimum": 1, "maximum": 100, "default": 20},
                "count": {"type": "integer", "minimum": 1, "maximum": 100, "description": "Alias for limit."},
            },
            "additionalProperties": False,
        },
        handler=lambda args: self.client.get_recent_messages(
            limit=args.get("limit", args.get("count", 20)),
            phone_number=args.get("phone_number"),
            chat_name=args.get("chat_name"),
        ),
    ),
Behavior2/5

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

With no annotations, the description carries full burden but provides minimal behavioral context. It states 'Read' (implying read-only) but doesn't disclose rate limits, pagination, error conditions, or what 'recent' means temporally. No contradictions exist, but critical behavioral traits are missing.

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 a single, efficient sentence that front-loads the core purpose. However, it could be more structured by separating identification methods from the action, and it lacks necessary details that would justify additional sentences.

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 no annotations, low schema coverage, and no output schema, the description is incomplete. It doesn't explain return values, error handling, or behavioral constraints, making it inadequate for a tool with 4 parameters and read operations in a chat context.

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

Parameters2/5

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

Schema description coverage is low (25%), with only 'count' having a description ('Alias for limit'). The description adds that phone_number or chat_name identify the chat, but doesn't explain format, exclusivity, or default behavior. It fails to compensate for the coverage gap, leaving most parameters semantically unclear.

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 ('Read recent messages') and resource ('from a chat'), specifying identification by phone number or chat name. It distinguishes from siblings like 'send_message' (write vs read) and 'list_recent_chats' (messages vs chats), but doesn't explicitly differentiate from other read operations if they existed.

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?

No guidance on when to use this tool versus alternatives is provided. It doesn't mention prerequisites (e.g., authentication status from 'get_auth_status'), when to prefer phone_number vs chat_name, or how it relates to 'list_recent_chats' for discovering chats first.

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

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/ekaksher/whatsapp-mcp'

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