Skip to main content
Glama
jlucaso1

WhatsApp MCP Server

by jlucaso1

get_chat

Retrieve chat history from WhatsApp, including the last message, by specifying the chat JID to access conversation data for AI agents.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
chat_jidYesThe JID of the chat to retrieve
include_last_messageNoInclude last message details (default true)

Implementation Reference

  • MCP tool handler for 'get_chat': logs execution, calls getChat from database, formats the chat with formatDbChatForJson, returns JSON or error.
    async ({ chat_jid, include_last_message }) => {
      mcpLogger.info(
        `[MCP Tool] Executing get_chat for ${chat_jid}, lastMsg=${include_last_message}`,
      );
      try {
        const chat = getChat(chat_jid, include_last_message);
        if (!chat) {
          return {
            isError: true,
            content: [
              { type: "text", text: `Chat with JID ${chat_jid} not found.` },
            ],
          };
        }
        const formattedChat = formatDbChatForJson(chat);
        return {
          content: [
            {
              type: "text",
              text: JSON.stringify(formattedChat, null, 2),
            },
          ],
        };
      } catch (error: any) {
        mcpLogger.error(
          `[MCP Tool Error] get_chat failed for ${chat_jid}: ${error.message}`,
        );
        return {
          isError: true,
          content: [
            {
              type: "text",
              text: `Error retrieving chat ${chat_jid}: ${error.message}`,
            },
          ],
        };
      }
    },
  • Zod input schema for 'get_chat' tool defining parameters chat_jid (required string) and optional include_last_message (boolean, default true).
    {
      chat_jid: z.string().describe("The JID of the chat to retrieve"),
      include_last_message: z
        .boolean()
        .optional()
        .default(true)
        .describe("Include last message details (default true)"),
    },
  • src/mcp.ts:270-318 (registration)
    Registration of the 'get_chat' MCP tool using server.tool, including inline schema and handler function.
    server.tool(
      "get_chat",
      {
        chat_jid: z.string().describe("The JID of the chat to retrieve"),
        include_last_message: z
          .boolean()
          .optional()
          .default(true)
          .describe("Include last message details (default true)"),
      },
      async ({ chat_jid, include_last_message }) => {
        mcpLogger.info(
          `[MCP Tool] Executing get_chat for ${chat_jid}, lastMsg=${include_last_message}`,
        );
        try {
          const chat = getChat(chat_jid, include_last_message);
          if (!chat) {
            return {
              isError: true,
              content: [
                { type: "text", text: `Chat with JID ${chat_jid} not found.` },
              ],
            };
          }
          const formattedChat = formatDbChatForJson(chat);
          return {
            content: [
              {
                type: "text",
                text: JSON.stringify(formattedChat, null, 2),
              },
            ],
          };
        } catch (error: any) {
          mcpLogger.error(
            `[MCP Tool Error] get_chat failed for ${chat_jid}: ${error.message}`,
          );
          return {
            isError: true,
            content: [
              {
                type: "text",
                text: `Error retrieving chat ${chat_jid}: ${error.message}`,
              },
            ],
          };
        }
      },
    );
  • Helper function to format database Chat object to JSON-friendly structure for the get_chat tool response.
    function formatDbChatForJson(chat: DbChat) {
      return {
        jid: chat.jid,
        name: chat.name ?? chat.jid.split("@")[0] ?? "Unknown Chat",
        is_group: chat.jid.endsWith("@g.us"),
        last_message_time: chat.last_message_time?.toISOString() ?? null,
        last_message_preview: chat.last_message ?? null,
        last_sender_jid: chat.last_sender ?? null,
        last_sender_display: chat.last_sender
          ? chat.last_sender.split("@")[0]
          : chat.last_is_from_me
            ? "Me"
            : null,
        last_is_from_me: chat.last_is_from_me ?? null,
      };
    }
  • Database function getChat that queries SQLite for a specific chat by JID, optionally includes last message details, used by the MCP get_chat handler.
    export function getChat(
      jid: string,
      includeLastMessage: boolean = true,
    ): Chat | null {
      const db = getDb();
      try {
        let sql = `
                SELECT
                    c.jid,
                    c.name,
                    c.last_message_time
                    ${
                      includeLastMessage
                        ? `,
                    (SELECT m.content FROM messages m WHERE m.chat_jid = c.jid ORDER BY m.timestamp DESC LIMIT 1) as last_message,
                    (SELECT m.sender FROM messages m WHERE m.chat_jid = c.jid ORDER BY m.timestamp DESC LIMIT 1) as last_sender,
                    (SELECT m.is_from_me FROM messages m WHERE m.chat_jid = c.jid ORDER BY m.timestamp DESC LIMIT 1) as last_is_from_me
                    `
                        : ""
                    }
                FROM chats c
                WHERE c.jid = ? -- Positional parameter 1
            `;
    
        const stmt = db.prepare(sql);
        const row = stmt.get(jid) as any | undefined;
        return row ? rowToChat(row) : null;
      } catch (error) {
        console.error("Error getting chat:", error);
        return null;
      }
    }

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