fluxmail 0.23.0 → 0.25.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 (74) hide show
  1. package/dist/auth.d.ts +2 -0
  2. package/dist/auth.d.ts.map +1 -1
  3. package/dist/auth.js +1 -0
  4. package/dist/auth.js.map +1 -1
  5. package/dist/authorization.d.ts +42 -4
  6. package/dist/authorization.d.ts.map +1 -1
  7. package/dist/authorization.js +94 -6
  8. package/dist/authorization.js.map +1 -1
  9. package/dist/cli.d.ts +0 -4
  10. package/dist/cli.d.ts.map +1 -1
  11. package/dist/cli.js +94 -75
  12. package/dist/cli.js.map +1 -1
  13. package/dist/cliMail.d.ts.map +1 -1
  14. package/dist/cliMail.js +8 -2
  15. package/dist/cliMail.js.map +1 -1
  16. package/dist/cliMailBackend.d.ts.map +1 -1
  17. package/dist/cliMailBackend.js +56 -6
  18. package/dist/cliMailBackend.js.map +1 -1
  19. package/dist/context.d.ts +6 -0
  20. package/dist/context.d.ts.map +1 -1
  21. package/dist/context.js +29 -0
  22. package/dist/context.js.map +1 -1
  23. package/dist/http/admin.d.ts.map +1 -1
  24. package/dist/http/admin.js +28 -7
  25. package/dist/http/admin.js.map +1 -1
  26. package/dist/http/app.d.ts.map +1 -1
  27. package/dist/http/app.js +7 -2
  28. package/dist/http/app.js.map +1 -1
  29. package/dist/http/identity.d.ts +4 -0
  30. package/dist/http/identity.d.ts.map +1 -1
  31. package/dist/http/identity.js +110 -46
  32. package/dist/http/identity.js.map +1 -1
  33. package/dist/http/rest.d.ts.map +1 -1
  34. package/dist/http/rest.js +25 -18
  35. package/dist/http/rest.js.map +1 -1
  36. package/dist/lifecycle.d.ts +1 -1
  37. package/dist/lifecycle.d.ts.map +1 -1
  38. package/dist/lifecycle.js +2 -20
  39. package/dist/lifecycle.js.map +1 -1
  40. package/dist/mcp/buildServer.d.ts.map +1 -1
  41. package/dist/mcp/buildServer.js +219 -135
  42. package/dist/mcp/buildServer.js.map +1 -1
  43. package/dist/mcp/outputSchemas.d.ts +1 -37
  44. package/dist/mcp/outputSchemas.d.ts.map +1 -1
  45. package/dist/mcp/outputSchemas.js +1 -2
  46. package/dist/mcp/outputSchemas.js.map +1 -1
  47. package/dist/permissions.d.ts +2 -2
  48. package/dist/permissions.d.ts.map +1 -1
  49. package/dist/permissions.js +2 -7
  50. package/dist/permissions.js.map +1 -1
  51. package/dist/service/emailService.d.ts +21 -5
  52. package/dist/service/emailService.d.ts.map +1 -1
  53. package/dist/service/emailService.js +86 -42
  54. package/dist/service/emailService.js.map +1 -1
  55. package/dist/stdioShutdown.d.ts +27 -0
  56. package/dist/stdioShutdown.d.ts.map +1 -0
  57. package/dist/stdioShutdown.js +65 -0
  58. package/dist/stdioShutdown.js.map +1 -0
  59. package/dist/storage/apiKeys.d.ts +15 -3
  60. package/dist/storage/apiKeys.d.ts.map +1 -1
  61. package/dist/storage/apiKeys.js +34 -7
  62. package/dist/storage/apiKeys.js.map +1 -1
  63. package/dist/storage/db.d.ts +21 -2
  64. package/dist/storage/db.d.ts.map +1 -1
  65. package/dist/storage/db.js +15 -2
  66. package/dist/storage/db.js.map +1 -1
  67. package/dist/storage/imapState.d.ts.map +1 -1
  68. package/dist/storage/imapState.js +9 -0
  69. package/dist/storage/imapState.js.map +1 -1
  70. package/dist/storage/members.d.ts +8 -3
  71. package/dist/storage/members.d.ts.map +1 -1
  72. package/dist/storage/members.js +36 -7
  73. package/dist/storage/members.js.map +1 -1
  74. package/package.json +5 -5
@@ -4,12 +4,12 @@ import { randomUUID } from 'node:crypto';
4
4
  import { z } from 'zod';
5
5
  import { CLIENT_INFO_META_KEY, PROTOCOL_VERSION_META_KEY, McpServer, ResourceTemplate, } from '@modelcontextprotocol/server';
6
6
  import { isEmailError, mergeEmailQueries, parseEmailSearch, parseSingleAddress, } from '@fluxmail/core';
