Skip to main content
Glama

get_chat_messages

Retrieve chat messages by specifying a chat ID, with options to filter by user, time range, and sort order. Access message content, sender details, and timestamps for analysis or integration.

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
descendingNoSort in descending order (newest first)
fromUserNoFilter messages from specific user ID
limitNoNumber of messages to retrieve
orderByNoSort ordercreatedDateTime
sinceNoGet messages since this ISO datetime
untilNoGet messages until this ISO datetime

Implementation Reference

  • Handler function that fetches recent chat messages from a specific chat using Microsoft Graph API, supports filtering by date (client-side), user, ordering, and limits the number of messages returned. Formats and returns a JSON response with message summaries.
    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 for tool inputs: chatId (string, required), limit (number, 1-50, default 20), since/until (ISO datetime strings, optional), fromUser (string, optional), orderBy (enum, default 'createdDateTime'), descending (boolean, default true).
    { 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)"), },
  • server.tool() registration call for 'get_chat_messages', providing name, description, input schema, and handler function.
    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