@miguelarios/email-mcp 0.11.0 → 0.13.0

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/CHANGELOG.md CHANGED
@@ -1,5 +1,32 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.13.0 (2026-09-15)
4
+
5
+ - Attachments and message sources are now addressable as MCP resources, so a client can fetch the bytes with `resources/read` instead of only ever receiving them inline in a tool result: `imap://{folder}/{uid}/{partId}` serves one attachment under its own media type, `imap://{folder}/{uid}.eml` serves the raw RFC 822 source. `download_attachment` and `get_email_raw` already stamped these URIs onto the blocks they returned, but nothing could resolve one (PR #102, `claude/laughing-euler-nko3sh`).
6
+ - **BREAKING:** `download_attachment` and `get_email_raw` no longer embed a payload over 256 KiB. Above the limit they return a `resource_link` plus a note naming the size, the limit and the URI, and the bytes stay reachable via `resources/read`. A caller that unconditionally reads `content[0].resource.blob` must now check `structuredContent.embedded` first. Previously there was no ceiling at all: an 8 MB PDF became ~10.7 MB of base64 in one tool result, which most clients put straight into the model's context, so the call failed downstream after the bytes had already been pulled off the IMAP server (PR #103, `claude/laughing-euler-nko3sh-size-guard`).
7
+ - `EMAIL_MAX_INLINE_BYTES` overrides that ceiling; `0` links everything, and an unparseable value falls back to the default rather than disabling the guard. The default matches the 256 KiB `MAX_INLINE_CALENDAR_BYTES` that has guarded calendar parts since 0.12.0 (PR #103, `claude/laughing-euler-nko3sh-size-guard`).
8
+ - `download_attachment` and `get_email_raw` output gained `uri` and `embedded`, so a caller can tell which path it got without inspecting content blocks (PR #103, `claude/laughing-euler-nko3sh-size-guard`).
9
+ - Oversized payloads are no longer fetched, only to be discarded: attachment size comes from BODYSTRUCTURE before the body is read, and message size from RFC822.SIZE in a single FETCH. A server that withholds either is still held to the ceiling, after the fetch rather than before it (PR #103, `claude/laughing-euler-nko3sh-size-guard`).
10
+ - `send_email` attachments accept `encoding: "base64" | "utf8"` and `contentType`. `content` is a JSON string and was read as UTF-8, so binary could not be attached through it at all — the only working path for a real file was `attachments[].path`, which requires `EMAIL_ATTACHMENT_DIR`. Downloading an attachment and sending it back out now works without a directory on the server. Invalid base64 is rejected rather than attached, since `Buffer.from(s, "base64")` discards anything outside the alphabet and would otherwise deliver a silently corrupt file (PR #104, `claude/laughing-euler-nko3sh`).
11
+ - Attachment errors on `send_email` now report `INVALID_INPUT` and are raised before the send confirmation, instead of `INTERNAL_ERROR` after the user had already confirmed an irreversible send. This also corrects the pre-existing `EMAIL_ATTACHMENT_DIR` path rejection, which had both problems (PR #104, `claude/laughing-euler-nko3sh`).
12
+ - Bumped `@miguelarios/pim-core` dependency to `^0.10.0`.
13
+
14
+ ## 0.12.0 (2026-08-10)
15
+
16
+ - `get_email` now detects `text/calendar` MIME parts regardless of content disposition or filename, so inline calendar invitations are no longer omitted from responses (PR #19, `claude/feature-planning-xexlsc`).
17
+ - Added `calendarParts` to the `get_email` output: MIME part ID, content type, iTIP method (uppercased), filename when present, and decoded iCalendar content (base64/quoted-printable handled, charset parameter honored). Content is inlined up to 256 KiB; larger parts set `truncated: true` and remain downloadable via `download_attachment` (PR #19, `claude/feature-planning-xexlsc`).
18
+ - `hasAttachments` in `get_email` and `search_emails` now counts inline calendar parts, and such parts are listed in `attachments` with a working `partId` (PR #19, `claude/feature-planning-xexlsc`).
19
+
20
+ ## 0.11.0 (2026-08-07)
21
+
22
+ - Adopted MCP spec revision 2026-07-28: migrated from `@modelcontextprotocol/sdk` to `@modelcontextprotocol/server` v2 (`McpServer` + `registerTools` + `serveStdio`); 2025-era clients are still served from the same tool definitions (PR #15, `claude/mcp-spec-improvements-m9bqli`).
23
+ - Tool arguments are now validated against the declared input schemas before handlers run, and every tool declares a title, all four behaviour annotations, and an `outputSchema` with validated `structuredContent` (PR #15, `claude/mcp-spec-improvements-m9bqli`).
24
+ - Irreversible operations (`send_email` when actually sending, `send_draft`, `delete_email` with `permanent`) now confirm via the spec's multi round-trip request pattern; `PIM_MCP_CONFIRM=off` bypasses it for headless use (PR #15, `claude/mcp-spec-improvements-m9bqli`).
25
+ - `download_attachment` no longer duplicates the base64 payload in `structuredContent` — the bytes ride only in the embedded resource block (PR #15, `claude/mcp-spec-improvements-m9bqli`).
26
+ - `send_email`/`create_draft` may set a visible `From` address when explicitly allowed via server configuration; documented `EMAIL_ATTACHMENT_DIR`, `URL_RESOLVE_DISABLE`, `SMTP_AUTO_SENT`, and the SPF/DKIM/DMARC alignment requirements for `SMTP_ALLOWED_FROM` (PR #2, `feat/email-shared-sender`).
27
+ - Added `src/__tests__/roundtrip.test.ts` driving a real MCP client over an in-memory transport on both protocol eras (PR #15, `claude/mcp-spec-improvements-m9bqli`).
28
+ - Bumped `@miguelarios/pim-core` dependency to `^0.8.0`.
29
+
3
30
  ## 0.10.0 (2026-07-10)
4
31
 
5
32
  - **BREAKING:** attachment `partId` values now identify a MIME bodystructure part path instead of an array index — callers that cached or hardcoded a previous `partId` must re-fetch it via `get_email` before calling `download_attachment` (PR #10, `fix/email-attachments`).
package/README.md CHANGED
@@ -40,6 +40,12 @@ Add the server to your MCP client config (Claude Desktop, Claude Code, etc.). Cr
40
40
 
41
41
  Optional env vars: `IMAP_PORT` (default 993), `IMAP_SECURE` (default true), `SMTP_PORT` (default 465), `SMTP_SECURE` (default true), `SMTP_FROM_NAME`, `PIM_TIMEZONE`.
42
42
 
43
+ - `EMAIL_MAX_INLINE_BYTES` — bytes above which `download_attachment` and `get_email_raw`
44
+ return a resource link instead of embedding the payload. Defaults to `262144` (256 KB),
45
+ matching the ceiling calendar parts already use. `0` links everything; an unparseable
46
+ value falls back to the default rather than disabling the guard. Base64 adds a third on
47
+ top, and most clients put a tool result straight into the model's context, so raise it
48
+ deliberately.
43
49
  - `EMAIL_ATTACHMENT_DIR` — directory that gates `send_email` file attachments. Path-based attachments (`attachments[].path`) are rejected unless this is set, and only files resolving inside it are allowed. Use `attachments[].content` for inline content without setting this.
44
50
  - `URL_RESOLVE_DISABLE` — set to `1`/`true` to skip network link-resolution when rendering email to markdown; links are left unresolved in the output.
45
51
  - `SMTP_AUTO_SENT` — set to `true` if your provider auto-files sent mail, so the server skips the extra IMAP append to Sent.
@@ -73,7 +79,7 @@ See [docs/tools/email-mcp.md](../../docs/tools/email-mcp.md) for full parameter
73
79
  | Tool | Description |
74
80
  |------|-------------|
75
81
  | `search_emails` | Search and filter emails by folder, sender, subject, date, flags |
76
- | `get_email` | Fetch full email by UID — headers, body, attachment metadata |
82
+ | `get_email` | Fetch full email by UID — headers, body, attachment metadata, calendar invitation parts |
77
83
  | `send_email` | Compose and send via SMTP, reply with threading, save as draft, or use an allowed visible From address |
78
84
  | `send_draft` | Send an existing draft from the Drafts folder |
79
85
  | `move_email` | Move emails between folders |
@@ -85,6 +91,51 @@ See [docs/tools/email-mcp.md](../../docs/tools/email-mcp.md) for full parameter
85
91
  | `get_email_raw` | Export email as raw .eml |
86
92
  | `get_folder_status` | Get total and unread message counts for a folder |
87
93
 
94
+ ## Resources
95
+
96
+ Attachments and message sources are addressable as `imap://` resources, not just
97
+ returned inline by a tool. A client that wants the bytes can fetch them with
98
+ `resources/read` on its own terms — which keeps a large payload out of the model's
99
+ context when only the file itself is wanted.
100
+
101
+ | URI template | Contents |
102
+ |--------------|----------|
103
+ | `imap://{folder}/{uid}/{partId}` | One attachment's bytes, under its own media type. Part IDs come from `get_email`'s attachment metadata. |
104
+ | `imap://{folder}/{uid}.eml` | The message's raw RFC 822 source. |
105
+
106
+ `download_attachment` and `get_email_raw` stamp these URIs onto whatever they return,
107
+ so a URI from a tool result can be read back directly. Under `EMAIL_MAX_INLINE_BYTES`
108
+ the payload is embedded as before; over it, the tool returns a `resource_link` and the
109
+ bytes stay one `resources/read` away instead of arriving as multi-megabyte base64.
110
+ Either way `structuredContent` carries the `uri` and an `embedded` flag saying which
111
+ happened.
112
+
113
+ The folder occupies the URI's authority and is percent-encoded whole, so a hierarchy
114
+ delimiter inside it survives: `Archive/2024` becomes `imap://Archive%2F2024/99/1.2`.
115
+ Folder case is preserved, because IMAP mailbox names are case-sensitive.
116
+
117
+ Neither template is enumerable — there is no `resources/list` entry for them, since
118
+ listing every attachment in an account would mean walking every message. Discover
119
+ them through `resources/templates/list`, and find part IDs with `get_email`.
120
+
121
+ ## Sending attachments
122
+
123
+ `send_email` takes attachments three ways:
124
+
125
+ | Field | Use for |
126
+ |-------|---------|
127
+ | `content` alone | Text. Read as UTF-8, so it **corrupts binary**. |
128
+ | `content` + `encoding: "base64"` | Binary — a PDF, an image, or bytes from `download_attachment`. |
129
+ | `path` | A file on the server, only inside `EMAIL_ATTACHMENT_DIR`. |
130
+
131
+ Set `contentType` when the filename has no extension to guess from.
132
+
133
+ This is what makes the download-then-forward round trip work without a configured
134
+ directory: `download_attachment` returns base64, and `encoding: "base64"` is where
135
+ it goes. Invalid base64 is rejected rather than attached — a payload that silently
136
+ decoded to fewer bytes would reach the recipient as a corrupt file with no error
137
+ anywhere.
138
+
88
139
  ## License
89
140
 
90
141
  MIT
@@ -1 +1 @@
1
- {"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,SAAS,EAAE,MAAM,8BAA8B,CAAC;AAUzD,wBAAsB,YAAY,IAAI,OAAO,CAAC,SAAS,CAAC,CA2BvD;AAED,wBAAsB,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC,CAOjD"}
1
+ {"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,SAAS,EAAE,MAAM,8BAA8B,CAAC;AAWzD,wBAAsB,YAAY,IAAI,OAAO,CAAC,SAAS,CAAC,CAiCvD;AAED,wBAAsB,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC,CAOjD"}
package/dist/main.js CHANGED
@@ -4,6 +4,7 @@ import { TOOL_LIST_CACHE_HINT, registerTools } from "@miguelarios/pim-core/mcp";
4
4
  import { McpServer } from "@modelcontextprotocol/server";
5
5
  import { serveStdio } from "@modelcontextprotocol/server/stdio";
6
6
  import { disposeUrlCleaner } from "./htmlToMarkdown.js";
7
+ import { registerImapResources } from "./resources/imapResources.js";
7
8
  import { ImapService } from "./services/ImapService.js";
8
9
  import { SmtpService } from "./services/SmtpService.js";
9
10
  import { EMAIL_TOOLS } from "./tools/emailTools.js";
@@ -16,11 +17,17 @@ export async function createServer() {
16
17
  smtp: new SmtpService(config),
17
18
  };
18
19
  const server = new McpServer({ name: "@miguelarios/email-mcp", title: "IMAP/SMTP Email", version }, {
19
- capabilities: { tools: { listChanged: false } },
20
- instructions: "Read, search and send email over IMAP/SMTP. Folder paths are IMAP paths and default to INBOX — call list_folders to discover them. send_email, send_draft and permanent deletes ask the user to confirm first.",
20
+ capabilities: {
21
+ tools: { listChanged: false },
22
+ // Attachment and message URIs are addressable but not enumerable, so
23
+ // there is no list to change.
24
+ resources: { listChanged: false },
25
+ },
26
+ instructions: "Read, search and send email over IMAP/SMTP. Folder paths are IMAP paths and default to INBOX — call list_folders to discover them. send_email, send_draft and permanent deletes ask the user to confirm first. Attachments and message sources are also addressable as imap:// resources, so their bytes can be fetched with resources/read instead of through a tool result.",
21
27
  cacheHints: { "tools/list": TOOL_LIST_CACHE_HINT },
22
28
  });
23
29
  registerTools(server, EMAIL_TOOLS, services);
30
+ registerImapResources(server, services.imap);
24
31
  const handleShutdown = async () => {
25
32
  await disposeUrlCleaner();
26
33
  process.exit(0);
package/dist/main.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"main.js","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,oBAAoB,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAChF,OAAO,EAAE,SAAS,EAAE,MAAM,8BAA8B,CAAC;AACzD,OAAO,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAChE,OAAO,EA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;IAEF,MAAM,MAAM,GAAG,IAAI,SAAS,CAC1B,EAAE,IAAI,EAAE,wBAAwB,EAAE,KAAK,EAAE,iBAAiB,EAAE,OAAO,EAAE,EACrE;QACE,YAAY,EAAE;YACZ,KAAK,EAAE,EAAE,WAAW,EAAE,KAAK,EAAE;YAC7B,qEAAqE;YACrE,8BAA8B;YAC9B,SAAS,EAAE,EAAE,WAAW,EAAE,KAAK,EAAE;SAClC;QACD,YAAY,EACV,+WAA+W;QACjX,UAAU,EAAE,EAAE,YAAY,EAAE,oBAAoB,EAAE;KACnD,CACF,CAAC;IAEF,aAAa,CAAC,MAAM,EAAE,WAAW,EAAE,QAAQ,CAAC,CAAC;IAC7C,qBAAqB,CAAC,MAAM,EAAE,QAAQ,CAAC,IAAI,CAAC,CAAC;IAE7C,MAAM,cAAc,GAAG,KAAK,IAAI,EAAE;QAChC,MAAM,iBAAiB,EAAE,CAAC;QAC1B,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,CAAC;IACF,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,cAAc,CAAC,CAAC;IACrC,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,cAAc,CAAC,CAAC;IAEtC,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,WAAW;IAC/B,uEAAuE;IACvE,yEAAyE;IACzE,UAAU,CAAC,GAAG,EAAE,CAAC,YAAY,EAAE,EAAE;QAC/B,OAAO,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,2BAA2B,EAAE,KAAK,CAAC,OAAO,CAAC;KAC9E,CAAC,CAAC;IACH,OAAO,CAAC,KAAK,CAAC,qCAAqC,CAAC,CAAC;AACvD,CAAC"}
@@ -0,0 +1,67 @@
1
+ import { type McpServer } from "@modelcontextprotocol/server";
2
+ import type { ImapService } from "../services/ImapService.js";
3
+ /** RFC 6570 template for one attachment: `imap://INBOX/4471/2`. */
4
+ export declare const ATTACHMENT_URI_TEMPLATE = "imap://{folder}/{uid}/{partId}";
5
+ /** RFC 6570 template for a message's RFC 822 source: `imap://INBOX/4471.eml`. */
6
+ export declare const RAW_EMAIL_URI_TEMPLATE = "imap://{folder}/{uid}.eml";
7
+ /** The IMAP surface these handlers need — narrowed so tests can pass a stub. */
8
+ type AttachmentReader = Pick<ImapService, "downloadAttachment">;
9
+ type RawEmailReader = Pick<ImapService, "fetchRawEmail">;
10
+ /**
11
+ * The URI for one attachment.
12
+ *
13
+ * The folder occupies the authority, so it is percent-encoded whole: an IMAP
14
+ * hierarchy delimiter inside it (`Archive/2024`) must not become a path
15
+ * separator, or the parse would read `2024` as the uid.
16
+ */
17
+ export declare function attachmentUri(folder: string, uid: number, partId: string): string;
18
+ /** The URI for a message's RFC 822 source. */
19
+ export declare function rawEmailUri(folder: string, uid: number): string;
20
+ /** What an `imap://` URI addresses, once parsed. */
21
+ export type ImapTarget = {
22
+ kind: "attachment";
23
+ folder: string;
24
+ uid: number;
25
+ partId: string;
26
+ } | {
27
+ kind: "raw";
28
+ folder: string;
29
+ uid: number;
30
+ };
31
+ /**
32
+ * Parses an `imap://` URI, or returns `undefined` when it is not one of ours.
33
+ *
34
+ * Parsing goes through `URL` rather than the template variables the SDK hands
35
+ * the read callback, so tool-minted and client-supplied URIs are read by the
36
+ * same code. `imap:` is not a WHATWG "special" scheme, so the authority keeps
37
+ * its case — which matters, because IMAP mailbox names are case-sensitive and
38
+ * an http-style lowercasing would silently retarget `INBOX` to `inbox`.
39
+ */
40
+ export declare function parseImapUri(uri: string | URL): ImapTarget | undefined;
41
+ /** Serves one attachment's bytes, base64-encoded under its own media type. */
42
+ export declare function readAttachmentResource(uri: URL, imap: AttachmentReader): Promise<{
43
+ contents: {
44
+ uri: string;
45
+ mimeType: string;
46
+ blob: string;
47
+ }[];
48
+ }>;
49
+ /** Serves a message's RFC 822 source. */
50
+ export declare function readRawEmailResource(uri: URL, imap: RawEmailReader): Promise<{
51
+ contents: {
52
+ uri: string;
53
+ mimeType: string;
54
+ text: string;
55
+ }[];
56
+ }>;
57
+ /**
58
+ * Registers both templates against an {@link McpServer}.
59
+ *
60
+ * Neither template gets a `list` callback: enumerating every attachment in an
61
+ * account would mean walking every message in every folder, and the useful
62
+ * entry point is `search_emails` / `get_email` anyway. Clients still discover
63
+ * the shapes through `resources/templates/list`.
64
+ */
65
+ export declare function registerImapResources(server: McpServer, imap: AttachmentReader & RawEmailReader): void;
66
+ export {};
67
+ //# sourceMappingURL=imapResources.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"imapResources.d.ts","sourceRoot":"","sources":["../../src/resources/imapResources.ts"],"names":[],"mappings":"AAeA,OAAO,EAAE,KAAK,SAAS,EAAoB,MAAM,8BAA8B,CAAC;AAChF,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAE9D,mEAAmE;AACnE,eAAO,MAAM,uBAAuB,mCAAmC,CAAC;AAExE,iFAAiF;AACjF,eAAO,MAAM,sBAAsB,8BAA8B,CAAC;AAElE,gFAAgF;AAChF,KAAK,gBAAgB,GAAG,IAAI,CAAC,WAAW,EAAE,oBAAoB,CAAC,CAAC;AAChE,KAAK,cAAc,GAAG,IAAI,CAAC,WAAW,EAAE,eAAe,CAAC,CAAC;AAEzD;;;;;;GAMG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAEjF;AAED,8CAA8C;AAC9C,wBAAgB,WAAW,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAE/D;AAED,oDAAoD;AACpD,MAAM,MAAM,UAAU,GAClB;IAAE,IAAI,EAAE,YAAY,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GACnE;IAAE,IAAI,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,CAAC;AAEjD;;;;;;;;GAQG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,GAAG,UAAU,GAAG,SAAS,CA6BtE;AAED,8EAA8E;AAC9E,wBAAsB,sBAAsB,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,gBAAgB;;;;;;GAmB5E;AAED,yCAAyC;AACzC,wBAAsB,oBAAoB,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,cAAc;;;;;;GAaxE;AAED;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CACnC,MAAM,EAAE,SAAS,EACjB,IAAI,EAAE,gBAAgB,GAAG,cAAc,GACtC,IAAI,CAsBN"}
@@ -0,0 +1,139 @@
1
+ /**
2
+ * `imap://` resource URIs, and the `resources/read` handlers behind them.
3
+ *
4
+ * `download_attachment` and `get_email_raw` have always stamped these URIs onto
5
+ * their embedded resource blocks, but nothing could resolve one — the URI was a
6
+ * label on a payload the client had already been handed. Registering them as
7
+ * real resources makes them addressable, so a client can fetch the bytes on its
8
+ * own terms instead of only ever receiving them inline.
9
+ *
10
+ * The URI shape is this server's own, not RFC 5092's `imap://` URL: there the
11
+ * authority names the *server*, because a URL has to be resolvable by a third
12
+ * party. These never leave the session that minted them, so the authority is
13
+ * spent on the mailbox instead, which is the part that varies per call.
14
+ */
15
+ import { EmailError, ErrorCode } from "@miguelarios/pim-core";
16
+ import { ResourceTemplate } from "@modelcontextprotocol/server";
17
+ /** RFC 6570 template for one attachment: `imap://INBOX/4471/2`. */
18
+ export const ATTACHMENT_URI_TEMPLATE = "imap://{folder}/{uid}/{partId}";
19
+ /** RFC 6570 template for a message's RFC 822 source: `imap://INBOX/4471.eml`. */
20
+ export const RAW_EMAIL_URI_TEMPLATE = "imap://{folder}/{uid}.eml";
21
+ /**
22
+ * The URI for one attachment.
23
+ *
24
+ * The folder occupies the authority, so it is percent-encoded whole: an IMAP
25
+ * hierarchy delimiter inside it (`Archive/2024`) must not become a path
26
+ * separator, or the parse would read `2024` as the uid.
27
+ */
28
+ export function attachmentUri(folder, uid, partId) {
29
+ return `imap://${encodeURIComponent(folder)}/${uid}/${encodeURIComponent(partId)}`;
30
+ }
31
+ /** The URI for a message's RFC 822 source. */
32
+ export function rawEmailUri(folder, uid) {
33
+ return `imap://${encodeURIComponent(folder)}/${uid}.eml`;
34
+ }
35
+ /**
36
+ * Parses an `imap://` URI, or returns `undefined` when it is not one of ours.
37
+ *
38
+ * Parsing goes through `URL` rather than the template variables the SDK hands
39
+ * the read callback, so tool-minted and client-supplied URIs are read by the
40
+ * same code. `imap:` is not a WHATWG "special" scheme, so the authority keeps
41
+ * its case — which matters, because IMAP mailbox names are case-sensitive and
42
+ * an http-style lowercasing would silently retarget `INBOX` to `inbox`.
43
+ */
44
+ export function parseImapUri(uri) {
45
+ let url;
46
+ try {
47
+ url = typeof uri === "string" ? new URL(uri) : uri;
48
+ }
49
+ catch {
50
+ return undefined;
51
+ }
52
+ if (url.protocol !== "imap:")
53
+ return undefined;
54
+ const folder = decodeSegment(url.host);
55
+ if (!folder)
56
+ return undefined;
57
+ const segments = url.pathname.replace(/^\//, "").split("/");
58
+ if (segments.length === 1) {
59
+ const raw = segments[0];
60
+ if (!raw.endsWith(".eml"))
61
+ return undefined;
62
+ const uid = parseUid(raw.slice(0, -".eml".length));
63
+ return uid === undefined ? undefined : { kind: "raw", folder, uid };
64
+ }
65
+ if (segments.length === 2) {
66
+ const uid = parseUid(segments[0]);
67
+ const partId = decodeSegment(segments[1]);
68
+ if (uid === undefined || !partId)
69
+ return undefined;
70
+ return { kind: "attachment", folder, uid, partId };
71
+ }
72
+ return undefined;
73
+ }
74
+ /** Serves one attachment's bytes, base64-encoded under its own media type. */
75
+ export async function readAttachmentResource(uri, imap) {
76
+ const target = parseImapUri(uri);
77
+ if (target?.kind !== "attachment") {
78
+ throw new EmailError(`${uri.href} is not a valid attachment URI — expected imap://<folder>/<uid>/<partId>`, ErrorCode.INVALID_INPUT);
79
+ }
80
+ const attachment = await imap.downloadAttachment(target.folder, target.uid, target.partId);
81
+ return {
82
+ contents: [
83
+ {
84
+ uri: uri.href,
85
+ mimeType: attachment.contentType,
86
+ blob: attachment.content.toString("base64"),
87
+ },
88
+ ],
89
+ };
90
+ }
91
+ /** Serves a message's RFC 822 source. */
92
+ export async function readRawEmailResource(uri, imap) {
93
+ const target = parseImapUri(uri);
94
+ if (target?.kind !== "raw") {
95
+ throw new EmailError(`${uri.href} is not a valid message URI — expected imap://<folder>/<uid>.eml`, ErrorCode.INVALID_INPUT);
96
+ }
97
+ const raw = await imap.fetchRawEmail(target.folder, target.uid);
98
+ return {
99
+ contents: [{ uri: uri.href, mimeType: "message/rfc822", text: raw }],
100
+ };
101
+ }
102
+ /**
103
+ * Registers both templates against an {@link McpServer}.
104
+ *
105
+ * Neither template gets a `list` callback: enumerating every attachment in an
106
+ * account would mean walking every message in every folder, and the useful
107
+ * entry point is `search_emails` / `get_email` anyway. Clients still discover
108
+ * the shapes through `resources/templates/list`.
109
+ */
110
+ export function registerImapResources(server, imap) {
111
+ server.registerResource("email-attachment", new ResourceTemplate(ATTACHMENT_URI_TEMPLATE, { list: undefined }), {
112
+ title: "Email Attachment",
113
+ description: "One attachment's bytes, addressed by folder, message UID and MIME part ID. Part IDs come from get_email's attachment metadata.",
114
+ }, (uri) => readAttachmentResource(uri, imap));
115
+ server.registerResource("email-source", new ResourceTemplate(RAW_EMAIL_URI_TEMPLATE, { list: undefined }), {
116
+ title: "Email Source",
117
+ description: "A message's raw RFC 822 source, addressed by folder and message UID.",
118
+ mimeType: "message/rfc822",
119
+ }, (uri) => readRawEmailResource(uri, imap));
120
+ }
121
+ /** A percent-decoded URI segment, or `undefined` when it is empty or malformed. */
122
+ function decodeSegment(segment) {
123
+ if (!segment)
124
+ return undefined;
125
+ try {
126
+ return decodeURIComponent(segment) || undefined;
127
+ }
128
+ catch {
129
+ return undefined;
130
+ }
131
+ }
132
+ /** A UID, or `undefined` unless the text is a plain positive integer. */
133
+ function parseUid(text) {
134
+ if (!/^\d+$/.test(text))
135
+ return undefined;
136
+ const uid = Number(text);
137
+ return uid > 0 ? uid : undefined;
138
+ }
139
+ //# sourceMappingURL=imapResources.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"imapResources.js","sourceRoot":"","sources":["../../src/resources/imapResources.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAC9D,OAAO,EAAkB,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAGhF,mEAAmE;AACnE,MAAM,CAAC,MAAM,uBAAuB,GAAG,gCAAgC,CAAC;AAExE,iFAAiF;AACjF,MAAM,CAAC,MAAM,sBAAsB,GAAG,2BAA2B,CAAC;AAMlE;;;;;;GAMG;AACH,MAAM,UAAU,aAAa,CAAC,MAAc,EAAE,GAAW,EAAE,MAAc;IACvE,OAAO,UAAU,kBAAkB,CAAC,MAAM,CAAC,IAAI,GAAG,IAAI,kBAAkB,CAAC,MAAM,CAAC,EAAE,CAAC;AACrF,CAAC;AAED,8CAA8C;AAC9C,MAAM,UAAU,WAAW,CAAC,MAAc,EAAE,GAAW;IACrD,OAAO,UAAU,kBAAkB,CAAC,MAAM,CAAC,IAAI,GAAG,MAAM,CAAC;AAC3D,CAAC;AAOD;;;;;;;;GAQG;AACH,MAAM,UAAU,YAAY,CAAC,GAAiB;IAC5C,IAAI,GAAQ,CAAC;IACb,IAAI,CAAC;QACH,GAAG,GAAG,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;IACrD,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,IAAI,GAAG,CAAC,QAAQ,KAA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,IAAI,gBAAgB,CAAC,uBAAuB,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC,EAClE;QACE,KAAK,EAAE,kBAAkB;QACzB,WAAW,EACT,gIAAgI;KACnI,EACD,CAAC,GAAG,EAAE,EAAE,CAAC,sBAAsB,CAAC,GAAG,EAAE,IAAI,CAAC,CAC3C,CAAC;IAEF,MAAM,CAAC,gBAAgB,CACrB,cAAc,EACd,IAAI,gBAAgB,CAAC,sBAAsB,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC,EACjE;QACE,KAAK,EAAE,cAAc;QACrB,WAAW,EAAE,sEAAsE;QACnF,QAAQ,EAAE,gBAAgB;KAC3B,EACD,CAAC,GAAG,EAAE,EAAE,CAAC,oBAAoB,CAAC,GAAG,EAAE,IAAI,CAAC,CACzC,CAAC;AACJ,CAAC;AAED,mFAAmF;AACnF,SAAS,aAAa,CAAC,OAAe;IACpC,IAAI,CAAC,OAAO;QAAE,OAAO,SAAS,CAAC;IAC/B,IAAI,CAAC;QACH,OAAO,kBAAkB,CAAC,OAAO,CAAC,IAAI,SAAS,CAAC;IAClD,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC;AAED,yEAAyE;AACzE,SAAS,QAAQ,CAAC,IAAY;IAC5B,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC;QAAE,OAAO,SAAS,CAAC;IAC1C,MAAM,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;IACzB,OAAO,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,SAAS,CAAC;AACnC,CAAC"}
@@ -32,18 +32,62 @@ export interface EmailFull extends EmailSummary {
32
32
  size: number;
33
33
  partId: string;
34
34
  }>;
35
+ /** Present only when the message carries `text/calendar` MIME parts. */
36
+ calendarParts?: CalendarPart[];
37
+ }
38
+ export interface CalendarPart {
39
+ partId: string;
40
+ contentType: string;
41
+ /** iTIP method from the Content-Type parameters, uppercased, e.g. "REQUEST". */
42
+ method: string | null;
43
+ filename: string | null;
44
+ /** Transfer-encoded size on the wire; may differ from `content.length`. */
45
+ size: number;
46
+ /** Decoded iCalendar text; absent when oversized or not correlatable. */
47
+ content?: string;
48
+ /** True when `content` was withheld — fetch via `download_attachment`. */
49
+ truncated?: boolean;
35
50
  }
36
51
  export interface FolderInfo {
37
52
  path: string;
38
53
  specialUse?: string;
39
54
  delimiter: string;
40
55
  }
41
- export interface AttachmentData {
56
+ /** What is known about an attachment without necessarily holding its bytes. */
57
+ export interface AttachmentMeta {
42
58
  filename: string;
43
59
  contentType: string;
60
+ /** Size in bytes as the server reports it, falling back to the fetched length. */
44
61
  size: number;
62
+ }
63
+ /** An attachment whose bytes were fetched. */
64
+ export interface AttachmentBytes extends AttachmentMeta {
65
+ oversized: false;
45
66
  content: Buffer;
46
67
  }
68
+ /**
69
+ * An attachment deliberately left on the server because it exceeded the
70
+ * caller's `maxBytes`. Its bytes remain reachable through `resources/read` on
71
+ * the matching `imap://` URI.
72
+ */
73
+ export interface AttachmentTooLarge extends AttachmentMeta {
74
+ oversized: true;
75
+ content?: undefined;
76
+ }
77
+ export type AttachmentDownload = AttachmentBytes | AttachmentTooLarge;
78
+ /** A message source that was fetched. */
79
+ export interface RawEmailSource {
80
+ size: number;
81
+ oversized: false;
82
+ source: string;
83
+ }
84
+ /** A message source left on the server for exceeding the caller's `maxBytes`. */
85
+ export interface RawEmailTooLarge {
86
+ size: number;
87
+ oversized: true;
88
+ source?: undefined;
89
+ }
90
+ export type RawEmailResult = RawEmailSource | RawEmailTooLarge;
47
91
  export interface SearchOptions {
48
92
  limit?: number;
49
93
  offset?: number;
@@ -60,11 +104,13 @@ export declare class ImapService {
60
104
  private fetchSummaries;
61
105
  fetchEmail(folder: string, uid: number): Promise<EmailFull>;
62
106
  fetchRawEmail(folder: string, uid: number): Promise<string>;
107
+ fetchRawEmail(folder: string, uid: number, maxBytes: number): Promise<RawEmailResult>;
63
108
  moveEmails(folder: string, uids: number[], destination: string): Promise<void>;
64
109
  markEmails(folder: string, uids: number[], flags: string[], action: "add" | "remove"): Promise<void>;
65
110
  deleteEmails(folder: string, uids: number[], permanent?: boolean): Promise<void>;
66
111
  createFolder(path: string): Promise<void>;
67
- downloadAttachment(folder: string, uid: number, partId: string): Promise<AttachmentData>;
112
+ downloadAttachment(folder: string, uid: number, partId: string): Promise<AttachmentBytes>;
113
+ downloadAttachment(folder: string, uid: number, partId: string, maxBytes: number): Promise<AttachmentDownload>;
68
114
  private static FALLBACK_NAMES;
69
115
  private specialUseCache;
70
116
  getSpecialUseFolder(flag: string): Promise<string>;
@@ -1 +1 @@
1
- {"version":3,"file":"ImapService.d.ts","sourceRoot":"","sources":["../../src/services/ImapService.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,WAAW,EAMjB,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EAAE,KAAK,YAAY,EAAuB,MAAM,cAAc,CAAC;AAEtE,MAAM,WAAW,YAAY;IAC3B,GAAG,EAAE,MAAM,CAAC;IACZ,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC;IACzC,EAAE,EAAE,KAAK,CAAC;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAC9C,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,cAAc,EAAE,OAAO,CAAC;CACzB;AAED,MAAM,WAAW,SAAU,SAAQ,YAAY;IAC7C,EAAE,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAC/C,SAAS,EAAE,MAAM,GAA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,CAAC,IAAI,CAAC;IAYzC,kBAAkB,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,CAAC;IACzF,kBAAkB,CACtB,MAAM,EAAE,MAAM,EACd,GAAG,EAAE,MAAM,EACX,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,MAAM,GACf,OAAO,CAAC,kBAAkB,CAAC;IA6D9B,OAAO,CAAC,MAAM,CAAC,cAAc,CAI3B;IAEF,OAAO,CAAC,eAAe,CAA6B;IAE9C,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAsClD,aAAa,CACjB,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,MAAM,EACjB,KAAK,EAAE,MAAM,EAAE,GACd,OAAO,CAAC;QAAE,GAAG,EAAE,MAAM,CAAA;KAAE,CAAC;IAcrB,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAwB5D,eAAe,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC;CAYlF"}
@@ -139,6 +139,7 @@ export class ImapService {
139
139
  }
140
140
  const parsed = await simpleParser(fetchResult.source);
141
141
  const attachmentParts = collectAttachmentParts(fetchResult.bodyStructure);
142
+ const calendarParts = buildCalendarParts(attachmentParts, parsed.attachments ?? []);
142
143
  return {
143
144
  uid,
144
145
  messageId: parsed.messageId || "",
@@ -172,6 +173,7 @@ export class ImapService {
172
173
  size: att.size,
173
174
  partId: att.part,
174
175
  })),
176
+ ...(calendarParts.length > 0 ? { calendarParts } : {}),
175
177
  };
176
178
  }
177
179
  finally {
@@ -187,17 +189,35 @@ export class ImapService {
187
189
  await client.logout().catch(() => { });
188
190
  }
189
191
  }
190
- async fetchRawEmail(folder, uid) {
192
+ async fetchRawEmail(folder, uid, maxBytes) {
191
193
  const client = this.createClient();
192
194
  try {
193
195
  await client.connect();
194
196
  const lock = await client.getMailboxLock(folder);
195
197
  try {
198
+ if (maxBytes !== undefined) {
199
+ // RFC822.SIZE is a single cheap FETCH item, so an oversized message
200
+ // is identified without pulling its body across the wire at all.
201
+ const stat = await client.fetchOne(String(uid), { size: true }, { uid: true });
202
+ if (!stat) {
203
+ throw new EmailError(`Email UID ${uid} not found`, ErrorCode.EMAIL_NOT_FOUND, uid);
204
+ }
205
+ if (typeof stat.size === "number" && stat.size > maxBytes) {
206
+ return { size: stat.size, oversized: true };
207
+ }
208
+ }
196
209
  const fetchResult = await client.fetchOne(String(uid), { source: true }, { uid: true });
197
210
  if (!fetchResult || !fetchResult.source) {
198
211
  throw new EmailError(`Email UID ${uid} not found`, ErrorCode.EMAIL_NOT_FOUND, uid);
199
212
  }
200
- return fetchResult.source.toString();
213
+ const source = fetchResult.source.toString();
214
+ if (maxBytes === undefined)
215
+ return source;
216
+ // A server that withheld RFC822.SIZE is still held to the ceiling, just
217
+ // after the fetch rather than before it.
218
+ return source.length > maxBytes
219
+ ? { size: source.length, oversized: true }
220
+ : { size: source.length, oversized: false, source };
201
221
  }
202
222
  finally {
203
223
  lock.release();
@@ -299,7 +319,7 @@ export class ImapService {
299
319
  await client.logout().catch(() => { });
300
320
  }
301
321
  }
302
- async downloadAttachment(folder, uid, partId) {
322
+ async downloadAttachment(folder, uid, partId, maxBytes) {
303
323
  const client = this.createClient();
304
324
  try {
305
325
  await client.connect();
@@ -309,16 +329,32 @@ export class ImapService {
309
329
  if (!content) {
310
330
  throw new EmailError(`Attachment ${partId} not found for email ${uid}`, ErrorCode.ATTACHMENT_NOT_FOUND, uid);
311
331
  }
332
+ const attachment = {
333
+ filename: meta.filename || `attachment-${partId}`,
334
+ contentType: meta.contentType || "application/octet-stream",
335
+ };
336
+ if (maxBytes !== undefined && meta.expectedSize && meta.expectedSize > maxBytes) {
337
+ // The size came from BODYSTRUCTURE, so it is known before the body is
338
+ // read. Draining a stream we are about to discard is precisely the
339
+ // cost this ceiling exists to avoid, so the stream is dropped instead.
340
+ // Abandoning it mid-literal would leave the connection out of step,
341
+ // but `createClient` opens a fresh one per call and the `finally`
342
+ // below logs this one out, so it is never reused.
343
+ content.destroy?.();
344
+ return { ...attachment, size: meta.expectedSize, oversized: true };
345
+ }
312
346
  const chunks = [];
313
347
  for await (const chunk of content) {
314
348
  chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
315
349
  }
316
- return {
317
- filename: meta.filename || `attachment-${partId}`,
318
- contentType: meta.contentType || "application/octet-stream",
319
- size: meta.expectedSize || Buffer.concat(chunks).length,
320
- content: Buffer.concat(chunks),
321
- };
350
+ const buffer = Buffer.concat(chunks);
351
+ const size = meta.expectedSize || buffer.length;
352
+ // A server that withheld the expected size is still held to the
353
+ // ceiling; only the network saving is lost, not the context saving.
354
+ if (maxBytes !== undefined && size > maxBytes) {
355
+ return { ...attachment, size, oversized: true };
356
+ }
357
+ return { ...attachment, size, oversized: false, content: buffer };
322
358
  }
323
359
  finally {
324
360
  lock.release();
@@ -465,14 +501,65 @@ function collectAttachmentParts(node, out = []) {
465
501
  const type = String(node.type ?? "").toLowerCase();
466
502
  if (type.startsWith("multipart/"))
467
503
  return out;
468
- if (disposition === "attachment" || (filename && disposition !== "inline")) {
504
+ // Calendar invitations are often delivered inline with no filename or
505
+ // disposition, so text/calendar collects unconditionally.
506
+ const isCalendar = type === "text/calendar";
507
+ if (disposition === "attachment" || (filename && disposition !== "inline") || isCalendar) {
469
508
  out.push({
470
509
  part: String(node.part ?? "1"),
471
510
  filename,
472
511
  contentType: node.type || "application/octet-stream",
473
512
  size: node.size ?? 0,
513
+ method: isCalendar ? (node.parameters?.method ?? undefined) : undefined,
514
+ charset: isCalendar ? (node.parameters?.charset ?? undefined) : undefined,
474
515
  });
475
516
  }
476
517
  return out;
477
518
  }
519
+ const MAX_INLINE_CALENDAR_BYTES = 256 * 1024;
520
+ function buildCalendarParts(attachmentParts, parsedAttachments) {
521
+ const structureParts = attachmentParts.filter((att) => att.contentType.toLowerCase() === "text/calendar");
522
+ if (structureParts.length === 0)
523
+ return [];
524
+ const decodedParts = parsedAttachments.filter((att) => (att.contentType ?? "").toLowerCase() === "text/calendar");
525
+ // Both the BODYSTRUCTURE walk and mailparser emit parts in document order,
526
+ // so equal counts pair up by index. On a mismatch, return metadata only and
527
+ // let download_attachment provide the bytes.
528
+ const correlated = decodedParts.length === structureParts.length;
529
+ return structureParts.map((att, index) => {
530
+ const part = {
531
+ partId: att.part,
532
+ contentType: att.contentType,
533
+ method: att.method ? att.method.toUpperCase() : null,
534
+ filename: att.filename ?? null,
535
+ size: att.size,
536
+ };
537
+ if (correlated) {
538
+ const content = decodedParts[index].content;
539
+ if (content.length > MAX_INLINE_CALENDAR_BYTES) {
540
+ // A mid-file cut would be syntactically broken ICS, so withhold instead.
541
+ part.truncated = true;
542
+ }
543
+ else {
544
+ part.content = decodeText(content, att.charset);
545
+ }
546
+ }
547
+ return part;
548
+ });
549
+ }
550
+ /**
551
+ * mailparser leaves attachment bytes charset-undecoded, so honor the part's
552
+ * declared charset (e.g. ISO-8859-1 from older Exchange senders).
553
+ */
554
+ function decodeText(buffer, charset) {
555
+ if (charset) {
556
+ try {
557
+ return new TextDecoder(charset).decode(buffer);
558
+ }
559
+ catch {
560
+ // Unknown charset label — fall through to UTF-8.
561
+ }
562
+ }
563
+ return buffer.toString("utf-8");
564
+ }
478
565
  //# sourceMappingURL=ImapService.js.map