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
@@ -0,0 +1,172 @@
1
+ 'use strict';
2
+
3
+ // The MCP (Model Context Protocol) endpoint: a single stateless JSON-RPC-over-POST route, per
4
+ // the Streamable HTTP transport of protocol revision 2026-07-28, plus the sessionless subset of
5
+ // the 2025-06-18/2025-11-25 revisions for clients that still open with `initialize`.
6
+ //
7
+ // Registered from lib/api-routes/index.js like every other API route so the route-table
8
+ // guardrail sees it. Tagged `external` (skips the CSRF crumb, stays out of /swagger.json - the
9
+ // endpoint speaks JSON-RPC, not REST, so it has no OpenAPI operation) plus the two scopes it
10
+ // admits (see the tags below).
11
+ //
12
+ // The api-token strategy treats this route specially in three documented ways (see the
13
+ // mcpOptions() handling in workers/api.js): the token-permission check and the audit row are
14
+ // deferred to the injected inner request, whose routeGrant() names the real operation, and an
15
+ // account-bound token is admitted at the door with its binding parked on
16
+ // request.app.mcpBoundAccount - binding enforcement too happens on the inner request, which
17
+ // actually names an account.
18
+
19
+ const Boom = require('@hapi/boom');
20
+
21
+ const settings = require('../settings');
22
+ const { isMcpEnabled, MCP_DISABLED_MESSAGE } = require('../mcp');
23
+ const { processMcpRequest, isAllowedOrigin, acceptsEventStream, rpcError, ERROR_CODES, serverInstructions } = require('../mcp/protocol');
24
+ const { getToolRegistry, callTool, listToolsFor } = require('../mcp/tools');
25
+ const { listResources, readResource } = require('../mcp/resources');
26
+ const { acceptFilter, openListenStream, canOpenListenStream, MAX_STREAMS_PER_CREDENTIAL } = require('../mcp/listen');
27
+
28
+ async function init(args) {
29
+ const { server, CORS_CONFIG, MAX_BODY_SIZE, MAX_PAYLOAD_TIMEOUT } = args;
30
+
31
+ // Build the registry once the route table is complete, rather than on the first request.
32
+ // buildToolRegistry() throws on a duplicate tool name or a colliding argument source, and
33
+ // those are wiring bugs that should stop the worker starting - lazily, the same throw became
34
+ // a 500 on every tools/list and an empty catalog on the admin page instead. onPreStart runs
35
+ // after every module has registered, which is why this cannot happen inline here.
36
+ server.ext('onPreStart', () => {
37
+ getToolRegistry(server);
38
+ });
39
+
40
+ server.route({
41
+ method: 'POST',
42
+ path: '/mcp',
43
+
44
+ async handler(request, h) {
45
+ // One read for both settings the handler needs; the deployment gate already decided
46
+ // route registration, so only the runtime switch is checked here
47
+ const stored = await settings.getMulti('mcpEnabled', 'serviceUrl');
48
+ if (!stored.mcpEnabled) {
49
+ throw Boom.notFound(MCP_DISABLED_MESSAGE);
50
+ }
51
+
52
+ const origin = request.headers.origin;
53
+ if (origin && !isAllowedOrigin(origin, { serviceUrl: stored.serviceUrl, corsOrigins: (CORS_CONFIG && CORS_CONFIG.origin) || [] })) {
54
+ return h.response(rpcError(null, ERROR_CODES.INVALID_REQUEST, 'Origin not allowed')).code(403);
55
+ }
56
+
57
+ const boundAccount = request.app.mcpBoundAccount;
58
+
59
+ const ctx = {
60
+ // A credential sees the surface it can actually use, so the agent does not plan
61
+ // around tools that would only ever answer it with a 403: a bound credential
62
+ // loses the instance-wide listings (list_accounts, get_outbox) and the `account`
63
+ // argument of everything else, and a permission-narrowed token loses the tools
64
+ // whose grant its record refuses - the same check the injected inner request
65
+ // would enforce, asked ahead of time. Advertisement only: tools/call still
66
+ // dispatches whatever is asked, and the inner request stays the enforcement.
67
+ //
68
+ // Auth mode is required and every strategy success path sets artifacts (the token
69
+ // record, or {} for the preauth caller).
70
+ listTools: () => listToolsFor(server, { tokenData: request.auth.artifacts, boundAccount }),
71
+
72
+ callTool: async (name, toolArgs) => {
73
+ const tool = getToolRegistry(server).byName.get(name);
74
+ if (!tool) {
75
+ const err = new Error(`Unknown tool: ${name}. Call tools/list for the available tools`);
76
+ err.rpcCode = ERROR_CODES.INVALID_PARAMS;
77
+ throw err;
78
+ }
79
+ return callTool({ server, tool, args: toolArgs, request });
80
+ },
81
+
82
+ listResources: () => listResources({ server, request }),
83
+ readResource: uri => readResource({ server, request, uri }),
84
+
85
+ // An account-bound credential cannot list accounts and its tools carry no
86
+ // account argument, so the opening line of the generic instructions - call
87
+ // list_accounts, then pass the id - describes a workflow it cannot perform
88
+ instructions: boundAccount ? serverInstructions(boundAccount) : undefined,
89
+
90
+ acceptsEventStream: acceptsEventStream(request.headers.accept)
91
+ };
92
+
93
+ const outcome = await processMcpRequest({ body: request.payload, headers: request.headers, ctx });
94
+
95
+ if (outcome.listen) {
96
+ // Checked before the authorization fan-out below, so a client that is already at
97
+ // its stream budget cannot spend the instance's Redis round trips discovering it
98
+ if (!canOpenListenStream(request)) {
99
+ return h.response(
100
+ rpcError(
101
+ outcome.listen.id,
102
+ ERROR_CODES.INVALID_REQUEST,
103
+ `Too many open subscription streams for this credential (limit ${MAX_STREAMS_PER_CREDENTIAL}). Close one before opening another`
104
+ )
105
+ );
106
+ }
107
+
108
+ const accepted = await acceptFilter({ server, request, filter: outcome.listen.filter });
109
+ return openListenStream({ h, request, subscriptionId: outcome.listen.id, accepted });
110
+ }
111
+
112
+ if (!outcome.body) {
113
+ return h.response().code(outcome.httpStatus);
114
+ }
115
+
116
+ return h.response(outcome.body).code(outcome.httpStatus);
117
+ },
118
+
119
+ options: {
120
+ description: 'MCP endpoint',
121
+ notes: ['JSON-RPC endpoint implementing the Model Context Protocol Streamable HTTP transport'],
122
+
123
+ // `external`: no CSRF crumb and no OpenAPI operation. Two scopes: `api` tokens can
124
+ // do over MCP whatever they can do over REST, and `mcp` tokens are surface-bound
125
+ // credentials this endpoint admits and plain REST refuses (see the scope check in
126
+ // workers/api.js).
127
+ tags: ['external', 'scope:api', 'scope:mcp'],
128
+
129
+ plugins: {
130
+ mcp: { endpoint: true }
131
+ },
132
+
133
+ payload: {
134
+ maxBytes: MAX_BODY_SIZE,
135
+ timeout: MAX_PAYLOAD_TIMEOUT,
136
+ allow: ['application/json'],
137
+ parse: true
138
+ },
139
+
140
+ auth: {
141
+ strategy: 'api-token',
142
+ mode: 'required'
143
+ },
144
+ cors: CORS_CONFIG
145
+ }
146
+ });
147
+
148
+ // The modern revision removed the standalone GET notification stream and protocol sessions;
149
+ // 405 on GET and DELETE is the spec-prescribed answer to older clients probing for them,
150
+ // and it is also what tells a dual-era client this is not a 2024-11-05 HTTP+SSE server.
151
+ server.route({
152
+ method: ['GET', 'DELETE'],
153
+ path: '/mcp',
154
+
155
+ async handler(request, h) {
156
+ if (!(await isMcpEnabled())) {
157
+ throw Boom.notFound(MCP_DISABLED_MESSAGE);
158
+ }
159
+
160
+ return h.response().code(405).header('Allow', 'POST');
161
+ },
162
+
163
+ options: {
164
+ description: 'MCP endpoint method guard',
165
+ tags: ['external'],
166
+ auth: false,
167
+ cors: CORS_CONFIG
168
+ }
169
+ });
170
+ }
171
+
172
+ module.exports = init;
@@ -10,6 +10,32 @@ const { handleError } = require('./route-helpers');
10
10
  const BEHAVIOR = require('./behavior-notes');
