@mindstone/mcp-server-microsoft-mail 0.1.2 → 0.3.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
@@ -6,6 +6,63 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/)
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.3.0] - 2026-08-06
10
+
11
+ ### Changed
12
+
13
+ - Add attachments, draft lifecycle, triage, threads, BCC, OOF; Graph filter/orderby fix; staging-dir downloads; Zod boundaries; four hardening rounds
14
+
15
+ ### Added
16
+
17
+ - `list_attachments` tool: lists attachment metadata (ID, name, type, size) for a message, so agents can act on `hasAttachments` instead of dead-ending.
18
+ - `download_attachment` tool: saves a file attachment into `MCP_WORKSPACE_PATH` (or the OS temp directory when unset) with canonical-prefix containment, filename sanitization, a 25 MB cap, and clear guidance for embedded-message/reference attachments that Graph does not inline.
19
+ - `MCP_WORKSPACE_PATH` optional environment variable declared in `server.json`.
20
+ - `send_draft` tool: sends an existing draft (`POST /me/messages/{id}/send`), completing the draft lifecycle that previously dead-ended after `create_draft`/`create_reply_draft`.
21
+ - `update_draft` tool: patches a draft's subject, body, to/cc recipients, or importance before sending.
22
+ - `mark_email_read` tool: marks an email read or unread.
23
+ - `set_email_flag` tool: flags an email for follow-up, marks it complete, or clears the flag.
24
+ - `get_conversation` tool: lists every message in a thread (oldest first) from a message ID or conversationId.
25
+ - `bcc` parameter on `send_email`, `compose_email`, and `create_draft`; the compose view now renders a BCC row (regenerated from `@mindstone/mcp-app-compose`).
26
+ - `get_automatic_replies` and `set_automatic_replies` tools: read and set the out-of-office configuration via `mailboxSettings`, including scheduled windows. Both require the `MailboxSettings.Read`/`MailboxSettings.ReadWrite` Graph permissions; when the connected account lacks them the tools return an admin-consent-aware guidance envelope instead of a raw Graph 403.
27
+
28
+ ### Changed
29
+
30
+ - Graph responses for the new tools (and `create_draft`) are validated with Zod at the boundary instead of cast, per the planned tightening noted in 0.1.1; pre-existing read tools still cast and remain tracked as planned debt.
31
+ - Each successful `download_attachment` save leaves its private staging directory (`microsoft-mail-attachment-*`) under the workspace root in place — by design, so the saved file survives — but repeated downloads accumulate directories there; prune them as part of normal workspace housekeeping.
32
+
33
+ ### Fixed
34
+
35
+ - `get_conversation` and `list_emails` (when a `filter` is supplied) no longer send `$orderby` alongside `$filter`: Microsoft Graph rejects that combination with HTTP 400 `InefficientFilter`, which made `get_conversation` fail on every live call and `list_emails` fail for any filtered query. Results are now sorted client-side by `receivedDateTime` (oldest first for conversations, newest first for `list_emails`). Note the sort is page-local: Graph applies `$top` before the client-side sort, so a filtered result is the sorted view of the returned page rather than a globally ordered scan (now documented in the README). The unfiltered `list_emails` path still lets Graph sort server-side.
36
+ - Error guidance for Graph's `InefficientFilter` rejection now names the actual cause (the filter is too complex, e.g. combined with a sort order) and suggests simplifying or removing the `filter`, instead of pointing at retry/re-authentication, which cannot resolve this failure class.
37
+ - A Graph response that fails Zod boundary validation is now always classified as a schema-validation failure, even when the attacker's value embedded in the Zod error text happens to contain the `InefficientFilter` trigger phrase; previously the filter check ran first on the raw error message and could misroute such a failure (and its raw issue details) down the filter path.
38
+ - A non-2xx response on the `download_attachment` content or metadata stream now surfaces the upstream error detail (enveloped as untrusted content) instead of degrading to a bare `Microsoft Graph API error (HTTP <status>)` — or, for 403s, an empty envelope: the Graph SDK throws these errors with the response body still an unread stream, which is now drained (with a hard byte cap) into text before classification, also releasing the underlying socket.
39
+ - Generic non-auth failures (filesystem errors, malformed Graph responses, validation failures) no longer mention re-authentication at all; the guidance now covers retry and argument verification only, and the failures where re-authentication genuinely helps are routed to the dedicated auth-required response. Graph 403 permission denials on the generic path are answered with connector-local guidance explaining that re-authenticating the same account will not change the outcome (previously the shared formatter advised disconnecting and reconnecting the account on every 403).
40
+ - `set_automatic_replies` scheduled windows are validated and normalized: inputs must be ISO 8601 date-times, explicit offsets are converted to UTC (previously an offset such as `+02:00` was passed through verbatim while declaring `timeZone: 'UTC'`, mislabeling the instant), and a start that is not earlier than the end is rejected before calling Graph.
41
+ - Recipient fields (`to`/`cc`/`bcc` on `send_email`, `compose_email`, `create_draft`, `update_draft`, `forward_email`) now require trimmed, well-formed email addresses (max 254 chars each, max 500 per field) instead of accepting arbitrary strings.
42
+
43
+ ### Security
44
+
45
+ - `download_attachment` no longer materializes the full attachment JSON (with inline base64 `contentBytes`) in memory: metadata is fetched without `contentBytes`, an oversized declared size is rejected up front, and the bytes are streamed from the `$value` endpoint with a hard 25 MB cap that aborts the stream the moment it is exceeded.
46
+ - `download_attachment` now writes with an atomic exclusive create (`O_CREAT|O_EXCL` through the opened file descriptor) instead of a check-then-`writeFile` sequence, so a symlink or hardlink planted at the destination path can no longer cause an arbitrary file overwrite.
47
+ - Attacker-controlled attachment names are now wrapped in an untrusted-content envelope on every `download_attachment` error path (previously interpolated raw into model-visible error text).
48
+ - Graph responses that fail Zod boundary validation no longer echo raw issue details (which can contain attacker-controlled values) into model-visible error text; the failure class is reported and field paths are logged locally instead.
49
+ - `download_attachment` now stages every save in a fresh, unpredictable private directory created atomically with `fs.mkdtemp` (mode `0700`) directly under the canonical (symlink-resolved) workspace root, carrying over only the attachment file name; `savedTo` reports the path inside that staging directory. Because the connector invents the directory name, there is no validated user-visible pathname for a local attacker to pre-plant, rename, or symlink-swap between validation and the write syscall — the parent-directory check-then-use race is removed by construction, with no descriptor-relative APIs, so the tool saves safely on every platform (this supersedes the interim descriptor-pinning approach, which had to refuse non-Linux saves outright). The file is created with `O_CREAT|O_EXCL` (mode `0600`), so a pre-existing same-named file or symlink is never touched and overwrite is impossible; a failed write removes its whole staging directory, leaving no residue.
50
+ - `download_attachment` metadata responses are now streamed with a hard 1 MB cap instead of being materialized as unbounded JSON (`$select` is not a transport limit), and a non-JSON metadata body fails closed with a trusted message rather than a parse error that can echo upstream body fragments.
51
+ - Auth-classified Graph errors (consent/tenant 403s, expired tokens) now wrap the formatted upstream error message in an untrusted-content envelope on the `auth_required` response path; previously the shared formatter's output — which embeds the upstream Graph error-body message raw — was passed into model-visible JSON unwrapped.
52
+ - Attacker-controlled attachment `@odata.type` and `contentType` values are now wrapped in untrusted-content envelopes everywhere they surface (previously interpolated raw in the unsupported-type error and returned raw by both attachment tools), and upstream Graph error-body messages on the generic failure path are enveloped instead of interpolated raw.
53
+ - `download_attachment`'s success message no longer echoes the attachment file name: the filename sanitizer constrains the name lexically (no separators, `..`, leading dots, NUL) but cannot neutralize attacker-authored prose, so the message now names only the connector-invented staging directory. `savedTo` still reports the real path (the host needs it), and the raw name surfaces only inside the untrusted-content envelope.
54
+ - The `download_attachment` metadata `$select` now explicitly requests `@odata.type`: the not-a-file-attachment guard reads that annotation, so the request must ask for it rather than rely on the server's default projection (a server omitting it would have silently failed the guard open).
55
+
56
+ ## [0.2.0] - 2026-07-29
57
+
58
+ ### Changed
59
+
60
+ - Add compose_email interactive draft view (MCP App iframe) via the shared mcp-app-compose generator
61
+
62
+ ### Added
63
+
64
+ - `compose_email` tool: opens an editable draft in an interactive compose view (MCP App served at `ui://microsoft-mail/compose-email`) so the user reviews and edits before the form itself calls `send_email`. The view HTML is generated at build time from the shared `@mindstone/mcp-app-compose` package (CC but no BCC — `send_email` has no BCC parameter — and no provider deep link), with a `--check` drift gate wired into `pretest`.
65
+
9
66
  ## [0.1.2] - 2026-07-03
