langmail-mcp 0.1.0 → 0.2.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.
Files changed (137) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +89 -169
  3. package/dist/chunk-0fxfqny0.js +12642 -0
  4. package/dist/langmail-mcp.js +7 -0
  5. package/package.json +93 -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,40 +0,0 @@
1
- // archive_emails tool — take messages out of the Inbox and into the Archive
2
- // mailbox. Add-Archive + drop-Inbox rather than a wholesale replacement so a
3
- // message that also lives in Sent (your own reply in a thread) stays there;
4
- // this is the same patch the rules engine's `archive` action builds.
5
- import { z } from "zod";
6
- import { ACCOUNT_WRITE } from "./annotations.js";
7
- import { formatBatchResult, idsInput, idsShape, } from "./file-emails-common.js";
8
- import { errorResult } from "./result.js";
9
- export const archiveEmails = async (deps, ctx) => {
10
- const places = await deps.resolvePlaces(ctx.token);
11
- if (!places.archive) {
12
- // Deliberately not created here: a model-driven call must not invent
13
- // folders. The rules engine creates one on first use of an archive rule.
14
- return errorResult("This account has no Archive mailbox. Nothing was archived. Create one in the mail client, " +
15
- "or use move_emails with an existing folder.");
16
- }
17
- const mailboxIds = { [places.archive]: true };
18
- if (places.inbox && places.inbox !== places.archive) {
19
- mailboxIds[places.inbox] = false;
20
- }
21
- const result = await deps.updateEmails(ctx.token, ctx.args.ids, {
22
- mailboxIds,
23
- });
24
- return formatBatchResult("Archived", result);
25
- };
26
- // --- MCP registration ----------------------------------------------------
27
- export const registerArchiveEmails = (server, deps, getToken) => {
28
- server.registerTool("archive_emails", {
29
- annotations: ACCOUNT_WRITE,
30
- description: "Archive one or more messages: remove them from the Inbox and file them in the Archive " +
31
- 'mailbox. Use this when the user says archive, clear, or "get this out of my inbox". ' +
32
- "Read state and flags (to-do, starred) are untouched (use mark_emails for those), and " +
33
- "re-running it on the same ids is harmless. Takes message ids " +
34
- "from search_emails or get_thread; pass all of a thread's ids to archive the conversation. " +
35
- "To file into a specific folder use move_emails; to delete use trash_emails. Reports how " +
36
- "many messages were archived and lists any id the server refused.",
37
- inputSchema: z.object(idsShape),
38
- title: "Archive emails",
39
- }, (args) => archiveEmails(deps, { args: idsInput.parse(args), token: getToken() }));
40
- };
@@ -1,64 +0,0 @@
1
- // Name-or-URL resolution for the tools that take a `calendar` argument
2
- // (update_calendar, move_calendar_events). An agent that skipped
3
- // list_calendars still lands on the right calendar — and when it does not,
4
- // the error lists every calendar with its URL so the next call can succeed
5
- // without a separate lookup.
6
- import { withTrailingSlash } from "../caldav/client.js";
7
- import { errorResult } from "./result.js";
8
- // A URL or a server-absolute path ("/dav/cal/…"), as opposed to a name.
9
- const URL_OR_PATH_RE = /^(?:https?:\/\/|\/)/iu;
10
- export const normalizeCalendarName = (name) => name.trim().toLowerCase();
11
- // Every calendar sits on the one CalDAV server, so the decoded path alone
12
- // identifies it: an agent that decodes %40 to @, swaps the scheme, or
13
- // changes host case still lands on the same calendar.
14
- const urlKey = (url) => {
15
- try {
16
- const { pathname } = new URL(url, "https://calendar.invalid");
17
- return withTrailingSlash(decodeURIComponent(pathname));
18
- }
19
- catch {
20
- // An unparseable URL or a malformed %-escape matches nothing; the miss
21
- // error then lists the calendars.
22
- return null;
23
- }
24
- };
25
- // Whether two calendar URLs name the same collection (see urlKey).
26
- export const sameCalendarUrl = (a, b) => {
27
- const key = urlKey(a);
28
- return key !== null && key === urlKey(b);
29
- };
30
- export const calendarLabel = (cal) => cal.displayName || "(unnamed)";
31
- const calendarLines = (calendars) => calendars
32
- .map((c, i) => `${i + 1}. ${calendarLabel(c)} — ${c.url}`)
33
- .join("\n");
34
- // Strict resolution: an exact URL (modulo trailing slash) or an exact name
35
- // (modulo case and outer spaces). No fuzzy matching — a miss lists every
36
- // calendar instead, which beats a guess when a person has a handful of them.
37
- export const resolveCalendar = (calendars, ref, wording) => {
38
- const { argName, nothingDone } = wording;
39
- const isUrl = URL_OR_PATH_RE.test(ref);
40
- // An unparseable reference has no key, so it matches nothing and the miss below lists the calendars.
41
- const refKey = isUrl ? urlKey(ref) : null;
42
- const matches = isUrl
43
- ? calendars.filter((c) => refKey !== null && urlKey(c.url) === refKey)
44
- : calendars.filter((c) => normalizeCalendarName(c.displayName) === normalizeCalendarName(ref));
45
- const [only] = matches;
46
- if (only && matches.length === 1) {
47
- return { calendar: only, ok: true };
48
- }
49
- if (matches.length > 1) {
50
- return {
51
- error: errorResult(`${matches.length} calendars are named "${ref}". ${nothingDone} ` +
52
- `Pass the URL of the one you mean as ${argName}:\n${calendarLines(matches)}`),
53
- ok: false,
54
- };
55
- }
56
- const miss = isUrl ? `No calendar at ${ref}.` : `No calendar named "${ref}".`;
57
- const available = calendars.length === 0
58
- ? "This account has no calendars; use create_calendar to make one."
59
- : `Your calendars:\n${calendarLines(calendars)}\nPass one of these names or URLs as ${argName}.`;
60
- return {
61
- error: errorResult(`${miss} ${nothingDone} ${available}`),
62
- ok: false,
63
- };
64
- };
@@ -1,146 +0,0 @@
1
- // Shared seam and input shapes for the contact write tools. The read
2
- // side (search_contacts) keeps its own richer deps bundle — it hydrates
3
- // subjects and event titles, which no writer needs. Prose rendering, which
4
- // both sides do share, lives in contact-format.ts.
5
- import { z } from "zod";
6
- import { COLLECTED_BOOK_NAME, normalizeAddress } from "../contacts/index.js";
7
- import { accountIdForContacts, addressBookCreate, addressBookList, authorizationHeader, contactCardCreate, contactCardDestroy, contactCardGet, contactCardMerge, contactCardQuery, contactCardUpdate, } from "../jmap/index.js";
8
- export const contactCtx = async (deps, token) => {
9
- const authorization = authorizationHeader(token);
10
- return {
11
- accountId: await deps.resolveAccountId(authorization),
12
- apiUrl: "",
13
- authorization,
14
- };
15
- };
16
- // Candidate window for the ownership probe. The filter is a whole address, so
17
- // the substring matches are the handful of cards holding an address that
18
- // *contains* it — sized well above that rather than at it, because a window
19
- // that truncated past the real owner would let the guard miss a duplicate
20
- // instead of rejecting it.
21
- const OWNER_WINDOW = 100;
22
- // The card that actually holds `address`, or undefined. The RFC 9610 `email`
23
- // filter is a *substring* match, so `ann@example.com` also hits a card
24
- // holding `joann@example.com` — trusting the query alone would refuse a
25
- // legitimate create. The candidates are fetched and compared exactly, the
26
- // same way search_contacts refines its own server-side hits.
27
- export const ownerOfAddress = async (deps, ctx, address) => {
28
- const wanted = normalizeAddress(address);
29
- const ids = await deps.contactCardQuery({
30
- ...ctx,
31
- filter: { email: wanted },
32
- limit: OWNER_WINDOW,
33
- });
34
- const cards = await deps.contactCardGet({ ...ctx, ids });
35
- return cards.find((c) => Object.values(c.emails ?? {}).some((e) => normalizeAddress(e.address) === wanted))?.id;
36
- };
37
- // The Collected book's id, which `sourceOf` needs to tell an old Collected
38
- // card without a source marker apart from an imported one.
39
- export const collectedBookIdOf = async (deps, ctx) => (await deps.addressBookList(ctx)).find((b) => b.name === COLLECTED_BOOK_NAME)
40
- ?.id;
41
- // --- shared input shapes ---------------------------------------------------
42
- // Bare and defaulted variants, the same split the mail-rule fields use: an
43
- // update needs "not provided" to stay observable, a create wants the default.
44
- export const postalLabelSchema = z
45
- .enum(["home", "work", "other"])
46
- .describe("What the address is for.");
47
- const postalLabelWithDefault = postalLabelSchema
48
- .default("other")
49
- .describe("What the address is for. Defaults to `other`.");
50
- const phoneLabelSchema = z
51
- .enum(["mobile", "home", "work", "fax", "other"])
52
- .default("other")
53
- .describe("What the number is. Defaults to `other`.");
54
- // Structured, not one free-text block: address formats are country-specific,
55
- // and an agent addressing a letter needs the parts separately.
56
- export const postalAddressSchema = z
57
- .object({
58
- city: z
59
- .string()
60
- .min(1)
61
- .max(100)
62
- .optional()
63
- .describe("City or locality, e.g. München."),
64
- country: z
65
- .string()
66
- .regex(/^[A-Za-z]{2}$/u)
67
- .optional()
68
- .describe("ISO 3166-1 alpha-2 country code, e.g. DE. Convert a country name yourself."),
69
- label: postalLabelWithDefault,
70
- postalCode: z
71
- .string()
72
- .min(1)
73
- .max(20)
74
- .optional()
75
- .describe("Postal or ZIP code, e.g. 80331."),
76
- region: z
77
- .string()
78
- .min(1)
79
- .max(100)
80
- .optional()
81
- .describe("State, province, or region — where the country uses one."),
82
- street: z
83
- .string()
84
- .min(1)
85
- .max(200)
86
- .optional()
87
- .describe('Street including the house number, as one line, e.g. "Beispielweg 1".'),
88
- })
89
- .refine((a) => Boolean(a.street ?? a.city ?? a.postalCode ?? a.region), {
90
- message: "a postal address needs at least a street, city, postal code, or region",
91
- });
92
- export const phoneSchema = z.object({
93
- label: phoneLabelSchema,
94
- number: z
95
- .string()
96
- .min(3)
97
- .max(50)
98
- .describe('The number as the user gave it, e.g. "+49 89 1234567".'),
99
- });
100
- export const emailEntrySchema = z.object({
101
- address: z.email().describe("The email address."),
102
- context: z
103
- .enum(["work", "private"])
104
- .optional()
105
- .describe("Whether this is a work or a private address. Inferred from the domain when omitted."),
106
- });
107
- // The two vCard spellings (RFC 6350 §4.3.1), validated as a calendar date by
108
- // parseBirthday in the handler — a zod regex alone would accept Feb 30, and
109
- // its error names both spellings, which a bare schema rejection would not.
110
- export const birthdaySchema = z
111
- .string()
112
- .max(40)
113
- .describe("Birthday as `YYYY-MM-DD`, or `--MM-DD` when the year is unknown.");
114
- // What the person is to the user, in the user's words: "lawyer",
115
- // "landlord". Stored only when the user said or confirmed it.
116
- export const roleSchema = z
117
- .string()
118
- .trim()
119
- .min(1)
120
- .max(50)
121
- .describe('What the person is to the user, e.g. "lawyer" or "landlord" (a leading "my" is dropped).');
122
- export const contactIdSchema = z
123
- .string()
124
- .min(1)
125
- .describe("The contact id, as printed by search_contacts under `contact_id`.");
126
- // Reads the card back after a write. A card that vanished between the write
127
- // and the read is not worth failing the tool over — the write succeeded.
128
- export const readBack = async (deps, ctx, cardId) => {
129
- const [card] = await deps.contactCardGet({ ...ctx, ids: [cardId] });
130
- return card;
131
- };
132
- // --- live wiring -----------------------------------------------------------
133
- export const makeLiveDeps = (live) => {
134
- const url = async (authorization) => (await live.getSession(authorization)).apiUrl;
135
- return {
136
- addressBookCreate: async (p) => addressBookCreate({ ...p, apiUrl: await url(p.authorization) }),
137
- addressBookList: async (p) => addressBookList({ ...p, apiUrl: await url(p.authorization) }),
138
- contactCardCreate: async (p) => contactCardCreate({ ...p, apiUrl: await url(p.authorization) }),
139
- contactCardDestroy: async (p) => contactCardDestroy({ ...p, apiUrl: await url(p.authorization) }),
140
- contactCardGet: async (p) => contactCardGet({ ...p, apiUrl: await url(p.authorization) }),
141
- contactCardMerge: async (p) => contactCardMerge({ ...p, apiUrl: await url(p.authorization) }),
142
- contactCardQuery: async (p) => contactCardQuery({ ...p, apiUrl: await url(p.authorization) }),
143
- contactCardUpdate: async (p) => contactCardUpdate({ ...p, apiUrl: await url(p.authorization) }),
144
- resolveAccountId: async (authorization) => accountIdForContacts(await live.getSession(authorization)),
145
- };
146
- };
@@ -1,72 +0,0 @@
1
- // Prose rendering of a contact card, shared by the read tool and the
2
- // writers: what an agent reads back after a write is spelled exactly like
3
- // what search_contacts showed it, down to the `[a0]`-style handles — which
4
- // is what makes "search, then correct one field" a two-call sequence rather
5
- // than a guessing game.
6
- //
7
- // Separate from contact-common.ts so search_contacts depends on the
8
- // formatting alone, not on the write tools' deps bundle (mirrors
9
- // mail-rule-format.ts next to mail-rule-common.ts).
10
- import { formatBirthday, readBirthday, readNote, readOrganization, readPhones, readPostalAddresses, readRoles, sourceOf, } from "../contacts/index.js";
11
- // Indented so a multi-line note stays visually attached to its contact
12
- // block, which is how the whole search_contacts output is shaped.
13
- const indentNote = (note) => note.split("\n").join("\n ");
14
- // `birthday: 1990-03-03` / `birthday: --03-03` — the spelling the write
15
- // tools accept, so the line can be echoed straight back into update_contact.
16
- export const birthdayLine = (card) => {
17
- const birthday = readBirthday(card);
18
- return birthday ? ` birthday: ${formatBirthday(birthday)}` : undefined;
19
- };
20
- // `roles: lawyer, landlord` — what the person is to the user. On the concise
21
- // search format too: "write to my lawyer" resolves on that line.
22
- export const rolesLine = (card) => {
23
- const roles = readRoles(card);
24
- return roles.length > 0 ? ` roles: ${roles.join(", ")}` : undefined;
25
- };
26
- // The authored half of a card: birthday, phone numbers, postal addresses,
27
- // note. Only the detailed search format and the write confirmations show
28
- // these — the call that resolves a name before drafting mail has no use for
29
- // a street address. The birthday is the one line the concise format shows
30
- // too, so a caller that already printed it passes `{ birthday: false }`.
31
- export const profileLines = (card, shown = { birthday: true }) => {
32
- const lines = [];
33
- const birthday = shown.birthday ? birthdayLine(card) : undefined;
34
- if (birthday) {
35
- lines.push(birthday);
36
- }
37
- const phones = readPhones(card);
38
- if (phones.length > 0) {
39
- lines.push(" phones:", ...phones.map((p) => ` - [${p.key}] ${p.number} (${p.label})`));
40
- }
41
- const postal = readPostalAddresses(card);
42
- if (postal.length > 0) {
43
- lines.push(" postal_addresses:", ...postal.map((a) => ` - [${a.key}] ${a.display} (${a.label})`));
44
- }
45
- const note = readNote(card);
46
- if (note) {
47
- lines.push(` note: ${indentNote(note)}`);
48
- }
49
- return lines;
50
- };
51
- // The whole card as prose — what create_contact and update_contact echo back
52
- // so the caller never has to re-read to see the result of its own write.
53
- export const renderContact = (card, collectedBookId) => {
54
- const organization = readOrganization(card);
55
- const roles = rolesLine(card);
56
- // Only the lowest `pref` is the preferred one (RFC 9553 §1.5.4), as in
57
- // search_contacts: an imported card can rank several addresses.
58
- const prefs = Object.values(card.emails ?? {}).flatMap((e) => typeof e.pref === "number" ? [e.pref] : []);
59
- const top = prefs.length > 0 ? Math.min(...prefs) : undefined;
60
- const emails = Object.values(card.emails ?? {}).map((e) => top !== undefined && e.pref === top ? `${e.address} (preferred)` : e.address);
61
- return [
62
- card.name?.full ?? "(unnamed)",
63
- ` contact_id: ${card.id}`,
64
- ...(organization ? [` organization: ${organization}`] : []),
65
- ...(roles ? [roles] : []),
66
- ...(emails.length > 0
67
- ? [" emails:", ...emails.map((a) => ` - ${a}`)]
68
- : []),
69
- ...profileLines(card),
70
- ` source: ${sourceOf(card, collectedBookId)}`,
71
- ].join("\n");
72
- };
@@ -1,37 +0,0 @@
1
- // Contact write-through for the calendar tools: after a successful
2
- // create/update/RSVP, the attendee list the tool already holds is folded
3
- // into the user's collected address book under the request's own bearer.
4
- // This covers the organizer side that mail headers never see — the
5
- // motivating Robin case enters the address book the moment the lunch is
6
- // scheduled. Failures are logged, never surfaced: a contact upsert must
7
- // not fail a scheduling action.
8
- import { collectContacts, liveCollectionDeps, observationsFromEvent, } from "../contacts/index.js";
9
- import { accountIdForContacts, authorizationHeader, } from "../jmap/index.js";
10
- import { logger } from "../logger.js";
11
- import { describeError } from "../observability/errors.js";
12
- export const makeAttendeeWriteThrough = (live) => async (input) => {
13
- try {
14
- const authorization = authorizationHeader(input.token);
15
- const session = await live.getSession(authorization);
16
- const ctx = {
17
- accountId: accountIdForContacts(session),
18
- apiUrl: session.apiUrl,
19
- authorization,
20
- };
21
- const extracted = observationsFromEvent({
22
- attendees: input.attendees,
23
- start: input.start,
24
- uid: input.uid,
25
- ...(input.organizer ? { organizer: input.organizer } : {}),
26
- }, {
27
- kind: input.kind ?? "action",
28
- selfAddresses: new Set([input.selfAddress.trim().toLowerCase()]),
29
- });
30
- await collectContacts(liveCollectionDeps, ctx, extracted);
31
- }
32
- catch (err) {
33
- // Through describeError like every other error line: an upstream
34
- // message can carry the mailbox address.
35
- logger.warn(describeError(err), "Contact write-through failed after a calendar action");
36
- }
37
- };
@@ -1,231 +0,0 @@
1
- // create_calendar_event tool — builds a VEVENT and PUTs it to a CalDAV
2
- // calendar. With attendees it is a scheduling object (METHOD:REQUEST, the
3
- // authenticated principal as ORGANIZER) and Stalwart fans out DKIM-signed
4
- // iMIP invitations to them. Without, it is a personal event — a block of the
5
- // user's own time — carrying neither METHOD nor ORGANIZER, and triggers no
6
- // scheduling at all.
7
- //
8
- // Logic sits behind a `Deps` interface (discover + putEvent) so it
9
- // unit-tests without live Stalwart; `makeLiveDeps` wires tsdav in.
10
- import { z } from "zod";
11
- import { makeAccountTimeZoneResolver, } from "../caldav/account-settings.js";
12
- import { describeReminder, MAX_REMINDER_MINUTES } from "../caldav/alarm.js";
13
- import { discoverAccount, putEvent, resolveCalendarUrl, } from "../caldav/client.js";
14
- import { buildInvite } from "../caldav/ical.js";
15
- import { alignUntil, recurrenceDescription, recurrenceSchema, toRRule, } from "../caldav/recurrence.js";
16
- import { logSchedulingHandover } from "../caldav/scheduling-handover.js";
17
- import { eventTimeSchema, resolveEventTimes, timeZoneSchema, UTC_TIME_ZONE, } from "../caldav/timezone.js";
18
- import { OUTWARD_WRITE } from "./annotations.js";
19
- import { errorResult, textResult } from "./result.js";
20
- const TOOL_NAME = "create_calendar_event";
21
- // An event's iCalendar UID, as accepted by the update/delete/RSVP tools and
22
- // returned by create_calendar_event. Deliberately permissive: it must keep
23
- // accepting the legacy `<uuid>@<domain>` form, because events created before
24
- // the UID became a bare UUID are still addressed by those UIDs.
25
- //
26
- // Path separators stay rejected. No code path derives a resource URL from a
27
- // UID any more (resources are resolved by parsed VEVENT UID, and created under
28
- // an independently generated name — see newEventResourceName), so this is
29
- // defence in depth rather than the load-bearing guard it once was.
30
- export const eventUidSchema = z
31
- .string()
32
- .min(1)
33
- .max(255)
34
- .regex(/^[^/\\]+$/u, "uid must not contain path separators");
35
- export const createCalendarEventInput = z.object({
36
- attendees: z
37
- .array(z.email())
38
- .max(50)
39
- .optional()
40
- .describe("Email addresses to invite; each receives an iMIP invitation. Omit for a personal event — a block " +
41
- "of the user’s own time — with no invitations sent."),
42
- // Optional CalDAV URL from list_calendars; defaults to the principal's
43
- // discovered default calendar.
44
- calendarUrl: z.url().optional(),
45
- description: z.string().max(5000).optional(),
46
- // The timezone rule is stated once, on `timeZone`, rather than repeated on
47
- // start/end: all three strings are indexed by tool search.
48
- //
49
- // All-day is expressed by the value type (a bare date), not an `allDay`
50
- // flag: a flag would make `allDay: true` + a clock time representable, and
51
- // an update would need a third "keep" state. See resolveEventTimes.
52
- end: eventTimeSchema.describe("Event end as ISO 8601 (see `timeZone`). For an all-day event a date, exclusive: the day after the " +
53
- "last day (a day off on 2026-10-03 ends 2026-10-04)."),
54
- location: z.string().max(500).optional(),
55
- notify: z
56
- .enum(["all", "none"])
57
- .optional()
58
- .describe("Whether to send the iMIP invitations. `all` (default) sends them; `none` invites nobody."),
59
- recurrence: recurrenceSchema
60
- .describe(`Repeat rule; omit for a one-off event. start/end are its first occurrence. ${recurrenceDescription}`)
61
- .optional(),
62
- reminderMinutesBefore: z
63
- .number()
64
- .int()
65
- .min(0)
66
- .max(MAX_REMINDER_MINUTES)
67
- .optional()
68
- .describe("Remind the user this many minutes before the start (e.g. 30); omit for no reminder. An all-day event " +
69
- "starts at 00:00, so 900 = 09:00 the day before."),
70
- showAs: z
71
- .enum(["busy", "free"])
72
- .optional()
73
- .describe("Whether this event counts as busy time. `busy` (default) means it does; `free` means it does not — " +
74
- "for holds, reminders and travel buffers the user does not want counted against their availability. " +
75
- "Inviting people makes an event count as busy time, so `free` is refused when `attendees` are given."),
76
- start: eventTimeSchema.describe("Event start as ISO 8601 (see `timeZone`), or a date (2026-10-03) for an all-day event."),
77
- timeZone: timeZoneSchema
78
- .optional()
79
- .describe("IANA zone for start/end, e.g. Europe/Berlin: their clock digits are read as wall-clock time here, " +
80
- "overriding any offset. Defaults to the account timezone, then UTC."),
81
- title: z.string().min(1).max(200),
82
- });
83
- // One-line human summary of who the PUT invited (create-side counterpart of
84
- // update-calendar-event's deliverySummary).
85
- const deliverySummary = (attendees, notify, allDay, reminder) => {
86
- const invites = inviteSummary(attendees, notify);
87
- return reminder === undefined
88
- ? invites
89
- : `${invites}; reminder ${describeReminder(reminder, allDay)}`;
90
- };
91
- const inviteSummary = (attendees, notify) => {
92
- if (attendees.length === 0) {
93
- return "no attendees, no invitations";
94
- }
95
- // The CalDAV write is all this tool sees; Stalwart sends the iMIP mail
96
- // afterwards and may fail or skip it, so say "requested", never "sent".
97
- const roster = `${attendees.length} attendee(s): ${attendees.join(", ")}`;
98
- return notify === "none"
99
- ? `invitations suppressed for the ${roster}`
100
- : `invitations requested for ${roster}`;
101
- };
102
- // "Event", "Recurring event", "All-day event", "Recurring all-day event".
103
- const eventNoun = (allDay, recurring) => {
104
- const noun = `${recurring ? "recurring " : ""}${allDay ? "all-day " : ""}event`;
105
- return `${noun.charAt(0).toUpperCase()}${noun.slice(1)}`;
106
- };
107
- export const createCalendarEvent = async (deps, ctx) => {
108
- const { args, token } = ctx;
109
- const account = await deps.discover(token);
110
- if (!account.organizer) {
111
- return errorResult("Could not determine an organizer address for this account.");
112
- }
113
- const resolved = resolveCalendarUrl(account, args.calendarUrl);
114
- if (!resolved.ok) {
115
- return errorResult(resolved.reason === "none"
116
- ? "No calendar available to create the event in."
117
- : `Calendar not found: ${args.calendarUrl}`);
118
- }
119
- const calendarUrl = resolved.url;
120
- const timeZone = args.timeZone ?? (await deps.resolveTimeZone(token)) ?? UTC_TIME_ZONE;
121
- const times = resolveEventTimes(args.start, args.end, timeZone, args.timeZone !== undefined);
122
- if (!times.ok) {
123
- return errorResult(`${times.error} Nothing was created.`);
124
- }
125
- const { allDay, end, start } = times.value;
126
- const rrule = args.recurrence
127
- ? alignUntil(toRRule(args.recurrence), allDay, timeZone)
128
- : undefined;
129
- // No attendees → a personal event: a block of the user's own time rather
130
- // than a scheduling object, so the VEVENT gets neither METHOD nor ORGANIZER
131
- // and Stalwart's scheduler has nothing to fan out.
132
- //
133
- // Create is the only caller that may omit the ORGANIZER. An *edit* that
134
- // leaves an event with no attendees must still name one — see the field's
135
- // comment on InviteInput for the two ways that goes silently wrong.
136
- const attendees = args.attendees ?? [];
137
- const isSchedulingObject = attendees.length > 0;
138
- // In a meeting each attendee decides their own free/busy, and the stored
139
- // event is also the invitation they receive, so a meeting cannot be marked
140
- // free. `busy` is the RFC default and changes nothing for them.
141
- if (isSchedulingObject && args.showAs === "free") {
142
- return errorResult('An event with attendees cannot be marked `showAs: "free"`: inviting people makes it count as busy time. ' +
143
- "Nothing was created. Omit `showAs` to create the meeting, or omit `attendees` for a free personal event.");
144
- }
145
- // A bare UUID: RFC 7986 §5.3 (2016) supersedes the RFC 5545 advice to
146
- // qualify a UID with a domain — it MUST NOT carry host or domain data. Side
147
- // benefit: the mail domain no longer leaks into every invitation sent to an
148
- // external attendee.
149
- const uid = crypto.randomUUID();
150
- const ical = buildInvite({
151
- allDay,
152
- attendees,
153
- end,
154
- start,
155
- timeZone,
156
- title: args.title,
157
- uid,
158
- ...(isSchedulingObject ? { organizer: account.organizer } : {}),
159
- ...(args.description ? { description: args.description } : {}),
160
- ...(args.location ? { location: args.location } : {}),
161
- ...(rrule ? { rrule } : {}),
162
- ...(args.showAs ? { showAs: args.showAs } : {}),
163
- ...(args.notify === "none" ? { scheduleAgent: "NONE" } : {}),
164
- ...(args.reminderMinutesBefore === undefined
165
- ? {}
166
- : { alarms: [{ minutesBefore: args.reminderMinutesBefore }] }),
167
- });
168
- await deps.putEvent({ calendarUrl, ical, token });
169
- // A personal event hands Stalwart nothing to schedule, so only a scheduling
170
- // object gets the audit line.
171
- if (isSchedulingObject) {
172
- logSchedulingHandover({
173
- attendees,
174
- ical,
175
- removedAttendees: [],
176
- scheduleAgent: args.notify === "none" ? "NONE" : undefined,
177
- // buildInvite emits no SEQUENCE, so the RFC 5545 default of 0 applies.
178
- sequence: 0,
179
- tool: TOOL_NAME,
180
- uid,
181
- });
182
- }
183
- await deps.collectAttendees?.({
184
- attendees: attendees.map((email) => ({ email })),
185
- organizer: account.organizer,
186
- selfAddress: account.organizer,
187
- start: start.toISOString(),
188
- token,
189
- uid,
190
- });
191
- return textResult(`${eventNoun(allDay, rrule !== undefined)} "${args.title}" created ` +
192
- `(${deliverySummary(attendees, args.notify, allDay, args.reminderMinutesBefore)}).\n` +
193
- // Surface the UID + calendar so a later turn can update_calendar_event /
194
- // delete_calendar_event this event.
195
- `uid: ${uid}\ncalendarUrl: ${calendarUrl}`);
196
- };
197
- // --- live-deps wiring ----------------------------------------------------
198
- export const makeLiveDeps = (cfg,
199
- // Shared across the calendar tools (see mcp/handler.ts) so create→update reuse
200
- // one per-token cache; defaults to a fresh resolver for standalone callers.
201
- resolveTimeZone = makeAccountTimeZoneResolver({
202
- serverUrl: cfg.serverUrl,
203
- }), collectAttendees) => ({
204
- discover: (token) => discoverAccount(cfg, token),
205
- putEvent: (params) => putEvent(cfg, params),
206
- resolveTimeZone,
207
- ...(collectAttendees ? { collectAttendees } : {}),
208
- });
209
- // --- MCP registration ----------------------------------------------------
210
- export const registerCreateCalendarEvent = (server, deps,
211
- // Bearer threaded per request — see mcp/handler.ts.
212
- getToken) => {
213
- server.registerTool(TOOL_NAME, {
214
- annotations: OUTWARD_WRITE,
215
- // Front-loaded with what a user types to want this tool ("schedule a
216
- // meeting", "book", "invite", "put it on my calendar"); the specification
217
- // detail lives on the docs site, because this string is indexed by tool
218
- // search and length costs ranking.
219
- description: "Create, schedule or book a new calendar event or meeting on the user’s calendar, and invite " +
220
- "people to it with the authenticated user as organizer. Attendees receive iMIP invitations " +
221
- '(pass `notify: "none"` to suppress them); omit `attendees` for a personal event — a block of the ' +
222
- "user’s own time. For an all-day event (a day off, a vacation) pass `start`/`end` as " +
223
- "dates. Pass `recurrence` for a repeating series (e.g. a weekly team meeting) in one call, and " +
224
- "`reminderMinutesBefore` to be reminded. Defaults to the user’s default calendar.",
225
- inputSchema: createCalendarEventInput,
226
- title: "Create calendar event",
227
- }, (args) => {
228
- const parsed = createCalendarEventInput.parse(args);
229
- return createCalendarEvent(deps, { args: parsed, token: getToken() });
230
- });
231
- };
@@ -1,54 +0,0 @@
1
- // create_calendar tool — issues a CalDAV MKCALENDAR against the authenticated
2
- // principal's calendar-home-set and returns the new calendar's URL so a later
3
- // turn can target it with create_calendar_event.
4
- //
5
- // Like the other CalDAV tools, the logic sits behind a `Deps` interface so it
6
- // unit-tests without live Stalwart; `makeLiveDeps` wires tsdav in.
7
- import { z } from "zod";
8
- import { createCalendar as createCalendarCollection, } from "../caldav/client.js";
9
- import { ACCOUNT_WRITE } from "./annotations.js";
10
- import { textResult } from "./result.js";
11
- // A hex color for the Apple `calendar-color` extension, e.g. "#FF6600" or
12
- // "#FF6600FF" (with alpha). Kept strict so a malformed value can't ride
13
- // straight into the MKCALENDAR body. Shared with update_calendar.
14
- export const colorSchema = z
15
- .string()
16
- .regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/u, "color must be a hex value like #FF6600");
17
- export const createCalendarInput = z.object({
18
- // Optional, but recommended so a new calendar is visually distinct.
19
- color: colorSchema.optional(),
20
- name: z.string().min(1).max(200),
21
- });
22
- export const createCalendar = async (deps, ctx) => {
23
- const { args, token } = ctx;
24
- const url = await deps.createCalendar({
25
- color: args.color,
26
- name: args.name,
27
- token,
28
- });
29
- return textResult(`Calendar "${args.name}" created.\n` +
30
- // Surface the URL so a later turn can target it with create_calendar_event.
31
- `calendarUrl: ${url}`);
32
- };
33
- // --- live-deps wiring ----------------------------------------------------
34
- export const makeLiveDeps = (cfg) => ({
35
- createCalendar: (params) => createCalendarCollection(cfg, params),
36
- });
37
- // --- MCP registration ----------------------------------------------------
38
- export const registerCreateCalendar = (server, deps,
39
- // Bearer threaded per request — see mcp/handler.ts.
40
- getToken) => {
41
- server.registerTool("create_calendar", {
42
- annotations: ACCOUNT_WRITE,
43
- description: "Creates a new calendar for the authenticated user, with an optional color. Use this when the " +
44
- "user wants to keep a workstream’s events separate from their other calendars. Returns the new " +
45
- "calendar’s CalDAV URL; pass it to create_calendar_event to add events to it. Each call makes " +
46
- "another calendar, so check list_calendars first; to rename or recolor an existing calendar use " +
47
- "update_calendar instead.",
48
- inputSchema: createCalendarInput,
49
- title: "Create calendar",
50
- }, (args) => {
51
- const parsed = createCalendarInput.parse(args);
52
- return createCalendar(deps, { args: parsed, token: getToken() });
53
- });
54
- };