Back

Give Claude Your Inbox, Safely

By Pablo Fernandez12 min read

When I first gave agents email, each one got an inbox of its own: an address nobody else read, mail arriving as a signed webhook, nothing to share. Then a customer asked for the opposite. They wanted their AI agent to read, search and answer the mail of addresses that people already use, from inside Claude.

The case I designed around is my own: hola@pablofr.com, which I read in Gmail over IMAP, in Apple Mail and on my phone. Put a second reader in that mailbox and three things go wrong at once. It opens a message and my unread count drops, so I never see it. It answers a customer I answered ten minutes ago. And it can write to anyone, from my address, in my name.

So the question was never how to expose mail as tools. That part is a table. It was how an agent can work in a mailbox a person also uses without stepping on that person. This is what Mailingest ships for it, on its main branch and answering at mcp.mailingest.com today.

Claude adds a remote server as a custom connector: you paste a URL and click Connect. Everything after that is discovery, as the Model Context Protocol describes in its authorization spec, built on the OAuth 2.1 draft. The server has to answer a request without a token with a 401 that says where to look, and the rest follows from that one header.

1 POST /mcp, no token ──▶ 401, WWW-Authenticate: resource_metadata="…"2 GET protected resource metadata ──▶ one authorization server: the same host3 GET authorization server ──▶ PKCE S256, client id documents, registration4 browser: /oauth/authorize ──▶ sign in, consent: addresses and capabilities5 POST /oauth/token + verifier ──▶ mi_at_ (1 hour) and mi_rt_ (30 days)6 POST /mcp, Bearer mi_at_ ──▶ tools/list: only what the grant allows
Connecting Claude: a 401 points to the metadata, the person consents in a browser, and the token that comes back is scoped to what they ticked.

The metadata documents are RFC 9728 for the resource and RFC 8414 for the authorization server. A client can identify itself with a Client ID Metadata Document (Claude Code does): its client_id is an https URL, whose JSON the server downloads through Mailingest's SSRF-guarded HTTP client, with a size cap and a 24-hour cache. Clients that don't do that can still register through dynamic client registration, limited per network. Every token request is tied to the server with a resource indicator, and the refresh token rotates on each use: presenting the previous one revokes the whole grant, since a client that rotated properly never sends it again.

The live 401 tells you one design choice before you sign in. This is the header the server sends right now:

Bash
curl -si -X POST https://mcp.mailingest.com/mcp -d '{}' | grep -i www-authenticate
# www-authenticate: Bearer resource_metadata="https://mcp.mailingest.com/.well-known/oauth-protected-resource/mcp", scope="messages:read attachments:read drafts:write calendars:read calendars:manage address_books:read address_books:manage"

send:submit isn't in the default scopes. The consent page lists sending, but leaves it unticked. An agent connected with the defaults can read and leave drafts, and nothing it writes leaves the building until a person sends it.

A grant is a key

The consent page asks three things: which addresses (all of them, or the ones you tick), which capabilities, and how the agent behaves in mailboxes you also use. What it stores is not a new kind of object. An OAuth grant is a row in api_keys with kind = 'oauth', carrying the same scopes, the same address list and the same agent settings as a secret key someone made in the dashboard. It shows up in the key list as a connected app, and revoking it there ends access and refresh at once.

That one decision removed a whole second authorization path. Every tool call becomes the matching API request and goes through the API's own router, in the same process, with no socket in between:

Claude ──▶ mailingest-mcp ──▶ API router, in process ──▶ the handler marks AgentCall scopes, Reach, throttle idempotency, audit log
A tool call is an API request dispatched in process, so the MCP server inherits every check the API makes instead of copying them.

AgentCall is a marker only code in the process can set; it never travels in a header. It turns on the shared-mailbox rules further down, and it's the only way an OAuth access token is accepted at all: a mi_at_ token sent straight to the public API gets a 401, because its audience is the MCP server.

The tools themselves come from the table that already describes the API. A row opts in with .mcp(...), and the server builds the tool's name, description and JSON Schema from the row and the OpenAPI spec. These are the two rows that send mail:

services/api/src/openapi/operations.rs
op("post", "/v1/emails", "emails", "send", Key, "Send an email").mcp(tool("send_email", "Send an email", Send, "send:submit").open_world().or_draft(Operation("drafts_create"))),
// ...
op("post", "/v1/threads/{id}/reply", "threads", "reply", Key, "Reply to a thread's latest received message").mcp(tool("reply_to_thread", "Reply in a conversation", Send, "send:submit").open_world().or_draft(Argument("mode", "draft"))),

or_draft is the drafts-only mode. A grant with drafts:write but not send:submit still sees send_email and reply_to_thread, and the server turns the call into a draft, saved in the mailbox's Drafts folder with a note telling the model it was saved as a draft for a person to review. The model doesn't need a separate tool, or to know which mode it's in before it tries.

Outside its addresses, nothing exists

