@amenophis1er/mailcore 0.0.0-stage → 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.
- package/LICENSE +21 -0
- package/README.md +296 -2
- package/index.d.ts +981 -0
- package/package.json +69 -4
- package/src/accounts.js +108 -0
- package/src/auth-headers.js +64 -0
- package/src/auto-reply.js +24 -0
- package/src/awaiting.js +406 -0
- package/src/body.js +263 -0
- package/src/cache.js +585 -0
- package/src/cal-caldav.js +411 -0
- package/src/cal-common.js +57 -0
- package/src/cal-google.js +257 -0
- package/src/calendar-watch.js +157 -0
- package/src/calendar.js +304 -0
- package/src/client.js +269 -0
- package/src/core.js +612 -0
- package/src/dav-xml.js +111 -0
- package/src/event-log.js +147 -0
- package/src/ews-calendar.js +484 -0
- package/src/ews-stream.js +305 -0
- package/src/ews-util.js +59 -0
- package/src/ews.js +924 -0
- package/src/google-auth.js +305 -0
- package/src/google-contacts.js +288 -0
- package/src/ical.js +632 -0
- package/src/imap-stream.js +196 -0
- package/src/imap.js +1158 -0
- package/src/index.js +28 -0
- package/src/jmap-stream.js +198 -0
- package/src/jmap.js +725 -0
- package/src/microsoft-auth.js +232 -0
- package/src/ntlm-guard.js +30 -0
- package/src/rules.js +45 -0
- package/src/store.js +23 -0
- package/src/text.js +93 -0
- package/src/tools.js +484 -0
- package/src/watch.js +262 -0
- package/tools.d.ts +50 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 908 Studio
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,297 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @amenophis1er/mailcore
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Mail and calendar accounts for Node: Exchange (EWS over NTLM), IMAP + SMTP, JMAP (any RFC 8621 server, such as
|
|
4
|
+
Fastmail), CalDAV (iCloud, Fastmail, any RFC 4791 server), Google Calendar, and Microsoft 365 / Outlook.com
|
|
5
|
+
mailboxes signed in with OAuth. Push (EWS streaming notifications, IMAP IDLE, JMAP event source), an encrypted
|
|
6
|
+
local cache (SQLCipher), search, plain-text reads, threads, attachments, drafts and send, calendars (list, events,
|
|
7
|
+
free/busy, free slots, create/update/delete/respond), and MCP-ready tools for agents.
|
|
8
|
+
|
|
9
|
+
Plain JS ESM, with types in `index.d.ts`. Node 20 or later.
|
|
10
|
+
|
|
11
|
+
**mailcore never reads a config file, a keychain, a password manager or the environment.** The caller hands in
|
|
12
|
+
the accounts, a credentials provider, the cache key and a data directory.
|
|
13
|
+
|
|
14
|
+
## Install
|
|
15
|
+
|
|
16
|
+
```sh
|
|
17
|
+
npm install @amenophis1er/mailcore
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
`zod` (^4) is a peer dependency, needed only for the tools (`@amenophis1er/mailcore/tools`).
|
|
21
|
+
|
|
22
|
+
## Quick start
|
|
23
|
+
|
|
24
|
+
```js
|
|
25
|
+
import { createMailcore } from '@amenophis1er/mailcore';
|
|
26
|
+
|
|
27
|
+
const mc = createMailcore({
|
|
28
|
+
accounts: {
|
|
29
|
+
work: { provider: 'ews', host: 'https://mail.example.org', username: 'me', domain: 'CORP', email: 'me@example.org' },
|
|
30
|
+
home: { provider: 'imap', email: 'me@home.example', imap: { host: 'imap.home.example' }, smtp: { host: 'smtp.home.example' } }
|
|
31
|
+
},
|
|
32
|
+
defaultAccount: 'work',
|
|
33
|
+
credentials: {
|
|
34
|
+
// refresh: true after the server rejected the last password
|
|
35
|
+
getPassword: async (account, { refresh }) => ({ username: account.username, password: await myStore.get(account.name, { refresh }) })
|
|
36
|
+
},
|
|
37
|
+
dataDir: '/path/to/data', // cache.db, state.json, calendar-<account>.json
|
|
38
|
+
cacheKey: ({ create }) => myStore.cacheKey({ create }), // or a string; none = no cache
|
|
39
|
+
timeZone: 'Europe/Paris',
|
|
40
|
+
log: (line) => console.log(line)
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
const unread = await mc.find(undefined, { unreadOnly: true, limit: 20 }); // all accounts, newest first
|
|
44
|
+
const msg = await mc.read(unread[0].id); // plain text; { bodyType: 'HTML' } for HTML
|
|
45
|
+
const draft = await mc.reply(msg.id, 'Thanks, will do.'); // a draft; { send: true } sends
|
|
46
|
+
const week = await mc.calendar.listEvents({ start: new Date(), end: '+7d' });
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
`accounts`, `defaultAccount`, `timeZone` and `pollSeconds` may also be functions, read on each use, so settings
|
|
50
|
+
can change while the instance lives. `accounts` is a map by name, or an array of definitions with `name`.
|
|
51
|
+
|
|
52
|
+
## Providers
|
|
53
|
+
|
|
54
|
+
`provider` is one of `ews`, `imap`, `jmap` (mail, and calendar on EWS), `caldav`, `google` (calendar only).
|
|
55
|
+
|
|
56
|
+
### Exchange (EWS)
|
|
57
|
+
|
|
58
|
+
```js
|
|
59
|
+
work: { provider: 'ews', host: 'https://mail.example.org', username: 'me', domain: 'CORP', email: 'me@example.org' }
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
NTLM over EWS, with its calendar. `host` is the server root; `streaming: false` turns push off. A sign-in
|
|
63
|
+
redirected to another origin is refused (`EWS_REDIRECT`).
|
|
64
|
+
|
|
65
|
+
### IMAP + SMTP
|
|
66
|
+
|
|
67
|
+
```js
|
|
68
|
+
home: { provider: 'imap', email: 'me@home.example', imap: { host: 'imap.home.example' }, smtp: { host: 'smtp.home.example' } }
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
`imap` and `smtp` take `{ host, port?, secure?, rejectUnauthorized? }`; `smtp.requireTLS` with `secure: false`
|
|
72
|
+
means STARTTLS or nothing is sent. `imap.folders` names a folder (`inbox junk sent drafts trash archive`) the
|
|
73
|
+
server does not mark. An IMAP account may carry a calendar of its own: `calendar: { provider: 'caldav' | 'google', … }`.
|
|
74
|
+
|
|
75
|
+
### JMAP
|
|
76
|
+
|
|
77
|
+
```js
|
|
78
|
+
fm: { provider: 'jmap', email: 'me@example.org', jmap: { session: 'https://api.fastmail.com/jmap/session' } }
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
- The API key is the account's password: `getPassword` returns `{ password: '<api key>' }`, sent as
|
|
82
|
+
`Authorization: Bearer <api key>`. A sign-in token works too (`{ oauth: async () => token }`, asked at each request).
|
|
83
|
+
- `jmap.session` is the session URL. A bare host (`mail.example.org`) means `https://mail.example.org/.well-known/jmap`;
|
|
84
|
+
none at all means the email domain's `/.well-known/jmap`. A redirect is followed with the key only on the same
|
|
85
|
+
origin; one to another host (or to http) is refused (`JMAP_UNSAFE`): set `jmap.session` to the session URL itself.
|
|
86
|
+
`jmap.folders` names a mailbox for a folder the server gives no role (as `imap.folders`).
|
|
87
|
+
- Written to RFC 8620/8621 only: folders by mailbox role, sending by `EmailSubmission/set` (the identity of the From
|
|
88
|
+
address, else the account's), drafts imported as raw messages, so they read and reply exactly as on IMAP.
|
|
89
|
+
- Push holds the session's `eventSourceUrl` (Server-Sent Events); a server without one is polled.
|
|
90
|
+
- Where the key goes: the session's `apiUrl`, `uploadUrl` and `eventSourceUrl` must be https on the session's host;
|
|
91
|
+
`downloadUrl` https, on another host only when that is a public DNS name. Every host is resolved before the first
|
|
92
|
+
request to it and refused when any of its addresses is private, loopback or link-local; IP-literal hosts are
|
|
93
|
+
refused. A refusal is `JMAP_UNSAFE`, nothing sent. `jmap.allowPrivate: true` lifts these for tests against a
|
|
94
|
+
local server only: never set it for a real account.
|
|
95
|
+
- Sending: a submission the server refuses removes the copy made for it; one whose answer never came (the line cut,
|
|
96
|
+
a timeout, a 5xx) is `SEND_UNKNOWN` and the draft is kept. The copy kept in Sent has the Bcc header, as on IMAP.
|
|
97
|
+
|
|
98
|
+
### CalDAV
|
|
99
|
+
|
|
100
|
+
```js
|
|
101
|
+
cal: { provider: 'caldav', service: 'fastmail', username: 'me@fastmail.example' }
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
`service` is `icloud`, `fastmail` or `other` (then `server` is the CalDAV URL). The password comes from
|
|
105
|
+
`getPassword`; for the CalDAV calendar of an IMAP account, `account.name` is `"<account>/calendar"`. Changes are
|
|
106
|
+
made with SCHEDULE-AGENT=CLIENT (nothing is sent by the server), and free/busy for other people goes through the
|
|
107
|
+
server's scheduling outbox when it has one.
|
|
108
|
+
|
|
109
|
+
### Google Calendar (OAuth)
|
|
110
|
+
|
|
111
|
+
```js
|
|
112
|
+
const mc = createMailcore({
|
|
113
|
+
accounts: { g: { provider: 'google', email: 'me@gmail.example' } },
|
|
114
|
+
credentials: {
|
|
115
|
+
getPassword, // as above, for the other accounts
|
|
116
|
+
google: { get: (account) => myStore.getJson(`google:${account}`), set: (account, tokens) => myStore.setJson(`google:${account}`, tokens) }
|
|
117
|
+
},
|
|
118
|
+
google: { clientId, clientSecret } // a Google Cloud Desktop OAuth client
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
await mc.google.login('g', { openUrl: (url) => openInBrowser(url) }); // PKCE, loopback redirect
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
- `credentials.google` stores Google tokens (`{ refresh_token, access_token, expires_at, scope, … }`, or a JSON
|
|
125
|
+
string). `scope` is what Google granted (`grantedScopes(tokens)` lists it); `refused_at` is set when Google
|
|
126
|
+
refused a renewal. A renewal writes only over the sign-in it renewed, never over a newer one.
|
|
127
|
+
- `google.login(account, { openUrl })` blocks until done; `google.beginLogin(account)` returns
|
|
128
|
+
`{ url, done, cancel }` to settle later. Options: `scopes`, `extraScopes` (`GOOGLE_CONTACTS_SCOPES` for contacts),
|
|
129
|
+
`loginHint`, `timeoutMs`, `appName` (named on the page the browser tab shows at the end), and
|
|
130
|
+
`accept(tokens, { signal })`, asked after the code exchange and before anything is stored (true, a reason to
|
|
131
|
+
refuse, or fields to keep beside the tokens; `googleAccountAddress(accessToken)` says which Google account signed
|
|
132
|
+
in). The loopback server answers one request, a GET of `/` with Host `127.0.0.1:<port>` and the state sent.
|
|
133
|
+
`cancel()` returns whether it ended the sign-in.
|
|
134
|
+
- `google` is `{ clientId, clientSecret, signInHint? }` or a function returning it (asked each time).
|
|
135
|
+
`signInHint(account)` is what a Google auth error tells the user to do (default "sign in to Google again").
|
|
136
|
+
- `google.contacts(account, { lists })` (also `googleContacts(account, { accessToken })`) reads the People API:
|
|
137
|
+
`{ saved, other, errors }`, each list `{ name, email, emails, kind, photo?, company?, title? }`, or null when
|
|
138
|
+
Google refused it, its reason in `errors`. Nothing is kept: where contacts go is the caller's choice.
|
|
139
|
+
|
|
140
|
+
### Microsoft 365 and Outlook.com (OAuth)
|
|
141
|
+
|
|
142
|
+
Microsoft mailboxes are IMAP + SMTP accounts signed in with OAuth (Microsoft has turned basic authentication off).
|
|
143
|
+
`microsoftAuth` runs the sign-in (PKCE, loopback redirect, a public client: no secret) and renews tokens; the
|
|
144
|
+
caller keeps them.
|
|
145
|
+
|
|
146
|
+
```js
|
|
147
|
+
import { createMailcore, microsoftAuth, microsoftServers } from '@amenophis1er/mailcore';
|
|
148
|
+
|
|
149
|
+
const ms = microsoftAuth({
|
|
150
|
+
clientId: '<app id registered in Microsoft Entra>', // or client: () => ({ clientId })
|
|
151
|
+
store: { get: (account) => myStore.getJson(`ms:${account}`), set: (account, tokens) => myStore.setJson(`ms:${account}`, tokens) }
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
const flow = await ms.beginLogin('outlook', { appName: 'My app' });
|
|
155
|
+
openInBrowser(flow.url);
|
|
156
|
+
const signedIn = await flow.done; // what was stored, with email, name and personal from the ID token
|
|
157
|
+
|
|
158
|
+
const mc = createMailcore({
|
|
159
|
+
accounts: { outlook: { provider: 'imap', email: signedIn.email, ...microsoftServers(signedIn.personal) } },
|
|
160
|
+
credentials: { getPassword: async (account) => ({ username: account.email, oauth: () => ms.accessToken(account.name) }) }
|
|
161
|
+
});
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
- `microsoftServers(personal)` gives Outlook's IMAP and SMTP settings (personal accounts send through
|
|
165
|
+
`smtp-mail.outlook.com`, work and school ones through `smtp.office365.com`).
|
|
166
|
+
- `beginLogin(account, opts)` options: `loginHint`, `timeoutMs`, `appName`, `accept(tokens, { signal })`, and
|
|
167
|
+
`redirectUri` (an https address of your own instead of the loopback; then `flow.complete({ state, code })`).
|
|
168
|
+
- `accessToken(account, { force? })` renews as needed (Microsoft rotates the refresh token; the new one is kept);
|
|
169
|
+
`signedIn(account)` says whether a refresh token is stored. A refused renewal is `MAIL_AUTH`.
|
|
170
|
+
- Scopes: `MICROSOFT_MAIL_SCOPES` (Outlook IMAP and SMTP, `offline_access`, `openid email profile`).
|
|
171
|
+
|
|
172
|
+
## Credentials
|
|
173
|
+
|
|
174
|
+
- `credentials.getPassword(account, { refresh })` returns `{ username?, domain?, password }`, or
|
|
175
|
+
`{ username?, oauth }` where `oauth()` returns an access token, asked fresh at each connection. On an auth failure
|
|
176
|
+
mailcore retries once with the same credentials (NTLM 401s are sometimes transient), then once with
|
|
177
|
+
`refresh: true`.
|
|
178
|
+
- A client's `close()` starts the sign-out without waiting for it (an IMAP LOGOUT is waited for at most 5 s even
|
|
179
|
+
then); `close({ wait: true })` resolves once it is done.
|
|
180
|
+
|
|
181
|
+
## API
|
|
182
|
+
|
|
183
|
+
Ids are `"<account>:<id>"` everywhere, so any id routes back to its account.
|
|
184
|
+
|
|
185
|
+
| | |
|
|
186
|
+
|---|---|
|
|
187
|
+
| `createMailcore(options)` | the instance (`options` in `index.d.ts`: `MailcoreOptions`) |
|
|
188
|
+
| `accountNames()`, `mailAccountNames()`, `account(name?)`, `listAccounts()`, `selectAccounts(name?)` | accounts |
|
|
189
|
+
| `find(account?, opts?, onError?)` | listing/search across accounts, newest first: `limit offset unreadOnly flaggedOnly senderContains subjectContains toContains text fromMe hasAttachments sinceIso untilIso folder live` |
|
|
190
|
+
| `read(id, { bodyType?, live? })` | one message with body, recipients and attachment list |
|
|
191
|
+
| `getThread({ id?, subject?, days?, account?, limit? })` | a thread across Inbox and Sent, oldest first |
|
|
192
|
+
| `awaitingReply({ account?, days?, limit?, includeCc?, since? })` | threads whose last message is theirs, unanswered |
|
|
193
|
+
| `awaitingThem({ account?, days?, limit?, olderThanHours? })` | threads whose last message is mine, to someone else, unanswered |
|
|
194
|
+
| `getAttachment(id, attachmentId)`, `saveAttachments(id, dir, { only? })` | attachments |
|
|
195
|
+
| `reply(id, body, { all?, send?, bodyType? })`, `forward(id, body, { to?, cc?, bcc? })`, `compose({ account, to, cc, bcc, subject, body, bodyType, send? })` | drafts and send |
|
|
196
|
+
| `updateDraft({ id, …, keepQuoted? })`, `addAttachment(id, ck, att)`, `removeAttachment(id, ck, attId)`, `deleteItem(id)`, `markRead(id, isRead?)`, `setFlag(id, flagged?)`, `send(id)` | draft and message changes |
|
|
197
|
+
| `moveItems(ids, folder, { onError? })` | move across accounts: old id → new id (null: no longer there); ids missing were not moved |
|
|
198
|
+
| `people(q, { accounts?, limit? })` | people of the cached mail (senders and fellow recipients, newsletters and robots out) |
|
|
199
|
+
| `client(name)`, `withClient(account, fn)` | an `AccountClient` for anything else, with the auth-retry policy |
|
|
200
|
+
| `calendar.*` | `calendarAccounts listCalendars listEvents listAllEvents readEvent createEvent updateEvent deleteEvent respondToEvent freeBusy findFreeSlots resolveCalendar` |
|
|
201
|
+
| `watch(opts)` → `MailWatch` | polling + push per account; events `mail baseline poll failure stream calendar reminder` |
|
|
202
|
+
| `watchCalendar(account, opts)` | one calendar's changes and reminders |
|
|
203
|
+
| `stream(name, hooks)` | the raw push stream of one account |
|
|
204
|
+
| `cache.*` | `cachedAccounts cacheUsable findCached getCached cacheStats prune clearCache`, and for a watcher of its own `upsertItems dropUnlisted reconcile noteSent applyChanges getMeta setMeta idsOf threadCounts snippets texts people …` |
|
|
205
|
+
| `google.login`, `google.beginLogin`, `google.signedIn`, `google.tokens`, `google.contacts` | Google sign-in and contacts (above) |
|
|
206
|
+
|
|
207
|
+
Also exported: `EventLog` (a cursor-backed, bounded, optionally persisted event queue with long-poll `wait()` and
|
|
208
|
+
an async iterator `events()`), rule matching (`ruleMatches`, `matchRule`, `accountOk`, `inQuietHours`), date
|
|
209
|
+
helpers (`parseWhen`, `parseDuration`, `dayStart`), body helpers (`prepareBody`, `replaceAboveQuote`,
|
|
210
|
+
`htmlToText`, …), thread helpers, stores (`jsonFileStore`, `memoryStore`), and account normalization
|
|
211
|
+
(`normalizeAccount`, `jmapSessionUrl`, `PROVIDERS`, …).
|
|
212
|
+
|
|
213
|
+
## The encrypted cache
|
|
214
|
+
|
|
215
|
+
With a `cacheKey` and a `dataDir`, mailcore keeps an encrypted copy of the inbox in `<dataDir>/cache.db`
|
|
216
|
+
(SQLCipher): headers always, bodies of new mail, for the last 30 days by default. Per account:
|
|
217
|
+
`cache: { enabled, days, bodies }`.
|
|
218
|
+
|
|
219
|
+
- `cacheKey` is a string, or `({ create }) => key | null`. Readers ask with `create: false` and never make a
|
|
220
|
+
cache; the watcher asks with `create: true` the first time. mailcore never stores the key. A cache the key does
|
|
221
|
+
not open is `CACHE_KEY`.
|
|
222
|
+
- The cache serves inbox listings only while a watcher has polled within 3× `pollSeconds` (the watcher writes
|
|
223
|
+
`lastPollAt` to the `state` store); `cacheFresh(accounts)` replaces that test. `{ live: true }` on `find` or
|
|
224
|
+
`read` goes to the server.
|
|
225
|
+
- `cache.cacheStats()`, `cache.prune()` and `cache.clearCache()` manage it.
|
|
226
|
+
|
|
227
|
+
## Push and watching
|
|
228
|
+
|
|
229
|
+
```js
|
|
230
|
+
const w = await mc.watch({ pollSeconds: 30 });
|
|
231
|
+
w.on('mail', ({ account, items }) => { /* new unread mail of one poll */ });
|
|
232
|
+
w.on('calendar', ({ account, changes }) => { /* created / updated / cancelled / deleted, `loud` for invitations */ });
|
|
233
|
+
w.on('reminder', (event) => { /* remindMinutes before start */ });
|
|
234
|
+
await w.start();
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
Each account is polled and, where the server offers it, pushed: EWS streaming notifications, IMAP IDLE, the JMAP
|
|
238
|
+
event source. The first poll of an account sets a baseline and reports nothing. Seen ids, and seen Message-IDs
|
|
239
|
+
(so a mail moved out of the inbox and back is not new), live in the `state` store (default
|
|
240
|
+
`<dataDir>/state.json`), so a restart does not re-announce mail. The Message-IDs are shared by all accounts on
|
|
241
|
+
purpose: a mail delivered to two of your accounts emits one `mail` event, from whichever account polls first.
|
|
242
|
+
|
|
243
|
+
`authGate: (account) => ({ blocked(), ok(), failed(err) })` lets the caller pause an account whose sign-in is
|
|
244
|
+
rejected: its poll, push stream and calendar refresh all wait while `blocked()`, and each tells the gate how
|
|
245
|
+
sign-in went.
|
|
246
|
+
|
|
247
|
+
## MCP tools (`@amenophis1er/mailcore/tools`)
|
|
248
|
+
|
|
249
|
+
Mail and calendar tools as plain objects any agent host can serve in-process, ready to list as MCP tools. They are
|
|
250
|
+
static, so a manifest can declare them before any instance exists; the instance comes with each call. zod (^4) is
|
|
251
|
+
a peer dependency: the schemas are your zod.
|
|
252
|
+
|
|
253
|
+
```js
|
|
254
|
+
import { mailTools, mailInstructions, MAIL_INSTRUCTIONS } from '@amenophis1er/mailcore/tools';
|
|
255
|
+
|
|
256
|
+
const tools = mailTools({ allowSend: false }); // [{ name, description, input: z.object, effect, effectFor?, run }]
|
|
257
|
+
const out = await tools[0].run(mc, { limit: 5 }, { signal }); // the data an MCP server sends as JSON text
|
|
258
|
+
const instructions = mailInstructions({ allowSend: false, name: 'my-app' }); // server instructions to go with them
|
|
259
|
+
```
|
|
260
|
+
|
|
261
|
+
`mailTools` options: `allowSend`, `attachmentsDir` (default `<dataDir>/attachments`), `attachmentsLabel` (how the
|
|
262
|
+
description names it), `sendDisabledHint` (what the refusal tells the user to do to allow sending).
|
|
263
|
+
|
|
264
|
+
`effect`, strictest first: `others` (sends mail to someone, or changes a meeting that has other attendees:
|
|
265
|
+
send_draft, create/update/delete_event, respond_to_event), `own-calendar` (an appointment with nobody else),
|
|
266
|
+
`draft`, `local` (mark_read, save_attachments), `read`. For create/update/delete_event, `effect` is the worst case
|
|
267
|
+
and `effectFor(core, args)` gives the effect of one call. Without `allowSend`, send_draft is absent and calendar
|
|
268
|
+
calls that would mail someone throw before doing anything.
|
|
269
|
+
|
|
270
|
+
## Errors
|
|
271
|
+
|
|
272
|
+
Errors are plain `Error`s with a `code`:
|
|
273
|
+
|
|
274
|
+
| code | meaning |
|
|
275
|
+
|---|---|
|
|
276
|
+
| `MAIL_AUTH`, `EWS_AUTH` | the sign-in was refused (`isAuthError(e)` tests for both) |
|
|
277
|
+
| `MAIL_NETWORK` | the server could not be reached |
|
|
278
|
+
| `MAIL_BUSY` | an IMAP account stayed busy longer than `turnWaitMs` (default 20000 ms) |
|
|
279
|
+
| `SEND_UNKNOWN` | a send whose answer never came: check Sent before sending again |
|
|
280
|
+
| `JMAP_UNSAFE`, `EWS_REDIRECT` | refused because the key or the sign-in would go somewhere unsafe |
|
|
281
|
+
| `NO_MAIL`, `NO_CALENDAR` | the account holds no mail (calendar only), or has no calendar |
|
|
282
|
+
| `CACHE_KEY` | the cache cannot be decrypted with the key given |
|
|
283
|
+
| `SIGN_IN_TIMEOUT`, `SIGN_IN_CANCELLED`, `SIGN_IN_REFUSED`, `SIGN_IN_REJECTED`, `SIGN_IN_FAILED` | an OAuth sign-in that did not finish (refused by the provider or the person; rejected by `accept`) |
|
|
284
|
+
| `GOOGLE_SCOPE`, `GOOGLE_API_DISABLED`, `GOOGLE_RATE`, `GOOGLE_API` | Google refused a contacts list |
|
|
285
|
+
|
|
286
|
+
On JMAP, any other 403 or a 5xx carries its HTTP `status` and is not an auth error.
|
|
287
|
+
|
|
288
|
+
## Tests
|
|
289
|
+
|
|
290
|
+
`npm test` runs `node --test` over the parts that need no network (the tool table, bodies, iCalendar, DAV XML,
|
|
291
|
+
EWS request building and parsing, JMAP, rules, the event log, thread heuristics, the encrypted cache, the
|
|
292
|
+
auth-retry policy, OAuth sign-ins against fake servers). `npm run typecheck` compiles a strict NodeNext consumer
|
|
293
|
+
against `index.d.ts`.
|
|
294
|
+
|
|
295
|
+
## Licence
|
|
296
|
+
|
|
297
|
+
MIT © 908 Studio. See [LICENSE](LICENSE).
|