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

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

No annotations are provided, so the description carries the full burden. It mentions the tool retrieves 'recent messages' and specifies return fields, but lacks critical behavioral details: whether it's paginated, sorted (e.g., by timestamp), if it requires specific permissions, rate limits, or error conditions. For a read operation with no annotation coverage, this is a significant gap.

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

Conciseness4/5

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

The description is a single, efficient sentence that front-loads the core purpose and return values. Every word contributes meaning, though it could be slightly more structured (e.g., separating purpose from returns).

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

Completeness2/5

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

Given no annotations and no output schema, the description is incomplete. It omits behavioral traits (e.g., pagination, sorting, permissions), doesn't clarify scope (e.g., how 'recent' is defined), and provides no usage guidance relative to siblings. For a 3-parameter tool in a rich sibling set, this leaves the agent under-informed.

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%, with clear parameter descriptions in the schema (e.g., 'Team ID', 'Channel ID', 'Number of messages to retrieve'). The description adds no parameter-specific information beyond what the schema provides, so it meets the baseline for high schema coverage.

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 action ('Retrieve recent messages'), resource ('from a specific channel in a Microsoft Team'), and return values ('message content, sender information, and timestamps'). However, it doesn't explicitly differentiate from siblings like 'get_recent_messages' or 'get_chat_messages', which likely retrieve messages from different contexts.

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. It doesn't mention siblings like 'get_recent_messages' (which might retrieve messages across channels) or 'get_chat_messages' (which might retrieve private chat messages), leaving the agent to guess based on tool names 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