NAME

mcp-imap - inspect and manage one IMAP account through MCP

SYNOPSIS

mcp-imap [OPTION]...
mcp-imap [OPTION]... login [method password|oauth2] [server HOST]
    [user USER] [tls connect|starttls|none] [port PORT] [oauth-KEY VALUE]...
mcp-imap [OPTION]... providers [SEARCH]

DESCRIPTION

Each --name selects one IMAP account and an independent MCP permission profile. Configure the account with login, then run the MCP server with --stdio, --connect, or an HTTP listener. Login takes passwords from the controlling terminal without echo, never from command-line arguments or MCP tools.

The account is stored as imap-NAME.ini under $XDG_CONFIG_HOME/anyevent-mcp or ~/.config/anyevent-mcp, mode 0600. Password data is Base64 in that private file, not encrypted. Protect the file like a password. Repeating login replaces the saved password after a successful connection. For login method oauth2, it prints a browser authorization URL and accepts the resulting redirect URL from the terminal, without listening on a callback port. The private file stores the refresh token; later IMAP sessions refresh access tokens automatically. Neither passwords nor OAuth tokens are accepted as command-line values. Unencrypted IMAP authentication is available only when explicitly selected with login tls none. This exposes credentials and message contents on the connection.

providers searches Thunderbird's ISPDB domain index and OAuth provider definitions. With no argument it lists known domains. A domain, substring, or full email address selects a provider and looks up provider-hosted HTTPS autoconfig (preferred) or Thunderbird's ISPDB as a fallback. It prints shell-quoted password login commands for supported IMAP/TLS alternatives, provider setup instructions, and OAuth commands if a matching public OAuth registration is known. An email address fills in the username. The commands are NOT executed. Thunderbird's client registrations may not be usable by unrelated applications. OAuth authorization requests need registered redirect URIs and may require provider-specific optional oauth-auth-NAME VALUE arguments (e.g. oauth-auth-access_type offline).

See "LOGIN KEYS" for an individually documented list of accepted connection and OAuth2 settings, including their defaults. Successful OAuth2 login requires a refresh token; provider-specific offline access parameters may be necessary. Authorization is human-initiated only, never exposed through an MCP tool. After authorization, the browser will normally show an error page because no server is listening on the loopback redirect URI. This is expected; copy the full redirect URL from the address bar anyway. Port 1 works with Chromium's error-page behavior, but provider redirect registrations and other browsers may differ.

IMAP runs in a separate persistent synchronous worker, so an IMAP command does not block the MCP event loop. One request at a time is processed by the worker. While it is blocked, the frontend can send 30-second elapsed-time progress notifications to clients that supply a progress token. These report frontend liveness, not progress within Dovecot. A dropped connection during a write can leave an unknown outcome; do not blindly retry such writes. An idle connection is kept alive with IMAP NOOP (250-second default). A failed keepalive (including a 30-second timeout) closes the connection until the next tool call, which reconnects and authenticates. A connection lost during an operation is not retried automatically.

When spawned as a multibroker stdio child, the server can exit after one hour without MCP requests, discarding any SORT snapshot. The caller must create a new snapshot if needed. Directly connected clients and HTTP listeners are unaffected.

Message references consist of mailbox, UIDVALIDITY and UID. Read operations use BODY.PEEK, never mark messages Seen. Deleted flags do not automatically expunge. EXPUNGE is explicit. Selecting another mailbox or logging out does not expunge. Search is bounded by UID windows, potentially returning a partial/empty page with a continuation cursor when matches are sparse. MCP mail processing requires Encode::MIME::Header for RFC 2047 subject and address display-name decoding. Additional character encodings are supported when optional Encode extensions (Encode::HanExtra, Encode::JIS2K, Encode::EUCJPASCII) are installed; the IMAP worker loads available extensions without requiring them. An unsupported charset yields a decoding error, not a silent empty message.

LOGIN KEYS

login accepts KEY VALUE pairs (without leading dashes). Values not supplied are inherited from the saved account when available. Changing authentication methods retains only the connection settings. Passwords and OAuth tokens are never accepted on the command line.

Connection and authentication

method password|oauth2

Login method. Defaults to the saved method, or password for a new account.

server HOST

IMAP hostname. Read from standard input if unset.

user USER

IMAP username, often a complete email address. Read from standard input if unset.

