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
passwordfor 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.starttlsupgrades an initially cleartext connection before authenticating, typically on port 143.noneskips TLS entirely, typically on port 143: the username, password or OAuth token, and mail contents travel unencrypted. Usenoneonly when the connection is otherwise protected, such as by a trusted local transport. Some IMAP servers advertiseLOGINDISABLEDbefore TLS negotiation; if they also offer no supported SASL authentication mechanism,tls nonecannot authenticate until the server's policy permits cleartext authentication. port PORT-
IMAP TCP port, default 993 for
connect, and 143 forstarttlsornone. Changingtlswithout specifyingportselects that TLS mode's default port.
OAuth2 keys (method oauth2)
oauth-client-id ID-
OAuth client ID registered with the provider (required).
-
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
nonewithout a client secret, otherwiseclient_secret_post. Non-nonemodes requireoauth-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 offlineto request a refresh token. NAME consists of ASCII letters, digits or underscores. Protocol-defined parameters such asclient_id,redirect_uriandstatecannot 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
mailboxesresult contains triples of[attributes, hierarchy_separator, name]. One entry might be[["\\HasNoChildren"], "/", "INBOX"]. Mailboxes marked\\Noselectare 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) anduidvalidityto retrieve those exact summaries in requested order, without SEARCH.missing_uidsreports 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 withincomplete: true. Always continue withcursor: next_cursorwhennext_cursoris present, preserving the originalfilter. Repeating without the cursor rescans the same UID interval.moreis true whenever continuation is needed, even if no further match is guaranteed; false means the search is exhausted.incompletespecifically means the scan budget was reached. For targeted whole-mailbox searches, usethreadswith a selective filter.filtercombines its keys with AND. Text search keys arefrom,to,cc,bcc,subject,bodyandtext(headers and body).headermaps header names to search strings. Date keys aresince,before,on,sent_since,sent_beforeandsent_on, with dates asD-Mon-YYYY.since/before/onuse the IMAP internal date;sent_*keys use the message's Date header.largerandsmallerfilter by message size. Boolean flags includeseen,unseen,answered,unanswered,flagged,unflagged,deleted,undeleted,draft,undraft,recent,oldandnew.allandanycontain arrays of nested filters (AND and OR);notcontains 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 withfilter(the same SEARCH criteria asmessages) and/or an inclusiveuid_rangesuch as1:5000. Returns the server's nested UID thread arrays, ordered by the oldest sent Date header within each subject group. Unlikemessages, 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 withmessagesusing explicituidsanduidvalidity. A UID range is not a message count; gaps in assigned UIDs reduce the matching population. Optionaluidvalidityrejects references from a different mailbox generation. The server must advertiseTHREAD=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) oruid_rangewhen appropriate. - sort_create
-
Run
UID SORT (SUBJECT DATE) UTF-8(RFC 5256) once, optionally with the samefilterasmessages. Retain the complete ordered UID array as one immutable snapshot in the worker; replace any previous snapshot only after a successful sort. Return a randomsnapshot_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-basedoffsetandlimit(default 100, maximum 1000). Returnsuidsandnext_offset, or null when exhausted. The page is not recomputed when mail arrives, moves or disappears; fetch the returned UIDs throughmessageswithuidvalidityand toleratemissing_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_idandmailbox. 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 (
uidvalidityrequired). Uses boundedBODY.PEEKwithout setting Seen;max_bytesdefaults 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. Preferstext/plainwhen useful; falls back totext/htmlif plain text is absent or mostly a stub. HTML is converted to plain text while preserving link URLs. When present,attachmentslists 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. NeedsHTML::Parseronly when HTML text is selected. This is approximate triage text, not full MIME rendering. Usemessage/partfor 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
uidvalidityanduidreturned bymessagesfor 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_textadditionally 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-fromis 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
uidsis omitted. Never fall back from UID EXPUNGE to whole-mailbox EXPUNGE. - mailbox
-
Create, rename, delete, subscribe or unsubscribe a mailbox. Deletion first checks
STATUS MESSAGESand refuses mailboxes containing any messages, including messages flagged\Deleted. Expunge those messages first, or useforceto 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;ttyandyadforce those local interfaces without fallback.mcpdelegates prompts to the MCP client;autouses client elicitation when advertised and otherwise falls back to the helper.nonedenies unmatched requests without prompting. A server spawned by a multibroker defaults tomcpso 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
providerscommand. Invalid for normal server startup orlogin. - --ispdb-file FILE
-
Use FILE as a local Thunderbird autoconfiguration XML source with the
providerscommand. Invalid for normal server startup orlogin.