Skip to main content
Glama

gmail-get-email

Retrieve a specific Gmail email using its message ID to access individual messages directly within the MCP Server Boilerplate framework.

Instructions

Get a specific email by message ID

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
messageIdYesGmail message ID

Implementation Reference

  • Main handler function 'getEmail' that retrieves a specific Gmail message by ID using the Gmail API v1, extracts headers and body (handling multipart), truncates long body, formats to Markdown using helper, and returns structured content or error.
    export async function getEmail(params: z.infer<typeof getEmailSchema>) {
      try {
        const auth = createGmailAuth();
        const gmail = google.gmail({ version: "v1", auth });
    
        const response = await gmail.users.messages.get({
          userId: "me",
          id: params.messageId,
          format: "full",
        });
    
        const message = response.data;
        const headers = message.payload?.headers || [];
        const getHeader = (name: string) =>
          headers.find((h) => h.name?.toLowerCase() === name.toLowerCase())
            ?.value || "";
    
        // Extract body content
        let body = "";
        if (message.payload?.body?.data) {
          body = Buffer.from(message.payload.body.data, "base64").toString();
        } else if (message.payload?.parts) {
          // Handle multipart messages
          for (const part of message.payload.parts) {
            if (part.mimeType === "text/plain" && part.body?.data) {
              body = Buffer.from(part.body.data, "base64").toString();
              break;
            }
          }
        }
    
        // Truncate body if it exceeds 30000 characters
        const truncatedBody =
          body.length > 20000
            ? body.substring(0, 20000) +
              "\n\n[Email body truncated - content too long]"
            : body;
    
        const emailDetail = {
          id: message.id,
          threadId: message.threadId,
          from: getHeader("From"),
          to: getHeader("To"),
          cc: getHeader("Cc"),
          bcc: getHeader("Bcc"),
          subject: getHeader("Subject"),
          date: getHeader("Date"),
          body: truncatedBody,
          snippet: message.snippet,
          labelIds: message.labelIds,
        };
    
        return {
          content: [
            {
              type: "text" as const,
              text: formatEmailToMarkdown(emailDetail),
            },
          ],
        };
      } catch (error) {
        return {
          content: [
            {
              type: "text" as const,
              text: `Error getting email: ${
                error instanceof Error ? error.message : String(error)
              }`,
            },
          ],
        };
      }
    }
  • Zod input schema for the tool, requiring a single 'messageId' string parameter.
    export const getEmailSchema = z.object({
      messageId: z.string().describe("Gmail message ID"),
    });
  • src/index.ts:200-207 (registration)
    MCP server tool registration for 'gmail-get-email', specifying name, description, input schema from getEmailSchema, and handler calling getEmail.
    server.tool(
      "gmail-get-email",
      "Get a specific email by message ID",
      getEmailSchema.shape,
      async (params) => {
        return await getEmail(params);
      }
    );
  • Helper function to format the retrieved email details into a readable Markdown structure, used in the handler's response.
    function formatEmailToMarkdown(email: any): string {
      const date = new Date(email.date).toLocaleDateString();
      const from = email.from.replace(/[<>]/g, '');
      const to = email.to.replace(/[<>]/g, '');
      const subject = email.subject || '(No Subject)';
      
      let markdown = `# ${subject}\n\n`;
      markdown += `From: ${from}  \n`;
      markdown += `To: ${to}  \n`;
      if (email.cc) markdown += `CC: ${email.cc.replace(/[<>]/g, '')}  \n`;
      if (email.bcc) markdown += `BCC: ${email.bcc.replace(/[<>]/g, '')}  \n`;
      markdown += `Date: ${date}  \n`;
      markdown += `Message ID: \`${email.id}\`\n\n`;
      
      if (email.body) {
        markdown += `---\n\n${email.body}\n`;
      }
      
      return markdown;
    }
  • Shared authentication helper function that creates OAuth2 client for Gmail API using environment variables for credentials and tokens.
    // OAuth2 Authentication helper
    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?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It states the action ('Get') but doesn't describe what 'get' returns (e.g., full email content, headers, attachments), error conditions (e.g., invalid ID, permissions), or side effects (e.g., marking as read). For a read operation with zero annotation coverage, this leaves significant gaps in understanding the tool's behavior.

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, direct sentence with zero wasted words. It front-loads the core action ('Get a specific email') and specifies the key identifier ('by message ID'), making it highly efficient. Every part of the sentence contributes essential information without redundancy.

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 the tool's simplicity (1 parameter, no output schema, no annotations), the description is incomplete. It doesn't explain what 'get' returns (e.g., email body, metadata), potential errors, or how the message ID should be obtained. For a tool that retrieves data, this lack of output and behavioral context makes it inadequate for reliable agent 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?

The description doesn't add any parameter-specific information beyond what's in the input schema, which has 100% coverage (the 'messageId' parameter is fully described as 'Gmail message ID'). With high schema coverage, the baseline is 3, as the schema already documents the parameter adequately, and the description doesn't compensate with additional context like format examples or sourcing details.

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 ('Get') and resource ('a specific email'), making the purpose immediately understandable. It distinguishes from sibling tools like 'gmail-read-emails' (which lists emails) and 'gmail-send-email' (which sends emails). However, it doesn't specify what 'get' entails (e.g., retrieving full content vs metadata), which prevents a perfect score.

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. It doesn't mention prerequisites (e.g., needing a valid message ID), contrast with 'gmail-read-emails' for listing emails, or specify use cases like retrieving a single known email. Without such context, the agent must infer usage from the tool name 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

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/CaptainCrouton89/maps-mcp'

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