11
11
  const { IMPACT } = require('./operation-impact');
12
12
  const { FIELD_USAGE } = require('../field-usage');
13
+ const { COLLAPSE_CLASS, MCP_MAX_PAGE_SIZE } = require('../consts');
14
+
15
+ // What the collapse marker means, said once because both body tools carry it. An agent that knows
16
+ // the class name can read the new part of a thread without the quoted copies of everything before
17
+ // it, which on a long thread is most of the tokens.
18
+ const COLLAPSE_MARKER_NOTE =
19
+ `Quoted reply and forward history is wrapped in a <details class="${COLLAPSE_CLASS}"> element - what an email client hides behind a "show more" ` +
20
+ 'control - so everything outside it is what the sender wrote this time.';
21
+
22
+ // The body budgets of the two MCP tools that return a message body. Both are forced rather than
23
+ // offered: the route's own maxBytes tops out at a gigabyte, which is not a number to put in front
24
+ // of a model, and an unbounded ask is fetched, sanitized and serialized in full before the MCP
25
+ // layer truncates it - all of that work for bytes nobody sees.
26
+ //
27
+ // What `maxBytes` actually bounds is the input: it cuts each text part to this many CHARACTERS
28
+ // before the web-safe rendering runs, and that rendering reads both parts and can come out larger
29
+ // than either (inlined CSS, the collapse markup). So these are work bounds, not a promise about
30
+ // the size of the result - MAX_TOOL_RESULT_BYTES in lib/mcp/tools.js is the promise. They are set
31
+ // at a quarter and a half of it so the two multipliers between the units do not routinely push a
32
+ // normal message into that truncation, which costs the caller a JSON fragment it cannot parse.
33
+ // test/mcp-tools-test.js asserts the margin and the ordering.
34
+ //
35
+ // Read as tokens: get_message inlines about 8k of them so that reading one message is one call
36
+ // rather than two, and get_message_text returns twice that when the body did not fit.
37
+ const MCP_MESSAGE_BODY_MAX_BYTES = 32 * 1024;
38
+ const MCP_MESSAGE_TEXT_MAX_BYTES = 64 * 1024;
13
39
 
