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,22 +0,0 @@
1
- // The label convention of JMAP mail clients. Agent/label keywords
2
- // are namespaced under `$label:` so JMAP clients render them as label chips; a
3
- // bare keyword like `receipt` is invisible there. The prefix is persisted on
4
- // every message, so changing it is a data migration. Defined here exactly once
5
- // so search filters and keyword writes share one prefix. Agent keywords use
6
- // the lowercased label verbatim as the suffix — no slug/sanitize pass.
7
- export const LABEL_KEYWORD_PREFIX = "$label:";
8
- // Build the JMAP keyword string for a label suffix, e.g. `receipt` ->
9
- // `$label:receipt`. The suffix is used verbatim (no lowercasing or slug pass);
10
- // callers are responsible for passing an already-lowercased, slug-stable value.
11
- export const toLabelKeyword = (suffix) => `${LABEL_KEYWORD_PREFIX}${suffix}`;
12
- // The classified email type's own namespace, kept apart from `$label:` because
13
- // the two vocabularies collide: one agent label covers several types
14
- // (`$label:receipt` is written for both `receipt` and `order`), and which
15
- // labels exist at all depends on the user's enabled agent cards. A message
16
- // carries exactly one `$type:` keyword — always the classified type — so a
17
- // search filter on it means precisely what its gloss promises.
18
- export const TYPE_KEYWORD_PREFIX = "$type:";
19
- // Build the JMAP keyword string for an email type, e.g. `ticket` ->
20
- // `$type:ticket`. Like `toLabelKeyword`, the suffix is used verbatim; the
21
- // taxonomy keys are already lowercase slugs.
22
- export const toTypeKeyword = (emailType) => `${TYPE_KEYWORD_PREFIX}${emailType}`;
package/dist/jmap/live.js DELETED
@@ -1,21 +0,0 @@
1
- // Shared JMAP live-deps plumbing: a per-credential session cache plus the
2
- // account-id resolution every JMAP call needs, shared by every tool.
3
- import { accountIdForMail, fetchSession } from "./session.js";
4
- export const makeJmapLive = (stalwartUrl) => {
5
- // Cache by the Authorization header value (single process). The JMAP
6
- // session resource is stable for a mailbox's lifetime.
7
- const sessionByAuthorization = new Map();
8
- const getSession = async (authorization) => {
9
- const hit = sessionByAuthorization.get(authorization);
10
- if (hit) {
11
- return hit;
12
- }
13
- const session = await fetchSession(stalwartUrl, authorization);
14
- sessionByAuthorization.set(authorization, session);
15
- return session;
16
- };
17
- return {
18
- getSession,
19
- resolveAccountId: async (authorization) => accountIdForMail(await getSession(authorization)),
20
- };
21
- };
@@ -1,113 +0,0 @@
1
- // Pins every request that carries the Stalwart credential to one origin: the
2
- // one the user configured as STALWART_URL.
3
- //
4
- // A mail server names further URLs in its answers: the JMAP session lists
5
- // `apiUrl`, `downloadUrl` and `uploadUrl`, CalDAV discovery answers with a
6
- // redirect and with hrefs, and any request can be redirected. Sending the
7
- // `Authorization` header wherever those point would hand the credential to
8
- // whatever host a misconfigured server or proxy names, for example an
9
- // `http://` URL advertised by a Stalwart that sits behind a TLS proxy. So a
10
- // URL on another origin is refused before anything is sent, and the error
11
- // says which two origins disagree.
12
- //
13
- // Origin means scheme, host and port together: `http` against `https` on the
14
- // same host is a mismatch, and the one that matters most.
15
- const fix = (actual) => `The credential is only ever sent to the configured address, so nothing was sent to ${actual}. Set Stalwart's public URL (scheme, hostname and port) to match STALWART_URL, or point STALWART_URL at ${actual}.`;
16
- export class OriginMismatchError extends Error {
17
- // The origin a URL pointed at, and the configured one it had to match.
18
- actual;
19
- expected;
20
- constructor(lead, actual, expected) {
21
- super(`${lead} ${actual}, but this server is configured for ${expected} (STALWART_URL). ${fix(actual)}`);
22
- this.actual = actual;
23
- this.expected = expected;
24
- this.name = "OriginMismatchError";
25
- }
26
- }
27
- // The origin of an absolute http(s) URL. Never the full URL: an origin cannot
28
- // carry a path, a query or credentials, so it is safe to put in an error.
29
- const originOf = (url) => new URL(url).origin;
30
- // Throws unless `url` (absolute, or relative to `base`) is on the origin of
31
- // `base`. Returns the absolute URL.
32
- const assertSameOrigin = (url, base, lead) => {
33
- const resolved = new URL(url, base);
34
- const expected = originOf(base);
35
- if (resolved.origin !== expected) {
36
- throw new OriginMismatchError(lead, resolved.origin, expected);
37
- }
38
- return resolved;
39
- };
40
- const ENCODED_BRACE_RE = /%7B|%7D/giu;
41
- // Checks one URL of the JMAP session resource against the configured base and
42
- // returns it absolute. The URL may be a URI template (`{accountId}`), whose
43
- // braces `URL` percent-encodes, so an absolute one is returned as it came and a
44
- // relative one gets its braces back.
45
- export const pinSessionUrl = (url, base) => {
46
- const resolved = assertSameOrigin(url, base, "Stalwart advertises its JMAP endpoints at");
47
- if (URL.canParse(url)) {
48
- return url;
49
- }
50
- return resolved.href.replace(ENCODED_BRACE_RE, (m) => m.toUpperCase() === "%7B" ? "{" : "}");
51
- };
52
- const MAX_REDIRECTS = 5;
53
- const HTTP_MOVED_PERMANENTLY = 301;
54
- const HTTP_FOUND = 302;
55
- const HTTP_SEE_OTHER = 303;
56
- const HTTP_MULTIPLE_CHOICES = 300;
57
- const HTTP_BAD_REQUEST = 400;
58
- // What the next hop of a redirect sends (the fetch standard's rule): a 303, or
59
- // a 301/302 answering a POST, turns into a GET without a body; everything else
60
- // repeats the request as it was.
61
- const afterRedirect = (status, init) => {
62
- const method = (init?.method ?? "GET").toUpperCase();
63
- const toGet = (status === HTTP_SEE_OTHER && method !== "GET" && method !== "HEAD") ||
64
- ((status === HTTP_MOVED_PERMANENTLY || status === HTTP_FOUND) &&
65
- method === "POST");
66
- if (!toGet) {
67
- return init;
68
- }
69
- const { body: _body, ...rest } = init ?? {};
70
- return { ...rest, method: "GET" };
71
- };
72
- /**
73
- * A `fetch` that only ever talks to the origin of `base`. A request to another
74
- * origin throws `OriginMismatchError` before anything is sent. Redirects are
75
- * followed by hand, so a redirect to another origin is refused the same way
76
- * instead of being followed with the request body. A caller that asks for
77
- * `redirect: "manual"` gets the redirect response back untouched (tsdav's
78
- * discovery does this and then requests the target through this same
79
- * function).
80
- */
81
- export const originPinnedFetch = (base, service) => {
82
- const lead = service === "JMAP"
83
- ? "Stalwart pointed a JMAP request at"
84
- : "Stalwart points its CalDAV endpoints at";
85
- return async (input, init) => {
86
- // The URL goes out as the caller wrote it; only a relative one is
87
- // replaced by what it resolves to.
88
- const first = assertSameOrigin(String(input), base, lead);
89
- let url = URL.canParse(String(input)) ? String(input) : first.href;
90
- if (init?.redirect === "manual") {
91
- return fetch(url, init);
92
- }
93
- let current = init;
94
- for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {
95
- const res = await fetch(url, { ...current, redirect: "manual" });
96
- const location = res.status >= HTTP_MULTIPLE_CHOICES && res.status < HTTP_BAD_REQUEST
97
- ? res.headers.get("location")
98
- : null;
99
- if (!location) {
100
- return res;
101
- }
102
- url = assertSameOrigin(new URL(location, url).href, base, `Stalwart redirected a ${service} request to`).href;
103
- await res.body?.cancel();
104
- current = afterRedirect(res.status, current);
105
- }
106
- throw new Error(`Stalwart redirected a ${service} request more than ${MAX_REDIRECTS} times`);
107
- };
108
- };
109
- /**
110
- * `fetch` for a URL that came out of an already checked JMAP session: it stays
111
- * on that URL's own origin, redirects included.
112
- */
113
- export const jmapFetch = (url, init) => originPinnedFetch(url, "JMAP")(url, init);
@@ -1,29 +0,0 @@
1
- // Shared Email/set PatchObject construction.
2
- //
3
- // Extracted from email.ts once EmailSubmission became the second consumer:
4
- // `onSuccessUpdateEmail` carries the same keyword/mailbox patch shape as a
5
- // plain Email/set update, and the JSON-Pointer escaping has to be identical
6
- // on both paths or a nested-label keyword silently patches the wrong key.
7
- // Escape a keyword or mailbox id for use as an RFC 6901 JSON Pointer token in
8
- // an Email/set PatchObject: `~` and `/` are structural and MUST be escaped
9
- // (`~`→`~0`, `/`→`~1`), order matters (escape `~` first). Agent `$label:`
10
- // keywords contain neither char, but keeping the escape correct means the
11
- // same wrapper is safe for nested-label keywords too.
12
- const jsonPointerEscape = (token) => token.replaceAll("~", "~0").replaceAll("/", "~1");
13
- export const buildEmailSetPatch = (changes) => {
14
- const patch = {};
15
- // Keywords: boolean value, `false` removes. Stalwart applies this form;
16
- // marking mail read or unread and adding or removing labels all go
17
- // through the `false`=remove path.
18
- for (const [keyword, value] of Object.entries(changes.keywords ?? {})) {
19
- patch[`keywords/${jsonPointerEscape(keyword)}`] = value;
20
- }
21
- // MailboxIds: `true` adds, `null` removes. RFC 8621 requires mailboxIds map
22
- // values be `true`, so removal uses the RFC 8620 canonical PatchObject `null`
23
- // rather than `false` — and unlike keywords there's no proven `false`-removal
24
- // precedent for mailboxes (Rust only ever replaces the set wholesale).
25
- for (const [mailboxId, value] of Object.entries(changes.mailboxIds ?? {})) {
26
- patch[`mailboxIds/${jsonPointerEscape(mailboxId)}`] = value ? true : null;
27
- }
28
- return patch;
29
- };
@@ -1,37 +0,0 @@
1
- // Shared JMAP request plumbing: POST a method-call batch and pick a single
2
- // method response out of the batch. Extracted from email.ts when the Sieve
3
- // wrappers became the second consumer.
4
- import { jmapFetch } from "./origin.js";
5
- import { JmapError } from "./session.js";
6
- import { jmapTimeoutSignal } from "./timeout.js";
7
- export const jmapCall = async (ctx, body) => {
8
- const res = await jmapFetch(ctx.apiUrl, {
9
- body: JSON.stringify(body),
10
- headers: {
11
- authorization: ctx.authorization,
12
- "content-type": "application/json",
13
- },
14
- method: "POST",
15
- signal: jmapTimeoutSignal(),
16
- });
17
- if (res.status !== 200) {
18
- throw new JmapError(res.status, `jmap request returned ${res.status}`);
19
- }
20
- return (await res.json());
21
- };
22
- export const methodResponse = (resp, name, callId) => {
23
- const entry = resp.methodResponses.find(([n, , id]) => n === name && id === callId);
24
- if (!entry) {
25
- // RFC 8620 §3.6.2: a failed method call is answered with an `error`
26
- // response under the same call id. Surface its type so callers can
27
- // recover from expected conditions (e.g. cannotCalculateChanges →
28
- // reseed the poll cursor).
29
- const err = resp.methodResponses.find(([n, , id]) => n === "error" && id === callId);
30
- if (err) {
31
- const detail = err[1];
32
- throw new JmapError(200, `jmap method error for ${name}/${callId}: ${detail.type ?? "unknown"}`, detail.type);
33
- }
34
- throw new JmapError(200, `missing method response for ${name}/${callId}`);
35
- }
36
- return entry[1];
37
- };
@@ -1,89 +0,0 @@
1
- // JMAP session discovery.
2
- //
3
- // The session resource changes rarely (accountId is stable for the
4
- // lifetime of a mailbox), so callers cache it (see `live.ts`). Auth is
5
- // caller-provided: every wrapper is handed the complete `Authorization`
6
- // header value — this module never mints or wraps credentials.
7
- import { originPinnedFetch, pinSessionUrl } from "./origin.js";
8
- import { jmapTimeoutSignal } from "./timeout.js";
9
- export class JmapError extends Error {
10
- status;
11
- // RFC 8620 method-level error type (e.g. "cannotCalculateChanges") when the
12
- // server answered the call with an `error` method response; undefined for
13
- // transport-level failures. Lets callers branch on recoverable conditions.
14
- errorType;
15
- constructor(status, message, errorType) {
16
- super(message);
17
- this.status = status;
18
- this.errorType = errorType;
19
- this.name = "JmapError";
20
- }
21
- }
22
- const TRAILING_SLASHES_RE = /\/+$/u;
23
- // The `Authorization` header value for a credential. Every tool is handed the
24
- // user's credential as the complete header value already (`Basic …` for an app
25
- // password, `Bearer …` for a token; see `src/config.ts`), so this returns it
26
- // unchanged. It marks the one place a tool turns "the credential" into "what
27
- // goes on the wire", for JMAP and CalDAV alike.
28
- export const authorizationHeader = (credential) => credential;
29
- export const fetchSession = async (stalwartBase, authorization) => {
30
- const url = `${stalwartBase.replace(TRAILING_SLASHES_RE, "")}/.well-known/jmap`;
31
- // Stalwart answers the well-known path with a redirect to the session
32
- // resource; it is followed only while it stays on the configured origin.
33
- const res = await originPinnedFetch(stalwartBase, "JMAP")(url, {
34
- headers: { authorization },
35
- signal: jmapTimeoutSignal(),
36
- });
37
- if (res.status !== 200) {
38
- throw new JmapError(res.status, `jmap session returned ${res.status}`);
39
- }
40
- const body = (await res.json());
41
- const { apiUrl } = body;
42
- const { downloadUrl } = body;
43
- const { uploadUrl } = body;
44
- const { primaryAccounts } = body;
45
- const { username } = body;
46
- // downloadUrl and uploadUrl are mandatory in the session resource
47
- // (RFC 8620 §2) and Stalwart always sends them — a session without
48
- // either is malformed.
49
- if (typeof apiUrl !== "string" ||
50
- typeof downloadUrl !== "string" ||
51
- typeof uploadUrl !== "string" ||
52
- typeof primaryAccounts !== "object") {
53
- throw new JmapError(200, "malformed jmap session response");
54
- }
55
- // Every later JMAP request sends the credential to one of these three URLs,
56
- // so each must be on the configured origin (`pinSessionUrl` throws
57
- // otherwise, before the credential goes anywhere else). A relative URL
58
- // resolves against the configured base.
59
- return {
60
- apiUrl: pinSessionUrl(apiUrl, stalwartBase),
61
- downloadUrl: pinSessionUrl(downloadUrl, stalwartBase),
62
- primaryAccounts: primaryAccounts,
63
- uploadUrl: pinSessionUrl(uploadUrl, stalwartBase),
64
- // Stalwart answers a request without a credential with an anonymous
65
- // session whose username is empty: that is not an identity.
66
- ...(typeof username === "string" && username !== "" ? { username } : {}),
67
- };
68
- };
69
- export const accountIdForMail = (session) => {
70
- const id = session.primaryAccounts["urn:ietf:params:jmap:mail"];
71
- if (!id) {
72
- throw new JmapError(200, "no primary mail account in session");
73
- }
74
- return id;
75
- };
76
- // Stalwart serves the Sieve capability (RFC 9661) on the same account as
77
- // mail; the fallback covers a session resource that only advertises the
78
- // mail primary.
79
- export const accountIdForSieve = (session) => session.primaryAccounts["urn:ietf:params:jmap:sieve"] ??
80
- accountIdForMail(session);
81
- // Same story for the contacts capability (RFC 9610): Stalwart hosts address
82
- // books on the mail account, so fall back to the mail primary when the
83
- // session omits a contacts primary.
84
- export const accountIdForContacts = (session) => session.primaryAccounts["urn:ietf:params:jmap:contacts"] ??
85
- accountIdForMail(session);
86
- // And for submission (RFC 8621 §7): identities and submissions live on the
87
- // account that owns the mail, so the mail primary is the fallback.
88
- export const accountIdForSubmission = (session) => session.primaryAccounts["urn:ietf:params:jmap:submission"] ??
89
- accountIdForMail(session);
@@ -1,71 +0,0 @@
1
- // Typed JMAP wrappers for the SieveScript capability (RFC 9661) — the
2
- // storage surface behind persistent mail rules. A mailbox holds at most a
3
- // handful of scripts (Stalwart allows one *active* script), so the read
4
- // side is a single SieveScript/get with `ids: null` (fetch all).
5
- //
6
- // Script content itself is a blob: upload via `blobUpload` first, then
7
- // reference the blobId here. Activation rides on SieveScript/set's
8
- // `onSuccessActivateScript` argument (RFC 9661 §2.3) so create/update and
9
- // activation are one atomic call.
10
- import { jmapCall, methodResponse } from "./request.js";
11
- import { JmapError } from "./session.js";
12
- const USING = ["urn:ietf:params:jmap:core", "urn:ietf:params:jmap:sieve"];
13
- // An invalidScript SetError carries the Sieve compiler diagnostic in
14
- // `description` — the one string that explains a rejected script.
15
- const setErrorDetail = (err) => [err?.type ?? "unknown", err?.description].filter(Boolean).join(" — ");
16
- export const sieveScriptList = async (p) => {
17
- const resp = await jmapCall(p, {
18
- methodCalls: [
19
- ["SieveScript/get", { accountId: p.accountId, ids: null }, "0"],
20
- ],
21
- using: USING,
22
- });
23
- const out = methodResponse(resp, "SieveScript/get", "0");
24
- return out.list ?? [];
25
- };
26
- // Create a script from an uploaded blob and activate it. Returns the
27
- // server-assigned script id.
28
- export const sieveScriptCreate = async (p) => {
29
- const resp = await jmapCall(p, {
30
- methodCalls: [
31
- [
32
- "SieveScript/set",
33
- {
34
- accountId: p.accountId,
35
- create: { s0: { blobId: p.blobId, name: p.name } },
36
- onSuccessActivateScript: "#s0",
37
- },
38
- "0",
39
- ],
40
- ],
41
- using: USING,
42
- });
43
- const out = methodResponse(resp, "SieveScript/set", "0");
44
- const id = out.created?.s0?.id;
45
- if (!id) {
46
- throw new JmapError(200, `SieveScript/set did not create ${p.name}: ${setErrorDetail(out.notCreated?.s0)}`);
47
- }
48
- return id;
49
- };
50
- // Point an existing script at a new content blob and (re)activate it —
51
- // activating the already-active script is a no-op per RFC 9661.
52
- export const sieveScriptUpdate = async (p) => {
53
- const resp = await jmapCall(p, {
54
- methodCalls: [
55
- [
56
- "SieveScript/set",
57
- {
58
- accountId: p.accountId,
59
- onSuccessActivateScript: p.scriptId,
60
- update: { [p.scriptId]: { blobId: p.blobId } },
61
- },
62
- "0",
63
- ],
64
- ],
65
- using: USING,
66
- });
67
- const out = methodResponse(resp, "SieveScript/set", "0");
68
- if (!(out.updated && p.scriptId in out.updated)) {
69
- throw new JmapError(200, `SieveScript/set did not update ${p.scriptId}: ${setErrorDetail(out.notUpdated?.[p.scriptId])}`);
70
- }
71
- };
@@ -1,107 +0,0 @@
1
- // Typed JMAP wrappers for the EmailSubmission capability (RFC 8621 §6–7) —
2
- // the account's sending identities and the submission that actually hands a
3
- // staged draft to the SMTP queue.
4
- //
5
- // Sending is two facts on the wire and nothing else: which Email, and which
6
- // Identity it goes out as. The envelope is deliberately not supplied: RFC 8621
7
- // §7.5 has the server derive it from the message's own To/Cc/Bcc headers, which
8
- // is both less to get wrong and how `bcc` recipients reach the queue without the
9
- // client assembling an envelope.
10
- //
11
- // Keeping `Bcc:` out of the *delivered* message is then the server's job, and the
12
- // RFC does not require it — so it is asserted rather than assumed: Stalwart
13
- // strips the header before handing the message to SMTP (`submission/set.rs`), and
14
- // `drafts-stalwart.test.ts` checks the delivered copy has no bcc.
15
- import { sentEmailPatch } from "./drafts.js";
16
- import { jmapCall as call, methodResponse } from "./request.js";
17
- import { JmapError } from "./session.js";
18
- // The mail capability rides along because `onSuccessUpdateEmail` is an implicit
19
- // Email/set — Stalwart rejects the request if `using` omits it.
20
- const USING = [
21
- "urn:ietf:params:jmap:core",
22
- "urn:ietf:params:jmap:mail",
23
- "urn:ietf:params:jmap:submission",
24
- ];
25
- const CREATE_ID = "send";
26
- const IDENTITY_PROPERTIES = ["id", "email", "name", "replyTo"];
27
- // Every address this account may send as. Stalwart returns one identity per
28
- // configured address/alias; the caller picks by email and passes the `id` to
29
- // `emailSubmissionCreate`.
30
- export const identityGet = async (p) => {
31
- const resp = await call(p, {
32
- methodCalls: [
33
- [
34
- "Identity/get",
35
- {
36
- accountId: p.accountId,
37
- ids: null,
38
- properties: [...IDENTITY_PROPERTIES],
39
- },
40
- "0",
41
- ],
42
- ],
43
- using: USING,
44
- });
45
- const out = methodResponse(resp, "Identity/get", "0");
46
- return out.list ?? [];
47
- };
48
- // Submit a staged draft for delivery, and clear `$draft` / move it to Sent in the
49
- // same request via `onSuccessUpdateEmail`.
50
- //
51
- // RFC 8621 §7.5 makes that patch a *separate implicit Email/set*, performed after
52
- // the submissions and answered under the same call id — and, crucially, its
53
- // failure does not fail the submission. So its response has to be read: if it
54
- // were ignored, a rejected patch (a Sent mailbox destroyed by another client
55
- // between the mailbox lookup and this call, say) would leave the message
56
- // delivered but still flagged `$draft`, and a caller retrying on that flag would
57
- // send it a second time. That flag is the whole structural duplicate-send guard,
58
- // so silently trusting it to have changed is not an option.
59
- //
60
- // The Email id is unchanged by the move, so the caller's `emailId` is also the
61
- // id of the resulting sent message.
62
- export const emailSubmissionCreate = async (p) => {
63
- const resp = await call(p, {
64
- methodCalls: [
65
- [
66
- "EmailSubmission/set",
67
- {
68
- accountId: p.accountId,
69
- create: {
70
- [CREATE_ID]: { emailId: p.emailId, identityId: p.identityId },
71
- },
72
- onSuccessUpdateEmail: {
73
- [`#${CREATE_ID}`]: sentEmailPatch(p.draftsMailboxId, p.sentMailboxId),
74
- },
75
- },
76
- "0",
77
- ],
78
- ],
79
- using: USING,
80
- });
81
- const out = methodResponse(resp, "EmailSubmission/set", "0");
82
- const created = out.created?.[CREATE_ID];
83
- if (!created?.id) {
84
- const reason = out.notCreated?.[CREATE_ID];
85
- // `type` is a JMAP error code (`forbiddenFrom`, `tooManyRecipients`, …),
86
- // not free text, so it's safe to surface; the description can quote the
87
- // message and stays out.
88
- // `type` is passed through as the error type, not just interpolated: callers
89
- // branch on it to tell "the server refused, nothing was sent" from "the
90
- // answer never arrived, delivery unknown" — and those two demand opposite
91
- // retry behaviour.
92
- throw new JmapError(200, `EmailSubmission/set did not send ${p.emailId}: ${reason?.type ?? "unknown"}`, reason?.type);
93
- }
94
- return { ...created, filed: emailWasPatched(resp, p.emailId) };
95
- };
96
- // Read the implicit Email/set that `onSuccessUpdateEmail` triggers. A server that
97
- // performed no such call at all counts as not filed — the point of the check is
98
- // to know the flag changed, and "no evidence" is not "yes".
99
- const emailWasPatched = (resp, emailId) => {
100
- const entry = resp.methodResponses.find(([name, , id]) => name === "Email/set" && id === "0");
101
- if (!entry) {
102
- return false;
103
- }
104
- const body = entry[1];
105
- return (Boolean(body.updated && emailId in body.updated) &&
106
- !(emailId in (body.notUpdated ?? {})));
107
- };
@@ -1,30 +0,0 @@
1
- // Deadlines for every JMAP fetch.
2
- //
3
- // Without one, a stalled Stalwart turns into an indefinitely hung request: a
4
- // reverse proxy in front of it may hold the connection open for a long time,
5
- // so the tool call never returns while the server looks healthy. A bounded
6
- // call fails instead, and a failure is something the log can show.
7
- //
8
- // 30 s is generous on purpose: queries over large mailboxes and blob transfers
9
- // are legitimately slow, and this deadline exists to catch a stall, not to
10
- // enforce a latency budget.
11
- import { jmapFetch } from "./origin.js";
12
- const JMAP_TIMEOUT_MS = 30_000;
13
- // Bounds the whole exchange — request, response headers, response body. The
14
- // right shape for the calls that read a bounded JSON body before returning.
15
- export const jmapTimeoutSignal = (ms = JMAP_TIMEOUT_MS) => AbortSignal.timeout(ms);
16
- // Bounds only the wait for response *headers*. Blob downloads hand the upstream
17
- // body onward as a stream (see blob.ts), so a whole-exchange signal would sever
18
- // a large attachment mid-transfer once the clock ran out. `fetch` resolves as
19
- // soon as the headers land, so clearing the timer there bounds the part that
20
- // can stall — connect, TLS, upstream think-time — and leaves the body alone.
21
- export const fetchWithHeadersDeadline = async (input, init = {}, ms = JMAP_TIMEOUT_MS) => {
22
- const controller = new AbortController();
23
- const timer = setTimeout(() => controller.abort(new Error(`upstream did not respond within ${ms}ms`)), ms);
24
- try {
25
- return await jmapFetch(input, { ...init, signal: controller.signal });
26
- }
27
- finally {
28
- clearTimeout(timer);
29
- }
30
- };
@@ -1,6 +0,0 @@
1
- // Minimal subset of JMAP types shared by the tools and helpers in src/.
2
- //
3
- // JMAP is huge; this file declares only the properties we actually read
4
- // or send. Adding fields when a new tool needs them is preferable to
5
- // trying to mirror the whole RFC up front.
6
- export {};
package/dist/logger.js DELETED
@@ -1,48 +0,0 @@
1
- // The server's logger: pino, writing to STDERR only.
2
- //
3
- // stdout belongs to the stdio transport — one stray byte there corrupts the
4
- // JSON-RPC stream — so nothing in this process may log to it. There are no
5
- // other destinations: no log shipping, no error tracking, no files.
6
- import { createHash } from "node:crypto";
7
- import pino from "pino";
8
- const STDERR_FD = 2;
9
- const HASH_LENGTH = 12;
10
- const LEVELS = new Set([
11
- "fatal",
12
- "error",
13
- "warn",
14
- "info",
15
- "debug",
16
- "trace",
17
- "silent",
18
- ]);
19
- // Quiet unless something is wrong: an MCP client shows or stores whatever a
20
- // stdio server writes to stderr. `LOG_LEVEL=info` adds one line per tool call.
21
- export const DEFAULT_LOG_LEVEL = "warn";
22
- /**
23
- * Normalizes a `LOG_LEVEL` value to a pino level. Pino level strings are
24
- * case-sensitive and an unknown one throws at start-up, so the input is
25
- * lowercased and an unknown value falls back to the default with a note on
26
- * stderr.
27
- */
28
- export const resolveLevel = (raw) => {
29
- const level = raw?.trim().toLowerCase();
30
- if (!level) {
31
- return DEFAULT_LOG_LEVEL;
32
- }
33
- if (LEVELS.has(level)) {
34
- return level;
35
- }
36
- process.stderr.write(`langmail-mcp: unknown LOG_LEVEL "${raw}", falling back to "${DEFAULT_LOG_LEVEL}"\n`);
37
- return DEFAULT_LOG_LEVEL;
38
- };
39
- // Synchronous writes: an async destination loses buffered lines when the
40
- // process exits, and a line per tool call costs nothing at this volume.
41
- // `base: undefined` leaves pid and hostname out of every line.
42
- export const logger = pino({ base: undefined, level: resolveLevel(process.env.LOG_LEVEL) }, pino.destination({ dest: STDERR_FD, sync: true }));
43
- // A short, stable stand-in for an address (or any other identifying token) in
44
- // a log line: lines can be correlated without carrying the plaintext.
45
- export const hashEmail = (email) => createHash("sha256")
46
- .update(email.toLowerCase())
47
- .digest("hex")
48
- .slice(0, HASH_LENGTH);