Skip to main content
Glama
jlucaso1

WhatsApp MCP Server

by jlucaso1

get_message_context

Retrieve surrounding messages from WhatsApp chats by specifying a message ID and optional before/after parameters to understand conversation context.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
message_idYesThe ID of the target message to get context around
beforeNoNumber of messages before (default 5)
afterNoNumber of messages after (default 5)

Implementation Reference

  • The main handler function for the 'get_message_context' MCP tool. It calls getMessagesAround from the database module, formats the messages using formatDbMessageForJson, and returns the context as JSON or an error.
    async ({ message_id, before, after }) => {
      mcpLogger.info(
        `[MCP Tool] Executing get_message_context for msg ${message_id}, before=${before}, after=${after}`,
      );
      try {
        const context = getMessagesAround(message_id, before, after);
        if (!context.target) {
          return {
            isError: true,
            content: [
              {
                type: "text",
                text: `Message with ID ${message_id} not found.`,
              },
            ],
          };
        }
        const formattedContext = {
          target: formatDbMessageForJson(context.target),
          before: context.before.map(formatDbMessageForJson),
          after: context.after.map(formatDbMessageForJson),
        };
        return {
          content: [
            {
              type: "text",
              text: JSON.stringify(formattedContext, null, 2),
            },
          ],
        };
      } catch (error: any) {
        mcpLogger.error(
          `[MCP Tool Error] get_message_context failed for ${message_id}: ${error.message}`,
        );
        return {
          isError: true,
          content: [
            {
              type: "text",
              text: `Error retrieving context for message ${message_id}: ${error.message}`,
            },
          ],
        };
      }
    },
  • Zod input schema defining parameters for the get_message_context tool: message_id (required string), before and after (optional nonnegative integers defaulting to 5).
    {
      message_id: z
        .string()
        .describe("The ID of the target message to get context around"),
      before: z
        .number()
        .int()
        .nonnegative()
        .optional()
        .default(5)
        .describe("Number of messages before (default 5)"),
      after: z
        .number()
        .int()
        .nonnegative()
        .optional()
        .default(5)
        .describe("Number of messages after (default 5)"),
    },
  • src/mcp.ts:320-386 (registration)
    Registration of the 'get_message_context' tool using server.tool() with schema and handler function.
    server.tool(
      "get_message_context",
      {
        message_id: z
          .string()
          .describe("The ID of the target message to get context around"),
        before: z
          .number()
          .int()
          .nonnegative()
          .optional()
          .default(5)
          .describe("Number of messages before (default 5)"),
        after: z
          .number()
          .int()
          .nonnegative()
          .optional()
          .default(5)
          .describe("Number of messages after (default 5)"),
      },
      async ({ message_id, before, after }) => {
        mcpLogger.info(
          `[MCP Tool] Executing get_message_context for msg ${message_id}, before=${before}, after=${after}`,
        );
        try {
          const context = getMessagesAround(message_id, before, after);
          if (!context.target) {
            return {
              isError: true,
              content: [
                {
                  type: "text",
                  text: `Message with ID ${message_id} not found.`,
                },
              ],
            };
          }
          const formattedContext = {
            target: formatDbMessageForJson(context.target),
            before: context.before.map(formatDbMessageForJson),
            after: context.after.map(formatDbMessageForJson),
          };
          return {
            content: [
              {
                type: "text",
                text: JSON.stringify(formattedContext, null, 2),
              },
            ],
          };
        } catch (error: any) {
          mcpLogger.error(
            `[MCP Tool Error] get_message_context failed for ${message_id}: ${error.message}`,
          );
          return {
            isError: true,
            content: [
              {
                type: "text",
                text: `Error retrieving context for message ${message_id}: ${error.message}`,
              },
            ],
          };
        }
      },
    );
  • Database helper function getMessagesAround that queries the SQLite database for messages before, the target message, and after the specified message ID, using timestamp ordering within the same chat.
    export function getMessagesAround(
      messageId: string,
      before: number = 5,
      after: number = 5,
    ): { before: Message[]; target: Message | null; after: Message[] } {
      const db = getDb();
      const result: {
        before: Message[];
        target: Message | null;
        after: Message[];
      } = { before: [], target: null, after: [] };
    
      try {
        const targetStmt = db.prepare(`
                 SELECT m.*, c.name as chat_name
                 FROM messages m
                 JOIN chats c ON m.chat_jid = c.jid
                 WHERE m.id = ? -- Positional parameter 1
            `);
        const targetRow = targetStmt.get(messageId) as any | undefined;
    
        if (!targetRow) {
          return result;
        }
        result.target = rowToMessage(targetRow);
        const targetTimestamp = result.target.timestamp.toISOString();
        const chatJid = result.target.chat_jid;
    
        const beforeStmt = 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 = ? AND m.timestamp < ? -- Positional params 1, 2
                ORDER BY m.timestamp DESC
                LIMIT ?                                  -- Positional param 3
            `);
        const beforeRows = beforeStmt.all(
          chatJid,
          targetTimestamp,
          before,
        ) as any[];
        result.before = beforeRows.map(rowToMessage).reverse();
    
        const afterStmt = 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 = ? AND m.timestamp > ? -- Positional params 1, 2
                ORDER BY m.timestamp ASC
                LIMIT ?                                  -- Positional param 3
            `);
        const afterRows = afterStmt.all(chatJid, targetTimestamp, after) as any[];
        result.after = afterRows.map(rowToMessage);
    
        return result;
      } catch (error) {
        console.error("Error getting messages around:", error);
        return result;
      }
    }
  • Helper function to format database message objects into a JSON-friendly structure used in the tool 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,
      };
    }
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