Skip to main content
Glama

gmail_mark_as_read_by_query

Mark Gmail emails matching search queries as read. Use Gmail query syntax to target specific messages, with confirmation required for changes. Preview results before applying.

Instructions

Mark emails matching a search query as read. Use Gmail query syntax. Requires confirmation.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesGmail search query to find emails to mark as read. Examples: 'from:newsletter@example.com', 'older_than:7d is:unread'.
max_emailsNoMaximum number of emails to mark as read. Default 100, max 500.
confirmYesMust be true to actually mark as read. Set false to preview what would be marked.

Implementation Reference

  • Core implementation: Searches for unread emails matching the Gmail query (limited to max_emails), retrieves their IDs, and marks them as read by calling mark_as_read.
    async def mark_as_read_by_query(self, query: str, max_emails: int = 100) -> dict:
        """Mark emails matching a query as read.
        
        Args:
            query: Gmail search query (e.g., "from:newsletter@example.com", "older_than:7d")
            max_emails: Maximum number of emails to mark as read (safety limit)
            
        Returns:
            Dict with success count, matched count, and any errors
        """
        try:
            # First, find matching emails
            results = (
                self.service.users()
                .messages()
                .list(userId="me", q=f"{query} is:unread", maxResults=max_emails)
                .execute()
            )
            
            messages = results.get("messages", [])
            if not messages:
                return {
                    "matched": 0,
                    "success": 0,
                    "errors": [],
                    "message": "No unread emails matched the query"
                }
            
            message_ids = [msg["id"] for msg in messages]
            
            # Mark them as read
            mark_result = await self.mark_as_read(message_ids)
            mark_result["matched"] = len(messages)
            
            # Check if there might be more
            if len(messages) == max_emails:
                mark_result["message"] = f"Marked {mark_result['success']} emails as read. There may be more matching emails (limit was {max_emails})."
            else:
                mark_result["message"] = f"Marked {mark_result['success']} emails as read."
                
            return mark_result
            
        except HttpError as e:
            logger.error(f"Failed to search and mark emails: {e}")
            return {"matched": 0, "success": 0, "errors": [str(e)], "message": f"Error: {e}"}
  • MCP tool dispatch handler: Parses arguments, provides preview if confirm=false by searching and listing matching emails, otherwise delegates to GmailClient.mark_as_read_by_query
    elif name == "gmail_mark_as_read_by_query":
        query = arguments.get("query", "")
        max_emails = min(arguments.get("max_emails", 100), 500)
        confirm = arguments.get("confirm", False)
        
        if not query:
            return [TextContent(type="text", text="Error: query is required.")]
        
        if not confirm:
            # Preview mode - show what would be marked
            search_results = await client.search_emails(f"{query} is:unread", max_emails)
            if not search_results:
                return [TextContent(type="text", text=f"No unread emails match the query: {query}")]
            
            lines = [f"Preview: {len(search_results)} email(s) would be marked as read:\n"]
            for email in search_results[:20]:
                lines.append(f"- {email.subject}")
                lines.append(f"  From: {email.sender.email}")
                lines.append(f"  Date: {email.date.strftime('%Y-%m-%d %H:%M')}")
                lines.append("")
            
            if len(search_results) > 20:
                lines.append(f"... and {len(search_results) - 20} more\n")
            
            lines.append("Set confirm=true to proceed.")
            return [TextContent(type="text", text="\n".join(lines))]
        else:
            result = await client.mark_as_read_by_query(query, max_emails)
            return [TextContent(
                type="text",
                text=f"Success: {result['message']}\nMatched: {result['matched']}, Marked as read: {result['success']}"
                + (f", Errors: {result['errors']}" if result['errors'] else "")
            )]
  • Tool registration in GMAIL_TOOLS list: Defines the tool name, description, and JSON schema for MCP server.
        name="gmail_mark_as_read_by_query",
        description="Mark emails matching a search query as read. Use Gmail query syntax. Requires confirmation.",
        inputSchema={
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": "Gmail search query to find emails to mark as read. Examples: 'from:newsletter@example.com', 'older_than:7d is:unread'."
                },
                "max_emails": {
                    "type": "integer",
                    "description": "Maximum number of emails to mark as read. Default 100, max 500."
                },
                "confirm": {
                    "type": "boolean",
                    "description": "Must be true to actually mark as read. Set false to preview what would be marked."
                }
            },
            "required": ["query", "confirm"]
        },
    ),
  • Supporting function: Batch removes the 'UNREAD' label from the specified message IDs using Gmail API batchModify.
    async def mark_as_read(self, message_ids: list[str]) -> dict:
        """Mark one or more emails as read by removing the UNREAD label.
        
        Args:
            message_ids: List of Gmail message IDs to mark as read
            
        Returns:
            Dict with success count and any errors
        """
        if not message_ids:
            return {"success": 0, "errors": [], "message": "No message IDs provided"}
        
        results = {"success": 0, "errors": []}
        
        try:
            # Use batchModify for efficiency (up to 1000 at a time)
            if len(message_ids) <= 1000:
                self.service.users().messages().batchModify(
                    userId="me",
                    body={
                        "ids": message_ids,
                        "removeLabelIds": ["UNREAD"]
                    }
                ).execute()
                results["success"] = len(message_ids)
            else:
                # Process in batches of 1000
                for i in range(0, len(message_ids), 1000):
                    batch = message_ids[i:i+1000]
                    self.service.users().messages().batchModify(
                        userId="me",
                        body={
                            "ids": batch,
                            "removeLabelIds": ["UNREAD"]
                        }
                    ).execute()
                    results["success"] += len(batch)
                    
        except HttpError as e:
            logger.error(f"Failed to mark emails as read: {e}")
            results["errors"].append(str(e))
            
        return results
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 mentions the confirmation requirement ('Requires confirmation'), which is a critical safety feature for a mutation tool. However, it doesn't disclose other important behaviors like whether the operation is reversible, what permissions are needed, rate limits, or what happens on success/failure. 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 perfectly concise with just two sentences that each earn their place. The first sentence states the core purpose, and the second adds critical behavioral context (confirmation requirement). There's zero wasted language, and the information is front-loaded appropriately.

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 this is a mutation tool with no annotations and no output schema, the description should do more to be complete. While it covers the basic purpose and confirmation requirement, it lacks information about what the tool returns, error conditions, side effects, or detailed behavioral constraints. The description is adequate but has clear gaps for a tool that modifies email state.

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%, so the schema already documents all three parameters thoroughly. The description adds no additional parameter information beyond what's in the schema. According to the scoring rules, when schema coverage is high (>80%), the baseline is 3 even with no param info in the description, which applies here.

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 ('mark as read') and target resource ('emails matching a search query'), distinguishing it from siblings like gmail_mark_as_read_by_ids (which uses IDs instead of queries) and gmail_mark_as_unread_by_query (which performs the opposite action). The verb+resource combination is precise and unambiguous.

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 provides clear context for when to use this tool ('mark emails matching a search query as read') and mentions the 'Requires confirmation' prerequisite. However, it doesn't explicitly state when NOT to use it or name alternatives like gmail_mark_as_read_by_ids for ID-based operations, which would be helpful for sibling differentiation.

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/murphy360/mcp_gmail'

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