emailengine-app 2.79.1 → 2.79.3

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 (87) hide show
  1. package/.github/workflows/deploy.yml +92 -39
  2. package/.github/workflows/release.yaml +94 -34
  3. package/.release-please-manifest.json +1 -1
  4. package/CHANGELOG.md +85 -0
  5. package/bin/emailengine.js +8 -1
  6. package/config/default.toml +6 -0
  7. package/copy-static-files.sh +23 -2
  8. package/data/google-crawlers.json +1 -1
  9. package/lib/account.js +138 -18
  10. package/lib/api-routes/account-routes.js +13 -1
  11. package/lib/api-routes/index.js +12 -0
  12. package/lib/api-routes/mailbox-routes.js +6 -0
  13. package/lib/api-routes/mcp-oauth-routes.js +259 -0
  14. package/lib/api-routes/mcp-routes.js +172 -0
  15. package/lib/api-routes/message-routes.js +125 -4
  16. package/lib/api-routes/outbox-routes.js +7 -0
  17. package/lib/api-routes/permission-map.js +97 -1
  18. package/lib/api-routes/route-helpers.js +16 -4
  19. package/lib/api-routes/route-metadata.js +24 -4
  20. package/lib/api-routes/submit-routes.js +41 -0
  21. package/lib/api-routes/template-routes.js +7 -0
  22. package/lib/api-routes/token-routes.js +4 -2
  23. package/lib/consts.js +30 -1
  24. package/lib/email-client/base-client.js +235 -163
  25. package/lib/email-client/gmail-client.js +99 -22
  26. package/lib/email-client/imap/mailbox.js +140 -66
  27. package/lib/email-client/imap-client.js +74 -68
  28. package/lib/email-client/outlook-client.js +29 -14
  29. package/lib/enum-descriptions.js +2 -1
  30. package/lib/field-usage.js +17 -1
  31. package/lib/logger.js +43 -3
  32. package/lib/lua/s-list-accounts.lua +5 -2
  33. package/lib/mcp/index.js +29 -0
  34. package/lib/mcp/inject.js +70 -0
  35. package/lib/mcp/json-schema.js +120 -0
  36. package/lib/mcp/listen.js +171 -0
  37. package/lib/mcp/oauth.js +324 -0
  38. package/lib/mcp/protocol.js +489 -0
  39. package/lib/mcp/resources.js +139 -0
  40. package/lib/mcp/tools.js +655 -0
  41. package/lib/openapi/index.js +3 -1
  42. package/lib/response-stream.js +52 -21
  43. package/lib/routes-ui.js +4 -0
  44. package/lib/schemas.js +24 -3
  45. package/lib/token-permission-view.js +104 -8
  46. package/lib/tokens.js +34 -5
  47. package/lib/tools.js +96 -0
  48. package/lib/ui-routes/account-routes.js +43 -1
  49. package/lib/ui-routes/admin-config-routes.js +114 -1
  50. package/lib/ui-routes/admin-entities-routes.js +54 -5
  51. package/lib/ui-routes/auth-routes.js +13 -0
  52. package/lib/ui-routes/mcp-consent-routes.js +330 -0
  53. package/lib/ui-routes/route-helpers.js +116 -1
  54. package/lib/utils/network.js +9 -1
  55. package/lib/web-safe-html.js +61 -0
  56. package/lib/webhooks.js +3 -8
  57. package/package.json +15 -14
  58. package/sbom.json +1 -1
  59. package/scripts/README.md +25 -0
  60. package/scripts/build-icon.js +77 -0
  61. package/server.js +21 -9
  62. package/static/css/flyonui.css +1 -1
  63. package/static/css/src/app.tailwind.css +98 -0
  64. package/static/emailengine.ico +0 -0
  65. package/static/js/ui.js +465 -1
  66. package/static/licenses.html +85 -135
  67. package/translations/messages.pot +103 -103
  68. package/views/config/mcp.hbs +361 -0
  69. package/views/config/oauth/index.hbs +7 -0
  70. package/views/layout/prompt.hbs +62 -0
  71. package/views/mcp/authorize.hbs +136 -0
  72. package/views/partials/head_assets.hbs +3 -3
  73. package/views/partials/mcp_access_levels.hbs +13 -0
  74. package/views/partials/mcp_account_limit.hbs +14 -0
  75. package/views/partials/mcp_tool_count.hbs +19 -0
  76. package/views/partials/side_menu.hbs +1 -0
  77. package/views/partials/ui/account-picker.hbs +59 -0
  78. package/views/partials/ui/code-block.hbs +26 -0
  79. package/views/partials/ui/menu-item.hbs +5 -0
  80. package/views/partials/ui/radio.hbs +41 -0
  81. package/views/partials/ui/tab.hbs +15 -10
  82. package/views/partials/ui/tabs.hbs +8 -5
  83. package/views/templates/template.hbs +4 -3
  84. package/views/tokens/index.hbs +8 -2
  85. package/views/tokens/new.hbs +514 -243
  86. package/winconf.js +148 -48
  87. package/workers/api.js +198 -48
