Skip to main content
Glama

search_messages

Find messages in Microsoft Teams by searching across channels and chats using KQL queries for sender, mentions, attachments, and other filters.

Instructions

Search for messages across all Microsoft Teams channels and chats using Microsoft Search API. Supports advanced KQL syntax for filtering by sender, mentions, attachments, and more.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesSearch query. Supports KQL syntax like 'from:user mentions:userId hasAttachment:true'
scopeNoScope of searchall
limitNoNumber of results to return
enableTopResultsNoEnable relevance-based ranking

Implementation Reference

  • The handler function that implements the core logic of the 'search_messages' tool. It constructs a SearchRequest for Microsoft Graph's /search/query endpoint, applies scope filters, processes search hits into results, and returns formatted JSON output or error messages.
    async ({ query, scope, limit, enableTopResults }) => {
      try {
        const client = await graphService.getClient();
    
        // Build the search request
        const searchRequest: SearchRequest = {
          entityTypes: ["chatMessage"],
          query: {
            queryString: query,
          },
          from: 0,
          size: limit,
          enableTopResults,
        };
    
        // Add scope-specific filters to the query if needed
        let enhancedQuery = query;
        if (scope === "channels") {
          enhancedQuery = `${query} AND (channelIdentity/channelId:*)`;
        } else if (scope === "chats") {
          enhancedQuery = `${query} AND (chatId:* AND NOT channelIdentity/channelId:*)`;
        }
    
        searchRequest.query.queryString = enhancedQuery;
    
        const response = (await client
          .api("/search/query")
          .post({ requests: [searchRequest] })) as SearchResponse;
    
        if (!response?.value?.length || !response.value[0]?.hitsContainers?.length) {
          return {
            content: [
              {
                type: "text",
                text: "No messages found matching your search criteria.",
              },
            ],
          };
        }
    
        const hits = response.value[0].hitsContainers[0].hits;
        const searchResults = hits.map((hit: SearchHit) => ({
          id: hit.resource.id,
          summary: hit.summary,
          rank: hit.rank,
          content: hit.resource.body?.content || "No content",
          from: hit.resource.from?.user?.displayName || "Unknown",
          createdDateTime: hit.resource.createdDateTime,
          chatId: hit.resource.chatId,
          teamId: hit.resource.channelIdentity?.teamId,
          channelId: hit.resource.channelIdentity?.channelId,
        }));
    
        return {
          content: [
            {
              type: "text",
              text: JSON.stringify(
                {
                  query,
                  scope,
                  totalResults: response.value[0].hitsContainers[0].total,
                  results: searchResults,
                  moreResultsAvailable: response.value[0].hitsContainers[0].moreResultsAvailable,
                },
                null,
                2
              ),
            },
          ],
        };
      } catch (error: unknown) {
        const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
        return {
          content: [
            {
              type: "text",
              text: `❌ Error searching messages: ${errorMessage}`,
            },
          ],
        };
      }
    }
  • Zod schema defining the input parameters for the 'search_messages' tool: query (required string), scope (enum: all/channels/chats, default 'all'), limit (1-100, default 25), enableTopResults (boolean, default true).
    {
      query: z
        .string()
        .describe(
          "Search query. Supports KQL syntax like 'from:user mentions:userId hasAttachment:true'"
        ),
      scope: z
        .enum(["all", "channels", "chats"])
        .optional()
        .default("all")
        .describe("Scope of search"),
      limit: z
        .number()
        .min(1)
        .max(100)
        .optional()
        .default(25)
        .describe("Number of results to return"),
      enableTopResults: z
        .boolean()
        .optional()
        .default(true)
        .describe("Enable relevance-based ranking"),
    },
  • The server.tool() call that registers the 'search_messages' tool with the MCP server, including name, description, input schema, and handler function.
    server.tool(
      "search_messages",
      "Search for messages across all Microsoft Teams channels and chats using Microsoft Search API. Supports advanced KQL syntax for filtering by sender, mentions, attachments, and more.",
      {
        query: z
          .string()
          .describe(
            "Search query. Supports KQL syntax like 'from:user mentions:userId hasAttachment:true'"
          ),
        scope: z
          .enum(["all", "channels", "chats"])
          .optional()
          .default("all")
          .describe("Scope of search"),
        limit: z
          .number()
          .min(1)
          .max(100)
          .optional()
          .default(25)
          .describe("Number of results to return"),
        enableTopResults: z
          .boolean()
          .optional()
          .default(true)
          .describe("Enable relevance-based ranking"),
      },
      async ({ query, scope, limit, enableTopResults }) => {
        try {
          const client = await graphService.getClient();
    
          // Build the search request
          const searchRequest: SearchRequest = {
            entityTypes: ["chatMessage"],
            query: {
              queryString: query,
            },
            from: 0,
            size: limit,
            enableTopResults,
          };
    
          // Add scope-specific filters to the query if needed
          let enhancedQuery = query;
          if (scope === "channels") {
            enhancedQuery = `${query} AND (channelIdentity/channelId:*)`;
          } else if (scope === "chats") {
            enhancedQuery = `${query} AND (chatId:* AND NOT channelIdentity/channelId:*)`;
          }
    
          searchRequest.query.queryString = enhancedQuery;
    
          const response = (await client
            .api("/search/query")
            .post({ requests: [searchRequest] })) as SearchResponse;
    
          if (!response?.value?.length || !response.value[0]?.hitsContainers?.length) {
            return {
              content: [
                {
                  type: "text",
                  text: "No messages found matching your search criteria.",
                },
              ],
            };
          }
    
          const hits = response.value[0].hitsContainers[0].hits;
          const searchResults = hits.map((hit: SearchHit) => ({
            id: hit.resource.id,
            summary: hit.summary,
            rank: hit.rank,
            content: hit.resource.body?.content || "No content",
            from: hit.resource.from?.user?.displayName || "Unknown",
            createdDateTime: hit.resource.createdDateTime,
            chatId: hit.resource.chatId,
            teamId: hit.resource.channelIdentity?.teamId,
            channelId: hit.resource.channelIdentity?.channelId,
          }));
    
          return {
            content: [
              {
                type: "text",
                text: JSON.stringify(
                  {
                    query,
                    scope,
                    totalResults: response.value[0].hitsContainers[0].total,
                    results: searchResults,
                    moreResultsAvailable: response.value[0].hitsContainers[0].moreResultsAvailable,
                  },
                  null,
                  2
                ),
              },
            ],
          };
        } catch (error: unknown) {
          const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
          return {
            content: [
              {
                type: "text",
                text: `❌ Error searching messages: ${errorMessage}`,
              },
            ],
          };
        }
      }
    );
  • src/index.ts:136-136 (registration)
    Invocation of registerSearchTools in the main MCP server setup, which registers the 'search_messages' tool along with other search-related tools.
    registerSearchTools(server, graphService);
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 of behavioral disclosure. It mentions the API and KQL syntax but lacks critical details like whether this is a read-only operation (implied by 'search'), potential rate limits, authentication requirements, or what the output format looks like (e.g., pagination, error handling). For a search tool with zero annotation coverage, this leaves significant gaps in understanding its behavior.

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

