emailengine-app 2.79.1 → 2.79.2

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 (81) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +40 -0
  3. package/bin/emailengine.js +8 -1
  4. package/config/default.toml +6 -0
  5. package/data/google-crawlers.json +1 -1
  6. package/lib/account.js +95 -18
  7. package/lib/api-routes/account-routes.js +13 -1
  8. package/lib/api-routes/index.js +12 -0
  9. package/lib/api-routes/mailbox-routes.js +6 -0
  10. package/lib/api-routes/mcp-oauth-routes.js +259 -0
  11. package/lib/api-routes/mcp-routes.js +172 -0
  12. package/lib/api-routes/message-routes.js +125 -4
  13. package/lib/api-routes/outbox-routes.js +7 -0
  14. package/lib/api-routes/permission-map.js +97 -1
  15. package/lib/api-routes/route-helpers.js +16 -4
  16. package/lib/api-routes/route-metadata.js +24 -4
  17. package/lib/api-routes/submit-routes.js +41 -0
  18. package/lib/api-routes/template-routes.js +7 -0
  19. package/lib/api-routes/token-routes.js +4 -2
  20. package/lib/consts.js +30 -1
  21. package/lib/email-client/base-client.js +102 -117
  22. package/lib/email-client/gmail-client.js +87 -22
  23. package/lib/email-client/imap/mailbox.js +140 -66
  24. package/lib/email-client/outlook-client.js +17 -14
  25. package/lib/enum-descriptions.js +2 -1
  26. package/lib/field-usage.js +17 -1
  27. package/lib/lua/s-list-accounts.lua +5 -2
  28. package/lib/mcp/index.js +29 -0
  29. package/lib/mcp/inject.js +70 -0
  30. package/lib/mcp/json-schema.js +120 -0
  31. package/lib/mcp/listen.js +171 -0
  32. package/lib/mcp/oauth.js +324 -0
  33. package/lib/mcp/protocol.js +489 -0
  34. package/lib/mcp/resources.js +139 -0
  35. package/lib/mcp/tools.js +655 -0
  36. package/lib/openapi/index.js +3 -1
  37. package/lib/response-stream.js +52 -21
  38. package/lib/routes-ui.js +4 -0
  39. package/lib/schemas.js +24 -3
  40. package/lib/token-permission-view.js +104 -8
  41. package/lib/tokens.js +34 -5
  42. package/lib/tools.js +96 -0
  43. package/lib/ui-routes/account-routes.js +43 -1
  44. package/lib/ui-routes/admin-config-routes.js +114 -1
  45. package/lib/ui-routes/admin-entities-routes.js +54 -5
  46. package/lib/ui-routes/auth-routes.js +13 -0
  47. package/lib/ui-routes/mcp-consent-routes.js +330 -0
  48. package/lib/ui-routes/route-helpers.js +116 -1
  49. package/lib/utils/network.js +9 -1
  50. package/lib/web-safe-html.js +61 -0
  51. package/lib/webhooks.js +3 -8
  52. package/package.json +9 -8
  53. package/sbom.json +1 -1
  54. package/scripts/README.md +25 -0
  55. package/scripts/build-icon.js +77 -0
  56. package/static/css/flyonui.css +1 -1
  57. package/static/css/src/app.tailwind.css +98 -0
  58. package/static/emailengine.ico +0 -0
  59. package/static/js/ui.js +465 -1
  60. package/static/licenses.html +42 -22
  61. package/translations/messages.pot +57 -57
  62. package/views/config/mcp.hbs +361 -0
  63. package/views/config/oauth/index.hbs +7 -0
  64. package/views/layout/prompt.hbs +62 -0
  65. package/views/mcp/authorize.hbs +136 -0
  66. package/views/partials/head_assets.hbs +3 -3
  67. package/views/partials/mcp_access_levels.hbs +13 -0
  68. package/views/partials/mcp_account_limit.hbs +14 -0
  69. package/views/partials/mcp_tool_count.hbs +19 -0
  70. package/views/partials/side_menu.hbs +1 -0
  71. package/views/partials/ui/account-picker.hbs +59 -0
  72. package/views/partials/ui/code-block.hbs +26 -0
  73. package/views/partials/ui/menu-item.hbs +5 -0
  74. package/views/partials/ui/radio.hbs +41 -0
  75. package/views/partials/ui/tab.hbs +15 -10
  76. package/views/partials/ui/tabs.hbs +8 -5
  77. package/views/templates/template.hbs +4 -3
  78. package/views/tokens/index.hbs +8 -2
  79. package/views/tokens/new.hbs +514 -243
  80. package/winconf.js +148 -48
  81. package/workers/api.js +198 -48
@@ -1,3 +1,3 @@
1
1
  {
2
- ".": "2.79.1"
2
+ ".": "2.79.2"
3
3
  }
