imap-mcp
This server lets an MCP client read, search, and inspect an IMAP mailbox under a read-only default, without sending mail or exposing raw IMAP.
Report account/server capabilities, permanent flags, new-mail keyword support, enabled tool groups, and configured limits.
List every mailbox/folder with message/unseen counts, special-use roles, and safe display names.
List and page through messages, filtering by sender, recipient, subject, body, date range, read/flagged state, custom keyword, or Gmail query.
Fetch messages not previously handed over, optionally with dry-run, using a separate AiSeen keyword so human read/unread state is untouched.
Retrieve one message's headers/body fenced as untrusted, plus SPF/DKIM/DMARC verdicts, prompt-injection/homoglyph warnings, attachment list, and optional thread summaries.
List attachments; read small text/images inline, extract text from PDF/Office/OpenDocument files, or save to a configured download directory, with type/size/magic-byte checks.
Not send mail, use SMTP, pass through raw IMAP, append arbitrary MIME, or compose HTML; write tools are not registered in this read-only schema.
Provides Gmail-aware IMAP access, including Gmail search syntax and Gmail conversation threading, alongside tools for reading and searching messages, listing folders, retrieving attachments, and saving draft replies.
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., "@imap-mcp Find the latest email from my bank and save the PDF attachment."
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.
imap-mcp
A Model Context Protocol (MCP) server for any IMAP mailbox. It speaks IMAP rather than one vendor's API, so it works with whatever provider you already have.
Lets MCP clients like Claude Code, Claude Desktop or Codex read and search your mail, organise it into folders, save attachments and draft replies — with every message fenced as untrusted content, and the write tools off unless you turn them on.
Eleven tools, not fifty: a mail account is a workflow, not an API surface, so related
operations are folded into one tool with a mode rather than split across many. And eleven is
the ceiling, not the floor — IMAP_ALLOW_TOOLS=essential registers a curated six instead, and
under the read-only default that narrows to four. See
choosing which tools load.
What makes it different
It cannot send mail. That is the feature. An agent with access to private data, exposure to
untrusted content, and a channel to the outside world is exploitable by anyone who can put a
message in the inbox — the pattern that produced
EchoLeak, where one
crafted email exfiltrated internal data from Microsoft 365 Copilot with no user interaction.
This server has the first two and deliberately not the third. save_draft writes the reply
into your Drafts folder; you send it from your own mail client. No amount of clever text in a
message can make this server post anything anywhere.
Writes are off until you turn them on. With only IMAP_HOST, IMAP_USER and
IMAP_PASSWORD set, the server registers six read tools and nothing else. The mailbox tools
appear with IMAP_READ_ONLY=false — note the default is true, the opposite of the other
servers in this family, because this one reaches a mailbox. Tools that are off are not registered at all — a
capability the model cannot see is one it cannot be talked into using.
Mail is treated as hostile input, because it is. Anyone in the world can put text in your inbox. Message bodies are fenced between markers carrying a per-call random nonce, and every line inside them is prefixed with that nonce, so the "this is data" signal does not stop at the edges of a long forwarded thread. A reminder follows the block, because otherwise the last instruction-shaped sentence in the model's context is the attacker's. Zero-width characters and directional overrides are stripped before the model sees anything, hidden HTML elements are dropped on a best-effort basis (the fencing, not the stripping, is what carries the weight), and markdown image syntax — inline and reference style — is defused so a rendering client cannot be made to fetch a tracking URL.
That covers folder names too: a folder name is chosen by whoever created
the folder, which on a shared mailbox is not necessarily you. list_mailboxes returns the name
twice — path exactly as the server spelled it, because that is the handle every other tool
takes, and display_name cleaned up for reading, with a warning on the entry when the two differ.
Alongside the message you get a server-side assessment: the SPF/DKIM/DMARC verdicts with the authserv-id they came from, which prompt-injection shapes matched, and which words mix Latin with Cyrillic or Greek letters. When something matches, the warning is the first thing in the result rather than a field buried in JSON.
Those verdicts carry a forgeable flag, and by default it is always true. A sender can write
an Authentication-Results header of their own, and if your provider does not add one, theirs
is the only one there — nothing inside the message distinguishes the two. Set
IMAP_TRUSTED_AUTHSERV_ID to the id your provider stamps (it is the first token of the header
on any message you already have) and only that id counts as authentic. Until you do, spf=pass
is reported as what it is: a claim, from a header anyone could have written.
"New mail" that actually works. The server tags messages it has handed over with a custom
IMAP keyword (AiSeen by default), so list_new_messages returns each message once. The human
\Seen state is never touched — everything is read with BODY.PEEK.
Deleting and moving ask a person. Where the client supports MCP elicitation, delete_messages,
move_messages and deleting a folder raise a real dialog that the model cannot answer on its
behalf. Where it does not, they fall back to a two-call token — and say so, rather than implying
somebody approved. ELICITATION=false takes that fallback deliberately; it never removes the
guard. See Asking a person.
Related MCP server: InboxTether MCP
Requirements
Node.js 24 or newer
An IMAP account. Providers with two-factor authentication generally need an app-specific password.
Configuration
Variable | Required | Default | Description |
| yes | — | Hostname of the IMAP server, e.g. |
| yes | — | Account username, usually the address |
| yes | — | Password or app-specific password |
| no |
| Defaults by TLS mode |
| no |
|
|
| no |
| Mailbox the message tools default to |
| no |
| Exactly |
| no | — | Tool names, |
| no | — | Same syntax; subtracted from the allow list |
| no |
| Keyword for new-mail tracking; empty turns it off |
| no | — | The authserv-id your provider stamps; see below |
| no | auto | Overrides the folder found via the |
| no |
| Default page size |
| no |
| Ceiling for returning an attachment inline |
| no |
| Ceiling for writing one to disk |
| no |
| Ceiling for reading a document's text; max |
| no |
| Seconds one IMAP command may take; max |
| no | see below | Comma-separated content-type allowlist |
| no | — | Setting it allows saving attachments there |
| no |
| Exactly |
| no |
|
|
Booleans are compared against the literal string true; 1, yes and True are not true.
IMAP_READ_ONLY is the mirror image: only the literal false turns it off, so a typo leaves
the write tools unregistered.
IMAP_COMMAND_TIMEOUT_SECONDS applies to each IMAP command, not to a whole tool call, and your
MCP client has a deadline of its own; read
slow servers before raising it.
Choosing which tools load
IMAP_ALLOW_TOOLS and IMAP_DENY_TOOLS take comma-separated tool names; a trailing *
matches a whole family. essential is a curated preset of six — list_mailboxes,
list_new_messages, list_messages, get_message, set_message_flags and move_messages.
Four of those are read tools, so it stays useful under the read-only default.
IMAP_ALLOW_TOOLS=essential
IMAP_ALLOW_TOOLS=list_new_messages,get_message,move_messages
IMAP_DENY_TOOLS=delete_messagesOne boundary the list cannot draw: move_messages copies as well as moves (mode: "copy"),
and the two are one tool. Denying move_messages removes both; there is no way to keep moving
and forbid copying, or the other way round. Both modes ask for confirmation.
An entry that matches no tool aborts startup and names it, so a typo cannot silently hide a
tool — an absent tool is not something anyone traces back to an environment variable. A
filtered tool is never registered, so it is absent from tools/list and unknown to
tools/call alike, exactly like a write tool under IMAP_READ_ONLY.
It covers tools, and the attachment resources follow get_attachments: when that tool
is filtered out, they are not registered either.
If you run several of these servers at once, mcp-hub is the other
answer — its /hub endpoint replaces every server's tools with six meta-tools.
The password is deleted from the process environment as soon as it is read, so child
processes do not inherit it. /proc/<pid>/environ still holds the environment the process
started with, readable by any process of the same user; the child that parses attachments
runs under Node's permission model and cannot read it.
Without IMAP_DOWNLOAD_DIR this server never writes to the filesystem. The three size limits are
separate on purpose, because they answer three different questions:
IMAP_MAX_ATTACHMENT_BYTES protects the model's context window,
IMAP_MAX_DOWNLOAD_BYTES protects your disk, and IMAP_MAX_EXTRACT_BYTES bounds how much
hostile input one parser is handed. Raising any one of them is not a request to raise the others.
The server starts without credentials on purpose — it completes the handshake and lists its tools, and every call then fails with setup instructions instead of reaching a server.
Installation
Claude Code
claude mcp add imap-mcp \
-e IMAP_HOST=imap.example.net -e IMAP_USER=you@example.net -e IMAP_PASSWORD=… \
-- npx -y @ni-c/imap-mcpClaude Desktop
{
"mcpServers": {
"imap-mcp": {
"command": "npx",
"args": ["-y", "@ni-c/imap-mcp"],
"env": {
"IMAP_HOST": "imap.example.net",
"IMAP_USER": "you@example.net",
"IMAP_PASSWORD": "…"
}
}
}
}Codex
[mcp_servers.imap-mcp]
command = "npx"
args = ["-y", "@ni-c/imap-mcp"]
env = { IMAP_HOST = "imap.example.net", IMAP_USER = "you@example.net", IMAP_PASSWORD = "…" }Docker
docker run --rm -i \
-e IMAP_HOST=imap.example.net \
-e IMAP_USER=you@example.net \
-e IMAP_PASSWORD=… \
ghcr.io/ni-c/imap-mcpSaving attachments needs a writable directory, and the image runs as uid 1000 — so a
bind mount has to be owned by it on the host: -e IMAP_DOWNLOAD_DIR=/data -v "$PWD/attachments:/data" with chown 1000:1000 attachments. Without
IMAP_DOWNLOAD_DIR the container never writes anything.
Through mcp-hub
A client that cannot spawn a local process — ChatGPT connectors, Claude on the web,
Cursor, LibreChat — reaches imap-mcp through mcp-hub: one
container serves many stdio MCP servers over Streamable HTTP, with an OAuth 2.1 login
behind a single password and long-lived tokens for the clients that cannot do OAuth. Its
/hub endpoint puts every server behind six meta-tools, so one connector reaches all of
them without N×tool schemas in the model's context, and it speaks both protocol revisions
— a question this server asks travels through it to the person at the far end.
Its /config/mcp.json uses Claude Code's format, so the entry is the one you already
have:
{
"mcpServers": {
"imap-mcp": {
"command": "npx",
"args": ["-y", "@ni-c/imap-mcp"],
"env": {
"IMAP_HOST": "imap.example.net",
"IMAP_USER": "me@example.net",
"IMAP_PASSWORD": "…",
"IMAP_ALLOW_TOOLS": "essential"
},
"denyTools": ["delete_messages"]
}
}
}allowTools and denyTools there are the hub's own per-server filter, which is not
the same thing as *_ALLOW_TOOLS in env — the difference, and the mistake it invites,
are in the client guide.
Tools
Read — always registered
Tool | What it does |
| Capabilities, permanent flags, whether the keyword is storable, which tool groups are on |
| Every folder with message and unseen counts and its special-use role |
| Lists and searches: sender, recipient, subject, body, date range, flags, Gmail query |
| Messages not handed over yet; marks them afterwards, |
| Headers and body, fenced untrusted, plus the security assessment; |
| Without |
Mailbox — needs IMAP_READ_ONLY=false
Tool | Confirmation |
| none — flags are reversible, and |
| 👤 for both |
| 👤 asks the user, 🔒 where the client cannot |
| 👤 for |
| none — a draft does not leave the mailbox |
👤 raises a dialog the model cannot answer · 🔒 needs a confirmation token: call once to receive one, then again with it.
copy is confirmed as well as move, because the thing that cannot be taken back is not
the deletion — it is the disclosure. A destination is a free-form folder name, and on a
shared account or a public namespace one call hands every message to everyone who can read
it, leaving the source folder untouched. For the same reason set_message_flags refuses to
add \Deleted: it is half a deletion, and the next client to close the mailbox may finish
it. Use delete_messages, which asks.
Neither a confirmation nor a dialog quotes a mailbox name inside its own sentence — folder names come from the account, which on a shared mailbox means a colleague chose them.
Structured output
Every tool declares an outputSchema and answers with structuredContent
alongside the text block, so a client can use the result without parsing prose:
{
"untrusted": true,
"source": "imap",
"mailbox": "INBOX",
"total_matching": 214,
"offset": 0,
"returned": 25,
"next_offset": 25,
"messages": [{ "uid": 4711, "subject": "…", "from": "…", "seen": false }],
}Every tool that reports anything out of the mailbox carries untrusted: true
and source: "imap" as fields — a sender display name, a folder name a
colleague chose and an attachment filename are all attacker-controllable, and
they reach the model through the listing tools long before anyone opens a
message. Only get_server_info and the five write tools are without it: those
report this server's own configuration, or what it just did with the uids it was
given.
get_message and a text attachment keep the per-call nonce fence in the text
block — the structured half states the same fields, so a client is not made to
parse the fence to find them. An image attachment keeps its bytes in the content
block, where a client renders them, rather than repeating the base64.
A refusal is now an error result: an attachment the policy rejects, one whose bytes are an executable whatever it claimed, one too large to inline. Each was a plain result that read like an answer.
Attachments are also available as MCP resources at imap://message/{uid}/part/{partId}
(with ?mailbox=… for a folder other than the default), which matters where the server has
no useful filesystem. The resource path runs the same allowlist,
size limit and magic-byte check as the tool — it is not a second, unguarded door.
Not exposed, on purpose
No sending, no SMTP, no raw IMAP passthrough, no APPEND of arbitrary MIME, no HTML
composition, no OAuth2, and no OCR — a scanned PDF has no text to extract and says so
rather than guessing. The first is the whole security argument (see SECURITY.md); the
second would make every guard here optional; the last is planned but needs a test account
before it ships.
Safety
Every result carrying mailbox content is marked untrusted, message bodies additionally fenced with a per-call nonce and marked line by line.
Attachments pass two independent gates. The declaration is checked against a content-type allowlist, an executable-extension refusal list and a size ceiling; the bytes are then checked against magic numbers. An executable renamed to
.pdfand declaredapplication/pdfclears every declaration check and fails on its bytes — including when saving to disk, where it would be more dangerous, not less.A
part_idmust come from a listing call, so the body cannot be pulled out through the attachment tool and escape its framing.Documents are parsed in a process that can be killed.
mode: "text"reads a PDF or Office file with a bundled PDF.js and a ZIP reader — the only place this server parses a binary a stranger sent. It runs in a child process with a heap limit and a timeout, its stdout discarded rather than shared with the JSON-RPC transport, PDF.js'sevalsupport off, compressed streams measured against a ceiling before PDF.js inflates them, and an entry allowlist that decides what is decompressed before the buffer is sized. Nothing in that path touches the network or the filesystem.Extracted text says what it is. Extraction returns every text-drawing instruction in a file, including text set below one point or drawn in the colour of the paper, and returns nothing that was drawn as a picture. The result says so above the fence, because "the document says X" is otherwise a claim the user has no way to check.
Downloads cannot escape their directory. The target comes only from the environment, the filename is sanitised, the resolved path is re-checked, and the file is opened with
wxand mode0600— so nothing is overwritten and no planted symlink is followed.Mailbox names, flags and addresses are refused if they contain line breaks. IMAP is a line protocol and a draft is a mail header; a CR is an injection primitive, not a typo.
TLS is never disabled globally.
IMAP_INSECURE_TLSis scoped to the connection it names;NODE_TLS_REJECT_UNAUTHORIZEDappears nowhere.Every change to the mailbox is logged to stderr with the UIDs and folder — never the subject. stderr is the one channel the model does not read.
Responses are bounded. Whole items are dropped rather than the JSON being sliced, and the truncation notice comes first so the recovery hint survives.
SECURITY.md has the trust model, what these measures do not cover, and how to report a
vulnerability.
Documentation
The full guide, tool reference and security notes live at
imap-mcp.ni-c.de (source in docs/).
Development
npm install
npm test
npm run buildThe test suite runs against an in-memory IMAP fake, so it needs no server and no network. For a live server to point the real thing at, see CONTRIBUTING.md — it starts a throwaway mailbox in a container.
Releasing
Add the CHANGELOG entry and bump
package.json.npm run lint && npm run build && npm run test:coverageCommit, then push a signed tag:
git tag -s vX.Y.Z -m "vX.Y.Z" && git push origin main vX.Y.Z
The release workflow publishes to npm (Trusted Publishing, with provenance), creates the GitHub release from the CHANGELOG section and updates the MCP Registry entry.
Contributing
Issues, discussions and pull requests are welcome — see CONTRIBUTING.md. For vulnerabilities please use private reporting rather than a public issue; the policy is in SECURITY.md.
License
MIT © Willi Thiel
Available Tools
6 toolsget_attachmentsList, read or download attachmentsARead-onlyIdempotent
Without part_id: lists the attachments of a message with their type, size, whether the policy allows fetching them and whether their text can be read. With part_id: returns that one attachment. Small text and images come back inline so you can read them; a PDF, Word, Excel, PowerPoint or OpenDocument file can be read as text with mode="text", which is the only way to read a document without access to this server's filesystem; anything else is written to the download directory, if one is configured, and you get the path. part_id must come from a listing call of this same tool. Executables are refused even when they claim to be something else — including when writing to disk.
Inputs: uid (required), mode, offset, mailbox, +2 more. Returns: uid, body, data, note, +23 more
get_messageGet one messageARead-onlyIdempotent
Fetches one message by UID and returns its headers and text body, fenced as untrusted content, together with a server-side security assessment (SPF/DKIM/DMARC verdicts, prompt-injection and homoglyph signals) and the list of its attachments. Does not change the read state. Set include_thread to also list the surrounding conversation.
Inputs: uid (required), mailbox, include_thread. Returns: uid, body, date, source, +10 more
get_server_infoServer and account informationARead-onlyIdempotent
Reports what this account and server can do: the configured mailbox, IMAP capabilities, which flags the mailbox stores permanently, whether the new-mail keyword can be used, and which tool groups are enabled. Start here when a call fails for reasons that sound like configuration.
Inputs: no named parameters. Returns: tls, host, port, limits, +11 more
list_mailboxesList mailboxesARead-onlyIdempotent
Lists every folder in the account with its message and unseen counts, its special-use role (drafts, sent, trash, junk) and whether it can hold messages. Use the returned "path" verbatim wherever a tool takes a mailbox.
Inputs: no named parameters. Returns: note, source, mailboxes, truncated, +4 more
list_messagesList and search messagesARead-onlyIdempotent
Lists messages newest first, optionally narrowed by sender, recipient, subject, body text, date range, flags or a native Gmail query. With no criteria it simply pages through the mailbox. Every filter is applied by the mail server, so searching a large folder is cheap. Returns summaries only — use get_message for the body.
Inputs: to, body, from, seen, +9 more. Returns: offset, source, mailbox, messages, +5 more
list_new_messagesList messages not seen beforeA
Returns messages this server has not handed over yet, newest first, and then marks them with the "AiSeen" keyword so the next call returns only what arrived since. This is separate from the human read/unread state, which is never touched. Use dry_run to preview without marking.
Inputs: limit, dry_run. Returns: marked, source, dry_run, mailbox, +6 more
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 6 tools
Most tools target distinct actions: server info, mailbox listing, message listing/search, single-message fetch, attachment handling, and new-message polling. The only mild overlap is that get_message includes an attachment list while get_attachments without part_id also lists attachments, but the descriptions clarify when to use each.
All tool names follow a clear snake_case verb_noun convention (get_server_info, list_messages, get_message, get_attachments, list_mailboxes, list_new_messages). The get_/list_ prefixes are used predictably and consistently.
Six tools is well-scoped for a read-oriented IMAP server, and each tool has a clear, non-redundant role. None feels like filler, and the surface is small enough to avoid selection overload.
The read-only email workflow is largely covered: discovery, mailbox navigation, search/list, message reading, attachment access, and new-mail polling. Minor gaps exist, such as no explicit raw-message retrieval or standalone thread-listing tool, but include_thread and existing tools let agents work around these.
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 mailbox for MCP clients: search, read, draft, send, rules and notes. Sending is off by default.
Your IMAP mailbox as an MCP server: read, search and (if you allow it) organize mail. Open source.
Related MCP Servers
- 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
- AlicenseNot gradedqualityBmaintenanceEnables MCP clients and AI assistants to search and read email through read-only IMAP access, including bounded message reads and explicitly selected attachment retrieval.MIT
- AlicenseNot gradedqualityBmaintenanceEnables MCP clients to work with ordinary email accounts over IMAP and SMTP — listing mailboxes, searching and reading messages, managing flags, folders, attachments and drafts, and sending, replying or forwarding mail. Supports multiple accounts and providers with per-account safety controls such as read-only mode, send/delete restrictions, recipient allow-lists and rate limits.35 npmMIT
- AlicenseAqualityBmaintenanceEnables MCP clients to manage multiple IMAP/SMTP mailboxes by listing folders, searching and reading messages, preparing Markdown drafts and replies, and sending only a draft the user has reviewed and confirmed.944 npmMIT