Skip to main content
Glama
taylorwilsdon

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

search_messages

Search Google Chat spaces for specific messages by query. Returns a formatted list of matched messages for efficient communication tracking and retrieval.

Instructions

Searches for messages in Google Chat spaces by text content.

Returns:
    str: A formatted list of messages matching the search query.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
page_sizeNo
queryYes
serviceYes
space_idNo
user_google_emailYes

Implementation Reference

  • Registers the search_messages function as an MCP tool using the @server.tool() decorator.
    @server.tool()
  • The core implementation of the search_messages tool. Searches Google Chat messages by query string, optionally within a specific space or across multiple spaces. Handles API calls, formats results, and logs activity.
    async def search_messages(
        service,
        user_google_email: str,
        query: str,
        space_id: Optional[str] = None,
        page_size: int = 25
    ) -> str:
        """
        Searches for messages in Google Chat spaces by text content.
    
        Returns:
            str: A formatted list of messages matching the search query.
        """
        logger.info(f"[search_messages] Email={user_google_email}, Query='{query}'")
    
        # If specific space provided, search within that space
        if space_id:
            response = await asyncio.to_thread(
                service.spaces().messages().list(
                    parent=space_id,
                    pageSize=page_size,
                    filter=f'text:"{query}"'
                ).execute
            )
            messages = response.get('messages', [])
            context = f"space '{space_id}'"
        else:
            # Search across all accessible spaces (this may require iterating through spaces)
            # For simplicity, we'll search the user's spaces first
            spaces_response = await asyncio.to_thread(
                service.spaces().list(pageSize=100).execute
            )
            spaces = spaces_response.get('spaces', [])
    
            messages = []
            for space in spaces[:10]:  # Limit to first 10 spaces to avoid timeout
                try:
                    space_messages = await asyncio.to_thread(
                        service.spaces().messages().list(
                            parent=space.get('name'),
                            pageSize=5,
                            filter=f'text:"{query}"'
                        ).execute
                    )
                    space_msgs = space_messages.get('messages', [])
                    for msg in space_msgs:
                        msg['_space_name'] = space.get('displayName', 'Unknown')
                    messages.extend(space_msgs)
                except HttpError:
                    continue  # Skip spaces we can't access
            context = "all accessible spaces"
    
        if not messages:
            return f"No messages found matching '{query}' in {context}."
    
        output = [f"Found {len(messages)} messages matching '{query}' in {context}:"]
        for msg in messages:
            sender = msg.get('sender', {}).get('displayName', 'Unknown Sender')
            create_time = msg.get('createTime', 'Unknown Time')
            text_content = msg.get('text', 'No text content')
            space_name = msg.get('_space_name', 'Unknown Space')
    
            # Truncate long messages
            if len(text_content) > 100:
                text_content = text_content[:100] + "..."
    
            output.append(f"- [{create_time}] {sender} in '{space_name}': {text_content}")
    
        return "\n".join(output)
  • Function signature and docstring defining the input parameters and output for the search_messages tool.
    async def search_messages(
        service,
        user_google_email: str,
        query: str,
        space_id: Optional[str] = None,
        page_size: int = 25
    ) -> str:
        """
        Searches for messages in Google Chat spaces by text content.
    
        Returns:
            str: A formatted list of messages matching the search query.
        """
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It mentions the return format ('formatted list of messages') but lacks critical details: authentication requirements (implied by 'user_google_email' param but not stated), pagination behavior (implied by 'page_size' param but not explained), rate limits, error conditions, or whether it's read-only/destructive. For a search tool with 5 parameters, this 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.

Conciseness4/5

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

The description is appropriately concise with two sentences that directly address purpose and return format. It's front-loaded with the core functionality. However, the second sentence about return values could be integrated more smoothly, and there's room to add brief usage context without sacrificing conciseness.

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 5 parameters with 0% schema coverage, no annotations, and no output schema, the description is incomplete. It covers basic purpose and return format but misses parameter explanations, authentication context, pagination behavior, and error handling. For a search tool interacting with Google Chat API, this leaves the agent with insufficient operational context.

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

Parameters2/5

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

Schema description coverage is 0%, so parameters are undocumented in the schema. The description adds minimal value: it mentions 'text content' which relates to the 'query' parameter, but doesn't explain the purpose of 'service', 'space_id', 'user_google_email', or 'page_size'. It doesn't clarify parameter relationships, formats, or constraints, failing to compensate for the schema's lack of documentation.

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 for messages in Google Chat spaces by text content, providing specific verb ('searches') and resource ('messages in Google Chat spaces'). It distinguishes from some siblings like 'get_messages' (which likely retrieves without search) and 'search_gmail_messages' (which searches Gmail instead of Chat), but doesn't explicitly differentiate from all potential alternatives.

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?

No guidance is provided on when to use this tool versus alternatives. It doesn't mention prerequisites, constraints, or compare with similar tools like 'get_messages' or 'search_gmail_messages'. The agent must infer usage from the description alone without explicit direction.

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