Skip to main content
Glama
taylorwilsdon

Google Workspace MCP Server - Control Gmail, Calendar, Docs, Sheets, Slides, Chat, Forms & Drive

search_gmail_messages

Search and retrieve specific Gmail messages using queries. Retrieve Message IDs, Thread IDs, and direct Gmail web links for verification. Supports standard Gmail search operators.

Instructions

Searches messages in a user's Gmail account based on a query.
Returns both Message IDs and Thread IDs for each found message, along with Gmail web interface links for manual verification.

Args:
    query (str): The search query. Supports standard Gmail search operators.
    user_google_email (str): The user's Google email address. Required.
    page_size (int): The maximum number of messages to return. Defaults to 10.

Returns:
    str: LLM-friendly structured results with Message IDs, Thread IDs, and clickable Gmail web interface URLs for each found message.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
page_sizeNo
queryYes
serviceYes
user_google_emailYes

Implementation Reference

  • The primary handler function for the 'search_gmail_messages' tool. It performs the Gmail API search using the provided query, handles responses safely, and formats the output using a helper function. Includes decorators for tool registration, error handling, and authentication requirements.
    @server.tool()
    @handle_http_errors("search_gmail_messages", is_read_only=True, service_type="gmail")
    @require_google_service("gmail", "gmail_read")
    async def search_gmail_messages(
        service, query: str, user_google_email: str, page_size: int = 10
    ) -> str:
        """
        Searches messages in a user's Gmail account based on a query.
        Returns both Message IDs and Thread IDs for each found message, along with Gmail web interface links for manual verification.
    
        Args:
            query (str): The search query. Supports standard Gmail search operators.
            user_google_email (str): The user's Google email address. Required.
            page_size (int): The maximum number of messages to return. Defaults to 10.
    
        Returns:
            str: LLM-friendly structured results with Message IDs, Thread IDs, and clickable Gmail web interface URLs for each found message.
        """
        logger.info(
            f"[search_gmail_messages] Email: '{user_google_email}', Query: '{query}'"
        )
    
        response = await asyncio.to_thread(
            service.users()
            .messages()
            .list(userId="me", q=query, maxResults=page_size)
            .execute
        )
    
        # Handle potential null response (but empty dict {} is valid)
        if response is None:
            logger.warning("[search_gmail_messages] Null response from Gmail API")
            return f"No response received from Gmail API for query: '{query}'"
    
        messages = response.get("messages", [])
        # Additional safety check for null messages array
        if messages is None:
            messages = []
    
        formatted_output = _format_gmail_results_plain(messages, query)
    
        logger.info(f"[search_gmail_messages] Found {len(messages)} messages")
        return formatted_output
  • Helper function specifically used by search_gmail_messages to format the list of found messages into a readable string, including IDs, web links, and usage instructions for further tools.
    def _format_gmail_results_plain(messages: list, query: str) -> str:
        """Format Gmail search results in clean, LLM-friendly plain text."""
        if not messages:
            return f"No messages found for query: '{query}'"
    
        lines = [
            f"Found {len(messages)} messages matching '{query}':",
            "",
            "📧 MESSAGES:",
        ]
    
        for i, msg in enumerate(messages, 1):
            # Handle potential null/undefined message objects
            if not msg or not isinstance(msg, dict):
                lines.extend([
                    f"  {i}. Message: Invalid message data",
                    "     Error: Message object is null or malformed",
                    "",
                ])
                continue
    
            # Handle potential null/undefined values from Gmail API
            message_id = msg.get("id")
            thread_id = msg.get("threadId")
    
            # Convert None, empty string, or missing values to "unknown"
            if not message_id:
                message_id = "unknown"
            if not thread_id:
                thread_id = "unknown"
    
            if message_id != "unknown":
                message_url = _generate_gmail_web_url(message_id)
            else:
                message_url = "N/A"
    
            if thread_id != "unknown":
                thread_url = _generate_gmail_web_url(thread_id)
            else:
                thread_url = "N/A"
    
            lines.extend(
                [
                    f"  {i}. Message ID: {message_id}",
                    f"     Web Link: {message_url}",
                    f"     Thread ID: {thread_id}",
                    f"     Thread Link: {thread_url}",
                    "",
                ]
            )
    
        lines.extend(
            [
                "💡 USAGE:",
                "  • Pass the Message IDs **as a list** to get_gmail_messages_content_batch()",
                "    e.g. get_gmail_messages_content_batch(message_ids=[...])",
                "  • Pass the Thread IDs to get_gmail_thread_content() (single) or get_gmail_threads_content_batch() (batch)",
            ]
        )
    
        return "\n".join(lines)
  • The @server.tool() decorator registers the search_gmail_messages function as an MCP tool.
    @server.tool()
Behavior3/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It describes what the tool returns (Message IDs, Thread IDs, web links) and mentions the default page_size, which is useful. However, it doesn't disclose important behavioral traits like whether this is a read-only operation, authentication requirements, rate limits, pagination behavior beyond page_size, or error handling. The description adds some value but leaves significant gaps.

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 well-structured and appropriately sized. It uses clear sections (Args, Returns) with bullet-like formatting that makes parameter information easy to parse. Every sentence adds value: the first states the purpose, the second describes the return format, and the parameter descriptions provide essential details. No wasted words or redundancy.

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, no annotations, no output schema), the description is partially complete. It covers the basic purpose and most parameters well, but has significant gaps: missing documentation for the 'service' parameter, no behavioral context beyond basic returns, and no guidance on when to use versus alternatives. For a search tool with authentication requirements, this leaves important questions unanswered.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

With 0% schema description coverage, the description must compensate for the lack of parameter documentation in the schema. It successfully documents 3 out of 4 parameters (query, user_google_email, page_size) with clear semantics, including the default value for page_size and that user_google_email is required. However, it completely omits the 'service' parameter, which is required according to the schema, creating a significant documentation gap.

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 tool searches messages in Gmail based on a query, which is a specific verb+resource combination. However, it doesn't distinguish this tool from the sibling 'search_messages' tool, which appears to be a similar functionality. The description mentions returning both Message IDs and Thread IDs with web links, which adds specificity but not sibling differentiation.

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. There's no mention of when this tool should be used instead of sibling tools like 'search_messages' or 'get_gmail_message_content', nor any prerequisites or exclusions. The only contextual information is that it searches 'in a user's Gmail account,' which is implied by the tool name.

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

Related 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/taylorwilsdon/google_workspace_mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server