Skip to main content
Glama
Racimy

iMail-mcp

search_messages

Search for messages in iCloud mail using text queries, date ranges, sender filters, and mailbox selection to find specific emails quickly.

Instructions

Search for messages using various criteria

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
dateFromNoStart date for search (YYYY-MM-DD format)
dateToNoEnd date for search (YYYY-MM-DD format)
fromEmailNoFilter by sender email address
limitNoMaximum number of messages to retrieve
mailboxNoMailbox name (default: INBOX)INBOX
queryNoSearch query text (searches in subject, from, body)
unreadOnlyNoSearch only unread messages

Implementation Reference

  • MCP server request handler for the 'search_messages' tool. Validates connection, extracts parameters from args, calls iCloudMailClient.searchMessages, and returns JSON-formatted results.
    case 'search_messages': {
      if (!mailClient) {
        throw new McpError(
          ErrorCode.InvalidRequest,
          'iCloud Mail not configured. Please set ICLOUD_EMAIL and ICLOUD_APP_PASSWORD environment variables.'
        );
      }
    
      const query = args?.query as string;
      const mailbox = (args?.mailbox as string) || 'INBOX';
      const limit = (args?.limit as number) || 10;
      const dateFrom = args?.dateFrom as string;
      const dateTo = args?.dateTo as string;
      const fromEmail = args?.fromEmail as string;
      const unreadOnly = (args?.unreadOnly as boolean) || false;
    
      const messages = await mailClient.searchMessages({
        query,
        mailbox,
        limit,
        dateFrom,
        dateTo,
        fromEmail,
        unreadOnly,
      });
    
      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify(messages, null, 2),
          },
        ],
      };
    }
  • src/index.ts:197-237 (registration)
    Registration of the 'search_messages' tool in the ListTools response, including name, description, and detailed input schema.
    {
      name: 'search_messages',
      description: 'Search for messages using various criteria',
      inputSchema: {
        type: 'object',
        properties: {
          query: {
            type: 'string',
            description:
              'Search query text (searches in subject, from, body)',
          },
          mailbox: {
            type: 'string',
            description: 'Mailbox name (default: INBOX)',
            default: 'INBOX',
          },
          limit: {
            type: 'number',
            description: 'Maximum number of messages to retrieve',
            default: 10,
          },
          dateFrom: {
            type: 'string',
            description: 'Start date for search (YYYY-MM-DD format)',
          },
          dateTo: {
            type: 'string',
            description: 'End date for search (YYYY-MM-DD format)',
          },
          fromEmail: {
            type: 'string',
            description: 'Filter by sender email address',
          },
          unreadOnly: {
            type: 'boolean',
            description: 'Search only unread messages',
            default: false,
          },
        },
      },
    },
  • TypeScript interface defining the SearchOptions used for the search_messages tool parameters, matching the JSON schema.
    export interface SearchOptions {
      query?: string;
      mailbox?: string;
      limit?: number;
      dateFrom?: string;
      dateTo?: string;
      fromEmail?: string;
      unreadOnly?: boolean;
    }
  • Core implementation of message searching in iCloudMailClient using IMAP search with criteria from options, fetching and parsing bodies of matching emails into EmailMessage objects.
    async searchMessages(options: SearchOptions): Promise<EmailMessage[]> {
      const {
        query,
        mailbox = 'INBOX',
        limit = 10,
        dateFrom,
        dateTo,
        fromEmail,
        unreadOnly = false,
      } = options;
    
      return new Promise((resolve, reject) => {
        this.imap.openBox(mailbox, true, (err: Error) => {
          if (err) {
            reject(err);
            return;
          }
    
          type SearchCriterion =
            | string
            | [string, string | Date]
            | [string, [string, string], [string, string]];
          const searchCriteria: SearchCriterion[] = [];
    
          if (unreadOnly) {
            searchCriteria.push('UNSEEN');
          }
    
          if (dateFrom) {
            const date = new Date(dateFrom);
            if (!isNaN(date.getTime())) {
              searchCriteria.push(['SINCE', date]);
            }
          }
    
          if (dateTo) {
            const date = new Date(dateTo);
            if (!isNaN(date.getTime())) {
              searchCriteria.push(['BEFORE', date]);
            }
          }
    
          if (fromEmail) {
            searchCriteria.push(['FROM', fromEmail]);
          }
    
          if (query) {
            searchCriteria.push(['OR', ['SUBJECT', query], ['BODY', query]]);
          }
    
          if (searchCriteria.length === 0) {
            searchCriteria.push('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. It states the tool searches messages but doesn't describe what happens during execution (e.g., whether it's read-only, if it requires authentication, potential rate limits, or what the output looks like). The phrase 'using various criteria' is vague and doesn't add meaningful behavioral context beyond what the parameters imply.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that gets straight to the point without unnecessary words. It's appropriately sized for a search tool, though it could be slightly more informative without losing conciseness.

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 has 7 parameters, no annotations, and no output schema, the description is incomplete. It doesn't explain the return values, error conditions, or behavioral traits like whether it's safe to use or has side effects. For a search tool with multiple filtering options, more context is needed to guide effective 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 all 7 parameters with clear descriptions. The description adds no specific parameter information beyond 'various criteria,' which doesn't provide additional meaning or context. This meets the baseline of 3 since the 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 ('search') and resource ('messages'), specifying the action and target. It mentions 'various criteria' which hints at filtering capabilities, but doesn't explicitly differentiate from sibling tools like 'get_messages' or 'auto_organize' that might also retrieve messages.

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 when to prefer search_messages over get_messages (which might retrieve specific messages without filtering) or auto_organize (which might involve searching as part of organization). No context about prerequisites or exclusions is provided.

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