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
| Name | Required | Description | Default |
|---|---|---|---|
| chatId | Yes | Chat ID (e.g. 19:meeting_Njhi..j@thread.v2 | |
| descending | No | Sort in descending order (newest first) | |
| fromUser | No | Filter messages from specific user ID | |
| limit | No | Number of messages to retrieve | |
| orderBy | No | Sort order | createdDateTime |
| since | No | Get messages since this ISO datetime | |
| until | No | Get messages until this ISO datetime |
Implementation Reference
- src/tools/chats.ts:104-210 (handler)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}`, }, ], }; } } );
- src/tools/chats.ts:81-103 (schema)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)"), },
- src/tools/chats.ts:78-211 (registration)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}`, }, ], }; } } );