Skip to main content
Glama
Racimy

iMail-mcp

auto_organize

Automatically organize emails by moving them to specific mailboxes based on sender or subject keyword rules you define.

Instructions

Automatically organize emails based on rules (sender, subject keywords, etc.)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
dryRunNoIf true, only shows what would be organized without moving emails
rulesYesArray of organization rules
sourceMailboxNoSource mailbox to organize (default: INBOX)INBOX

Implementation Reference

  • Core handler function that implements the auto_organize tool logic: fetches messages from source mailbox, matches them against provided rules based on sender and subject, optionally moves them to destination mailboxes, supports dry-run mode, and returns detailed results.
    async autoOrganize(
      rules: OrganizationRule[],
      sourceMailbox: string = 'INBOX',
      dryRun: boolean = false
    ): Promise<{
      status: string;
      message: string;
      results: Array<{
        rule: string;
        matchedMessages: number;
        moved: boolean;
        messages?: Array<{
          id: string;
          from: string;
          subject: string;
          destinationMailbox: string;
        }>;
      }>;
    }> {
      try {
        const messages = await this.getMessages(sourceMailbox, 100);
        const results: Array<{
          rule: string;
          matchedMessages: number;
          moved: boolean;
          messages?: Array<{
            id: string;
            from: string;
            subject: string;
            destinationMailbox: string;
          }>;
        }> = [];
    
        for (const rule of rules) {
          const matchedMessages: Array<{
            id: string;
            from: string;
            subject: string;
            destinationMailbox: string;
          }> = [];
    
          for (const message of messages) {
            let matches = false;
    
            if (rule.condition.fromContains) {
              matches =
                matches ||
                message.from
                  .toLowerCase()
                  .includes(rule.condition.fromContains.toLowerCase());
            }
    
            if (rule.condition.subjectContains) {
              matches =
                matches ||
                message.subject
                  .toLowerCase()
                  .includes(rule.condition.subjectContains.toLowerCase());
            }
    
            if (matches) {
              matchedMessages.push({
                id: message.id,
                from: message.from,
                subject: message.subject,
                destinationMailbox: rule.action.moveToMailbox,
              });
            }
          }
    
          if (matchedMessages.length > 0) {
            let moved = false;
    
            if (!dryRun) {
              try {
                const messageIds = matchedMessages.map((m) => m.id);
                await this.moveMessages(
                  messageIds,
                  sourceMailbox,
                  rule.action.moveToMailbox
                );
                moved = true;
              } catch (moveError) {
                console.error(
                  `Failed to move messages for rule '${rule.name}':`,
                  moveError
                );
              }
            }
    
            results.push({
              rule: rule.name,
              matchedMessages: matchedMessages.length,
              moved: !dryRun && moved,
              messages: matchedMessages,
            });
          } else {
            results.push({
              rule: rule.name,
              matchedMessages: 0,
              moved: false,
            });
          }
        }
    
        const totalMatched = results.reduce(
          (sum, result) => sum + result.matchedMessages,
          0
        );
    
        return {
          status: 'success',
          message: dryRun
            ? `Dry run completed. Found ${totalMatched} messages matching organization rules`
            : `Organization completed. Processed ${totalMatched} messages`,
          results,
        };
      } catch (error) {
        return {
          status: 'error',
          message: `Failed to organize emails: ${error instanceof Error ? error.message : String(error)}`,
          results: [],
        };
      }
    }
  • MCP server request handler for the 'auto_organize' tool, validates configuration, extracts parameters, delegates to mailClient.autoOrganize, and formats the response.
    case 'auto_organize': {
      if (!mailClient) {
        throw new McpError(
          ErrorCode.InvalidRequest,
          'iCloud Mail not configured. Please set ICLOUD_EMAIL and ICLOUD_APP_PASSWORD environment variables.'
        );
      }
    
      const rules = args?.rules as Array<{
        name: string;
        condition: {
          fromContains?: string;
          subjectContains?: string;
        };
        action: {
          moveToMailbox: string;
        };
      }>;
      const sourceMailbox = (args?.sourceMailbox as string) || 'INBOX';
      const dryRun = (args?.dryRun as boolean) || false;
    
      const result = await mailClient.autoOrganize(
        rules,
        sourceMailbox,
        dryRun
      );
    
      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify(result, null, 2),
          },
        ],
      };
    }
  • src/index.ts:314-373 (registration)
    Registration of the 'auto_organize' tool in the MCP tools array, including detailed input schema and description.
    {
      name: 'auto_organize',
      description:
        'Automatically organize emails based on rules (sender, subject keywords, etc.)',
      inputSchema: {
        type: 'object',
        properties: {
          rules: {
            type: 'array',
            items: {
              type: 'object',
              properties: {
                name: {
                  type: 'string',
                  description: 'Rule name',
                },
                condition: {
                  type: 'object',
                  properties: {
                    fromContains: {
                      type: 'string',
                      description: 'Move emails if sender contains this text',
                    },
                    subjectContains: {
                      type: 'string',
                      description:
                        'Move emails if subject contains this text',
                    },
                  },
                },
                action: {
                  type: 'object',
                  properties: {
                    moveToMailbox: {
                      type: 'string',
                      description: 'Mailbox to move matching emails to',
                    },
                  },
                  required: ['moveToMailbox'],
                },
              },
              required: ['name', 'condition', 'action'],
            },
            description: 'Array of organization rules',
          },
          sourceMailbox: {
            type: 'string',
            description: 'Source mailbox to organize (default: INBOX)',
            default: 'INBOX',
          },
          dryRun: {
            type: 'boolean',
            description:
              'If true, only shows what would be organized without moving emails',
            default: false,
          },
        },
        required: ['rules'],
      },
    },
  • TypeScript interface defining the OrganizationRule structure used for input validation and typing in the auto_organize tool.
    export interface OrganizationRule {
      name: string;
      condition: {
        fromContains?: string;
        subjectContains?: string;
      };
      action: {
        moveToMailbox: string;
      };
    }
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions 'automatically organize' and hints at rules, but doesn't describe what 'organize' entails (e.g., moving emails, potential side effects), authentication needs, rate limits, or error handling. For a mutation tool with zero annotation coverage, this is a significant gap in transparency.

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 front-loads the core functionality ('Automatically organize emails') and adds essential detail ('based on rules...'). There's zero waste, and it's appropriately sized for the tool's complexity.

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

Completeness3/5

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

Given the tool's moderate complexity (3 parameters, mutation operation, no output schema, and no annotations), the description is minimally adequate. It covers the purpose but lacks behavioral details, usage context, and output expectations. It meets a basic threshold but has clear gaps for effective agent 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 already documents all parameters thoroughly. The description adds no additional meaning beyond what's in the schema (e.g., it doesn't explain rule interactions or organizational logic). Baseline 3 is appropriate when 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 tool's purpose: 'Automatically organize emails based on rules (sender, subject keywords, etc.)'. It specifies the verb ('organize'), resource ('emails'), and mechanism ('rules'), but doesn't explicitly differentiate it from sibling tools like 'move_messages' or 'set_flags' that might also organize emails in different ways.

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 prerequisites (e.g., existing mailboxes), compare to siblings like 'move_messages' for manual operations, or specify use cases like bulk automation versus single actions. Usage is implied but not articulated.

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