Mailbox.org MCP Server
Provides comprehensive email, calendar, and filter management capabilities including IMAP/SMTP email operations (search, send, organize), CalDAV calendar access (events, scheduling, free/busy), and Sieve filter script management for automated email rules.
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
Mailbox.org MCP Server
A Model Context Protocol (MCP) server that integrates mailbox.org email, calendar and Sieve mail filters with Claude. It runs in either of two modes:
stdio (default): launched locally by Claude Desktop or Claude Code; your credentials and mail never leave your machine except to talk to mailbox.org.
http: a Streamable HTTP server you host yourself, reachable from Claude Code, claude.ai and mobile. See Hosted Mode.
Features
Email Integration (IMAP & SMTP)
Reading & Search:
✅ Search emails by text content, sender, subject, date range, and message flags (read/unread, flagged, answered, draft, deleted)
✅ Retrieve complete email content including headers, body, and attachments
✅ Email thread management with conversation grouping
✅ Folder browsing and navigation (INBOX, Sent, Drafts, etc.)
✅ Attachment detection and metadata extraction
Composition & Management:
✅ Send emails as plain text, HTML or both (sending attachments is not supported)
✅ Save drafts to the Drafts folder without sending them
✅ Email organization - move emails between folders
✅ Flag management - mark as read/unread, important, etc.
✅ Email deletion - trash or permanent removal
Performance:
✅ Connection pooling for SMTP and IMAP with health monitoring
✅ Session-based caching for improved performance
Calendar Integration (CalDAV)
✅ Retrieve calendar events within specified date ranges
✅ Search calendar events by title, description, location
✅ Free/busy time checking for scheduling
✅ Create, update and delete calendar events (timed or all-day, with attendees), without sending invitations unless you ask
✅ Multi-calendar support and aggregation
✅ Recurring events expanded into occurrences, with exception handling
✅ Circuit breaker on CalDAV requests, backing off after repeated failures
✅ Session-based caching for improved performance
Email Filter Management (Sieve/ManageSieve)
✅ List and retrieve existing Sieve filter scripts
✅ Create and update email filtering rules with Sieve syntax
✅ Activate/deactivate filter scripts
✅ Delete unwanted filter scripts
✅ Syntax validation before deploying filters
✅ Server capabilities discovery for supported Sieve extensions
Related MCP server: email-mcp
Requirements
Node.js 20 or later to run the server, and bun to install, build and test it
A mailbox.org account; an app password is recommended over your account password, so this server's access can be revoked on its own
At least one MCP client: Claude Desktop or Claude Code (stdio), or Claude Code / claude.ai against a hosted server (see Hosted Mode)
Installation
Clone and build the project:
git clone https://github.com/soenkenils/mailbox-mcp-server.git cd mailbox-mcp-server bun install bun run buildCopy the example environment file and update it with your credentials:
cp .env.example .envNote: For security, it's recommended to use an App Password instead of your main account password.
Edit the
.envfile with your mailbox.org credentials:# Required settings MAILBOX_EMAIL=your-email@mailbox.org MAILBOX_PASSWORD=your-app-specific-password # Optional: IMAP configuration (defaults shown) MAILBOX_IMAP_HOST=imap.mailbox.org MAILBOX_IMAP_PORT=993 MAILBOX_IMAP_SECURE=true # Optional: SMTP configuration (defaults shown) MAILBOX_SMTP_HOST=smtp.mailbox.org MAILBOX_SMTP_PORT=465 MAILBOX_SMTP_SECURE=true # Optional: CalDAV configuration (defaults shown) MAILBOX_CALDAV_URL=https://dav.mailbox.org/ # Optional: ManageSieve configuration (defaults shown) MAILBOX_SIEVE_HOST=imap.mailbox.org MAILBOX_SIEVE_PORT=4190 MAILBOX_SIEVE_SECURE=false # Optional: Enable debug logging DEBUG=falseNote: The server reads its configuration from environment variables only; it does not load
.envitself. Bun loads.envfrom the working directory when it runs the code (bun src/main.ts,bun dist/main.js);nodeneedsnode --env-file=.env dist/main.js. In Claude Desktop, set the variables in the server'senvblock instead.Add to Claude Desktop configuration:
Add this server to your Claude Desktop
claude_desktop_config.json. Claude Desktop does not read.env, so the credentials go in theenvblock:{ "mcpServers": { "mailbox-mcp-server": { "command": "node", "args": ["/path/to/mailbox-mcp-server/dist/main.js"], "env": { "MAILBOX_EMAIL": "your-email@mailbox.org", "MAILBOX_PASSWORD": "your-app-specific-password" } } } }
Available Tools
Every tool carries MCP tool annotations: a human-readable title plus hints that tell the client whether the tool only reads (readOnlyHint), can destroy data (destructiveHint), is safe to repeat (idempotentHint) and reaches outside your mailbox (openWorldHint). Clients use them to decide what to run freely and what to confirm with you first. The "Hints" column below summarises them for email and Sieve; the calendar reads (get_calendar_events, search_calendar, get_free_busy) are read-only, create_calendar_event is additive, update_calendar_event and delete_calendar_event are destructive, and all three calendar writes are open-world because they can email participants when asked to.
Each input schema is closed (additionalProperties: false). Undeclared arguments are ignored: they are dropped before validation, never reach the mail, calendar or Sieve server, and only their names are logged at debug level. Declared arguments are validated as before. update_calendar_event and delete_calendar_event are the exception and refuse undeclared arguments, so an edit is never reported for a field that was not applied.
Email Tools
Tool | What it does | Hints | Typed output |
| Search one folder, newest first. | read-only |
|
| One message in full by UID, with attachment metadata. UIDs are per folder | read-only |
|
| Every message in a conversation, found by the Message-ID of any message in it; bodies are shortened to 200 characters | read-only |
|
| Every folder with its path, flags and special-use role | read-only |
|
| Send a message over SMTP immediately; needs | destructive, open-world |
|
| Save a message to Drafts (or another | additive |
|
| Move one message to another folder (it gets a new UID there) | idempotent | – |
| Add or remove flags: | idempotent | – |
| Move one message to the trash, or with | destructive | – |
| Create a folder, optionally under an existing | additive | – |
Mail content in tool results is third-party data. search_emails, get_email and get_email_thread say so at the top of their text, and each message body is fenced between --- BEGIN EMAIL BODY <marker> --- and --- END EMAIL BODY <marker> --- lines with a random marker, so a message cannot pass itself off as instructions by closing the fence early.
Typed output. The tools with a "Typed output" entry return structuredContent that matches the outputSchema they declare, next to the same text as before, so a client can read a UID or the next offset without parsing prose. Fields that carry mail content (subjects, display names, bodies, previews, attachment names) are described in the schema as untrusted third-party data. A message that does not exist is found: false. A message date is its Date: header, else the server's arrival date; when neither is usable it is null ("unknown date" in the text) rather than a made-up one. Tools that only acknowledge an action report it through isError.
Calendar Tools
get_calendar_events- Retrieve events in a date range (default: today to 30 days later;limit1-500, default 100, andoffsetpage through them). Recurring events are listed once per occurrence; each event shows itsUID, and an occurrence of a series shows the series UID plus anOccurrence:line with its recurrence idsearch_calendar- Search events by keyword in title, description and location (same event format; default range today to one year later,limit1-200, default 50)get_free_busy- Check availability between a requiredstartandendcreate_calendar_event- Create an event (summary, start/end, optional description, location, all-day flag, attendees, target calendar) and return its UID. Timed events need a date-time with an explicit offset orZ(a date-time without one is read in the time zone of the machine running the server) and are stored in UTC. For all-day events pass dates (YYYY-MM-DD);endis the last day, inclusive, and can be omitted for a one-day event. Impossible dates such as2025-02-30and local times skipped by a daylight-saving change are refused. By default nobody is notified: attendees are only recorded on the event. Only withsendInvitations: true(meant for when you explicitly ask to invite people) does your account become the organizer, and mailbox.org may then email invitations to all attendees. The target calendar and theMAILBOX_CALENDARSentries are matched exactly, by display name, full URL or last URL segment; a name that matches several calendars is refused. WhenMAILBOX_CALENDARSis set, events can only be created in those calendars, and the first one listed is the defaultupdate_calendar_event- Change an event found by its UID: only the fields passed change (an emptydescriptionorlocationremoves it,attendeesreplaces the list and keeps the reply status of those who stay); alarms, recurrence rules and time zones are kept. Times follow thecreate_calendar_eventcontract; when onlystartis passed the event keeps its length, and values equal to the stored ones count as no change. The write carries the event's ETag (If-Match), so a change made elsewhere in the meantime fails with "changed on the server" instead of being overwrittendelete_calendar_event- Permanently delete an event found by its UID, also withIf-Match
Recurring events. Update and delete act on the whole series and take the series UID. Changing or deleting a single occurrence is not supported: an occurrence id from the read tools (UID:2025-06-20 or UID:2025-06-20T08:00:00.000Z) is refused with a message naming the series UID (a stored event whose UID merely looks like that, e.g. holiday:2025-12-25, is found and changed as usual). Moving a recurring series (start, end, all-day) is refused as well, because times are written in UTC and the series would shift across daylight-saving changes; title, description, location and attendees can be changed.
No surprise mail (RFC 6638). mailbox.org sends scheduling mail for events that have an organizer and attendees. These tools avoid that unless you ask for it:
update_calendar_eventrecords new attendees only (SCHEDULE-AGENT=CLIENT, no organizer added). WithsendInvitations: trueyour account becomes the organizer and the server may email invitations, updates and cancellations.A meeting you organize (organizer is your address, or one of the calendar user addresses the server reports, with attendees that are not marked
SCHEDULE-AGENT=CLIENT) is not changed withoutsendInvitations: trueand not deleted withoutnotifyParticipants: true, since any change makes the server email the attendees.An event is treated as an invitation you received only when your address is among its attendees and the organizer is someone else. Such an event cannot be changed; deleting it sends
Schedule-Reply: F, asking the server not to send the organizer a decline (withnotifyParticipants: truethe server may send one).Any other meeting (an organizer that is neither recognisably you nor someone who invited you, e.g. an alias the server does not report) is handled like one you organize: it is not changed or deleted without the opt-in flag, because the server may email the attendees.
Calendars for update and delete are chosen like for create: exact display name, URL or last URL segment, and only among MAILBOX_CALENDARS when that is set. A UID found in several calendars is refused until you name the calendar.
Read errors. When a calendar cannot be read, the read tools return an error naming it instead of an empty list or an all-free range (a partial list would show the unreadable calendar's meetings as free time). When the server cannot be reached, recently cached results are still served.
Sieve Filter Tools
Manage email filtering rules using the Sieve language (RFC 5228) through the ManageSieve protocol.
Tool | What it does | Hints |
| List the scripts on the server and which one is active | read-only |
| Return the source of one script | read-only |
| Save a script under a name (replacing one of that name) after the server has checked it; activates it unless | destructive, idempotent |
| Delete a script; the server refuses to delete the active one | destructive, idempotent |
| Make one script the active filter; the previous one stays stored but stops running | destructive, idempotent |
| Check a script's syntax without saving it | read-only |
| Show the server's limits and supported Sieve extensions | read-only |
Example Use Cases
Automatic Newsletter Filtering:
require ["fileinto"];
if header :contains "From" [
"newsletter@example.com",
"news@company.com"
] {
fileinto "Newsletter";
stop;
}Transaction Email Organization:
require ["fileinto"];
if anyof (
header :contains "From" ["paypal.de", "stripe.com"],
header :contains "Subject" ["Order", "Receipt", "Invoice"]
) {
fileinto "Transactional";
stop;
}Ask Claude to manage your filters:
"Analyze my inbox and suggest email filters"
"Create a filter to move all GitHub notifications to a Developer folder"
"Show me all my active Sieve filters"
"Validate this Sieve script for syntax errors"
Prompts
Prompts are workflows you pick in the client (Claude Desktop lists them as attachable prompts or slash commands). They only write the opening request; the work is done by the tools above, which the client shows and asks you to approve as usual.
draft_reply(uid, optionalfolder): read one message withget_emailand save a reply withcreate_draft, never sending it.summarize_thread(messageId, optionalfolder): read a conversation withget_email_threadand summarise what was decided and what is still open.
Both remind the model that the mail is third-party content.
Resources
mailbox://folders(application/json): the folder listget_foldersreturns, with path, delimiter, flags and special-use role, for clients that let you attach reference data without a tool call.
Server Instructions
On connect the server sends short instructions that clients add to the model's context: folder names differ per account (call get_folders), UIDs are only valid in the folder they came from, and search_emails returns headers only.
Configuration
Environment Variables
Configuration is automatically validated at startup using comprehensive validation rules. The server will fail fast with clear error messages if any configuration is invalid or missing.
Required Configuration
MAILBOX_EMAIL: Your mailbox.org email address (required)Must be a valid email address format
MAILBOX_PASSWORD: Your mailbox.org app password (required)Must be a non-empty string
Optional Email Configuration
IMAP (Reading Emails):
MAILBOX_IMAP_HOST: IMAP server host (default:imap.mailbox.org)Must be a non-empty string
MAILBOX_IMAP_PORT: IMAP server port (default:993)Must be a valid port number (1-65535)
MAILBOX_IMAP_SECURE: Use TLS encryption (default:true)Must be
"true"or"false"
SMTP (Sending Emails):
MAILBOX_SMTP_HOST: SMTP server host (default:smtp.mailbox.org)Must be a non-empty string
IPv4/IPv6 (dual-stack) connection is handled by nodemailer: it resolves both address families and falls back to the other one when one is unreachable
MAILBOX_SMTP_PORT: SMTP server port (default:465)Must be a valid port number (1-65535)
MAILBOX_SMTP_SECURE: Use TLS encryption (default:true)Must be
"true"or"false"Use
truefor port 465 (implicit TLS) andfalsefor port 587 (STARTTLS)TLS is always required: with
falsethe connection must upgrade via STARTTLS, otherwise it is refusedThe server certificate is verified, so
MAILBOX_SMTP_HOSTmust be a hostname covered by the certificate (e.g.smtp.mailbox.org); an IP address fails verification
Optional Calendar Configuration
MAILBOX_CALDAV_URL: CalDAV server URL (default:https://dav.mailbox.org/)Must be a valid URL format
MAILBOX_CALENDARS: Comma-separated list of calendars to access, for reading and writing. Entries match a calendar's exact display name, URL or last URL segment, never a substring; an entry that matches no calendar or several calendars is a configuration error, and the error lists the available calendars asDisplay Name (last URL segment). Events outside these calendars cannot be read, created, changed or deleted; the first entry is the default calendar forcreate_calendar_event
Breaking:
MAILBOX_CALENDARSentries now match exactly (display name, URL, or last path segment); substring matches no longer work. An entry such asworkthat used to match.../work-calendar/by substring is now refused with a configuration error listing the available calendars; use the display name or last URL segment shown there. This also applies to thecalendarargument of the calendar tools.
Optional Sieve Configuration
MAILBOX_SIEVE_HOST: Sieve server host (default:imap.mailbox.org)Must be a non-empty string
MAILBOX_SIEVE_PORT: Sieve server port (default:4190)Must be a valid port number (1-65535)
MAILBOX_SIEVE_SECURE: How the connection is encrypted (default:false)Must be
"true"or"false"false: connect in plain text and upgrade with STARTTLS. STARTTLS is mandatory: the client refuses to authenticate if the server does not offer it or the upgrade fails. This is what the standard ManageSieve port4190(including mailbox.org) expects.true: implicit TLS from the first byte. Only for servers that offer ManageSieve on a dedicated TLS port; the standard port4190does not speak implicit TLS.In both modes the server certificate is always verified.
Optional Cache Configuration
Cache lifetimes are fixed in code: email searches and threads 5 min, single messages 10 min, the folder list 15 min, calendar events and calendar searches 15 min, free/busy 5 min. An entry read often may have its lifetime extended, up to one hour. When the server is unreachable, an expired cached copy is served for up to a day past its lifetime; with no cached copy the tool returns an error. Moving, flagging and deleting mail, saving drafts, creating folders and calendar changes clear the affected cached entries.
CACHE_EMAIL_SEARCH_TTL, CACHE_EMAIL_MESSAGE_TTL, CACHE_EMAIL_THREAD_TTL,
CACHE_CALENDAR_EVENTS_TTL and CACHE_CALENDAR_FREEBUSY_TTL are still
validated at startup (non-negative numbers) but have no effect.
CACHE_MAX_SIZE: Maximum cache entries (default:1000)Must be a positive integer
CACHE_CLEANUP_INTERVAL: Cache cleanup frequency in ms (default:300000)Must be at least 1000ms
Optional Connection Pool Configuration
Note: mailbox.org limits concurrent IMAP connections per account. Using more than 2-3 connections may cause connection issues.
POOL_MIN_CONNECTIONS: IMAP connections kept open while idleDefault:
1in stdio mode,0in http modeMust be between 0 and
POOL_MAX_CONNECTIONS; a larger value is refused at startup0means connect on demand. This is the default for hosted deployments: a host that stops the container when idle would otherwise see repeated background IMAP logins that are never used, which a mail provider may treat as suspicious activity
POOL_MAX_CONNECTIONS: Maximum IMAP connections (default:3)Must be between 1 and 100 connections
Also caps the SMTP pool, at most
5; without it the SMTP pool allows2
POOL_TIMEOUT_MS: Connection acquire timeout (default:15000)Must be at least 1000ms
POOL_IDLE_TIMEOUT_MS: Idle connection timeout (default:30000)Must be at least 1000ms
POOL_HEALTH_CHECK_MS: Health check frequency (default:6000)Must be at least 1000ms
In stdio mode the IMAP pool keeps one connection open while idle (see POOL_MIN_CONNECTIONS). The SMTP pool connects on demand: checking an idle SMTP connection means a full login, so it is opened for a send and closed again once idle for POOL_IDLE_TIMEOUT_MS.
Optional Transport Configuration
MCP_TRANSPORT:stdioorhttp(default:stdio)stdiois what Claude Desktop and Claude Code launch locallyhttpserves MCP over Streamable HTTP for hosted deployments (see Hosted Mode)
PORT: HTTP listen port (default:8080, only used inhttpmode)MCP_AUTH_TOKEN: Shared secret required by every HTTP requestRequired in
httpmode; the server refuses to start without itMust be at least 32 characters; generate with
openssl rand -hex 32
PUBLIC_URL: Externally reachable origin, e.g.https://mcp.example.comOptional. Setting it enables OAuth, which needs a stable public URL to publish in discovery metadata and to build redirects
Must be
https, exceptlocalhost/127.0.0.1for local testingOrigin only: a path, query or fragment is refused, since the OAuth endpoints are served at the root
Without it the server accepts only the static
MCP_AUTH_TOKEN
OAUTH_ALLOWED_REDIRECT_HOSTS: Comma-separated hosts an OAuth client may register a redirect URI forDefaults to
claude.ai,claude.comLoopback (
localhost,127.0.0.1,::1) is always allowed on any port, since native clients such as Claude Code receive their callback locallyHosts match exactly: allowing
claude.aidoes not allowsub.claude.aiorclaude.ai.evil.example
Optional Debug Configuration
DEBUG: Enable debug logging (default:false)Must be
"true"or"false"Tool calls are logged with the names and types of their arguments only, never their values, so mail content, recipients and Sieve scripts stay out of the log
Security Notes
Use app-specific passwords instead of your main password for better security
All credentials are passed via environment variables (no persistent storage)
Consider using a
.envfile for local development (add it to.gitignore)In
httpmode,MCP_AUTH_TOKENis the only thing between the network and your mailbox. Treat it like the mailbox passwordLogs never contain credentials: only the authentication scheme of an
Authorizationheader is recorded, a token placed in the URL path is redacted, and OAuthcodeandcode_challengevalues are excluded
Hosted Mode
The same server can run remotely over Streamable HTTP, which makes it usable from clients that cannot launch a local process. Run it on any container host with MCP_TRANSPORT=http.
Put TLS in front of it. The server speaks plain HTTP and binds to all interfaces (0.0.0.0) so a host's proxy can reach it. The bearer token and all mail content would cross the network in clear text without a TLS-terminating proxy or load balancer in front. Never expose the port directly to the internet.
Endpoints
POST /mcp: the MCP endpoint. RequiresAuthorization: Bearer <MCP_AUTH_TOKEN>. Stateless (no session IDs) with JSON responses, so nothing is lost when the host stops an idle container.GETis refused, so no long-lived SSE stream is held open. Bodies over 4 MiB are rejectedGET /health(orHEAD): unauthenticated liveness check, returns{"status":"ok"}. It does not touch mailbox.orgWith
PUBLIC_URLset:/.well-known/oauth-authorization-server,/.well-known/oauth-protected-resource,/register,/authorizeand/token(see How OAuth works here)
The token is accepted only in the Authorization header, never in the URL, where proxies and access logs would record it.
Run with Docker
docker build -t mailbox-mcp-server .
docker run --rm -p 127.0.0.1:8080:8080 \
-e MAILBOX_EMAIL=you@mailbox.org \
-e MAILBOX_PASSWORD='your-app-password' \
-e MCP_AUTH_TOKEN="$(openssl rand -hex 32)" \
mailbox-mcp-serverThe image defaults to MCP_TRANSPORT=http on port 8080 and runs as an unprivileged user. Pass credentials through your host's secret store rather than baking them into the image.
Connect a client
Claude Code sends the token as a header:
claude mcp add --transport http mailbox https://your-host.example/mcp \
--header "Authorization: Bearer $MCP_AUTH_TOKEN"Verify a deployment:
curl -s -o /dev/null -w "%{http_code}\n" https://your-host.example/mcp \
-X POST -H "Authorization: Bearer $MCP_AUTH_TOKEN" \
-H "Content-Type: application/json" \
-H "Accept: application/json, text/event-stream" \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'200 means the token was accepted; 401 means it was missing or did not match.
claude.ai (web and mobile) via OAuth. Custom connectors cannot send an Authorization header; the dialog only offers OAuth fields. Set PUBLIC_URL and add a custom connector pointing at the plain endpoint, with no credential in the URL:
https://your-host.example/mcpLeave OAuth Client ID and OAuth Client Secret empty. The server supports dynamic client registration, so the client registers itself. PKCE is what ties an authorization code to the client that asked for it: a client registering as public gets no secret, and one registering as confidential is handed a secret that is never checked.
A browser page then names the application and the host the authorization code will be sent to. Check that destination before entering the value of MCP_AUTH_TOKEN. The client ends up holding a short-lived access token plus a refresh token, rather than a credential embedded in a URL.
Claude Desktop against the hosted server: bridge stdio to HTTP with a pinned mcp-remote version. It performs the OAuth flow itself and receives its callback on a loopback port, which the redirect allowlist permits:
{
"mcpServers": {
"mailbox": {
"command": "npx",
"args": ["-y", "mcp-remote@0.1.38", "https://your-host.example/mcp"]
}
}
}Pin the version rather than using a floating mcp-remote, which would fetch the latest package on every launch and run it locally. This path is untested here; the local stdio setup is the usual way to use Claude Desktop with this server.
How OAuth works here
There is exactly one resource owner, so the authorization step is a form asking for MCP_AUTH_TOKEN rather than a user database. Everything else is carried in HMAC-signed tokens (authorization codes, access tokens, refresh tokens, even client registrations), so the flow needs no database and survives the container being restarted or stopped while idle.
Consequences worth knowing:
Revocation is all-or-nothing. Nothing is stored, so individual tokens cannot be revoked before they expire. Rotating
MCP_AUTH_TOKENchanges the derived signing key and invalidates every outstanding token at once; that is the intended kill switch.Access tokens last 1 hour, refresh tokens 30 days, authorization codes 60 seconds. Refreshing never extends a session past 30 days from the original authorization, and never widens the granted scopes, so the token has to be entered again at least monthly.
Rotating
MCP_AUTH_TOKENdisconnects OAuth clients, since it is both the login credential and the signing key. Re-authorize the connector afterwards.The static token keeps working as an
Authorization: Bearerheader on/mcp, so Claude Code is unaffected.Registration is restricted. Anyone can reach
/register, so a client may only register a redirect URI on an allowed host (seeOAUTH_ALLOWED_REDIRECT_HOSTS). Without this, someone could register a client pointing at a host they control and send you an authorize link that looks entirely genuine. The consent screen also names the client and shows where the code will be sent, and refuses to be framed.Rate limits apply per client address: 100 requests per 15 minutes on
/authorize, 50 per 15 minutes on/token, 20 per hour on/register. The server trusts exactly one proxy hop forX-Forwarded-For, which matches a single TLS-terminating proxy in front of it.
Rotating the access token
MCP_AUTH_TOKEN is both the credential clients present and the secret the OAuth signing key is derived from, so rotating it is the kill switch for everything the server has issued: every OAuth access and refresh token, every client registration (the client_id is itself a signed token), and any client still using the old value as a bearer header.
Set a new MCP_AUTH_TOKEN on the host and restart the container, then update every client. claude.ai connectors must be removed and added again: they cannot be edited in place, and re-authorizing one with a stale client_id fails with invalid_client. Store the new value before you close the terminal: many hosts keep secrets write-only, so a lost token can only be replaced, not recovered.
Operational notes
Cold starts: if the host stops the container when idle, the first tool call re-establishes IMAP, CalDAV and Sieve connections and takes a few seconds. Pools connect on demand by default in http mode.
Logs: structured logs go to stderr. Rejected requests record the method, path, authentication scheme and which credential headers were present, never their values.
Do not point an external uptime monitor at
/healthif your host stops idle containers: it would keep the container awake.
Security Features
✅ TLS encryption with certificate verification for IMAP, SMTP and CalDAV (with the default settings), and STARTTLS required for SMTP on port 587 and for ManageSieve
✅ Connection pooling with health monitoring - automatic detection and recovery from failed connections
✅ Environment-based credentials - no persistent storage of passwords
✅ App-specific password support for enhanced security
✅ Session-only caching - an in-memory cache, cleared on restart
✅ No third-party data flow beyond your chosen client - mail content goes only between mailbox.org, this server, and the MCP client you connect
In stdio mode everything runs on your machine and nothing is exposed to the network. In http mode mail content passes through the host you deploy to, and the server adds:
✅ Shared-secret authentication on every MCP request, compared in constant time over SHA-256 digests
✅ Credential-free request logging - rejected requests are logged without the token they carried
✅ OAuth 2.0 with PKCE, dynamic client registration, and short-lived tokens, so no credential need appear in a URL
✅ Redirect URI allowlist - registration is open, so clients may only register a redirect on an allowed host (loopback excepted), preventing an authorization code being delivered to an attacker
✅ Consent screen naming the requesting client and the destination of the authorization code
✅ Stateless signed tokens, so no session store survives to be stolen, and rotating
MCP_AUTH_TOKENinvalidates everything at once
Architecture
Connection Pooling
The server implements robust connection pooling for optimal performance and reliability:
SMTP Connection Pool
Verification Timing: Connections are verified based on configurable intervals to avoid unnecessary overhead
Failure Tracking: Monitors connection health and automatically destroys connections after repeated failures
Retry Logic: Automatic retry with exponential backoff for failed connection attempts
Metrics: Real-time monitoring of pool status, verification failures, and connection distribution
IMAP Connection Pool
Folder-Aware Pooling: Connections remember selected folders to minimize folder switching overhead
Health Monitoring: Periodic validation using IMAP NOOP commands
Connection Reuse: Intelligent reuse of connections for the same folder operations
State Management: Automatic cleanup of folder state for unhealthy connections
Base Pool Features
Sensible Defaults: Production-ready configuration that works out of the box
Simple Tuning: Five
POOL_*environment variables cover the useful adjustmentsHealth Checks: Background monitoring and cleanup of idle/unhealthy connections
Graceful Shutdown: Proper cleanup of all connections on server termination
Error Recovery: Automatic recreation of failed connections with hardcoded retry logic
CalDAV and ManageSieve
CalDAV has no pool: requests go through a circuit breaker that stops calling the server for a while after repeated failures
ManageSieve opens a connection per tool call
Performance Benefits
Reduced Latency: Connection reuse eliminates costly connection establishment overhead
Better Throughput: Multiple concurrent operations through connection pooling
Resource Efficiency: Automatic scaling based on demand within configured limits
Reliability: Health monitoring ensures only working connections are used
Development
Setup
Clone the repository:
git clone https://github.com/soenkenils/mailbox-mcp-server.git cd mailbox-mcp-serverInstall dependencies:
bun installNote: This project uses bun as the package manager and test runner. CI pins the bun version in
.github/workflows/ci.yml.Create environment configuration:
cp .env.example .env # Edit .env with your mailbox.org credentials
Debugging with the MCP Inspector
The MCP Inspector is a separate tool (not a dependency of this project) that launches the server over stdio and lets you list and call its tools, prompts and resources from a browser UI:
bun run build
npx @modelcontextprotocol/inspector node --env-file=.env dist/main.js--env-file makes node load your .env, since the server does not read it itself. Add DEBUG=true to .env for debug-level logs, which go to stderr.
Available Scripts
bun run dev- Start the server from source withtsx watch, restarting on changesbun run build- Compilesrc/todist/bun run typecheck- Type-checksrc/andtests/(buildcoverssrc/only)bun run start- Start the built server (node dist/main.js)bun run test- Run the test suite oncebun run test:watch- Run the tests in watch modebun run test:coverage- Run the tests with coverage and enforce the thresholds invitest.config.tsbun run test:e2e- Run the end-to-end check against a local IMAP server (see End-to-end checks)bun run check- Lint and format check with Biome, read-only (what CI runs)bun run fix- Apply whatcheckcan fix automaticallybun run format- Format code with Biomebun run lint- Lint code with Biome
Testing
The tests live in tests/ and run with Vitest. They mock imapflow, nodemailer and tsdav, and the ManageSieve tests talk to a fake server on a local socket, so no test contacts mailbox.org; tests/integration.test.ts wires the real services together over those mocks. tests/toolContract.test.ts checks every tool's annotations, closed input schema and structured output.
# Run all tests
bun run test
# Run with coverage
bun run test:coverage
# Run one file, or tests matching a name
bun run test EmailService
bun run test -t "search"CI (.github/workflows/ci.yml) runs, in order: bun install --frozen-lockfile, bun audit --audit-level=high (with documented ignores), bun run check, bun run build, bun run typecheck and bun run test:coverage. Run the same before pushing.
End-to-end checks
The unit tests mock imapflow entirely, so they cannot catch protocol-level
regressions: a method that resolves false instead of throwing, a search
criterion the server ignores, or a library upgrade that changes envelope
shapes. tests/e2e/imap-e2e.mjs drives the built server over stdio
against GreenMail, which
keeps its mailboxes in memory and holds no real mail. The script refuses to
run unless every host it hands the server (IMAP, SMTP, Sieve, CalDAV) is
localhost or 127.0.0.1, and it does not pass on any MAILBOX_* variables
from your shell, so your own mailbox is never touched.
The server only sends mail over TLS and always verifies the certificate, and
GreenMail's built-in certificate is not issued for 127.0.0.1. So GreenMail
is started with a throwaway test certificate, which the check then trusts:
# 1. A test certificate for 127.0.0.1 (valid 30 days)
mkdir -p /tmp/greenmail-tls && cd /tmp/greenmail-tls
openssl req -x509 -newkey rsa:2048 -nodes -keyout key.pem -out cert.pem \
-days 30 -subj /CN=localhost -addext subjectAltName=IP:127.0.0.1,DNS:localhost
openssl pkcs12 -export -in cert.pem -inkey key.pem -out greenmail.p12 \
-passout pass:changeit -name greenmail
cd -
# 2. Start a throwaway IMAP/SMTP server
docker run --rm -p 3143:3143 -p 3465:3465 -p 3993:3993 \
-v /tmp/greenmail-tls:/certs:ro \
-e GREENMAIL_OPTS='-Dgreenmail.setup.test.all -Dgreenmail.hostname=0.0.0.0 -Dgreenmail.users=e2e:e2epass@example.com -Dgreenmail.users.login=email -Dgreenmail.tls.keystore.file=/certs/greenmail.p12 -Dgreenmail.tls.keystore.password=changeit -Dgreenmail.tls.key.password=changeit' \
greenmail/standalone:2.1.3
# 3. Build, then run the checks
bun run build
E2E_CA_FILE=/tmp/greenmail-tls/cert.pem bun run test:e2eGreenMail cannot delete a folder a closed session had open, so the Trash
folder the run creates outlives it; a second run against the same container
skips the "no trash folder" case and says so. Restart the container to cover
it again.
It covers folder creation (top-level and nested via parentPath) and cache
invalidation, drafts, sending, searching (newest first, flag filters),
fetching a message's addresses and body, flags, threading by Message-ID
header, moving, permanent deletion (re-checked from a fresh process so a warm
cache cannot mask it), and soft deletion with and without a trash folder. It
exits non-zero if any check fails. It is not run in CI.
SMTP always goes over GreenMail's SMTPS port (3465). To run IMAP over TLS as well:
E2E_CA_FILE=/tmp/greenmail-tls/cert.pem E2E_IMAP_PORT=3993 E2E_IMAP_SECURE=true bun run test:e2eWorth running before merging an upgrade to imapflow, mailparser,
nodemailer or the MCP SDK. E2E_SERVER=/path/to/dist/main.js points the
checks at another build, which is handy for comparing two revisions.
Dependencies
This project relies on the following key dependencies:
Runtime Dependencies
@modelcontextprotocol/server,@modelcontextprotocol/node,@modelcontextprotocol/core- MCP server implementation (SDK v2), its Node HTTP transport and shared typesimapflow- IMAP client for email accessnodemailer- SMTP client for sending mailtsdav- CalDAV client for calendar accessical.js- iCalendar parsing librarymailparser- Email message parsingvalibot- Validation of environment variables and tool argumentsdayjs- Date manipulation libraryexpress,cors,express-rate-limit- OAuth endpoints in http mode (SDK v2 no longer ships them)
ManageSieve is implemented directly on
node:net/node:tls, without a library.Development Dependencies
typescript- TypeScript compilervitest- Testing framework@biomejs/biome- Code formatting and lintingtsx- Runs the TypeScript sources inbun run dev@types/*- TypeScript type definitions
Troubleshooting
Common Issues
Connection Issues
Verify your mailbox.org credentials in
.envCheck if your account has IMAP and CalDAV access enabled
Ensure your network allows outbound connections to mailbox.org servers
SMTP certificate or TLS errors: use a hostname for
MAILBOX_SMTP_HOST(not an IP address) and setMAILBOX_SMTP_SECURE=falsewhen using port 587 (STARTTLS)
Authentication Failures
Use an App Password instead of your main password
Make sure 2FA is properly configured if enabled
Missing Dependencies
# If you encounter module not found errors: bun installDebugging
Enable debug mode for more detailed logs:
DEBUG=true bun run startCheck the Debugging with the MCP Inspector section for advanced troubleshooting
Hosted mode
The server exits at startup with
MCP_AUTH_TOKENMCP_TRANSPORT=httpneeds a token of at least 32 characters.
Every request returns 401
The token in the client does not match
MCP_AUTH_TOKEN. If it is lost, rotate it.The logs distinguish the cases:
credentialHeaders: []means nothing was sent,authScheme: Bearermeans a credential arrived and did not match.
A connector cannot complete OAuth
/registerreturninginvalid_client_metadatameans the redirect URI's host is not allowed; add it toOAUTH_ALLOWED_REDIRECT_HOSTS.invalid_clienton/authorizemeans the storedclient_idis no longer valid, which happens afterMCP_AUTH_TOKENis rotated. Remove and re-add the connector.OAuth endpoints returning 404 means
PUBLIC_URLis not set.
/mcp/<token>returns 404Expected. Tokens are accepted only in the
Authorizationheader.
First call after idle is slow
Expected when the host stops idle containers: connections are re-established on demand.
Contributing
Contributions are welcome! Here's how you can help:
Fork the repository
Create a feature branch (
git checkout -b feature/amazing-feature)Commit your changes (
git commit -m 'Add some amazing feature')Push to the branch (
git push origin feature/amazing-feature)Open a Pull Request
Please make sure to update tests as appropriate and follow the project's code style.
License
MIT License - see LICENSE file for details
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
Connect any IMAP/SMTP mailbox to Claude & ChatGPT: search, read, sort, draft. Sends only with OK.
Connect any mailbox to Claude, ChatGPT & AI: read, send, reply, schedule & search emails.
Read, search and manage iCloud Mail, Calendar and Contacts from Claude and other MCP clients.
Your mailboxes in ChatGPT and Claude: Gmail, iCloud, Fastmail, any IMAP. Passwords stay yours.
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceEnables Claude Desktop to securely access Amazon WorkMail email and calendar functionality through a local MCP server. Provides tools for reading, searching, and sending emails, as well as managing calendar events with built-in security protections.-
- FlicenseNot gradedqualityBmaintenanceEnables Claude to read, search, draft, send, flag, and move email across multiple IMAP/SMTP mailboxes while keeping credentials local.-
- AlicenseAqualityBmaintenanceLets Claude Desktop read any IMAP mailbox and send emails via SMTP, with support for multiple mailboxes and locally stored credentials.13MIT
- AlicenseNot gradedqualityDmaintenanceEnables Claude to read, search, send, and organize email over IMAP/SMTP and to manage calendars over CalDAV, including finding free slots and creating events, across multiple self-hosted accounts behind one authenticated endpoint.MIT