Skip to main content
Glama

get_channel_messages

Retrieve recent messages from a Microsoft Teams channel to access message content, sender details, and timestamps for monitoring or analysis.

Instructions

Retrieve recent messages from a specific channel in a Microsoft Team. Returns message content, sender information, and timestamps.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
teamIdYesTeam ID
channelIdYesChannel ID
limitNoNumber of messages to retrieve (default: 20)

Implementation Reference

  • Handler function that retrieves recent messages from a Microsoft Teams channel using the Microsoft Graph API. It fetches up to the specified limit of messages, maps them to summaries, sorts them by creation date (newest first), and returns a structured JSON response including total count and pagination info.
    async ({ teamId, channelId, limit }) => {
      try {
        const client = await graphService.getClient();
    
        // Build query parameters - Teams channel messages API has limited query support
        // Only $top is supported, no $orderby, $filter, etc.
        const queryParams: string[] = [`$top=${limit}`];
        const queryString = queryParams.join("&");
    
        const response = (await client
          .api(`/teams/${teamId}/channels/${channelId}/messages?${queryString}`)
          .get()) as GraphApiResponse<ChatMessage>;
    
        if (!response?.value?.length) {
          return {
            content: [
              {
                type: "text",
                text: "No messages found in this channel.",
              },
            ],
          };
        }
    
        const messageList: MessageSummary[] = response.value.map((message: ChatMessage) => ({
          id: message.id,
          content: message.body?.content,
          from: message.from?.user?.displayName,
          createdDateTime: message.createdDateTime,
          importance: message.importance,
        }));
    
        // Sort messages by creation date (newest first) since API doesn't support orderby
        messageList.sort((a, b) => {
          const dateA = new Date(a.createdDateTime || 0).getTime();
          const dateB = new Date(b.createdDateTime || 0).getTime();
          return dateB - dateA;
        });
    
        return {
          content: [
            {
              type: "text",
              text: JSON.stringify(
                {
                  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 input schema defining the required teamId and channelId strings, and optional limit number (1-50, default 20).
    {
      teamId: z.string().describe("Team ID"),
      channelId: z.string().describe("Channel ID"),
      limit: z
        .number()
        .min(1)
        .max(50)
        .optional()
        .default(20)
        .describe("Number of messages to retrieve (default: 20)"),
    },
  • Registration of the 'get_channel_messages' tool using server.tool() in the registerTeamsTools function, including name, description, input schema, and inline handler.
    server.tool(
      "get_channel_messages",
      "Retrieve recent messages from a specific channel in a Microsoft Team. Returns message content, sender information, and timestamps.",
      {
        teamId: z.string().describe("Team ID"),
        channelId: z.string().describe("Channel ID"),
        limit: z
          .number()
          .min(1)
          .max(50)
          .optional()
          .default(20)
          .describe("Number of messages to retrieve (default: 20)"),
      },
      async ({ teamId, channelId, limit }) => {
        try {
          const client = await graphService.getClient();
    
          // Build query parameters - Teams channel messages API has limited query support
          // Only $top is supported, no $orderby, $filter, etc.
          const queryParams: string[] = [`$top=${limit}`];
          const queryString = queryParams.join("&");
    
          const response = (await client
            .api(`/teams/${teamId}/channels/${channelId}/messages?${queryString}`)
            .get()) as GraphApiResponse<ChatMessage>;
    
          if (!response?.value?.length) {
            return {
              content: [
                {
                  type: "text",
                  text: "No messages found in this channel.",
                },
              ],
            };
          }
    
          const messageList: MessageSummary[] = response.value.map((message: ChatMessage) => ({
            id: message.id,
            content: message.body?.content,
            from: message.from?.user?.displayName,
            createdDateTime: message.createdDateTime,
            importance: message.importance,
          }));
    
          // Sort messages by creation date (newest first) since API doesn't support orderby
          messageList.sort((a, b) => {
            const dateA = new Date(a.createdDateTime || 0).getTime();
            const dateB = new Date(b.createdDateTime || 0).getTime();
            return dateB - dateA;
          });
    
          return {
            content: [
              {
                type: "text",
                text: JSON.stringify(
                  {
                    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