langmail-mcp 0.1.0 → 0.2.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.
Files changed (137) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +89 -169
  3. package/dist/chunk-ad2666h8.js +12696 -0
  4. package/dist/langmail-mcp.js +7 -0
  5. package/package.json +94 -98
  6. package/THIRD_PARTY_NOTICES.md +0 -388
  7. package/dist/attachments/download.js +0 -69
  8. package/dist/attachments/routes.js +0 -42
  9. package/dist/attachments/tickets.js +0 -45
  10. package/dist/attachments/upload-tickets.js +0 -43
  11. package/dist/attachments/upload.js +0 -136
  12. package/dist/caldav/account-settings.js +0 -92
  13. package/dist/caldav/agenda.js +0 -277
  14. package/dist/caldav/alarm.js +0 -97
  15. package/dist/caldav/client.js +0 -408
  16. package/dist/caldav/ical.js +0 -248
  17. package/dist/caldav/occurrence.js +0 -534
  18. package/dist/caldav/recurrence.js +0 -313
  19. package/dist/caldav/rsvp.js +0 -107
  20. package/dist/caldav/scheduling-handover.js +0 -22
  21. package/dist/caldav/timezone.js +0 -103
  22. package/dist/caldav/types.js +0 -5
  23. package/dist/config.js +0 -219
  24. package/dist/contacts/address-class.js +0 -79
  25. package/dist/contacts/birthdays.js +0 -81
  26. package/dist/contacts/card.js +0 -58
  27. package/dist/contacts/constants.js +0 -46
  28. package/dist/contacts/fold.js +0 -309
  29. package/dist/contacts/index.js +0 -10
  30. package/dist/contacts/merge.js +0 -388
  31. package/dist/contacts/observations.js +0 -115
  32. package/dist/contacts/profile.js +0 -402
  33. package/dist/contacts/scoring.js +0 -146
  34. package/dist/contacts/types.js +0 -7
  35. package/dist/contacts/upsert.js +0 -131
  36. package/dist/drafts/attachments.js +0 -254
  37. package/dist/drafts/idempotency.js +0 -60
  38. package/dist/drafts/send-guard.js +0 -184
  39. package/dist/email-render/email-viewer.html +0 -143
  40. package/dist/email-render/image-proxy.js +0 -389
  41. package/dist/email-render/meta.js +0 -48
  42. package/dist/email-render/sanitize.js +0 -93
  43. package/dist/email-render/viewer-resource.js +0 -104
  44. package/dist/http/bearer.js +0 -30
  45. package/dist/http/guard.js +0 -57
  46. package/dist/http/hosts.js +0 -10
  47. package/dist/http/listener.js +0 -170
  48. package/dist/http/routes.js +0 -72
  49. package/dist/ical/ical-parse.js +0 -357
  50. package/dist/ical/index.js +0 -4
  51. package/dist/ical/timezone.js +0 -22
  52. package/dist/ical/windows-zones.js +0 -155
  53. package/dist/index.js +0 -79
  54. package/dist/jmap/blob.js +0 -49
  55. package/dist/jmap/contacts.js +0 -226
  56. package/dist/jmap/drafts.js +0 -480
  57. package/dist/jmap/email.js +0 -668
  58. package/dist/jmap/index.js +0 -12
  59. package/dist/jmap/keywords.js +0 -22
  60. package/dist/jmap/live.js +0 -21
  61. package/dist/jmap/origin.js +0 -113
  62. package/dist/jmap/patch.js +0 -29
  63. package/dist/jmap/request.js +0 -37
  64. package/dist/jmap/session.js +0 -89
  65. package/dist/jmap/sieve.js +0 -71
  66. package/dist/jmap/submission.js +0 -107
  67. package/dist/jmap/timeout.js +0 -30
  68. package/dist/jmap/types.js +0 -6
  69. package/dist/logger.js +0 -48
  70. package/dist/mcp/handler.js +0 -255
  71. package/dist/mcp/http.js +0 -29
  72. package/dist/mcp/instructions.js +0 -44
  73. package/dist/mcp/links.js +0 -64
  74. package/dist/mcp/tool-logging.js +0 -67
  75. package/dist/observability/errors.js +0 -41
  76. package/dist/rules/apply.js +0 -236
  77. package/dist/rules/rule.js +0 -280
  78. package/dist/rules/store.js +0 -92
  79. package/dist/tools/annotations.js +0 -71
  80. package/dist/tools/archive-emails.js +0 -40
  81. package/dist/tools/calendar-lookup.js +0 -64
  82. package/dist/tools/contact-common.js +0 -146
  83. package/dist/tools/contact-format.js +0 -72
  84. package/dist/tools/contact-write-through.js +0 -37
  85. package/dist/tools/create-calendar-event.js +0 -231
  86. package/dist/tools/create-calendar.js +0 -54
  87. package/dist/tools/create-contact.js +0 -172
  88. package/dist/tools/create-draft.js +0 -369
  89. package/dist/tools/create-mail-rule.js +0 -101
  90. package/dist/tools/delete-calendar-event.js +0 -165
  91. package/dist/tools/delete-contact.js +0 -60
  92. package/dist/tools/delete-draft.js +0 -129
  93. package/dist/tools/delete-mail-rule.js +0 -38
  94. package/dist/tools/download-attachment.js +0 -90
  95. package/dist/tools/download-email.js +0 -112
  96. package/dist/tools/draft-common.js +0 -600
  97. package/dist/tools/email-types.js +0 -58
  98. package/dist/tools/error-detail.js +0 -10
  99. package/dist/tools/file-emails-common.js +0 -75
  100. package/dist/tools/format.js +0 -131
  101. package/dist/tools/forward-message.js +0 -237
  102. package/dist/tools/forward-quote.js +0 -179
  103. package/dist/tools/get-draft.js +0 -61
  104. package/dist/tools/get-email.js +0 -164
  105. package/dist/tools/get-thread.js +0 -67
  106. package/dist/tools/keywords.js +0 -43
  107. package/dist/tools/list-calendar-events.js +0 -180
  108. package/dist/tools/list-calendars.js +0 -44
  109. package/dist/tools/list-drafts.js +0 -134
  110. package/dist/tools/list-mail-rules.js +0 -28
  111. package/dist/tools/list-unsubscribe.js +0 -152
  112. package/dist/tools/list-upcoming-birthdays.js +0 -165
  113. package/dist/tools/mail-rule-common.js +0 -43
  114. package/dist/tools/mail-rule-format.js +0 -79
  115. package/dist/tools/mailbox-lookup.js +0 -13
  116. package/dist/tools/mark-emails.js +0 -78
  117. package/dist/tools/merge-contacts.js +0 -145
  118. package/dist/tools/move-calendar-events.js +0 -340
  119. package/dist/tools/move-emails.js +0 -64
  120. package/dist/tools/one-click-post.js +0 -275
  121. package/dist/tools/preview-email.js +0 -204
  122. package/dist/tools/preview-mail-rule.js +0 -79
  123. package/dist/tools/reply-quote.js +0 -426
  124. package/dist/tools/reply-to-message.js +0 -292
  125. package/dist/tools/respond-to-event.js +0 -110
  126. package/dist/tools/result.js +0 -9
  127. package/dist/tools/search-contacts.js +0 -431
  128. package/dist/tools/search-emails.js +0 -570
  129. package/dist/tools/send-draft.js +0 -308
  130. package/dist/tools/trash-emails.js +0 -36
  131. package/dist/tools/unsubscribe-from-list.js +0 -249
  132. package/dist/tools/update-calendar-event.js +0 -973
  133. package/dist/tools/update-calendar.js +0 -100
  134. package/dist/tools/update-contact.js +0 -382
  135. package/dist/tools/update-draft.js +0 -714
  136. package/dist/tools/update-mail-rule.js +0 -103
  137. package/dist/tools/upload-attachments.js +0 -126