The address list used to be one address per key. Migration 460 made it email_address_ids uuid[], any addresses of any domains in the account, and every handler that serves mail, threads, calendars, contacts or sending now takes the caller's Reach. Lists and searches are filtered to the granted mailboxes. A thread shows only if one of its messages is in a granted address, and then shows only those messages.

The detail I care about most is the status code. Reading, moving or answering a message outside the grant answers 404, not 403. A 403 would confirm the message exists, and an agent that can probe ids would learn the shape of mailboxes it was never given. Sending from an address outside the grant is a 403, because there the agent named the address itself and nothing is revealed.

Sharing a mailbox with a person

This is the part with no template to copy. Mailingest calls it hybrid mode, and its first rule is that everything the agent does shows up in the person's own mail client:

  • What it sends: goes through the same path as any API send and lands in the mailbox's Sent folder.
  • What it drafts: goes into the Drafts folder through the same code as an IMAP APPEND, flagged $AgentDraft. I can open it in Gmail, edit it and send it as my own.
  • What it reads: gets the $AgentRead keyword and keeps its unread state. Reading doesn't set \Seen unless the grant asks for that, so my unread count still means what I haven't read.

The keywords are ordinary IMAP keywords: Thunderbird shows them as tags, while Apple Mail and the Gmail app don't show arbitrary keywords at all. That limit shaped the next part.

The second rule is that the agent reads the mailbox before it writes. Before a reply goes out, the API looks at the thread across the grant's mailboxes: a message in Sent that no agent sent means the person replied, and a draft without $AgentDraft means the person is writing. Then one function decides:

crates/db/src/agents.rs
pub fn may_act(policy: ThreadPolicy, activity: &Activity, draft: bool) -> Result<(), Refusal> {
    if activity.is_persons() {
        return Err(Refusal::HandedToPerson);
    }
    if activity.person_drafting {
        return Err(Refusal::PersonDrafting);
    }
    if draft {
        return Ok(());
    }
    let handed = activity.handed_to_agent();
    match policy {
        ThreadPolicy::Handed if !handed => return Err(Refusal::NotHandedToAgent),
        ThreadPolicy::Untouched if !handed && activity.touched() => {
            return Err(Refusal::TouchedByPerson)
        }
        _ => {}
    }
    if activity.person_replied() {
        return Err(Refusal::PersonReplied);
    }
    Ok(())
}

Each refusal is a 409 with a code (person_drafting, person_replied, thread_touched_by_person…) and a sentence the tool passes to the model, such as "A person already replied in this conversation after its latest message: not sent, to avoid a double reply." A draft is refused only when the thread is the person's or they're writing in it, since leaving a draft sends nothing. And the check runs before outbound admission, so a refused reply spends none of the account's sending quota.

The policy is set per grant, and can be overridden per address:

PolicyThe agent may answer
untouched (default)Threads the person hasn't written in, or has handed over
handedOnly threads handed over on purpose
allEverything, except threads the person owns and the collisions above

Handing a thread over from Mail

"Handed over" needs a gesture the person can make without leaving their mail app. There are two, both handled by the IMAP server. Setting the $Agent keyword on a message gives its thread to the agent, and removing it takes it back. For clients that hide keywords, there's a folder: move a message into the mailbox's Agent folder and the thread is the agent's, move it out and it's yours again.

services/imap/src/agent_handoff.rs
/// Whether moving from folder `from` to folder `to` hands threads over.
pub fn by_folder(from: &str, to: &str) -> Option<bool> {
    let (out, into) = (
        from.eq_ignore_ascii_case(AGENT_FOLDER),
        to.eq_ignore_ascii_case(AGENT_FOLDER),
    );
    match (out, into) {
        (false, true) => Some(true),
        (true, false) => Some(false),
        _ => None,
    }
}

Every client can move a message, so the folder works on a phone where nothing else would. The change of owner happens off the command's path: the MOVE has already been answered when the thread changes hands, and a failure is logged rather than shown to the mail client.

The agent can go the other way, with hand_off_thread, which gives the thread to the person and marks its messages $AgentHandoff. What it can't do is take a thread back. The return route refuses agent calls, so only the person decides when the agent gets back in.