tls connect|starttls|none

connect (default) negotiates TLS immediately, typically on port 993. starttls upgrades an initially cleartext connection before authenticating, typically on port 143. none skips TLS entirely, typically on port 143: the username, password or OAuth token, and mail contents travel unencrypted. Use none only when the connection is otherwise protected, such as by a trusted local transport. Some IMAP servers advertise LOGINDISABLED before TLS negotiation; if they also offer no supported SASL authentication mechanism, tls none cannot authenticate until the server's policy permits cleartext authentication.

port PORT

IMAP TCP port, default 993 for connect, and 143 for starttls or none. Changing tls without specifying port selects that TLS mode's default port.

OAuth2 keys (method oauth2)

oauth-client-id ID

OAuth client ID registered with the provider (required).

oauth-authorization-endpoint URL

Provider authorization endpoint, HTTPS (required).

oauth-token-endpoint URL

Provider token endpoint, HTTPS (required).

oauth-scope TEXT

Space-separated OAuth scopes (required).

oauth-redirect-uri URI

Registered callback URI, HTTPS or HTTP loopback without query or fragment (required). The program does not listen on this URI; copy the full URL from the browser address bar after authorization.

oauth-client-secret SECRET

Optional client secret for confidential OAuth clients. Supplied as a login setting, not as an IMAP password.

oauth-client-auth none|client_secret_post|client_secret_basic

OAuth token-endpoint authentication. Default none without a client secret, otherwise client_secret_post. Non-none modes require oauth-client-secret.

oauth-pkce 0|1

Use PKCE S256, enabled by default (1). Disable (0) only if the provider registration does not support PKCE.

oauth-sasl xoauth2|oauthbearer

IMAP SASL mechanism for OAuth, default xoauth2.

oauth-auth-NAME VALUE

Add a provider-specific authorization query parameter, for example oauth-auth-access_type offline to request a refresh token. NAME consists of ASCII letters, digits or underscores. Protocol-defined parameters such as client_id, redirect_uri and state cannot be overridden.

FIRST USE

Discover your provider's settings before logging in:

mcp-imap --name personal providers alice@example.net

Replace the example address. This reports possible IMAP settings and login commands; provider-specific OAuth client registrations may be restricted to their original application. For a password-based provider, for example:

mcp-imap --name personal login method password \
   server imap.example.net user alice@example.net tls connect port 993

The password is read interactively. For OAuth2, run login method oauth2 with your provider-approved client ID, authorization/token endpoints, scope and redirect URI. For example, the structure of such a command (the provider URLs and registration below are placeholders) is:

mcp-imap --name personal login method oauth2 \
   server imap.example.net user alice@example.net tls connect port 993 \
   oauth-client-id REGISTERED_CLIENT_ID \
   oauth-authorization-endpoint https://login.example.net/authorize \
   oauth-token-endpoint https://login.example.net/token \
   oauth-scope MAIL_SCOPE \
   oauth-redirect-uri http://127.0.0.1:1

The redirect URI must be allowed by the OAuth client registration. Some providers additionally require oauth-auth-access_type offline or other authorization parameters to issue a refresh token. After opening the printed authorization URL, authorize the intended account and paste the full redirect URL from the browser's address bar even if the browser reports an unreachable loopback page. Login checks IMAP authentication before saving the account.

Then configure your MCP client to start:

mcp-imap --name personal --stdio

Or expose it through a multibroker:

mcp-multibroker --stdio mail --- mcp-imap --name personal --stdio ---

Ask the assistant:

List my subscribed mailboxes, then show the ten newest subjects
and senders in INBOX. Do not modify flags or move messages.

For example, to subscribe a folder called Receipts, invoke mailbox with {"operation":"subscribe","mailbox":"Receipts"}, then call lsub to see subscribed folders. Read operations request read permission; changing subscriptions requires manage. A mailbox-specific permission prompt can allow just that mailbox or all mailboxes.

To let a separately started server join an existing multibroker with an HTTP/extension listener, run:

mcp-imap --name personal --connect http://127.0.0.1:31740/TOKEN/mail

Replace TOKEN with the token obtained using the multibroker's --print-url. Use https:// with a trusted, matching certificate.

The lsub tool lists subscribed mailboxes; mailboxes lists all visible mailboxes. Subscriptions affect folder selection in clients, not message delivery or permissions. See "Read and organize mail" in AnyEvent::MCP::Intro for search and safety examples.