Conciseness5/5

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

The description is efficiently structured in two sentences: the first states the purpose and scope, and the second adds key capabilities. Every sentence earns its place by providing essential information without redundancy, making it front-loaded and appropriately sized for the tool's complexity.

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

Completeness3/5

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

Given the tool's moderate complexity (4 parameters, 100% schema coverage, no output schema, no annotations), the description is partially complete. It covers purpose and basic usage but lacks behavioral details (e.g., output format, error cases) and deeper contextual guidance. Without annotations or an output schema, the agent might struggle to fully understand how to interpret results or handle edge cases, leaving room for improvement.

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 each parameter well-documented in the schema (e.g., query supports KQL syntax, scope has enum values, limit has min/max). The description adds minimal value beyond the schema by mentioning 'advanced KQL syntax for filtering by sender, mentions, attachments, and more,' which slightly elaborates on the query parameter but doesn't provide new syntax or format details. Baseline 3 is appropriate when the schema does the heavy lifting.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the specific action ('Search for messages') and resource ('across all Microsoft Teams channels and chats'), distinguishing it from siblings like get_channel_messages or get_chat_messages that retrieve messages from specific sources without search capabilities. It also mentions the underlying API (Microsoft Search API) for technical context.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage context by stating it searches 'across all Microsoft Teams channels and chats' and supports 'advanced KQL syntax for filtering,' suggesting it should be used for comprehensive, filtered searches rather than retrieving specific message sets like sibling tools. However, it doesn't explicitly state when not to use it or name alternatives, such as get_recent_messages for non-search retrieval.

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