Skip to main content
Glama
adamzaidi

icloud-mcp

by adamzaidi

get_attachment

Download email attachments from iCloud Mail by specifying the email UID and attachment part ID, returning base64-encoded file content for integration with other tools.

Instructions

Download a specific attachment from an email. Returns the file content as base64-encoded data. Use list_attachments first to get the partId. Maximum 20 MB per request; use offset+length for larger files.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
uidYesEmail UID
partIdYesIMAP body part ID from list_attachments (e.g. "2", "1.2")
mailboxNoMailbox name (default INBOX)
offsetNoByte offset for paginated download (returns raw encoded bytes, not decoded)
lengthNoMax bytes to return for paginated download (default 20 MB)

Implementation Reference

  • The 'get_attachment' function is implemented in `lib/imap.js`. It fetches an email's body structure to locate the specified attachment part, then retrieves the raw data (optionally in chunks for large files), decodes it based on its transfer-encoding, and returns the data as base64.
    export async function getAttachment(uid, partId, mailbox = 'INBOX', offset = null, length = null, creds = null) {
      const client = createRateLimitedClient(creds);
      await client.connect();
      await client.mailboxOpen(mailbox);
    
      // First fetch bodyStructure to find the attachment and validate size
      const meta = await client.fetchOne(uid, { bodyStructure: true }, { uid: true });
      if (!meta) throw new Error(`Email UID ${uid} not found`);
    
      const attachments = meta.bodyStructure ? findAttachments(meta.bodyStructure) : [];
      const att = attachments.find(a => a.partId === partId);
      if (!att) throw new Error(`Part ID "${partId}" not found in email UID ${uid}. Use list_attachments to see available parts.`);
    
      const isPaginated = offset !== null || length !== null;
    
      if (!isPaginated && att.size > MAX_ATTACHMENT_BYTES) {
        await client.logout();
        return {
          error: `Attachment too large to download in one request (${Math.round(att.size / 1024 / 1024 * 10) / 10} MB). Use offset and length params to download in chunks (max ${MAX_ATTACHMENT_BYTES / 1024 / 1024} MB per request).`,
          filename: att.filename,
          mimeType: att.mimeType,
          size: att.size,
          totalSize: att.size
        };
      }
    
      // Build fetch spec
      let fetchSpec;
      if (isPaginated) {
        const start = offset ?? 0;
        const maxLength = length ?? MAX_ATTACHMENT_BYTES;
        fetchSpec = [{ key: partId, start, maxLength }];
      } else {
        fetchSpec = [partId];
      }
    
      // Fetch the raw body part bytes
      const rawChunks = [];
      for await (const msg of client.fetch({ uid }, { bodyParts: fetchSpec }, { uid: true })) {
        const buf = msg.bodyParts?.get(partId)
          ?? msg.bodyParts?.get(partId.toUpperCase())
          ?? msg.bodyParts?.get(partId.toLowerCase());
        if (buf) rawChunks.push(buf);
      }
      await client.logout();
    
      if (rawChunks.length === 0) throw new Error(`No data returned for part "${partId}" of UID ${uid}`);
    
      const raw = Buffer.concat(rawChunks);
    
      if (isPaginated) {
        // Paginated: return raw encoded bytes without transfer-encoding decode
        const fetchOffset = offset ?? 0;
        const actualLength = raw.length;
        const hasMore = att.size ? (fetchOffset + actualLength < att.size) : false;
        return {
          uid, partId,
          filename: att.filename,
          mimeType: att.mimeType,
          encoding: att.encoding,
          totalSize: att.size,
          offset: fetchOffset,
          length: actualLength,
          hasMore,
          data: raw.toString('base64'),
          dataEncoding: 'base64'
        };
      }
    
      // Full download: decode transfer encoding
      const encoding = att.encoding.toLowerCase();
      let decoded;
      if (encoding === 'base64') {
        decoded = Buffer.from(raw.toString('ascii').replace(/\s/g, ''), 'base64');
      } else if (encoding === 'quoted-printable') {
        const qp = raw.toString('binary').replace(/=\r?\n/g, '').replace(/=([0-9A-Fa-f]{2})/g, (_, h) => String.fromCharCode(parseInt(h, 16)));
        decoded = Buffer.from(qp, 'binary');
      } else {
        decoded = raw; // 7bit / 8bit / binary
      }
    
      return {
        uid,
        partId,
        filename: att.filename,
        mimeType: att.mimeType,
        size: decoded.length,
        encoding: att.encoding,
        data: decoded.toString('base64'),
        dataEncoding: 'base64'
      };
    }
Behavior4/5

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

With no annotations provided, the description carries the full burden and successfully discloses output format ('base64-encoded data'), size constraints ('Maximum 20 MB'), and pagination behavior. Lacks explicit read-only/safety declaration but 'download' implies non-destructive access.

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?

Four sentences with zero waste: purpose, return format, prerequisite workflow, and operational limits. Information is front-loaded and logically ordered.

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

Completeness4/5

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

Comprehensive given no annotations or output schema. Covers return value format, prerequisites, and pagination strategy. Would be a 5 with explicit mention of error handling or idempotency, but adequately complete for safe invocation.

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

Parameters4/5

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

Schema coverage is 100% (baseline 3). Description adds valuable semantic context: linking partId to the list_attachments prerequisite and explaining that offset+length work together for paginated downloads of large files.

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

Purpose5/5

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

The description opens with a specific verb ('Download') and resource ('attachment'), clearly distinguishing this from sibling 'list_attachments' by implying content retrieval vs. metadata listing.

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

Usage Guidelines5/5

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

Explicitly states the prerequisite workflow ('Use list_attachments first to get the partId') and provides clear pagination guidance for large files ('use offset+length for larger files'), covering both normal and edge-case usage.

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/adamzaidi/icloud-mcp'

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