Skip to main content
Glama
mundume
by mundume

listEmails

Retrieve and filter emails from Gmail with subject, sender, and body in Markdown format. Supports search queries and optional summarization.

Instructions

List emails from Gmail with subject, sender, and body in Markdown format. Optionally filter and summarize results.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryNoThe search query to filter emails. Use 'in:inbox','in:spam' 'in:unread', 'in:starred', 'in:sent', 'in:all', 'in:category_social', 'in:category_promotions', 'in:category_updates', 'in:category_forums', 'in:primary' or 'in:draft' to filter by label.in:inbox
maxResultsNoThe maximum number of emails to retrieve.

Implementation Reference

  • The handler function that executes the listEmails tool logic - fetches messages from Gmail API and parses them.
    case "listEmails": {
      if (!GMAIL_API_KEY) {
        return { content: [{ type: "text", text: "API Key not set." }] };
      }
    
      try {
        const { query, maxResults } = request.params.arguments || {};
    
        const queryParam = query
          ? `?q=${encodeURIComponent(query as string)}&maxResults=${maxResults}`
          : `?maxResults=${maxResults}`;
    
        const messageListResponse = await fetch(
          `https://gmail.googleapis.com/gmail/v1/users/${GMAIL_USER_ID}/messages${queryParam}`,
          { 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) {
          return { content: [{ type: "text", text: "No messages found." }] };
        }
    
        const emailMessages = [];
    
        for (const message of messageList.messages) {
          const messageId = message.id;
          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();
          emailMessages.push(await parseMessage(fullMessage));
        }
    
        return {
          content: [{ type: "text", text: JSON.stringify(emailMessages) }],
        };
      } catch (error: any) {
        return { content: [{ type: "text", text: `Error: ${error.message}` }] };
      }
    }
  • Zod schema defining the input parameters for the listEmails tool (query and maxResults).
    const ListEmailsSchema = z.object({
      query: z
        .string()
        .describe(
          "The search query to filter emails. Use 'in:inbox','in:spam' 'in:unread', 'in:starred', 'in:sent', 'in:all', 'in:category_social', 'in:category_promotions', 'in:category_updates', 'in:category_forums', 'in:primary' or 'in:draft' to filter by label."
        )
        .optional()
        .default("in:inbox"),
    
      maxResults: z
        .number()
        .optional()
        .describe("The maximum number of emails to retrieve.")
        .default(3),
    });
  • src/index.ts:60-64 (registration)
    Tool registration in the ListToolsRequestSchema handler, exposing listEmails to MCP clients.
      name: "listEmails",
      description:
        "List emails from Gmail with subject, sender, and body in Markdown format. Optionally filter and summarize results.",
      inputSchema: zodToJsonSchema(ListEmailsSchema),
    },
  • Helper function used by listEmails to parse Gmail message payload and extract subject, sender, and body.
    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?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions the output format ('Markdown format') and optional filtering/summarizing, but lacks critical details: it doesn't specify authentication needs, rate limits, pagination behavior, whether summaries are generated automatically or require parameters, or what happens if no emails match the query. For a tool with no annotations, this leaves significant gaps in understanding its 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 concise and front-loaded: the first sentence clearly states the core functionality, and the second adds optional features without redundancy. Every sentence earns its place by providing essential information, making it efficient and well-structured.

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 (listing emails with filtering), no annotations, and no output schema, the description is partially complete. It covers the basic purpose and output format but lacks details on authentication, error handling, summarization mechanics, and how results are structured. This is adequate as a minimum but has clear gaps for effective 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?

Schema description coverage is 100%, so the schema fully documents both parameters ('query' and 'maxResults') with descriptions and defaults. The description adds marginal value by mentioning 'Optionally filter and summarize results,' which hints at the 'query' parameter's purpose but doesn't provide additional semantic context beyond what's in the schema. 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 tool's purpose: 'List emails from Gmail with subject, sender, and body in Markdown format.' It specifies the verb ('List'), resource ('emails from Gmail'), and output format details. However, it doesn't explicitly distinguish this tool from its sibling 'getEmailContent' beyond the listing vs. content retrieval distinction.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides implied usage guidance through 'Optionally filter and summarize results,' suggesting this tool is for listing with optional filtering. It doesn't explicitly state when to use this vs. 'getEmailContent' (which likely retrieves a single email's full content) or 'sendEmail,' nor does it mention prerequisites like authentication requirements.

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