emailengine-app 2.88.0 → 2.90.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/.ncurc.js +36 -45
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +58 -0
  4. package/Dockerfile +5 -1
  5. package/bin/healthcheck.js +1 -1
  6. package/copy-static-files.sh +0 -8
  7. package/data/google-crawlers.json +1 -1
  8. package/encrypt.js +1 -4
  9. package/lib/account/field-codec.js +396 -0
  10. package/lib/account.js +158 -453
  11. package/lib/api-routes/account-routes.js +42 -6
  12. package/lib/api-routes/route-metadata.js +5 -2
  13. package/lib/api-routes/submit-routes.js +15 -2
  14. package/lib/api-token-auth.js +342 -274
  15. package/lib/arf-detect.js +174 -149
  16. package/lib/attachment-size.js +29 -0
  17. package/lib/autodetect-imap-settings.js +83 -234
  18. package/lib/consts.js +1 -5
  19. package/lib/db.js +1 -4
  20. package/lib/email-client/base-client.js +907 -780
  21. package/lib/email-client/gmail-client.js +557 -450
  22. package/lib/email-client/imap/cid-parts.js +61 -0
  23. package/lib/email-client/imap/mailbox.js +376 -422
  24. package/lib/email-client/imap/sync-operations.js +239 -178
  25. package/lib/email-client/new-message-steps.js +168 -2
  26. package/lib/email-client/outlook/graph-message.js +266 -0
  27. package/lib/email-client/outlook/subscription-expiry.js +30 -0
  28. package/lib/email-client/outlook-client.js +652 -808
  29. package/lib/get-raw-email.js +338 -232
  30. package/lib/get-secret.js +1 -4
  31. package/lib/license-subscription.js +77 -11
  32. package/lib/load-env.js +48 -0
  33. package/lib/logger.js +1 -4
  34. package/lib/mcp/tools.js +244 -207
  35. package/lib/metric-values.js +76 -0
  36. package/lib/metrics.js +320 -0
  37. package/lib/node-version.js +99 -12
  38. package/lib/oauth/gmail.js +39 -120
  39. package/lib/oauth/http-request.js +195 -0
  40. package/lib/oauth/mail-ru.js +24 -58
  41. package/lib/oauth/outlook.js +37 -137
  42. package/lib/oauth/pubsub/google.js +176 -117
  43. package/lib/oauth2-apps.js +440 -463
  44. package/lib/openapi/build-document.js +10 -10
  45. package/lib/read-env-value.js +1 -1
  46. package/lib/route-descriptors.js +78 -0
  47. package/lib/schemas.js +10 -1
  48. package/lib/sentry-integrations.js +299 -0
  49. package/lib/sentry.js +75 -27
  50. package/lib/settings.js +4 -1
  51. package/lib/sso-routes.js +249 -0
  52. package/lib/sso.js +29 -6
  53. package/lib/tools.js +5 -4
  54. package/lib/ui-routes/account-edit-form.js +198 -0
  55. package/lib/ui-routes/account-page.js +241 -0
  56. package/lib/ui-routes/account-routes.js +12 -318
  57. package/lib/ui-routes/auth-routes.js +10 -10
  58. package/lib/ui-routes/dashboard-routes.js +4 -0
  59. package/lib/ui-view-context.js +328 -0
  60. package/lib/utils/public-suffix.js +22 -101
  61. package/lib/web-safe-html.js +70 -13
  62. package/lib/worker-metrics.js +82 -0
  63. package/list-generate.js +57 -23
  64. package/package.json +34 -33
  65. package/sbom.json +380 -1612
  66. package/scripts/refresh-test-tokens.js +1 -1
  67. package/server.js +351 -707
  68. package/static/css/flyonui.css +1 -1
  69. package/static/css/src/app.tailwind.css +18 -0
  70. package/static/js/ee-client.js +2619 -645
  71. package/static/js/ui.js +12 -2
  72. package/static/licenses.html +1055 -969
  73. package/translations/messages.pot +71 -60
  74. package/views/accounts/browse.hbs +19 -1
  75. package/views/dashboard.hbs +9 -0
  76. package/views/upgrade.hbs +25 -0
  77. package/workers/api.js +20 -451
  78. package/data/public_suffix_list.dat +0 -16597
  79. package/lib/net-tos-guard.js +0 -42
