Skip to main content
Glama

get_chat_messages

Retrieve recent messages from Microsoft Teams chat conversations to access message content, sender details, and timestamps for analysis or review.

Instructions

Retrieve recent messages from a specific chat conversation. Returns message content, sender information, and timestamps.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
chatIdYesChat ID (e.g. 19:meeting_Njhi..j@thread.v2
limitNoNumber of messages to retrieve
sinceNoGet messages since this ISO datetime
untilNoGet messages until this ISO datetime
fromUserNoFilter messages from specific user ID
orderByNoSort ordercreatedDateTime
descendingNoSort in descending order (newest first)

Implementation Reference

  • The handler function that implements the core logic for retrieving recent messages from a specific chat. It uses Microsoft Graph API to fetch messages with support for pagination, filtering by user, ordering, and client-side date filtering. Returns a structured JSON response with message details.
    async ({ chatId, limit, since, until, fromUser, orderBy, descending }) => {
      try {
        const client = await graphService.getClient();
    
        // Build query parameters
        const queryParams: string[] = [`$top=${limit}`];
    
        // Add ordering - Graph API only supports descending order for datetime fields in chat messages
        if ((orderBy === "createdDateTime" || orderBy === "lastModifiedDateTime") && !descending) {
          return {
            content: [
              {
                type: "text",
                text: `❌ Error: QueryOptions to order by '${orderBy === "createdDateTime" ? "CreatedDateTime" : "LastModifiedDateTime"}' in 'Ascending' direction is not supported.`,
              },
            ],
          };
        }
    
        const sortDirection = descending ? "desc" : "asc";
        queryParams.push(`$orderby=${orderBy} ${sortDirection}`);
    
        // Add filters (only user filter is supported reliably)
        const filters: string[] = [];
        if (fromUser) {
          filters.push(`from/user/id eq '${fromUser}'`);
        }
    
        if (filters.length > 0) {
          queryParams.push(`$filter=${filters.join(" and ")}`);
        }
    
        const queryString = queryParams.join("&");
    
        const response = (await client
          .api(`/me/chats/${chatId}/messages?${queryString}`)
          .get()) as GraphApiResponse<ChatMessage>;
    
        if (!response?.value?.length) {
          return {
            content: [
              {
                type: "text",
                text: "No messages found in this chat with the specified filters.",
              },
            ],
          };
        }
    
        // Apply client-side date filtering since server-side filtering is not supported
        let filteredMessages = response.value;
    
        if (since || until) {
          filteredMessages = response.value.filter((message: ChatMessage) => {
            if (!message.createdDateTime) return true;
    
            const messageDate = new Date(message.createdDateTime);
            if (since) {
              const sinceDate = new Date(since);
              if (messageDate <= sinceDate) return false;
            }
            if (until) {
              const untilDate = new Date(until);
              if (messageDate >= untilDate) return false;
            }
            return true;
          });
        }
    
        const messageList: MessageSummary[] = filteredMessages.map((message: ChatMessage) => ({
          id: message.id,
          content: message.body?.content,
          from: message.from?.user?.displayName,
          createdDateTime: message.createdDateTime,
        }));
    
        return {
          content: [
            {
              type: "text",
              text: JSON.stringify(
                {
                  filters: { since, until, fromUser },
                  filteringMethod: since || until ? "client-side" : "server-side",
                  totalReturned: messageList.length,
                  hasMore: !!response["@odata.nextLink"],
                  messages: messageList,
                },
                null,
                2
              ),
            },
          ],
        };
      } catch (error: unknown) {
        const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
        return {
          content: [
            {
              type: "text",
              text: `❌ Error: ${errorMessage}`,
            },
          ],
        };
      }
    }
  • Zod schema defining the input parameters for the get_chat_messages tool, including chatId (required), optional limit, date filters (since/until), user filter, and sorting options.
      chatId: z.string().describe("Chat ID (e.g. 19:meeting_Njhi..j@thread.v2"),
      limit: z
        .number()
        .min(1)
        .max(50)
        .optional()
        .default(20)
        .describe("Number of messages to retrieve"),
      since: z.string().optional().describe("Get messages since this ISO datetime"),
      until: z.string().optional().describe("Get messages until this ISO datetime"),
      fromUser: z.string().optional().describe("Filter messages from specific user ID"),
      orderBy: z
        .enum(["createdDateTime", "lastModifiedDateTime"])
        .optional()
        .default("createdDateTime")
        .describe("Sort order"),
      descending: z
        .boolean()
        .optional()
        .default(true)
        .describe("Sort in descending order (newest first)"),
    },
  • Registration of the get_chat_messages tool within the registerChatTools function using server.tool(), including name, description, schema, and handler.
    // Get chat messages
    server.tool(
      "get_chat_messages",
      "Retrieve recent messages from a specific chat conversation. Returns message content, sender information, and timestamps.",
      {
        chatId: z.string().describe("Chat ID (e.g. 19:meeting_Njhi..j@thread.v2"),
        limit: z
          .number()
          .min(1)
          .max(50)
          .optional()
          .default(20)
          .describe("Number of messages to retrieve"),
        since: z.string().optional().describe("Get messages since this ISO datetime"),
        until: z.string().optional().describe("Get messages until this ISO datetime"),
        fromUser: z.string().optional().describe("Filter messages from specific user ID"),
        orderBy: z
          .enum(["createdDateTime", "lastModifiedDateTime"])
          .optional()
          .default("createdDateTime")
          .describe("Sort order"),
        descending: z
          .boolean()
          .optional()
          .default(true)
          .describe("Sort in descending order (newest first)"),
      },
      async ({ chatId, limit, since, until, fromUser, orderBy, descending }) => {
        try {
          const client = await graphService.getClient();
    
          // Build query parameters
          const queryParams: string[] = [`$top=${limit}`];
    
          // Add ordering - Graph API only supports descending order for datetime fields in chat messages
          if ((orderBy === "createdDateTime" || orderBy === "lastModifiedDateTime") && !descending) {
            return {
              content: [
                {
                  type: "text",
                  text: `❌ Error: QueryOptions to order by '${orderBy === "createdDateTime" ? "CreatedDateTime" : "LastModifiedDateTime"}' in 'Ascending' direction is not supported.`,
                },
              ],
            };
          }
    
          const sortDirection = descending ? "desc" : "asc";
          queryParams.push(`$orderby=${orderBy} ${sortDirection}`);
    
          // Add filters (only user filter is supported reliably)
          const filters: string[] = [];
          if (fromUser) {
            filters.push(`from/user/id eq '${fromUser}'`);
          }
    
          if (filters.length > 0) {
            queryParams.push(`$filter=${filters.join(" and ")}`);
          }
    
          const queryString = queryParams.join("&");
    
          const response = (await client
            .api(`/me/chats/${chatId}/messages?${queryString}`)
            .get()) as GraphApiResponse<ChatMessage>;
    
          if (!response?.value?.length) {
            return {
              content: [
                {
                  type: "text",
                  text: "No messages found in this chat with the specified filters.",
                },
              ],
            };
          }
    
          // Apply client-side date filtering since server-side filtering is not supported
          let filteredMessages = response.value;
    
          if (since || until) {
            filteredMessages = response.value.filter((message: ChatMessage) => {
              if (!message.createdDateTime) return true;
    
              const messageDate = new Date(message.createdDateTime);
              if (since) {
                const sinceDate = new Date(since);
                if (messageDate <= sinceDate) return false;
              }
              if (until) {
                const untilDate = new Date(until);
                if (messageDate >= untilDate) return false;
              }
              return true;
            });
          }
    
          const messageList: MessageSummary[] = filteredMessages.map((message: ChatMessage) => ({
            id: message.id,
            content: message.body?.content,
            from: message.from?.user?.displayName,
            createdDateTime: message.createdDateTime,
          }));
    
          return {
            content: [
              {
                type: "text",
                text: JSON.stringify(
                  {
                    filters: { since, until, fromUser },
                    filteringMethod: since || until ? "client-side" : "server-side",
                    totalReturned: messageList.length,
                    hasMore: !!response["@odata.nextLink"],
                    messages: messageList,
                  },
                  null,
                  2
                ),
              },
            ],
          };
        } catch (error: unknown) {
          const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
          return {
            content: [
              {
                type: "text",
                text: `❌ Error: ${errorMessage}`,
              },
            ],
          };
        }
      }
    );
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions the return data but doesn't cover critical aspects like pagination behavior (e.g., how 'limit' interacts with date filters), error conditions (e.g., invalid chatId), rate limits, or authentication requirements. For a read operation with 7 parameters, this leaves significant gaps.

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

