waitForReply
Waits for email replies in a specified folder within a set timeout period, enabling automated response monitoring and follow-up workflows.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| folder | No | INBOX | |
| timeout | No |
Implementation Reference
- src/tools/mail.ts:426-493 (handler)The MCP tool handler for 'waitForReply'. It invokes mailService.waitForNewReply, handles unread warnings by listing recent unread mails, timeout messages, and formats new reply details including sender, subject, date, UID, and body.async ({ folder, timeout }) => { try { const result = await this.mailService.waitForNewReply(folder, timeout); // 如果是未读邮件警告 if (result && typeof result === 'object' && 'type' in result && result.type === 'unread_warning') { let warningText = `⚠️ 检测到${result.mails.length}封最近5分钟内的未读邮件。\n`; warningText += `请先处理(阅读或回复)这些邮件,再继续等待新回复:\n\n`; result.mails.forEach((mail, index) => { const fromStr = mail.from.map(f => f.name ? `${f.name} <${f.address}>` : f.address).join(', '); warningText += `${index + 1}. 主题: ${mail.subject}\n`; warningText += ` 发件人: ${fromStr}\n`; warningText += ` 时间: ${mail.date.toLocaleString()}\n`; warningText += ` UID: ${mail.uid}\n\n`; }); warningText += `提示:\n`; warningText += `1. 使用 markAsRead 工具将邮件标记为已读\n`; warningText += `2. 使用 getEmailDetail 工具查看邮件详情\n`; warningText += `3. 处理完这些邮件后,再次调用 waitForReply 工具等待新回复\n`; return { content: [ { type: "text", text: warningText } ] }; } // 如果超时 if (!result) { return { content: [ { type: "text", text: `等待邮件回复超时(${timeout / 1000}秒)` } ] }; } // 收到新邮件 const email = result as MailItem; // 添加类型断言 const fromStr = email.from.map(f => f.name ? `${f.name} <${f.address}>` : f.address).join(', '); const date = email.date.toLocaleString(); const status = email.isRead ? '已读' : '未读'; const attachmentInfo = email.hasAttachments ? '📎' : ''; let resultText = `收到新邮件!\n\n`; resultText += `[${status}] ${attachmentInfo} 来自: ${fromStr}\n`; resultText += `主题: ${email.subject}\n`; resultText += `时间: ${date}\n`; resultText += `UID: ${email.uid}\n\n`; if (email.textBody) { resultText += `内容:\n${email.textBody}\n\n`; } return { content: [ { type: "text", text: resultText } ] }; } catch (error) { return { content: [ { type: "text", text: `等待邮件回复时发生错误: ${error instanceof Error ? error.message : String(error)}` } ] }; } }
- src/tools/mail.ts:422-425 (schema)Zod input schema for the waitForReply tool: optional folder (default 'INBOX') and timeout in milliseconds (default 3 hours).{ folder: z.string().default('INBOX'), timeout: z.number().default(3 * 60 * 60 * 1000) },
- src/tools/mail.ts:420-494 (registration)Registration of the waitForReply tool on the MCP server within the registerReceivingTools method.this.server.tool( "waitForReply", { folder: z.string().default('INBOX'), timeout: z.number().default(3 * 60 * 60 * 1000) }, async ({ folder, timeout }) => { try { const result = await this.mailService.waitForNewReply(folder, timeout); // 如果是未读邮件警告 if (result && typeof result === 'object' && 'type' in result && result.type === 'unread_warning') { let warningText = `⚠️ 检测到${result.mails.length}封最近5分钟内的未读邮件。\n`; warningText += `请先处理(阅读或回复)这些邮件,再继续等待新回复:\n\n`; result.mails.forEach((mail, index) => { const fromStr = mail.from.map(f => f.name ? `${f.name} <${f.address}>` : f.address).join(', '); warningText += `${index + 1}. 主题: ${mail.subject}\n`; warningText += ` 发件人: ${fromStr}\n`; warningText += ` 时间: ${mail.date.toLocaleString()}\n`; warningText += ` UID: ${mail.uid}\n\n`; }); warningText += `提示:\n`; warningText += `1. 使用 markAsRead 工具将邮件标记为已读\n`; warningText += `2. 使用 getEmailDetail 工具查看邮件详情\n`; warningText += `3. 处理完这些邮件后,再次调用 waitForReply 工具等待新回复\n`; return { content: [ { type: "text", text: warningText } ] }; } // 如果超时 if (!result) { return { content: [ { type: "text", text: `等待邮件回复超时(${timeout / 1000}秒)` } ] }; } // 收到新邮件 const email = result as MailItem; // 添加类型断言 const fromStr = email.from.map(f => f.name ? `${f.name} <${f.address}>` : f.address).join(', '); const date = email.date.toLocaleString(); const status = email.isRead ? '已读' : '未读'; const attachmentInfo = email.hasAttachments ? '📎' : ''; let resultText = `收到新邮件!\n\n`; resultText += `[${status}] ${attachmentInfo} 来自: ${fromStr}\n`; resultText += `主题: ${email.subject}\n`; resultText += `时间: ${date}\n`; resultText += `UID: ${email.uid}\n\n`; if (email.textBody) { resultText += `内容:\n${email.textBody}\n\n`; } return { content: [ { type: "text", text: resultText } ] }; } catch (error) { return { content: [ { type: "text", text: `等待邮件回复时发生错误: ${error instanceof Error ? error.message : String(error)}` } ] }; } } );
- src/tools/mail-service.ts:1135-1234 (helper)Core helper method in MailService that implements the waiting logic: first warns about recent unread mails, then polls IMAP mailbox for new messages every 5 seconds until timeout or new mail arrives.async waitForNewReply(folder: string = 'INBOX', timeout: number = 3 * 60 * 60 * 1000): Promise<MailItem | null | { type: 'unread_warning'; mails: MailItem[] }> { await this.connectImap(); // 检查5分钟内的未读邮件 const fiveMinutesAgo = new Date(Date.now() - 5 * 60 * 1000); const existingMails = await this.searchMails({ folder, limit: 5, readStatus: 'unread', fromDate: fiveMinutesAgo }); // 如果有5分钟内的未读邮件,返回特殊状态 if (existingMails.length > 0) { console.log(`[waitForNewReply] 发现${existingMails.length}封最近5分钟内的未读邮件,需要先处理`); return { type: 'unread_warning', mails: existingMails }; } return new Promise((resolve, reject) => { let timeoutId: NodeJS.Timeout; let isResolved = false; let initialCount = 0; let checkInterval: NodeJS.Timeout; // 清理函数 const cleanup = () => { if (timeoutId) { clearTimeout(timeoutId); } if (checkInterval) { clearInterval(checkInterval); } }; // 设置超时 timeoutId = setTimeout(() => { if (!isResolved) { isResolved = true; cleanup(); resolve(null); } }, timeout); // 获取初始邮件数量并开始轮询 this.imapClient.openBox(folder, false, (err, mailbox) => { if (err) { cleanup(); reject(err); return; } // 记录初始邮件数量 initialCount = mailbox.messages.total; console.log(`[waitForNewReply] 初始邮件数量: ${initialCount},开始等待新邮件回复...`); // 每5秒检查一次新邮件 checkInterval = setInterval(async () => { if (isResolved) return; try { // 重新打开邮箱以获取最新状态 this.imapClient.openBox(folder, false, async (err, mailbox) => { if (err || isResolved) return; const currentCount = mailbox.messages.total; console.log(`[waitForNewReply] 当前邮件数量: ${currentCount},初始数量: ${initialCount}`); if (currentCount > initialCount) { // 有新邮件,获取最新的邮件 try { const messages = await this.searchMails({ folder, limit: 1 }); if (messages.length > 0 && !isResolved) { // 获取完整的邮件内容 const fullMail = await this.getMailDetail(messages[0].uid, folder); if (fullMail) { console.log(`[waitForNewReply] 收到新邮件回复,主题: "${fullMail.subject}"`); isResolved = true; cleanup(); resolve(fullMail); } } } catch (error) { console.error('[waitForNewReply] 获取新邮件失败:', error); } } }); } catch (error) { console.error('[waitForNewReply] 检查新邮件时出错:', error); } }, 5000); }); }); }