apple-tools-mcp 3.3.4 → 3.4.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/README.md +6 -3
- package/index.js +6 -6
- package/indexer.js +34 -13
- package/lib/mailFind.js +9 -5
- package/lib/mailWrite.js +157 -0
- package/lib/writeTools.js +17 -1
- package/package.json +1 -1
- package/search.js +12 -0
package/README.md
CHANGED
|
@@ -278,7 +278,7 @@ Your client can also call `audit_index`.
|
|
|
278
278
|
| `mail_read` | Full email content by file path. |
|
|
279
279
|
| `mail_senders` | Most frequent senders. |
|
|
280
280
|
| `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. |
|
|
281
|
+
| `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
282
|
| `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
283
|
|
|
284
284
|
### Messages
|
|
@@ -295,8 +295,8 @@ Your client can also call `audit_index`.
|
|
|
295
295
|
| Tool | Description |
|
|
296
296
|
|------|-------------|
|
|
297
297
|
| `calendar_search` | Semantic search for events, with filters. |
|
|
298
|
-
| `calendar_date` | Events on a date, read live from Calendar rather than the search index. |
|
|
299
|
-
| `calendar_upcoming` | Next
|
|
298
|
+
| `calendar_date` | Events on a date, read live from Calendar rather than the search index. A failed read is an error, never an empty day. |
|
|
299
|
+
| `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
300
|
| `calendar_week` | Events for this week or a future week. |
|
|
301
301
|
| `calendar_free_time` | Open time on a date, read live from Calendar rather than the search index. |
|
|
302
302
|
| `calendar_recurring` | Recurring events. |
|
|
@@ -358,11 +358,14 @@ A missing or malformed id or recipient is refused. Calendar times are local date
|
|
|
358
358
|
| `mail_mark` | `message_id` or `file_path`, `status` (`read` or `unread`, default `read`) | no |
|
|
359
359
|
| `mail_archive` | `message_id` or `file_path` | no |
|
|
360
360
|
| `mail_trash` | `message_id` or `file_path`, or `message_ids[]` (up to 500) | yes |
|
|
361
|
+
| `mail_unjunk` | `message_ids[]` (required, up to 500), `from_name_contains` | no |
|
|
361
362
|
|
|
362
363
|
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
364
|
|
|
364
365
|
`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
366
|
|
|
367
|
+
`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`.
|
|
368
|
+
|
|
366
369
|
`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
370
|
|
|
368
371
|
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
|
@@ -219,6 +219,7 @@ import {
|
|
|
219
219
|
formatSendersResults,
|
|
220
220
|
formatMessageContactsResults,
|
|
221
221
|
formatUpcomingEventsResults,
|
|
222
|
+
requireCalendarRead,
|
|
222
223
|
formatWeekEventsResults,
|
|
223
224
|
formatEmailThreadResults,
|
|
224
225
|
formatRecurringEventsResults
|
|
@@ -576,13 +577,11 @@ async function calendarSearch(query, options = {}) {
|
|
|
576
577
|
}
|
|
577
578
|
|
|
578
579
|
async function calendarDate(date) {
|
|
579
|
-
|
|
580
|
-
return formatCalendarResults(result);
|
|
580
|
+
return formatCalendarResults(requireCalendarRead(await getCalendarDateResults(date)));
|
|
581
581
|
}
|
|
582
582
|
|
|
583
583
|
async function calendarFreeTime(date, options = {}) {
|
|
584
|
-
|
|
585
|
-
return formatFreeTimeResults(result);
|
|
584
|
+
return formatFreeTimeResults(requireCalendarRead(await calculateFreeTime(date, options)));
|
|
586
585
|
}
|
|
587
586
|
|
|
588
587
|
// Mail directory for path validation
|
|
@@ -1157,13 +1156,14 @@ function createServer() {
|
|
|
1157
1156
|
},
|
|
1158
1157
|
{
|
|
1159
1158
|
name: "mail_find",
|
|
1160
|
-
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.",
|
|
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, 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.",
|
|
1161
1160
|
inputSchema: {
|
|
1162
1161
|
type: "object",
|
|
1163
1162
|
properties: {
|
|
1164
1163
|
subject_prefix: { type: "string", description: "Subject starts with this text (case-insensitive), e.g. '[Network] '" },
|
|
1165
1164
|
subject_contains: { type: "string", description: "Subject contains this text (case-insensitive)" },
|
|
1166
1165
|
from: { type: "string", description: "Exact sender address" },
|
|
1166
|
+
from_name_contains: { type: "string", description: "Sender display name contains this text (case-insensitive; Mail stores the name decoded), e.g. 'via Cloaked'" },
|
|
1167
1167
|
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)" },
|
|
1168
1168
|
to: { type: "string", description: "Exact recipient address (To or Cc)" },
|
|
1169
1169
|
to_only: { type: "boolean", description: "With to: that address is the only recipient" },
|
|
@@ -1618,7 +1618,7 @@ function createServer() {
|
|
|
1618
1618
|
|
|
1619
1619
|
// Calendar tools
|
|
1620
1620
|
case "calendar_upcoming":
|
|
1621
|
-
result = formatUpcomingEventsResults(getUpcomingEvents(validateLimit(args?.limit, 30, 100)));
|
|
1621
|
+
result = formatUpcomingEventsResults(requireCalendarRead(getUpcomingEvents(validateLimit(args?.limit, 30, 100))));
|
|
1622
1622
|
break;
|
|
1623
1623
|
|
|
1624
1624
|
// ============ NEW TOOLS - PHASE 2 ============
|
package/indexer.js
CHANGED
|
@@ -1990,19 +1990,15 @@ export function getMessageContacts(limit = 50) {
|
|
|
1990
1990
|
}
|
|
1991
1991
|
}
|
|
1992
1992
|
|
|
1993
|
-
// calendar_upcoming: Get next N upcoming events
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
|
|
1997
|
-
|
|
1998
|
-
|
|
1999
|
-
const fetchLimit = safeLimit + 1; // Fetch one extra to detect if more exist
|
|
2000
|
-
|
|
2001
|
-
// Query OccurrenceCache to include recurring event occurrences
|
|
2002
|
-
const query = `
|
|
1993
|
+
// calendar_upcoming: Get next N upcoming events, starting with every event on the current local day.
|
|
1994
|
+
// OccurrenceCache.day is each occurrence's local midnight, so the lower bound is today's local midnight,
|
|
1995
|
+
// never now: comparing day to now dropped all of today (all-day and later-today events) after midnight.
|
|
1996
|
+
export function buildUpcomingEventsQuery(dayStartMac, fetchLimit) {
|
|
1997
|
+
const occStart = "COALESCE(oc.occurrence_end_date - (ci.end_date - ci.start_date), ci.start_date)";
|
|
1998
|
+
return `
|
|
2003
1999
|
SELECT
|
|
2004
2000
|
ci.summary as title,
|
|
2005
|
-
datetime(
|
|
2001
|
+
datetime(${occStart} + 978307200, 'unixepoch', 'localtime') as start,
|
|
2006
2002
|
datetime(COALESCE(oc.occurrence_end_date, ci.end_date) + 978307200, 'unixepoch', 'localtime') as end,
|
|
2007
2003
|
ci.all_day as isAllDay,
|
|
2008
2004
|
c.title as calendar,
|
|
@@ -2012,11 +2008,35 @@ export function getUpcomingEvents(limit = 10) {
|
|
|
2012
2008
|
INNER JOIN CalendarItem ci ON oc.event_id = ci.ROWID
|
|
2013
2009
|
LEFT JOIN Calendar c ON ci.calendar_id = c.ROWID
|
|
2014
2010
|
LEFT JOIN Location l ON ci.location_id = l.ROWID
|
|
2015
|
-
WHERE oc.day >= ${
|
|
2016
|
-
ORDER BY sort_day ASC
|
|
2011
|
+
WHERE oc.day >= ${dayStartMac} AND ci.summary IS NOT NULL AND ci.summary <> ''
|
|
2012
|
+
ORDER BY sort_day ASC, ci.all_day DESC, ${occStart} ASC, title ASC
|
|
2017
2013
|
LIMIT ${fetchLimit}
|
|
2018
2014
|
`;
|
|
2015
|
+
}
|
|
2016
|
+
|
|
2017
|
+
// Start of the current local day, in Apple/Core Data seconds.
|
|
2018
|
+
function localTodayStartMac() {
|
|
2019
|
+
const midnight = new Date();
|
|
2020
|
+
midnight.setHours(0, 0, 0, 0);
|
|
2021
|
+
return Math.floor(midnight.getTime() / 1000) - MAC_ABSOLUTE_EPOCH;
|
|
2022
|
+
}
|
|
2023
|
+
|
|
2024
|
+
// A copy with no OccurrenceCache rows at all is not a readable calendar: say so instead of an empty day.
|
|
2025
|
+
function assertOccurrenceCache(dbPath) {
|
|
2026
|
+
const rows = safeSqlite3Json(dbPath, "SELECT COUNT(*) AS n FROM (SELECT 1 FROM OccurrenceCache LIMIT 1)", { timeout: 10000 });
|
|
2027
|
+
if (!rows.length || !Number(rows[0].n)) {
|
|
2028
|
+
throw new Error("Calendar OccurrenceCache is empty, so the calendar could not be read");
|
|
2029
|
+
}
|
|
2030
|
+
}
|
|
2031
|
+
|
|
2032
|
+
export function getUpcomingEvents(limit = 10) {
|
|
2033
|
+
try {
|
|
2034
|
+
// Validate limit to prevent SQL issues
|
|
2035
|
+
const safeLimit = validateLimit(limit, 10, 100);
|
|
2036
|
+
const fetchLimit = safeLimit + 1; // Fetch one extra to detect if more exist
|
|
2037
|
+
const query = buildUpcomingEventsQuery(localTodayStartMac(), fetchLimit);
|
|
2019
2038
|
const events = withCalendarCopy((dbPath) => {
|
|
2039
|
+
assertOccurrenceCache(dbPath);
|
|
2020
2040
|
return safeSqlite3Json(dbPath, query, { timeout: 10000 });
|
|
2021
2041
|
});
|
|
2022
2042
|
const hasMore = events.length > safeLimit;
|
|
@@ -2149,6 +2169,7 @@ export function getEventsOnDate(startMs, endMs) {
|
|
|
2149
2169
|
const query = buildEventsOnDateQuery(startMac, endMac, { includeUid: attempt === 0 });
|
|
2150
2170
|
try {
|
|
2151
2171
|
const events = withCalendarCopy((dbPath) => {
|
|
2172
|
+
assertOccurrenceCache(dbPath);
|
|
2152
2173
|
return safeSqlite3Json(dbPath, query, { timeout: 15000 });
|
|
2153
2174
|
});
|
|
2154
2175
|
return { events, error: null };
|
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/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.0",
|
|
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
|
@@ -1601,6 +1601,18 @@ export function formatMessageContactsResults(contacts) {
|
|
|
1601
1601
|
return output;
|
|
1602
1602
|
}
|
|
1603
1603
|
|
|
1604
|
+
// A calendar tool result that failed to read the calendar becomes a thrown error, so the MCP
|
|
1605
|
+
// dispatcher answers isError: true. A failed read must never look like an empty day.
|
|
1606
|
+
export function requireCalendarRead(result) {
|
|
1607
|
+
if (result?.success === false) {
|
|
1608
|
+
throw new Error(result.error || "The calendar could not be read");
|
|
1609
|
+
}
|
|
1610
|
+
if (result?.error) {
|
|
1611
|
+
throw new Error(`Error getting upcoming events: ${result.error}`);
|
|
1612
|
+
}
|
|
1613
|
+
return result;
|
|
1614
|
+
}
|
|
1615
|
+
|
|
1604
1616
|
// Format calendar_upcoming results
|
|
1605
1617
|
export function formatUpcomingEventsResults(result) {
|
|
1606
1618
|
if (result?.error) {
|