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}`, }, ], }; } } );

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