Skip to main content
Glama
ricleedo

Google Services MCP Server

by ricleedo

gmail-read-emails

Retrieve and list emails from Gmail accounts using search queries, label filters, and result limits for email management.

Instructions

Read/list emails from Gmail with optional search query

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryNoGmail search query (e.g., 'is:unread', 'from:example@gmail.com')
maxResultsNoMaximum number of emails to return
labelIdsNoArray of label IDs to filter by

Implementation Reference

  • Main handler function for reading/listing Gmail emails. Uses Google Gmail API to list messages by query/label, fetches metadata for each, formats as Markdown list.
    export async function readEmails(params: z.infer<typeof readEmailsSchema>) {
      try {
        const auth = createGmailAuth();
        const gmail = google.gmail({ version: "v1", auth });
    
        const listParams: any = {
          userId: "me",
          maxResults: params.maxResults,
        };
    
        if (params.query) listParams.q = params.query;
        if (params.labelIds) listParams.labelIds = params.labelIds;
    
        const response = await gmail.users.messages.list(listParams);
    
        if (!response.data.messages || response.data.messages.length === 0) {
          return {
            content: [
              {
                type: "text" as const,
                text: "# No Emails Found\n\nNo emails found matching your search criteria.",
              },
            ],
          };
        }
    
        // Get detailed information for each message
        const emailDetails = await Promise.all(
          response.data.messages
            .slice(0, params.maxResults)
            .map(async (message) => {
              const detail = await gmail.users.messages.get({
                userId: "me",
                id: message.id!,
                format: "metadata",
                metadataHeaders: ["From", "To", "Subject", "Date"],
              });
    
              const headers = detail.data.payload?.headers || [];
              const getHeader = (name: string) =>
                headers.find((h) => h.name?.toLowerCase() === name.toLowerCase())
                  ?.value || "";
    
              return {
                id: message.id,
                threadId: message.threadId,
                from: getHeader("From"),
                to: getHeader("To"),
                subject: getHeader("Subject"),
                date: getHeader("Date"),
                snippet: detail.data.snippet,
                labelIds: detail.data.labelIds,
              };
            })
        );
    
        return {
          content: [
            {
              type: "text" as const,
              text: formatEmailListToMarkdown(emailDetails),
            },
          ],
        };
      } catch (error) {
        return {
          content: [
            {
              type: "text" as const,
              text: `Error reading emails: ${
                error instanceof Error ? error.message : String(error)
              }`,
            },
          ],
        };
      }
    }
  • Zod schema defining input parameters for the gmail-read-emails tool: optional query string, maxResults (default 10, 1-100), optional labelIds array.
    export const readEmailsSchema = z.object({
      query: z
        .string()
        .optional()
        .describe(
          "Gmail search query (e.g., 'is:unread', 'from:example@gmail.com')"
        ),
      maxResults: z
        .number()
        .min(1)
        .max(100)
        .default(10)
        .describe("Maximum number of emails to return"),
      labelIds: z
        .array(z.string())
        .optional()
        .describe("Array of label IDs to filter by"),
    });
  • src/index.ts:191-198 (registration)
    Registration of the 'gmail-read-emails' tool in the MCP server, linking to readEmails handler and readEmailsSchema.
    server.tool(
      "gmail-read-emails",
      "Read/list emails from Gmail with optional search query",
      readEmailsSchema.shape,
      async (params) => {
        return await readEmails(params);
      }
    );
  • Helper function to format the list of email details into Markdown for the tool response.
    function formatEmailListToMarkdown(emails: any[]): string {
      if (!emails.length) return "No emails found.";
      
      let markdown = `# Inbox (${emails.length} emails)\n\n`;
      
      emails.forEach((email, index) => {
        const date = new Date(email.date).toLocaleDateString();
        const from = email.from.replace(/[<>]/g, '');
        const subject = email.subject || '(No Subject)';
        const snippet = email.snippet || '';
        
        markdown += `## ${index + 1}. ${subject}\n`;
        markdown += `From: ${from}  \n`;
        markdown += `Date: ${date}  \n`;
        markdown += `ID: \`${email.id}\`\n\n`;
        
        if (snippet) {
          markdown += `${snippet}\n\n`;
        }
        
        markdown += `---\n\n`;
      });
      
      return markdown;
    }
  • Helper function to create authenticated Gmail client using environment variables for OAuth2 credentials.
    function createGmailAuth() {
      const clientId = process.env.GOOGLE_CLIENT_ID;
      const clientSecret = process.env.GOOGLE_CLIENT_SECRET;
      const redirectUri =
        process.env.GOOGLE_REDIRECT_URI || "http://localhost:3000/oauth2callback";
    
      if (!clientId || !clientSecret) {
        throw new Error(
          "GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET are required. Run oauth-setup.js to configure."
        );
      }
    
      const oauth2Client = new google.auth.OAuth2(
        clientId,
        clientSecret,
        redirectUri
      );
    
      const accessToken = process.env.GOOGLE_ACCESS_TOKEN;
      const refreshToken = process.env.GOOGLE_REFRESH_TOKEN;
    
      if (!accessToken || !refreshToken) {
        throw new Error("OAuth2 tokens missing. Run oauth-setup.js to get tokens.");
      }
    
      oauth2Client.setCredentials({
        access_token: accessToken,
        refresh_token: refreshToken,
      });
    
      return oauth2Client;
    }
Behavior2/5

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

With no annotations provided, the description carries full burden but only states the basic action. It doesn't disclose whether this requires authentication, rate limits, pagination behavior, what data is returned (e.g., full emails vs summaries), or any side effects. 'Read/list' implies a safe operation but lacks confirmation of read-only nature or other behavioral traits.

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 states the core functionality with no wasted words. It's appropriately front-loaded with the main action and includes the key optional feature.

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?

For a read operation with 3 parameters and no annotations or output schema, the description is insufficient. It doesn't explain what gets returned (email objects, metadata, etc.), authentication requirements, error conditions, or how results are structured. The agent would need to guess about the output format and behavioral details.

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 fully documents all three parameters. The description adds no parameter-specific information beyond mentioning 'optional search query' which is already covered in the schema. Baseline 3 is appropriate when schema does the heavy lifting.

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 verb ('Read/list') and resource ('emails from Gmail') with the optional search functionality. It distinguishes from siblings like 'gmail-get-email' (singular retrieval) and 'gmail-send-email' (write operation), though it doesn't explicitly mention this differentiation in the text.

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 'gmail-get-email' (for single email retrieval) or 'gmail-get-labels' (for label management). It mentions optional search query but gives no context about when filtering is appropriate versus using other tools.

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/ricleedo/Google-Service-MCP'

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