Skip to main content
Glama
mundume
by mundume

getEmailContent

Retrieve full email content from Gmail by specifying the email index to access complete message details.

Instructions

Retrieve the full content of an email from Gmail.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
emailIndexYesThe index of the email to retrieve.

Implementation Reference

  • The getEmailContent tool handler that retrieves full email content. It validates the emailIndex parameter, fetches the list of messages to find the message at the specified index, retrieves the full message content from Gmail API, parses it, and returns the result.
    case "getEmailContent": {
      if (!GMAIL_API_KEY) {
        return { content: [{ type: "text", text: "API Key not set." }] };
      }
    
      try {
        const { emailIndex } = EmailIndexSchema.parse(request.params.arguments);
    
        // 1. Get List of Message IDs (up to the requested index)
        const messageListResponse = await fetch(
          `https://gmail.googleapis.com/gmail/v1/users/${GMAIL_USER_ID}/messages?maxResults=${emailIndex}`,
          { headers: { Authorization: `Bearer ${GMAIL_API_KEY}` } }
        );
    
        if (!messageListResponse.ok) {
          const errorData = await messageListResponse.json();
          const errorMessage =
            errorData.error?.message || messageListResponse.statusText;
          return {
            content: [{ type: "text", text: `Error: ${errorMessage}` }],
          };
        }
    
        const messageList = await messageListResponse.json();
    
        if (!messageList.messages || messageList.messages.length < emailIndex) {
          return {
            content: [
              { type: "text", text: "Email not found at the specified index." },
            ],
          };
        }
    
        const messageId = messageList.messages[emailIndex - 1].id; // Get the ID at the requested index
    
        // 2. Get Full Message Content
        const messageResponse = await fetch(
          `https://gmail.googleapis.com/gmail/v1/users/${GMAIL_USER_ID}/messages/${messageId}?format=full`,
          { headers: { Authorization: `Bearer ${GMAIL_API_KEY}` } }
        );
    
        if (!messageResponse.ok) {
          const errorData = await messageResponse.json();
          const errorMessage =
            errorData.error?.message || messageResponse.statusText;
          return {
            content: [{ type: "text", text: `Error: ${errorMessage}` }],
          };
        }
    
        const fullMessage = await messageResponse.json();
        const emailContent = await parseMessage(fullMessage);
    
        return {
          content: [{ type: "text", text: JSON.stringify(emailContent) }],
        };
      } catch (error: any) {
        return { content: [{ type: "text", text: `Error: ${error.message}` }] };
      }
    }
  • src/index.ts:65-69 (registration)
    Tool registration in the MCP server that defines the getEmailContent tool with its name, description, and input schema.
    {
      name: "getEmailContent",
      description: "Retrieve the full content of an email from Gmail.",
      inputSchema: zodToJsonSchema(EmailIndexSchema),
    },
  • Zod schema definition for the getEmailContent tool parameters, validating the emailIndex input.
    const EmailIndexSchema = z.object({
      emailIndex: z.number().describe("The index of the email to retrieve."),
    });
  • Helper function parseMessage that extracts and decodes the email subject, sender, and body from the Gmail API message format, handling both multipart and simple messages.
    async function parseMessage(message: {
      payload: {
        headers: { name: string; value: string }[];
        parts: { mimeType: string; body: { data: WithImplicitCoercion<string> } }[];
        body: { data: WithImplicitCoercion<string> };
      };
      id: string;
    }) {
      const headers = message.payload.headers;
      const subject = headers.find(
        (header: { name: string }) => header.name === "Subject"
      )?.value;
      const from = headers.find(
        (header: { name: string }) => header.name === "From"
      )?.value;
      let body = "";
    
      if (message.payload.parts) {
        const textPart = message.payload.parts.find(
          (part) => part.mimeType === "text/plain"
        );
        if (textPart) {
          body = Buffer.from(textPart.body.data, "base64").toString("utf-8");
        } else {
          const htmlPart = message.payload.parts.find(
            (part) => part.mimeType === "text/html"
          );
          if (htmlPart) {
            body = Buffer.from(htmlPart.body.data, "base64").toString("utf-8");
          }
        }
      } else if (message.payload.body.data) {
        body = Buffer.from(message.payload.body.data, "base64").toString("utf-8");
      }
    
      return {
        id: message.id,
        subject: subject,
        from: from,
        body: body,
      };
    }
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 states the tool retrieves email content but doesn't mention important aspects like authentication requirements, rate limits, error conditions, or what format the content is returned in (plain text, HTML, attachments). This leaves significant gaps for an agent to understand how to use it effectively.

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 directly states the tool's purpose with zero wasted words. It's appropriately sized for a simple retrieval tool and gets straight to the point.

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 tool with no annotations and no output schema, the description is insufficient. It doesn't explain what 'full content' includes (body, headers, attachments), doesn't mention authentication needs, and provides no context about how emailIndex is obtained or validated. Given the complexity of email retrieval and lack of structured metadata, more completeness is needed.

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 the emailIndex parameter. The description doesn't add any additional parameter context beyond what's in the schema, such as explaining how emailIndex relates to listEmails output or valid index ranges. This meets the baseline for high schema coverage.

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 action ('Retrieve') and target ('full content of an email from Gmail'), making the purpose immediately understandable. However, it doesn't differentiate from sibling tools like 'listEmails' or 'sendEmail' beyond the obvious functional difference.

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. The description doesn't mention prerequisites (like needing to list emails first to get an index), nor does it clarify the relationship with 'listEmails' for obtaining the required emailIndex parameter.

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/mundume/gmail-mcp'

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