@@ -1,100 +0,0 @@
1
- // update_calendar tool — renames and/or recolors one of the principal's
2
- // calendars with a CalDAV PROPPATCH of `displayname` and `calendar-color`.
3
- //
4
- // The calendar is picked by its current name or its URL; see calendar-lookup.ts.
5
- //
6
- // Like the other CalDAV tools, the logic sits behind a `Deps` interface so it
7
- // unit-tests without live Stalwart; `makeLiveDeps` wires tsdav in.
8
- import { z } from "zod";
9
- import { fetchCalendarList, updateCalendar as updateCalendarCollection, } from "../caldav/client.js";
10
- import { ACCOUNT_WRITE } from "./annotations.js";
11
- import { calendarLabel, normalizeCalendarName, resolveCalendar, } from "./calendar-lookup.js";
12
- import { colorSchema } from "./create-calendar.js";
13
- import { errorResult, textResult } from "./result.js";
14
- const updateCalendarShape = {
15
- calendar: z
16
- .string()
17
- .trim()
18
- .min(1)
19
- .describe("The calendar to change: its current name (matched ignoring case) or its URL, both as " +
20
- "list_calendars shows them. Use the URL when two calendars share a name."),
21
- color: colorSchema
22
- .optional()
23
- .describe('New color as a hex value, e.g. "#2E6FD8". Omit to keep the current color.'),
24
- name: z
25
- .string()
26
- .trim()
27
- .min(1)
28
- .max(200)
29
- .optional()
30
- .describe("New name; must differ from every other calendar’s name. Omit to keep the current name."),
31
- };
32
- export const updateCalendarInput = z.object(updateCalendarShape);
33
- const describeChanges = (args) => [
34
- ...(args.name === undefined ? [] : [`name → "${args.name}"`]),
35
- ...(args.color === undefined ? [] : [`color → ${args.color}`]),
36
- ].join(", ");
37
- export const updateCalendar = async (deps, ctx) => {
38
- const { args, token } = ctx;
39
- if (args.name === undefined && args.color === undefined) {
40
- return errorResult("Nothing to change. Pass name, color, or both.");
41
- }
42
- const calendars = await deps.listCalendars(token);
43
- const resolved = resolveCalendar(calendars, args.calendar, {
44
- argName: "calendar",
45
- nothingDone: "Nothing was changed.",
46
- });
47
- if (!resolved.ok) {
48
- return resolved.error;
49
- }
50
- const target = resolved.calendar;
51
- // A duplicate name would make every later lookup by that name ambiguous.
52
- if (args.name !== undefined) {
53
- const newName = args.name;
54
- const taken = calendars.find((c) => c.url !== target.url &&
55
- normalizeCalendarName(c.displayName) === normalizeCalendarName(newName));
56
- if (taken) {
57
- return errorResult(`Another calendar is already named "${taken.displayName}" (${taken.url}). Nothing was changed. ` +
58
- "Pick a different name, or rename that calendar first with update_calendar.");
59
- }
60
- }
61
- try {
62
- await deps.updateCalendar({
63
- color: args.color,
64
- name: args.name,
65
- token,
66
- url: target.url,
67
- });
68
- }
69
- catch (err) {
70
- const reason = err instanceof Error ? err.message : String(err);
71
- // PROPPATCH is all-or-nothing (RFC 4918 §9.2), so a refusal changed nothing.
72
- return errorResult(`Could not update calendar "${calendarLabel(target)}": ${reason}. Nothing was changed. ` +
73
- "The calendar may be read-only for this account; check it with list_calendars.");
74
- }
75
- return textResult(`Calendar "${calendarLabel(target)}" updated: ${describeChanges(args)}.\ncalendarUrl: ${target.url}`);
76
- };
77
- // --- live-deps wiring ----------------------------------------------------
78
- export const makeLiveDeps = (cfg) => ({
79
- listCalendars: (token) => fetchCalendarList(cfg, token),
80
- updateCalendar: (params) => updateCalendarCollection(cfg, params),
81
- });
82
- // --- MCP registration ----------------------------------------------------
83
- export const registerUpdateCalendar = (server, deps,
84
- // Bearer threaded per request — see mcp/handler.ts.
85
- getToken) => {
86
- server.registerTool("update_calendar", {
87
- annotations: ACCOUNT_WRITE,
88
- description: "Renames or recolors one of the user’s calendars — the calendar itself, not an event on it. " +
89
- "Use this when the user wants to rename a calendar or change its color; name the calendar by " +
90
- "its current name or its URL from list_calendars. Returns the changes made and the calendar’s " +
91
- "URL; when no calendar matches, the error lists every calendar with its URL, and nothing is " +
92
- "changed. To change an event, use update_calendar_event; to add a new calendar, use " +
93
- "create_calendar. Safe to re-run.",
94
- inputSchema: z.object(updateCalendarShape),
95
- title: "Update calendar",
96
- }, (args) => {
97
- const parsed = updateCalendarInput.parse(args);
98
- return updateCalendar(deps, { args: parsed, token: getToken() });
99
- });
100
- };
@@ -1,382 +0,0 @@
1
- // update_contact tool — edits a stored contact in place.
2
- //
3
- // The edit is a *delta*, never a full replacement, for the same reason
4
- // update_calendar_event takes `removedAttendees` rather than a rebuilt
5
- // attendee list: a replacement object forces a caller to read the whole
6
- // record first and silently drops everything it did not know to re-send.
7
- // Here that would mean an agent correcting a postal code could wipe a phone
8
- // number a CardDAV client added an hour ago.
9
- //
10
- // So: scalars (`name`, `organization`, `note`) are set by naming them and
11
- // cleared with `""`; the repeated fields take `added…` / `removed…` lists;
12
- // and a stored postal address can be corrected component-by-component
13
- // through `updatedPostalAddresses`, addressed by the handle search_contacts
14
- // prints in square brackets.
15
- import { z } from "zod";
16
- import { COLLECTED_NOTE_KEY, MAX_ROLES, nextKey, parseBirthday, patchCardAddress, readPostalAddresses, readRoles, toCardAddress, toCardPhone, userNoteEntry, userNoteKey, withBirthday, withPreferredEmail, withRoles, } from "../contacts/index.js";
17
- import { ACCOUNT_WRITE } from "./annotations.js";
18
- import { birthdaySchema, collectedBookIdOf, contactCtx, contactIdSchema, emailEntrySchema, ownerOfAddress, phoneSchema, postalAddressSchema, postalLabelSchema, readBack, roleSchema, } from "./contact-common.js";
19
- import { renderContact } from "./contact-format.js";
20
- import { errorResult, textResult } from "./result.js";
21
- // Same components as a new address, all optional: this one merges onto what
22
- // is stored, so a caller fixing a postal code sends the postal code alone.
23
- const postalPatchSchema = z.object({
24
- city: z.string().min(1).max(100).optional(),
25
- country: z
26
- .string()
27
- .regex(/^[A-Za-z]{2}$/u)
28
- .optional(),
29
- key: z
30
- .string()
31
- .min(1)
32
- .describe("The handle printed in square brackets by search_contacts, e.g. `a0`."),
33
- label: postalLabelSchema.optional(),
34
- postalCode: z.string().min(1).max(20).optional(),
35
- region: z.string().min(1).max(100).optional(),
36
- street: z.string().min(1).max(200).optional(),
37
- });
38
- const updateContactShape = {
39
- addedEmails: z
40
- .array(emailEntrySchema)
41
- .max(10)
42
- .optional()
43
- .describe("Email addresses to add to the contact."),
44
- addedPhones: z
45
- .array(phoneSchema)
46
- .max(10)
47
- .optional()
48
- .describe("Phone numbers to add to the contact."),
49
- addedPostalAddresses: z
50
- .array(postalAddressSchema)
51
- .max(5)
52
- .optional()
53
- .describe("Postal addresses to add."),
54
- addedRoles: z
55
- .array(roleSchema)
56
- .max(MAX_ROLES)
57
- .optional()
58
- .describe('Roles to add: what the person is to the user ("lawyer"), as the user said or confirmed it. ' +
59
- "Never inferred from mail."),
60
- birthday: birthdaySchema
61
- .optional()
62
- .describe('New birthday as `YYYY-MM-DD`, or `--MM-DD` when the year is unknown; `""` clears it. Omit to keep it.'),
63
- contactId: contactIdSchema,
64
- name: z
65
- .string()
66
- .min(1)
67
- .max(200)
68
- .optional()
69
- .describe("New display name. Omit to keep the stored one."),
70
- note: z
71
- .string()
72
- .max(2000)
73
- .optional()
74
- .describe('New note, replacing every note stored on the contact; `""` clears them. ' +
75
- "Omit to keep them. (A contact edited elsewhere can carry more than one.)"),
76
- organization: z
77
- .string()
78
- .max(200)
79
- .optional()
80
- .describe('New organization; `""` clears it. Omit to keep the stored one.'),
81
- preferredEmail: z
82
- .email()
83
- .optional()
84
- .describe("The address mail to this contact should go to: one already on the contact or added in this call. " +
85
- "search_contacts then ranks it first. Omit to keep the current one."),
86
- removedEmails: z
87
- .array(z.email())
88
- .max(10)
89
- .optional()
90
- .describe("Email addresses to remove (case-insensitive)."),
91
- removedPhones: z
92
- .array(z.string().min(1))
93
- .max(10)
94
- .optional()
95
- .describe("Phone numbers to remove, each given either as its `[p0]` handle or as the number itself."),
96
- removedRoles: z
97
- .array(roleSchema)
98
- .max(MAX_ROLES)
99
- .optional()
100
- .describe("Roles to remove (case-insensitive)."),
101
- removedPostalAddresses: z
102
- .array(z.string().min(1))
103
- .max(5)
104
- .optional()
105
- .describe("Postal addresses to remove, each given either as its `[a0]` handle or as its label (`home`, `work`)."),
106
- updatedPostalAddresses: z
107
- .array(postalPatchSchema)
108
- .max(5)
109
- .optional()
110
- .describe("Corrections to stored postal addresses: name the handle plus only the components that change."),
111
- };
112
- export const updateContactInput = z
113
- .object(updateContactShape)
114
- .refine((a) => a.birthday !== undefined ||
115
- a.name !== undefined ||
116
- a.note !== undefined ||
117
- a.organization !== undefined ||
118
- a.preferredEmail !== undefined ||
119
- Boolean(a.addedEmails ?? a.removedEmails ?? a.addedPhones ?? a.removedPhones) ||
120
- Boolean(a.addedPostalAddresses ??
121
- a.updatedPostalAddresses ??
122
- a.removedPostalAddresses) ||
123
- Boolean(a.addedRoles ?? a.removedRoles), { message: "update_contact needs at least one field to change." });
124
- // A removal handle matches either the storage key or the value it names, so
125
- // a caller can echo back what it read without knowing which is which.
126
- const matchesHandle = (handles, key, ...values) => handles.has(key) || values.some((v) => handles.has(v.trim().toLowerCase()));
127
- const normalizedHandles = (raw) => new Set((raw ?? []).map((h) => h.trim().toLowerCase()));
128
- const resolveEmails = (card, args) => {
129
- if (!(args.addedEmails ?? args.removedEmails)) {
130
- return;
131
- }
132
- const removed = normalizedHandles(args.removedEmails);
133
- const kept = Object.fromEntries(Object.entries(card.emails ?? {}).filter(([, e]) => !removed.has(e.address.trim().toLowerCase())));
134
- const present = new Set(Object.values(kept).map((e) => e.address.trim().toLowerCase()));
135
- for (const entry of args.addedEmails ?? []) {
136
- if (present.has(entry.address.toLowerCase())) {
137
- continue;
138
- }
139
- present.add(entry.address.toLowerCase());
140
- kept[nextKey(kept, "e")] = {
141
- address: entry.address,
142
- ...(entry.context ? { contexts: { [entry.context]: true } } : {}),
143
- };
144
- }
145
- return kept;
146
- };
147
- const resolvePhones = (card, args) => {
148
- if (!(args.addedPhones ?? args.removedPhones)) {
149
- return;
150
- }
151
- const removed = normalizedHandles(args.removedPhones);
152
- const kept = Object.fromEntries(Object.entries(card.phones ?? {}).filter(([key, p]) => !matchesHandle(removed, key, p.number)));
153
- for (const phone of args.addedPhones ?? []) {
154
- kept[nextKey(kept, "p")] = toCardPhone(phone);
155
- }
156
- return kept;
157
- };
158
- const resolvePostal = (card, args) => {
159
- if (!(args.addedPostalAddresses ??
160
- args.updatedPostalAddresses ??
161
- args.removedPostalAddresses)) {
162
- return;
163
- }
164
- const stored = new Map(readPostalAddresses(card).map((a) => [a.key, a]));
165
- const removed = normalizedHandles(args.removedPostalAddresses);
166
- const kept = Object.fromEntries(Object.entries(card.addresses ?? {}).filter(([key]) => !matchesHandle(removed, key, stored.get(key)?.label ?? "other")));
167
- for (const patch of args.updatedPostalAddresses ?? []) {
168
- const current = kept[patch.key];
169
- if (current) {
170
- // Merged onto the stored card entry, not rebuilt from the flat read:
171
- // an address written by another CardDAV client can carry components
172
- // this model has no field for, and rebuilding would delete them.
173
- kept[patch.key] = patchCardAddress(current, patch);
174
- }
175
- }
176
- for (const address of args.addedPostalAddresses ?? []) {
177
- kept[nextKey(kept, "a")] = toCardAddress(address);
178
- }
179
- return kept;
180
- };
181
- // The note lives in its own entry so the machine-owned collection payload on
182
- // the same card is never touched. Every *other* user note entry is dropped in
183
- // the same patch: `note` is documented as replacing what is stored and `""`
184
- // as clearing it, and search_contacts shows all of them joined — so writing
185
- // beside a note a CardDAV client left behind would report a replacement while
186
- // the old text stayed on screen and on every synced device.
187
- //
188
- // RFC 8620 §5.3 rejects a patch path whose parent is missing, so a card with
189
- // no notes at all takes a full top-level set instead — safe, because there is
190
- // nothing there to clobber.
191
- const notePatch = (card, note) => {
192
- const key = userNoteKey(card);
193
- const hasNotes = typeof card.notes === "object" && card.notes !== null;
194
- if (!hasNotes) {
195
- return note.length === 0 ? {} : { notes: { [key]: userNoteEntry(note) } };
196
- }
197
- const superseded = Object.keys(card.notes ?? {}).filter((k) => k !== COLLECTED_NOTE_KEY && k !== key);
198
- const removals = Object.fromEntries(superseded.map((k) => [`notes/${k}`, null]));
199
- if (note.length === 0) {
200
- return key in (card.notes ?? {})
201
- ? { ...removals, [`notes/${key}`]: null }
202
- : removals;
203
- }
204
- return { ...removals, [`notes/${key}`]: userNoteEntry(note) };
205
- };
206
- // The whole `anniversaries` map is re-sent with only the birth entry
207
- // changed: withBirthday keeps every foreign entry (a wedding date a phone
208
- // wrote) in place, and a whole-property set is the one patch shape that is
209
- // valid whether or not the card carried the property before (RFC 8620 §5.3
210
- // rejects a scoped path whose parent is missing). When nothing remains the
211
- // property is set to null — the unambiguous "absent" — rather than to `{}`.
212
- const birthdayPatch = (card, text) => {
213
- const parsed = text.length === 0 ? undefined : parseBirthday(text);
214
- if (parsed && "error" in parsed) {
215
- return parsed;
216
- }
217
- const anniversaries = withBirthday(card, parsed?.birthday);
218
- return {
219
- patch: {
220
- anniversaries: Object.keys(anniversaries).length > 0 ? anniversaries : null,
221
- },
222
- };
223
- };
224
- // The emails with `preferredEmail` marked, on top of this call's adds and
225
- // removals. Undefined when neither the emails nor the preference change.
226
- const resolvePreferred = (card, args, resolved) => {
227
- const wanted = args.preferredEmail;
228
- if (wanted === undefined) {
229
- return { emails: resolved };
230
- }
231
- if ((args.removedEmails ?? []).some((a) => a.trim().toLowerCase() === wanted.trim().toLowerCase())) {
232
- return {
233
- error: `${wanted} is removed in this same call, so it cannot become the preferred address. ` +
234
- "Nothing was changed. Keep it, or name another address as preferredEmail.",
235
- };
236
- }
237
- const emails = withPreferredEmail(resolved ?? card.emails ?? {}, wanted);
238
- return emails
239
- ? { emails }
240
- : {
241
- error: `${wanted} is not an address of this contact. Nothing was changed. ` +
242
- "Add it with addedEmails in the same call to make it the preferred one.",
243
- };
244
- };
245
- const organizationPatch = (card, organization) => {
246
- if (organization.length === 0) {
247
- return { organizations: {} };
248
- }
249
- const key = Object.keys(card.organizations ?? {})[0] ?? "o0";
250
- return { organizations: { [key]: { name: organization } } };
251
- };
252
- // The whole `titles` map, as with `anniversaries`: a whole-property set is
253
- // valid whether or not the card had titles before, and job titles another
254
- // client wrote ride along untouched. Null when nothing remains; an empty
255
- // patch when the roles do not change.
256
- const rolesPatch = (card, args) => {
257
- if (!(args.addedRoles ?? args.removedRoles)) {
258
- return { patch: {} };
259
- }
260
- const titles = withRoles(card, args.addedRoles ?? [], args.removedRoles ?? []);
261
- const roles = readRoles({ titles });
262
- // Only a call that adds roles is held to the cap: a merge can leave more,
263
- // and removing them one at a time must still work.
264
- if (roles.length > MAX_ROLES && roles.length > readRoles(card).length) {
265
- return {
266
- error: `A contact holds at most ${MAX_ROLES} roles; this one would have ${roles.length}.`,
267
- };
268
- }
269
- if (roles.join("\n") === readRoles(card).join("\n")) {
270
- return { patch: {} };
271
- }
272
- return { patch: { titles: Object.keys(titles).length > 0 ? titles : null } };
273
- };
274
- // The four scalars — set by naming them, cleared with `""` (name excepted).
275
- const scalarPatch = (card, args) => {
276
- const birthday = args.birthday === undefined
277
- ? undefined
278
- : birthdayPatch(card, args.birthday.trim());
279
- if (birthday && "error" in birthday) {
280
- return birthday;
281
- }
282
- return {
283
- patch: {
284
- ...(birthday?.patch ?? {}),
285
- ...(args.name === undefined ? {} : { name: { full: args.name.trim() } }),
286
- ...(args.note === undefined ? {} : notePatch(card, args.note.trim())),
287
- ...(args.organization === undefined
288
- ? {}
289
- : organizationPatch(card, args.organization.trim())),
290
- },
291
- };
292
- };
293
- export const updateContact = async (deps, cx) => {
294
- const { args } = cx;
295
- const ctx = await contactCtx(deps, cx.token);
296
- const [card] = await deps.contactCardGet({ ...ctx, ids: [args.contactId] });
297
- if (!card) {
298
- return errorResult(`No contact with id ${args.contactId}. Use search_contacts to find the person and read their contact_id.`);
299
- }
300
- // A correction addressed to a handle that isn't on the card is a caller
301
- // mistake worth failing on: silently doing nothing would read as success.
302
- const knownKeys = new Set(Object.keys(card.addresses ?? {}));
303
- const unknown = (args.updatedPostalAddresses ?? [])
304
- .map((p) => p.key)
305
- .filter((key) => !knownKeys.has(key));
306
- if (unknown.length > 0) {
307
- const available = [...knownKeys].join(", ") || "none";
308
- return errorResult(`This contact has no postal address ${unknown.join(", ")}. Stored handles: ${available}. ` +
309
- 'Read them back with search_contacts (response_format: "detailed").');
310
- }
311
- // Same guard create_contact applies, for the same reason: an address that
312
- // already belongs to another card would split that person's history, and
313
- // collection would keep feeding observations to whichever card it matched
314
- // first while searches returned both.
315
- for (const { address } of args.addedEmails ?? []) {
316
- const owner = await ownerOfAddress(deps, ctx, address);
317
- if (owner && owner !== args.contactId) {
318
- return errorResult(`${address} already belongs to a different contact (contact_id: ${owner}). ` +
319
- "Remove it there first, add what is missing to that record instead, or, if both are the same " +
320
- "person or organization, fold them into one with merge_contacts.");
321
- }
322
- }
323
- const scalars = scalarPatch(card, args);
324
- if ("error" in scalars) {
325
- return errorResult(`${scalars.error} Nothing was changed.`);
326
- }
327
- const roles = rolesPatch(card, args);
328
- if ("error" in roles) {
329
- return errorResult(`${roles.error} Nothing was changed.`);
330
- }
331
- const addresses = resolvePostal(card, args);
332
- const preferred = resolvePreferred(card, args, resolveEmails(card, args));
333
- if ("error" in preferred) {
334
- return errorResult(preferred.error);
335
- }
336
- const { emails } = preferred;
337
- const phones = resolvePhones(card, args);
338
- const changed = {
339
- ...(addresses === undefined ? {} : { addresses }),
340
- ...(emails === undefined ? {} : { emails }),
341
- ...(phones === undefined ? {} : { phones }),
342
- };
343
- const patch = {
344
- ...changed,
345
- ...scalars.patch,
346
- ...roles.patch,
347
- };
348
- if (Object.keys(patch).length === 0) {
349
- return errorResult("Nothing to change: the requested edit is already the stored state.");
350
- }
351
- // Read before the write, so a failed lookup can never fail an edit that
352
- // already landed.
353
- const collectedBookId = await collectedBookIdOf(deps, ctx);
354
- await deps.contactCardUpdate({ ...ctx, cardId: args.contactId, patch });
355
- const stored = await readBack(deps, ctx, args.contactId);
356
- return textResult(`Updated contact:\n\n${stored ? renderContact(stored, collectedBookId) : args.contactId}\n\n` +
357
- "Fields you did not name are unchanged. The edit syncs to every device connected over CardDAV.");
358
- };
359
- // --- MCP registration ----------------------------------------------------
360
- export const registerUpdateContact = (server, deps, getToken) => {
361
- server.registerTool("update_contact", {
362
- annotations: ACCOUNT_WRITE,
363
- description: "Edit a stored contact by id, changing only the fields you name — everything else " +
364
- "is kept, so you never have to read the record and re-send it. Set `name`, " +
365
- '`organization`, `birthday` or `note` directly (`""` clears all but the name); add or remove email ' +
366
- "addresses, phone numbers, postal addresses and roles with the `added…`/`removed…` lists; " +
367
- 'a role is what the person is to the user ("lawyer"), recorded only when the user said or ' +
368
- "confirmed it, and search_contacts then finds them by it; " +
369
- "correct one component of a stored postal address with `updatedPostalAddresses`; " +
370
- "mark the address mail should go to with `preferredEmail`. " +
371
- "Find the contact_id and the `[a0]`-style handles with search_contacts. " +
372
- "To fold two contacts that are the same person into one, use merge_contacts instead.",
373
- inputSchema: z.object(updateContactShape),
374
- title: "Update contact",
375
- }, (args) => {
376
- const parsed = updateContactInput.safeParse(args);
377
- if (!parsed.success) {
378
- return Promise.resolve(errorResult(parsed.error.issues.map((i) => i.message).join("; ")));
379
- }
380
- return updateContact(deps, { args: parsed.data, token: getToken() });
381
- });
382
- };