package/CHANGELOG.md CHANGED
@@ -1,5 +1,45 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.79.2](https://github.com/postalsys/emailengine/compare/v2.79.1...v2.79.2) (2026-08-22)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * **api:** confine browse-page session tokens and gate the SBOM ([7f3fc6e](https://github.com/postalsys/emailengine/commit/7f3fc6e464a6161286e1fa3ccd3cc933db7cf874))
9
+ * **api:** end browse-page session tokens when every session is logged out ([4040773](https://github.com/postalsys/emailengine/commit/40407733c79c4d65a223cc594b925015e201862a))
10
+ * **attachments:** collect cid references in one pass instead of scanning the HTML per attachment ([9dd6b0c](https://github.com/postalsys/emailengine/commit/9dd6b0c17ab6db174ef6cc6777fdee506e57bc3d))
11
+ * **deps:** refresh dependencies ([6e11a55](https://github.com/postalsys/emailengine/commit/6e11a55cd66e2609efb524e3494ad2ee5bcf0a11))
12
+ * **gmail:** stop a killer history entry from looping forever and apply the text size limit on API accounts ([cb6ca8a](https://github.com/postalsys/emailengine/commit/cb6ca8aab406cefbba3fbb9c973c0de30036fc1f))
13
+ * **imap:** recover addresses when the ENVELOPE reports none ([1e83178](https://github.com/postalsys/emailengine/commit/1e83178de8ba3f00250eb5fc90d0d869d294c3ec))
14
+ * **mcp:** advertise only the tools a credential can actually call ([abeb137](https://github.com/postalsys/emailengine/commit/abeb13749fbd103f4d9ef1cf438c13f789780300))
15
+ * **mcp:** carry the required cache hints on modern-era results ([6dd70b9](https://github.com/postalsys/emailengine/commit/6dd70b99d6158d9e0dabc3c9ea3dc3750c4fbf8a))
16
+ * **mcp:** close the defects a deep review found in the MCP surface ([c3fc7ba](https://github.com/postalsys/emailengine/commit/c3fc7ba2dc8b8f8d4eea379ddbdcc788fbf1a9c6))
17
+ * **mcp:** make connecting an agent a one-step operation ([914dff5](https://github.com/postalsys/emailengine/commit/914dff58d423b8e84a29332e74cf023cfbbabfa8))
18
+ * **mcp:** make token restrictions work over MCP and tighten the OAuth edges ([b1f1dc0](https://github.com/postalsys/emailengine/commit/b1f1dc09902a2a68924fd5cec3dbeed070cd871f))
19
+ * **mcp:** narrow the agent tool schemas, and let webSafeHtml skip inlined images ([e381af0](https://github.com/postalsys/emailengine/commit/e381af01e4494532396879651025193ccd0ab969))
20
+ * **mcp:** offer three access levels when connecting an agent, and make its tokens findable ([15e7bda](https://github.com/postalsys/emailengine/commit/15e7bda7a012096785ca2c87f6b580e2eaab8dac))
21
+ * **mcp:** position MCP support as a labeled beta ([a19a612](https://github.com/postalsys/emailengine/commit/a19a6123c5a4f794325ac96d8bade18d473a68fe))
22
+ * **mcp:** return web-safe bodies and infer the bound account ([923bb25](https://github.com/postalsys/emailengine/commit/923bb25d02471fd9e98a8dc7a2008d794682990f))
23
+ * **mcp:** serve the Model Context Protocol at /mcp as an opt-in beta ([1907015](https://github.com/postalsys/emailengine/commit/190701506978df65d410c3652f09e48bb723dfa0))
24
+ * **mcp:** show the tool count wherever an mcp token is minted ([a85d8f6](https://github.com/postalsys/emailengine/commit/a85d8f67f043a01bebdc969401244d95fbbd116c))
25
+ * **mcp:** tell agents how to reply to and forward a message ([a3f17ad](https://github.com/postalsys/emailengine/commit/a3f17adb0ee5ce276347f5cb883bb984e6eeb0a2))
26
+ * **mcp:** update the consent integration test for the access-level radio ([f4b6b18](https://github.com/postalsys/emailengine/commit/f4b6b1877aa1073c3b3b5cbd9144f7c3fe13d6e1))
27
+ * **submit:** stop a reply borrowing recipients it should not have ([1032605](https://github.com/postalsys/emailengine/commit/10326056db2df7839463789215757c36bf45c34d))
28
+ * **ui:** count the MCP tools a bound token actually receives ([5bbdee3](https://github.com/postalsys/emailengine/commit/5bbdee3beb425887d1cc52846252034bf673da80))
29
+ * **ui:** explain the OAuth connector form on the MCP config page ([b7db99a](https://github.com/postalsys/emailengine/commit/b7db99a03a2b466c7b43b0e324441ad851ece6d1))
30
+ * **ui:** give MCP tokens their own access-level editor on the token form ([308a217](https://github.com/postalsys/emailengine/commit/308a2178e994e656ea88674b1dc0b6372723f51a))
31
+ * **ui:** make the MCP pages vendor-neutral and the consent wording plain ([f0f0e8e](https://github.com/postalsys/emailengine/commit/f0f0e8e5c5a49c2add8688eb746b42e1b51a9e4f))
32
+ * **ui:** nest the MCP OAuth switch under the endpoint switch ([bb619b4](https://github.com/postalsys/emailengine/commit/bb619b4e3329b576a7ccae1787687e3f78922191))
33
+ * **ui:** pick an account in the send-test dialog too ([6dcdbb5](https://github.com/postalsys/emailengine/commit/6dcdbb54918dbfcfc3ff78304d80f45fa64436a4))
34
+ * **ui:** pick an account instead of typing its id ([11be805](https://github.com/postalsys/emailengine/commit/11be8057cd8415ed083349ed40f74c390e1ece3a))
35
+ * **ui:** render the MCP client consent page as an authorization prompt ([4626123](https://github.com/postalsys/emailengine/commit/4626123fc72936ea79d6319010b9f181e6ed06b0))
36
+ * **ui:** separate the collapsible cards on the MCP config page ([691f0d4](https://github.com/postalsys/emailengine/commit/691f0d46eec36927fc128c2f72e785401413b4d7))
37
+ * **ui:** show each app's client id in the OAuth2 apps listing ([0cc36e0](https://github.com/postalsys/emailengine/commit/0cc36e0ee7e067ed54df6c04c3c16e048585d02e))
38
+ * **ui:** split the MCP connect tab into connection-method sub-tabs ([ec632bd](https://github.com/postalsys/emailengine/commit/ec632bd75bc9cbe02403dac98099f47e0b6aa50e))
39
+ * **ui:** split the MCP page into Settings and Connect an agent tabs ([301c7d0](https://github.com/postalsys/emailengine/commit/301c7d0ed5d0108c46732752018860290bc27093))
40
+ * **ui:** stack the agent generator fields in one column ([9a1ab8e](https://github.com/postalsys/emailengine/commit/9a1ab8ec7f890be7707966bc72e1aec4d7dcdf29))
41
+ * **windows:** set CompanyName and ship a multi-size icon in the exe ([33b7842](https://github.com/postalsys/emailengine/commit/33b784211b5d630ae4b716662edc2b5008c75752))
42
+
3
43
  ## [2.79.1](https://github.com/postalsys/emailengine/compare/v2.79.0...v2.79.1) (2026-08-19)
4
44
 
5
45
 
@@ -112,6 +112,13 @@ const GLOBAL_OPTIONS = [
112
112
  type: 'boolean',
113
113
  default: false,
114
114
  group: 'Document Store (deprecated)'
115
+ },
116
+ {
117
+ name: '--mcp.enabled',
118
+ description: 'Register the MCP endpoint at /mcp (the mcpEnabled runtime setting still has to be turned on)',
119
+ type: 'boolean',
120
+ default: true,
121
+ group: 'MCP'
115
122
  }
116
123
  ];
117
124
 
@@ -497,7 +504,7 @@ function run() {
497
504
  switch (tokensCmd) {
498
505
  case 'issue':
499
506
  {
500
- let allowedScopes = ['*', 'api', 'metrics', 'smtp', 'imap-proxy'];
507
+ let allowedScopes = ['*', 'api', 'metrics', 'smtp', 'imap-proxy', 'mcp'];
501
508
  let scopes = []
502
509
  .concat(argv.scope || [])
503
510
  .concat(argv.s || [])
@@ -36,6 +36,12 @@ proxy = false # Set to true if using HAProxy with send-proxy option
36
36
  # all document-store API/UI endpoints are only available when this is enabled.
37
37
  enabled = false
38
38
 
39
+ [mcp]
40
+ # MCP (Model Context Protocol) endpoint at /mcp. This deployment-level gate controls whether
41
+ # the endpoint exists in the route table at all; the runtime on/off switch is the mcpEnabled
42
+ # setting (Configuration > MCP in the admin UI), which starts out disabled.
43
+ enabled = true
44
+
39
45
  [dbs]
40
46
  # redis connection
41
47
  redis = "redis://127.0.0.1:6379/8"
@@ -1,5 +1,5 @@
1
1
  {
2
- "creationTime": "2026-08-14T14:46:51.000000",
2
+ "creationTime": "2026-08-21T14:46:19.000000",
3
3
  "prefixes": [
4
4
  {
5
5
  "ipv6Prefix": "2001:4860:4801:2008::/64"
package/lib/account.js CHANGED
@@ -14,7 +14,8 @@ const {
14
14
  isEmail,
15
15
  resolveDelegatedAccount,
16
16
  escapeRedisGlob,
17
- getMailboxStatusKey
17
+ getMailboxStatusKey,
18
+ cidReferenceRegex
18
19
  } = require('./tools');
19
20
  const { MessageChannel } = require('worker_threads');
20
21
  const { MessagePortReadable } = require('./message-port-stream');
@@ -33,7 +34,7 @@ const Lock = require('ioredfour');
33
34
  const { redis } = require('./db');
34
35
  const nanoid = customAlphabet('0123456789abcdefghijklmnopqrstuvwxyz', 16);
35
36
  const { REDIS_PREFIX, ACCOUNT_DELETED_NOTIFY } = require('./consts');
36
- const { messageWebSafeHtml } = require('./web-safe-html');
37
+ const { messageWebSafeHtml, webSafeTextResponse, applyWebSafeHtmlOptions } = require('./web-safe-html');
37
38
  const { checkAccountScopes: checkScopes } = require('./oauth/scope-checker');
38
39
  const { ACCOUNT_STATES, ERROR_STATES, calculateEffectiveState, validateAccountState, getDisplayState, formatLastError } = require('./account/account-state');
39
40
  const { decodeStoredMailboxEntry } = require('./email-client/imap/listing-diff');
@@ -163,6 +164,22 @@ class Account {
163
164
  return !!accountData.smtp;
164
165
  }
165
166
 
167
+ /**
168
+ * Lists accounts, filtered by state and by a substring search.
169
+ *
170
+ * The provider enrichment below is not optional, however little of it a caller reads: it
171
+ * resolves each account's OAuth2 app, and `isApi` falls out of that. getDisplayState() reads
172
+ * `isApi` to decide whether a stored state can be trusted when the run index is behind, so an
173
+ * API account listed without it reports `init` rather than what it is actually doing. A "lean"
174
+ * listing that skipped the loop was tried and reverted for exactly that: it made the cheap
175
+ * fields cheaper and the one field every caller renders wrong.
176
+ *
177
+ * @param {String|Array} state - state filter, 'errors' for every attention state, falsy for all
178
+ * @param {String} query - substring matched against account id, name and address
179
+ * @param {Number} page - zero-based page
180
+ * @param {Number} limit - page size
181
+ * @returns {Promise<Object>} `{ total, pages, page, query, state, accounts }`
182
+ */
166
183
  async listAccounts(state, query, page, limit) {
167
184
  limit = Number(limit) || 20;
168
185
  page = Math.max(Number(page) || 0, 0);
@@ -179,7 +196,19 @@ class Account {
179
196
  }
180
197
  let filterState = Array.isArray(state) ? state.join(',') : state || '*';
181
198
 
182
- let result = await this.redis.sListAccounts(`${REDIS_PREFIX}ia:accounts`, filterState, skip, limit, `${REDIS_PREFIX}`, query);
199
+ // The search is a plain substring match against the lowercased fields, and two things about
200
+ // that were left to the caller to get right:
201
+ //
202
+ // - the needle was passed through as typed, so anything with a capital in it matched
203
+ // nothing at all - on a search box, the account you can see is the one you cannot find.
204
+ // The script folds the needle too, so any caller gets a case-insensitive search; this
205
+ // fold is the one that also covers non-ASCII, which string.lower() leaves alone.
206
+ // - "no search" was spelled `false` by some callers, and ioredis sends that as the string
207
+ // "false", which the script then dutifully searched for. Anything that is not a string
208
+ // is one of those, and means no search.
209
+ let search = typeof query === 'string' ? query.toLowerCase() : '';
210
+
211
+ let result = await this.redis.sListAccounts(`${REDIS_PREFIX}ia:accounts`, filterState, skip, limit, `${REDIS_PREFIX}`, search);
183
212
 
184
213
  let accounts = result[2].map(formatAccountListingResponse).map(this.unserializeAccountData.bind(this));
185
214
  let oauthApps = new Map();
@@ -1730,6 +1759,13 @@ class Account {
1730
1759
  }
1731
1760
 
1732
1761
  async getText(text, options) {
1762
+ if (options.webSafeHtml) {
1763
+ // Both bodies are needed to build the web-safe rendering: the generator falls back to
1764
+ // the plaintext part when the message carries no HTML one, and the thread-collapse
1765
+ // analysis reads whichever of the two the extractor picks.
1766
+ options = Object.assign({}, options, { textType: '*' });
1767
+ }
1768
+
1733
1769
  if (options.documentStore && (await isDocumentStoreEnabled())) {
1734
1770
  await this.loadAccountData(this.account, false);
1735
1771
 
@@ -1764,7 +1800,7 @@ class Account {
1764
1800
  }
1765
1801
  }
1766
1802
 
1767
- return response;
1803
+ return this.textResponse(response, options);
1768
1804
  }
1769
1805
 
1770
1806
  await this.loadAccountData(this.account, true);
@@ -1778,15 +1814,17 @@ class Account {
1778
1814
  });
1779
1815
 
1780
1816
  // IMAP backend returns false for unknown messages and folders
1781
- return this.assertMessageFound(textData);
1817
+ return this.textResponse(this.assertMessageFound(textData), options);
1818
+ }
1819
+
1820
+ // The one exit of getText(), so the document-store branch and the live one cannot answer a
1821
+ // webSafeHtml request differently
1822
+ async textResponse(textData, options) {
1823
+ return options.webSafeHtml ? webSafeTextResponse(textData) : textData;
1782
1824
  }
1783
1825
 
1784
1826
  async getMessage(message, options) {
1785
- if (options.webSafeHtml) {
1786
- options.textType = '*';
1787
- options.embedAttachedImages = true;
1788
- options.preProcessHtml = true;
1789
- }
1827
+ applyWebSafeHtmlOptions(options);
1790
1828
 
1791
1829
  if (options.documentStore && (await isDocumentStoreEnabled())) {
1792
1830
  await this.loadAccountData(this.account, false);
@@ -1854,15 +1892,28 @@ class Account {
1854
1892
  }
1855
1893
 
1856
1894
  if (options.embedAttachedImages && messageData.text && messageData.text.html && messageData.attachments && messageData.attachments.length) {
1857
- let attachmentsToDownload = [];
1895
+ // map both content id forms (bare and <bracketed>) to the first attachment carrying them,
1896
+ // so the passes below cost one lookup per reference instead of a scan of all attachments
1897
+ let attachmentsByContentId = new Map();
1898
+ for (let attachment of messageData.attachments) {
1899
+ if (!attachment.contentId) {
1900
+ continue;
1901
+ }
1902
+ for (let key of [attachment.contentId, attachment.contentId.replace(/^<(.*)>$/, '$1')]) {
1903
+ if (!attachmentsByContentId.has(key)) {
1904
+ attachmentsByContentId.set(key, attachment);
1905
+ }
1906
+ }
1907
+ }
1858
1908
 
1859
1909
  // first pass, find attachments to inline
1860
- messageData.text.html.replace(/\bcid:([^"'\s>]+)/g, (fullMatch, cidMatch) => {
1861
- let attachment = messageData.attachments.find(attachment => [`<${cidMatch}>`, cidMatch].includes(attachment.contentId));
1910
+ let attachmentsToDownload = new Set();
1911
+ for (let match of messageData.text.html.matchAll(cidReferenceRegex())) {
1912
+ let attachment = attachmentsByContentId.get(match[1]);
1862
1913
  if (attachment && !attachment.content) {
1863
- attachmentsToDownload.push(attachment);
1914
+ attachmentsToDownload.add(attachment);
1864
1915
  }
1865
- });
1916
+ }
1866
1917
 
1867
1918
  // download large inline attachments not stored in ES
1868
1919
  for (let attachment of attachmentsToDownload) {
@@ -1885,8 +1936,8 @@ class Account {
1885
1936
  }
1886
1937
 
1887
1938
  // second pass, replace placeholders with inline attachments
1888
- messageData.text.html = messageData.text.html.replace(/\bcid:([^"'\s>]+)/g, (fullMatch, cidMatch) => {
1889
- let attachment = messageData.attachments.find(attachment => [`<${cidMatch}>`, cidMatch].includes(attachment.contentId));
1939
+ messageData.text.html = messageData.text.html.replace(cidReferenceRegex(), (fullMatch, cidMatch) => {
1940
+ let attachment = attachmentsByContentId.get(cidMatch);
1890
1941
  if (attachment && attachment.content) {
1891
1942
  return `data:${attachment.contentType || 'application/octet-stream'};base64,${attachment.content}`;
1892
1943
  }
@@ -3042,4 +3093,30 @@ async function accountsExist(redis, accounts) {
3042
3093
  return new Map(accounts.map((account, i) => [account, values[i] === 1]));
3043
3094
  }
3044
3095
 
3045
- module.exports = { Account, accountExists, accountsExist };
3096
+ /**
3097
+ * The display fields of one account, without loading or decrypting anything.
3098
+ *
3099
+ * What a form that already holds an account id needs in order to show it back as something a
3100
+ * person recognises: a name, an address and a connection state. loadAccountData() answers the same
3101
+ * question by reading and decrypting the whole record, which is a lot of work for three strings on
3102
+ * a page that is not about that account.
3103
+ *
3104
+ * @param {Object} redis - Redis client
3105
+ * @param {String} account - Account ID
3106
+ * @returns {Promise<Object|null>} `{ account, name, email, state }`, or null when no such account exists
3107
+ */
3108
+ async function accountSummary(redis, account) {
3109
+ if (!account) {
3110
+ return null;
3111
+ }
3112
+
3113
+ // `account` is the existence marker (see accountExists); the rest are optional on a record
3114
+ let [exists, name, email, state] = await redis.hmget(`${REDIS_PREFIX}iad:${account}`, 'account', 'name', 'email', 'state');
3115
+ if (!exists) {
3116
+ return null;
3117
+ }
3118
+
3119
+ return { account, name: name || '', email: email || '', state: state || 'init' };
3120
+ }
3121
+
3122
+ module.exports = { Account, accountExists, accountsExist, accountSummary };
@@ -32,7 +32,7 @@ const {
32
32
  ENUM_DESCRIPTIONS
33
33
  } = require('../schemas');
34
34
 
35
- const { REDIS_PREFIX, MAX_FORM_TTL, NONCE_BYTES } = require('../consts');
35
+ const { REDIS_PREFIX, MAX_FORM_TTL, NONCE_BYTES, MCP_MAX_PAGE_SIZE } = require('../consts');
36
36
  const BEHAVIOR = require('./behavior-notes');
37
37
  const { IMPACT } = require('./operation-impact');
38
38
  const { FIELD_USAGE } = require('../field-usage');
@@ -798,6 +798,13 @@ async function init(args) {
798
798
  tags: ['api', 'Account'],
799
799
 
800
800
  plugins: {
801
+ mcp: {
802
+ name: 'list_accounts',
803
+ title: 'List accounts',
804
+ description:
805
+ 'List the email accounts on this instance, paged. Use the returned account id as the account argument of the other tools. Check the state field: only connected accounts can be read.',
806
+ bounds: { pageSize: MCP_MAX_PAGE_SIZE }
807
+ },
801
808
  openapi: {
802
809
  responses: apiResponses('Returns a page of accounts with their connection states.', 400, 401, 403, 429, 500)
803
810
  }
@@ -1045,6 +1052,11 @@ async function init(args) {
1045
1052
  tags: ['api', 'Account'],
1046
1053
 
1047
1054
  plugins: {
1055
+ mcp: {
1056
+ name: 'get_account',
1057
+ title: 'Get account',
1058
+ description: 'Get one account: its display name, email address, connection state and sync status. Credentials are masked.'
1059
+ },
1048
1060
  openapi: {
1049
1061
  'x-ee-behavior': [BEHAVIOR.NO_QUOTA_ON_API_ACCOUNTS],
1050
1062
  responses: apiResponses('Returns the account configuration, connection state and sync status.', 400, 401, 403, 404, 429, 500)
@@ -31,6 +31,8 @@ const deliveryTestRoutes = require('./delivery-test-routes');
31
31
  const blocklistRoutes = require('./blocklist-routes');
32
32
  const submitRoutes = require('./submit-routes');
33
33
  const changesRoutes = require('./changes-routes');
34
+ const mcpRoutes = require('./mcp-routes');
35
+ const mcpOauthRoutes = require('./mcp-oauth-routes');
34
36
 
35
37
  /**
36
38
  * Registers every /v1 route module on the supplied Hapi server.
@@ -48,6 +50,7 @@ const changesRoutes = require('./changes-routes');
48
50
  * @param {Number} args.MAX_BODY_SIZE
49
51
  * @param {Number} args.MAX_PAYLOAD_TIMEOUT
50
52
  * @param {Boolean} args.documentStoreFeatureEnabled - gate for the deprecated Document Store
53
+ * @param {Boolean} args.mcpFeatureEnabled - gate for the MCP endpoint
51
54
  * @param {Object} args.oauth2Schema
52
55
  * @param {Object} args.imapSchema
53
56
  * @param {Object} args.smtpSchema
@@ -68,6 +71,7 @@ async function registerApiRoutes(args) {
68
71
  MAX_BODY_SIZE,
69
72
  MAX_PAYLOAD_TIMEOUT,
70
73
  documentStoreFeatureEnabled,
74
+ mcpFeatureEnabled,
71
75
  oauth2Schema,
72
76
  imapSchema,
73
77
  smtpSchema,
@@ -155,6 +159,14 @@ async function registerApiRoutes(args) {
155
159
 
156
160
  // setup the account state change stream (SSE)
157
161
  await changesRoutes({ server, CORS_CONFIG });
162
+
163
+ // setup the MCP endpoint and its OAuth discovery/registration/token routes (only when the
164
+ // deployment gate is on; the OAuth routes additionally answer 404 until the mcpOAuthEnabled
165
+ // setting is turned on)
166
+ if (mcpFeatureEnabled) {
167
+ await mcpRoutes({ server, CORS_CONFIG, MAX_BODY_SIZE, MAX_PAYLOAD_TIMEOUT });
168
+ await mcpOauthRoutes({ server });
169
+ }
158
170
  }
159
171
 
160
172
  module.exports = registerApiRoutes;
@@ -79,6 +79,12 @@ async function init(args) {
79
79
  tags: ['api', 'Mailbox'],
80
80
 
81
81
  plugins: {
82
+ mcp: {
83
+ name: 'list_mailboxes',
84
+ title: 'List mailboxes',
85
+ description:
86
+ 'List the folders of an account with message counts and special-use roles (Inbox, Sent, Trash and so on). Folder paths from here are what list_messages, search_messages and move_message take.'
87
+ },
82
88
  openapi: {
83
89
  responses: apiResponses(
84
90
  'Returns the account folder tree, including special-use designations and message counts.',
@@ -0,0 +1,259 @@
1
+ 'use strict';
2
+
3
+ // The public half of the MCP OAuth flow: discovery metadata (RFC 9728 protected resource
4
+ // metadata and RFC 8414 authorization server metadata), open dynamic client registration
5
+ // (RFC 7591), and the token endpoint. The consent page - the only part with a human in it -
6
+ // lives on the admin surface (lib/ui-routes/mcp-consent-routes.js).
7
+ //
8
+ // Everything here is unauthenticated by design and rate limited per IP: registration mints
9
+ // nothing but a client id that only an admin's consent can turn into a credential, and the
10
+ // token endpoint redeems single-use PKCE-bound codes. Every route answers 404 while the flow
11
+ // is unavailable (MCP disabled, the mcpOAuthEnabled setting off, or no serviceUrl to anchor
12
+ // the canonical origin on).
13
+ //
14
+ // CORS is wide open on these routes on purpose, independent of the instance's CORS setting:
15
+ // browser-based MCP clients fetch the metadata and call the token endpoint cross-origin, and
16
+ // none of these endpoints reads a cookie or serves per-user state.
17
+
18
+ const Boom = require('@hapi/boom');
19
+ const Joi = require('joi');
20
+
21
+ const { checkRateLimit } = require('../rate-limit');
22
+ const { oauthOrigin, mcpResource, registerClient, redeemAuthorizationCode, MAX_REDIRECT_URIS } = require('../mcp/oauth');
23
+
24
+ const OPEN_CORS = { origin: ['*'] };
25
+
26
+ // One OAuth-style error shape for every failure on these routes (RFC 6749 5.2)
27
+ function oauthErrorResponse(h, statusCode, error, description) {
28
+ return h.response({ error, error_description: description }).code(statusCode);
29
+ }
30
+
31
+ // Registration and token requests are unauthenticated writes, so both get a per-IP budget that
32
+ // no working client comes near: a real flow registers once and redeems one code. Checked before
33
+ // any other Redis work in the handlers, so an abusive caller costs one Redis op per request.
34
+ // lib/rate-limit directly rather than the h.checkRateLimit toolkit decoration on purpose: the
35
+ // decoration routes through a main-thread RPC, the library call is one Redis round trip, and
36
+ // both count in the same Redis buckets.
37
+ async function assertRateLimit(request, bucket, allowed) {
38
+ const limit = await checkRateLimit(`mcp:oauth:${bucket}:${request.app.ip}`, 1, allowed, 3600);
39
+ if (!limit.success) {
40
+ const ttl = Math.ceil(limit.ttl);
41
+ const err = Boom.tooManyRequests('Rate limit exceeded');
42
+ err.output.payload.ttl = ttl;
43
+ // The conventional header for a 429, so a generic HTTP client backs off without
44
+ // knowing about the ttl field in the body
45
+ err.output.headers['Retry-After'] = ttl;
46
+ throw err;
47
+ }
48
+ }
49
+
50
+ async function init(args) {
51
+ const { server } = args;
52
+
53
+ // Sends OAuth discovery at MCP clients that authenticate with nothing or with an unusable
54
+ // token: the WWW-Authenticate pointer at the protected resource metadata is how a client
55
+ // finds the authorization server (RFC 9728). Header-only, so token-authenticated clients
56
+ // never notice it.
57
+ server.ext('onPreResponse', async (request, h) => {
58
+ const response = request.response;
59
+
60
+ if (request.path !== '/mcp' || !response.isBoom || response.output.statusCode !== 401) {
61
+ return h.continue;
62
+ }
63
+
64
+ const origin = await oauthOrigin();
65
+ if (origin) {
66
+ // The exact capitalized key Boom used for the strategy's own challenge: the worker's
67
+ // preResponse extension rebuilds bearer 401s from output.headers['WWW-Authenticate'],
68
+ // so writing any other key would be dropped in the rebuild. The strategy's challenge
69
+ // params (error="...") are kept - a client debugging a bad token needs both.
70
+ const pointer = `resource_metadata="${origin}/.well-known/oauth-protected-resource/mcp"`;
71
+ const existing = response.output.headers['WWW-Authenticate'];
72
+ response.output.headers['WWW-Authenticate'] =
73
+ typeof existing === 'string' && /^Bearer\s+\S/.test(existing) ? `${existing}, ${pointer}` : `Bearer ${pointer}`;
74
+ }
75
+
76
+ return h.continue;
77
+ });
78
+
79
+ // RFC 9728: served both at the path-suffixed location clients derive from the resource URI
80
+ // (/mcp) and at the root for clients that use the bare origin as the resource identifier
81
+ server.route({
82
+ method: 'GET',
83
+ path: '/.well-known/oauth-protected-resource/{suffix?}',
84
+
85
+ async handler(request) {
86
+ if (request.params.suffix && request.params.suffix !== 'mcp') {
87
+ throw Boom.notFound();
88
+ }
89
+
90
+ const origin = await oauthOrigin();
91
+ if (!origin) {
92
+ throw Boom.notFound();
93
+ }
94
+
95
+ return {
96
+ resource: mcpResource(origin),
97
+ authorization_servers: [origin],
98
+ scopes_supported: ['mcp'],
99
+ bearer_methods_supported: ['header'],
100
+ resource_name: 'EmailEngine MCP'
101
+ };
102
+ },
103
+
104
+ options: {
105
+ description: 'MCP OAuth protected resource metadata',
106
+ tags: ['external'],
107
+ auth: false,
108
+ cors: OPEN_CORS
109
+ }
110
+ });
111
+
112
+ server.route({
113
+ method: 'GET',
114
+ path: '/.well-known/oauth-authorization-server',
115
+
116
+ async handler() {
117
+ const origin = await oauthOrigin();
118
+ if (!origin) {
119
+ throw Boom.notFound();
120
+ }
121
+
122
+ return {
123
+ issuer: origin,
124
+ authorization_endpoint: `${origin}/admin/mcp/authorize`,
125
+ token_endpoint: `${origin}/mcp/oauth/token`,
126
+ registration_endpoint: `${origin}/mcp/oauth/register`,
127
+ response_types_supported: ['code'],
128
+ grant_types_supported: ['authorization_code'],
129
+ code_challenge_methods_supported: ['S256'],
130
+ token_endpoint_auth_methods_supported: ['none'],
131
+ scopes_supported: ['mcp'],
132
+ authorization_response_iss_parameter_supported: true
133
+ };
134
+ },
135
+
136
+ options: {
137
+ description: 'MCP OAuth authorization server metadata',
138
+ tags: ['external'],
139
+ auth: false,
140
+ cors: OPEN_CORS
141
+ }
142
+ });
143
+
144
+ server.route({
145
+ method: 'POST',
146
+ path: '/mcp/oauth/register',
147
+
148
+ async handler(request, h) {
149
+ await assertRateLimit(request, 'register', 20);
150
+
151
+ if (!(await oauthOrigin())) {
152
+ throw Boom.notFound();
153
+ }
154
+
155
+ try {
156
+ const client = await registerClient({
157
+ redirectUris: request.payload.redirect_uris,
158
+ clientName: request.payload.client_name
159
+ });
160
+ return h.response(client).code(201);
161
+ } catch (err) {
162
+ if (err.oauthError) {
163
+ return oauthErrorResponse(h, 400, err.oauthError, err.message);
164
+ }
165
+ throw err;
166
+ }
167
+ },
168
+
169
+ options: {
170
+ description: 'MCP OAuth dynamic client registration',
171
+ tags: ['external'],
172
+ auth: false,
173
+ cors: OPEN_CORS,
174
+
175
+ payload: {
176
+ maxBytes: 64 * 1024,
177
+ allow: ['application/json']
178
+ },
179
+
180
+ validate: {
181
+ payload: Joi.object({
182
+ redirect_uris: Joi.array().items(Joi.string().max(2048)).min(1).max(MAX_REDIRECT_URIS).required(),
183
+ client_name: Joi.string().max(1024),
184
+ token_endpoint_auth_method: Joi.string().valid('none'),
185
+ grant_types: Joi.array().items(Joi.string().max(64)).max(10),
186
+ response_types: Joi.array().items(Joi.string().max(64)).max(10),
187
+ scope: Joi.string().max(1024)
188
+ }).unknown(true),
189
+
190
+ failAction: (request, h, err) =>
191
+ oauthErrorResponse(h, 400, 'invalid_client_metadata', (err && err.message) || 'Invalid client metadata').takeover()
192
+ }
193
+ }
194
+ });
195
+
196
+ server.route({
197
+ method: 'POST',
198
+ path: '/mcp/oauth/token',
199
+
200
+ async handler(request, h) {
201
+ await assertRateLimit(request, 'token', 60);
202
+
203
+ const origin = await oauthOrigin();
204
+ if (!origin) {
205
+ throw Boom.notFound();
206
+ }
207
+
208
+ if (request.payload.grant_type !== 'authorization_code') {
209
+ return oauthErrorResponse(h, 400, 'unsupported_grant_type', 'Only authorization_code is supported');
210
+ }
211
+
212
+ try {
213
+ const tokenResponse = await redeemAuthorizationCode({
214
+ code: request.payload.code,
215
+ clientId: request.payload.client_id,
216
+ redirectUri: request.payload.redirect_uri,
217
+ codeVerifier: request.payload.code_verifier,
218
+ resource: request.payload.resource,
219
+ origin,
220
+ ip: request.app.ip
221
+ });
222
+
223
+ return h.response(tokenResponse).header('Cache-Control', 'no-store').header('Pragma', 'no-cache');
224
+ } catch (err) {
225
+ if (err.oauthError) {
226
+ return oauthErrorResponse(h, 400, err.oauthError, err.message);
227
+ }
228
+ throw err;
229
+ }
230
+ },
231
+
232
+ options: {
233
+ description: 'MCP OAuth token endpoint',
234
+ tags: ['external'],
235
+ auth: false,
236
+ cors: OPEN_CORS,
237
+
238
+ payload: {
239
+ maxBytes: 64 * 1024,
240
+ allow: ['application/x-www-form-urlencoded', 'application/json']
241
+ },
242
+
243
+ validate: {
244
+ payload: Joi.object({
245
+ grant_type: Joi.string().max(64).required(),
246
+ code: Joi.string().max(256),
247
+ client_id: Joi.string().max(256),
248
+ redirect_uri: Joi.string().max(2048),
249
+ code_verifier: Joi.string().max(256),
250
+ resource: Joi.string().max(2048)
251
+ }).unknown(true),
252
+
253
+ failAction: (request, h, err) => oauthErrorResponse(h, 400, 'invalid_request', (err && err.message) || 'Invalid request').takeover()
254
+ }
255
+ }
256
+ });
257
+ }
258
+
259
+ module.exports = init;