Skip to main content
Glama
Soundhannes

IMAP MCP Server

by Soundhannes

download_attachment

Retrieve email attachment content in base64 format from IMAP mailboxes by specifying the email UID and attachment index.

Instructions

Download attachment content (base64)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
uidYesEmail UID
attachmentIndexYesAttachment index (0-based)
mailboxNoMailbox name (default: current)

Implementation Reference

  • The actual implementation of the download_attachment tool in the IMAP client class.
    def download_attachment(
        self, uid: int, attachment_index: int, mailbox: Optional[str] = None
    ) -> tuple[str, str, bytes]:
        """Download attachment content (returns filename, content_type, base64 data)."""
        import base64
    
        self._ensure_connected()
        if mailbox:
            self.select_mailbox(mailbox)
    
        data = self.client.fetch([uid], ["BODY[]"])
        if uid not in data:
            raise ValueError(f"Email with UID {uid} not found")
    
        raw_body = data[uid].get(b"BODY[]", b"")
        msg = email.message_from_bytes(raw_body)
    
        index = 0
        for part in msg.walk():
            content_disposition = str(part.get("Content-Disposition", ""))
            if "attachment" in content_disposition or "inline" in content_disposition:
                filename = part.get_filename()
                if filename:
                    if index == attachment_index:
                        filename = self._decode_header(filename)
                        content_type = part.get_content_type()
                        payload = part.get_payload(decode=True)
                        return filename, content_type, base64.b64encode(payload)
                    index += 1
    
        raise ValueError(f"Attachment at index {attachment_index} not found")
    
    def get_thread(self, uid: int, mailbox: Optional[str] = None) -> list[EmailHeader]:
        """Get email thread/conversation."""
        self._ensure_connected()
        if mailbox:
            self.select_mailbox(mailbox)
    
        # Get the email to find its references
        email_data = self.get_email(uid, mailbox)
        message_id = email_data.header.message_id
        subject = email_data.header.subject
    
        # Search for related emails by subject (simplified thread detection)
        if subject:
            # Remove Re: Fwd: etc. prefixes
            clean_subject = subject
  • The definition and registration of the download_attachment tool in the server script.
    make_tool(
        "download_attachment",
        "Download attachment content (base64)",
        {
            "uid": {"type": "number", "description": "Email UID"},
            "attachmentIndex": {"type": "number", "description": "Attachment index (0-based)"},
            "mailbox": {"type": "string", "description": "Mailbox name (default: current)"},
        },
        ["uid", "attachmentIndex"],
    ),
  • The tool handler logic in server.py that calls the imap_client implementation.
    elif name == "download_attachment":
        filename, content_type, data = imap_client.download_attachment(
            uid=args["uid"],
            attachment_index=args["attachmentIndex"],
            mailbox=args.get("mailbox"),
        )
        return {
Behavior2/5

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

With no annotations, the description carries full burden but provides minimal behavioral insight. It mentions the output format (base64) but omits critical details: whether it's a read-only operation, potential side effects (e.g., caching), error conditions, or performance implications. This is inadequate for a tool that likely involves data retrieval and encoding.

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 extremely concise—a single phrase that front-loads the core purpose without unnecessary words. Every element ('Download', 'attachment content', 'base64') earns its place by conveying essential information efficiently, making it easy to parse quickly.

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

Completeness2/5

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

Given no annotations and no output schema, the description is incomplete. It lacks details on return values (beyond 'base64' hint), error handling, authentication needs, or operational constraints. For a tool with 3 parameters and potential complexity in email systems, this minimal description fails to provide sufficient context for safe and effective 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 parameters are well-documented in the schema. The description adds no additional semantic context about parameters (e.g., explaining 'attachmentIndex' relevance or 'mailbox' defaults). It meets the baseline of 3 since the schema handles documentation, but doesn't enhance understanding beyond that.

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 action ('Download') and resource ('attachment content'), specifying the format ('base64'). It distinguishes from siblings like 'get_attachments' (likely listing metadata) by focusing on content retrieval. However, it doesn't explicitly contrast with all potential alternatives, keeping it at 4 rather than 5.

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?

No guidance is provided on when to use this tool versus alternatives like 'get_attachments' or 'get_email_body'. The description lacks context about prerequisites (e.g., needing email access) or exclusions, offering only basic functional intent without usage directives.

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/Soundhannes/IMAP-MCP'

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