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
| Name | Required | Description | Default |
|---|---|---|---|
| dateFrom | No | Start date for search (YYYY-MM-DD format) | |
| dateTo | No | End date for search (YYYY-MM-DD format) | |
| fromEmail | No | Filter by sender email address | |
| limit | No | Maximum number of messages to retrieve | |
| mailbox | No | Mailbox name (default: INBOX) | INBOX |
| query | No | Search query text (searches in subject, from, body) | |
| unreadOnly | No | Search only unread messages |
Implementation Reference
- src/index.ts:585-619 (handler)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, }, }, }, },
- src/types/config.ts:41-49 (schema)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); }); }); }); }); }