Skip to main content
Glama
rishipradeep-think41

Google Workspace MCP Server

search_emails

Search and filter emails in your Google Workspace account using advanced Gmail queries. Retrieve specific messages by sender, recipient, subject, attachments, date range, or unread status, with customizable result limits.

Instructions

Search emails with advanced query

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
maxResultsNoMaximum number of emails to return (default: 10)
queryYesGmail search query (e.g., "from:example@gmail.com has:attachment"). Examples: - "from:alice@example.com" (Emails from Alice) - "to:bob@example.com" (Emails sent to Bob) - "subject:Meeting Update" (Emails with "Meeting Update" in the subject) - "has:attachment filename:pdf" (Emails with PDF attachments) - "after:2024/01/01 before:2024/02/01" (Emails between specific dates) - "is:unread" (Unread emails) - "from:@company.com has:attachment" (Emails from a company domain with attachments)

Implementation Reference

  • The handler function that implements the 'search_emails' tool. It uses the Gmail API to search for emails using the provided query, fetches details for each matching message including subject, sender, date, body (extracted from plain text parts), and labels, then returns the results as a JSON string in the MCP response format.
    private async handleSearchEmails(args: any) {
      try {
        const maxResults = args?.maxResults || 10;
        const query = args?.query || "";
    
        const getEmailBody = (payload: any): string => {
          if (!payload) return "";
    
          if (payload.body && payload.body.data) {
            return Buffer.from(payload.body.data, "base64").toString("utf-8");
          }
    
          if (payload.parts && payload.parts.length > 0) {
            for (const part of payload.parts) {
              if (part.mimeType === "text/plain") {
                return Buffer.from(part.body.data, "base64").toString("utf-8");
              }
            }
          }
    
          return "(No body content)";
        };
    
        const response = await this.gmail.users.messages.list({
          userId: "me",
          maxResults,
          q: query,
        });
    
        const messages = response.data.messages || [];
        const emailDetails = await Promise.all(
          messages.map(async (msg) => {
            const detail = await this.gmail.users.messages.get({
              userId: "me",
              id: msg.id!,
            });
    
            const headers = detail.data.payload?.headers;
            const subject =
              headers?.find((h) => h.name === "Subject")?.value || "";
            const from = headers?.find((h) => h.name === "From")?.value || "";
            const date = headers?.find((h) => h.name === "Date")?.value || "";
            const body = getEmailBody(detail.data.payload);
            // Use helper function to extract the email body correctly
    
            return {
              id: msg.id,
              subject,
              from,
              date,
              body,
              labels: detail.data.labelIds || [],
            };
          })
        );
    
        return {
          content: [
            {
              type: "text",
              text: JSON.stringify(emailDetails, null, 2),
            },
          ],
        };
      } catch (error: any) {
        return {
          content: [
            {
              type: "text",
              text: `Error fetching emails: ${error.message}`,
            },
          ],
          isError: true,
        };
      }
    }
  • The input schema for the 'search_emails' tool, defining the expected arguments: a required 'query' string for Gmail search and optional 'maxResults' number.
    inputSchema: {
      type: "object",
      properties: {
        query: {
          type: "string",
          description:
            'Gmail search query (e.g., "from:example@gmail.com has:attachment"). Examples:\n' +
            '- "from:alice@example.com" (Emails from Alice)\n' +
            '- "to:bob@example.com" (Emails sent to Bob)\n' +
            '- "subject:Meeting Update" (Emails with "Meeting Update" in the subject)\n' +
            '- "has:attachment filename:pdf" (Emails with PDF attachments)\n' +
            '- "after:2024/01/01 before:2024/02/01" (Emails between specific dates)\n' +
            '- "is:unread" (Unread emails)\n' +
            '- "from:@company.com has:attachment" (Emails from a company domain with attachments)',
        },
        maxResults: {
          type: "number",
          description: "Maximum number of emails to return (default: 10)",
        },
      },
      required: ["query"],
  • src/index.ts:80-105 (registration)
    Registration of the 'search_emails' tool in the MCP ListToolsRequestSchema handler, including name, description, and input schema.
    {
      name: "search_emails",
      description: "Search emails with advanced query",
      inputSchema: {
        type: "object",
        properties: {
          query: {
            type: "string",
            description:
              'Gmail search query (e.g., "from:example@gmail.com has:attachment"). Examples:\n' +
              '- "from:alice@example.com" (Emails from Alice)\n' +
              '- "to:bob@example.com" (Emails sent to Bob)\n' +
              '- "subject:Meeting Update" (Emails with "Meeting Update" in the subject)\n' +
              '- "has:attachment filename:pdf" (Emails with PDF attachments)\n' +
              '- "after:2024/01/01 before:2024/02/01" (Emails between specific dates)\n' +
              '- "is:unread" (Unread emails)\n' +
              '- "from:@company.com has:attachment" (Emails from a company domain with attachments)',
          },
          maxResults: {
            type: "number",
            description: "Maximum number of emails to return (default: 10)",
          },
        },
        required: ["query"],
      },
    },
  • src/index.ts:276-277 (registration)
    Dispatch case in the CallToolRequestSchema handler that routes 'search_emails' tool calls to the handleSearchEmails method.
    case "search_emails":
      return await this.handleSearchEmails(request.params.arguments);
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 states the tool searches emails but doesn't mention whether this is a read-only operation, if it requires specific permissions, how results are returned (e.g., pagination), or any rate limits. The description adds minimal behavioral context beyond the basic action.

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 a single, efficient sentence that front-loads the core purpose ('Search emails with advanced query'). It avoids redundancy and wastes no words, making it highly concise and well-structured for quick understanding.

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 (search with query parameters), no annotations, and no output schema, the description is minimally adequate. It covers the basic action but lacks details on behavioral traits, usage context, and return values, leaving gaps that could hinder an agent's effective use.

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 detailed examples for the 'query' parameter and a clear description for 'maxResults'. The description adds no additional parameter semantics beyond what the schema provides, so it meets the baseline of 3 for adequate coverage without extra value.

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's purpose as 'Search emails with advanced query', which specifies the verb (search) and resource (emails). It distinguishes from siblings like 'list_emails' by emphasizing 'advanced query' capabilities, though it doesn't explicitly contrast with 'list_emails' which might be a simpler listing tool.

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 like 'list_emails' or 'modify_email'. It mentions 'advanced query' but doesn't specify scenarios where this is preferred over simpler tools or when not to use it, leaving the agent to infer usage from context 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

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/rishipradeep-think41/gsuite-mcp'

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