@@ -0,0 +1,489 @@
1
+ 'use strict';
2
+
3
+ // The MCP wire protocol: JSON-RPC parsing, protocol version negotiation and method dispatch for
4
+ // the /mcp endpoint. Transport-independent on purpose - nothing in here touches Hapi, Redis or
5
+ // streams, so the whole state machine is unit-testable (test/mcp-protocol-test.js). The route
6
+ // handler in lib/api-routes/mcp-routes.js owns HTTP concerns: auth ran before this is called,
7
+ // and the {httpStatus, body} / {listen} descriptors returned here are rendered there.
8
+ //
9
+ // Two protocol eras are served on the same endpoint, per the dual-era server rules in the MCP
10
+ // spec (Versioning and Compatibility, revision 2026-07-28):
11
+ //
12
+ // - Modern (2026-07-28): every request carries its protocol version in
13
+ // params._meta['io.modelcontextprotocol/protocolVersion'], mirrored into the
14
+ // MCP-Protocol-Version header, plus Mcp-Method / Mcp-Name routing headers that MUST match
15
+ // the body. There is no handshake and no session. Results carry resultType: 'complete'.
16
+ //
17
+ // - Legacy (2025-06-18, 2025-11-25): the client opens with an `initialize` request and then
18
+ // names the negotiated version in the MCP-Protocol-Version header. This server is
19
+ // stateless, which the legacy revisions explicitly permit: no Mcp-Session-Id is minted, and
20
+ // the standalone GET notification stream is answered with 405 by the route.
21
+ //
22
+ // JSON-RPC batching is rejected: it only ever existed in revision 2025-03-26, which is not
23
+ // supported here.
24
+
25
+ const packageData = require('../../package.json');
26
+ const { COLLAPSE_CLASS } = require('../consts');
27
+
28
+ const MODERN_PROTOCOL_VERSION = '2026-07-28';
29
+ const LEGACY_PROTOCOL_VERSIONS = ['2025-11-25', '2025-06-18'];
30
+ const SUPPORTED_PROTOCOL_VERSIONS = [MODERN_PROTOCOL_VERSION].concat(LEGACY_PROTOCOL_VERSIONS);
31
+
32
+ const META_PREFIX = 'io.modelcontextprotocol/';
33
+ const META_PROTOCOL_VERSION = `${META_PREFIX}protocolVersion`;
34
+ const META_SERVER_INFO = `${META_PREFIX}serverInfo`;
35
+
36
+ const ERROR_CODES = {
37
+ PARSE_ERROR: -32700,
38
+ INVALID_REQUEST: -32600,
39
+ METHOD_NOT_FOUND: -32601,
40
+ INVALID_PARAMS: -32602,
41
+ INTERNAL_ERROR: -32603,
42
+ // Reserved protocol-defined errors (2026-07-28)
43
+ HEADER_MISMATCH: -32020,
44
+ UNSUPPORTED_PROTOCOL_VERSION: -32022
45
+ };
46
+
47
+ const SERVER_INFO = { name: 'EmailEngine', version: packageData.version };
48
+
49
+ // Everything the instructions say that does not depend on which credential is asking. The collapse
50
+ // marker earns its line here: it is a machine-readable "show more" boundary, and an agent that
51
+ // knows the class name can read the new part of a thread without the quoted copies of everything
52
+ // before it. The send warning is the other one that matters, and having it in one place is why it
53
+ // cannot be edited in the generic set and forgotten in the bound one.
54
+ const COMMON_INSTRUCTIONS = [
55
+ 'Message ids come from list_messages or search_messages.',
56
+ `Message bodies are returned as sanitized HTML; quoted reply and forward history is wrapped in a <details class="${COLLAPSE_CLASS}"> element, ` +
57
+ 'so what the sender actually wrote is everything outside it.',
58
+ 'send_message delivers real email to real recipients - confirm with the user before calling it.'
59
+ ];
60
+
61
+ /**
62
+ * The instructions shown to the calling model by clients that surface them.
63
+ *
64
+ * Only the opening differs, and it differs on the one thing that changes what the agent can do:
65
+ * the generic set tells it to list the accounts and pass an id, which a bound credential can do
66
+ * neither of - the listing tools are not advertised to it, and its tools carry no `account`
67
+ * argument because the endpoint already knows which account they act on. Saying so up front is
68
+ * what stops the agent looking for a way to supply one.
69
+ *
70
+ * Kept short either way: this rides along on every discover/initialize response.
71
+ *
72
+ * @param {String} [account] - the bound account id, for an account-bound credential
73
+ * @returns {String} instructions
74
+ */
75
+ function serverInstructions(account) {
76
+ const opening = account
77
+ ? [
78
+ `EmailEngine gives access to the email account '${account}' on this instance.`,
79
+ 'This credential reaches that one account and no other, so the tools take no account argument - it is applied for you.'
80
+ ]
81
+ : [
82
+ 'EmailEngine gives access to the email accounts registered on this instance.',
83
+ 'Call list_accounts first and use the returned account id as the `account` argument of the other tools.'
84
+ ];
85
+
86
+ return opening.concat(COMMON_INSTRUCTIONS).join(' ');
87
+ }
88
+
89
+ const SERVER_INSTRUCTIONS = serverInstructions();
90
+
91
+ // URL hostnames that mean "this machine" for the transport policies below: the Origin check
92
+ // here and the loopback redirect-URI rule in lib/mcp/oauth.js read the same list, so the two
93
+ // cannot drift on what counts as local.
94
+ const LOOPBACK_HOSTNAMES = ['localhost', '127.0.0.1', '::1', '[::1]'];
95
+
96
+ // Cache policy of the modern era (Caching utility, revision 2026-07-28): every complete result
97
+ // of the discovery and listing methods MUST carry ttlMs and cacheScope, and strict clients
98
+ // (Claude Code among them) refuse a tools/list without them. The table is total over the
99
+ // result-bearing methods on purpose: null declares a method non-cacheable per the spec, and
100
+ // completeResult() throws on a method with no entry at all, so adding a method forces a caching
101
+ // decision instead of silently shipping a listing a strict client rejects.
102
+ //
103
+ // The scope is uniformly private because nothing this endpoint serves is caller-neutral:
104
+ // server/discover embeds a bound credential's account id in its instructions, tools/list is
105
+ // narrowed to what the caller's token permits, and the resource listings and reads are that
106
+ // caller's accounts. The templates listing is an empty constant today, but private is the value
107
+ // that stays correct if that ever changes. The TTLs are freshness hints, not contracts: the
108
+ // catalog-shaped results move only when an operator edits settings or token permissions, the
109
+ // account listing moves as accounts come and go, and a read carries connection state that flips
110
+ // on its own.
111
+ const CACHE_TTLS = {
112
+ 'server/discover': 300 * 1000,
113
+ 'tools/list': 300 * 1000,
114
+ 'resources/templates/list': 300 * 1000,
115
+ 'resources/list': 60 * 1000,
116
+ 'resources/read': 30 * 1000,
117
+ ping: null,
118
+ 'tools/call': null
119
+ };
120
+
121
+ // Builds a modern-era complete result: the resultType marker, the declared cache hints, then
122
+ // the payload. The throw is unreachable from the wire - an unknown method is answered
123
+ // method-not-found before any result is built - so it only fires on a half-finished code change.
124
+ function completeResult(method, result) {
125
+ if (!Object.hasOwn(CACHE_TTLS, method)) {
126
+ throw new Error(`No cache policy declared for method: ${method}`);
127
+ }
128
+ const ttlMs = CACHE_TTLS[method];
129
+ return Object.assign({ resultType: 'complete' }, ttlMs === null ? null : { ttlMs, cacheScope: 'private' }, result);
130
+ }
131
+
132
+ function isPlainObject(value) {
133
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
134
+ }
135
+
136
+ /**
137
+ * Whether the client's Accept header admits an SSE response.
138
+ *
139
+ * Parses q-values rather than matching the media type alone: `text/event-stream;q=0` is the
140
+ * standard way for a JSON-only client to say it cannot consume the stream, and handing one to it
141
+ * anyway is exactly what the check exists to prevent.
142
+ */
143
+ function acceptsEventStream(header) {
144
+ for (const entry of String(header || '').split(',')) {
145
+ const [mediaType, ...params] = entry.split(';').map(part => part.trim());
146
+
147
+ if (!['text/event-stream', 'text/*', '*/*'].includes(mediaType.toLowerCase())) {
148
+ continue;
149
+ }
150
+
151
+ const quality = params.map(param => /^q=/i.test(param) && Number.parseFloat(param.slice(2))).find(value => value !== false);
152
+
153
+ // An unparseable q is not a refusal; only an explicit zero is
154
+ if (quality === 0) {
155
+ continue;
156
+ }
157
+
158
+ return true;
159
+ }
160
+
161
+ return false;
162
+ }
163
+
164
+ /**
165
+ * Whether a browser Origin may talk to the MCP endpoint. Non-browser MCP clients send no Origin
166
+ * header at all; a present Origin means a web page is calling, and anything that is not
167
+ * provably this instance or an explicitly configured CORS origin is refused to keep DNS
168
+ * rebinding out (MCP Streamable HTTP, "Security & Endpoint").
169
+ */
170
+ function isAllowedOrigin(origin, { serviceUrl, corsOrigins }) {
171
+ if (!origin) {
172
+ return true;
173
+ }
174
+
175
+ let parsed;
176
+ try {
177
+ parsed = new URL(origin);
178
+ } catch (err) {
179
+ return false;
180
+ }
181
+
182
+ if (LOOPBACK_HOSTNAMES.includes(parsed.hostname)) {
183
+ return true;
184
+ }
185
+
186
+ if (serviceUrl) {
187
+ try {
188
+ if (new URL(serviceUrl).origin === parsed.origin) {
189
+ return true;
190
+ }
191
+ } catch (err) {
192
+ // a malformed serviceUrl setting grants nothing
193
+ }
194
+ }
195
+
196
+ return (corsOrigins || []).some(entry => entry === '*' || entry === parsed.origin);
197
+ }
198
+
199
+ function rpcError(id, code, message, data) {
200
+ const error = { code, message };
201
+ if (data !== undefined) {
202
+ error.data = data;
203
+ }
204
+ return { jsonrpc: '2.0', id: id === undefined ? null : id, error };
205
+ }
206
+
207
+ function rpcResult(id, result) {
208
+ return { jsonrpc: '2.0', id, result };
209
+ }
210
+
211
+ /**
212
+ * Decodes the =?base64?...?= sentinel format the transport uses for header values that are not
213
+ * plain ASCII (Streamable HTTP, "Value Encoding"). Plain values pass through untouched.
214
+ */
215
+ function decodeHeaderValue(value) {
216
+ if (typeof value !== 'string') {
217
+ return value;
218
+ }
219
+
220
+ const match = /^=\?base64\?(.*)\?=$/.exec(value);
221
+ if (!match) {
222
+ return value;
223
+ }
224
+
225
+ try {
226
+ return Buffer.from(match[1], 'base64').toString('utf8');
227
+ } catch (err) {
228
+ return value;
229
+ }
230
+ }
231
+
232
+ function unsupportedVersionError(id, requested) {
233
+ return rpcError(id, ERROR_CODES.UNSUPPORTED_PROTOCOL_VERSION, 'Unsupported protocol version', {
234
+ supported: SUPPORTED_PROTOCOL_VERSIONS,
235
+ requested: requested === undefined ? null : requested
236
+ });
237
+ }
238
+
239
+ function capabilities(era) {
240
+ return {
241
+ tools: {},
242
+ resources: era === 'legacy' ? { subscribe: false, listChanged: false } : {}
243
+ };
244
+ }
245
+
246
+ /**
247
+ * Processes one JSON-RPC message POSTed to the MCP endpoint.
248
+ *
249
+ * @param {Object} opts
250
+ * @param {*} opts.body - the parsed request payload
251
+ * @param {Object} opts.headers - lowercased HTTP request headers
252
+ * @param {Object} opts.ctx - dispatch context:
253
+ * listTools() => [tool definitions],
254
+ * callTool(name, args) => tool result (throws {rpcCode, message} for protocol errors),
255
+ * listResources() => [resources], readResource(uri) => contents,
256
+ * instructions - optional per-credential replacement for SERVER_INSTRUCTIONS,
257
+ * acceptsEventStream - whether the request's Accept header admits text/event-stream
258
+ * @returns {Promise<Object>} { httpStatus, body } for a JSON response (body undefined for 202),
259
+ * or { listen: { id, filter } } when a subscriptions/listen request was accepted and
260
+ * the caller should open the SSE stream
261
+ */
262
+ async function processMcpRequest({ body, headers, ctx }) {
263
+ if (Array.isArray(body)) {
264
+ // Batching existed only in revision 2025-03-26, which predates every version this
265
+ // endpoint speaks
266
+ return { httpStatus: 200, body: rpcError(null, ERROR_CODES.INVALID_REQUEST, 'JSON-RPC batch requests are not supported') };
267
+ }
268
+
269
+ if (!isPlainObject(body) || body.jsonrpc !== '2.0' || typeof body.method !== 'string') {
270
+ return { httpStatus: 200, body: rpcError(isPlainObject(body) ? body.id : null, ERROR_CODES.INVALID_REQUEST, 'Not a valid JSON-RPC 2.0 request') };
271
+ }
272
+
273
+ const id = Object.prototype.hasOwnProperty.call(body, 'id') ? body.id : undefined;
274
+ const isNotification = id === undefined;
275
+ const params = isPlainObject(body.params) ? body.params : {};
276
+ const meta = isPlainObject(params._meta) ? params._meta : {};
277
+ const metaVersion = typeof meta[META_PROTOCOL_VERSION] === 'string' ? meta[META_PROTOCOL_VERSION] : undefined;
278
+
279
+ if (metaVersion !== undefined) {
280
+ return processModern({ body, id, isNotification, params, metaVersion, headers, ctx });
281
+ }
282
+
283
+ return processLegacy({ body, id, isNotification, params, headers, ctx });
284
+ }
285
+
286
+ async function processModern({ body, id, isNotification, params, metaVersion, headers, ctx }) {
287
+ const headerVersion = headers['mcp-protocol-version'];
288
+
289
+ // The header and the body value MUST agree, so that an intermediary routing on the header
290
+ // and this server executing on the body cannot act on different requests
291
+ if (headerVersion !== metaVersion) {
292
+ return {
293
+ httpStatus: 400,
294
+ body: rpcError(id, ERROR_CODES.HEADER_MISMATCH, 'MCP-Protocol-Version header does not match the protocol version in the request body')
295
+ };
296
+ }
297
+
298
+ if (metaVersion !== MODERN_PROTOCOL_VERSION) {
299
+ return { httpStatus: 400, body: unsupportedVersionError(id, metaVersion) };
300
+ }
301
+
302
+ if (!isNotification) {
303
+ const headerMethod = decodeHeaderValue(headers['mcp-method']);
304
+ if (headerMethod !== body.method) {
305
+ return {
306
+ httpStatus: 400,
307
+ body: rpcError(
308
+ id,
309
+ ERROR_CODES.HEADER_MISMATCH,
310
+ headers['mcp-method'] ? 'Mcp-Method header does not match the request body' : 'Missing required Mcp-Method header'
311
+ )
312
+ };
313
+ }
314
+
315
+ // Mcp-Name mirrors the tool name or resource URI on the requests that carry one
316
+ const namedValue = body.method === 'tools/call' ? params.name : body.method === 'resources/read' ? params.uri : undefined;
317
+ if (namedValue !== undefined) {
318
+ const headerName = decodeHeaderValue(headers['mcp-name']);
319
+ if (headerName !== namedValue) {
320
+ return {
321
+ httpStatus: 400,
322
+ body: rpcError(
323
+ id,
324
+ ERROR_CODES.HEADER_MISMATCH,
325
+ headers['mcp-name'] ? 'Mcp-Name header does not match the request body' : 'Missing required Mcp-Name header'
326
+ )
327
+ };
328
+ }
329
+ }
330
+ }
331
+
332
+ if (isNotification) {
333
+ // The modern revision defines no client-to-server notifications over Streamable HTTP,
334
+ // but an accepted notification is answered 202 rather than rejected, so a conforming
335
+ // client that sends one anyway is not punished for it
336
+ return { httpStatus: 202 };
337
+ }
338
+
339
+ switch (body.method) {
340
+ case 'server/discover': {
341
+ const result = completeResult(body.method, {
342
+ supportedVersions: SUPPORTED_PROTOCOL_VERSIONS,
343
+ capabilities: capabilities('modern'),
344
+ instructions: ctx.instructions || SERVER_INSTRUCTIONS,
345
+ _meta: { [META_SERVER_INFO]: SERVER_INFO }
346
+ });
347
+ return { httpStatus: 200, body: rpcResult(id, result) };
348
+ }
349
+
350
+ case 'subscriptions/listen': {
351
+ if (!ctx.acceptsEventStream) {
352
+ return {
353
+ httpStatus: 400,
354
+ body: rpcError(id, ERROR_CODES.INVALID_REQUEST, 'subscriptions/listen requires an Accept header that includes text/event-stream')
355
+ };
356
+ }
357
+ return { listen: { id, filter: isPlainObject(params.notifications) ? params.notifications : {} } };
358
+ }
359
+
360
+ default:
361
+ return dispatchCommon({ era: 'modern', method: body.method, id, params, ctx });
362
+ }
363
+ }
364
+
365
+ async function processLegacy({ body, id, isNotification, params, headers, ctx }) {
366
+ const headerVersion = headers['mcp-protocol-version'];
367
+
368
+ if (headerVersion !== undefined) {
369
+ if (headerVersion === MODERN_PROTOCOL_VERSION) {
370
+ // A modern header on a request whose body carries no modern metadata: the two
371
+ // sources of truth disagree, which is exactly what the mirrored-header validation
372
+ // exists to refuse
373
+ return {
374
+ httpStatus: 400,
375
+ body: rpcError(
376
+ id,
377
+ ERROR_CODES.HEADER_MISMATCH,
378
+ 'MCP-Protocol-Version header names a modern revision but the request body carries no protocol version metadata'
379
+ )
380
+ };
381
+ }
382
+
383
+ if (!LEGACY_PROTOCOL_VERSIONS.includes(headerVersion)) {
384
+ return { httpStatus: 400, body: unsupportedVersionError(id, headerVersion) };
385
+ }
386
+ }
387
+
388
+ if (isNotification) {
389
+ // notifications/initialized and friends: acknowledged and dropped, since there is no
390
+ // session state to arm
391
+ return { httpStatus: 202 };
392
+ }
393
+
394
+ if (body.method === 'initialize') {
395
+ const proposed = typeof params.protocolVersion === 'string' ? params.protocolVersion : undefined;
396
+
397
+ // Echo a supported proposal; counter an unsupported one with the newest legacy version
398
+ // this endpoint speaks, as the legacy negotiation rules prescribe. The modern version is
399
+ // never offered here - it has no initialize handshake to arrive through.
400
+ const negotiated = LEGACY_PROTOCOL_VERSIONS.includes(proposed) ? proposed : LEGACY_PROTOCOL_VERSIONS[0];
401
+
402
+ const result = {
403
+ protocolVersion: negotiated,
404
+ capabilities: capabilities('legacy'),
405
+ serverInfo: SERVER_INFO,
406
+ instructions: ctx.instructions || SERVER_INSTRUCTIONS
407
+ };
408
+ return { httpStatus: 200, body: rpcResult(id, result) };
409
+ }
410
+
411
+ return dispatchCommon({ era: 'legacy', method: body.method, id, params, ctx });
412
+ }
413
+
414
+ // The methods both eras share. Results are identical apart from the modern resultType marker
415
+ // and the modern cache hints - the legacy revisions define neither.
416
+ async function dispatchCommon({ era, method, id, params, ctx }) {
417
+ const respond = result => {
418
+ if (era === 'modern') {
419
+ result = completeResult(method, result);
420
+ }
421
+ return { httpStatus: 200, body: rpcResult(id, result) };
422
+ };
423
+
424
+ // Runs a dispatcher whose domain errors carry an rpcCode: those become JSON-RPC error
425
+ // responses, anything else stays an exception for the route's own error handling
426
+ const respondWith = async produce => {
427
+ try {
428
+ return respond(await produce());
429
+ } catch (err) {
430
+ if (err.rpcCode) {
431
+ return { httpStatus: 200, body: rpcError(id, err.rpcCode, err.message) };
432
+ }
433
+ throw err;
434
+ }
435
+ };
436
+
437
+ switch (method) {
438
+ case 'ping':
439
+ return respond({});
440
+
441
+ case 'tools/list':
442
+ return respond({ tools: await ctx.listTools() });
443
+
444
+ case 'tools/call':
445
+ if (typeof params.name !== 'string' || !params.name) {
446
+ return { httpStatus: 200, body: rpcError(id, ERROR_CODES.INVALID_PARAMS, 'Missing tool name') };
447
+ }
448
+ return respondWith(() => ctx.callTool(params.name, params.arguments));
449
+
450
+ case 'resources/list':
451
+ return respond({ resources: await ctx.listResources() });
452
+
453
+ case 'resources/read':
454
+ if (typeof params.uri !== 'string' || !params.uri) {
455
+ return { httpStatus: 200, body: rpcError(id, ERROR_CODES.INVALID_PARAMS, 'Missing resource uri') };
456
+ }
457
+ return respondWith(async () => ({ contents: await ctx.readResource(params.uri) }));
458
+
459
+ case 'resources/templates/list':
460
+ // A standard listing some clients call unprompted; empty is the truthful answer
461
+ return respond({ resourceTemplates: [] });
462
+
463
+ default:
464
+ // Method not found: HTTP 404 in the modern era (so intermediaries can tell it apart
465
+ // from a legacy server without parsing), plain JSON-RPC error in the legacy one
466
+ return {
467
+ httpStatus: era === 'modern' ? 404 : 200,
468
+ body: rpcError(id, ERROR_CODES.METHOD_NOT_FOUND, `Method not found: ${method}`)
469
+ };
470
+ }
471
+ }
472
+
473
+ module.exports = {
474
+ processMcpRequest,
475
+ decodeHeaderValue,
476
+ isAllowedOrigin,
477
+ acceptsEventStream,
478
+ rpcError,
479
+ ERROR_CODES,
480
+ CACHE_TTLS,
481
+ LOOPBACK_HOSTNAMES,
482
+ MODERN_PROTOCOL_VERSION,
483
+ LEGACY_PROTOCOL_VERSIONS,
484
+ SUPPORTED_PROTOCOL_VERSIONS,
485
+ META_PROTOCOL_VERSION,
486
+ SERVER_INFO,
487
+ SERVER_INSTRUCTIONS,
488
+ serverInstructions
489
+ };
@@ -0,0 +1,139 @@
1
+ 'use strict';
2
+
3
+ // MCP resources: the connected email accounts, one resource per account.
4
+ //
5
+ // The URI scheme is emailengine://account/{account}. Reads go through the same authenticated
6
+ // server.inject() dispatch as tool calls, so what a credential can list and read here is exactly
7
+ // what it can reach over REST - an account-bound token sees its own account and nothing else,
8
+ // without this module holding any policy of its own.
9
+
10
+ const { apiInject } = require('./inject');
11
+ const { ERROR_CODES } = require('./protocol');
12
+
13
+ const ACCOUNT_URI_PREFIX = 'emailengine://account/';
14
+
15
+ // How many accounts one resources/list reports. The listing exists so an agent can find the
16
+ // account ids it should pass to tools; an instance running tens of thousands of accounts is not
17
+ // browsable that way, and list_accounts with paging arguments is the tool for it.
18
+ const MAX_LISTED_ACCOUNTS = 500;
19
+
20
+ function accountUri(account) {
21
+ return ACCOUNT_URI_PREFIX + encodeURIComponent(account);
22
+ }
23
+
24
+ /**
25
+ * Whether an account id survives the URI round-trip. parseAccountUri refuses decoded URI
26
+ * structure, so an id carrying any would be listed under a URI that resources/read and the
27
+ * listen filter then reject - such an account is reachable through the tools, just not
28
+ * addressable as a resource, and the listings skip it rather than advertise a dead URI.
29
+ */
30
+ function isRepresentableAccountId(account) {
31
+ return typeof account === 'string' && !!account && !/[/?#]/.test(account);
32
+ }
33
+
34
+ /**
35
+ * The account id an emailengine://account/{account} URI names, or null for anything else.
36
+ * The one place the URI scheme is parsed and validated - resources/read and the
37
+ * subscriptions/listen filter both come through here.
38
+ */
39
+ function parseAccountUri(uri) {
40
+ if (typeof uri !== 'string' || !uri.startsWith(ACCOUNT_URI_PREFIX)) {
41
+ return null;
42
+ }
43
+
44
+ let account;
45
+ try {
46
+ account = decodeURIComponent(uri.slice(ACCOUNT_URI_PREFIX.length));
47
+ } catch (err) {
48
+ // A malformed percent-escape ('%', '%zz') throws URIError. That is an unparseable URI
49
+ // like any other, and it has to answer as one: an uncaught throw here carries no
50
+ // rpcCode, so the endpoint would answer 500 with no JSON-RPC envelope at all.
51
+ return null;
52
+ }
53
+
54
+ if (!isRepresentableAccountId(account)) {
55
+ return null;
56
+ }
57
+
58
+ return account;
59
+ }
60
+
61
+ function resourceNotFound(message) {
62
+ const err = new Error(message);
63
+ // Standard MCP "resource not found" error code
64
+ err.rpcCode = -32002;
65
+ return err;
66
+ }
67
+
68
+ function accountResource(accountData) {
69
+ return {
70
+ uri: accountUri(accountData.account),
71
+ name: accountData.account,
72
+ title: accountData.name || accountData.account,
73
+ description: [accountData.email, accountData.state ? `state: ${accountData.state}` : null].filter(Boolean).join(', ') || undefined,
74
+ mimeType: 'application/json'
75
+ };
76
+ }
77
+
78
+ /**
79
+ * Lists connected accounts as MCP resources, as far as the caller's credential can see them.
80
+ */
81
+ async function listResources({ server, request }) {
82
+ // An account-bound token may not enumerate the instance (the same rule REST enforces on
83
+ // GET /v1/accounts), but it should still see its own account here rather than an error -
84
+ // the strategy parked the binding on the request for exactly this kind of consumer
85
+ const boundAccount = request.app && request.app.mcpBoundAccount;
86
+
87
+ if (boundAccount) {
88
+ if (!isRepresentableAccountId(boundAccount)) {
89
+ return [];
90
+ }
91
+ const res = await apiInject({ server, request, method: 'get', url: `/v1/account/${encodeURIComponent(boundAccount)}` });
92
+ if (res.statusCode >= 400 || !res.result) {
93
+ return [];
94
+ }
95
+ return [accountResource(res.result)];
96
+ }
97
+
98
+ // One request: the route accepts page sizes up to 1000, so the whole cap fits a single page
99
+ const res = await apiInject({ server, request, method: 'get', url: `/v1/accounts?page=0&pageSize=${MAX_LISTED_ACCOUNTS}` });
100
+ if (res.statusCode >= 400 || !res.result || !Array.isArray(res.result.accounts)) {
101
+ return [];
102
+ }
103
+
104
+ return res.result.accounts.filter(accountData => isRepresentableAccountId(accountData.account)).map(accountData => accountResource(accountData));
105
+ }
106
+
107
+ /**
108
+ * Reads one account resource.
109
+ *
110
+ * @returns {Promise<Array>} MCP resource contents
111
+ */
112
+ async function readResource({ server, request, uri }) {
113
+ const account = parseAccountUri(uri);
114
+ if (!account) {
115
+ throw resourceNotFound(`Unknown resource: ${uri}`);
116
+ }
117
+
118
+ const res = await apiInject({ server, request, method: 'get', url: `/v1/account/${encodeURIComponent(account)}` });
119
+
120
+ if (res.statusCode === 404) {
121
+ throw resourceNotFound(`No such account: ${account}`);
122
+ }
123
+
124
+ if (res.statusCode >= 400) {
125
+ const err = new Error((res.result && res.result.message) || `Failed to read account: HTTP ${res.statusCode}`);
126
+ err.rpcCode = ERROR_CODES.INVALID_PARAMS;
127
+ throw err;
128
+ }
129
+
130
+ return [
131
+ {
132
+ uri: accountUri(account),
133
+ mimeType: 'application/json',
134
+ text: JSON.stringify(res.result)
135
+ }
136
+ ];
137
+ }
138
+
139
+ module.exports = { listResources, readResource, accountUri, parseAccountUri, isRepresentableAccountId, ACCOUNT_URI_PREFIX };