Skip to main content
Glama
Racimy

iMail-mcp

get_messages

Retrieve email messages from your iCloud mailbox, with options to filter by unread status and limit results for focused email management.

Instructions

Get email messages from specified mailbox

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
limitNoMaximum number of messages to retrieve
mailboxNoMailbox name (default: INBOX)INBOX
unreadOnlyNoRetrieve only unread messages

Implementation Reference

  • src/index.ts:57-80 (registration)
    Registration of the 'get_messages' tool in the MCP server's listTools handler, including name, description, and input schema.
    {
      name: 'get_messages',
      description: 'Get email messages from specified mailbox',
      inputSchema: {
        type: 'object',
        properties: {
          mailbox: {
            type: 'string',
            description: 'Mailbox name (default: INBOX)',
            default: 'INBOX',
          },
          limit: {
            type: 'number',
            description: 'Maximum number of messages to retrieve',
            default: 10,
          },
          unreadOnly: {
            type: 'boolean',
            description: 'Retrieve only unread messages',
            default: false,
          },
        },
      },
    },
  • MCP tool handler for 'get_messages': validates connection, extracts parameters (mailbox, limit, unreadOnly), calls iCloudMailClient.getMessages, and returns JSON stringified messages.
    case 'get_messages': {
      if (!mailClient) {
        throw new McpError(
          ErrorCode.InvalidRequest,
          'iCloud Mail not configured. Please set ICLOUD_EMAIL and ICLOUD_APP_PASSWORD environment variables.'
        );
      }
    
      const mailbox = (args?.mailbox as string) || 'INBOX';
      const limit = (args?.limit as number) || 10;
      const unreadOnly = (args?.unreadOnly as boolean) || false;
    
      const messages = await mailClient.getMessages(
        mailbox,
        limit,
        unreadOnly
      );
    
      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify(messages, null, 2),
          },
        ],
      };
    }
  • Core helper method getMessages in iCloudMailClient class: opens IMAP mailbox, searches for recent messages (optionally unread), fetches bodies, parses with mailparser, extracts metadata/attachments/flags, returns EmailMessage array.
    async getMessages(
      mailbox: string = 'INBOX',
      limit: number = 10,
      unreadOnly: boolean = false
    ): Promise<EmailMessage[]> {
      return new Promise((resolve, reject) => {
        this.imap.openBox(mailbox, true, (err: Error) => {
          if (err) {
            reject(err);
            return;
          }
    
          const searchCriteria = unreadOnly ? ['UNSEEN'] : ['ALL'];
    
          this.imap.search(searchCriteria, (err: Error, results: number[]) => {
            if (err) {
              reject(err);
              return;
            }
    
            if (!results || results.length === 0) {
              resolve([]);
              return;
            }
    
            const messageIds = results.slice(-limit);
            const fetch = this.imap.fetch(messageIds, {
              bodies: '',
              struct: true,
            });
    
            const messages: EmailMessage[] = [];
    
            fetch.on('message', (msg: ImapMessage, seqno: number) => {
              let emailData = '';
    
              msg.on('body', (stream: NodeJS.ReadableStream) => {
                stream.on('data', (chunk: Buffer) => {
                  emailData += chunk.toString('utf8');
                });
    
                stream.once('end', async () => {
                  try {
                    const parsed: ParsedMail = await simpleParser(emailData);
    
                    const attachments: Attachment[] = [];
                    if (parsed.attachments) {
                      parsed.attachments.forEach((att: MailparserAttachment) => {
                        attachments.push({
                          filename: att.filename || 'unknown',
                          contentType:
                            att.contentType || 'application/octet-stream',
                          size: att.size || 0,
                          data: att.content,
                        });
                      });
                    }
    
                    const getEmailText = (
                      addr:
                        | MailparserAddressObject
                        | MailparserAddressObject[]
                        | undefined
                    ) => {
                      if (!addr) return '';
                      if (Array.isArray(addr))
                        return addr.map((a) => a.text).join(', ');
                      return addr.text;
                    };
    
                    const emailMessage: EmailMessage = {
                      id: parsed.messageId || `${seqno}`,
                      from: getEmailText(parsed.from),
                      to: parsed.to
                        ? Array.isArray(parsed.to)
                          ? parsed.to.map((t) => getEmailText(t))
                          : [getEmailText(parsed.to)]
                        : [],
                      subject: parsed.subject || '',
                      body: parsed.text || parsed.html || '',
                      date: parsed.date || new Date(),
                      flags: [],
                      attachments:
                        attachments.length > 0 ? attachments : undefined,
                    };
    
                    messages.push(emailMessage);
                  } catch (parseError) {
                    console.error('Error parsing email:', parseError);
                  }
                });
              });
    
              msg.once('attributes', (attrs: ImapMessageAttributes) => {
                if (attrs.flags) {
                  const lastMessage = messages[messages.length - 1];
                  if (lastMessage) {
                    lastMessage.flags = attrs.flags;
                  }
                }
              });
            });
    
            fetch.once('error', (fetchErr: Error) => {
              reject(fetchErr);
            });
    
            fetch.once('end', () => {
              resolve(messages);
            });
          });
        });
      });
    }
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. While 'Get' implies a read operation, it doesn't specify whether this requires authentication, what format messages are returned in, whether there are rate limits, or how errors are handled. For a tool with 3 parameters and no annotation coverage, this leaves significant behavioral gaps.

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 without unnecessary words. It's appropriately sized for a straightforward retrieval tool and gets directly to the point with zero wasted language.

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 3 parameters, no annotations, and no output schema, the description is insufficiently complete. It doesn't explain what format messages are returned in, whether there's pagination, what authentication is required, or how to handle errors. Given the complexity of email retrieval and the lack of structured metadata, the description should provide more operational context.

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 schema description coverage is 100%, with all parameters well-documented in the schema itself. The description adds no additional parameter information beyond what's already in the schema properties. This meets the baseline expectation when the schema does the heavy lifting, but doesn't provide 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 verb ('Get') and resource ('email messages') with scope ('from specified mailbox'), making the purpose immediately understandable. However, it doesn't differentiate from sibling tools like 'search_messages' or 'get_mailboxes', which would require more specific language about what distinguishes this retrieval operation.

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 'search_messages' or 'get_mailboxes'. There's no mention of prerequisites, typical use cases, or exclusions that would help an agent choose appropriately among the available email-related 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/Racimy/iMail-mcp'

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