10
67
 
11
68
  ### Changed
package/README.md CHANGED
@@ -3,15 +3,15 @@
3
3
  [![npm version](https://img.shields.io/npm/v/@mindstone/mcp-server-microsoft-mail.svg)](https://www.npmjs.com/package/@mindstone/mcp-server-microsoft-mail)
4
4
  [![License: FSL-1.1-MIT](https://img.shields.io/badge/License-FSL--1.1--MIT-blue.svg)](./LICENSE)
5
5
 
6
- Microsoft 365 Outlook Mail MCP server — list, search, read, send, reply, forward, draft, move, and delete email via the Microsoft Graph API.
6
+ Microsoft 365 Outlook Mail MCP server — list, search, read, send, reply, forward, draft, move, and delete email, download attachments, read threads, triage (read/flag), and manage out-of-office replies via the Microsoft Graph API.
7
7
 
8
8
  *Cohort-style Microsoft 365 mail MCP. Host owns the OAuth flow, this server reads per-account tokens off disk, and each tool fails closed with a structured `auth_required` envelope so the host can drive reauth.*
9
9
 
10
10
  ## Status
11
11
 
12
- - **Version:** [0.1.2](./CHANGELOG.md) · [npm](https://www.npmjs.com/package/@mindstone/mcp-server-microsoft-mail)
12
+ - **Version:** [0.3.0](./CHANGELOG.md) · [npm](https://www.npmjs.com/package/@mindstone/mcp-server-microsoft-mail)
13
13
  - **Auth:** OAuth (host-orchestrated) ([`MS_CLIENT_ID`](./server.json))
14
- - **Tools:** [12](./src/tools.ts) (messages, folders, drafts)
14
+ - **Tools:** [22](./src/tools.ts) (messages, folders, drafts, attachments, threads, settings)
15
15
  - **Surface:** cloud-api
16
16
  - **Machine-readable:** [`STATUS.json`](./STATUS.json)
17
17
  - **Shared library:** [`@mindstone/mcp-server-microsoft-shared`](https://www.npmjs.com/package/@mindstone/mcp-server-microsoft-shared)
@@ -129,6 +129,7 @@ This server runs alongside a host application that owns the Microsoft 365 OAuth
129
129
  | `MS_MCP_PACKAGE_ID` | Logical package ID surfaced in error responses. | `Microsoft365Mail` |
130
130
  | `MICROSOFT_REQUEST_TIMEOUT_MS` | Override the upstream Microsoft Graph request timeout (max `300000` ms). | `60000` |
131
131
  | `MICROSOFT_DISABLE_REFRESH` | Set to `1` to disable token refresh on this surface. Tools fail closed with the structured `auth_required` response so the host can drive reauth. Cloud surfaces set this to `1`. | unset |
132
+ | `MCP_WORKSPACE_PATH` | Workspace root where `download_attachment` saves files. | OS temp directory |
132
133
 
133
134
  ## Host configuration examples
134
135
 
@@ -168,22 +169,42 @@ Until the host has written `${MS_CONFIG_DIR}/credentials/<account>.token.json` a
168
169
  }
169
170
  ```
170
171
 
171
- ## Tools (12)
172
+ ## Tools (22)
172
173
 
173
174
  | Tool | Description |
174
175
  | ---- | ----------- |
175
176
  | `authenticate_microsoft_account` | Emit the structured `auth_required` handoff so the host runs the Microsoft 365 OAuth flow. |
176
- | `list_emails` | List emails in a folder, ordered by most recent. |
177
+ | `list_emails` | List emails in a folder, ordered by most recent (see ordering note below). |
177
178
  | `get_email` | Read a single email by message ID. |
178
- | `send_email` | Send a new email message. |
179
+ | `list_attachments` | List attachment metadata (ID, name, type, size) for a message. |
180
+ | `download_attachment` | Save a file attachment into the workspace (or OS temp directory). |
181
+ | `send_email` | Send a new email message (supports CC and BCC). |
182
+ | `compose_email` | Open an editable draft in an interactive compose view; nothing is sent until the user clicks Send. |
179
183
  | `search_emails` | Search emails using Microsoft Search syntax. |
184
+ | `get_conversation` | List messages in a thread, oldest first (see ordering note below). |
180
185
  | `reply_to_email` | Reply (or reply-all) to an existing email. |
181
186
  | `forward_email` | Forward an email to additional recipients. |
182
187
  | `delete_email` | Move an email to Deleted Items, or hard-delete it. |
183
188
  | `list_folders` | List mail folders. |
184
189
  | `move_email` | Move an email to a different folder. |
185
190
  | `create_reply_draft` | Save a draft reply to an existing email. |
186
- | `create_draft` | Save a new standalone draft email. |
191
+ | `create_draft` | Save a new standalone draft email (supports CC and BCC). |
192
+ | `send_draft` | Send an existing draft. |
193
+ | `update_draft` | Update a draft's subject, body, recipients, or importance. |
194
+ | `mark_email_read` | Mark an email as read or unread. |
195
+ | `set_email_flag` | Flag an email for follow-up, complete it, or clear the flag. |
196
+ | `get_automatic_replies` | Read the out-of-office configuration (requires `MailboxSettings.Read`). |
197
+ | `set_automatic_replies` | Turn out-of-office replies on/off or schedule them (requires `MailboxSettings.ReadWrite`). |
198
+
199
+ ### Graph permissions
200
+
201
+ Mail tools run on the `Mail.ReadWrite` + `Mail.Send` delegated grants. The automatic-replies tools additionally need `MailboxSettings.Read` / `MailboxSettings.ReadWrite`; in many organizations an administrator must approve that permission, and the tools return a guidance envelope (rather than a raw Graph 403) when the connected account lacks it.
202
+
203
+ ### Ordering and validation notes
204
+
205
+ - **Filtered listing is page-local.** Microsoft Graph rejects `$filter` combined with `$orderby`, so when `list_emails` is called with a `filter` (and always for `get_conversation`) the connector sorts only the returned page client-side: Graph applies `$top` first, so the result is the sorted view of whichever page Graph returned, not a globally ordered scan of the mailbox. Unfiltered `list_emails` still sorts server-side.
206
+ - **Recipients are validated.** `to`/`cc`/`bcc` entries must be email addresses (trimmed, max 254 chars, max 500 recipients per field); invalid entries are rejected before any Graph call.
207
+ - **Scheduled out-of-office windows** require ISO 8601 date-times; explicit offsets are converted to UTC (zone-less values are treated as UTC) and the start must be earlier than the end.
187
208
 
188
209
  ## Security notes
189
210
 
@@ -191,6 +212,8 @@ Until the host has written `${MS_CONFIG_DIR}/credentials/<account>.token.json` a
191
212
  - `MICROSOFT_DISABLE_REFRESH=1` is the default on cloud surfaces so the desktop session remains the sole refresh-token authority and avoids racing for single-use refresh tokens.
192
213
  - Successful tool responses drop the OSS-only `ok:true` wrapper to match the bundled `successResult` shape; manual validation/business errors return `isError:true` with a `{ ok:false, error, action_required, next_step }` payload so the host's recovery layer can act on them.
193
214
  - Per-tool Graph calls run under a composed caller + cohort timeout signal via `.options({signal})` plus a `Promise.race` wrapper for defence-in-depth.
215
+ - `download_attachment` writes only inside `MCP_WORKSPACE_PATH` (or the OS temp directory when unset), rejects anything but a plain filename, and caps downloads at 25 MB. Attachment bytes are streamed from the `$value` endpoint with a hard byte cap (never fully materialized past the limit), metadata is streamed with a hard 1 MB cap for the same reason, and the workspace root is canonicalised (symlinks resolved) before anything is written. Each download is saved into a fresh, private staging directory created atomically (`fs.mkdtemp`, mode `0700`) directly under the canonical workspace root, carrying over only the attachment file name; the reported `savedTo` points inside that staging directory. Because the connector invents the directory name, there is no validated user-visible pathname to pre-plant, rename, or symlink-swap between validation and the write syscall, so the parent-directory check-then-use race is removed by construction — on every platform, with no descriptor-relative APIs. The file itself is created with an exclusive open (`O_CREAT|O_EXCL`, mode `0600`), so overwrite is impossible and a pre-existing same-named file or symlink is never touched; a failed write removes its whole staging directory, leaving no residue. Attacker-controlled attachment fields (name, type, content type) are wrapped in untrusted-content envelopes wherever they surface as text, including error paths. `savedTo` necessarily reports the real file path (the host needs it to open the file), but the human-facing `message` names only the connector-invented staging directory, so the attacker-authored file name is never echoed as trusted prose.
216
+ - Error guidance for non-authentication failures never recommends re-authentication: Graph 403 permission denials are answered with connector-local guidance explaining that re-authenticating the same account will not help, and upstream Graph error text is enveloped as untrusted content before it reaches the model.
194
217
 
195
218
  ## Licence
196
219
 
@@ -0,0 +1,54 @@
1
+ import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
2
+ /**
3
+ * compose_email: returns an editable draft rendered by the host as an
4
+ * interactive MCP-App view (the compose-email iframe). Performs no Graph
5
+ * calls — the iframe invokes send_email itself when the user clicks Send.
6
+ *
7
+ * The `_meta.ui` producer contract below is shared with the Gmail
8
+ * compose_workspace_email tool; the helpers are vendored from there (each
9
+ * connector is an independent package — no cross-connector imports) and the
10
+ * two must stay field-for-field identical apart from the resource URI.
11
+ */
12
+ export declare const COMPOSE_EMAIL_RESOURCE_URI = "ui://microsoft-mail/compose-email";
13
+ export interface ComposeEmailParams {
14
+ to: string[];
15
+ cc?: string[];
16
+ bcc?: string[];
17
+ subject: string;
18
+ body: string;
19
+ }
20
+ interface ComposeEmailResult extends CallToolResult {
21
+ content: Array<{
22
+ type: 'text';
23
+ text: string;
24
+ }>;
25
+ _meta: {
26
+ ui: {
27
+ resourceUri: string;
28
+ presentation: 'primary';
29
+ viewSummary: string;
30
+ viewRoleLabel: string;
31
+ structuredFallback: {
32
+ kind: 'email-draft';
33
+ payload: {
34
+ to: string[];
35
+ cc: string[];
36
+ bcc: string[];
37
+ subject: string;
38
+ body: string;
39
+ };
40
+ };
41
+ };
42
+ };
43
+ structuredContent: {
44
+ to: string[];
45
+ cc: string[];
46
+ bcc: string[];
47
+ subject: string;
48
+ body: string;
49
+ email: string;
50
+ };
51
+ }
52
+ export declare function handleComposeEmail(params: ComposeEmailParams): Promise<ComposeEmailResult>;
53
+ export {};
54
+ //# sourceMappingURL=compose.d.ts.map
@@ -0,0 +1,70 @@
1
+ import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
2
+ /**
3
+ * compose_email: returns an editable draft rendered by the host as an
4
+ * interactive MCP-App view (the compose-email iframe). Performs no Graph
5
+ * calls — the iframe invokes send_email itself when the user clicks Send.
6
+ *
7
+ * The `_meta.ui` producer contract below is shared with the Gmail
8
+ * compose_workspace_email tool; the helpers are vendored from there (each
9
+ * connector is an independent package — no cross-connector imports) and the
10
+ * two must stay field-for-field identical apart from the resource URI.
11
+ */
12
+ export const COMPOSE_EMAIL_RESOURCE_URI = 'ui://microsoft-mail/compose-email';
13
+ const ANSI_ESCAPE_SEQUENCE_PATTERN = /\x1b\[[0-?]*[ -/]*[@-~]/g;
14
+ const HTML_TAG_PATTERN = /<[^>]*>/g;
15
+ function truncateText(value, maxChars) {
16
+ if (value.length <= maxChars)
17
+ return value;
18
+ return `${value.slice(0, Math.max(0, maxChars - 1))}…`;
19
+ }
20
+ function sanitizeViewSummaryPart(value) {
21
+ return value
22
+ .replace(ANSI_ESCAPE_SEQUENCE_PATTERN, '')
23
+ .replace(HTML_TAG_PATTERN, '')
24
+ .trim();
25
+ }
26
+ export async function handleComposeEmail(params) {
27
+ const nonEmpty = (addrs) => Array.isArray(addrs)
28
+ ? addrs.filter((addr) => typeof addr === 'string' && addr.trim().length > 0)
29
+ : [];
30
+ const to = nonEmpty(params.to);
31
+ const cc = nonEmpty(params.cc);
32
+ const bcc = nonEmpty(params.bcc);
33
+ const subject = typeof params.subject === 'string' ? params.subject : '';
34
+ const body = typeof params.body === 'string' ? params.body : '';
35
+ if (to.length === 0 || subject.trim().length === 0 || body.trim().length === 0) {
36
+ throw new McpError(ErrorCode.InvalidParams, 'compose_email requires non-empty "to" (at least one recipient), "subject", and "body". Provide all three so the editable draft has content for the user to review.');
37
+ }
38
+ // The connector's only account identity; when absent the iframe's
39
+ // From-missing helper tells the user to recreate the draft.
40
+ const email = (process.env.MS_ACCOUNT_EMAIL ?? '').trim();
41
+ const recipientSummary = to.length > 0 ? to.join(', ') : '(no recipients)';
42
+ const fallbackSubject = truncateText(subject, 256);
43
+ const fallbackBody = truncateText(body, 5_000);
44
+ const viewSummaryRecipient = truncateText(sanitizeViewSummaryPart(recipientSummary), 120);
45
+ const viewSummarySubject = truncateText(sanitizeViewSummaryPart(subject), 120);
46
+ const viewSummary = truncateText(`Email draft to ${viewSummaryRecipient || '(no recipients)'} — subject "${viewSummarySubject}".`, 280);
47
+ const draftData = { to, cc, bcc, subject, body, email };
48
+ return {
49
+ content: [
50
+ {
51
+ type: 'text',
52
+ text: `Drafting email to ${recipientSummary} with subject "${subject}"\n\n${JSON.stringify(draftData)}\n\n[View: ${COMPOSE_EMAIL_RESOURCE_URI}]`,
53
+ },
54
+ ],
55
+ _meta: {
56
+ ui: {
57
+ resourceUri: COMPOSE_EMAIL_RESOURCE_URI,
58
+ presentation: 'primary',
59
+ viewSummary,
60
+ viewRoleLabel: 'Editable email draft',
61
+ structuredFallback: {
62
+ kind: 'email-draft',
63
+ payload: { to, cc, bcc, subject: fallbackSubject, body: fallbackBody },
64
+ },
65
+ },
66
+ },
67
+ structuredContent: draftData,
68
+ };
69
+ }
70
+ //# sourceMappingURL=compose.js.map
package/dist/mail.d.ts CHANGED
@@ -15,6 +15,7 @@ export interface SendEmailArgs {
15
15
  subject: string;
16
16
  body: string;
17
17
  cc?: string | string[];
18
+ bcc?: string | string[];
18
19
  importance?: 'low' | 'normal' | 'high';
19
20
  }
20
21
  export declare function sendEmail(client: Client, args: SendEmailArgs, signal: AbortSignal): Promise<unknown>;
@@ -60,6 +61,113 @@ export interface CreateDraftArgs {
60
61
  subject: string;
61
62
  body: string;
62
63
  cc?: string | string[];
64
+ bcc?: string | string[];
63
65
  }
64
66
  export declare function createDraft(client: Client, args: CreateDraftArgs, signal: AbortSignal): Promise<unknown>;
67
+ export interface ListAttachmentsArgs {
68
+ id: string;
69
+ }
70
+ export declare function listAttachments(client: Client, args: ListAttachmentsArgs, signal: AbortSignal): Promise<unknown>;
71
+ /**
72
+ * The validated attachment-download target: the canonical (symlink-resolved)
73
+ * workspace root every attachment write must stay contained in. It is the
74
+ * only path component trusted at write time — see writeFileExclusive.
75
+ */
76
+ export interface AttachmentDirTarget {
77
+ root: string;
78
+ }
79
+ /**
80
+ * Resolve the root attachments are saved under, honouring the repo's
81
+ * file-write invariant: the download root is `MCP_WORKSPACE_PATH` (or
82
+ * `os.tmpdir()` when unset), canonicalised (symlinks resolved) so the
83
+ * containment anchor is the real directory, never a symlinked alias, and a
84
+ * nonexistent or unresolvable root fails closed before any content is
85
+ * written. This is the intent-validation gate — it decides WHERE downloads
86
+ * may land; it deliberately returns no user-visible pathname to write to
87
+ * (see writeFileExclusive).
88
+ *
89
+ * Exported for tests (the guard below is exercised directly).
90
+ */
91
+ export declare function resolveAttachmentDir(): Promise<AttachmentDirTarget>;
92
+ /**
93
+ * Write `content` as `filename` inside a fresh, unpredictable staging
94
+ * directory created atomically with `fs.mkdtemp` directly under the
95
+ * canonical download root (mode 0700), and report the real path of the
96
+ * saved file.
97
+ *
98
+ * No validated user-visible pathname is ever opened: the connector invents
99
+ * the staging directory name, so there is no pre-existing pathname for a
100
+ * local attacker to pre-plant, rename, or symlink-swap between validation
101
+ * and the write syscall — the parent-directory check-then-use (TOCTOU) race
102
+ * that a "validate a directory, then open a path inside it" scheme leaves
103
+ * open is removed by construction, with no descriptor-relative APIs, on
104
+ * every platform. The only path component trusted at write time is the
105
+ * canonical workspace root itself, which a principal whose write access is
106
+ * scoped to the workspace's contents cannot swap out.
107
+ *
108
+ * The file is created with O_CREAT|O_EXCL ('wx', mode 0600) and fstat-checked
109
+ * to be a regular file, so even a same-named entry planted inside the fresh
110
+ * staging directory is never written through. A same-named file anywhere
111
+ * else is simply never touched: overwrite is impossible by construction.
112
+ *
113
+ * On failure the whole staging directory is removed, so a rejected write
114
+ * leaves no residue.
115
+ *
116
+ * Exported for tests.
117
+ */
118
+ export declare function writeFileExclusive(target: AttachmentDirTarget, filename: string, content: Buffer): Promise<string>;
119
+ export interface DownloadAttachmentArgs {
120
+ id: string;
121
+ attachmentId: string;
122
+ }
123
+ export declare function downloadAttachment(client: Client, args: DownloadAttachmentArgs, signal: AbortSignal): Promise<unknown>;
124
+ export interface SendDraftArgs {
125
+ id: string;
126
+ }
127
+ export declare function sendDraft(client: Client, args: SendDraftArgs, signal: AbortSignal): Promise<unknown>;
128
+ export interface UpdateDraftArgs {
129
+ id: string;
130
+ to?: string | string[];
131
+ cc?: string | string[];
132
+ subject?: string;
133
+ body?: string;
134
+ importance?: 'low' | 'normal' | 'high';
135
+ }
136
+ export declare function updateDraft(client: Client, args: UpdateDraftArgs, signal: AbortSignal): Promise<unknown>;
137
+ export interface MarkEmailReadArgs {
138
+ id: string;
139
+ isRead?: boolean;
140
+ }
141
+ export declare function markEmailRead(client: Client, args: MarkEmailReadArgs, signal: AbortSignal): Promise<unknown>;
142
+ export interface SetEmailFlagArgs {
143
+ id: string;
144
+ flag: 'flagged' | 'complete' | 'notFlagged';
145
+ }
146
+ export declare function setEmailFlag(client: Client, args: SetEmailFlagArgs, signal: AbortSignal): Promise<unknown>;
147
+ export interface GetConversationArgs {
148
+ id?: string;
149
+ conversationId?: string;
150
+ top?: number;
151
+ }
152
+ export declare function getConversation(client: Client, args: GetConversationArgs, signal: AbortSignal): Promise<unknown>;
153
+ export declare function getAutomaticReplies(client: Client, signal: AbortSignal): Promise<unknown>;
154
+ export interface SetAutomaticRepliesArgs {
155
+ status: 'disabled' | 'alwaysEnabled' | 'scheduled';
156
+ internalReplyMessage?: string;
157
+ externalReplyMessage?: string;
158
+ externalAudience?: 'none' | 'contactsOnly' | 'all';
159
+ scheduledStart?: string;
160
+ scheduledEnd?: string;
161
+ }
162
+ /**
163
+ * Validate and normalize a scheduled out-of-office window: both bounds must
164
+ * be ISO 8601 date-times (offsets converted to UTC) and start must precede
165
+ * end. Throws with actionable guidance otherwise. Idempotent — its own
166
+ * output re-normalizes to itself.
167
+ */
168
+ export declare function normalizeScheduledWindow(scheduledStart: string | undefined, scheduledEnd: string | undefined): {
169
+ start: string;
170
+ end: string;
171
+ };
172
+ export declare function setAutomaticReplies(client: Client, args: SetAutomaticRepliesArgs, signal: AbortSignal): Promise<unknown>;
65
173
  //# sourceMappingURL=mail.d.ts.map