@mgcrea/mcp-apple-mail 0.0.0-bootstrap

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Olivier Louvignes <olivier@mgcrea.io>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,318 @@
1
+ # @mgcrea/mcp-apple-mail
2
+
3
+ Model Context Protocol server for the macOS **Apple Mail** app. Read, search and act on the mail
4
+ that is already synced to your Mac — no IMAP credentials, no OAuth, no mail leaving the machine.
5
+
6
+ > **Unofficial.** Not affiliated with Apple. It drives the Mail app that is already on your Mac.
7
+
8
+ ## Status
9
+
10
+ Search, listing, counting, threading, body reading, body _search_ and every mutation are
11
+ implemented.
12
+
13
+ ## How it works
14
+
15
+ Apple Mail exposes two very different surfaces, and this server uses each for what it is good at.
16
+ The split is not a preference; it comes from measurements on a real 29,617-message mailbox:
17
+
18
+ | Operation | Apple Events (AppleScript/JXA) | Verdict |
19
+ | ------------------------------------------- | ------------------------------- | ------------- |
20
+ | List 4 accounts + every mailbox | **0.6 s** | fine |
21
+ | Mailbox total / unread count | 295 ms / 76 ms | fine |
22
+ | Resolve one message by id in a 29 k mailbox | **0.10 s** | fine |
23
+ | Fetch N messages, per field | ~130 ms + **42 ms per message** | usable to ~50 |
24
+ | Read one property per message in a loop | ~250 ms each | never do this |
25
+ | `messages whose read status is false` | **74 seconds** | unusable |
26
+
27
+ So searching cannot go through Apple Events at all. It has to read Mail's own SQLite index
28
+ (`~/Library/Mail/V10/MailData/Envelope Index`), which is what Mail itself searches. That gives
29
+ three lanes:
30
+
31
+ - **AppleScript lane** — accounts, mailboxes, counts, message-by-id, and every mutation. This is
32
+ also the _authority_ lane: after a write, the result is what Mail re-read, never what the index
33
+ says.
34
+ - **Index lane** — read-only SQLite for search and filtering. Needs Full Disk Access.
35
+ - **Body lane** — `.emlx` files on disk for message bodies and attachments. Needs Full Disk Access,
36
+ and falls back to a per-message Apple Event.
37
+
38
+ The index is never written to. Mail owns it, holds it open, and reconciles it against IMAP; a write
39
+ there is corruption with a delay fuse.
40
+
41
+ ## Permissions
42
+
43
+ Two separate macOS permissions, doing different jobs. Neither is granted to Mail.app — it is the
44
+ _reader_ that needs permission, not Mail.
45
+
46
+ | Permission | Needed for | Without it |
47
+ | --------------------- | ----------------------------------- | ------------------------------------------------------------------------------- |
48
+ | **Automation → Mail** | everything | the server cannot do anything; you get a `-1743` error |
49
+ | **Full Disk Access** | search, message bodies, attachments | the server still runs: accounts, mailboxes, counts and capped listings all work |
50
+
51
+ **Automation** is granted to the app that launches the server (Terminal, iTerm, VS Code, Claude…).
52
+ macOS prompts for it on the first Apple Event, so usually you just click Allow.
53
+
54
+ **Full Disk Access** is the awkward one, and the reason this package ships a launcher.
55
+
56
+ ### Why you should not just grant it to your editor
57
+
58
+ macOS attributes a process's file access to its _responsible process_ — the app at the top of the
59
+ launch chain. When Claude spawns this server the chain is:
60
+
61
+ ```
62
+ launchd → Visual Studio Code.app → Code Helper → claude → node dist/cli.js
63
+ ```
64
+
65
+ so the grant would have to go to **VS Code**, and with it every extension, task and terminal command
66
+ that editor ever runs would gain read access to your entire disk: Messages, Safari history, SSH
67
+ keys, other apps' containers. That is a much larger permission than "may search my mail", and it
68
+ defeats `APPLE_MAIL_ACCOUNTS`, which exists to bound exactly this.
69
+
70
+ You cannot avoid it by granting the permission to `.mcp.json` (it is data, not code) or to `node`
71
+ (it is not the responsible process, and it is shared by every node program on the machine).
72
+
73
+ ### The launcher
74
+
75
+ `scripts/install-wrapper.sh` builds a small signed launcher that re-execs itself with
76
+ `responsibility_spawnattrs_setdisclaim`, making it its own responsible process, and starts the
77
+ server beneath it. Full Disk Access then goes to **that one binary** and nothing else.
78
+
79
+ ```bash
80
+ pnpm build
81
+ ./scripts/install-wrapper.sh
82
+ ```
83
+
84
+ Grant Full Disk Access to the path it prints, and point `.mcp.json` at it instead of `node`:
85
+
86
+ ```json
87
+ {
88
+ "mcpServers": {
89
+ "apple-mail": {
90
+ "command": "/Users/YOU/Library/Application Support/apple-mail-mcp/bin/apple-mail-mcp",
91
+ "env": { "APPLE_MAIL_ALLOW_WRITES": "1" }
92
+ }
93
+ }
94
+ }
95
+ ```
96
+
97
+ Verified on macOS 26.6: the launcher reads Mail's index while plain `node` in the same shell stays
98
+ denied, so the grant really is scoped. `apple_mail_diagnostics` will confirm it.
99
+
100
+ Three things worth knowing:
101
+
102
+ - **It is not a general-purpose "run X with Full Disk Access" tool.** The node and server paths are
103
+ compiled in and `argv` is never consulted for what to execute. A launcher that ran whatever it was
104
+ told would let any local process read your whole disk using a permission you granted for mail.
105
+ - **Install it once, outside the repo.** macOS ties the grant to a file path, so a launcher living in
106
+ `node_modules` or an `npx` cache would silently lose its permission on the next version bump.
107
+ - **`responsibility_spawnattrs_setdisclaim` is a private API.** It has been stable since 10.14, and
108
+ if it ever disappears the launcher says so on stderr and starts the server anyway — you lose the
109
+ search and body lanes, not the server. The fallback is granting Full Disk Access to the host app.
110
+
111
+ Restart your MCP host after granting. `apple_mail_diagnostics` reports which permission is missing
112
+ and what it is blocking.
113
+
114
+ A wrinkle worth knowing: `stat()` on a TCC-protected file **succeeds** — you can see the size and
115
+ mtime of the index without Full Disk Access, and only reading it is denied. So "the file is there"
116
+ is not evidence that the permission is granted; `access(R_OK)` is.
117
+
118
+ This install flow is a stopgap. [docs/distribution.md](../../docs/distribution.md) covers where it
119
+ goes next — a signed, notarized app so the grant survives updates and no one needs a compiler —
120
+ and why the App Store cannot host any of it.
121
+
122
+ ## Quick start
123
+
124
+ ```bash
125
+ # A. from npm
126
+ npx -y @mgcrea/mcp-apple-mail
127
+
128
+ # B. from source
129
+ pnpm install && pnpm build && node dist/cli.js
130
+ ```
131
+
132
+ Wire it into Claude Code (`.mcp.json`) or Claude Desktop:
133
+
134
+ ```jsonc
135
+ {
136
+ "mcpServers": {
137
+ "apple-mail": {
138
+ "command": "npx",
139
+ "args": ["-y", "@mgcrea/mcp-apple-mail"],
140
+ "env": {
141
+ // Off by default. With it off the write tools are not registered at all.
142
+ "APPLE_MAIL_ALLOW_WRITES": "0",
143
+ },
144
+ },
145
+ },
146
+ }
147
+ ```
148
+
149
+ Inspect the tools directly:
150
+
151
+ ```bash
152
+ npx @modelcontextprotocol/inspector node dist/cli.js
153
+ ```
154
+
155
+ ## Tools
156
+
157
+ | Tool | Does |
158
+ | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
159
+ | `apple_mail_diagnostics` | What the server can currently do and why. **Call this first when anything looks wrong** — it names the exact System Settings pane to open. |
160
+ | `apple_mail_list_accounts` | Accounts with UUIDs, addresses and mailbox names. Start here. |
161
+ | `apple_mail_list_mailboxes` | Mailboxes, optionally with counts (~0.3 s each). |
162
+ | `apple_mail_list_messages` | Newest N of one mailbox, with a `ref` per message. |
163
+ | `apple_mail_search_messages` | Any combination of filters. `body` searches message text — see [Body search](#body-search). |
164
+ | `apple_mail_count_messages` | Totals and unread, labelled by source. |
165
+
166
+ Every message carries an opaque `ref` (`m1:<accountUuid>/<mailbox>#<id>`) which the read and action
167
+ tools take. It is versioned and carries its mailbox, so a row id can never be applied to the wrong
168
+ mailbox. Do not construct one by hand.
169
+
170
+ ### Attachments
171
+
172
+ Mail almost always stores attachment bodies _outside_ the message file, in a sidecar tree — on a
173
+ real mail store, none of the attachments sampled were inline. So an attachment's size and whether it
174
+ can be fetched cannot be answered by parsing the message alone, and two plausible shortcuts are both
175
+ wrong:
176
+
177
+ - A non-empty MIME part does **not** mean the bytes are there. Stripping leaves a byte of delimiter
178
+ whitespace behind, which reads as a present, 1-byte attachment.
179
+ - `X-Apple-Content-Length` is **not** a byte size. It records the base64-encoded length, so a
180
+ 164,156-byte PDF advertises 224,634.
181
+
182
+ `list_attachments` therefore reports `sizeBytes` from the file on disk and a `retrievable` flag
183
+ saying whether `save_attachment` will actually succeed, rather than guessing from the message.
184
+
185
+ ## Security
186
+
187
+ **Blast radius.** This server can read your entire mail archive and, with writes on, send mail as
188
+ you. Two independent controls:
189
+
190
+ - `APPLE_MAIL_ALLOW_WRITES` (default off) gates every mutation. With it off the write tools are not
191
+ registered — they are invisible to the model, not merely refused.
192
+ - `APPLE_MAIL_ACCOUNTS` restricts which accounts are visible at all. This is the _read_-side
193
+ control, and `ALLOW_WRITES` does not cover it. It is enforced in one place, so no query path can
194
+ escape it.
195
+
196
+ Once implemented, sending will default to leaving a **draft** open for review; actually sending
197
+ requires both `ALLOW_WRITES` and an explicit `confirm: true`.
198
+
199
+ **No secrets.** The server holds no credential of any kind — its access is the macOS permission you
200
+ granted the host app. There is nothing here to leak, and nothing is sent anywhere: no network calls
201
+ are made at all.
202
+
203
+ **Attachments.** `save_attachment` can only write inside `APPLE_MAIL_ATTACHMENT_DIR`, and the
204
+ filename is reduced to its basename first — a sender who names their attachment
205
+ `../../../.ssh/authorized_keys` gets a file called `authorized_keys` in your downloads folder and
206
+ nothing else. Existing files are never overwritten unless you ask.
207
+
208
+ **No shell.** The one place this package spawns a process uses `execFile`, never `exec`, and no
209
+ caller input is ever interpolated into script text. Scripts are static constants piped to
210
+ `osascript` over stdin; every value travels as a JSON argument. A mailbox named
211
+ `"; do shell script "touch /tmp/pwned"; //` is data, not syntax — there is a test for exactly that,
212
+ and a tripwire that refuses to run any script containing a `${`.
213
+
214
+ **Dependencies.** Two: the MCP SDK and zod. SQLite comes from `node:sqlite`, built into Node 24.
215
+
216
+ ## Configure
217
+
218
+ | Variable | Default | Notes |
219
+ | ---------------------------------- | ------------- | ------------------------------------------------------------------------------- |
220
+ | `APPLE_MAIL_ALLOW_WRITES` | `0` | Register the mutating tools. |
221
+ | `APPLE_MAIL_ACCOUNTS` | all | Comma-separated account names or UUIDs. |
222
+ | `APPLE_MAIL_DEBUG` | off | Verbose logging to stderr. |
223
+ | `APPLE_MAIL_INDEX_MODE` | `auto` | `auto` \| `ro` \| `immutable` \| `off`. `off` disables the index lane entirely. |
224
+ | `APPLE_MAIL_ROOT` | auto | Override Mail's data root. Normally discovered from Mail itself. |
225
+ | `APPLE_MAIL_ENVELOPE_INDEX` | auto | Explicit index path, for tests and forensic copies. |
226
+ | `APPLE_MAIL_OSASCRIPT_TIMEOUT_MS` | `30000` | Sized for the first-run permission prompt, which blocks. |
227
+ | `APPLE_MAIL_DEGRADED_MAX_MESSAGES` | `50` | Cap for the Apple Events listing lane. |
228
+ | `APPLE_MAIL_MAX_RESULTS` | `200` | Ceiling for search results. |
229
+ | `APPLE_MAIL_BODY_MAX_BYTES` | `262144` | Body truncation, to protect the context window. |
230
+ | `APPLE_MAIL_ATTACHMENT_DIR` | `~/Downloads` | The only directory attachments may be saved into. |
231
+ | `APPLE_MAIL_MAILBOX_CACHE_TTL_MS` | `60000` | How long the account/mailbox map is cached. |
232
+
233
+ ## Notes
234
+
235
+ Things that will bite you, documented so nobody has to rediscover them:
236
+
237
+ - **`unread count` from Mail can be flatly wrong.** On this machine a mailbox reported
238
+ `unreadCount = 0` while `messages whose read status is false` counted 1618 and Mail's own badge
239
+ showed 37 — three numbers for one mailbox. It is a cached value. Counts are therefore reported
240
+ with their source rather than merged.
241
+ - **Gmail accounts keep everything in `[Gmail]/All Mail`.** INBOX membership is a _label_, so the
242
+ obvious index query (`WHERE mailbox = ?`) returns an empty inbox. Mailbox names are resolved
243
+ through a ladder that strips the `[Gmail]/` prefix.
244
+ - **The on-disk layout nests too, and the ref cannot see it.** `All Mail` is not at
245
+ `<account>/All Mail.mbox` — it is at `<account>/[Gmail].mbox/All Mail.mbox`, and a label like
246
+ `Work/Projects` nests two deep. The index knows the full path, but the ladder above strips it
247
+ down to the leaf before the ref is minted, so the file lane gets `All Mail` and nothing else.
248
+ It therefore resolves the name by walking `*.mbox` directories under the account root (never
249
+ into `Data/`) and, when a leaf name is ambiguous, picks the container that actually holds the
250
+ rowid. A flat join here silently disabled every message-file capability on Gmail accounts.
251
+ - **`existsSync` succeeds on a TCC-protected path.** It is stat-based, so it answers "is it
252
+ there", not "may I read it" — `readdirSync` and `readFileSync` are the calls that return
253
+ `EPERM`. Existence and readability are different questions, which is why
254
+ `apple_mail_diagnostics` reads a byte of a real message file rather than statting it, and why
255
+ a lookup can distinguish "wrong path" from "no permission" instead of blaming Full Disk Access
256
+ for both.
257
+ - **`immutable=1` is the wrong way to open the index**, even though it is the common advice. It
258
+ tells SQLite to ignore the `-wal` file, and Mail runs in WAL mode, so a read can miss whatever has
259
+ not been checkpointed yet — precisely the recent mail an agent is usually asked about. Note this
260
+ is a race, not a certainty: probing both modes on a live 437 MB index with a 1 MB `-wal` present
261
+ returned the _same_ `MAX(ROWID)`, because the newest message happened to be checkpointed already.
262
+ `mode=ro` is the default because it removes the question, not because staleness was observed.
263
+ - **Reading a message does not launch Mail.** If Mail is not running, read tools fail cleanly rather
264
+ than launching it, because launching Mail steals focus and starts a sync.
265
+
266
+ ## Body search
267
+
268
+ `search_messages` takes a `body` term, and it is the one filter with no index behind it.
269
+
270
+ There is nothing to index against. The Envelope Index carries no FTS table, and the Spotlight
271
+ volume index **excludes `~/Library` entirely** — `mdfind` returns nothing under that path however
272
+ the query is phrased, which is a fact about Spotlight's scope and not about mail. Mail's own body
273
+ search runs on CoreSpotlight donations, queried through `CSSearchQuery` by the app that donated
274
+ them and unreachable from here. The measurements are in
275
+ [docs/mail-body.md](../../docs/mail-body.md).
276
+
277
+ So the index narrows and the scan reads only the survivors. **Cost is linear in survivors**,
278
+ measured at 0.48 ms per message on a 181,734-message store:
279
+
280
+ | Candidates after the other filters | Cost |
281
+ | ---------------------------------- | -------------- |
282
+ | 100 — a tight filter | 48 ms |
283
+ | 500 | 242 ms |
284
+ | 1,932 — 90 days of one mailbox | 0.9 s |
285
+ | 6,566 — 90 days, every mailbox | 3.2 s |
286
+ | 182,329 — no filter at all | 88 s, unusable |
287
+
288
+ Which is why the bound is **declared, not hidden**. Over `APPLE_MAIL_BODY_SCAN_MAX` (2,000) the
289
+ search returns `degraded` naming the candidate count and the bound, and scans nothing. A silent cap
290
+ at the newest N messages would answer "not found" for older mail indistinguishably from a real
291
+ absence, and the model has no way to tell those apart; a refusal it can read, it can act on.
292
+
293
+ Two consequences worth knowing:
294
+
295
+ - **Combine `body` with a narrowing filter.** `mailbox`, `sender`, `dateFrom` — any of them. A body
296
+ search over a few hundred candidates is near-instant.
297
+ - **The scan reads the first `APPLE_MAIL_BODY_SCAN_BYTES` (64 KB) of each file.** 79% of a real
298
+ store's bytes are base64 that no text search would match, and MIME puts text parts ahead of
299
+ attachments — so this trades a tail nothing wants for a cost paid on every candidate. A term
300
+ hiding past the cap is missed; raise it if that matters more than latency.
301
+
302
+ ## Develop
303
+
304
+ ```bash
305
+ pnpm install
306
+ pnpm dev # tsdown --watch
307
+ pnpm test # vitest, fully offline
308
+ pnpm typecheck
309
+ pnpm lint && pnpm format:check
310
+ pnpm probe # the phase 0 spike (needs Full Disk Access)
311
+ ```
312
+
313
+ Tests are offline and hermetic: the process boundary is injected, so the queue, the injection
314
+ tripwire and the envelope handling all run for real without spawning `osascript` or touching Mail.
315
+
316
+ ## License
317
+
318
+ MIT
package/dist/cli.d.ts ADDED
@@ -0,0 +1 @@
1
+ export {}
package/dist/cli.js ADDED
@@ -0,0 +1,28 @@
1
+ #!/usr/bin/env node
2
+ import { a as loadConfig, b as MAIL_SURFACE, j as BUILD_INFO, r as createServer } from "./server-OoiI7t3N.js";
3
+ import { runStdioServer } from "@mgcrea/mcp-apple-core";
4
+ //#region src/cli.ts
5
+ const LOG_PREFIX = "apple-mail-mcp";
6
+ runStdioServer({
7
+ build: BUILD_INFO,
8
+ surface: MAIL_SURFACE,
9
+ logPrefix: LOG_PREFIX,
10
+ start: async (logger) => {
11
+ const config = loadConfig();
12
+ const { server } = createServer({
13
+ config,
14
+ logger
15
+ });
16
+ return {
17
+ server,
18
+ banner: `writes=${config.allowWrites ? "ENABLED" : "disabled"}, accounts=${config.accounts.length ? config.accounts.join("/") : "all"}, index=${config.indexMode}`
19
+ };
20
+ }
21
+ }).catch((err) => {
22
+ console.error(`[${LOG_PREFIX}] fatal:`, err);
23
+ process.exit(1);
24
+ });
25
+ //#endregion
26
+ export {};
27
+
28
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { runStdioServer } from \"@mgcrea/mcp-apple-core\";\n\nimport { BUILD_INFO } from \"./build-info.js\";\nimport { MAIL_SURFACE } from \"./client/errors.js\";\nimport { loadConfig } from \"./config.js\";\nimport { createServer } from \"./server.js\";\n\nconst LOG_PREFIX = \"apple-mail-mcp\";\n\nrunStdioServer({\n build: BUILD_INFO,\n surface: MAIL_SURFACE,\n logPrefix: LOG_PREFIX,\n start: async (logger) => {\n const config = loadConfig();\n const { server } = createServer({ config, logger });\n return {\n server,\n banner:\n `writes=${config.allowWrites ? \"ENABLED\" : \"disabled\"}, ` +\n `accounts=${config.accounts.length ? config.accounts.join(\"/\") : \"all\"}, ` +\n `index=${config.indexMode}`,\n };\n },\n}).catch((err: unknown) => {\n console.error(`[${LOG_PREFIX}] fatal:`, err);\n process.exit(1);\n});\n"],"mappings":";;;;AAQA,MAAM,aAAa;AAEnB,eAAe;CACb,OAAO;CACP,SAAS;CACT,WAAW;CACX,OAAO,OAAO,WAAW;EACvB,MAAM,SAAS,WAAW;EAC1B,MAAM,EAAE,WAAW,aAAa;GAAE;GAAQ;EAAO,CAAC;EAClD,OAAO;GACL;GACA,QACE,UAAU,OAAO,cAAc,YAAY,WAAW,aAC1C,OAAO,SAAS,SAAS,OAAO,SAAS,KAAK,GAAG,IAAI,MAAM,UAC9D,OAAO;EACpB;CACF;AACF,CAAC,CAAC,CAAC,OAAO,QAAiB;CACzB,QAAQ,MAAM,IAAI,WAAW,WAAW,GAAG;CAC3C,QAAQ,KAAK,CAAC;AAChB,CAAC"}