Skip to main content
Glama
jlucaso1

WhatsApp MCP Server

by jlucaso1

list_messages

Retrieve chat history from WhatsApp by specifying a chat JID, with pagination controls to manage message display.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
chat_jidYesThe JID of the chat (e.g., '123456@s.whatsapp.net' or 'group@g.us')
limitNoMax messages per page (default 20)
pageNoPage number (0-indexed, default 0)

Implementation Reference

  • The main handler function for the 'list_messages' MCP tool. It retrieves messages from the database using getMessages, handles pagination and empty results, formats them using formatDbMessageForJson, and returns a JSON string response or an error.
    async ({ chat_jid, limit, page }) => {
      mcpLogger.info(
        `[MCP Tool] Executing list_messages for chat ${chat_jid}, limit=${limit}, page=${page}`,
      );
      try {
        const messages = getMessages(chat_jid, limit, page);
        if (!messages.length && page === 0) {
          return {
            content: [
              { type: "text", text: `No messages found for chat ${chat_jid}.` },
            ],
          };
        } else if (!messages.length) {
          return {
            content: [
              {
                type: "text",
                text: `No more messages found on page ${page} for chat ${chat_jid}.`,
              },
            ],
          };
        }
        const formattedMessages = messages.map(formatDbMessageForJson);
        return {
          content: [
            {
              type: "text",
              text: JSON.stringify(formattedMessages, null, 2),
            },
          ],
        };
      } catch (error: any) {
        mcpLogger.error(
          `[MCP Tool Error] list_messages failed for ${chat_jid}: ${error.message}`,
        );
        return {
          isError: true,
          content: [
            {
              type: "text",
              text: `Error listing messages for ${chat_jid}: ${error.message}`,
            },
          ],
        };
      }
    },
  • Zod input schema defining parameters for the list_messages tool: chat_jid (required string), limit (optional number default 20), page (optional number default 0).
    {
      chat_jid: z
        .string()
        .describe(
          "The JID of the chat (e.g., '123456@s.whatsapp.net' or 'group@g.us')",
        ),
      limit: z
        .number()
        .int()
        .positive()
        .optional()
        .default(20)
        .describe("Max messages per page (default 20)"),
      page: z
        .number()
        .int()
        .nonnegative()
        .optional()
        .default(0)
        .describe("Page number (0-indexed, default 0)"),
    },
  • src/mcp.ts:113-182 (registration)
    Registration of the 'list_messages' tool on the MCP server using server.tool() with schema and handler function.
    server.tool(
      "list_messages",
      {
        chat_jid: z
          .string()
          .describe(
            "The JID of the chat (e.g., '123456@s.whatsapp.net' or 'group@g.us')",
          ),
        limit: z
          .number()
          .int()
          .positive()
          .optional()
          .default(20)
          .describe("Max messages per page (default 20)"),
        page: z
          .number()
          .int()
          .nonnegative()
          .optional()
          .default(0)
          .describe("Page number (0-indexed, default 0)"),
      },
      async ({ chat_jid, limit, page }) => {
        mcpLogger.info(
          `[MCP Tool] Executing list_messages for chat ${chat_jid}, limit=${limit}, page=${page}`,
        );
        try {
          const messages = getMessages(chat_jid, limit, page);
          if (!messages.length && page === 0) {
            return {
              content: [
                { type: "text", text: `No messages found for chat ${chat_jid}.` },
              ],
            };
          } else if (!messages.length) {
            return {
              content: [
                {
                  type: "text",
                  text: `No more messages found on page ${page} for chat ${chat_jid}.`,
                },
              ],
            };
          }
          const formattedMessages = messages.map(formatDbMessageForJson);
          return {
            content: [
              {
                type: "text",
                text: JSON.stringify(formattedMessages, null, 2),
              },
            ],
          };
        } catch (error: any) {
          mcpLogger.error(
            `[MCP Tool Error] list_messages failed for ${chat_jid}: ${error.message}`,
          );
          return {
            isError: true,
            content: [
              {
                type: "text",
                text: `Error listing messages for ${chat_jid}: ${error.message}`,
              },
            ],
          };
        }
      },
    );
  • Helper function to format database Message objects into JSON-friendly structure used by the list_messages handler.
    function formatDbMessageForJson(msg: DbMessage) {
      return {
        id: msg.id,
        chat_jid: msg.chat_jid,
        chat_name: msg.chat_name ?? "Unknown Chat",
        sender_jid: msg.sender ?? null,
        sender_display: msg.sender
          ? msg.sender.split("@")[0]
          : msg.is_from_me
            ? "Me"
            : "Unknown",
        content: msg.content,
        timestamp: msg.timestamp.toISOString(),
        is_from_me: msg.is_from_me,
      };
    }
  • Database query function that retrieves paginated messages for a specific chat JID, used by the list_messages tool handler.
    export function getMessages(
      chatJid: string,
      limit: number = 20,
      page: number = 0,
    ): Message[] {
      const db = getDb();
      try {
        const offset = page * limit;
        const stmt = db.prepare(`
                SELECT m.*, c.name as chat_name
                FROM messages m
                JOIN chats c ON m.chat_jid = c.jid
                WHERE m.chat_jid = ? -- Positional parameter 1
                ORDER BY m.timestamp DESC
                LIMIT ?             -- Positional parameter 2
                OFFSET ?            -- Positional parameter 3
            `);
        const rows = stmt.all(chatJid, limit, offset) as any[];
        return rows.map(rowToMessage);
      } catch (error) {
        console.error("Error getting messages:", error);
        return [];
      }
    }
Behavior1/5

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

Tool has no description.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness1/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Tool has no description.

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

Completeness1/5

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

Tool has no description.

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

Parameters1/5

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

Tool has no description.

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

Purpose1/5

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

Tool has no description.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines1/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Tool has no description.

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

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