Skip to main content
Glama
shuakami

Mail MCP Tool

by shuakami

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
NameRequiredDescriptionDefault
folderNoINBOX
timeoutNo

Implementation Reference

  • 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)}` }
          ]
        };
      }
    }
  • 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)
    },
  • 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)}` }
            ]
          };
        }
      }
    );
  • 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);
        });
      });
    }
Behavior1/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Tool has no description.

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

Conciseness1/5

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

Tool has no description.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness1/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Tool has no description.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters1/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Tool has no description.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose1/5

Does the description clearly state what the tool does and how it differs from similar tools?

Tool has no description.

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

Usage Guidelines1/5

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

Tool has no description.

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/shuakami/mcp-mail'

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