TOOLS

mailboxes

List visible mailboxes. The mailboxes result contains triples of [attributes, hierarchy_separator, name]. One entry might be [["\\HasNoChildren"], "/", "INBOX"]. Mailboxes marked \\Noselect are containers, not selectable message folders.

lsub

List subscribed mailboxes (IMAP LSUB). Uses the same result format as mailboxes.

messages

List at most 1000 message summaries (default 100), newest UID first. Optional SEARCH filter, summary fields, header names and UIDVALIDITY-aware cursor. Alternatively pass uids (1..1000) and uidvalidity to retrieve those exact summaries in requested order, without SEARCH. missing_uids reports vanished messages; do not combine explicit UIDs with cursor, filter or limit. RFC 2047 encoded words in subject and address display fields are decoded for display; explicitly requested arbitrary headers remain unchanged. Searches at most 20000 UID values per call, not 20000 existing messages. Sparse mailboxes may return an empty page with incomplete: true. Always continue with cursor: next_cursor when next_cursor is present, preserving the original filter. Repeating without the cursor rescans the same UID interval. more is true whenever continuation is needed, even if no further match is guaranteed; false means the search is exhausted. incomplete specifically means the scan budget was reached. For targeted whole-mailbox searches, use threads with a selective filter.

filter combines its keys with AND. Text search keys are from, to, cc, bcc, subject, body and text (headers and body). header maps header names to search strings. Date keys are since, before, on, sent_since, sent_before and sent_on, with dates as D-Mon-YYYY. since/before/on use the IMAP internal date; sent_* keys use the message's Date header. larger and smaller filter by message size. Boolean flags include seen, unseen, answered, unanswered, flagged, unflagged, deleted, undeleted, draft, undraft, recent, old and new. all and any contain arrays of nested filters (AND and OR); not contains one nested filter. For example:

{
  "mailbox": "INBOX",
  "limit": 20,
  "filter": {
    "since": "1-Nov-2026",
    "any": [
      {"from": "alice@example.net"},
      {"subject": "invoice", "body": "overdue"}
    ],
    "not": {"flagged": true}
  }
}

The example finds messages with an internal date since November 1 from Alice or containing both invoice in the subject and overdue in the body, excluding flagged mail. Filter nesting and size are bounded; search values are explicitly quoted as IMAP arguments, never interpolated into raw SEARCH commands.

threads

Use UID THREAD ORDEREDSUBJECT UTF-8 (RFC 5256) on all messages in the selected mailbox, or restrict candidates with filter (the same SEARCH criteria as messages) and/or an inclusive uid_range such as 1:5000. Returns the server's nested UID thread arrays, ordered by the oldest sent Date header within each subject group. Unlike messages, it searches the entire selected mailbox without the 20000-UID scan cap. Useful for targeted lookups and uncertain MOVE destination verification; fetch matching message details with messages using explicit uids and uidvalidity. A UID range is not a message count; gaps in assigned UIDs reduce the matching population. Optional uidvalidity rejects references from a different mailbox generation. The server must advertise THREAD=ORDEREDSUBJECT. This command does not fetch message summaries or mark mail as Seen. Thread results are not paginated: the entire matching population is threaded and returned, potentially expensive on large mailboxes. Restrict with SEARCH criteria (e.g. before) or uid_range when appropriate.

sort_create

Run UID SORT (SUBJECT DATE) UTF-8 (RFC 5256) once, optionally with the same filter as messages. Retain the complete ordered UID array as one immutable snapshot in the worker; replace any previous snapshot only after a successful sort. Return a random snapshot_id, uidvalidity, count, and the first page (default 100, maximum 1000 UIDs). Subject groups are alphabetical, with messages sorted by sent date inside each group, not oldest group first. The sort covers the entire matching mailbox and may be expensive.

sort_page

Retrieve a page from the current SORT snapshot using snapshot_id, mailbox, zero-based offset and limit (default 100, maximum 1000). Returns uids and next_offset, or null when exhausted. The page is not recomputed when mail arrives, moves or disappears; fetch the returned UIDs through messages with uidvalidity and tolerate missing_uids. A mailbox UIDVALIDITY change, replaced snapshot or worker restart fails clearly. No disk persistence or automatic reconstruction.