$Agent keyword, or moved into Agent/ ┌─────────────────────────────────────────┐ │ ▼┌─────────────┐ ┌─────────────┐│ person │ │ agent │└─────────────┘ └─────────────┘ ▲ │ └─────────────────────────────────────────┘ keyword removed, moved out, or the agent calls hand_off_thread (it can't undo it)
Who owns a thread, and who can move it: the person both ways, the agent only toward the person.

Sends that wait for a person

The rules so far keep the agent from colliding with me. They don't stop it from writing to someone it shouldn't. Drafts-only does, but it puts every message through my mail client, which is too much once the agent is mostly right. The middle ground came on November 7: a key or grant can send some mail alone, and the rest waits.

Each key now carries a send policy: a mode (direct or approval), the recipients it may write to unasked (addresses or whole domains; empty means anyone), and daily limits on emails and on recipients. Past any of them, the email waits:

crates/db/src/agents.rs
pub fn reasons(&self, recipients: &[&str], sent: i64, reached: i64) -> Vec<ApprovalReason> {
    let mut reasons = Vec::new();
    if self.mode == SendMode::Approval {
        reasons.push(ApprovalReason::Mode);
    }
    if recipients.iter().any(|r| !self.allows(r)) {
        reasons.push(ApprovalReason::RecipientNotAllowed);
    }
    if self
        .daily_limit
        .is_some_and(|limit| sent + 1 > i64::from(limit))
    {
        reasons.push(ApprovalReason::DailyLimit);
    }
    if self
        .recipients_daily_limit
        .is_some_and(|limit| reached + recipients.len() as i64 > i64::from(limit))
    {
        reasons.push(ApprovalReason::RecipientsDailyLimit);
    }
    reasons
}

A domain in the list matches that domain exactly: the unit test allows bob@partner.org and refuses bob@sub.partner.org. The daily counts live in Redis and are reserved with HINCRBY before the decision, so concurrent sends can't all read the same count and pass a limit together; a send that ends up waiting gives its count back. If Redis can't be reached, the day can't be counted, and an email from a key with daily limits waits for a person instead of going.

send_email, reply_to_thread, forward_message │ scopes, reach, hybrid rules: passed ▼SendPolicy::reasons ── empty ──▶ queued, goes now │ any reason ▼awaiting_approval ──▶ the owner gets an email with a link │ ├── approved, as is or edited ──▶ goes the way every email does ├── rejected ──▶ canceled └── 7 days without a decision ──▶ canceled
An email past the key's policy is queued with every check already passed; only a person's decision moves it.

The held email is queued with every check already passed, so approving it releases exactly what would have gone, or what the person edited. Nothing else publishes it: it isn't even in the retry index. The approval records why it waited (mode, recipient_not_allowed, daily_limit, recipients_daily_limit), and the agent can follow it with list_approvals and get_approval.

Only a signed-in person can decide. A key that tries to approve gets 403 person_required. A security pass the same day closed the side doors around that rule: a key whose sends are reviewed can't change agent settings, make new keys, resume a paused key, set up repeating sends, send broadcasts or add forwarding destinations. Each would let the key lift its own review, or send mail later, to many people or onward, without it.

For Claude connectors, the consent page has a box called "Ask me before sending", ticked by default: "Every email it sends or forwards waits for your approval in the dashboard, where you can edit or reject it." So a person who ticks Send and changes nothing else gets an agent that proposes every email and sends none on its own. This is the same idea as the preview and confirmation in Sumalos, moved from a chat to a mail queue, and like the agent there that borrows the user's permissions, the agent here never holds more than the person granted it.

Mail is data, not instructions

Everything above assumes the agent behaves, and an agent reading mail from strangers is the easiest one to fool, the case I wrote about in assuming your agent will be fooled. MCP has no "untrusted" annotation, so results that carry mail, threads, drafts or calendar events are marked three ways: a first block addressed to the assistant that says the content is third parties' data and not instructions, the data inside an <untrusted-email-content> tag whose boundary is 24 random characters per response (an email can't close a tag it can't predict), and structuredContent flagged untrusted_content: true.

None of that guarantees the model ignores a planted instruction. It's why the limits above sit in the API and not in a prompt. A fooled agent still can't see addresses outside its grant, can't reply over me, and can't send past its policy without me clicking approve. On top of that, each grant gets 120 tool calls a minute, 20 of them writes, and every call lands in the audit log with the grant, the tool and the address, never the content.

What still isn't there

Two gaps are real today. The API stores attendees on calendar events but sends no invitations: the invitation emails (iMIP) still come only from the CalDAV server, and moving them to shared code is the next step. And the agent sends as the mailbox, my own address, with an optional signature per grant; which grant sent a message is in agent_actions and the audit log, but no header tells the recipient. That was a choice, and it means a customer can't tell from the message whether I or the agent wrote it.

The mailbox is the interface

Looking back at the design, most of it isn't new machinery. The approval queue for drafts-only mode is the Drafts folder. The record of what the agent sent is the Sent folder. Handing a thread over is moving a message to a folder, a gesture every mail client has had for decades. The agent's collisions with me are detected by reading the same folders my phone syncs.

The new parts are the ones a mailbox can't express: which addresses a grant reaches, how much it may send alone, and a person's yes before the rest goes out. Everything else, I left in the mailbox, which is where I was already looking.

Related articles

Hybrid Email Search

BM25 scores words, trigrams only say yes or no, vectors give a cosine. Mailingest throws the numbers away and fuses the three lists by rank.

Search a Table in Plain Words

Type a sentence into a table's search box and get its filters back as chips, the first in a third of a second, from a model that only picks real values.

350,000 Rows in One Fast Table

Virtualizing 350,000 rows is the easy part. The counts and filter lists around them took seconds, until Postgres started saying which columns changed.