bg-imapMCPSever
A read-only, TLS-only IMAP client you can point at your own mailbox — browse folders, list/search message headers, and read message bodies and attachment metadata without ever modifying mail.
check_connection— verify IMAP TLS connectivity and login (no credentials returned).list_folders— enumerate folders with server flags and hierarchy info.folder_status— total and unread counts for a folder without marking anything read.list_messages— newest messages by stable IMAP UID, with headers, seen flag and size; optional unread-only.search_messages— plain-text IMAP search (subject/from/to/body/text) returning matching headers and UIDs, with limit and unread-only options.read_message— fetch subject, sender, recipients, date, text body, attachment names/types/sizes, structured addresses, thread and list headers by folder + UID; never marks as read.Read-only by design:
EXAMINEandBODY.PEEKonly — no STORE/COPY/MOVE/EXPUNGE/APPEND; listings fetch only headers, flags, size and BODYSTRUCTURE.Robustness: opaque HMAC-signed cursors/checkpoints, stable error codes (
AUTHENTICATION_FAILED,UIDVALIDITY_CHANGED,IMAP_TIMEOUT, …), worker threads with up to 3 concurrent IMAP sessions, retry with backoff.Deployment: stdio locally or loopback-only Streamable HTTP; optional built-in single-owner OAuth 2.1 (PKCE, rotating refresh tokens) for remote connectors such as ChatGPT.
Beyond the schema: the README documents additional tools —
get_mailbox_inventory,search_messages_advanced(deterministic pagination),get_messages_batch,get_message_headers, andget_mailbox_changes(polling checkpoints).Caveat: mailbox content is untrusted and may contain prompt injection; the project is not independently security-audited.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@bg-imapMCPSever list my unread messages in the inbox"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
bg-imapMCPSever
Read-only MCP server for any standard IMAP-over-TLS mailbox, intended for personal hosting on Linux. No provider details, addresses, or passwords are hardcoded. Written in Python using the official MCP SDK v1 line (pinned to <2 for API stability).
Features
Original tools (unchanged arguments and results; new fields are additive):
check_connection: verify IMAP TLS/loginlist_folders: folder names (decoded from IMAP modified UTF-7), hierarchy delimiter and flagsfolder_status: total and unread counts plusUIDVALIDITYlist_messages: latest headers/UIDs with seen flag and size, optionally unread-onlysearch_messages: plain-text IMAP search intext(default),subject,from,toorbody, optionally unread-onlyread_message: subject, sender, recipients, date, text body, attachment names/types/sizes, plus structured addresses,reply_to,internal_date,in_reply_to,references,list_id,has_attachments,body_format; optionaluidvaliditycheck
Historical analysis and monitoring:
get_mailbox_inventory: every folder with server-reported special use (\Sent,\Trash, …), hierarchy, counts,UIDVALIDITY,UIDNEXT, and whether it belongs in a history analysis by default (not Trash/Junk/Drafts)search_messages_advanced: structured search (delivery-date range, sender, recipient, subject, text, seen, size) returning compact metadata with complete, deterministic pagination: the first page fixes an upper UID bound, eachnext_cursorcontinues from the last UID returned, and every matching message is returned exactly once with no hidden cap. Mail arriving mid-enumeration is excluded (use monitoring for it); expunged messages simply drop outget_messages_batch: up to 100 messages by UID with per-message status, decoded text bodies (HTML converted to text with link targets), attachment metadata and optional thread/list headers; bodies share an output budget and continue withbody_offsetget_message_headers: selected or all headers, plus normalized Message-ID/In-Reply-To/References/List-ID/List-Unsubscribe/Auto-Submitted/Precedence/Delivered-Toget_mailbox_changes: polling checkpoint API. A stateless checkpoint (folder, UIDVALIDITY, last delivered UID) returns newer messages oldest first; retrying a checkpoint is safe, it survives restarts, and a UIDVALIDITY change returnsresync_required. Deletions and flag changes are reported as unsupported (they need CONDSTORE/QRESYNC, which many servers lack)
Common properties:
Read-only by design:
EXAMINEandBODY.PEEKonly; no STORE/COPY/MOVE/EXPUNGE/APPEND. All tools carry the MCPreadOnlyHintannotation; the Dovecot test suite records every IMAP command to prove itCursors and checkpoints are opaque, HMAC-signed tokens (key in the state directory, mode 600); they contain no credentials
Errors start with a stable code:
AUTHENTICATION_FAILED,FOLDER_NOT_FOUND,UIDVALIDITY_CHANGED,INVALID_CURSOR,CURSOR_EXPIRED,MESSAGE_NOT_FOUND,MESSAGE_TOO_LARGE,IMAP_TIMEOUT,IMAP_CONNECTION_ERROR,INVALID_ARGUMENT,UNSUPPORTED_OPERATION,IMAP_ERROR,CONFIG_ERRORTools run in worker threads with at most 3 concurrent IMAP sessions, so a slow full-text search does not block other requests; connection failures are retried with backoff
Listing/search fetch only header fields, flags, size and BODYSTRUCTURE, never message bodies
Security: Email bodies can contain prompt injection. Treat mailbox content as untrusted. The server does not intentionally modify mail, but connecting to a remote service still exposes sensitive mail contents to whichever MCP clients you authorize. This project has not been independently security-audited.
Related MCP server: imap-mcp
Install on horsetooth (Ubuntu/Linux)
git clone https://github.com/junga-com/bg-imapMCPSever.git
cd bg-imapMCPSever
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -e '.[dev]'
cp .env.example .env
chmod 600 .env
$EDITOR .env
pytest -qIn .env, set IMAP_HOST, IMAP_USERNAME and IMAP_PASSWORD to the actual values from your email provider's mail-client setup page. IMAP TLS commonly uses port 993; verify your provider's settings. Do not post passwords in chat or commit .env. An app-specific password, if supported, is preferable.
Test locally
Start the MCP Inspector (requires Node.js/npm):
source .venv/bin/activate
npx -y @modelcontextprotocol/inspectorIn Inspector, select STDIO, set command to the absolute path of .venv/bin/bg-imap-mcp, and set working directory to this repository so .env is loaded. Alternatively, from a terminal in the repository:
bg-imap-mcp --transport streamable-http --host 127.0.0.1 --port 8765Then connect Inspector to http://127.0.0.1:8765/mcp using Streamable HTTP, and call check_connection and folder_status first. The HTTP endpoint is not authenticated; it is deliberately restricted to loopback. Never expose it directly to the Internet or bind to 0.0.0.0.
Remote access (ChatGPT) with built-in OAuth
ChatGPT's custom MCP connectors need a public HTTPS URL and OAuth (or no auth at all; never use that here). The server includes a small single-owner OAuth 2.1 authorization server, enabled by setting OAUTH_ISSUER_URL:
Dynamic client registration is open, as ChatGPT requires, but redirect URIs must be on an allowlisted origin (
OAUTH_ALLOWED_REDIRECT_ORIGINS, defaulthttps://chatgpt.com), so authorization codes can only be delivered there.Authorization shows a consent page that requires the owner passphrase (stored only as an scrypt hash). Five failures in 15 minutes lock sign-in for everyone; three on one attempt cancel it.
PKCE (S256) is mandatory. Codes are single use and last 5 minutes. Access tokens last 1 hour and are bound to
<issuer>/mcp; refresh tokens last 30 days and rotate, and replaying a rotated refresh token revokes the whole grant.Codes and tokens are stored only as SHA-256 hashes in a mode-600 SQLite file (
OAUTH_STATE_DB).The server still binds only to loopback. Publish it with a TLS tunnel that terminates on this machine, e.g. Tailscale Funnel.
Setup with Tailscale Funnel. Use port 443: ChatGPT does not connect to MCP servers on other ports (with :8443 it fails with "Couldn't discover OAuth settings" and never sends a request). Funnel is enabled per port, so move any tailnet-only tailscale serve on 443 to another port first (e.g. sudo tailscale serve --https=443 off && sudo tailscale serve --bg --https=8443 http://127.0.0.1:<port>).
bg-imap-mcp-auth set-password # prompts; writes OAUTH_OWNER_PASSWORD_HASH to .env
echo 'OAUTH_ISSUER_URL=https://<machine>.<tailnet>.ts.net' >> .env
bg-imap-mcp --transport streamable-http --port 8765
sudo tailscale funnel --bg --https=443 http://127.0.0.1:8765Then in ChatGPT add a custom MCP server with URL https://<machine>.<tailnet>.ts.net/mcp and OAuth authentication, and approve on the consent page.
Run it as a service (systemd user unit; survives reboots with lingering enabled):
mkdir -p ~/.config/systemd/user && cp scripts/bg-imap-mcp.service ~/.config/systemd/user/
systemctl --user daemon-reload && systemctl --user enable --now bg-imap-mcp
loginctl enable-linger "$USER"
journalctl --user -u bg-imap-mcp -f # logsOperations:
bg-imap-mcp-auth statuslists registered clients and active grants.bg-imap-mcp-auth revoke-all [--clients]revokes every token immediately (a kill switch).sudo tailscale funnel --https=443 offtakes the endpoint off the Internet;systemctl --user stop bg-imap-mcpstops the server.After
bg-imap-mcp-auth set-passwordor.envchanges:systemctl --user restart bg-imap-mcp.
When OAuth is enabled, local clients must use OAuth too (MCP Inspector supports it); use the stdio transport for unauthenticated local use.
Configuration
Variable | Default | Purpose |
| required | IMAP DNS name |
|
| TLS IMAP port |
| required | Mailbox login |
| required | Mailbox/app password |
|
| Folder used when a tool call omits |
|
| IMAP socket inactivity timeout (seconds) |
|
| Hard cap for listing/search results |
|
| Cap on returned message body characters |
|
| Cap on fetched message size (see note below) |
|
| Maximum |
|
| Maximum UIDs per |
|
| Body-text budget shared by the messages of one batch |
| system trust | CA bundle for servers with a private CA (certificate is still verified) |
Size note: read_message checks the server-reported RFC822.SIZE before downloading, so messages over IMAP_MAX_MESSAGE_BYTES are refused without being transferred. Attachment contents are not returned, but the MIME parser processes the full message.
Body note: the text/plain part is preferred; if it is a short stub (as in much bulk mail) and an HTML part has substantially more text, the HTML is converted to text instead. body_source reports which was used.
Known limitations
Searches are IMAP substring searches done by the server (no Gmail syntax or boolean expressions). Matching of non-ASCII text depends on the server's charset support. Full-text (
text/body) searches of large folders take tens of seconds; date, sender and subject filters take one or two.Date filters use the IMAP INTERNALDATE (delivery time) at day granularity, as the server interprets it (Dovecot compares UTC dates);
date_fromis inclusive,date_toexclusive. TheDate:header is reported separately.has_attachmentsin listings is derived from BODYSTRUCTURE (anattachmentdisposition or a non-signatureapplication/*part);get_messages_batch/read_messagereport the parsed attachments.Search cursors expire after 7 days; deleting
cursor.keyin the state directory invalidates all cursors and checkpoints.Search/list return the newest UIDs, not necessarily the newest Date headers.
Attachment contents and HTML originals are not exposed; HTML-only mail gets a basic plaintext extraction.
Each tool call uses its own IMAP connection (no pooling or caching).
read_messagerequires the UID and folder returned from search/list; IMAP UIDs are scoped to a folder and can be invalidated if its UIDVALIDITY changes.Without
OAUTH_ISSUER_URLthe HTTP transport has no authorization and rejects any non-loopbackHostheader; never publish it in that mode.The OAuth server is single-owner and not independently audited. Pending authorizations and the sign-in lockout are kept in memory and reset on restart.
Development
python -m pip install -e '.[dev]'
pytest -qCI runs tests on Python 3.11 and 3.12. No real IMAP account is used in tests. The acceptance suite in tests/test_dovecot_integration.py starts a disposable Dovecot container with a throwaway CA, seeds it through a separate admin connection, and covers pagination under concurrent arrivals/expunges, UIDVALIDITY resets, batch decoding, body continuation, monitoring checkpoints, and read-only command recording:
BG_IMAP_DOVECOT_TESTS=1 pytest -q # requires docker and opensslAvailable Tools
6 toolscheck_connectionA
Test authenticated IMAP connectivity; never return credentials.
Inputs: no named parameters.
folder_statusB
Count total and unread messages in a folder without marking any read.
Inputs: folder.
list_foldersA
List IMAP folders (raw server entries; flags and quoted names may be present).
Inputs: no named parameters. Returns: result
list_messagesB
List newest message headers by stable IMAP UID (max configured cap).
Inputs: limit, folder, unseen_only.
read_messageA
Read text content and attachment metadata by folder and UID; does not mark read.
Inputs: uid (required), folder.
search_messagesC
Search mailbox TEXT for plain text query, returning matching headers and UIDs.
Inputs: query (required), limit, folder, unseen_only.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 6 tools
Each tool has a clearly distinct purpose: connectivity check, folder listing, folder statistics, message listing, message search, and message reading. There is no meaningful overlap between tools, so an agent can easily select the right one.
All tool names use snake_case consistently. Most follow a verb_noun pattern, though folder_status is noun-based rather than verb-based, which is a minor deviation but still clear.
Six tools is well-scoped for a read-only IMAP interface, with each tool covering a distinct step in the email access workflow. No tool feels redundant or unnecessary.
The server covers the core read path: connection, folders, status, listing, search, and reading. However, it lacks common IMAP lifecycle operations such as flag updates, moving/deleting messages, folder management, and attachment retrieval, which would limit agents needing write or maintenance tasks.
Maintenance
Related MCP Connectors
Your own IMAP mailbox in any MCP client: search, read, flag, move; send and delete need confirm.
Hosted email MCP for your own Gmail, Outlook.com, Microsoft 365, iCloud or IMAP inbox: read, search, draft, reply in thread, forward and file mail. It moves or flags up to 500 messages in one call, and a send leaves exactly one copy in Sent. A calendar is a separate connection, and connecting one adds diary and scheduling tools.
Your IMAP mailbox as an MCP server: read, search and (if you allow it) organize mail. Open source.
Hosted MCP server for your Gmail, Outlook and IMAP mail, with mailboxes and scopes set per agent.
Related MCP Servers
- AlicenseAqualityCmaintenanceRead-only MCP server that connects to multiple IMAP accounts, enabling cross-account email listing, search, and retrieval without modifying mailboxes.4MIT
- AlicenseAqualityAmaintenanceEnables MCP clients to read, search, organise, and manage IMAP mailbox messages, including saving attachments and drafting replies, while treating mail content as untrusted and keeping write capabilities opt-in.6496 npm4MIT
- AlicenseNot gradedqualityCmaintenanceEnables MCP clients to check, list, search, read, send, draft, and trash email in a single IMAP mailbox using standard IMAP and SMTP settings, with sending and trash moves enabled only when explicitly allowed.MIT
- AlicenseNot gradedqualityBmaintenanceEnables read-only IMAP email access through MCP, including listing accounts and folders, searching messages, retrieving message bodies and attachments, and viewing threads without modifying mail state.MIT