7
- import { ATTACHMENT_URI_TEMPLATE, attachmentUri, bodyPage, MAX_BODY_CHARS, MAX_THREAD_PAGE_TOKEN_CHARS, selectBody, sharedTool, threadPage, threadPageOffset, toModifyAction, } from '@fluxmail/core/mcp';
8
- import { batchFailureCause } from '../service/emailService.js';
7
+ import { ATTACHMENT_URI_TEMPLATE, attachmentUri, bodyPage, MAX_BODY_CHARS, MAX_THREAD_PAGE_TOKEN_CHARS, selectBody, sharedTool, sharedToolTarget, threadPage, threadPageOffset, toModifyAction, } from '@fluxmail/core/mcp';
8
+ import { batchFailureCause, modifyFailure, } from '../service/emailService.js';
9
9
  import { DEFAULT_MAX_ATTACHMENT_BYTES } from '../config.js';
10
10
  import { DEFAULT_PERMISSION_POLICY, MCP_CAPABILITIES, MCP_CAPABILITY_DESCRIPTIONS, enableCapabilitiesInstructions, hasCapability, normalizePermissionPolicy, } from '../permissions.js';
11
11
  import { captureOperation } from '../telemetry.js';
12
- import { logFailure } from '../logging.js';
12
+ import { logCodedFailure, logFailure } from '../logging.js';
13
13
  import { attachmentTooLarge, ClientInputError, isAttachmentSizeError, MissingCapabilityError, publicError, } from '../service/publicErrors.js';
14
14
  import { sendAtSchema } from '../sendAt.js';
15
15
  import { outputSchemas } from './outputSchemas.js';
