apple-tools-mcp 3.3.5 → 3.4.1
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/README.md +9 -2
- package/index.js +19 -7
- package/indexer.js +14 -12
- package/lib/indexerRuntime.js +10 -3
- package/lib/mailFind.js +9 -5
- package/lib/mailWrite.js +157 -0
- package/lib/urlQuery.js +14 -0
- package/lib/writeTools.js +17 -1
- package/package.json +1 -1
- package/search.js +8 -6
package/README.md
CHANGED
|
@@ -210,6 +210,8 @@ apple-tools-mcp http-token
|
|
|
210
210
|
|
|
211
211
|
Under a secrets manager's runtime injection (for example `infisical run -- apple-tools-http`), set `APPLE_TOOLS_HTTP_TOKEN` and the server uses it instead of Keychain, which it then neither reads nor writes. To rotate without cutting off clients, start the server with the new token in `APPLE_TOOLS_HTTP_TOKEN` and the old one in `APPLE_TOOLS_HTTP_TOKEN_PREVIOUS`; once every client has the new token, restart without `APPLE_TOOLS_HTTP_TOKEN_PREVIOUS` and the old token stops working.
|
|
212
212
|
|
|
213
|
+
The HTTP server never indexes and never takes `indexer.lock`: it serves the index the indexer daemon keeps fresh, so run the indexer too. It also refuses `rebuild_index`; rebuild from a stdio client or as described under the index rebuild below. Restarting either one in any order is safe.
|
|
214
|
+
|
|
213
215
|
An example LaunchAgent is `examples/com.apple-tools-http.plist`. How to point Claude and other clients at it, including `apple-tools-http-proxy`, is in `examples/mcp-client.md`.
|
|
214
216
|
|
|
215
217
|
## Index commands
|
|
@@ -278,7 +280,7 @@ Your client can also call `audit_index`.
|
|
|
278
280
|
| `mail_read` | Full email content by file path. |
|
|
279
281
|
| `mail_senders` | Most frequent senders. |
|
|
280
282
|
| `mail_thread` | Every email in a conversation. |
|
|
281
|
-
| `mail_find` | Exact lookup in Mail's own database by subject prefix or text, sender, recipient, mailbox, and date. Returns every copy with its Message-ID. Does not wait on the index. |
|
|
283
|
+
| `mail_find` | Exact lookup in Mail's own database by subject prefix or text, sender, sender name, recipient, mailbox, and date. Returns every copy with its Message-ID. Does not wait on the index. |
|
|
282
284
|
| `mail_links` | The links in one email (by its `mail_find` id), decoded, with each link's visible text. Use it for the URL behind a button, such as a sign-in link; `mail_read` drops link targets. Does not wait on the index. |
|
|
283
285
|
|
|
284
286
|
### Messages
|
|
@@ -299,7 +301,9 @@ Your client can also call `audit_index`.
|
|
|
299
301
|
| `calendar_upcoming` | Next events, starting with everything on today's date (all-day and earlier-today events included). A failed read is an error. |
|
|
300
302
|
| `calendar_week` | Events for this week or a future week. |
|
|
301
303
|
| `calendar_free_time` | Open time on a date, read live from Calendar rather than the search index. |
|
|
302
|
-
| `calendar_recurring` | Recurring events. |
|
|
304
|
+
| `calendar_recurring` | Recurring events with their next occurrence, counting today's. |
|
|
305
|
+
|
|
306
|
+
Calendar tools print links in event titles and locations without their query string or fragment (`https://zoom.us/j/123?pwd=...` prints as `https://zoom.us/j/123`), so a meeting passcode never reaches a chat that reads the calendar.
|
|
303
307
|
|
|
304
308
|
### Contacts
|
|
305
309
|
|
|
@@ -358,11 +362,14 @@ A missing or malformed id or recipient is refused. Calendar times are local date
|
|
|
358
362
|
| `mail_mark` | `message_id` or `file_path`, `status` (`read` or `unread`, default `read`) | no |
|
|
359
363
|
| `mail_archive` | `message_id` or `file_path` | no |
|
|
360
364
|
| `mail_trash` | `message_id` or `file_path`, or `message_ids[]` (up to 500) | yes |
|
|
365
|
+
| `mail_unjunk` | `message_ids[]` (required, up to 500), `from_name_contains` | no |
|
|
361
366
|
|
|
362
367
|
Pass the RFC822 Message-ID, or the `file_path` from `mail_search` or `mail_recent` and the server reads the Message-ID from the file. `mail_archive` moves the message to that account's Archive (or All Mail). `mail_trash` moves it to Trash.
|
|
363
368
|
|
|
364
369
|
`mail_trash` with `message_ids` moves every copy of each message, for example the INBOX copy and the Sent copy of a mail you sent yourself, to that account's Trash. It finds each copy through Mail's database (`mail_find` uses the same lookup) and checks its Message-ID again before it moves it. One call stops starting new moves after about 35 seconds and reports `remaining`. Run it again for the rest. Copies that are already in Trash are left alone. Nothing is deleted for good. Mail empties Trash on its own schedule.
|
|
365
370
|
|
|
371
|
+
`mail_unjunk` moves only the Junk copies of `message_ids` to that account's Inbox (on the server for IMAP accounts); a copy in any other mailbox is left alone, and nothing is deleted, marked or sent. It re-checks each copy's Message-ID, and with `from_name_contains` it also re-checks that the sender's display name still contains that text (any case) and leaves the copy in Junk if not. Pair it with `mail_find` `from_name_contains` and `mailboxes: ["junk"]`. Same 35 second budget and `remaining` as bulk `mail_trash`.
|
|
372
|
+
|
|
366
373
|
`body_format: "html"` pastes the text into Mail's compose window. Mail may still create its own HTML version. New mail is a new message, not a quoted reply. Reply and forward still include the original.
|
|
367
374
|
|
|
368
375
|
A send is successful only after the message is in **Sent** or still in **Outbox**. If the call times out, check Sent before you try again. Retrying a message that already went out sends a second copy. A timeout is not the same thing as a denied Automation prompt.
|
package/index.js
CHANGED
|
@@ -42,6 +42,7 @@ import { closeEventKitSession, ensureEventKitSession } from "./lib/eventKitSessi
|
|
|
42
42
|
import { EVENTKIT_JXA_HELPERS } from "./lib/calendarWrite.js";
|
|
43
43
|
import { mailFind, MAILBOX_KINDS, MAIL_FIND_MAX_LIMIT } from "./lib/mailFind.js";
|
|
44
44
|
import { mailLinks } from "./lib/mailLinks.js";
|
|
45
|
+
import { stripUrlQueries } from "./lib/urlQuery.js";
|
|
45
46
|
|
|
46
47
|
const PACKAGE_VERSION = JSON.parse(
|
|
47
48
|
fs.readFileSync(new URL("./package.json", import.meta.url), "utf8")
|
|
@@ -449,9 +450,12 @@ async function initializeIndexing() {
|
|
|
449
450
|
// MCP stdio: if the indexer daemon (or another instance) holds the lock,
|
|
450
451
|
// skip background refresh and use the shared index. If nothing holds the
|
|
451
452
|
// lock, index locally as before so the stdio happy path still works.
|
|
452
|
-
|
|
453
|
+
// The HTTP server never takes the lock (see mcpIndexingStartup).
|
|
454
|
+
const startup = mcpIndexingStartup(() => acquireLock(), { httpMode: HTTP_MODE });
|
|
453
455
|
if (!startup.startBackground) {
|
|
454
|
-
console.error(
|
|
456
|
+
console.error(startup.reason === "http-server"
|
|
457
|
+
? "HTTP server never takes indexer.lock; it serves the index the indexer daemon keeps fresh."
|
|
458
|
+
: "Another apple-tools-mcp instance is indexing. Server will run without background indexing.");
|
|
455
459
|
// Lost lock is not "still indexing": this process will never complete a
|
|
456
460
|
// local cycle. Searches proceed whenever isIndexReady() is true (initDB
|
|
457
461
|
// re-lists shared on-disk tables; it must not cache an empty first connect).
|
|
@@ -675,7 +679,7 @@ function formatSmartSearchResults(results, synthesizedGroups = null) {
|
|
|
675
679
|
for (const group of synthesizedGroups.slice(0, 5)) {
|
|
676
680
|
sections.push(`📅 ${group.timeWindow} (${group.totalItems} items)`);
|
|
677
681
|
if (group.calendar.length > 0) {
|
|
678
|
-
sections.push(` Calendar: ${group.calendar.map(c => c.title).join(', ')}`);
|
|
682
|
+
sections.push(` Calendar: ${group.calendar.map(c => stripUrlQueries(c.title)).join(', ')}`);
|
|
679
683
|
}
|
|
680
684
|
if (group.mail.length > 0) {
|
|
681
685
|
sections.push(` Emails: ${group.mail.map(m => m.subject).join(', ')}`);
|
|
@@ -715,10 +719,10 @@ function formatSmartSearchResults(results, synthesizedGroups = null) {
|
|
|
715
719
|
sections.push("📅 CALENDAR:");
|
|
716
720
|
for (const r of results.calendar.results) {
|
|
717
721
|
sections.push(` [${r.rank}] Score: ${r.score}`);
|
|
718
|
-
sections.push(` Event: ${r.title}${r.isAllDay ? ' (All Day)' : ''}`);
|
|
722
|
+
sections.push(` Event: ${stripUrlQueries(r.title)}${r.isAllDay ? ' (All Day)' : ''}`);
|
|
719
723
|
sections.push(` Start: ${r.start}`);
|
|
720
724
|
sections.push(` Calendar: ${r.calendar}`);
|
|
721
|
-
if (r.location) sections.push(` Location: ${r.location}`);
|
|
725
|
+
if (r.location) sections.push(` Location: ${stripUrlQueries(r.location)}`);
|
|
722
726
|
}
|
|
723
727
|
sections.push("");
|
|
724
728
|
}
|
|
@@ -1057,7 +1061,7 @@ function formatPersonSearchResults(results) {
|
|
|
1057
1061
|
if (results.calendar && results.calendar.results && results.calendar.results.length > 0) {
|
|
1058
1062
|
sections.push(`📅 CALENDAR (${results.calendar.results.length}):`);
|
|
1059
1063
|
for (const r of results.calendar.results.slice(0, 10)) {
|
|
1060
|
-
sections.push(` • ${r.title}`);
|
|
1064
|
+
sections.push(` • ${stripUrlQueries(r.title)}`);
|
|
1061
1065
|
sections.push(` ${r.start} | ${r.calendar}`);
|
|
1062
1066
|
}
|
|
1063
1067
|
sections.push("");
|
|
@@ -1156,13 +1160,14 @@ function createServer() {
|
|
|
1156
1160
|
},
|
|
1157
1161
|
{
|
|
1158
1162
|
name: "mail_find",
|
|
1159
|
-
description: "Exact email lookup in Mail's own database (not the semantic index, so it never waits on indexing and matches filters exactly). Returns JSON: one row per copy (the same Message-ID in INBOX and Sent is two rows) with message_id, subject, from, to, received, mailbox, account_id. Needs at least one of subject_prefix, subject_contains, from, to, message_ids. Trash is excluded unless include_trash or mailboxes asks for it. Pair with mail_trash message_ids to clear what it finds.",
|
|
1163
|
+
description: "Exact email lookup in Mail's own database (not the semantic index, so it never waits on indexing and matches filters exactly). Returns JSON: one row per copy (the same Message-ID in INBOX and Sent is two rows) with message_id, subject, from, from_name, to, received, mailbox, account_id. Needs at least one of subject_prefix, subject_contains, from_name_contains, from, to, message_ids. Trash is excluded unless include_trash or mailboxes asks for it. Pair with mail_trash message_ids to clear what it finds, or mail_unjunk to move Junk copies to the Inbox.",
|
|
1160
1164
|
inputSchema: {
|
|
1161
1165
|
type: "object",
|
|
1162
1166
|
properties: {
|
|
1163
1167
|
subject_prefix: { type: "string", description: "Subject starts with this text (case-insensitive), e.g. '[Network] '" },
|
|
1164
1168
|
subject_contains: { type: "string", description: "Subject contains this text (case-insensitive)" },
|
|
1165
1169
|
from: { type: "string", description: "Exact sender address" },
|
|
1170
|
+
from_name_contains: { type: "string", description: "Sender display name contains this text (case-insensitive; Mail stores the name decoded), e.g. 'via Cloaked'" },
|
|
1166
1171
|
from_me: { type: "boolean", description: "Only messages sent from one of your own addresses (any address that appears as a sender in a Sent mailbox)" },
|
|
1167
1172
|
to: { type: "string", description: "Exact recipient address (To or Cc)" },
|
|
1168
1173
|
to_only: { type: "boolean", description: "With to: that address is the only recipient" },
|
|
@@ -1570,6 +1575,13 @@ function createServer() {
|
|
|
1570
1575
|
break;
|
|
1571
1576
|
}
|
|
1572
1577
|
|
|
1578
|
+
// The HTTP server never takes indexer.lock (it could hold it while the
|
|
1579
|
+
// indexer daemon restarts); rebuilds run from stdio or the indexer.
|
|
1580
|
+
if (HTTP_MODE) {
|
|
1581
|
+
result = "rebuild_index does not run over the HTTP server, which never takes indexer.lock. Run it from a stdio session (apple-tools-mcp) or with npm run build-index while the indexer daemon is stopped.";
|
|
1582
|
+
break;
|
|
1583
|
+
}
|
|
1584
|
+
|
|
1573
1585
|
// Acquire lock to prevent parallel rebuilds across multiple MCP instances
|
|
1574
1586
|
if (!acquireLock()) {
|
|
1575
1587
|
result = "Indexing is already in progress in a different session. Please wait for it to complete before starting a rebuild.";
|
package/indexer.js
CHANGED
|
@@ -2340,17 +2340,11 @@ export async function getEmailThread(filePath, limit = 20) {
|
|
|
2340
2340
|
}
|
|
2341
2341
|
}
|
|
2342
2342
|
|
|
2343
|
-
// calendar_recurring:
|
|
2344
|
-
|
|
2345
|
-
|
|
2346
|
-
|
|
2347
|
-
|
|
2348
|
-
const nowMac = Math.floor(Date.now() / 1000) - 978307200;
|
|
2349
|
-
const fetchLimit = safeLimit + 1; // Fetch one extra to detect if more exist
|
|
2350
|
-
|
|
2351
|
-
// Query events that have recurrence rules defined in the Recurrence table
|
|
2352
|
-
// Show the next upcoming occurrence of each recurring event
|
|
2353
|
-
const query = `
|
|
2343
|
+
// calendar_recurring: recurring events (a Recurrence row) with their next occurrence, from today on.
|
|
2344
|
+
// Bounded by today's local midnight, never now: OccurrenceCache.day is each occurrence's local midnight,
|
|
2345
|
+
// so comparing day to now dropped today's occurrence after midnight (the calendar_upcoming bug fixed in 3.3.5).
|
|
2346
|
+
export function buildRecurringEventsQuery(dayStartMac, fetchLimit) {
|
|
2347
|
+
return `
|
|
2354
2348
|
SELECT DISTINCT
|
|
2355
2349
|
ci.summary as title,
|
|
2356
2350
|
datetime(COALESCE(MIN(oc.occurrence_end_date) - (ci.end_date - ci.start_date), MIN(oc.day)) + 978307200, 'unixepoch', 'localtime') as start,
|
|
@@ -2361,12 +2355,20 @@ export function getRecurringEvents(limit = 20) {
|
|
|
2361
2355
|
INNER JOIN CalendarItem ci ON r.owner_id = ci.ROWID
|
|
2362
2356
|
INNER JOIN OccurrenceCache oc ON oc.event_id = ci.ROWID
|
|
2363
2357
|
LEFT JOIN Calendar c ON ci.calendar_id = c.ROWID
|
|
2364
|
-
WHERE oc.day >= ${
|
|
2358
|
+
WHERE oc.day >= ${dayStartMac}
|
|
2365
2359
|
AND ci.summary IS NOT NULL AND ci.summary <> ''
|
|
2366
2360
|
GROUP BY ci.ROWID, ci.summary, c.title, ci.all_day
|
|
2367
2361
|
ORDER BY occurrenceCount DESC, MIN(oc.day) ASC
|
|
2368
2362
|
LIMIT ${fetchLimit}
|
|
2369
2363
|
`;
|
|
2364
|
+
}
|
|
2365
|
+
|
|
2366
|
+
export function getRecurringEvents(limit = 20) {
|
|
2367
|
+
try {
|
|
2368
|
+
// Validate limit to prevent SQL issues
|
|
2369
|
+
const safeLimit = validateLimit(limit, 20, 100);
|
|
2370
|
+
const fetchLimit = safeLimit + 1; // Fetch one extra to detect if more exist
|
|
2371
|
+
const query = buildRecurringEventsQuery(localTodayStartMac(), fetchLimit);
|
|
2370
2372
|
const events = withCalendarCopy((dbPath) => {
|
|
2371
2373
|
return safeSqlite3Json(dbPath, query, { timeout: 30000 });
|
|
2372
2374
|
});
|
package/lib/indexerRuntime.js
CHANGED
|
@@ -178,12 +178,19 @@ export function applyIndexerCycleEnd({ success, indexerMode, cycleEndFlags, rele
|
|
|
178
178
|
}
|
|
179
179
|
|
|
180
180
|
/**
|
|
181
|
-
* MCP
|
|
181
|
+
* MCP startup: stdio indexes locally only when the lock is free. The HTTP
|
|
182
|
+
* server never takes indexer.lock: it serves the shared index the indexer
|
|
183
|
+
* daemon keeps fresh. As a local fallback it could win the lock while the
|
|
184
|
+
* daemon restarted after an install, leaving the daemon waiting for it.
|
|
182
185
|
*
|
|
183
186
|
* @param {() => boolean} acquireLock
|
|
184
|
-
* @
|
|
187
|
+
* @param {{ httpMode?: boolean }} [options]
|
|
188
|
+
* @returns {{ startBackground: boolean, ownsIndexLock: boolean, startHeartbeat: boolean, reason: "local-fallback" | "lock-held" | "http-server" }}
|
|
185
189
|
*/
|
|
186
|
-
export function mcpIndexingStartup(acquireLock) {
|
|
190
|
+
export function mcpIndexingStartup(acquireLock, { httpMode = false } = {}) {
|
|
191
|
+
if (httpMode) {
|
|
192
|
+
return { startBackground: false, ownsIndexLock: false, startHeartbeat: false, reason: "http-server" };
|
|
193
|
+
}
|
|
187
194
|
if (!acquireLock()) {
|
|
188
195
|
return { startBackground: false, ownsIndexLock: false, startHeartbeat: false, reason: "lock-held" };
|
|
189
196
|
}
|
package/lib/mailFind.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Exact mail lookup against Mail's own Envelope Index (no vector index).
|
|
3
3
|
*
|
|
4
4
|
* mail_find answers "which messages match these exact facts" (subject
|
|
5
|
-
* prefix, sender, recipient, mailbox, date) and bulk mail_trash uses
|
|
5
|
+
* prefix, sender, sender display name, recipient, mailbox, date) and bulk mail_trash uses
|
|
6
6
|
* locateMessageCopies() to address every copy of a Message-ID by Mail's
|
|
7
7
|
* internal id. A message's AppleScript `id` is its Envelope Index ROWID, so
|
|
8
8
|
* `messages of <one mailbox> whose id is N` resolves in about 2s even on a
|
|
@@ -140,7 +140,7 @@ function parseTime(value, field) {
|
|
|
140
140
|
*/
|
|
141
141
|
export function validateFindArgs(args = {}, { now = Date.now() } = {}) {
|
|
142
142
|
const f = {};
|
|
143
|
-
for (const [key, field] of [["subjectPrefix", "subject_prefix"], ["subjectContains", "subject_contains"]]) {
|
|
143
|
+
for (const [key, field] of [["subjectPrefix", "subject_prefix"], ["subjectContains", "subject_contains"], ["fromNameContains", "from_name_contains"]]) {
|
|
144
144
|
const r = cleanText(args[field], field);
|
|
145
145
|
if (r.error) return { error: r.error };
|
|
146
146
|
f[key] = r.value;
|
|
@@ -184,8 +184,8 @@ export function validateFindArgs(args = {}, { now = Date.now() } = {}) {
|
|
|
184
184
|
f.receivedBefore = f.receivedBefore === null ? cutoff : Math.min(f.receivedBefore, cutoff);
|
|
185
185
|
}
|
|
186
186
|
|
|
187
|
-
if (!f.subjectPrefix && !f.subjectContains && !f.from && !f.to && f.messageIds.length === 0) {
|
|
188
|
-
return { error: "add at least one of subject_prefix, subject_contains, from, to, or message_ids" };
|
|
187
|
+
if (!f.subjectPrefix && !f.subjectContains && !f.fromNameContains && !f.from && !f.to && f.messageIds.length === 0) {
|
|
188
|
+
return { error: "add at least one of subject_prefix, subject_contains, from_name_contains, from, to, or message_ids" };
|
|
189
189
|
}
|
|
190
190
|
|
|
191
191
|
const limit = args.limit === undefined || args.limit === null ? MAIL_FIND_DEFAULT_LIMIT : Number(args.limit);
|
|
@@ -204,6 +204,8 @@ export function buildFindQuery(f) {
|
|
|
204
204
|
if (f.subjectPrefix) where.push(likeClause(SUBJECT_EXPR, `${likeEscape(f.subjectPrefix)}%`));
|
|
205
205
|
if (f.subjectContains) where.push(likeClause(SUBJECT_EXPR, `%${likeEscape(f.subjectContains)}%`));
|
|
206
206
|
if (f.from) where.push(`lower(a.address) = ${sqlLiteral(f.from)}`);
|
|
207
|
+
// Mail stores the sender's display name decoded (RFC 2047) in addresses.comment; LIKE is case-insensitive for ASCII.
|
|
208
|
+
if (f.fromNameContains) where.push(likeClause("coalesce(a.comment, '')", `%${likeEscape(f.fromNameContains)}%`));
|
|
207
209
|
if (f.to) {
|
|
208
210
|
where.push(
|
|
209
211
|
`EXISTS (SELECT 1 FROM recipients r JOIN addresses ra ON ra.ROWID = r.address WHERE r.message = m.ROWID AND lower(ra.address) = ${sqlLiteral(f.to)})`
|
|
@@ -228,7 +230,7 @@ export function buildFindQuery(f) {
|
|
|
228
230
|
}
|
|
229
231
|
|
|
230
232
|
return `SELECT m.ROWID AS id, g.message_id_header AS message_id, ${SUBJECT_EXPR} AS subject,
|
|
231
|
-
a.address AS sender, m.date_received AS received, mb.url AS mailbox_url,
|
|
233
|
+
a.address AS sender, a.comment AS sender_name, m.date_received AS received, mb.url AS mailbox_url,
|
|
232
234
|
(SELECT group_concat(ra.address, ',') FROM recipients r JOIN addresses ra ON ra.ROWID = r.address WHERE r.message = m.ROWID) AS recipients
|
|
233
235
|
FROM messages m
|
|
234
236
|
JOIN subjects s ON s.ROWID = m.subject
|
|
@@ -247,6 +249,7 @@ function mapRow(row) {
|
|
|
247
249
|
message_id: row.message_id ? String(row.message_id).replace(/^</, "").replace(/>$/, "") : null,
|
|
248
250
|
subject: row.subject || "",
|
|
249
251
|
from: row.sender || null,
|
|
252
|
+
from_name: row.sender_name || null,
|
|
250
253
|
to: row.recipients ? String(row.recipients).split(",") : [],
|
|
251
254
|
received: Number.isFinite(row.received) ? new Date(row.received * 1000).toISOString() : null,
|
|
252
255
|
mailbox: mailboxKind(box.mailboxPath),
|
|
@@ -286,6 +289,7 @@ export function locateMessageCopies(messageIds, options = {}) {
|
|
|
286
289
|
const filters = {
|
|
287
290
|
subjectPrefix: null,
|
|
288
291
|
subjectContains: null,
|
|
292
|
+
fromNameContains: null,
|
|
289
293
|
from: null,
|
|
290
294
|
to: null,
|
|
291
295
|
toOnly: false,
|
package/lib/mailWrite.js
CHANGED
|
@@ -2121,3 +2121,160 @@ export function mailTrash(args = {}) {
|
|
|
2121
2121
|
|
|
2122
2122
|
return { ok: true, message: writeSuccessMessage(action, "moved to Trash", { message_id: resolved.messageId }) };
|
|
2123
2123
|
}
|
|
2124
|
+
|
|
2125
|
+
/** Mailbox names Mail uses for an account's Inbox, tried in order. */
|
|
2126
|
+
export const INBOX_MAILBOX_NAMES = ["INBOX", "Inbox"];
|
|
2127
|
+
const MAX_NAME_GUARD = 300;
|
|
2128
|
+
|
|
2129
|
+
/**
|
|
2130
|
+
* One osascript for every Junk copy: found by Mail's internal id in its own
|
|
2131
|
+
* mailbox, moved to that account's Inbox only if its Message-ID still
|
|
2132
|
+
* matches and, with a name guard, its sender's display name (decoded by
|
|
2133
|
+
* Mail) still contains the guard text (AppleScript compares ignoring case).
|
|
2134
|
+
* Output: one `<id>\t<status>` line per copy; status is moved, missing,
|
|
2135
|
+
* mismatch, name_mismatch, no_account, no_inbox, skipped or `error <n>`.
|
|
2136
|
+
*/
|
|
2137
|
+
export function buildUnjunkScript(copies, { fromNameContains = "", budgetSec = MAIL_BULK_TRASH_BUDGET_SEC } = {}) {
|
|
2138
|
+
const items = copies
|
|
2139
|
+
.map((c) => `{${asString(c.account_id)}, ${asString(c.mailbox_path)}, ${asInteger(c.id, { min: 1, field: "id" })}, ${asString(c.message_id)}}`)
|
|
2140
|
+
.join(", ");
|
|
2141
|
+
const inboxNames = INBOX_MAILBOX_NAMES.map((name) => asString(name)).join(", ");
|
|
2142
|
+
return `set guardName to ${asString(fromNameContains || "")}
|
|
2143
|
+
|
|
2144
|
+
on atmInboxBox(acct)
|
|
2145
|
+
tell application "Mail"
|
|
2146
|
+
repeat with nm in {${inboxNames}}
|
|
2147
|
+
if (exists mailbox (contents of nm) of acct) then return mailbox (contents of nm) of acct
|
|
2148
|
+
end repeat
|
|
2149
|
+
end tell
|
|
2150
|
+
return missing value
|
|
2151
|
+
end atmInboxBox
|
|
2152
|
+
|
|
2153
|
+
on atmUnjunkCopy(acctId, boxPath, rid, mid, guardText)
|
|
2154
|
+
tell application "Mail"
|
|
2155
|
+
try
|
|
2156
|
+
set acct to account id acctId
|
|
2157
|
+
-- An account specifier resolves lazily; reading a property proves it exists.
|
|
2158
|
+
set acctName to name of acct
|
|
2159
|
+
on error
|
|
2160
|
+
return "no_account"
|
|
2161
|
+
end try
|
|
2162
|
+
try
|
|
2163
|
+
set hits to (messages of (mailbox boxPath of acct) whose id is rid)
|
|
2164
|
+
on error errMsg number errNum
|
|
2165
|
+
return "error " & errNum
|
|
2166
|
+
end try
|
|
2167
|
+
if (count of hits) is 0 then return "missing"
|
|
2168
|
+
set msg to item 1 of hits
|
|
2169
|
+
if (message id of msg) is not mid then return "mismatch"
|
|
2170
|
+
if guardText is not "" then
|
|
2171
|
+
set senderName to extract name from (sender of msg)
|
|
2172
|
+
if senderName does not contain guardText then return "name_mismatch"
|
|
2173
|
+
end if
|
|
2174
|
+
set inboxBox to my atmInboxBox(acct)
|
|
2175
|
+
if inboxBox is missing value then return "no_inbox"
|
|
2176
|
+
try
|
|
2177
|
+
set mailbox of msg to inboxBox
|
|
2178
|
+
on error errMsg number errNum
|
|
2179
|
+
return "error " & errNum
|
|
2180
|
+
end try
|
|
2181
|
+
return "moved"
|
|
2182
|
+
end tell
|
|
2183
|
+
end atmUnjunkCopy
|
|
2184
|
+
|
|
2185
|
+
set atmStart to current date
|
|
2186
|
+
set atmOut to ""
|
|
2187
|
+
repeat with atmItem in {${items}}
|
|
2188
|
+
if ((current date) - atmStart) > ${asInteger(budgetSec, { min: 1, max: 600, field: "budgetSec" })} then
|
|
2189
|
+
set atmStatus to "skipped"
|
|
2190
|
+
else
|
|
2191
|
+
set atmStatus to atmUnjunkCopy(item 1 of atmItem, item 2 of atmItem, item 3 of atmItem, item 4 of atmItem, guardName)
|
|
2192
|
+
end if
|
|
2193
|
+
set atmOut to atmOut & (item 3 of atmItem) & tab & atmStatus & linefeed
|
|
2194
|
+
end repeat
|
|
2195
|
+
return atmOut`;
|
|
2196
|
+
}
|
|
2197
|
+
|
|
2198
|
+
/**
|
|
2199
|
+
* mail_unjunk: move the Junk copies of message_ids (from mail_find) to each
|
|
2200
|
+
* account's Inbox. Copies anywhere else are never touched; nothing is
|
|
2201
|
+
* deleted, marked or sent. Not destructive (Inbox is where mail lands), so
|
|
2202
|
+
* it needs no confirm; dry_run previews.
|
|
2203
|
+
*/
|
|
2204
|
+
export function mailUnjunk(args = {}, { locate = locateMessageCopies, budgetSec = MAIL_BULK_TRASH_BUDGET_SEC } = {}) {
|
|
2205
|
+
const action = "mail_unjunk";
|
|
2206
|
+
if (args.message_id || args.file_path) {
|
|
2207
|
+
return { ok: false, message: `${action} refused: pass message_ids (a list, e.g. from mail_find), not message_id / file_path.` };
|
|
2208
|
+
}
|
|
2209
|
+
const raw = normalizeList(args.message_ids);
|
|
2210
|
+
if (raw.length === 0) return { ok: false, message: `${action} refused: message_ids is empty.` };
|
|
2211
|
+
if (raw.length > MAIL_TRASH_MAX_IDS) {
|
|
2212
|
+
return { ok: false, message: `${action} refused: message_ids accepts at most ${MAIL_TRASH_MAX_IDS} ids per call.` };
|
|
2213
|
+
}
|
|
2214
|
+
const ids = [];
|
|
2215
|
+
for (const value of raw) {
|
|
2216
|
+
const id = validateMessageId(value);
|
|
2217
|
+
if (!id) return { ok: false, message: `${action} refused: message_ids contains an invalid RFC822 Message-ID.` };
|
|
2218
|
+
if (!ids.includes(id)) ids.push(id);
|
|
2219
|
+
}
|
|
2220
|
+
let guard = "";
|
|
2221
|
+
if (args.from_name_contains !== undefined && args.from_name_contains !== null) {
|
|
2222
|
+
if (typeof args.from_name_contains !== "string") return { ok: false, message: `${action} refused: from_name_contains must be a string.` };
|
|
2223
|
+
guard = args.from_name_contains.replace(/\s+/g, " ").trim();
|
|
2224
|
+
if (guard.length > MAX_NAME_GUARD) return { ok: false, message: `${action} refused: from_name_contains is longer than ${MAX_NAME_GUARD} characters.` };
|
|
2225
|
+
}
|
|
2226
|
+
|
|
2227
|
+
let located;
|
|
2228
|
+
try {
|
|
2229
|
+
located = locate(ids);
|
|
2230
|
+
} catch (e) {
|
|
2231
|
+
return { ok: false, message: `${action} failed — could not look the messages up. ${e.message}` };
|
|
2232
|
+
}
|
|
2233
|
+
const junk = located.copies.filter((c) => c.mailbox === "junk");
|
|
2234
|
+
const movable = junk.filter((c) => c.account_id);
|
|
2235
|
+
const unaddressable = junk.length - movable.length;
|
|
2236
|
+
const withJunk = new Set(junk.map((c) => c.message_id));
|
|
2237
|
+
const notInJunk = ids.length - located.missingIds.length - withJunk.size;
|
|
2238
|
+
const summary = `move ${plural(movable.length, "Junk copy", "Junk copies")} of ${plural(withJunk.size, "message")} to the Inbox` +
|
|
2239
|
+
(guard ? ` (sender name must still contain "${truncate(guard, 60)}")` : "");
|
|
2240
|
+
|
|
2241
|
+
const plan = planWrite({ action, summary, dryRun: isFlagTrue(args.dry_run), confirm: isFlagTrue(args.confirm) });
|
|
2242
|
+
if (!plan.proceed) return plannedWriteResult(plan);
|
|
2243
|
+
|
|
2244
|
+
const base = { not_in_junk: notInJunk || undefined, not_found: located.missingIds.length || undefined, unaddressable: unaddressable || undefined };
|
|
2245
|
+
if (movable.length === 0) return { ok: true, message: writeSuccessMessage(action, "nothing to move", base) };
|
|
2246
|
+
|
|
2247
|
+
const result = runAppleScript(buildUnjunkScript(movable, { fromNameContains: guard, budgetSec }), {
|
|
2248
|
+
timeout: MCP_CALL_DEADLINE_MS,
|
|
2249
|
+
appName: "Mail"
|
|
2250
|
+
});
|
|
2251
|
+
if (!result.ok) return { ok: false, message: failure(action, summary, result, []) };
|
|
2252
|
+
|
|
2253
|
+
const statuses = parseBulkTrashOutput(result.output);
|
|
2254
|
+
const counts = { moved: 0, stale: 0, nameMismatch: 0, remaining: 0, failed: 0 };
|
|
2255
|
+
const failures = new Set();
|
|
2256
|
+
for (const copy of movable) {
|
|
2257
|
+
const status = statuses.get(copy.id) || "skipped";
|
|
2258
|
+
if (status === "moved") counts.moved += 1;
|
|
2259
|
+
else if (status === "missing" || status === "mismatch") counts.stale += 1;
|
|
2260
|
+
else if (status === "name_mismatch") counts.nameMismatch += 1;
|
|
2261
|
+
else if (status === "skipped") counts.remaining += 1;
|
|
2262
|
+
else {
|
|
2263
|
+
counts.failed += 1;
|
|
2264
|
+
failures.add(status);
|
|
2265
|
+
}
|
|
2266
|
+
}
|
|
2267
|
+
const details = {
|
|
2268
|
+
moved: counts.moved,
|
|
2269
|
+
copies: movable.length,
|
|
2270
|
+
...base,
|
|
2271
|
+
name_mismatch: counts.nameMismatch || undefined,
|
|
2272
|
+
stale: counts.stale || undefined,
|
|
2273
|
+
remaining: counts.remaining || undefined,
|
|
2274
|
+
failed: counts.failed || undefined,
|
|
2275
|
+
failure_reasons: failures.size ? [...failures].join(", ") : undefined
|
|
2276
|
+
};
|
|
2277
|
+
const tail = counts.remaining ? " Time budget reached; run again for the rest." : "";
|
|
2278
|
+
const message = writeSuccessMessage(action, `moved ${counts.moved} of ${plural(movable.length, "Junk copy", "Junk copies")} to the Inbox`, details) + tail;
|
|
2279
|
+
return { ok: counts.failed === 0, message };
|
|
2280
|
+
}
|
package/lib/urlQuery.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// Meeting links in calendar titles and locations often carry the join passcode
|
|
2
|
+
// in their query string (zoom.us/j/123?pwd=...). Calendar tools print each URL
|
|
3
|
+
// with its scheme, host and path only: the ?query and #fragment are dropped, so
|
|
4
|
+
// a passcode never reaches a chat that reads the calendar.
|
|
5
|
+
//
|
|
6
|
+
// A URL here is a scheme with "//" (https://, zoommtg://), a "www." host, or a
|
|
7
|
+
// bare host.tld/ path. The query runs to the next space, angle bracket or quote;
|
|
8
|
+
// closing ) or ] at its end are kept, since they close the text around the URL.
|
|
9
|
+
const URL_WITH_QUERY = /((?:\b[a-z][a-z0-9+.-]*:\/\/|\bwww\.|\b[a-z0-9-]+(?:\.[a-z0-9-]+)*\.[a-z]{2,}\/)[^\s?#<>"']*)([?#][^\s<>"']*)/gi;
|
|
10
|
+
|
|
11
|
+
export function stripUrlQueries(text) {
|
|
12
|
+
if (typeof text !== "string" || !text) return text;
|
|
13
|
+
return text.replace(URL_WITH_QUERY, (_, url, query) => url + (query.match(/[)\]]+$/) || [""])[0]);
|
|
14
|
+
}
|
package/lib/writeTools.js
CHANGED
|
@@ -17,7 +17,8 @@ import {
|
|
|
17
17
|
mailForward,
|
|
18
18
|
mailMark,
|
|
19
19
|
mailArchive,
|
|
20
|
-
mailTrash
|
|
20
|
+
mailTrash,
|
|
21
|
+
mailUnjunk
|
|
21
22
|
} from "./mailWrite.js";
|
|
22
23
|
import { messagesSend } from "./messagesWrite.js";
|
|
23
24
|
import {
|
|
@@ -179,6 +180,20 @@ export const WRITE_TOOL_DEFINITIONS = [
|
|
|
179
180
|
}
|
|
180
181
|
},
|
|
181
182
|
|
|
183
|
+
{
|
|
184
|
+
name: "mail_unjunk",
|
|
185
|
+
description: "Move the Junk copies of messages (message_ids, e.g. from mail_find with mailboxes ['junk']) to that account's Inbox, on the server for IMAP accounts. Copies in any other mailbox are never touched; nothing is deleted, marked or sent. Each copy's Message-ID is re-checked before it moves, and with from_name_contains the sender's display name must still contain that text (any case) or the copy stays in Junk. Not destructive, so no confirm is needed; dry_run previews. A call stops starting new moves after ~35s and reports 'remaining'; run it again for the rest.",
|
|
186
|
+
inputSchema: {
|
|
187
|
+
type: "object",
|
|
188
|
+
properties: {
|
|
189
|
+
message_ids: { type: "array", items: { type: "string" }, description: "RFC822 Message-IDs (up to 500). Only their Junk copies move." },
|
|
190
|
+
from_name_contains: { type: "string", description: "Optional guard: move a copy only if its sender's display name still contains this text (case-insensitive)" },
|
|
191
|
+
...CONFIRM_PROPS
|
|
192
|
+
},
|
|
193
|
+
required: ["message_ids"]
|
|
194
|
+
}
|
|
195
|
+
},
|
|
196
|
+
|
|
182
197
|
// ============ MESSAGES WRITES ============
|
|
183
198
|
{
|
|
184
199
|
name: "messages_send",
|
|
@@ -351,6 +366,7 @@ export const WRITE_TOOL_HANDLERS = {
|
|
|
351
366
|
mail_mark: mailMark,
|
|
352
367
|
mail_archive: mailArchive,
|
|
353
368
|
mail_trash: mailTrash,
|
|
369
|
+
mail_unjunk: mailUnjunk,
|
|
354
370
|
messages_send: messagesSend,
|
|
355
371
|
calendar_list_calendars: () => calendarListCalendars(),
|
|
356
372
|
calendar_add: calendarAdd,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "apple-tools-mcp",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.4.1",
|
|
4
4
|
"description": "MCP server for semantic search and write actions across Apple Mail, Messages, Calendar, and Contacts. Speaks stdio (local) or bearer-token-authenticated Streamable HTTP (LAN / Tailscale).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "index.js",
|
package/search.js
CHANGED
|
@@ -4,6 +4,7 @@ import { safeMatch, validateSearchQuery, toUnixMillis } from "./lib/validators.j
|
|
|
4
4
|
import { embed, getOpenTable, getRecentEmails, getEmailsByDateRange, getRecentMessages, getConversation, getEventsOnDate, resolveEmail, resolvePhone, resolveByExactName, normalizePhone, formatContact } from "./indexer.js";
|
|
5
5
|
import { createMessageContactMatcher, describeMessagePeer } from "./lib/messageContact.js";
|
|
6
6
|
import { indexUnavailableMessage } from "./lib/indexGate.js";
|
|
7
|
+
import { stripUrlQueries } from "./lib/urlQuery.js";
|
|
7
8
|
|
|
8
9
|
// ============ CACHING ============
|
|
9
10
|
|
|
@@ -1524,11 +1525,12 @@ export function formatCalendarResults(searchResult) {
|
|
|
1524
1525
|
const results = searchResult.results.map(r => {
|
|
1525
1526
|
let result = `[${r.rank || r.index}]`;
|
|
1526
1527
|
if (r.score) result += ` Score: ${r.score}`;
|
|
1527
|
-
|
|
1528
|
+
// Meeting-link passcodes ride in URL query strings: titles and locations print URLs without them.
|
|
1529
|
+
result += `\nEvent: ${stripUrlQueries(r.title)}`;
|
|
1528
1530
|
if (r.isAllDay) result += " (All Day)";
|
|
1529
1531
|
result += `\nCalendar: ${r.calendar}\nStart: ${r.start}\nEnd: ${r.end}`;
|
|
1530
1532
|
if (r.eventId) result += `\nEvent ID: ${r.eventId}`;
|
|
1531
|
-
if (r.location) result += `\nLocation: ${r.location}`;
|
|
1533
|
+
if (r.location) result += `\nLocation: ${stripUrlQueries(r.location)}`;
|
|
1532
1534
|
if (r.attendees && r.attendees.length > 0) {
|
|
1533
1535
|
const attendeeList = r.attendees.map(a => `${a.name} (${a.status})`).join(", ");
|
|
1534
1536
|
result += `\nAttendees: ${attendeeList}`;
|
|
@@ -1626,10 +1628,10 @@ export function formatUpcomingEventsResults(result) {
|
|
|
1626
1628
|
let output = "";
|
|
1627
1629
|
for (let i = 0; i < events.length; i++) {
|
|
1628
1630
|
const e = events[i];
|
|
1629
|
-
output += `${i + 1}. ${e.title || "No title"}${e.isAllDay ? " (All Day)" : ""}\n`;
|
|
1631
|
+
output += `${i + 1}. ${stripUrlQueries(e.title) || "No title"}${e.isAllDay ? " (All Day)" : ""}\n`;
|
|
1630
1632
|
output += ` ${e.start}${e.isAllDay ? "" : ` - ${e.end}`}\n`;
|
|
1631
1633
|
output += ` Calendar: ${e.calendar || "Unknown"}`;
|
|
1632
|
-
if (e.location) output += ` | Location: ${e.location}`;
|
|
1634
|
+
if (e.location) output += ` | Location: ${stripUrlQueries(e.location)}`;
|
|
1633
1635
|
output += "\n\n";
|
|
1634
1636
|
}
|
|
1635
1637
|
|
|
@@ -1672,7 +1674,7 @@ export function formatWeekEventsResults(result) {
|
|
|
1672
1674
|
output += `${day}:\n`;
|
|
1673
1675
|
for (const e of dayEvents) {
|
|
1674
1676
|
const time = e.isAllDay ? "All Day" : e.start.split(" ")[1];
|
|
1675
|
-
output += ` • ${time} - ${e.title || "No title"}`;
|
|
1677
|
+
output += ` • ${time} - ${stripUrlQueries(e.title) || "No title"}`;
|
|
1676
1678
|
if (e.calendar) output += ` [${e.calendar}]`;
|
|
1677
1679
|
output += "\n";
|
|
1678
1680
|
}
|
|
@@ -1723,7 +1725,7 @@ export function formatRecurringEventsResults(result) {
|
|
|
1723
1725
|
|
|
1724
1726
|
let output = "";
|
|
1725
1727
|
for (const e of events) {
|
|
1726
|
-
output += ` • ${e.title || "No title"}${e.isAllDay ? " (All Day)" : ""}\n`;
|
|
1728
|
+
output += ` • ${stripUrlQueries(e.title) || "No title"}${e.isAllDay ? " (All Day)" : ""}\n`;
|
|
1727
1729
|
output += ` Next: ${e.start} | Calendar: ${e.calendar || "Unknown"}\n`;
|
|
1728
1730
|
output += ` Occurrences: ${e.occurrenceCount}\n\n`;
|
|
1729
1731
|
}
|