@mgcrea/mcp-apple-mail 1.8.0 → 1.10.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/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { a as loadConfig, b as MAIL_SURFACE, j as BUILD_INFO, r as createServer } from "./server-DR29GCV5.js";
2
+ import { a as loadConfig, b as MAIL_SURFACE, j as BUILD_INFO, r as createServer } from "./server-D-ufMDi0.js";
3
3
  import { runStdioServer } from "@mgcrea/mcp-apple-core";
4
4
  //#region src/cli.ts
5
5
  const LOG_PREFIX = "apple-mail-mcp";
package/dist/index.d.ts CHANGED
@@ -203,6 +203,32 @@ type SearchFilters = {
203
203
  limit: number;
204
204
  offset: number;
205
205
  };
206
+ /**
207
+ * What a mail query can group on.
208
+ *
209
+ * The single source of truth for both the tool's enum and the SQL expressions
210
+ * in `#groupExpr` — a field can only be asked for if it is listed here, which
211
+ * is what keeps caller strings out of the statement.
212
+ */
213
+ declare const GROUP_FIELDS: readonly ["sender", "mailbox", "subject", "day", "month"];
214
+ type GroupField = (typeof GROUP_FIELDS)[number];
215
+ type GroupRow = {
216
+ /** The grouped value. Null where the underlying column is null. */
217
+ key: string | null;
218
+ /** A display form of `key` where the schema carries one, else null. */
219
+ label: string | null;
220
+ count: number;
221
+ unread: number;
222
+ firstAt: string | null;
223
+ lastAt: string | null;
224
+ };
225
+ type GroupResult = {
226
+ groups: GroupRow[];
227
+ /** Distinct groups matched, before `limit` cut the list. */
228
+ totalGroups: number;
229
+ /** Messages aggregated. Never capped by `limit`. */
230
+ totalRows: number;
231
+ };
206
232
  type OpenResult = {
207
233
  db: DatabaseSync;
208
234
  /** Which mode actually opened. `immutable` results are WAL-blind — say so. */
@@ -223,6 +249,16 @@ declare class EnvelopeIndex {
223
249
  unread: number | null;
224
250
  }[];
225
251
  search(filters: SearchFilters): MessageRow[];
252
+ /**
253
+ * Count matches per group, over every match rather than a page of them.
254
+ *
255
+ * `filters.limit` caps the number of GROUPS returned, not the number of
256
+ * messages considered — that distinction is the whole point of this lane.
257
+ * Aggregating a page instead would answer "the top senders among the
258
+ * twenty-five rows we happened to return", which is indistinguishable from a
259
+ * real top-N unless you already knew to doubt it.
260
+ */
261
+ groupBy(filters: Omit<SearchFilters, "offset">, field: GroupField): GroupResult;
226
262
  count(filters: Omit<SearchFilters, "limit" | "offset">): {
227
263
  total: number;
228
264
  unread: number;
@@ -420,6 +456,22 @@ declare class AppleMailClient {
420
456
  get indexError(): string | null;
421
457
  /** How stale the index file is, so callers can see when they are reading history. */
422
458
  indexAgeSeconds(): Promise<number | null>;
459
+ /**
460
+ * Aggregate matches instead of listing them.
461
+ *
462
+ * Same filters as `searchMessages`, same index — the difference is that the
463
+ * counting happens in SQLite over the whole match set rather than in the
464
+ * model's head over a page of it. Returns null on the same condition
465
+ * `searchMessages` does, so callers keep one degradation path.
466
+ */
467
+ groupMessages(opts: Omit<SearchFilters, "mailboxRowids" | "offset"> & {
468
+ account?: string | undefined;
469
+ mailbox?: string | undefined;
470
+ }, field: GroupField): Promise<(GroupResult & {
471
+ indexMode: string;
472
+ indexAgeSeconds: number | null;
473
+ walBlind: boolean;
474
+ }) | null>;
423
475
  searchMessages(opts: Omit<SearchFilters, "mailboxRowids"> & {
424
476
  account?: string | undefined;
425
477
  mailbox?: string | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/build-info.ts","../src/client/errors.ts","../src/client/locate.ts","../src/config.ts","../src/client/mime.ts","../src/client/emlx.ts","../src/client/schema.ts","../src/client/envelope.ts","../src/client/mailbox-map.ts","../src/client/mail.ts","../src/client/ref.ts","../src/server.ts","../src/tools/index.ts"],"mappings":";;;;;cAkBa,YAAY;;;;cCWZ,6BAA6B;WACtB;EAElB,YAAY;;;;;;;;;;;;;;;;;;;;KCTF;;EAEV;;EAEA;EACA;;EAEA;EACA;EACA;EACA;EACA;;EAEA;EACA;EACA;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C;IACA;IACA;IACA;;;;;;;;;;;;;;EAuCI,cACJ,cACA,mBACC;IACD;IACA;IACA;IACA;IACA;;;;;;;;;;;;;;;EAkDI,YACJ,aACA;IAAQ;IAAc;MACrB,QAAQ;EAoBL,gBAAgB,mBAAmB;EAKnC,YAAY;IAChB;IACA;IACA;IACA;IACA;IACA;IACA;MACE;EAaE,eACJ,aACA;IACE;IACA;IACA;IACA;IACA;MAED;;;;;;;;;;;;;;;;;;;;;cC5nCQ;KAED;EACV;EACA;EACA;;cAKW,YAAS,KAAS;cAGlB,YAAS,gBAAkB;;cA2B3B,qBAAkB,MAAU,iBAAe,YAAY;;;cChDvD;cACA;KAED;EACV,QAAQ;EACR,SAAS;;EAET,YAAY;;KAGF;EACV,QAAQ;EACR,QAAQ;;;;;;;cAQG,eAAY,MAAU,wBAAsB;;;KCtB7C;;;;;EAKV;;;;;;;;;;;;cAaW,gBAAa,QAChB,WAAS,QACT,iBAAe,KAClB"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/build-info.ts","../src/client/errors.ts","../src/client/locate.ts","../src/config.ts","../src/client/mime.ts","../src/client/emlx.ts","../src/client/schema.ts","../src/client/envelope.ts","../src/client/mailbox-map.ts","../src/client/mail.ts","../src/client/ref.ts","../src/server.ts","../src/tools/index.ts"],"mappings":";;;;;cAkBa,YAAY;;;;cCWZ,6BAA6B;WACtB;EAElB,YAAY;;;;;;;;;;;;;;;;;;;;KCTF;;EAEV;;EAEA;EACA;;EAEA;EACA;EACA;EACA;EACA;;EAEA;EACA;EACA;;KAKU;;EAEV;;EAEA;;EAEA;;EAEA;;cAiBW,sBAAmB,OAAU,kBAAqB;;;;;;;;;;;;;;;cC3CzD,cAAY,EAAA;;;;;;;;;;;;;;;;;;;;;;GA8CP,EAAA,KAAA;KAEC,SAAS,EAAE,aAAa;;;;;cAMvB,aAAU,MAAS,OAAO,eAA2B;;;KCvDtD;EACV;EACA;EACA;;;;;;;;;EASA;;EAEA;;;;;;;;;;;;;;;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EAuCI,cACJ,cACA,mBACC;IACD;IACA;IACA;IACA;IACA;;;;;;;;;;;;;;;EAkDI,YACJ,aACA;IAAQ;IAAc;MACrB,QAAQ;EAoBL,gBAAgB,mBAAmB;EAKnC,YAAY;IAChB;IACA;IACA;IACA;IACA;IACA;IACA;MACE;EAaE,eACJ,aACA;IACE;IACA;IACA;IACA;IACA;MAED;;;;;;;;;;;;;;;;;;;;;cCzrCQ;KAED;EACV;EACA;EACA;;cAKW,YAAS,KAAS;cAGlB,YAAS,gBAAkB;;cA2B3B,qBAAkB,MAAU,iBAAe,YAAY;;;cChDvD;cACA;KAED;EACV,QAAQ;EACR,SAAS;;EAET,YAAY;;KAGF;EACV,QAAQ;EACR,QAAQ;;;;;;;cAQG,eAAY,MAAU,wBAAsB;;;KCrB7C;;;;;EAKV;;;;;;;;;;;;cAaW,gBAAa,QAChB,WAAS,QACT,iBAAe,KAClB"}
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import { A as WritesDisabledError, C as MessageNotFoundError, D as ProtocolError, E as PreconditionError, O as SchemaDriftError, S as MailNotRunningError, T as PlatformError, _ as locateEnvelopeIndex, a as loadConfig, c as decodeRef, d as assertStaticScript, f as createOsascriptRunner, g as inspectFile, h as MailboxMap, i as registerTools, j as BUILD_INFO, k as TccDeniedError, l as encodeRef, m as withBusyRetry, n as SERVER_VERSION, o as AppleMailClient, p as mapOsaError, r as createServer, s as REF_VERSION, t as SERVER_NAME, u as groupRefsByMailbox, v as AppleMailError, w as OsascriptTimeoutError, x as MailBusyError, y as IndexUnavailableError } from "./server-DR29GCV5.js";
1
+ import { A as WritesDisabledError, C as MessageNotFoundError, D as ProtocolError, E as PreconditionError, O as SchemaDriftError, S as MailNotRunningError, T as PlatformError, _ as locateEnvelopeIndex, a as loadConfig, c as decodeRef, d as assertStaticScript, f as createOsascriptRunner, g as inspectFile, h as MailboxMap, i as registerTools, j as BUILD_INFO, k as TccDeniedError, l as encodeRef, m as withBusyRetry, n as SERVER_VERSION, o as AppleMailClient, p as mapOsaError, r as createServer, s as REF_VERSION, t as SERVER_NAME, u as groupRefsByMailbox, v as AppleMailError, w as OsascriptTimeoutError, x as MailBusyError, y as IndexUnavailableError } from "./server-D-ufMDi0.js";
2
2
  export { AppleMailClient, AppleMailError, BUILD_INFO, IndexUnavailableError, MailBusyError, MailNotRunningError, MailboxMap, MessageNotFoundError, OsascriptTimeoutError, PlatformError, PreconditionError, ProtocolError, REF_VERSION, SERVER_NAME, SERVER_VERSION, SchemaDriftError, TccDeniedError, WritesDisabledError, assertStaticScript, createOsascriptRunner, createServer, decodeRef, encodeRef, groupRefsByMailbox, inspectFile, loadConfig, locateEnvelopeIndex, mapOsaError, registerTools, withBusyRetry };
@@ -1,4 +1,4 @@
1
- import { AppBusyError as MailBusyError, AppNotRunningError as MailNotRunningError, AppleAutomationError, AppleAutomationError as AppleMailError, BaseConfigSchema, IndexUnavailableError, OsascriptTimeoutError, PlatformError, PreconditionError, ProtocolError, SchemaDriftError, TccDeniedError, WritesDisabledError, assertStaticScript, confirmArg, createOsascriptRunner, detectEpoch, escapeLike, fingerprintSchema, inspectFile, limitArg, mapOsaError, openReadOnly, parseBool, parseConfig, parseIntOpt, parseList, promptArg, readPackageIdentity, registerSurfaceResources, registerWorkflowPrompt, requiredPromptArg, resolveLimit, tableMap, trimmed, withBusyRetry, wrap } from "@mgcrea/mcp-apple-core";
1
+ import { AppBusyError as MailBusyError, AppNotRunningError as MailNotRunningError, AppleAutomationError, AppleAutomationError as AppleMailError, BaseConfigSchema, IndexUnavailableError, OsascriptTimeoutError, PlatformError, PreconditionError, ProtocolError, SchemaDriftError, TccDeniedError, WritesDisabledError, assertStaticScript, confirmArg, createOsascriptRunner, describeAggregation, detectEpoch, escapeLike, fingerprintSchema, groupByArg, inspectFile, limitArg, mapOsaError, openReadOnly, parseBool, parseConfig, parseIntOpt, parseList, project, promptArg, readPackageIdentity, registerSurfaceResources, registerWorkflowPrompt, requiredPromptArg, resolveLimit, selectArg, tableMap, trimmed, withBusyRetry, wrap } from "@mgcrea/mcp-apple-core";
2
2
  import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, statSync, writeFileSync } from "node:fs";
3
3
  import { homedir } from "node:os";
4
4
  import { basename, dirname, join, resolve, sep } from "node:path";
@@ -12,8 +12,8 @@ const pkg = readPackageIdentity(new URL("../package.json", import.meta.url), {
12
12
  const BUILD_INFO = {
13
13
  name: pkg.name,
14
14
  version: pkg.version,
15
- gitCommit: "e813542",
16
- gitCommitDate: "2026-09-01T21:11:56+02:00"
15
+ gitCommit: "372c3c1",
16
+ gitCommitDate: "2026-09-02T22:36:25+02:00"
17
17
  };
18
18
  //#endregion
19
19
  //#region src/client/errors.ts
@@ -795,6 +795,20 @@ const assertUsable = (caps) => {
795
795
  };
796
796
  //#endregion
797
797
  //#region src/client/envelope.ts
798
+ /**
799
+ * What a mail query can group on.
800
+ *
801
+ * The single source of truth for both the tool's enum and the SQL expressions
802
+ * in `#groupExpr` — a field can only be asked for if it is listed here, which
803
+ * is what keeps caller strings out of the statement.
804
+ */
805
+ const GROUP_FIELDS = [
806
+ "sender",
807
+ "mailbox",
808
+ "subject",
809
+ "day",
810
+ "month"
811
+ ];
798
812
  const contains = (value) => `%${escapeLike(value)}%`;
799
813
  const openIndex = (path, mode, logger) => {
800
814
  const { db, mode: opened, validated: caps } = openReadOnly(path, mode, {
@@ -815,7 +829,7 @@ const openIndex = (path, mode, logger) => {
815
829
  caps
816
830
  };
817
831
  };
818
- var EnvelopeIndex = class {
832
+ var EnvelopeIndex = class EnvelopeIndex {
819
833
  #db;
820
834
  caps;
821
835
  mode;
@@ -859,8 +873,18 @@ var EnvelopeIndex = class {
859
873
  #toEpoch(iso) {
860
874
  return Math.floor(Date.parse(iso) / 1e3) - this.caps.epochOffset;
861
875
  }
862
- search(filters) {
863
- const params = [];
876
+ /**
877
+ * The WHERE half of a filtered read, appending its bind values to `params`.
878
+ *
879
+ * Shared by `search` and `groupBy` so the two cannot drift: a filter that
880
+ * narrowed a listing but not its aggregate would make "count per sender in
881
+ * INBOX" quietly count the whole archive.
882
+ *
883
+ * Call this before adding any other bind value — the placeholders it appends
884
+ * have to come first in the parameter list, which mirrors WHERE preceding
885
+ * ORDER BY and LIMIT in every statement built from it.
886
+ */
887
+ #filterPredicate(filters, params) {
864
888
  const where = ["m.deleted = 0"];
865
889
  where.push(this.#mailboxPredicate(filters.mailboxRowids, params));
866
890
  if (filters.query) {
@@ -890,7 +914,25 @@ var EnvelopeIndex = class {
890
914
  where.push("m.date_received <= ?");
891
915
  params.push(this.#toEpoch(filters.dateTo));
892
916
  }
893
- const sql = `SELECT m.ROWID AS rowid, mb.url AS mailboxUrl, ${this.caps.has.subjectPrefix ? "COALESCE(m.subject_prefix, '') || COALESCE(s.subject, '')" : "COALESCE(s.subject, '')"} AS subject, a.address AS senderAddress, a.comment AS senderName, m.date_received AS dateReceived, ${this.caps.has.dateSent ? "m.date_sent" : "NULL"} AS dateSent, m.read AS read, ${this.caps.has.flagged ? "m.flagged" : "0"} AS flagged, m.size AS size, ${this.caps.has.conversationId ? "m.conversation_id" : "NULL"} AS conversationId, ` + (this.caps.has.attachments ? "EXISTS (SELECT 1 FROM attachments at2 WHERE at2.message = m.ROWID) AS hasAttachment " : "0 AS hasAttachment ") + `FROM messages m JOIN mailboxes mb ON mb.ROWID = m.mailbox LEFT JOIN subjects s ON s.ROWID = m.subject LEFT JOIN addresses a ON a.ROWID = m.sender WHERE ${where.join(" AND ")} ORDER BY m.date_received DESC LIMIT ? OFFSET ?`;
917
+ return where.join(" AND ");
918
+ }
919
+ /**
920
+ * The joins every filtered read needs. `s` and `a` are LEFT joins because a
921
+ * message can legitimately have no subject row and no sender row, and an
922
+ * INNER join here would drop exactly those from counts.
923
+ */
924
+ static #FROM = "FROM messages m JOIN mailboxes mb ON mb.ROWID = m.mailbox LEFT JOIN subjects s ON s.ROWID = m.subject LEFT JOIN addresses a ON a.ROWID = m.sender";
925
+ /**
926
+ * subject_prefix holds "Re: " / "Fwd: " separately from the deduplicated
927
+ * subject row, so the displayed subject is the concatenation of the two.
928
+ */
929
+ get #subjectExpr() {
930
+ return this.caps.has.subjectPrefix ? "COALESCE(m.subject_prefix, '') || COALESCE(s.subject, '')" : "COALESCE(s.subject, '')";
931
+ }
932
+ search(filters) {
933
+ const params = [];
934
+ const predicate = this.#filterPredicate(filters, params);
935
+ const sql = `SELECT m.ROWID AS rowid, mb.url AS mailboxUrl, ${this.#subjectExpr} AS subject, a.address AS senderAddress, a.comment AS senderName, m.date_received AS dateReceived, ${this.caps.has.dateSent ? "m.date_sent" : "NULL"} AS dateSent, m.read AS read, ${this.caps.has.flagged ? "m.flagged" : "0"} AS flagged, m.size AS size, ${this.caps.has.conversationId ? "m.conversation_id" : "NULL"} AS conversationId, ` + (this.caps.has.attachments ? "EXISTS (SELECT 1 FROM attachments at2 WHERE at2.message = m.ROWID) AS hasAttachment " : "0 AS hasAttachment ") + `${EnvelopeIndex.#FROM} WHERE ${predicate} ORDER BY m.date_received DESC LIMIT ? OFFSET ?`;
894
936
  params.push(filters.limit, filters.offset);
895
937
  return this.#db.prepare(sql).all(...params).map((r) => ({
896
938
  rowid: Number(r.rowid),
@@ -907,6 +949,74 @@ var EnvelopeIndex = class {
907
949
  hasAttachment: Boolean(r.hasAttachment)
908
950
  }));
909
951
  }
952
+ /**
953
+ * The column expression each groupable field aggregates on.
954
+ *
955
+ * A key here is the ONLY thing that reaches the statement — the tool matches
956
+ * the caller's string against `GROUP_FIELDS` and passes the matched literal,
957
+ * so no caller-controlled text is ever interpolated. `label` is a second,
958
+ * human-readable form of the same group where one exists; it goes through
959
+ * MAX() because everything outside GROUP BY has to be aggregated, and the
960
+ * value is constant within a group anyway.
961
+ */
962
+ #groupExpr(field) {
963
+ switch (field) {
964
+ case "sender": return {
965
+ key: "a.address",
966
+ label: "MAX(NULLIF(a.comment, ''))"
967
+ };
968
+ case "mailbox": return {
969
+ key: "m.mailbox",
970
+ label: "MAX(mb.url)"
971
+ };
972
+ case "subject": return {
973
+ key: this.#subjectExpr,
974
+ label: "NULL"
975
+ };
976
+ case "day": return {
977
+ key: this.#dateBucket("%Y-%m-%d"),
978
+ label: "NULL"
979
+ };
980
+ case "month": return {
981
+ key: this.#dateBucket("%Y-%m"),
982
+ label: "NULL"
983
+ };
984
+ }
985
+ }
986
+ /** `date_received` is epoch-with-offset, so shift it before formatting. */
987
+ #dateBucket(format) {
988
+ return `strftime('${format}', datetime(m.date_received + ${this.caps.epochOffset}, 'unixepoch'))`;
989
+ }
990
+ /**
991
+ * Count matches per group, over every match rather than a page of them.
992
+ *
993
+ * `filters.limit` caps the number of GROUPS returned, not the number of
994
+ * messages considered — that distinction is the whole point of this lane.
995
+ * Aggregating a page instead would answer "the top senders among the
996
+ * twenty-five rows we happened to return", which is indistinguishable from a
997
+ * real top-N unless you already knew to doubt it.
998
+ */
999
+ groupBy(filters, field) {
1000
+ const { key, label } = this.#groupExpr(field);
1001
+ const totalsParams = [];
1002
+ const totalsPredicate = this.#filterPredicate(filters, totalsParams);
1003
+ const totals = this.#db.prepare(`SELECT COUNT(*) AS totalRows, COUNT(DISTINCT ${key}) + MAX(CASE WHEN ${key} IS NULL THEN 1 ELSE 0 END) AS totalGroups ${EnvelopeIndex.#FROM} WHERE ${totalsPredicate}`).get(...totalsParams);
1004
+ const params = [];
1005
+ const predicate = this.#filterPredicate(filters, params);
1006
+ params.push(filters.limit);
1007
+ return {
1008
+ groups: this.#db.prepare(`SELECT ${key} AS key, ${label} AS label, COUNT(*) AS count, SUM(CASE WHEN m.read = 0 THEN 1 ELSE 0 END) AS unread, MIN(m.date_received) AS firstAt, MAX(m.date_received) AS lastAt ${EnvelopeIndex.#FROM} WHERE ${predicate} GROUP BY ${key} ORDER BY count DESC, key ASC LIMIT ?`).all(...params).map((r) => ({
1009
+ key: r.key === null ? null : String(r.key),
1010
+ label: r.label || null,
1011
+ count: Number(r.count),
1012
+ unread: Number(r.unread ?? 0),
1013
+ firstAt: this.#toIso(r.firstAt),
1014
+ lastAt: this.#toIso(r.lastAt)
1015
+ })),
1016
+ totalRows: totals.totalRows,
1017
+ totalGroups: totals.totalGroups ?? 0
1018
+ };
1019
+ }
910
1020
  count(filters) {
911
1021
  const params = [];
912
1022
  const predicate = this.#mailboxPredicate(filters.mailboxRowids, params);
@@ -2760,6 +2870,44 @@ var AppleMailClient = class {
2760
2870
  }
2761
2871
  return rowids;
2762
2872
  }
2873
+ /**
2874
+ * Aggregate matches instead of listing them.
2875
+ *
2876
+ * Same filters as `searchMessages`, same index — the difference is that the
2877
+ * counting happens in SQLite over the whole match set rather than in the
2878
+ * model's head over a page of it. Returns null on the same condition
2879
+ * `searchMessages` does, so callers keep one degradation path.
2880
+ */
2881
+ async groupMessages(opts, field) {
2882
+ const index = await this.index();
2883
+ if (!index) return null;
2884
+ const mailboxRowids = await this.#targetMailboxRowids(opts);
2885
+ const result = index.groupBy({
2886
+ ...opts,
2887
+ ...mailboxRowids ? { mailboxRowids } : {}
2888
+ }, field);
2889
+ const groups = field === "mailbox" ? await (async () => {
2890
+ const lookup = await this.#mailboxLookup();
2891
+ return result.groups.map((g) => {
2892
+ const entry = g.key === null ? void 0 : lookup.get(Number(g.key));
2893
+ return entry ? {
2894
+ ...g,
2895
+ key: entry.mailbox,
2896
+ label: entry.accountUuid
2897
+ } : {
2898
+ ...g,
2899
+ label: g.label ?? null
2900
+ };
2901
+ });
2902
+ })() : result.groups;
2903
+ return {
2904
+ ...result,
2905
+ groups,
2906
+ indexMode: index.mode,
2907
+ indexAgeSeconds: await this.indexAgeSeconds(),
2908
+ walBlind: index.mode === "immutable"
2909
+ };
2910
+ }
2763
2911
  async searchMessages(opts) {
2764
2912
  const index = await this.index();
2765
2913
  if (!index) return null;
@@ -4043,6 +4191,93 @@ const registerMessageTools = (server, client, allowWrites) => {
4043
4191
  }, async ({ ref, filename, overwrite }) => wrap(async () => client.saveAttachment(ref, filename, overwrite ? { overwrite } : {})));
4044
4192
  };
4045
4193
  //#endregion
4194
+ //#region src/tools/query.ts
4195
+ /** What a search result actually carries, and therefore what `select` may name. */
4196
+ const SELECTABLE = [
4197
+ "ref",
4198
+ "subject",
4199
+ "sender",
4200
+ "dateReceived",
4201
+ "dateSent",
4202
+ "read",
4203
+ "flagged",
4204
+ "size"
4205
+ ];
4206
+ /**
4207
+ * The cheap-answer lane: same index as `apple_mail_search_messages`, but able to
4208
+ * return less than a whole row, or a count instead of the rows.
4209
+ *
4210
+ * Read-only by construction — it reaches nothing but the index — and registered
4211
+ * only on servers with writes off, so the surface a write-enabled client sees is
4212
+ * unchanged while this is proven out.
4213
+ */
4214
+ const registerQueryTools = (server, client) => {
4215
+ server.registerTool("apple_mail_query", {
4216
+ description: "Answer a question ABOUT your mail without reading the mail. Takes the same index filters as apple_mail_search_messages, plus two things it cannot do: `select` to keep only the fields you need, and `groupBy` to get counts per sender, mailbox, subject, day or month. Reach for this whenever the question is 'how many', 'who most', 'which mailbox' or 'when' — one grouped call replaces paging through hundreds of messages and tallying them by hand. Grouping counts every match, not just the first `limit`. Body search is not offered here (it is a linear file scan, which does not belong behind an aggregate) — use apple_mail_search_messages for that. Requires Full Disk Access; without it this returns degraded:true.",
4217
+ inputSchema: {
4218
+ query: z.string().optional().describe("Free text matched against subject and sender."),
4219
+ sender: z.string().optional().describe("Match the sender address or display name."),
4220
+ recipient: z.string().optional().describe("Match any recipient address."),
4221
+ subject: z.string().optional().describe("Match the subject only."),
4222
+ account: accountArg,
4223
+ mailbox: mailboxArg,
4224
+ unreadOnly: z.boolean().optional().describe("Only unread messages."),
4225
+ flaggedOnly: z.boolean().optional().describe("Only flagged messages."),
4226
+ hasAttachment: z.boolean().optional().describe("Only messages carrying an attachment."),
4227
+ dateFrom: z.string().optional().describe("ISO date/time lower bound, e.g. 2026-01-01."),
4228
+ dateTo: z.string().optional().describe("ISO date/time upper bound."),
4229
+ groupBy: groupByArg(GROUP_FIELDS),
4230
+ select: selectArg,
4231
+ limit: limitArg,
4232
+ offset: z.number().int().min(0).optional().describe("Skip this many rows, for paging. Ignored when grouping.")
4233
+ },
4234
+ annotations: { readOnlyHint: true }
4235
+ }, async ({ groupBy, select, limit, offset, ...filters }) => wrap(async () => {
4236
+ const resolved = resolveLimit(limit, client.config.maxResults);
4237
+ if (groupBy) {
4238
+ const result = await client.groupMessages({
4239
+ ...filters,
4240
+ limit: resolved
4241
+ }, groupBy);
4242
+ if (!result) return degraded(client);
4243
+ return {
4244
+ ...describeAggregation(groupBy, result.groups, result),
4245
+ indexAgeSeconds: result.indexAgeSeconds,
4246
+ ...walBlindWarning(result.walBlind)
4247
+ };
4248
+ }
4249
+ const result = await client.searchMessages({
4250
+ ...filters,
4251
+ limit: resolved,
4252
+ offset: offset ?? 0
4253
+ });
4254
+ if (!result) return degraded(client);
4255
+ const { rows, unknownFields } = project(result.messages, select, SELECTABLE);
4256
+ return {
4257
+ returned: rows.length,
4258
+ indexAgeSeconds: result.indexAgeSeconds,
4259
+ ...unknownFields ? {
4260
+ unknownFields,
4261
+ hint: `Selectable fields are: ${SELECTABLE.join(", ")}.`
4262
+ } : {},
4263
+ ...walBlindWarning(result.walBlind),
4264
+ messages: rows
4265
+ };
4266
+ }));
4267
+ };
4268
+ /**
4269
+ * The same degradation the other index-backed tools report. Kept identical on
4270
+ * purpose: a model that has learned what `capability: "search-index"` means
4271
+ * should not have to learn a second spelling of it here.
4272
+ */
4273
+ const degraded = (client) => ({
4274
+ degraded: true,
4275
+ capability: "search-index",
4276
+ reason: client.indexError ?? "the search index is unavailable",
4277
+ hint: "Grant Full Disk Access and restart the host app, then retry. Call apple_mail_diagnostics for details."
4278
+ });
4279
+ const walBlindWarning = (walBlind) => walBlind ? { warning: "Index opened WAL-blind (immutable); very recent mail may be missing." } : {};
4280
+ //#endregion
4046
4281
  //#region src/tools/search.ts
4047
4282
  /** Searching, listing and counting. */
4048
4283
  const registerSearchTools = (server, client) => {
@@ -4191,7 +4426,10 @@ const registerTools = (server, client, ctx) => {
4191
4426
  registerAccountTools(server, client);
4192
4427
  registerSearchTools(server, client);
4193
4428
  registerMessageTools(server, client, ctx.allowWrites);
4194
- if (!ctx.allowWrites) return;
4429
+ if (!ctx.allowWrites) {
4430
+ registerQueryTools(server, client);
4431
+ return;
4432
+ }
4195
4433
  registerActionTools(server, client);
4196
4434
  registerComposeTools(server, client);
4197
4435
  };
@@ -4244,4 +4482,4 @@ const createServer = (opts) => {
4244
4482
  //#endregion
4245
4483
  export { WritesDisabledError as A, MessageNotFoundError as C, ProtocolError as D, PreconditionError as E, SchemaDriftError as O, MailNotRunningError as S, PlatformError as T, locateEnvelopeIndex as _, loadConfig as a, MAIL_SURFACE as b, decodeRef as c, assertStaticScript as d, createOsascriptRunner as f, inspectFile as g, MailboxMap as h, registerTools as i, BUILD_INFO as j, TccDeniedError as k, encodeRef as l, withBusyRetry as m, SERVER_VERSION as n, AppleMailClient as o, mapOsaError as p, createServer as r, REF_VERSION as s, SERVER_NAME as t, groupRefsByMailbox as u, AppleMailError as v, OsascriptTimeoutError as w, MailBusyError as x, IndexUnavailableError as y };
4246
4484
 
4247
- //# sourceMappingURL=server-DR29GCV5.js.map
4485
+ //# sourceMappingURL=server-D-ufMDi0.js.map