{
  "markdown": "# Agent Email\n\n[![npm version](https://img.shields.io/npm/v/email-agent-mcp)](https://www.npmjs.com/package/email-agent-mcp)\n[![npm downloads](https://img.shields.io/npm/dm/email-agent-mcp.svg)](https://npmjs.org/package/email-agent-mcp)\n[![License: Apache-2.0](https://img.shields.io/badge/License-Apache--2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)\n[![CI](https://github.com/UseJunior/email-agent-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/UseJunior/email-agent-mcp/actions/workflows/ci.yml)\n[![codecov](https://img.shields.io/codecov/c/github/UseJunior/email-agent-mcp/main)](https://app.codecov.io/gh/UseJunior/email-agent-mcp)\n[![GitHub stargazers](https://img.shields.io/github/stars/UseJunior/email-agent-mcp?style=social)](https://github.com/UseJunior/email-agent-mcp/stargazers)\n[![Tests: Vitest](https://img.shields.io/badge/tests-vitest-6E9F18)](https://vitest.dev/)\n[![OpenSpec Traceability](https://img.shields.io/badge/openspec-traceability%20gate-brightgreen)](./scripts/check-spec-coverage.mjs)\n[![Socket Badge](https://socket.dev/api/badge/npm/package/email-agent-mcp)](https://socket.dev/npm/package/email-agent-mcp)\n[![install size](https://img.shields.io/npm/unpacked-size/email-agent-mcp)](https://www.npmjs.com/package/email-agent-mcp)\n\n[English](./README.md) | [Español](./README.es.md) | [简体中文](./README.zh.md) | [Português (Brasil)](./README.pt-br.md) | [Deutsch](./README.de.md)\n\n**email-agent-mcp** by [UseJunior](https://usejunior.com?utm_source=github&utm_medium=readme&utm_campaign=email-agent-mcp) -- local email connectivity for AI agents.\n\nAgent Email is an open-source TypeScript MCP server that lets Claude Code, Cursor, Gemini CLI, OpenClaw, and other MCP-compatible runtimes read email, search threads, draft replies, label messages, change read state, move messages, and send mail through your own mailbox. Microsoft 365 / Outlook and Gmail are supported today. Security-first defaults mean agents cannot send email until you explicitly configure an allowlist.\n\n## Quick Start\n\n```bash\nnpx -y email-agent-mcp\n```\n\nThe interactive setup wizard walks you through OAuth configuration and mailbox selection.\n\n## What Works Today\n\n- Microsoft 365 / Outlook mailbox access through MCP stdio\n- `list_emails`, `read_email`, `search_emails`, and `get_thread`\n- `create_draft`, `update_draft`, `send_draft`, `send_email`, and `reply_to_email`\n- `label_email`, `mark_read`, and `move_to_folder`\n- send allowlists, delete disabled by default, and sanitized errors\n\nThe current launch-prep pass was validated against a real Outlook mailbox for read, draft, send, categorize, move, and read-state flows.\n\n## Why This Exists\n\nAI agents need to read, reply to, and act on email, but email APIs are complex. OAuth flows, Graph delta queries, Gmail push subscriptions, HTML-to-markdown conversion, threading semantics -- each provider has its own quirks.\n\nAgent Email wraps this complexity into deterministic MCP tools with security guardrails:\n\n- send and receive allowlists that control who agents can contact\n- delete disabled by default (requires explicit opt-in)\n- error sanitization that strips API keys, file paths, and stack traces\n- body file sandboxing with path traversal protection\n\n## Use with Claude Code\n\nAdd to `~/.claude/settings.json` or your project `.claude/settings.json`:\n\n```json\n{\n  \"mcpServers\": {\n    \"email-agent-mcp\": {\n      \"type\": \"stdio\",\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"email-agent-mcp\"]\n    }\n  }\n}\n```\n\n## Use with Cursor\n\n```json\n// .cursor/mcp.json\n{\n  \"mcpServers\": {\n    \"email-agent-mcp\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"email-agent-mcp\"]\n    }\n  }\n}\n```\n\n## Use with Gemini CLI\n\n```bash\ngemini extensions install https://github.com/UseJunior/email-agent-mcp\n```\n\n## Use with OpenClaw\n\nAdd an `mcp` block to `~/.openclaw/openclaw.json`:\n\n```json5\n{\n  // ... existing config ...\n  mcp: {\n    servers: {\n      email: {\n        command: \"npx\",\n        args: [\"tsx\", \"/path/to/email-agent-mcp/packages/email-mcp/src/serve-entry.ts\"],\n        transport: \"stdio\"\n      }\n    }\n  }\n}\n```\n\n> **Version note**: The `mcp` config key requires OpenClaw app >= 2026.3.24. If the CLI is older than the app, it may reject this key during validation even though the gateway accepts it. Update the CLI with `npm install openclaw@latest` in your NemoClaw directory, or restart the gateway directly with `launchctl kickstart -k gui/501/ai.openclaw.gateway`.\n\n### Email watcher\n\nThe watcher polls your mailbox and sends wake signals to OpenClaw when new email arrives:\n\n```bash\n# Set the hooks token (must match hooks.token in openclaw.json)\nexport OPENCLAW_HOOKS_TOKEN=\"your-hooks-token\"\n\n# Start the watcher (defaults to http://localhost:18789/hooks/wake)\nnpm run dev:watch\n```\n\nThe watcher requires at least one configured mailbox. Run `npx email-agent-mcp` or `npm run dev:configure` first to complete the OAuth flow.\n\n## Launch Prep Smoke Test\n\nBefore recording a demo, run the live smoke script against a real mailbox and a safe send allowlist. The script exercises:\n\n- `get_mailbox_status`\n- `list_emails` + `read_email`\n- `mark_read` unread -> read -> unread\n- `label_email` on a safe inbox candidate\n- `create_draft`\n- draft-only `reply_to_email`\n- optional `send_email`\n\nExample:\n\n```bash\nEMAIL_AGENT_MCP_HOME=/tmp/email-agent-mcp-live \\\nAGENT_EMAIL_SEND_ALLOWLIST=/tmp/email-agent-mcp-live/send-allowlist.json \\\nnpm run launch:prep:smoke -- --live-write --send-to beta@usejunior.com\n```\n\nDefault safe-candidate selection looks for `notifications@github.com` in the inbox so you can rehearse the recording flow on a public-safe message instead of customer mail.\nIf your mailbox status name is not an email address, pass `--reply-sender <email>` or set `EMAIL_AGENT_MCP_REPLY_SENDER` so the script can find a self-sent message for the draft-reply check.\n\n## Tool Reference\n\n### Scope profiles\n\nSet `EMAIL_AGENT_MCP_SCOPE_PROFILE` before configuring and starting the server to\nchoose the permissions exposed to an agent. The default is `full` for backward\ncompatibility.\n\n| Profile | Microsoft delegated scopes | Exposed tools |\n|---------|-----------------------------|---------------|\n| `observe` | `Mail.Read`, `User.Read`, `offline_access` | Read-only email tools, minus `list_inbox_rules` (see below) |\n| `full` (default) | `Mail.Read`, `Mail.ReadWrite`, `Mail.Send`, `MailboxSettings.ReadWrite`, `User.Read`, `offline_access` | All tools |\n\nFor an observation-only deployment, set the profile for both configuration and\nruntime so the OAuth consent and MCP tool list agree:\n\n```bash\nexport EMAIL_AGENT_MCP_SCOPE_PROFILE=observe\nnpx email-agent-mcp configure\nnpx email-agent-mcp serve\n```\n\n`observe`'s scopes are a deliberate **strict subset** of `full`'s. That is what\nmakes the profile adoptable: a tenant that has already consented to the full set\ngrants `observe` silently, so switching `full` → `observe` needs no new consent.\nSwitching `observe` → `full` does require a new interactive consent, because it\nasks for scopes that were never granted.\n\nFor the same reason `observe` does **not** expose `list_inbox_rules`. Graph gates\n`/mailFolders/inbox/messageRules` behind `MailboxSettings`, and Entra treats\n`MailboxSettings.Read` as a distinct scope from `full`'s\n`MailboxSettings.ReadWrite` rather than implied by it. Requesting it would break\nthe subset property and force a fresh consent on every `observe` deployment — an\nadmin-approval request in tenants that restrict user consent. Use `full` if you\nneed inbox-rule visibility.\n\nAn invalid profile value stops startup instead of silently granting broader\naccess. If cached credentials do not cover the profile's scopes, the server\nfails fast with an actionable error rather than blocking on an interactive\nsign-in.\n\n#### What `observe` does and does not guarantee\n\n`observe` always removes the write tools from the MCP tool surface, so an agent\ncannot invoke them. That part holds everywhere.\n\nIt only narrows the **OAuth token** on a mailbox that has not already consented\nto the write scopes. Entra issues an access token carrying every scope the user\nor tenant has already consented to for that application — not just the subset\nrequested at token-acquisition time. So if you point `observe` at a mailbox\npreviously configured as `full`, the underlying token still carries\n`Mail.ReadWrite` and `Mail.Send`; only the tool surface is reduced.\n\nFor a genuine least-privilege token, consent to `observe` from a mailbox that\nhas never been granted the write scopes — a fresh `configure` against an app\nregistration whose delegated permissions stop at `Mail.Read`/`User.Read`. Treat\nthe tool-surface reduction as defense in depth, not as an OAuth boundary, unless\nyou control the grant.\n\n### Tools\n\nThe `full` profile exposes 26 MCP tools; `observe` omits every tool whose action\nis marked as mailbox-mutating:\n\n| Tool | Description | Type |\n|------|-------------|------|\n| `list_emails` | List recent emails with filtering | read |\n| `read_email` | Read full email content as markdown, or raw HTML with `format: \"html\"` | read |\n| `search_emails` | Full-text search across mailboxes | read |\n| `list_mailboxes` | Enumerate configured mailboxes, their status, and the default | read |\n| `get_mailbox_status` | Connection status and warnings | read |\n| `get_thread` | Full conversation context | read |\n| `list_attachments` | List attachment metadata for an email | read |\n| `download_attachment` | Download a file attachment as base64 | read |\n| `send_email` | Send new email (allowlist-gated) | write |\n| `reply_to_email` | Reply within thread (allowlist-gated on send) | write |\n| `create_draft` | Create email draft | write |\n| `update_draft` | Update draft content | write |\n| `send_draft` | Send a saved draft | write |\n| `list_scheduled_sends` | List pending provider-held scheduled sends (Microsoft 365) | read |\n| `cancel_scheduled_send` | Cancel a pending scheduled send (Microsoft 365) | destructive |\n| `label_email` | Apply labels/categories | write |\n| `flag_email` | Flag/unflag emails | write |\n| `mark_read` | Mark as read/unread | write |\n| `move_to_folder` | Move between folders | write |\n| `delete_email` | Delete (requires operator env + caller flag) | destructive |\n| `list_folders` | Recursively list folders and computed paths (Microsoft 365) | read |\n| `create_folder` | Create a custom child folder (Microsoft 365) | write |\n| `delete_folder` | Delete a custom folder (requires operator env + caller flag); system folders are protected (Microsoft 365) | destructive |\n| `list_inbox_rules` | List server-side inbox rules (Microsoft 365) | read |\n| `create_inbox_rule` | Create a persistent safe inbox rule; forwarding, redirection, deletion, and discarding to Deleted Items are blocked (Microsoft 365) | write |\n| `delete_inbox_rule` | Delete a server-side inbox rule (requires operator env + caller flag) (Microsoft 365) | destructive |\n\nThis is a shared cross-provider tool surface. Although `label_email`,\n`flag_email`, `mark_read`, `move_to_folder`, and `delete_email` are advertised,\nthe Gmail adapter intentionally does not implement those mutation capabilities.\nThey fail closed before any Gmail mutation request: unsupported actions return\n`NOT_SUPPORTED`, while deletion can stop first at the default `DELETE_DISABLED`\noperator gate. The default `gmail.readonly` plus `gmail.compose` grant would not\nauthorize those mutations either; do not add `gmail.modify` to try to make the\ntools available. They remain available only for providers whose adapters and\ngrants support them.\n\nEvery row returned by `list_emails`, `search_emails`, and `get_thread`, and the\n`read_email` response, carries an always-present `isDraft` boolean. `isDraft: true`\nmeans the message is an unsent draft: it has **not** been sent, and its `receivedAt`\nis provider-supplied metadata rather than evidence of delivery. The field is never\nomitted, so a consuming agent can distinguish \"not a draft\" from \"draft status not\nreported\" — but note `false` asserts only that the provider did not mark the message\nas an unsent draft, not that the mailbox owner sent it (received mail is also\n`false`). Drafts otherwise appear in listings and search results as before.\n\nFolder and inbox-rule management requires Microsoft Graph `MailboxSettings.ReadWrite` consent. Existing Microsoft mailbox connections must re-consent after upgrading. Gmail uses labels rather than hierarchical folders/server-side Exchange rules, so these six tools return `NOT_SUPPORTED` for Gmail mailboxes.\n\n### Body formats\n\nBodies cross the wire as markdown by default in both directions. That default is\ndeliberate — markdown is token-efficient, and a routine read should stay cheap.\nBoth directions can opt out of it.\n\n**Writing** — `send_email`, `reply_to_email`, `create_draft`, and `update_draft`\naccept an optional `format`:\n\n| `format` | Behavior |\n|----------|----------|\n| `markdown` (default) | Rendered to HTML via `marked` (GFM, `breaks: true`). Raw HTML embedded in the markdown is preserved. |\n| `html` | Passthrough — your HTML is sent as-is. |\n| `text` | No rendering; sent as plain text. |\n\n`html` is unsanitised passthrough: no sanitiser, no allowlist, no rewriting of\nyour markup. Inline CSS and arbitrary tags survive to the wire — that is what\nmakes styled mail possible, and it means you own whatever you send. The one\ndefault modification is the force-black wrapper below; with `force_black:\nfalse` the body passes through byte-for-byte.\n\nFor `markdown` and `html` the rendered HTML is wrapped in a\n`<div style=\"color: #000000;\">` so Outlook's dark mode does not turn the text\nwhite-on-white.\n\n**Body files** — `send_email`, `create_draft`, and `update_draft` also accept\n`body_file`: a path to a `.md`, `.html`, or `.txt` file (read relative to\n`EMAIL_MCP_SAFE_DIR`, default the process working directory, plus any\n`AGENT_EMAIL_ALLOWED_DIRS` roots) used as the body\ninstead of `body`. A `.md` body file may\nopen with a YAML frontmatter block:\n\nFor `update_draft`, `body` and `body_file` are permitted only on a non-reply\ndraft and require `replace_body: true`; the stored body is then replaced\nwholesale. Reply draft bodies cannot be edited safely because they include\nprovider-assembled quoted history, so create a new draft instead. Subject,\nrecipient, and attachment updates remain available on reply drafts.\n\n```md\n---\nto: alex@example.com\nsubject: Quarterly summary\nformat: html\nforce_black: false\n---\n<p>The body starts after the closing delimiter.</p>\n```\n\nRecognized keys are `to`, `cc`, `subject`, `reply_to`, `draft`, `format`, and\n`force_black` (`draft: true` turns a `send_email` call into a draft save). A\nfrontmatter value overrides the same-named tool parameter. Frontmatter is\nparsed only from `.md` files, and the file extension never selects the format —\nwithout an explicit `format` tool parameter, even a `.html` body file gets the\ndefault markdown rendering; pass `format: \"html\"` for passthrough.\n\n**Reading** — `read_email` accepts an optional `format` of `markdown` (default)\nor `html`:\n\n```json\n{ \"id\": \"AAMkAD...\", \"format\": \"html\" }\n```\n\n`format: \"html\"` returns the message's raw body HTML verbatim. Reach for it when\nyou need styling that markdown cannot carry — `color`, `background-color`,\n`text-decoration`, `<u>` — for example to change one sentence of a formatted body\nand leave the rest alone. Through the markdown path that styling is silently\ndestroyed on the way out.\n\nTwo fields come back with it:\n\n- `bodyFormat` — always present: `markdown`, `html`, or `text`. You get `text`\n  when you asked for `html` but the message has no HTML part, in which case the\n  plain-text body is returned. Check this before writing a body back.\n- `bodyTruncated` — present and `true` only if the body exceeded the 256 KB\n  response budget for `format: \"html\"` (the markdown path is unbounded, as\n  before). Do not write a truncated body back to a draft.\n\nRaw HTML costs far more tokens than its markdown reduction, so leave the default\nalone unless you need the styling. `strip_quoted_history` and `strip_signatures`\nare markdown-shaped text transforms and are not applied when `format` is `html` —\nthe raw HTML is returned untouched.\n\n**Writing it back.** Pass `format: \"html\"` **and `force_black: false`**:\n\n```json\n{ \"draft_id\": \"AAMkAD...\", \"body\": \"<edited html>\", \"format\": \"html\", \"force_black\": false }\n```\n\n`force_black` defaults to `true`, which wraps whatever HTML you send in a\n`<div style=\"color: #000000;\">`. That is right for HTML you authored yourself,\nbut on a body you just read back it nests one more wrapper on every cycle — after\nfifteen revisions you have fifteen nested divs. With `force_black: false` the\nbytes survive the round trip untouched.\n\n### Scheduled send\n\n`send_email` and `send_draft` accept `scheduled_send_at`, an ISO 8601 future\ntimestamp with an explicit timezone. Microsoft 365 holds the message\nserver-side, so delivery survives this process exiting. Use the returned\n`messageId` with `cancel_scheduled_send` while it is pending, or inspect pending\nitems with `list_scheduled_sends`. That listing covers messages you scheduled\nfrom Outlook itself, not just ones scheduled through this server — Outlook parks\nthe held message wherever it likes (often Deleted Items), so discovery scans the\nmailbox rather than a folder, and reports only sends whose time is still ahead.\n\nMicrosoft Graph changes the message ID when the held draft moves to Sent Items,\nso the returned ID is a pre-delivery management handle, not a permanent sent\nmessage ID. Gmail's public API does not expose scheduled send; all scheduled\nsend surfaces return `NOT_SUPPORTED` for Gmail while immediate sends remain\nunchanged.\n\n### Outbound attachments\n\n`send_email`, `reply_to_email`, `create_draft`, and `update_draft` accept an\noptional `attachments` array. Each entry takes a sandboxed file `path` (read\nrelative to `EMAIL_MCP_SAFE_DIR`, default the process working directory, plus\nany `AGENT_EMAIL_ALLOWED_DIRS` roots — see below) or\ninline `base64`, plus optional `filename` / `mimeType` overrides:\n\n```json\n{\n  \"to\": \"alice@example.com\",\n  \"subject\": \"Signed agreement\",\n  \"body\": \"Attached as requested.\",\n  \"attachments\": [\n    { \"path\": \"./out/agreement.pdf\" },\n    { \"base64\": \"iVBORw0KGgo...\", \"filename\": \"screenshot.png\" }\n  ]\n}\n```\n\nFiles are capped at 25MB each; Microsoft Graph additionally caps inline sends\nat ~3MB total (larger files need an upload session — not yet supported). For\n`update_draft`, omitting `attachments` preserves the draft's existing files;\npassing an array (even empty) replaces them.\n\n**Attaching files from outside the working directory** — set\n`AGENT_EMAIL_ALLOWED_DIRS` to a delimiter-separated list of absolute\ndirectories (`:` on macOS/Linux, `;` on Windows; a leading `~` is expanded) that\n`attachments[].path` and `body_file` may also read from:\n\n```json\n{\n  \"mcpServers\": {\n    \"email-agent-mcp\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@usejunior/email-agent-mcp\"],\n      \"env\": { \"AGENT_EMAIL_ALLOWED_DIRS\": \"~/Downloads:/Volumes/Shared/Contracts\" }\n    }\n  }\n}\n```\n\n**How a caller's path is resolved** — the two rules below both surface as\n`FILE_NOT_FOUND`, which is easy to misread as a missing file:\n\n| Path you pass | Resolves against | Finds a file in an allowed root? |\n|---|---|---|\n| `contract.pdf` | `EMAIL_MCP_SAFE_DIR` (default: cwd) | ❌ relative paths never search the extra roots |\n| `~/Downloads/contract.pdf` | `EMAIL_MCP_SAFE_DIR` — the `~` is **not** expanded | ❌ |\n| `/Users/you/Downloads/contract.pdf` | each root in turn | ✅ |\n\nThe `~` shorthand is expanded in `AGENT_EMAIL_ALLOWED_DIRS` (the operator's\nconfig) but **not** in `attachments[].path` or `body_file` (the caller's\nargument) — pass those as absolute paths. And a relative path is deliberately\nconfined to the safe directory: searching every allowed root for a bare\n`contract.pdf` would silently attach whichever copy happened to exist first.\n\nEach root is canonicalised with `realpath` before the containment check: an\nallowlisted root that is itself a symlink resolves to its real location, a root\nthat cannot be canonicalised authorises nothing, and a symlink escaping every\nroot is still rejected. Unset (the default) keeps the working directory as the\nonly root — which is why an agent that cannot reach a file should ask you to\nallowlist its directory rather than copy confidential documents into a git\nworking tree.\n\nAllowlisting a directory trusts everyone who can write to it. Validation and\nopen are separate operations on a path, so a principal who can replace a\ndirectory *inside* an allowed root between the two can still redirect the read;\nonly allowlist roots whose ancestors are not writable by untrusted users. The\nfinal file is opened with `O_NOFOLLOW`, so the file itself cannot be swapped for\na symlink after validation.\n\n## Provider Support\n\n| Provider | Status | Package |\n|----------|--------|---------|\n| Microsoft 365 (Graph API) | Fully supported | `@usejunior/provider-microsoft` |\n| Gmail | Supported via interactive CLI OAuth (default client or your own) or manual refresh-token setup | `@usejunior/provider-gmail` |\n\nUse `email-agent-mcp configure --provider gmail` to run the local browser OAuth flow, or add a manual mailbox token file under `~/.email-agent-mcp/tokens/`. See [Gmail Setup](#gmail-setup) below and [packages/provider-gmail/README.md](./packages/provider-gmail/README.md).\n\n## Gmail Setup\n\nGmail has two supported OAuth paths. Both end with the same result: a refresh\ntoken on your machine, and Gmail API calls going directly from your machine to\nGoogle.\n\n| Path | Command | Google Cloud project needed? |\n|------|---------|------------------------------|\n| Default OAuth client | `email-agent-mcp configure --provider gmail` | No |\n| Bring your own key (BYOK) | same command plus `--client-id` / `--client-secret` | Yes, yours |\n\n**Recommended for now: BYOK.** Our default OAuth client is still in Google's\n\"Testing\" publishing status while verification is in progress, which caps it at\n100 registered test users and shows the \"Google hasn't verified this app\"\ninterstitial during consent. Verification for Gmail's restricted scope requires\na CASA security assessment and takes several weeks; progress is tracked in\n[issue #112](https://github.com/UseJunior/email-agent-mcp/issues/112). BYOK\nsidesteps the shared 100-user cap and puts the app's publishing status under\nyour control; your own app still has Google's Testing constraints until you\npublish it.\n\nOther reasons to pick BYOK: dedicated API quota, your own privacy policy and\nverification status, and no dependency on the hosted broker at\n`https://oauth.usejunior.com`.\n\n### Scopes requested\n\nAgent Email requests exactly these two Gmail scopes by default:\n\n```text\nhttps://www.googleapis.com/auth/gmail.readonly\nhttps://www.googleapis.com/auth/gmail.compose\n```\n\n`gmail.readonly` is required for reading messages and threads;\n`gmail.compose` manages drafts and sending but does not authorize\n`users.threads.get` or `users.messages.get`. The default grant does not include\n`gmail.modify`. Separately, the Gmail adapter intentionally leaves label\nchanges, read-state changes, moves, trash, and delete operations unsupported,\nso those tools fail closed with `NOT_SUPPORTED`. Add both scopes to your OAuth\nconsent screen.\n\nDeployments that explicitly set `GMAIL_OAUTH_SCOPES` must update it to the two\nspace-separated scopes above. New authorizations and repeated authorizations\nmust re-consent to the new scope pair. Existing mailbox files and their stored\nrefresh-token metadata remain unchanged.\n\n### BYOK: create your own Google OAuth client\n\n1. **Create a project** in the [Google Cloud Console](https://console.cloud.google.com/projectcreate),\n   or select an existing one.\n2. **Enable the Gmail API** under *APIs & Services → Library → Gmail API → Enable*.\n3. **Configure the OAuth consent screen** under *APIs & Services → OAuth consent screen*:\n   - User type **External** for a personal `@gmail.com` account, or **Internal**\n     if you are on Google Workspace and only your own org needs access.\n   - Add both `https://www.googleapis.com/auth/gmail.readonly` and\n     `https://www.googleapis.com/auth/gmail.compose`.\n   - While the app is in *Testing*, add your own Gmail address under **Test users**,\n     or consent will be refused.\n4. **Create the OAuth client** under *APIs & Services → Credentials → Create\n   credentials → OAuth client ID*. Choose application type **Desktop app**.\n   Desktop is required: `configure` starts a throwaway listener on an ephemeral\n   loopback port (`http://127.0.0.1:<port>/oauth2callback`), and only Desktop\n   clients let Google accept an arbitrary loopback port without pre-registering\n   the exact redirect URI. A Web application client will fail with\n   `redirect_uri_mismatch`.\n5. **Copy the client ID and client secret.**\n\n### BYOK: hand the credentials to email-agent-mcp\n\nPass both halves as flags:\n\n```bash\nnpx email-agent-mcp configure \\\n  --provider gmail \\\n  --mailbox personal \\\n  --client-id YOUR_GOOGLE_CLIENT_ID \\\n  --client-secret YOUR_GOOGLE_CLIENT_SECRET\n```\n\nOr set the two namespaced environment variables and omit the flags:\n\n```bash\nexport AGENT_EMAIL_GMAIL_CLIENT_ID=YOUR_GOOGLE_CLIENT_ID\nexport AGENT_EMAIL_GMAIL_CLIENT_SECRET=YOUR_GOOGLE_CLIENT_SECRET\n\nnpx email-agent-mcp configure --provider gmail --mailbox personal\n```\n\nBoth halves are required. Supplying only one exits with an error rather than\nsilently falling back to the default client. Supplying neither selects the\ndefault OAuth client.\n\nYour browser opens Google's consent screen, the CLI catches the callback on\nloopback, exchanges the code with PKCE, and writes the mailbox to\n`~/.email-agent-mcp/tokens/<safe-key>.json` with `\"source\": \"byok\"` alongside\nyour `clientId`, `clientSecret`, and the resulting `refreshToken`. Token\nrefreshes then go straight to Google's token endpoint; no broker is involved.\n\nRe-running `configure` for a mailbox that is already saved reuses the saved\ncredentials, so you only pass the flags once. Passing `--client-id` and\n`--client-secret` for a mailbox previously configured against the default\nclient migrates it to BYOK.\n\n### BYOK: keep the grant from expiring after 7 days\n\nGoogle expires refresh tokens after 7 days while *your* OAuth app is in\n*Testing* publishing status, which shows up as a re-authentication prompt about\nonce a week. `email-agent-mcp status` warns when a mailbox is approaching that\nwindow. Publishing your app (*OAuth consent screen → Publish app*) removes the\n7-day expiry. Since you own the app and are its only user, the 100-user test\ncap does not apply to you either way.\n\n### Disconnect Gmail and revoke access\n\nDisconnecting has two independent parts:\n\n1. Stop any running `email-agent-mcp` process. In Finder, open\n   `~/.email-agent-mcp/tokens/`, identify the single JSON file for the mailbox\n   you intend to disconnect, and move that exact file to Trash. Do not open,\n   paste, or share its contents, and do not delete the whole\n   `~/.email-agent-mcp` directory if other mailboxes are configured. If you\n   set `EMAIL_AGENT_MCP_HOME`, use that directory's `tokens/` folder instead.\n2. Open [Google Account third-party\n   connections](https://myaccount.google.com/connections), select Email Agent\n   MCP (or the name of your BYOK application), and remove its access.\n\nDeleting the local file prevents this installation from using the saved\ncredential. Removing the Google Account connection revokes the grant at\nGoogle. Run `email-agent-mcp status` afterward to confirm the mailbox is no\nlonger configured.\n\n## Security Defaults\n\nAgent Email ships with restrictive defaults that you loosen as needed:\n\n- **Send allowlist**: empty by default -- agents cannot send email until you add recipients\n- **Receive allowlist**: accepts all by default -- controls which senders trigger the watcher\n- **Delete disabled**: agents cannot delete email by default. Two gates must both be satisfied:\n  1. operator sets `AGENT_EMAIL_DELETE_ENABLED=true` in the email-agent-mcp process environment (and `AGENT_EMAIL_HARD_DELETE_ENABLED=true` for permanent deletion). Restart required after change.\n  2. the caller passes `user_explicitly_requested_deletion: true` on the tool call.\n- **Error sanitization**: API keys, file paths, and stack traces are redacted from error responses\n- **Body file sandboxing**: no `../` traversal, no symlinks, binary detection\n\n## Packages\n\n| Package | Description |\n|---------|-------------|\n| `@usejunior/email-core` | Core email actions, content engine, security, and provider interfaces |\n| `@usejunior/email-mcp` | MCP server adapter, CLI, and watcher |\n| `@usejunior/provider-microsoft` | Microsoft Graph API email provider |\n| `@usejunior/provider-gmail` | Gmail API email provider |\n| `email-agent-mcp` | Distribution wrapper (`npx email-agent-mcp`) |\n| `@usejunior/email-agent-mcp` | Compatibility wrapper, published in lockstep; use `email-agent-mcp` for new installs |\n\n## Quality and Trust Signals\n\n- CI runs on every pull request and push to main (lint, typecheck, tests on Node 20 + 22)\n- CodeQL and Semgrep security scanning\n- Coverage published to Codecov\n- OpenSpec traceability enforcement via `npm run check:spec-coverage`\n- 300+ tests across the suite\n- Maintainer: [Steven Obiajulu](https://www.linkedin.com/in/steven-obiajulu/)\n\n## Architecture\n\n```\nemail-agent-mcp/\n├── packages/\n│   ├── email-core          Core actions, content engine, security\n│   ├── email-mcp           MCP server adapter, CLI, watcher\n│   ├── provider-microsoft  Microsoft Graph provider\n│   ├── provider-gmail      Gmail API provider\n│   └── email-agent-mcp         Distribution wrapper (npx entry point)\n├── openspec/               Spec-driven development\n└── scripts/                CI and validation scripts\n```\n\n## Releasing\n\nTag-driven release via GitHub Actions with npm OIDC trusted publishing. All 6 packages publish in dependency order with `--provenance`, then `server.json` is published to the official MCP Registry with `mcp-publisher`.\n\n## FAQ\n\n### Does this work with Claude Code?\n\nYes. Run `npx email-agent-mcp` to start the MCP server, then configure it in your Claude Code settings.\n\n### Can agents send email without my permission?\n\nNo. The send allowlist is empty by default. Agents cannot send any email until you explicitly configure allowed recipients.\n\n### Does this store my email credentials?\n\nOAuth tokens are managed by MSAL (Microsoft) and stored in your OS keychain or local config files under `~/.email-agent-mcp/`. Agent Email never stores raw passwords.\n\n### Can I connect multiple mailboxes?\n\nYes. You can configure Microsoft 365 and Gmail simultaneously. Read actions default to your primary mailbox; write actions require specifying a mailbox when multiple are configured.\n\n### The OpenClaw CLI rejects my config with \"Unrecognized key: mcp\"\n\nThe OpenClaw CLI and macOS app can be different versions. The app (which runs the gateway) may support config keys the CLI doesn't recognize yet. Update the CLI: `cd ~/Projects/NemoClaw && npm install openclaw@latest`. Alternatively, restart the gateway directly: `launchctl kickstart -k gui/501/ai.openclaw.gateway`.\n\n### The watcher starts but finds zero mailboxes\n\nMailbox credentials are stored in `~/.email-agent-mcp/tokens/`. If this directory is empty, run `npx email-agent-mcp` or `npm run dev:configure` to authenticate via OAuth. The watcher will exit with no mailboxes to poll until at least one is configured.\n\n### OpenClaw says \"Demo mode -- run email-agent-mcp configure to connect\"\n\nThe MCP server is running but has no real mailbox credentials. Run `npx email-agent-mcp` to complete the interactive OAuth setup, then restart the OpenClaw gateway so the MCP server reconnects with valid tokens.\n\n### Token expired after a week even though I just authenticated\n\nMicrosoft refresh tokens typically last 90 days, but your Azure AD tenant may enforce shorter lifetimes. The code uses MSAL with OS keychain persistence (`@azure/identity-cache-persistence`), which handles silent token refresh automatically. If MSAL reports `interaction_required` or `invalid_grant`, re-run `npx email-agent-mcp` to re-authenticate. Common causes: conditional access policies, MFA re-verification requirements, or admin-configured token lifetime policies.\n\n### OpenClaw Telegram bot receives messages but doesn't respond\n\nVerify the Telegram channel is healthy with `openclaw status`. If the channel shows OK but no responses come back, check that: (1) your Telegram user ID is in `channels.telegram.allowFrom` in `openclaw.json`, (2) a binding exists matching `channel: \"telegram\"`, and (3) the gateway was restarted after config changes. For one-owner bots, use `dmPolicy: \"allowlist\"` with explicit `allowFrom` IDs rather than relying on pairing approvals.\n\n## Development\n\n```bash\nnpm ci\nnpm run build\nnpm run lint --workspaces --if-present\nnpm run test:run\nnpm run check:spec-coverage\n```\n\n## See Also\n\n- [Safe DOCX Suite](https://github.com/UseJunior/safe-docx) -- surgical editing of Word documents with coding agents\n- [Open Agreements](https://github.com/open-agreements/open-agreements) -- fill standard legal templates with coding agents\n\n## Privacy\n\nAgent Email runs entirely on your local machine. Email credentials are stored in your OS keychain (MSAL) and local config files. No email content is sent to external servers by Agent Email itself.\n\n## Governance\n\n- [Contributing Guide](CONTRIBUTING.md)\n- [Code of Conduct](CODE_OF_CONDUCT.md)\n- [Security Policy](SECURITY.md)\n- [Changelog](CHANGELOG.md)\n",
  "bytes": 33647,
  "sha": "ff0b233c5548612ddc393d499b1294890a24972fbc08f370580eb57820824a79",
  "repo_slug": "usejunior/email-agent-mcp",
  "fonte": "repo",
  "truncated": false,
  "api": "https://agentalog.com/api/listings/plg_usejunior_email_agent_mcp_90c1b32c/readme"
}