Conciseness5/5

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

The description is a single, well-structured sentence that efficiently conveys the core purpose and return data. It's front-loaded with the main action and avoids unnecessary details, making it easy for an agent to parse quickly.

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

Completeness3/5

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

For a read tool with 7 parameters and no output schema, the description is minimally adequate. It covers the basic purpose and return format but lacks behavioral context (e.g., pagination, errors) and usage differentiation from siblings. The high schema coverage helps, but the absence of annotations and output schema means the description should do more to compensate.

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

Parameters3/5

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

Schema description coverage is 100%, so the schema fully documents all 7 parameters. The description adds no parameter-specific information beyond what's in the schema (e.g., it doesn't clarify interactions between 'since', 'until', and 'limit'). Baseline 3 is appropriate when the schema does the heavy lifting.

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 verb ('retrieve') and resource ('recent messages from a specific chat conversation'), and specifies the return data ('message content, sender information, and timestamps'). However, it doesn't explicitly differentiate from siblings like 'get_recent_messages' or 'get_channel_messages', which likely have overlapping purposes.

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?

The description provides no guidance on when to use this tool versus alternatives like 'get_recent_messages' or 'get_channel_messages'. It doesn't mention prerequisites (e.g., needing a valid chatId) or exclusions, leaving the agent to infer usage from the tool name and parameters alone.

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/floriscornel/teams-mcp'

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