14
40
  const {
15
41
  accountIdSchema,
@@ -142,6 +168,23 @@ async function init(args) {
142
168
  tags: ['api', 'Message'],
143
169
 
144
170
  plugins: {
171
+ mcp: {
172
+ name: 'get_message',
173
+ title: 'Get message',
174
+ description:
175
+ 'Get one message: subject, addresses, date, flags, attachment list and the body. The body arrives in text.html as sanitized HTML, generated from the plaintext part when the message carries no HTML one, with no separate plaintext copy. ' +
176
+ `It is capped at ${MCP_MESSAGE_BODY_MAX_BYTES} characters - text.hasMore true means more of it is available from get_message_text. ` +
177
+ COLLAPSE_MARKER_NOTE,
178
+ // The rendering knobs are not the calling model's to choose. One canonical
179
+ // body shape is what an agent can reason about, and web-safe HTML is the one
180
+ // that exists for every message. Attached images stay out of it: an agent
181
+ // reads the body rather than displaying it, so inlining them as data URIs
182
+ // would multiply the size of a tool result that already carries the whole
183
+ // body, and the `cid:` references it keeps instead name the attachments
184
+ // get_attachment can fetch.
185
+ omit: ['textType', 'webSafeHtml', 'preProcessHtml', 'embedAttachedImages', 'maxBytes'],
186
+ force: { webSafeHtml: true, embedAttachedImages: false, maxBytes: MCP_MESSAGE_BODY_MAX_BYTES }
187
+ },
145
188
  openapi: {
146
189
  responses: apiResponses(
147
190
  'Returns the message envelope and structure. Text content is only included when requested.',
@@ -192,11 +235,15 @@ async function init(args) {
192
235
  .meta({ usage: FIELD_USAGE.webSafeHtml })
193
236
  .label('WebSafeHtml'),
194
237
 
238
+ // Deliberately no default: applyWebSafeHtmlOptions() has to tell "not asked
239
+ // for" from an explicit false, because an explicit false is what overrides
240
+ // the webSafeHtml shorthand. It resolves the tri-state to a boolean, so no
241
+ // consumer downstream sees the undefined.
195
242
  embedAttachedImages: Joi.boolean()
196
243
  .truthy('Y', 'true', '1')
197
244
  .falsy('N', 'false', 0)
198
- .default(false)
199
- .description('If true, then fetches attached images and embeds these in the HTML as data URIs')
245
+ .description('If true, then fetches attached images and embeds these in the HTML as data URIs. Not set means false')
246
+ .meta({ usage: FIELD_USAGE.embedAttachedImages })
200
247
  .label('EmbedImages'),
201
248
 
202
249
  preProcessHtml: Joi.boolean()
@@ -260,6 +307,21 @@ async function init(args) {
260
307
  tags: ['api', 'Message'],
261
308
 
262
309
  plugins: {
310
+ mcp: {
311
+ name: 'create_draft',
312
+ title: 'Create draft',
313
+ description:
314
+ 'Store a new message in a folder, typically a draft in the Drafts folder. Takes structured fields (from, to, subject, text, html). ' +
315
+ 'It takes the same `reference` block as send_message, so a reply or a forward can be drafted for the user to look over first. ' +
316
+ 'Nothing is sent - use send_message for that.',
317
+ // An allowlist for the same reason send_message uses one: the composed message
318
+ // is a small stable set, the route's payload is not, and a field added later
319
+ // should not join an agent-facing schema by default. Left out are `raw` (which
320
+ // replaces the structured fields this tool is made of), `messageId`/`headers`
321
+ // (headers EmailEngine derives), `internalDate` (backdates the stored copy)
322
+ // and `locale`/`tz` (rendering detail).
323
+ keep: ['account', 'path', 'flags', 'reference', 'from', 'to', 'cc', 'bcc', 'subject', 'text', 'html', 'attachments']
324
+ },
263
325
  openapi: {
264
326
  'x-ee-behavior': [BEHAVIOR.UPLOAD_DRAFTS_ONLY_GRAPH],
265
327
  responses: apiResponses('Returns the uploaded message with the identifiers the provider assigned to it.', 400, 401, 403, 404, 429, 500, 503)
@@ -433,6 +495,11 @@ async function init(args) {
433
495
  tags: ['api', 'Message'],
434
496
 
435
497
  plugins: {
498
+ mcp: {
499
+ name: 'update_message',
500
+ title: 'Update message flags',
501
+ description: 'Update the flags or labels of one message, e.g. add \\Seen to mark it read or \\Flagged to star it.'
502
+ },
436
503
  openapi: {
437
504
  'x-ee-behavior': [BEHAVIOR.NO_LABEL_SET_ON_GMAIL],
438
505
  responses: apiResponses('Returns which flag and label changes were applied.', 400, 401, 403, 404, 429, 500, 503)
@@ -599,6 +666,11 @@ async function init(args) {
599
666
  tags: ['api', 'Message'],
600
667
 
601
668
  plugins: {
669
+ mcp: {
670
+ name: 'move_message',
671
+ title: 'Move message',
672
+ description: 'Move one message to another folder. The target folder path comes from list_mailboxes.'
673
+ },
602
674
  openapi: {
603
675
  responses: apiResponses('Returns the message identifiers in the target folder.', 400, 401, 403, 404, 429, 500, 503)
604
676
  }
@@ -751,6 +823,11 @@ async function init(args) {
751
823
  tags: ['api', 'Message'],
752
824
 
753
825
  plugins: {
826
+ mcp: {
827
+ name: 'delete_message',
828
+ title: 'Delete message',
829
+ description: 'Delete one message. It is moved to Trash when possible, and deleted permanently when it already is in Trash.'
830
+ },
754
831
  openapi: {
755
832
  'x-ee-impact': IMPACT.DESTRUCTIVE,
756
833
  'x-ee-behavior': [BEHAVIOR.GMAIL_DELETE_IS_TRASH],
@@ -939,6 +1016,12 @@ async function init(args) {
939
1016
  tags: ['api', 'Message'],
940
1017
 
941
1018
  plugins: {
1019
+ mcp: {
1020
+ name: 'list_messages',
1021
+ title: 'List messages',
1022
+ description: 'List messages in one mailbox folder, newest first, paged. The folder path comes from list_mailboxes.',
1023
+ bounds: { pageSize: MCP_MAX_PAGE_SIZE }
1024
+ },
942
1025
  openapi: {
943
1026
  responses: apiResponses('Returns a page of messages from the folder, newest first.', 400, 401, 403, 404, 429, 500, 503)
944
1027
  }
@@ -1043,6 +1126,13 @@ async function init(args) {
1043
1126
  tags: ['api', 'Message'],
1044
1127
 
1045
1128
  plugins: {
1129
+ mcp: {
1130
+ name: 'search_messages',
1131
+ title: 'Search messages',
1132
+ description:
1133
+ 'Search for messages in one folder using structured criteria (from, to, subject, body, date ranges, flags). Searches a single folder, not the whole account.',
1134
+ bounds: { pageSize: MCP_MAX_PAGE_SIZE }
1135
+ },
1046
1136
  openapi: {
1047
1137
  'x-ee-impact': IMPACT.READONLY,
1048
1138
  responses: apiResponses('Returns a page of matching messages, newest first.', 400, 401, 403, 404, 422, 429, 500, 503)
@@ -1325,6 +1415,17 @@ async function init(args) {
1325
1415
  tags: ['api', 'Message'],
1326
1416
 
1327
1417
  plugins: {
1418
+ mcp: {
1419
+ name: 'get_message_text',
1420
+ title: 'Get message text',
1421
+ description:
1422
+ 'Fetch the body of a message as sanitized HTML, generated from the plaintext part when the message carries no HTML one. The text id comes from the text.id field of get_message or list_messages. ' +
1423
+ `It is capped at ${MCP_MESSAGE_TEXT_MAX_BYTES} characters - hasMore true means the body is longer than that. ` +
1424
+ COLLAPSE_MARKER_NOTE,
1425
+ // Same single body shape get_message returns, for the same reason
1426
+ omit: ['textType', 'webSafeHtml', 'maxBytes'],
1427
+ force: { webSafeHtml: true, maxBytes: MCP_MESSAGE_TEXT_MAX_BYTES }
1428
+ },
1328
1429
  openapi: {
1329
1430
  responses: apiResponses('Returns the message text content in the requested formats.', 400, 401, 403, 404, 429, 500, 503)
1330
1431
  }
@@ -1350,7 +1451,7 @@ async function init(args) {
1350
1451
  .min(0)
1351
1452
  .max(1024 * 1024 * 1024)
1352
1453
  .example(MAX_ATTACHMENT_SIZE)
1353
- .description('Max length of text content. Ignored for Gmail API and MS Graph API accounts (full content is always returned)'),
1454
+ .description('Max length of text content'),
1354
1455
  textType: Joi.string()
1355
1456
  .lowercase()
1356
1457
  .valid('html', 'plain', '*')
@@ -1358,6 +1459,15 @@ async function init(args) {
1358
1459
  .example('*')
1359
1460
  .description('Which text content to return, use * for all. By default all contents are returned.')
1360
1461
  .label('TextSearchTextType'),
1462
+
1463
+ webSafeHtml: Joi.boolean()
1464
+ .truthy('Y', 'true', '1')
1465
+ .falsy('N', 'false', 0)
1466
+ .default(false)
1467
+ .description('If true, then returns a single sanitized HTML rendering of the body instead of the raw text parts')
1468
+ .meta({ usage: FIELD_USAGE.webSafeText })
1469
+ .label('WebSafeText'),
1470
+
1361
1471
  documentStore: documentStoreSchema.default(false)
1362
1472
  }),
1363
1473
 
@@ -1374,8 +1484,11 @@ async function init(args) {
1374
1484
 
1375
1485
  response: {
1376
1486
  schema: Joi.object({
1377
- plain: Joi.string().example('Hello world').description('Plaintext content'),
1487
+ plain: Joi.string().example('Hello world').description('Plaintext content. Not returned when webSafeHtml was requested'),
1378
1488
  html: Joi.string().example('<p>Hello world</p>').description('HTML content'),
1489
+ webSafe: Joi.boolean()
1490
+ .example(true)
1491
+ .description('Whether the HTML content has been processed into a web-safe version (set when webSafeHtml was requested)'),
1379
1492
  hasMore: Joi.boolean()
1380
1493
  .example(false)
1381
1494
  .description('Is the current text output capped or not. Always false for Gmail API and MS Graph API accounts')
@@ -1417,6 +1530,14 @@ async function init(args) {
1417
1530
  cors: CORS_CONFIG,
1418
1531
 
1419
1532
  plugins: {
1533
+ mcp: {
1534
+ name: 'get_attachment',
1535
+ title: 'Get attachment',
1536
+ description:
1537
+ 'Download one attachment, returned inline as a base64 resource. The attachment id comes from the attachments list of get_message. Fails above 1 MB - larger files have to be fetched over the REST API.',
1538
+ binary: true,
1539
+ resourceUriTemplate: 'emailengine://account/{account}/attachment/{attachment}'
1540
+ },
1420
1541
  openapi: {
1421
1542
  produces: ['application/octet-stream'],
1422
1543
  responses: apiResponses('Returns the attachment content as a binary stream.', 400, 401, 403, 404, 429, 500, 503)
@@ -8,6 +8,7 @@ const { failAction } = require('../tools');
8
8
  const { handleError, maskSecrets, MASK_NOTE } = require('./route-helpers');
9
9
  const { outboxEntrySchema, apiResponses } = require('../schemas');
10
10
  const { IMPACT } = require('./operation-impact');
11
+ const { MCP_MAX_PAGE_SIZE } = require('../consts');
11
12
 
12
13
  async function init(args) {
13
14
  const { server, CORS_CONFIG } = args;
@@ -38,6 +39,12 @@ async function init(args) {
38
39
  tags: ['api', 'Outbox'],
39
40
 
40
41
  plugins: {
42
+ mcp: {
43
+ name: 'get_outbox',
44
+ title: 'List outbox',
45
+ description: 'List messages queued for delivery, paged, including scheduled sends and their delivery progress.',
46
+ bounds: { pageSize: MCP_MAX_PAGE_SIZE }
47
+ },
41
48
  openapi: {
42
49
  responses: apiResponses('Returns the messages currently queued for delivery.', 400, 401, 403, 429, 500)
43
50
  }
@@ -145,9 +145,101 @@ const SURFACE_GRANTS = {
145
145
  ],
146
146
  // Not a submission surface: /metrics is an ordinary api-token route, so this mirrors its entry in
147
147
  // GROUP_ROUTES below. Listed with the others because the admin form shows all three together.
148
- metrics: [{ action: ACTION.READ, group: GROUP.DIAGNOSTICS }]
148
+ metrics: [{ action: ACTION.READ, group: GROUP.DIAGNOSTICS }],
149
+
150
+ // The MCP endpoint. Unlike smtp and imap-proxy this surface is checked per request, not once
151
+ // at login (see PER_REQUEST_SURFACES below): an mcp-scoped token opens /mcp, and each tool
152
+ // call is re-authenticated as the API request it dispatches, admitted only when that route's
153
+ // grant is in this list - the surfaceAdmits() predicate below is the one place that rule is
154
+ // written. The list must therefore cover every grant a tool the MCP registry exposes can
155
+ // require - test/mcp-tools-test.js asserts exactly that, so a new plugins.mcp block on a
156
+ // route outside these grants fails the build rather than shipping a tool that mcp-scoped
157
+ // tokens cannot call.
158
+ mcp: [
159
+ { action: ACTION.READ, group: GROUP.ACCOUNT },
160
+ { action: ACTION.READ, group: GROUP.MAILBOX },
161
+ { action: ACTION.READ, group: GROUP.MESSAGE },
162
+ { action: ACTION.WRITE, group: GROUP.MESSAGE },
163
+ { action: ACTION.DESTRUCTIVE, group: GROUP.MESSAGE },
164
+ { action: ACTION.SEND, group: GROUP.SUBMIT },
165
+ { action: ACTION.READ, group: GROUP.OUTBOX },
166
+ { action: ACTION.READ, group: GROUP.TEMPLATE }
167
+ ]
149
168
  };
150
169
 
170
+ // The quantifier over SURFACE_GRANTS differs by surface, and consumers must not hard-code their
171
+ // own: the login-time surfaces (smtp, imap-proxy, metrics) admit a token only if it holds ALL of
172
+ // their grants, because they are checked once and then hand over a session; a per-request
173
+ // surface admits a request when ANY single grant covers it, because every request is checked on
174
+ // its own. The admin token form renders its scope warning from this distinction too.
175
+ const PER_REQUEST_SURFACES = new Set(['mcp']);
176
+
177
+ function grantListAdmits(grants, grant) {
178
+ return (grants || []).some(entry => entry.action === grant.action && entry.group === grant.group);
179
+ }
180
+
181
+ /**
182
+ * Whether one operation is inside a surface's grant list. This is the per-request quantifier -
183
+ * the api-token strategy asks it for the `mcp` scope, and test/mcp-tools-test.js asserts every
184
+ * exposed tool against it, so the guardrail and the enforcement share one predicate.
185
+ *
186
+ * @param {String} scope - a SURFACE_GRANTS key
187
+ * @param {{action: String, group: String}} grant - the operation, from routeGrant()
188
+ * @returns {Boolean}
189
+ */
190
+ function surfaceAdmits(scope, grant) {
191
+ return grantListAdmits(SURFACE_GRANTS[scope], grant);
192
+ }
193
+
194
+ /**
195
+ * What a `sess_` session token may reach.
196
+ *
197
+ * Deliberately not a SURFACE_GRANTS entry: those are token scopes an operator picks on the token
198
+ * form, and this is not one. A session token is minted by the message browser page for its own
199
+ * fetches (lib/ui-routes/account-routes.js), lives in the page HTML where any script on it can read
200
+ * it, and is bound to the account whose page issued it.
201
+ *
202
+ * The list is exactly what static/js/ee-client.js calls: read the account and its folders, read,
203
+ * flag, move, upload and delete messages, and submit. Before it existed the credential skipped the
204
+ * permission check entirely, which let a page-readable token reach every api-tagged route naming
205
+ * its account - including `PUT /v1/account/{account}`, which rewrites the account's webhook target
206
+ * and credentials, and `GET /v1/account/{account}/oauth-token`, which hands out the account's live
207
+ * provider access token. Both are in the never-grantable ADMIN group that no issued token may hold,
208
+ * and this is what makes that true of session tokens too.
209
+ *
210
+ * Per-request, like the mcp surface: the browser calls one route at a time.
211
+ */
212
+ const SESSION_TOKEN_GRANTS = [
213
+ { action: ACTION.READ, group: GROUP.ACCOUNT },
214
+ { action: ACTION.READ, group: GROUP.MAILBOX },
215
+ { action: ACTION.READ, group: GROUP.MESSAGE },
216
+ { action: ACTION.WRITE, group: GROUP.MESSAGE },
217
+ { action: ACTION.DESTRUCTIVE, group: GROUP.MESSAGE },
218
+ { action: ACTION.SEND, group: GROUP.SUBMIT }
219
+ ];
220
+
221
+ /**
222
+ * Whether a session token may perform one operation on one account.
223
+ *
224
+ * The account is half the rule rather than a detail of it. A session token is bound to the account
225
+ * whose page minted it, so a route that names no account is outside its scope by construction - and
226
+ * `GET /v1/accounts`, which lists every account on the instance, resolves to the same read/account
227
+ * grant as the account page the browser does need. The grant list cannot tell those two apart, so
228
+ * the binding is what separates them, and both halves live here so the enforcement and the
229
+ * guardrail ask one question.
230
+ *
231
+ * @param {{action: String, group: String}} grant - the operation, from routeGrant()
232
+ * @param {Object} [opts]
233
+ * @param {String} [opts.account] - the account the request names, from request.params
234
+ * @returns {Boolean}
235
+ */
236
+ function sessionTokenAdmits(grant, opts) {
237
+ if (!opts || !opts.account) {
238
+ return false;
239
+ }
240
+ return grantListAdmits(SESSION_TOKEN_GRANTS, grant);
241
+ }
242
+
151
243
  // Membership sets for the two vocabularies. lib/token-permissions.js rejects a record naming
152
244
  // anything outside them, which is what makes an unknown value a denial rather than something a
153
245
  // reader silently drops.
@@ -390,6 +482,10 @@ module.exports = {
390
482
  ACTION,
391
483
  GROUP,
392
484
  SURFACE_GRANTS,
485
+ PER_REQUEST_SURFACES,
486
+ surfaceAdmits,
487
+ SESSION_TOKEN_GRANTS,
488
+ sessionTokenAdmits,
393
489
  GRANTABLE_GROUPS,
394
490
  ACTION_VALUES,
395
491
  GROUP_VALUES,
@@ -309,9 +309,15 @@ function isMaskedRoundTrip(key, incoming, stored) {
309
309
  * reading a stored credential back is masked, sending it somewhere is not. It applies here because
310
310
  * `submit` is a grantable group, so the narrowing has to hold the line the route grant cannot.
311
311
  *
312
- * Only for narrowed tokens. An unnarrowed one already reaches PUT /v1/account/{account} and can
313
- * point the account's own proxy wherever it likes, so refusing it here would cost a documented
314
- * capability and buy nothing.
312
+ * Refused for two kinds of credential. A narrowed token, for the reason above. And a browse-page
313
+ * session token, which is bounded by SESSION_TOKEN_GRANTS rather than by a permissions record and
314
+ * so reads as unnarrowed here - it holds `send/submit` but is refused `PUT /v1/account/{account}`,
315
+ * which is exactly the shape this guard exists for. Without it the one credential that lives in
316
+ * page HTML could still post the account's SMTP session to an address of its choosing.
317
+ *
318
+ * Everything else is left alone: an unnarrowed API token already reaches PUT /v1/account/{account}
319
+ * and can point the account's own proxy wherever it likes, so refusing it here would cost a
320
+ * documented capability and buy nothing.
315
321
  *
316
322
  * The refusal is not written to the per-token audit log, deliberately. That trail records what a
317
323
  * credential was ADMITTED to attempt - it is written by the auth strategy, before payload validation
@@ -326,10 +332,16 @@ function assertNoNetworkOverride(request) {
326
332
  return;
327
333
  }
328
334
 
335
+ // Set by the api-token strategy for a `sess_` credential. Marked on the request rather than
336
+ // faked into a permissions record: the session bound is a grant list, which the two axes cannot
337
+ // express without widening it, and a record that says more than the rule would be read as
338
+ // policy by the next thing that looks at it.
339
+ const sessionToken = !!(request.app && request.app.sessionToken);
340
+
329
341
  // Asked of the module that enforces the narrowing rather than by testing `permissions` for
330
342
  // truthiness, so `{}` and an unreadable record are read here exactly as they are at the
331
343
  // strategy. `artifacts` is the token record the api-token strategy resolved.
332
- if (!tokenPermissions.inspect(request.auth && request.auth.artifacts).narrowed) {
344
+ if (!sessionToken && !tokenPermissions.inspect(request.auth && request.auth.artifacts).narrowed) {
333
345
  return;
334
346
  }
335
347
 
@@ -15,14 +15,34 @@
15
15
 
16
16
  const PLUGIN_OPTIONS_KEY = 'openapi';
17
17
 
18
+ // The shared no-metadata answer. This accessor runs in the api-token strategy on every API
19
+ // request, and nearly every route declares no plugins.mcp block, so allocating a fresh empty
20
+ // object per call would be steady-state garbage. Frozen so a caller that tries to write into
21
+ // it fails loudly instead of poisoning every other route's answer.
22
+ const NO_OPTIONS = Object.freeze({});
23
+
18
24
  /**
19
25
  * The documentation and permission metadata a route declares.
20
26
  *
21
27
  * @param {Object} route - a `server.table()` entry, or a live `request.route`
22
- * @returns {Object} the route's `plugins.openapi`, or an empty object when it declares none
28
+ * @param {String} [namespace] - which plugins block to read; defaults to `plugins.openapi`
29
+ * @returns {Object} the route's plugins block, or an empty object when it declares none
30
+ */
31
+ function pluginOptions(route, namespace) {
32
+ return (route && route.settings && route.settings.plugins && route.settings.plugins[namespace || PLUGIN_OPTIONS_KEY]) || NO_OPTIONS;
33
+ }
34
+
35
+ /**
36
+ * The MCP metadata a route declares (`plugins.mcp`): a tool definition block on wrapped routes,
37
+ * `{ endpoint: true }` on the /mcp door itself. Three readers - the tool registry, the api-token
38
+ * strategy's door carve-outs, and the route-table guardrail - and this accessor is what keeps a
39
+ * renamed key from turning into an empty object for exactly one of them.
40
+ *
41
+ * @param {Object} route - a `server.table()` entry, or a live `request.route`
42
+ * @returns {Object} the route's `plugins.mcp`, or an empty object when it declares none
23
43
  */
24
- function pluginOptions(route) {
25
- return (route && route.settings && route.settings.plugins && route.settings.plugins[PLUGIN_OPTIONS_KEY]) || {};
44
+ function mcpOptions(route) {
45
+ return pluginOptions(route, 'mcp');
26
46
  }
27
47
 
28
- module.exports = { pluginOptions };
48
+ module.exports = { pluginOptions, mcpOptions };