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 [];
      }
    }

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