emailengine-app 2.79.0 → 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 (110) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +79 -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 +137 -19
  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 +101 -1
  15. package/lib/api-routes/route-helpers.js +87 -4
  16. package/lib/api-routes/route-metadata.js +24 -4
  17. package/lib/api-routes/settings-routes.js +37 -14
  18. package/lib/api-routes/submit-routes.js +41 -0
  19. package/lib/api-routes/template-routes.js +7 -0
  20. package/lib/api-routes/token-routes.js +292 -122
  21. package/lib/arf-detect.js +17 -4
  22. package/lib/bounce-detect.js +28 -17
  23. package/lib/consts.js +36 -1
  24. package/lib/db.js +6 -0
  25. package/lib/email-client/base-client.js +102 -117
  26. package/lib/email-client/gmail-client.js +91 -29
  27. package/lib/email-client/imap/mailbox.js +175 -101
  28. package/lib/email-client/imap-client.js +49 -2
  29. package/lib/email-client/outlook-client.js +20 -24
  30. package/lib/enum-descriptions.js +2 -1
  31. package/lib/field-usage.js +17 -1
  32. package/lib/lua/h-set-new-mark.lua +36 -0
  33. package/lib/lua/s-list-accounts.lua +5 -2
  34. package/lib/mcp/index.js +29 -0
  35. package/lib/mcp/inject.js +70 -0
  36. package/lib/mcp/json-schema.js +120 -0
  37. package/lib/mcp/listen.js +171 -0
  38. package/lib/mcp/oauth.js +324 -0
  39. package/lib/mcp/protocol.js +489 -0
  40. package/lib/mcp/resources.js +139 -0
  41. package/lib/mcp/tools.js +655 -0
  42. package/lib/message-port-stream.js +84 -1
  43. package/lib/oauth2-apps.js +84 -15
  44. package/lib/openapi/build-document.js +5 -1
  45. package/lib/openapi/index.js +3 -1
  46. package/lib/response-stream.js +52 -21
  47. package/lib/routes-ui.js +4 -0
  48. package/lib/schemas.js +26 -5
  49. package/lib/settings.js +23 -9
  50. package/lib/token-audit-log.js +32 -9
  51. package/lib/token-permission-view.js +104 -8
  52. package/lib/tokens.js +194 -68
  53. package/lib/tools.js +96 -0
  54. package/lib/ui-routes/account-routes.js +55 -6
  55. package/lib/ui-routes/admin-config-routes.js +114 -1
  56. package/lib/ui-routes/admin-entities-routes.js +103 -19
  57. package/lib/ui-routes/auth-routes.js +13 -0
  58. package/lib/ui-routes/mcp-consent-routes.js +330 -0
  59. package/lib/ui-routes/oauth-config-routes.js +7 -7
  60. package/lib/ui-routes/route-helpers.js +143 -1
  61. package/lib/ui-routes/suppression-list-routes.js +14 -9
  62. package/lib/utils/decode-headers.js +42 -0
  63. package/lib/utils/header-map.js +48 -0
  64. package/lib/utils/network.js +9 -1
  65. package/lib/utils/unsafe-key.js +59 -0
  66. package/lib/web-safe-html.js +61 -0
  67. package/lib/webhook-routing.js +6 -2
  68. package/lib/webhooks.js +31 -8
  69. package/package.json +9 -8
  70. package/sbom.json +1 -1
  71. package/scripts/README.md +25 -0
  72. package/scripts/build-icon.js +77 -0
  73. package/server.js +39 -17
  74. package/static/css/flyonui.css +1 -1
  75. package/static/css/src/app.tailwind.css +98 -0
  76. package/static/emailengine.ico +0 -0
  77. package/static/js/ui.js +465 -1
  78. package/static/licenses.html +42 -22
  79. package/translations/messages.pot +57 -57
  80. package/views/accounts/account.hbs +8 -8
  81. package/views/accounts/browse.hbs +1 -1
  82. package/views/accounts/edit.hbs +2 -2
  83. package/views/config/mcp.hbs +361 -0
  84. package/views/config/oauth/index.hbs +7 -0
  85. package/views/gateways/edit.hbs +1 -1
  86. package/views/gateways/gateway.hbs +2 -2
  87. package/views/gateways/index.hbs +7 -7
  88. package/views/layout/prompt.hbs +62 -0
  89. package/views/mcp/authorize.hbs +136 -0
  90. package/views/partials/accounts_table.hbs +7 -7
  91. package/views/partials/head_assets.hbs +3 -3
  92. package/views/partials/mcp_access_levels.hbs +13 -0
  93. package/views/partials/mcp_account_limit.hbs +14 -0
  94. package/views/partials/mcp_tool_count.hbs +19 -0
  95. package/views/partials/side_menu.hbs +1 -0
  96. package/views/partials/ui/account-picker.hbs +59 -0
  97. package/views/partials/ui/code-block.hbs +26 -0
  98. package/views/partials/ui/menu-item.hbs +5 -0
  99. package/views/partials/ui/radio.hbs +41 -0
  100. package/views/partials/ui/tab.hbs +15 -10
  101. package/views/partials/ui/tabs.hbs +8 -5
  102. package/views/suppression-lists/list.hbs +1 -1
  103. package/views/templates/index.hbs +2 -2
  104. package/views/templates/template.hbs +5 -4
  105. package/views/tokens/index.hbs +30 -4
  106. package/views/tokens/new.hbs +517 -239
  107. package/winconf.js +148 -48
  108. package/workers/api.js +239 -95
  109. package/workers/imap.js +65 -72
  110. package/workers/webhooks.js +21 -1
@@ -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;
@@ -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)