sort_discard

Release the current SORT snapshot using its snapshot_id and mailbox. Only one snapshot exists per worker; it is also discarded at worker exit. These snapshot tools are read-only as far as IMAP messages are concerned.

previews

Fetch decoded text previews for 1..25 selected UIDs (uidvalidity required). Uses bounded BODY.PEEK without setting Seen; max_bytes defaults to 2048 and is capped at 4096 raw bytes per message. Returns selected MIME part, content type, text and truncation status, or an individual error. Prefers text/plain when useful; falls back to text/html if plain text is absent or mostly a stub. HTML is converted to plain text while preserving link URLs. When present, attachments lists MIME part numbers, types, filenames, transfer-encoded sizes in octets, and dispositions. Includes inline non-text parts; uses the already-fetched BODYSTRUCTURE without downloading attachments. Needs HTML::Parser only when HTML text is selected. This is approximate triage text, not full MIME rendering. Use message/part for complete mail.

message

Read ENVELOPE, flags, dates, size and MIME BODYSTRUCTURE for a UID. RFC 2047 encoded words in ENVELOPE subjects and display names are decoded. Use the uidvalidity and uid returned by messages for the selected mailbox. For example, if the current UIDVALIDITY is 13 and the UID is 42:

{"mailbox": "INBOX", "uidvalidity": "13", "uid": 42}
part

Read a MIME part using BODY.PEEK with a byte ceiling. Returns Base64 raw transferred bytes; decode_text additionally decodes complete text parts using MIME transfer encoding and charset.

raw

Read raw RFC 5322 message bytes (bounded, Base64). Never sets Seen.

flags

Add/remove a set of IMAP flags, including Deleted (but never expunge).

copy, move

Copy or move named UIDs. MOVE requires server MOVE capability and has no unsafe emulation.

append

APPEND a Base64-encoded RFC 5322 message up to 1 MiB. Use CRLF line endings. Reject unescaped mbox From_ separator-like lines in the raw message unless --allow-mbox-from is set. Refusal identifies the raw line number and explains the mboxo hazard. This uploads bytes unchanged; it is not an SMTP send operation.

expunge

Permanently expunge explicitly named deleted UIDs when UIDPLUS is available, or all Deleted messages in the selected mailbox when uids is omitted. Never fall back from UID EXPUNGE to whole-mailbox EXPUNGE.

mailbox

Create, rename, delete, subscribe or unsubscribe a mailbox. Deletion first checks STATUS MESSAGES and refuses mailboxes containing any messages, including messages flagged \Deleted. Expunge those messages first, or use force to bypass the check. The check is not atomic with IMAP DELETE.

PERMISSIONS

The independent profile is imap-NAME, with read, modify, manage and expunge actions. Each tool checks permission before network activity. Mailbox-specific operations can be approved for one mailbox or all mailboxes; mailboxes and lsub list folders without selecting a mailbox. This worker is NOT filesystem- or network-sandboxed; permissions authorize operations, not OS-level confinement.

OPTIONS

Shared switches are documented in "COMMON COMMAND-LINE OPTIONS" in AnyEvent::MCP::Server::Simple. The --ask switch is shared but has the following permission behavior; the other switches below are specific to mcp-imap.

--ask MODE

Choose where permission prompts appear: helper (default when run independently) uses a local helper; tty and yad force those local interfaces without fallback. mcp delegates prompts to the MCP client; auto uses client elicitation when advertised and otherwise falls back to the helper. none denies unmatched requests without prompting. A server spawned by a multibroker defaults to mcp so the broker can present its prompts.

--keepalive SECONDS

Send an IMAP NOOP after this many seconds without a tool call, to keep the connection alive across NAT and server idle timeouts. Default 250. Set to 0 to disable idle keepalives. The next tool call reconnects automatically if the IMAP connection has closed.

--allow-mbox-from

Allow APPEND messages with unescaped mbox From_ separator-like lines. Unsafe with mboxo servers which fail to escape these lines. Off by default; can only be enabled by the server operator, not through an MCP tool.

--provider-file FILE

Use FILE as a local Thunderbird OAuth JavaScript source with the providers command. Invalid for normal server startup or login.

--ispdb-file FILE

Use FILE as a local Thunderbird autoconfiguration XML source with the providers command. Invalid for normal server startup or login.