@@ -32,6 +32,8 @@ function sizeLabel(bytes) {
32
32
  const TELEMETRY_ERROR = Symbol('telemetryError');
33
33
  /** The error behind a partial failure, read only for telemetry failure detail. */
34
34
  const TELEMETRY_FAILURE = Symbol('telemetryFailure');
35
+ /** The telemetry error code for a partial failure. Defaults to `account_failure`. */
36
+ const TELEMETRY_ERROR_CODE = Symbol('telemetryErrorCode');
35
37
  const EMPTY_INPUT_SCHEMA = {
36
38
  type: 'object',
37
39
  properties: {},
@@ -74,15 +76,76 @@ function toolJsonSchema(shape, pipeStrategy) {
74
76
  delete schema.$schema;
75
77
  return schema;
76
78
  }
79
+ const MAX_REPORTED_ARGUMENT_PROBLEMS = 10;
80
+ const MAX_REPORTED_ARGUMENT_CHARS = 100;
81
+ function argumentPath(path) {
82
+ const formatted = path
83
+ .map((step, index) => {
84
+ if (typeof step === 'number')
85
+ return `[${step}]`;
86
+ return index ? `.${String(step)}` : String(step);
87
+ })
88
+ .join('');
89
+ return formatted.slice(0, MAX_REPORTED_ARGUMENT_CHARS);
90
+ }
91
+ /** Tool arguments that do not match the input schema. The message names client-supplied keys. */
92
+ class InvalidToolArgumentsError extends ClientInputError {
93
+ constructor(tool, issues) {
94
+ // A misspelled argument often causes the other problems, so unknown arguments come first.
95
+ const problems = [
96
+ ...issues.flatMap((issue) => issue.code === 'unrecognized_keys'
97
+ ? issue.keys.map((key) => `unknown argument ${JSON.stringify(argumentPath([...issue.path, key]))}`)
98
+ : []),
99
+ ...issues
100
+ .filter((issue) => issue.code !== 'unrecognized_keys')
101
+ .map((issue) => `${issue.path.length ? argumentPath(issue.path) : 'arguments'}: ${issue.message}`),
102
+ ];
103
+ const shown = problems.slice(0, MAX_REPORTED_ARGUMENT_PROBLEMS);
104
+ const more = problems.length - shown.length;
105
+ super('invalid_request', `Invalid arguments for ${tool}: ${shown.join('; ')}${more ? `; and ${more} more` : ''}. ` +
106
+ "Check the tool's input schema.");
107
+ }
108
+ }
109
+ /**
110
+ * Raw tool arguments, parsed by the tool handler after its quota gate so that every
111
+ * schema problem becomes one invalid_request error.
112
+ */
113
+ class ToolInput {
114
+ tool;
115
+ raw;
116
+ schema;
117
+ constructor(tool, raw, schema) {
118
+ this.tool = tool;
119
+ this.raw = raw;
120
+ this.schema = schema;
121
+ }
122
+ async parse() {
123
+ const result = await this.schema.safeParseAsync(this.raw ?? {});
124
+ if (!result.success)
125
+ throw new InvalidToolArgumentsError(this.tool, result.error.issues);
126
+ return result.data;
127
+ }
128
+ }
129
+ /**
130
+ * Tools with arguments reject undeclared ones, as their schemas advertise, even when every
131
+ * argument is optional. Dropping one could widen a search. Tools without arguments advertise
132
+ * an open schema and ignore extras, which some clients send to tools that take no arguments.
133
+ */
134
+ function toolInputSchema(shape) {
135
+ return Object.keys(shape).length ? z.object(shape).strict() : z.object(shape);
136
+ }
77
137
  // Retain the existing validators, transforms and JSON Schemas at the SDK boundary.
78
- // The SDK consumes only Standard Schema here.
79
- function mcpSchema(shape, strict = false) {
80
- const schema = strict ? z.object(shape).strict() : z.object(shape);
138
+ // The SDK consumes only Standard Schema here. Tool handlers parse inputs themselves, so the
139
+ // input validator passes arguments through unchanged.
140
+ function mcpSchema(shape, io) {
141
+ const schema = io === 'output' ? z.object(shape) : undefined;
81
142
  return {
82
143
  '~standard': {
83
144
  version: 1,
84
145
  vendor: 'fluxmail',
85
146
  validate: async (value) => {
147
+ if (!schema)
148
+ return { value };
86
149
  const result = await schema.safeParseAsync(value);
87
150
  return result.success ? { value: result.data } : { issues: result.error.issues };
88
151
  },
@@ -117,21 +180,11 @@ const addressList = z
117
180
  .max(MAX_RECIPIENTS)
118
181
  .describe('Recipients, each "Name <a@x.com>" or "a@x.com"');
119
182
  const searchString = z.string().max(MAX_SEARCH_CHARS);
120
- const isoDate = z.string().regex(/^\d{4}-\d{2}-\d{2}$/);
121
183
  const queryShape = {
122
184
  folder: searchString
123
185
  .min(1)
124
186
  .optional()
125
187
  .describe("Folder role (inbox, sent, drafts, trash, spam, starred, archive, all) or a label/folder name. Use all or omit this field to search all mail except Spam and Trash. An IMAP server's \\All mailbox may use different rules."),
126
- text: searchString.optional().describe('Literal full-text search terms'),
127
- from: searchString.optional(),
128
- to: searchString.optional(),
129
- subject: searchString.optional(),
130
- read: z.boolean().optional(),
131
- starred: z.boolean().optional(),
132
- hasAttachment: z.boolean().optional(),
133
- after: isoDate.optional().describe('YYYY-MM-DD received date, inclusive in UTC'),
134
- before: isoDate.optional().describe('YYYY-MM-DD received date, exclusive in UTC'),
135
188
  rawProviderQuery: searchString
136
189
  .optional()
137
190
  .describe('Provider-native Gmail syntax or Outlook KQL for one compatible account'),
@@ -141,8 +194,13 @@ const queryShape = {
141
194
  includeSearchContext: z
142
195
  .boolean()
143
196
  .optional()
144
- .describe('Include a match-centered body excerpt; requires a portable text query'),
197
+ .describe('Include a match-centered body excerpt; requires search words in query'),
145
198
  };
199
+ const sendAtParam = sendAtSchema
200
+ .optional()
201
+ .describe('Schedule delivery instead of sending now: ISO 8601 with timezone offset or Z ' +
202
+ '(e.g. 2026-07-11T09:00:00-07:00), at most a year ahead. Fluxmail saves the message as a draft in the ' +
203
+ 'mailbox and sends that draft at the scheduled time. Returns a scheduleId for list/cancel.');
146
204
  const draftShape = {
147
205
  accountId: accountIdParam,
148
206
  from: z.string().email().optional().describe('Connected address or an available send-as address'),
@@ -170,7 +228,8 @@ const draftShape = {
170
228
  .optional()
171
229
  .describe('With replyToMessageId: set to false to leave the original message out of the reply. Defaults to true.'),
172
230
  attachments: z
173
- .array(z.object({
231
+ .array(z
232
+ .object({
174
233
  filename: z.string().min(1).max(MAX_ATTACHMENT_FIELD_CHARS),
175
234
  mimeType: z.string().min(1).max(MAX_ATTACHMENT_FIELD_CHARS),
176
235
  content: z.string().describe('base64'),
@@ -181,7 +240,8 @@ const draftShape = {
181
240
  .optional()
182
241
  .describe('Content-ID for an inline image, referenced from bodyHtml as cid:<contentId>'),
183
242
  disposition: z.enum(['inline', 'attachment']).optional().describe('Defaults to attachment'),
184
- }))
243
+ })
244
+ .strict())
185
245
  .optional(),
186
246
  };
187
247
  function parseAddresses(raw) {
@@ -289,7 +349,12 @@ function toolFeatureProperties(tool, args) {
289
349
  reply_all: input.replyAll === true,
290
350
  };
291
351
  case 'forward_email':
292
- return { include_attachments: input.includeAttachments !== false };
352
+ return { include_attachments: input.includeAttachments !== false, scheduled: input.sendAt !== undefined };
353
+ case 'list_emails':
354
+ case 'search_emails':
355
+ case 'list_emails_batch':
356
+ case 'search_emails_batch':
357
+ return { typed_query: typeof input.query === 'string' && input.query.trim() !== '' };
293
358
  case 'download_attachment':
294
359
  return {
295
360
  destination: input.inline === true ? 'inline' : typeof input.pages === 'string' ? 'pdf_pages' : 'resource',
@@ -304,14 +369,35 @@ function toolTelemetryProperties(tool, args, options) {
304
369
  ...options.clientProperties?.(args[1]),
305
370
  };
306
371
  }
307
- function handleResult(tool, fn, gate, options = {}) {
372
+ /** Handlers built by handleResult, which parse their tool input. Only these can be registered. */
373
+ const toolHandlers = new WeakSet();
374
+ /**
375
+ * Runs a request handler as a telemetry activity. A stdio session waits for every activity before it closes
376
+ * provider connections, so each tool and resource handler goes through this.
377
+ */
378
+ function withActivity(options, fn) {
308
379
  return async (...args) => {
309
- const finishActivity = options.telemetry?.beginActivity?.();
380
+ const finish = options.telemetry?.beginActivity?.();
381
+ try {
382
+ return await fn(...args);
383
+ }
384
+ finally {
385
+ finish?.();
386
+ }
387
+ };
388
+ }
389
+ function handleResult(tool, fn, gate, options = {}) {
390
+ const handler = withActivity(options, async (...received) => {
310
391
  const startedAt = performance.now();
392
+ const input = received[0] instanceof ToolInput ? received[0] : undefined;
393
+ // Until the input parses, telemetry reports no properties derived from it.
394
+ let args = (input ? [undefined, ...received.slice(1)] : received);
311
395
  try {
312
396
  // The gate throws when a lapsed license leaves the instance over quota,
313
397
  // and yields a renewal warning to attach while the license is in grace.
314
398
  const warning = gate?.();
399
+ if (input)
400
+ args = [await input.parse(), ...received.slice(1)];
315
401
  const result = await fn(...args);
316
402
  if (warning)
317
403
  result.content.push({ type: 'text', text: `Note: ${warning}` });
@@ -321,7 +407,10 @@ function handleResult(tool, fn, gate, options = {}) {
321
407
  operation: tool,
322
408
  outcome: telemetryFailed ? 'error' : 'success',
323
409
  ...(telemetryFailed
324
- ? { errorCode: 'account_failure', error: result[TELEMETRY_FAILURE] }
410
+ ? {
411
+ errorCode: result[TELEMETRY_ERROR_CODE] ?? 'account_failure',
412
+ error: result[TELEMETRY_FAILURE],
413
+ }
325
414
  : {}),
326
415
  durationMs: performance.now() - startedAt,
327
416
  transport: options.transport ?? 'unknown',
@@ -331,12 +420,18 @@ function handleResult(tool, fn, gate, options = {}) {
331
420
  }
332
421
  catch (err) {
333
422
  const requestId = randomUUID();
334
- logFailure(options.logger, 'mcp.operation_failed', err, {
423
+ const logContext = {
335
424
  productSurface: 'mcp',
336
425
  operation: tool,
337
426
  durationMs: performance.now() - startedAt,
338
427
  details: { request_id: requestId },
339
- });
428
+ };
429
+ // The client sees which arguments were wrong; the log omits their names.
430
+ if (err instanceof InvalidToolArgumentsError) {
431
+ logCodedFailure(options.logger, 'mcp.operation_failed', err.code, 'Tool arguments did not match the input schema', logContext);
432
+ }
433
+ else
434
+ logFailure(options.logger, 'mcp.operation_failed', err, logContext);
340
435
  captureOperation(options.telemetry, {
341
436
  productSurface: 'mcp',
342
437
  operation: tool,
@@ -349,10 +444,9 @@ function handleResult(tool, fn, gate, options = {}) {
349
444
  });
350
445
  return toolError(err, requestId);
351
446
  }
352
- finally {
353
- finishActivity?.();
354
- }
355
- };
447
+ });
448
+ toolHandlers.add(handler);
449
+ return handler;
356
450
  }
357
451
  function handle(tool, fn, gate, options = {}) {
358
452
  return handleResult(tool, async (...args) => ok(await fn(...args)), gate, options);
@@ -365,20 +459,26 @@ function pageOpts(args) {
365
459
  ...(args.includeSearchContext !== undefined ? { includeSearchContext: args.includeSearchContext } : {}),
366
460
  };
367
461
  }
462
+ function invalidSearch(diagnostics) {
463
+ return new ClientInputError('invalid_request', diagnostics.map((item) => item.message).join(' '), { diagnostics });
464
+ }
465
+ /**
466
+ * Parses a typed query and merges it with the structured filters sent beside it. Rejects either step's errors.
467
+ * A missing or blank query leaves the structured filters as they are.
468
+ */
469
+ function typedSearch(query, structured) {
470
+ if (query === undefined || query.trim() === '')
471
+ return { query: structured, warnings: [] };
472
+ const parsed = parseEmailSearch(query);
473
+ if (!parsed.valid)
474
+ throw invalidSearch(parsed.diagnostics);
475
+ const merged = mergeEmailQueries(parsed.query, structured);
476
+ if (!merged.success)
477
+ throw invalidSearch(merged.diagnostics);
478
+ return { query: merged.query, warnings: parsed.diagnostics };
479
+ }
368
480
  function emailQuery(args) {
369
- const keys = [
370
- 'folder',
371
- 'text',
372
- 'from',
373
- 'to',
374
- 'subject',
375
- 'read',
376
- 'starred',
377
- 'hasAttachment',
378
- 'after',
379
- 'before',
380
- 'rawProviderQuery',
381
- ];
481
+ const keys = ['folder', 'rawProviderQuery'];
382
482
  const q = {};
383
483
  for (const key of keys) {
384
484
  const value = args[key];
@@ -406,8 +506,6 @@ export const MODIFY_TOOLS = {
406
506
  /** Scopes for the tools only this product offers. Shared tools take theirs from the contract. */
407
507
  const PRODUCT_TOOL_SCOPES = {
408
508
  get_status: 'mail.read',
409
- list_scheduled_emails: 'mail.read',
410
- cancel_scheduled_email: 'mail.drafts',
411
509
  };
412
510
  function toolScopes(name) {
413
511
  const product = PRODUCT_TOOL_SCOPES[name];
@@ -416,14 +514,18 @@ function toolScopes(name) {
416
514
  const tool = sharedTool(name);
417
515
  return [...(tool.scope ? [tool.scope] : []), ...(tool.alsoRequires ? [tool.alsoRequires] : [])];
418
516
  }
517
+ const SCHEDULE_DELIVERY = 'Scheduled mail is delivered by fluxmail serve or fluxmail scheduled run using the same store. Stdio does not ' +
518
+ 'deliver schedules. Overdue mail may send when a worker starts.';
419
519
  /** Sentences this product appends to the contract's base descriptions. */
420
520
  const PRODUCT_DESCRIPTIONS = {
421
521
  send_feedback: 'Self-hosted sends the approved message, category, optional diagnostics and optional reply address, product type and package version to the Fluxmail Cloud feedback intake. The reply address is user-provided and unverified.',
422
522
  list_accounts: 'Each entry includes the account ID, provider, email address, status and capabilities.',
423
523
  list_emails: 'Use get_email for full bodies.',
424
524
  get_email: 'Use get_email_body to read the rest.',
425
- send_email: 'Confirm with the user when the intent is ambiguous. Add sendAt to any mode to schedule the message instead ' +
426
- 'of sending it now.',
525
+ forward_email: SCHEDULE_DELIVERY,
526
+ send_email: `Confirm with the user when the intent is ambiguous. ${SCHEDULE_DELIVERY}`,
527
+ list_scheduled_emails: 'Pending sends only fire while the Fluxmail server is running.',
528
+ cancel_scheduled_email: 'Get the scheduleId from send_email or forward_email with sendAt, or from list_scheduled_emails.',
427
529
  delete_emails: "Gmail accounts connected through Fluxmail's built-in Google app cannot delete permanently; move their " +
428
530
  'messages to the trash instead.',
429
531
  };
@@ -526,14 +628,19 @@ export function buildMcpServer(service, options = {}) {
526
628
  const supportsResourceLinks = (ctx) => (protocolVersionOf(ctx) ?? '2025-03-26') >= '2025-06-18';
527
629
  const listedTools = [];
528
630
  const registerTool = (name, config, callback) => {
529
- const outputSchema = outputSchemas[name];
631
+ // An alias returns the same result as the tool it names.
632
+ const outputSchema = outputSchemas[sharedToolTarget(name)];
530
633
  const inputShape = config.inputSchema;
531
634
  const inputSchema = inputShape && (name === 'send_feedback' ? inputShape : nullableOptionalInputs(inputShape));
635
+ if (!toolHandlers.has(callback))
636
+ throw new Error(`${name} must be registered with a tool handler`);
637
+ const run = callback;
638
+ const parser = toolInputSchema(inputSchema ?? {});
532
639
  const registered = server.registerTool(name, {
533
640
  ...config,
534
- inputSchema: mcpSchema(inputSchema ?? {}, name === 'send_feedback'),
535
- outputSchema: mcpSchema(outputSchema),
536
- }, callback);
641
+ inputSchema: mcpSchema(inputSchema ?? {}, 'input'),
642
+ outputSchema: mcpSchema(outputSchema, 'output'),
643
+ }, ((args, ctx) => run(new ToolInput(name, args, parser), ctx)));
537
644
  listedTools.push({
538
645
  name,
539
646
  title: config.title,
@@ -546,7 +653,7 @@ export function buildMcpServer(service, options = {}) {
546
653
  return registered;
547
654
  };
548
655
  /** Registers a shared tool with its contract metadata when the connection has the tool's scopes. */
549
- const registerSharedTool = (name, inputSchema, callback, productDescription = PRODUCT_DESCRIPTIONS[name]) => {
656
+ const registerSharedTool = (name, inputSchema, callback, productDescription = PRODUCT_DESCRIPTIONS[sharedToolTarget(name)]) => {
550
657
  if (!canAll(toolScopes(name)))
551
658
  return;
552
659
  const tool = sharedTool(name);
@@ -565,7 +672,7 @@ export function buildMcpServer(service, options = {}) {
565
672
  description: 'Account connection and scheduled-send status, including accounts that need re-authentication, and ' +
566
673
  'the time zone for the date above the quoted message in replies. Administrators also see plan details.',
567
674
  inputSchema: {},
568
- annotations: { readOnlyHint: true },
675
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false },
569
676
  }, allowed('get_status', async () => {
570
677
  const update = options.availableUpdate?.();
571
678
  return { ...(await service.status()), ...(update ? { update } : {}) };
@@ -573,58 +680,28 @@ export function buildMcpServer(service, options = {}) {
573
680
  registerSharedTool('list_folders', { accountId: accountIdParam }, gated('list_folders', async (args) => service.listFolders(args.accountId)));
574
681
  registerSharedTool('list_labels', { accountId: accountIdParam }, gated('list_labels', async (args) => service.listLabels(args.accountId)));
575
682
  registerSharedTool('list_send_as', { accountId: accountIdParam }, gated('list_send_as', async (args) => service.listSendAs(args.accountId)));
576
- registerSharedTool('list_emails', { accountId: accountIdParam, ...queryShape }, gated('list_emails', async (args) => service.listMessages(args.accountId, emailQuery(args), pageOpts(args))));
577
- const { text: _text, ...searchFilterShape } = queryShape;
578
- registerSharedTool('search_emails', {
579
- accountId: accountIdParam,
580
- query: searchString.min(1).describe('Typed portable search syntax'),
581
- ...searchFilterShape,
582
- }, gated('search_emails', async (args) => {
583
- const parsed = parseEmailSearch(args.query);
584
- if (!parsed.valid) {
585
- throw new ClientInputError('invalid_request', parsed.diagnostics.map((item) => item.message).join(' '), {
586
- diagnostics: parsed.diagnostics,
587
- });
588
- }
589
- const merged = mergeEmailQueries(parsed.query, emailQuery(args));
590
- if (!merged.success) {
591
- throw new ClientInputError('invalid_request', merged.diagnostics.map((item) => item.message).join(' '), {
592
- diagnostics: merged.diagnostics,
593
- });
594
- }
595
- const result = await service.listMessages(args.accountId, merged.query, pageOpts(args));
596
- return {
597
- ...result,
598
- ...([...parsed.diagnostics, ...(result.diagnostics ?? [])].length
599
- ? { diagnostics: [...parsed.diagnostics, ...(result.diagnostics ?? [])] }
600
- : {}),
601
- };
602
- }));
603
- const { pageToken: _batchPageToken, rawProviderQuery: _batchRawProviderQuery, ...batchSearchFilterShape } = searchFilterShape;
604
- registerSharedTool('search_emails_batch', {
605
- accounts: z
606
- .array(z.object(nullableOptionalInputs({ accountId: idParam, pageToken: z.string().min(1).optional() })).strict())
607
- .min(1)
608
- .max(20),
609
- query: searchString.min(1).describe('Typed portable search syntax'),
610
- ...batchSearchFilterShape,
611
- folder: z.enum(['inbox', 'sent', 'drafts', 'archive', 'spam', 'trash', 'all']).optional(),
612
- }, gatedResult('search_emails_batch', async (args) => {
613
- const parsed = parseEmailSearch(args.query);
614
- if (!parsed.valid) {
615
- throw new ClientInputError('invalid_request', parsed.diagnostics.map((item) => item.message).join(' '), {
616
- diagnostics: parsed.diagnostics,
617
- });
618
- }
619
- const merged = mergeEmailQueries(parsed.query, emailQuery(args));
620
- if (!merged.success) {
621
- throw new ClientInputError('invalid_request', merged.diagnostics.map((item) => item.message).join(' '), {
622
- diagnostics: merged.diagnostics,
623
- });
624
- }
683
+ const typedQuery = searchString
684
+ .optional()
685
+ .describe('Typed search. Plain words search the message text; quote a phrase or a value that has spaces. Filters: ' +
686
+ 'from:, to:, subject:, in:inbox|sent|drafts|archive|spam|trash|all, is:read, is:unread, is:starred, ' +
687
+ 'is:unstarred, has:attachment, -has:attachment, after:YYYY-MM-DD (inclusive) and before:YYYY-MM-DD ' +
688
+ '(exclusive), in UTC. Terms combine with AND; OR and parentheses are searched as text.');
689
+ const listEmails = async (args) => {
690
+ const { query, warnings } = typedSearch(args.query, emailQuery(args));
691
+ const result = await service.listMessages(args.accountId, query, pageOpts(args));
692
+ const diagnostics = [...warnings, ...(result.diagnostics ?? [])];
693
+ return { ...result, ...(diagnostics.length ? { diagnostics } : {}) };
694
+ };
695
+ const listEmailsShape = { accountId: accountIdParam, query: typedQuery, ...queryShape };
696
+ // search_emails is an alias of list_emails. It reports its own operation name so telemetry can tell them apart.
697
+ for (const name of ['list_emails', 'search_emails']) {
698
+ registerSharedTool(name, listEmailsShape, gated(name, listEmails));
699
+ }
700
+ const listEmailsBatch = async (args) => {
701
+ const { query, warnings } = typedSearch(args.query, emailQuery(args));
625
702
  const result = await service.searchMessagesBatch({
626
703
  accounts: args.accounts,
627
- query: merged.query,
704
+ query: query,
628
705
  ...(args.pageSize !== undefined ? { pageSize: args.pageSize } : {}),
629
706
  ...(args.includeSnippet !== undefined ? { includeSnippet: args.includeSnippet } : {}),
630
707
  ...(args.includeSearchContext !== undefined ? { includeSearchContext: args.includeSearchContext } : {}),
@@ -634,7 +711,7 @@ export function buildMcpServer(service, options = {}) {
634
711
  groups: result.groups.map((group) => {
635
712
  if (!group.page)
636
713
  return group;
637
- const diagnostics = [...parsed.diagnostics, ...(group.page.diagnostics ?? [])];
714
+ const diagnostics = [...warnings, ...(group.page.diagnostics ?? [])];
638
715
  return {
639
716
  ...group,
640
717
  page: { ...group.page, ...(diagnostics.length ? { diagnostics } : {}) },
@@ -648,7 +725,24 @@ export function buildMcpServer(service, options = {}) {
648
725
  response[TELEMETRY_FAILURE] = batchFailureCause(result.groups);
649
726
  }
650
727
  return response;
651
- }));
728
+ };
729
+ const { pageSize, includeSnippet, includeSearchContext } = queryShape;
730
+ const listEmailsBatchShape = {
731
+ accounts: z
732
+ .array(z.object(nullableOptionalInputs({ accountId: idParam, pageToken: z.string().min(1).optional() })).strict())
733
+ .min(1)
734
+ .max(20),
735
+ query: typedQuery,
736
+ // Custom folder names differ between accounts, so a batch takes only a folder role.
737
+ folder: z.enum(['inbox', 'sent', 'drafts', 'archive', 'spam', 'trash', 'all']).optional(),
738
+ pageSize,
739
+ includeSnippet,
740
+ includeSearchContext,
741
+ };
742
+ // search_emails_batch is an alias of list_emails_batch, with its own operation name in telemetry.
743
+ for (const name of ['list_emails_batch', 'search_emails_batch']) {
744
+ registerSharedTool(name, listEmailsBatchShape, gatedResult(name, listEmailsBatch));
745
+ }
652
746
  registerSharedTool('get_email', {
653
747
  accountId: accountIdParam,
654
748
  messageId: idParam,
@@ -661,12 +755,12 @@ export function buildMcpServer(service, options = {}) {
661
755
  registerSharedTool('get_email_body', {
662
756
  accountId: accountIdParam,
663
757
  messageId: idParam,
664
- format: z.enum(['text', 'html']),
758
+ bodyFormat: z.enum(['text', 'html']).describe('The body part to read'),
665
759
  offset: z.number().int().min(0).optional(),
666
760
  maxChars: z.number().int().min(1).max(MAX_BODY_CHARS).optional(),
667
761
  }, gated('get_email_body', async (args) => {
668
762
  const message = await service.getMessage(args.accountId, args.messageId);
669
- return bodyPage(message, args.format, args.offset, args.maxChars);
763
+ return bodyPage(message, args.bodyFormat, args.offset, args.maxChars);
670
764
  }));
671
765
  registerSharedTool('get_thread', {
672
766
  accountId: accountIdParam,
@@ -720,12 +814,7 @@ export function buildMcpServer(service, options = {}) {
720
814
  .describe('Reuse this key when retrying the same delivery'),
721
815
  draftId: idParam.optional().describe('Send this existing draft'),
722
816
  ...draftShape,
723
- sendAt: sendAtSchema
724
- .optional()
725
- .describe('Schedule delivery instead of sending now: ISO 8601 with timezone offset or Z ' +
726
- '(e.g. 2026-07-11T09:00:00-07:00). Fluxmail saves the message as a real draft in the mailbox ' +
727
- 'for delivery by fluxmail serve or fluxmail scheduled run using the same store. Stdio does not ' +
728
- 'deliver schedules. Overdue mail may send when a worker starts. Returns a scheduleId for list/cancel.'),
817
+ sendAt: sendAtParam,
729
818
  }, handleResult('send_email', async (args) => {
730
819
  requireToolScopes('send_email');
731
820
  if (args.replyToMessageId !== undefined)
@@ -735,24 +824,9 @@ export function buildMcpServer(service, options = {}) {
735
824
  ? service.scheduleDelivery(args.accountId, toSendRequest(sendArgs), sendAt, idempotencyKey)
736
825
  : service.deliver(args.accountId, toSendRequest(sendArgs), idempotencyKey)));
737
826
  }, () => service.enforceQuota(), toolOptions));
738
- if (canAll(toolScopes('list_scheduled_emails')))
739
- registerTool('list_scheduled_emails', {
740
- title: 'List scheduled emails',
741
- description: 'List scheduled sends: pending ones first (with sendAt), then past ones (sent, failed, canceled). ' +
742
- 'For failed entries, lastError says what went wrong. Pending sends only fire while the ' +
743
- 'Fluxmail server is running.',
744
- inputSchema: { accountId: accountIdParam },
745
- annotations: { readOnlyHint: true },
746
- }, gated('list_scheduled_emails', async (args) => service.listScheduled(args.accountId)));
747
- registerSharedTool('get_delivery_operation', { accountId: idParam, operationId: idParam }, allowed('get_delivery_operation', async (args) => service.getDelivery(args.accountId, args.operationId)));
748
- if (canAll(toolScopes('cancel_scheduled_email')))
749
- registerTool('cancel_scheduled_email', {
750
- title: 'Cancel scheduled email',
751
- description: 'Cancel a pending scheduled send by scheduleId (from send_email with sendAt, or list_scheduled_emails). ' +
752
- 'The draft stays in the Drafts folder, so the content is not lost.',
753
- inputSchema: { scheduleId: idParam },
754
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
755
- }, gated('cancel_scheduled_email', async (args) => service.cancelScheduled(args.scheduleId)));
827
+ registerSharedTool('list_scheduled_emails', { accountId: accountIdParam }, gated('list_scheduled_emails', async (args) => service.listScheduled(args.accountId)));
828
+ registerSharedTool('get_delivery_operation', { accountId: accountIdParam, operationId: idParam }, allowed('get_delivery_operation', async (args) => service.getDelivery(args.accountId, args.operationId)));
829
+ registerSharedTool('cancel_scheduled_email', { accountId: accountIdParam, scheduleId: idParam }, gated('cancel_scheduled_email', async (args) => service.cancelScheduled(args.scheduleId, args.accountId)));
756
830
  registerSharedTool('forward_email', {
757
831
  idempotencyKey: z
758
832
  .string()
@@ -763,23 +837,30 @@ export function buildMcpServer(service, options = {}) {
763
837
  from: z.string().email().optional().describe('Connected address or an available send-as address'),
764
838
  to: addressList.min(1),
765
839
  cc: addressList.optional(),
840
+ bcc: addressList.optional(),
766
841
  comment: z
767
842
  .string()
768
843
  .optional()
769
844
  .describe('Comment above the forwarded message. Keep prose paragraphs on one continuous line and separate paragraphs with blank lines.'),
770
845
  includeAttachments: z.boolean().optional().describe('Default true'),
846
+ sendAt: sendAtParam,
771
847
  }, handleResult('forward_email', async (args) => {
772
848
  requireToolScopes('forward_email');
773
849
  const to = parseAddresses(args.to) ?? [];
774
850
  const cc = parseAddresses(args.cc);
775
- return deliveryResult(await service.deliverForward(args.accountId, {
851
+ const bcc = parseAddresses(args.bcc);
852
+ const forward = {
776
853
  messageId: args.messageId,
777
854
  to,
778
855
  ...(cc?.length ? { cc } : {}),
856
+ ...(bcc?.length ? { bcc } : {}),
779
857
  ...(args.comment !== undefined ? { comment: args.comment } : {}),
780
858
  ...(args.includeAttachments !== undefined ? { includeAttachments: args.includeAttachments } : {}),
781
859
  ...(args.from !== undefined ? { from: args.from } : {}),
782
- }, args.idempotencyKey));
860
+ };
861
+ return deliveryResult(await (args.sendAt !== undefined
862
+ ? service.scheduleDelivery(args.accountId, { forward }, args.sendAt, args.idempotencyKey)
863
+ : service.deliverForward(args.accountId, forward, args.idempotencyKey)));
783
864
  }, () => service.enforceQuota(), toolOptions));
784
865
  const modifyEmails = async (action, args) => {
785
866
  requireToolScopes(MODIFY_TOOLS[action].name);
@@ -788,9 +869,12 @@ export function buildMcpServer(service, options = {}) {
788
869
  throw new ClientInputError('invalid_request', mapped.error);
789
870
  const result = await service.modify(args.accountId, args.messageIds, mapped.action);
790
871
  const response = ok({ ...result, action });
791
- if (result.failed.length || result.uncertainIds.length) {
872
+ const failure = modifyFailure(result);
873
+ if (failure) {
792
874
  response.isError = true;
793
875
  response[TELEMETRY_ERROR] = true;
876
+ response[TELEMETRY_ERROR_CODE] = failure.errorCode;
877
+ response[TELEMETRY_FAILURE] = failure.cause;
794
878
  }
795
879
  return response;
796
880
  };
@@ -840,12 +924,12 @@ export function buildMcpServer(service, options = {}) {
840
924
  };
841
925
  }), `The size limit is ${sizeLabel(maxAttachmentBytes)}.`);
842
926
  if (can('mail.read'))
843
- server.registerResource('attachment', new ResourceTemplate(ATTACHMENT_URI_TEMPLATE, { list: undefined }), { description: 'Read one attachment from an authorized mailbox.' }, async (uri, variables) => {
927
+ server.registerResource('attachment', new ResourceTemplate(ATTACHMENT_URI_TEMPLATE, { list: undefined }), { description: 'Read one attachment from an authorized mailbox.' }, withActivity(options, async (uri, variables) => {
844
928
  requireCapabilities(['mail.read']);
845
929
  service.enforceQuota();
846
930
  const { meta, content } = await downloadAttachment(decodeURIComponent(String(variables.accountId)), decodeURIComponent(String(variables.messageId)), decodeURIComponent(String(variables.attachmentId)));
847
931
  return { contents: [attachmentContents(uri.href, meta.mimeType || 'application/octet-stream', content)] };
848
- });
932
+ }));
849
933
  if (can('mail.read'))
850
934
  server.server.registerCapabilities({ resources: { listChanged: false } });
851
935
  if (listedTools.length) {