package/lib/mcp/tools.js CHANGED
@@ -19,6 +19,7 @@ const { routeGrant, surfaceAdmits, surfaceBoundAdmits, PER_REQUEST_SURFACES, ACT
19
19
  const { routeAdmitsBoundToken } = require('../api-routes/account-binding');
20
20
  const tokenPermissions = require('../token-permissions');
21
21
  const { mcpOptions } = require('../api-routes/route-metadata');
22
+ const { describeRoutes } = require('../route-descriptors');
22
23
  const { joiToJsonSchema } = require('./json-schema');
23
24
  const { apiInject } = require('./inject');
24
25
  const { DOT_SEGMENT } = require('./resources');
@@ -100,14 +101,14 @@ function convertSource(schema) {
100
101
  /**
101
102
  * Derives the MCP tool list from a Hapi route table.
102
103
  *
103
- * @param {Array} routes - server.table()
104
+ * @param {Array} routes - the route table: hapi's server.table() or route descriptors
104
105
  * @returns {{tools: Array, byName: Map}} tool definitions in deterministic (name) order, plus the
105
106
  * executor's lookup table carrying the dispatch data the wire format does not
106
107
  */
107
108
  function buildToolRegistry(routes) {
108
109
  const byName = new Map();
109
110
 
110
- for (const route of routes) {
111
+ for (const route of describeRoutes(routes)) {
111
112
  const options = mcpOptions(route);
112
113
  if (!options.name) {
113
114
  continue;
@@ -119,242 +120,278 @@ function buildToolRegistry(routes) {
119
120
  throw new Error(`MCP tool ${options.name} is declared by two routes`);
120
121
  }
121
122
 
122
- // Nothing else checks the shape of a plugins.mcp block, so a misspelled key would be a
123
- // silent no-op - and every knob here is one that hides or pins something on the
124
- // agent-facing schema, where a no-op means the opposite of what was declared
125
- const unknownOptions = Object.keys(options).filter(key => !MCP_OPTION_KEYS.has(key));
126
- if (unknownOptions.length) {
127
- throw new Error(`MCP tool ${options.name}: unknown plugins.mcp option${unknownOptions.length > 1 ? 's' : ''}: ${unknownOptions.join(', ')}`);
128
- }
129
-
130
- const validate = (route.settings && route.settings.validate) || {};
131
-
132
- // Which arguments the tool offers, expressed either way round. `keep` is the allowlist
133
- // form and is what the composition tools use: their exposed set is small, the route's is
134
- // large and grows, and with a deny list a field added to the submit route later would
135
- // join send_message's schema by default - failing open on the one tool that reaches
136
- // people outside the mailbox. `omit` stays for the tools that hide two or three knobs
137
- // out of a stable handful, where an allowlist would be a list of everything.
138
- if (options.keep && options.omit) {
139
- throw new Error(`MCP tool ${options.name}: declare either keep or omit, not both`);
140
- }
141
- const keep = options.keep ? new Set(options.keep) : null;
142
- const omit = new Set(options.omit || []);
123
+ validateMcpOptions(options);
143
124
 
125
+ const validate = route.validate;
144
126
  const params = convertSource(validate.params);
145
127
  const query = convertSource(validate.query);
146
128
  const payload = convertSource(validate.payload);
147
129
 
148
- // Tool argument names for route arguments that cannot keep their own. A route may take the
149
- // same name from two sources - the bulk move reads its source folder from the query and
150
- // its target from the payload, both as `path` - and one tool argument cannot be both.
151
- // `{ query: { path: 'source' } }` offers the query `path` as `source` and sends it back
152
- // under its own name. Every other option (keep, omit, force, bounds) names the tool
153
- // argument. Path parameters cannot be renamed: the dispatch fills the route template by
154
- // their names.
155
- const renames = new Map();
156
- for (const [sourceName, mapping] of Object.entries(options.rename || {})) {
157
- const source = { query, payload }[sourceName];
158
- if (!source) {
159
- throw new Error(`MCP tool ${options.name}: cannot rename arguments of ${sourceName}, only of query and payload`);
160
- }
161
- for (const [key, toolName] of Object.entries(mapping || {})) {
162
- if (!(key in source.properties)) {
163
- throw new Error(`MCP tool ${options.name}: renamed argument ${key} is not a ${sourceName} argument of ${route.method} ${route.path}`);
164
- }
165
- renames.set(`${sourceName}:${key}`, toolName);
130
+ const renames = resolveRenames(options, route, { query, payload });
131
+ const args = partitionArguments(options, route, { params, query, payload }, renames);
132
+ const forced = applyForce(options, route, args);
133
+ const bounds = applyBounds(options, route, args);
134
+
135
+ byName.set(options.name, buildToolEntry(route, options, args, forced, bounds));
136
+ }
137
+
138
+ const tools = [...byName.values()].map(entry => entry.definition).sort((a, b) => a.name.localeCompare(b.name, 'en'));
139
+
140
+ // The catalog reduced to what the admin pages count and group by, in tools/list order. Built
141
+ // here with the registry rather than on each read: the registry is immutable for the life of
142
+ // the worker and three admin pages plus the MCP door read this.
143
+ const grants = tools.map(tool => {
144
+ const entry = byName.get(tool.name);
145
+ return Object.assign({ name: tool.name, accountScoped: entry.accountScoped, surfaces: entry.surfaces }, entry.grant);
146
+ });
147
+
148
+ return { tools, byName, grants };
149
+ }
150
+
151
+ // The shape of a plugins.mcp block, checked before anything is derived from it
152
+ function validateMcpOptions(options) {
153
+ // Nothing else checks the shape of a plugins.mcp block, so a misspelled key would be a
154
+ // silent no-op - and every knob here is one that hides or pins something on the
155
+ // agent-facing schema, where a no-op means the opposite of what was declared
156
+ const unknownOptions = Object.keys(options).filter(key => !MCP_OPTION_KEYS.has(key));
157
+ if (unknownOptions.length) {
158
+ throw new Error(`MCP tool ${options.name}: unknown plugins.mcp option${unknownOptions.length > 1 ? 's' : ''}: ${unknownOptions.join(', ')}`);
159
+ }
160
+
161
+ // Which arguments the tool offers, expressed either way round. `keep` is the allowlist
162
+ // form and is what the composition tools use: their exposed set is small, the route's is
163
+ // large and grows, and with a deny list a field added to the submit route later would
164
+ // join send_message's schema by default - failing open on the one tool that reaches
165
+ // people outside the mailbox. `omit` stays for the tools that hide two or three knobs
166
+ // out of a stable handful, where an allowlist would be a list of everything.
167
+ if (options.keep && options.omit) {
168
+ throw new Error(`MCP tool ${options.name}: declare either keep or omit, not both`);
169
+ }
170
+ }
171
+
172
+ // Tool argument names for route arguments that cannot keep their own. A route may take the
173
+ // same name from two sources - the bulk move reads its source folder from the query and
174
+ // its target from the payload, both as `path` - and one tool argument cannot be both.
175
+ // `{ query: { path: 'source' } }` offers the query `path` as `source` and sends it back
176
+ // under its own name. Every other option (keep, omit, force, bounds) names the tool
177
+ // argument. Path parameters cannot be renamed: the dispatch fills the route template by
178
+ // their names.
179
+ //
180
+ // Returns `source:routeKey` -> tool argument name
181
+ function resolveRenames(options, route, renameable) {
182
+ const renames = new Map();
183
+ for (const [sourceName, mapping] of Object.entries(options.rename || {})) {
184
+ const source = renameable[sourceName];
185
+ if (!source) {
186
+ throw new Error(`MCP tool ${options.name}: cannot rename arguments of ${sourceName}, only of query and payload`);
187
+ }
188
+ for (const [key, toolName] of Object.entries(mapping || {})) {
189
+ if (!(key in source.properties)) {
190
+ throw new Error(`MCP tool ${options.name}: renamed argument ${key} is not a ${sourceName} argument of ${route.method} ${route.path}`);
166
191
  }
192
+ renames.set(`${sourceName}:${key}`, toolName);
167
193
  }
168
- // Tool argument name -> the name the route takes it under, for the renamed ones only
169
- const wireNames = new Map();
194
+ }
195
+ return renames;
196
+ }
170
197
 
171
- const properties = {};
172
- const required = [];
173
- const sources = new Map();
198
+ // Splits the route's request arguments into the ones the tool offers and the ones it hides
199
+ function partitionArguments(options, route, converted, renames) {
200
+ const keep = options.keep ? new Set(options.keep) : null;
201
+ const omit = new Set(options.omit || []);
202
+
203
+ const args = {
204
+ // Tool argument name -> the name the route takes it under, for the renamed ones only
205
+ wireNames: new Map(),
206
+ properties: {},
207
+ required: [],
208
+ sources: new Map(),
174
209
  // Every request argument of the route, hidden ones included. `sources` is what a caller
175
210
  // may address; this is what the route actually accepts, and it is what a forced value has
176
211
  // to be looked up in - a forced argument is almost always a hidden one.
177
- const argSources = new Map();
212
+ argSources: new Map(),
178
213
  // The arguments the tool does not offer, and the subset of those the route requires
179
- const hidden = new Set();
180
- const hiddenRequired = new Set();
181
-
182
- for (const [sourceName, source] of [
183
- ['params', params],
184
- ['query', query],
185
- ['payload', payload]
186
- ]) {
187
- for (const [routeKey, propertySchema] of Object.entries(source.properties)) {
188
- const key = renames.get(`${sourceName}:${routeKey}`) || routeKey;
189
- if (key !== routeKey) {
190
- wireNames.set(key, routeKey);
191
- }
192
- if (argSources.has(key)) {
193
- // A path parameter and a payload field sharing a name cannot both be a single
194
- // tool argument. None of the wrapped routes do this; refuse at build time so
195
- // the next one cannot silently shadow.
196
- throw new Error(`MCP tool ${options.name}: argument ${key} is defined by two request sources`);
197
- }
198
- argSources.set(key, sourceName);
199
- if (keep ? !keep.has(key) : omit.has(key)) {
200
- hidden.add(key);
201
- if (source.required.includes(routeKey)) {
202
- // A required argument the tool does not offer has to be supplied by
203
- // `force`, or every call dies on the same joi 400 with nothing the model
204
- // can do about it
205
- hiddenRequired.add(key);
206
- }
207
- continue;
208
- }
209
- sources.set(key, sourceName);
210
- properties[key] = propertySchema;
214
+ hidden: new Set(),
215
+ hiddenRequired: new Set()
216
+ };
217
+
218
+ for (const sourceName of ['params', 'query', 'payload']) {
219
+ const source = converted[sourceName];
220
+ for (const [routeKey, propertySchema] of Object.entries(source.properties)) {
221
+ const key = renames.get(`${sourceName}:${routeKey}`) || routeKey;
222
+ if (key !== routeKey) {
223
+ args.wireNames.set(key, routeKey);
224
+ }
225
+ if (args.argSources.has(key)) {
226
+ // A path parameter and a payload field sharing a name cannot both be a single
227
+ // tool argument. None of the wrapped routes do this; refuse at build time so
228
+ // the next one cannot silently shadow.
229
+ throw new Error(`MCP tool ${options.name}: argument ${key} is defined by two request sources`);
230
+ }
231
+ args.argSources.set(key, sourceName);
232
+ if (keep ? !keep.has(key) : omit.has(key)) {
233
+ args.hidden.add(key);
211
234
  if (source.required.includes(routeKey)) {
212
- required.push(key);
235
+ // A required argument the tool does not offer has to be supplied by
236
+ // `force`, or every call dies on the same joi 400 with nothing the model
237
+ // can do about it
238
+ args.hiddenRequired.add(key);
213
239
  }
240
+ continue;
214
241
  }
215
- }
216
-
217
- // Both lists are checked against what the route actually accepts. A name that matches no
218
- // argument is the failure mode this exists to catch: it reads as a decision that was made
219
- // and is not in force - a still-exposed knob under `omit`, a still-hidden one under
220
- // `keep`.
221
- for (const [label, declared] of [
222
- ['kept', options.keep || []],
223
- ['omitted', options.omit || []]
224
- ]) {
225
- for (const key of declared) {
226
- if (!argSources.has(key)) {
227
- throw new Error(`MCP tool ${options.name}: ${label} argument ${key} is not an argument of ${route.method} ${route.path}`);
228
- }
242
+ args.sources.set(key, sourceName);
243
+ args.properties[key] = propertySchema;
244
+ if (source.required.includes(routeKey)) {
245
+ args.required.push(key);
229
246
  }
230
247
  }
248
+ }
231
249
 
232
- // Values the MCP layer pins on every call, so a tool has one behavior rather than a matrix
233
- // of them. A forced value is sent with the injected request but is not a tool argument: the
234
- // point is that the calling model does not get to choose. The lookup is against every
235
- // argument of the route rather than against the tool's own, since a hidden key has left
236
- // the latter - which is also why `force` on a still-offered argument is refused. That pair
237
- // is the whole mechanism, and declaring one half of it would advertise an argument whose
238
- // value is then thrown away, which reads to the model as a control it does not have.
239
- const force = Object.entries(options.force || {});
240
- const forcedValues = {};
241
- // The routing table the injected request is built from: the tool's own arguments plus the
242
- // forced ones, which are not tool arguments and so are absent from `sources`. Only when
243
- // there is something to add - otherwise the tool routes through `sources` itself.
244
- const forcedSources = force.length ? new Map(sources) : sources;
245
-
246
- for (const [key, value] of force) {
247
- const sourceName = argSources.get(key);
248
- if (!sourceName) {
249
- throw new Error(`MCP tool ${options.name}: forced argument ${key} is not an argument of ${route.method} ${route.path}`);
250
- }
251
- if (!hidden.has(key)) {
252
- throw new Error(`MCP tool ${options.name}: forced argument ${key} must also be hidden, or the schema offers a choice that is not there`);
250
+ // Both lists are checked against what the route actually accepts. A name that matches no
251
+ // argument is the failure mode this exists to catch: it reads as a decision that was made
252
+ // and is not in force - a still-exposed knob under `omit`, a still-hidden one under
253
+ // `keep`.
254
+ for (const [label, declared] of [
255
+ ['kept', options.keep || []],
256
+ ['omitted', options.omit || []]
257
+ ]) {
258
+ for (const key of declared) {
259
+ if (!args.argSources.has(key)) {
260
+ throw new Error(`MCP tool ${options.name}: ${label} argument ${key} is not an argument of ${route.method} ${route.path}`);
253
261
  }
254
- forcedSources.set(key, sourceName);
255
- forcedValues[key] = value;
256
- hiddenRequired.delete(key);
257
262
  }
263
+ }
258
264
 
259
- if (hiddenRequired.size) {
260
- throw new Error(
261
- `MCP tool ${options.name}: required argument${hiddenRequired.size > 1 ? 's' : ''} ${[...hiddenRequired].join(', ')} ` +
262
- `${hiddenRequired.size > 1 ? 'are' : 'is'} hidden but not forced, so every call would fail validation`
263
- );
264
- }
265
+ return args;
266
+ }
265
267
 
266
- // Ceilings the MCP layer lowers on an argument the route keeps offering in full (see
267
- // MCP_MAX_PAGE_SIZE in lib/consts.js for the case this exists for). The advertised
268
- // maximum comes down AND the dispatch clamps, so the bound holds for a client that
269
- // ignores the schema too.
270
- //
271
- // Refused at build time unless it actually narrows an exposed numeric argument - a bound
272
- // that names a hidden key, or one the route has since raised past, is a bound that
273
- // silently stopped doing anything.
274
- const bounds = new Map();
275
- for (const [key, max] of Object.entries(options.bounds || {})) {
276
- if (!sources.has(key)) {
277
- throw new Error(`MCP tool ${options.name}: bounded argument ${key} is not an exposed argument of ${route.method} ${route.path}`);
278
- }
279
- if (typeof properties[key].maximum !== 'number' || properties[key].maximum <= max) {
280
- throw new Error(`MCP tool ${options.name}: bound on ${key} does not narrow the schema maximum (${properties[key].maximum})`);
281
- }
282
- properties[key] = Object.assign({}, properties[key], { maximum: max });
283
- bounds.set(key, max);
268
+ // Values the MCP layer pins on every call, so a tool has one behavior rather than a matrix
269
+ // of them. A forced value is sent with the injected request but is not a tool argument: the
270
+ // point is that the calling model does not get to choose. The lookup is against every
271
+ // argument of the route rather than against the tool's own, since a hidden key has left
272
+ // the latter - which is also why `force` on a still-offered argument is refused. That pair
273
+ // is the whole mechanism, and declaring one half of it would advertise an argument whose
274
+ // value is then thrown away, which reads to the model as a control it does not have.
275
+ function applyForce(options, route, args) {
276
+ const force = Object.entries(options.force || {});
277
+ const forcedValues = {};
278
+ // The routing table the injected request is built from: the tool's own arguments plus the
279
+ // forced ones, which are not tool arguments and so are absent from `sources`. Only when
280
+ // there is something to add - otherwise the tool routes through `sources` itself.
281
+ const forcedSources = force.length ? new Map(args.sources) : args.sources;
282
+
283
+ for (const [key, value] of force) {
284
+ const sourceName = args.argSources.get(key);
285
+ if (!sourceName) {
286
+ throw new Error(`MCP tool ${options.name}: forced argument ${key} is not an argument of ${route.method} ${route.path}`);
284
287
  }
288
+ if (!args.hidden.has(key)) {
289
+ throw new Error(`MCP tool ${options.name}: forced argument ${key} must also be hidden, or the schema offers a choice that is not there`);
290
+ }
291
+ forcedSources.set(key, sourceName);
292
+ forcedValues[key] = value;
293
+ args.hiddenRequired.delete(key);
294
+ }
285
295
 
286
- const grant = routeGrant(route);
296
+ const hiddenRequired = args.hiddenRequired;
297
+ if (hiddenRequired.size) {
298
+ throw new Error(
299
+ `MCP tool ${options.name}: required argument${hiddenRequired.size > 1 ? 's' : ''} ${[...hiddenRequired].join(', ')} ` +
300
+ `${hiddenRequired.size > 1 ? 'are' : 'is'} hidden but not forced, so every call would fail validation`
301
+ );
302
+ }
287
303
 
288
- const annotations = {
289
- title: options.title,
290
- readOnlyHint: grant.action === ACTION.READ,
291
- destructiveHint: grant.action === ACTION.DESTRUCTIVE,
292
- // Sending mail reaches arbitrary external recipients. A tool whose grant does not
293
- // imply that but whose purpose is reaching a host outside the instance - the
294
- // autodiscovery lookup, the connection tests - declares `openWorld` itself.
295
- openWorldHint: grant.action === ACTION.SEND || !!options.openWorld
296
- };
304
+ return { forcedSources, forcedValues };
305
+ }
297
306
 
298
- const inputSchema = {
299
- type: 'object',
300
- properties,
301
- additionalProperties: false
302
- };
303
- if (required.length) {
304
- inputSchema.required = required;
307
+ // Ceilings the MCP layer lowers on an argument the route keeps offering in full (see
308
+ // MCP_MAX_PAGE_SIZE in lib/consts.js for the case this exists for). The advertised
309
+ // maximum comes down AND the dispatch clamps, so the bound holds for a client that
310
+ // ignores the schema too.
311
+ //
312
+ // Refused at build time unless it actually narrows an exposed numeric argument - a bound
313
+ // that names a hidden key, or one the route has since raised past, is a bound that
314
+ // silently stopped doing anything.
315
+ function applyBounds(options, route, args) {
316
+ const bounds = new Map();
317
+ const properties = args.properties;
318
+ for (const [key, max] of Object.entries(options.bounds || {})) {
319
+ if (!args.sources.has(key)) {
320
+ throw new Error(`MCP tool ${options.name}: bounded argument ${key} is not an exposed argument of ${route.method} ${route.path}`);
305
321
  }
306
-
307
- byName.set(options.name, {
308
- definition: {
309
- name: options.name,
310
- title: options.title,
311
- description: options.description || (route.settings && route.settings.description),
312
- inputSchema,
313
- annotations
314
- },
315
- method: route.method,
316
- path: route.path,
317
- sources,
318
- forcedSources,
319
- forcedValues,
320
- bounds,
321
- wireNames,
322
- // The operation this tool resolves to, for consumers that answer per-credential
323
- // questions about the catalog: tools/list uses it to show a permission-narrowed
324
- // token only the tools its record can actually call
325
- grant,
326
- // The per-request scopes whose table covers that operation, in the order the scopes
327
- // are declared: the other half of what tools/list filters on, and what the admin
328
- // pages group and count by
329
- surfaces: [...PER_REQUEST_SURFACES].filter(scope => surfaceAdmits(scope, grant)),
330
- // Whether an account-bound credential can reach this tool at all, which is the same
331
- // question the api-token strategy answers when it checks the binding - so it is answered
332
- // from the table that strategy switches on (lib/api-routes/account-binding.js) rather
333
- // than from "the route takes an `account` argument". The two are different questions:
334
- // verify_oauth2_app's `account` is a mailbox address for a delegation check, and
335
- // create_account, create_account_setup_link and add_to_blocklist all take one in the
336
- // payload, yet a bound token is refused every one of them.
337
- accountScoped: routeAdmitsBoundToken(route.method, route.path),
338
- binary: !!options.binary,
339
- // A text result whose newest and most useful lines are LAST, so the cap keeps its end
340
- // rather than its beginning. Declared by the route, because which half of a response
341
- // matters is a property of that endpoint and not something this module can infer
342
- tail: !!options.tail,
343
- resourceUriTemplate: options.resourceUriTemplate
344
- });
322
+ if (typeof properties[key].maximum !== 'number' || properties[key].maximum <= max) {
323
+ throw new Error(`MCP tool ${options.name}: bound on ${key} does not narrow the schema maximum (${properties[key].maximum})`);
324
+ }
325
+ properties[key] = Object.assign({}, properties[key], { maximum: max });
326
+ bounds.set(key, max);
345
327
  }
328
+ return bounds;
329
+ }
346
330
 
347
- const tools = [...byName.values()].map(entry => entry.definition).sort((a, b) => a.name.localeCompare(b.name, 'en'));
331
+ function buildAnnotations(options, grant) {
332
+ return {
333
+ title: options.title,
334
+ readOnlyHint: grant.action === ACTION.READ,
335
+ destructiveHint: grant.action === ACTION.DESTRUCTIVE,
336
+ // Sending mail reaches arbitrary external recipients. A tool whose grant does not
337
+ // imply that but whose purpose is reaching a host outside the instance - the
338
+ // autodiscovery lookup, the connection tests - declares `openWorld` itself.
339
+ openWorldHint: grant.action === ACTION.SEND || !!options.openWorld
340
+ };
341
+ }
348
342
 
349
- // The catalog reduced to what the admin pages count and group by, in tools/list order. Built
350
- // here with the registry rather than on each read: the registry is immutable for the life of
351
- // the worker and three admin pages plus the MCP door read this.
352
- const grants = tools.map(tool => {
353
- const entry = byName.get(tool.name);
354
- return Object.assign({ name: tool.name, accountScoped: entry.accountScoped, surfaces: entry.surfaces }, entry.grant);
355
- });
343
+ // The registry entry of one tool: its wire definition plus the dispatch data the wire format
344
+ // does not carry
345
+ function buildToolEntry(route, options, args, forced, bounds) {
346
+ const grant = routeGrant(route);
356
347
 
357
- return { tools, byName, grants };
348
+ const inputSchema = {
349
+ type: 'object',
350
+ properties: args.properties,
351
+ additionalProperties: false
352
+ };
353
+ if (args.required.length) {
354
+ inputSchema.required = args.required;
355
+ }
356
+
357
+ return {
358
+ definition: {
359
+ name: options.name,
360
+ title: options.title,
361
+ description: options.description || route.description,
362
+ inputSchema,
363
+ annotations: buildAnnotations(options, grant)
364
+ },
365
+ method: route.method,
366
+ path: route.path,
367
+ sources: args.sources,
368
+ forcedSources: forced.forcedSources,
369
+ forcedValues: forced.forcedValues,
370
+ bounds,
371
+ wireNames: args.wireNames,
372
+ // The operation this tool resolves to, for consumers that answer per-credential
373
+ // questions about the catalog: tools/list uses it to show a permission-narrowed
374
+ // token only the tools its record can actually call
375
+ grant,
376
+ // The per-request scopes whose table covers that operation, in the order the scopes
377
+ // are declared: the other half of what tools/list filters on, and what the admin
378
+ // pages group and count by
379
+ surfaces: [...PER_REQUEST_SURFACES].filter(scope => surfaceAdmits(scope, grant)),
380
+ // Whether an account-bound credential can reach this tool at all, which is the same
381
+ // question the api-token strategy answers when it checks the binding - so it is answered
382
+ // from the table that strategy switches on (lib/api-routes/account-binding.js) rather
383
+ // than from "the route takes an `account` argument". The two are different questions:
384
+ // verify_oauth2_app's `account` is a mailbox address for a delegation check, and
385
+ // create_account, create_account_setup_link and add_to_blocklist all take one in the
386
+ // payload, yet a bound token is refused every one of them.
387
+ accountScoped: routeAdmitsBoundToken(route.method, route.path),
388
+ binary: !!options.binary,
389
+ // A text result whose newest and most useful lines are LAST, so the cap keeps its end
390
+ // rather than its beginning. Declared by the route, because which half of a response
391
+ // matters is a property of that endpoint and not something this module can infer
392
+ tail: !!options.tail,
393
+ resourceUriTemplate: options.resourceUriTemplate
394
+ };
358
395
  }
359
396
 
360
397
  /**
@@ -0,0 +1,76 @@
1
+ 'use strict';
2
+
3
+ // Values the main thread publishes as Prometheus gauges, computed from its state without touching
4
+ // the gauges themselves, so they can be tested without starting server.js.
5
+
6
+ const DAY_MS = 24 * 60 * 60 * 1000;
7
+
8
+ /**
9
+ * The license_days_remaining gauge value.
10
+ *
11
+ * @param {Object} licenseInfo - the main thread's license state (`active`, `details`)
12
+ * @param {number} now - current time in milliseconds
13
+ * @returns {number} days left on a time-limited license (never below 0), -1 for a lifetime or
14
+ * subscription license, 0 when no license is active
15
+ */
16
+ function licenseDaysRemaining(licenseInfo, now) {
17
+ if (!licenseInfo.active || !licenseInfo.details) {
18
+ // No active license
19
+ return 0;
20
+ }
21
+
22
+ if (licenseInfo.details.lt) {
23
+ // Lifetime license
24
+ return -1;
25
+ }
26
+
27
+ if (licenseInfo.details.expires) {
28
+ // Time-limited license
29
+ let expiresAt = new Date(licenseInfo.details.expires).getTime();
30
+ return Math.max(0, Math.ceil((expiresAt - now) / DAY_MS));
31
+ }
32
+
33
+ // Subscription license (no fixed expiry)
34
+ return -1;
35
+ }
36
+
37
+ /**
38
+ * Worker thread counts for the threads gauge, split by type and by whether the thread came
39
+ * online within the recent window, plus how many threads failed to answer a resource reading.
40
+ *
41
+ * @param {Array<Object>} threadsInfo - thread readings (`type`, `online`, `resourceUsageError`)
42
+ * @param {number} now - current time in milliseconds
43
+ * @param {number} recentWindow - how long after coming online a thread counts as recent, in ms
44
+ * @returns {{threadCounts: Map<string, number>, unresponsiveCount: number}} counts keyed
45
+ * `<type>_recent` or `<type>_total`, in first-seen order
46
+ */
47
+ function countThreads(threadsInfo, now, recentWindow) {
48
+ let threadCounts = new Map();
49
+ let unresponsiveCount = 0;
50
+
51
+ for (let workerThreadInfo of threadsInfo || []) {
52
+ let key = workerThreadInfo.type;
53
+ let metricKey = `${key}_total`;
54
+
55
+ // Check if thread is recent (started within the recent window)
56
+ let recent = now - workerThreadInfo.online < recentWindow;
57
+ if (recent) {
58
+ metricKey = `${key}_recent`;
59
+ }
60
+
61
+ if (!threadCounts.has(metricKey)) {
62
+ threadCounts.set(metricKey, 1);
63
+ } else {
64
+ threadCounts.set(metricKey, threadCounts.get(metricKey) + 1);
65
+ }
66
+
67
+ // Count unresponsive workers
68
+ if (workerThreadInfo.resourceUsageError && workerThreadInfo.resourceUsageError.unresponsive) {
69
+ unresponsiveCount++;
70
+ }
71
+ }
72
+
73
+ return { threadCounts, unresponsiveCount };
74
+ }
75
+
76
+ module.exports = { licenseDaysRemaining, countThreads };