ofw-mcp 2.29.0 → 2.30.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.
@@ -1,9 +1,9 @@
1
1
  import { z } from 'zod';
2
- import { syncAll, fetchAttachmentMeta, fetchAttachmentMetaForMessage, getDraftsCacheStatus, latestViewedAt, NEW_MESSAGES_CAP, refreshReadReporting } from '../sync.js';
2
+ import { FolderIdSchema, syncAll, fetchAttachmentMeta, fetchAttachmentMetaForMessage, getDraftsCacheStatus, latestViewedAt, NEW_MESSAGES_CAP, refreshReadReporting } from '../sync.js';
3
3
  import { buildFreshness } from './freshness.js';
4
4
  import { briefDate, briefLine, briefPage, briefResult, familyMeta } from './hints.js';
5
5
  import { checkDraftFreshness, draftRevision, fetchServerDraft, staleDraftPayload, } from './draft-freshness.js';
6
- import { FOLDER_TYPE, newDraftKey, persistFolderIds, probeIds, resolveDraftKey } from './lifecycle.js';
6
+ import { FOLDER_TYPE, newDraftKey, persistFolderIds, probeIds, readFolderIdMap, resolveDraftKey } from './lifecycle.js';
7
7
  import { CONFIRM_NOTE, confirmTokenParam, confirmWrite } from './_confirm.js';
8
8
  import { getFolderVerifiedAt } from '../sync.js';
9
9
  import { MAX_UPLOAD_BYTES } from './attachments.js';
@@ -16,9 +16,10 @@ import { resolveDownloadMime, resolveSaveDest } from './attachments.js';
16
16
  import { getAllowMarkRead, getConfirmMarkRead, getAttachmentsDir, getAutoRefreshStaleReads, getDefaultInlineAttachments, getFetchUnreadBodies, getSyncMaxRequests, getWriteMode, } from '../config.js';
17
17
  import { basename, resolve } from 'node:path';
18
18
  import { randomUUID } from 'node:crypto';
19
- import { ApiRecipientSchema, deriveRead, draftReplyTarget, hasRealView, jsonErrorResponse, jsonResponse, jsonText, mapRecipients, notedJsonResponse, postMessageAndRefetch, reportsThreaded, UnconfirmedWriteError, reportsUnthreaded, threadedReplyTo, verifyWriteLanded, withReadState } from './_shared.js';
19
+ import { ApiRecipientSchema, deriveRead, detailRecipients, mergeRecipients, withViewOrigin, draftReplyTarget, hasRealView, jsonErrorResponse, jsonResponse, jsonText, mapRecipients, notedJsonResponse, postMessageAndRefetch, reportsThreaded, UnconfirmedWriteError, reportsUnthreaded, threadedReplyTo, verifyWriteLanded, withReadState } from './_shared.js';
20
20
  import { parseLenient } from '@chrischall/mcp-utils';
21
21
  import { pageState } from './pagination.js';
22
+ import { fetchFolderPage, folderMessageBrief, getFolderSighting, LIVE_FOLDER_MAX_PAGE, recordFolderSightings, resolveMessageFolder, sightingGateRow } from './folder-messages.js';
22
23
  import { compactSentMessage, compactWrittenDraft, MESSAGE_VIEWS, senderOf, viewDrafts, viewMessages, viewOne } from './project.js';
23
24
  // The `view` note on the two write tools. Their echo is what the caller just
24
25
  // wrote, so compact replaces the body with its length + hash rather than
@@ -120,7 +121,7 @@ const DetailFilesSchema = z.looseObject({ files: z.array(z.number()).optional()
120
121
  // guessing, since a wrong count would manufacture a false out-of-sync verdict.
121
122
  const FolderCountsSchema = z.looseObject({
122
123
  systemFolders: z.array(z.looseObject({
123
- id: z.string(),
124
+ id: FolderIdSchema,
124
125
  folderType: z.string(),
125
126
  totalCount: z.number().optional(),
126
127
  messageCount: z.number().optional(),
@@ -304,11 +305,12 @@ async function unreadCandidates(cache) {
304
305
  */
305
306
  async function openUnreadBody(client, cache, cached) {
306
307
  const detail = parseLenient(MessageDetailSchema, await client.request('GET', `/pub/v3/messages/${cached.id}`), { label: 'ofw-mcp', context: 'GET /pub/v3/messages/{id} (sync, confirmed mark-read)' });
308
+ const checkedAt = new Date().toISOString();
307
309
  await cache.upsertMessage({
308
310
  ...cached,
309
- recipients: detail.recipients ? mapRecipients(detail.recipients) : cached.recipients,
311
+ recipients: mergeRecipients(cached.recipients, detailRecipients(detail.recipients, checkedAt)),
310
312
  body: detail.body ?? '',
311
- fetchedBodyAt: new Date().toISOString(),
313
+ fetchedBodyAt: checkedAt,
312
314
  });
313
315
  if (Array.isArray(detail.files) && detail.files.length > 0) {
314
316
  await fetchAttachmentMetaForMessage(client, cached.id, detail.files, cache);
@@ -318,6 +320,12 @@ async function openUnreadBody(client, cache, cached) {
318
320
  viewedAt: latestViewedAt(detail.recipients), reason: 'fetchUnreadBodies',
319
321
  };
320
322
  }
323
+ /**
324
+ * What to do about an id the cache has never seen. A sync covers inbox, sent
325
+ * and drafts; a message in any other folder is only ever seen by listing that
326
+ * folder, which records a sighting the mark-read gates can judge.
327
+ */
328
+ const UNSEEN_ID_HINT = 'Run ofw_sync_messages first: it walks list pages, not bodies, so it learns an inbox or sent message\'s subject, sender and read state without marking anything read. If the message is in another folder (Archived, Action Items, a folder you created), list that folder instead with ofw_list_messages(folderId: <its id or name>) — that reads its list page without opening anything. Then call ofw_get_message again.';
321
329
  /**
322
330
  * OFW_CONFIRM_MARK_READ: before `ofw_get_message` fetches a body that would
323
331
  * mark an unread inbox message read, show the user which message it is and
@@ -340,7 +348,7 @@ async function confirmMarkRead(ctx, cached, args, overriding) {
340
348
  error: 'MARK_READ_CONFIRMATION_UNAVAILABLE',
341
349
  messageId: Number(args.messageId),
342
350
  reason: 'This server asks before opening an unread message (OFW_CONFIRM_MARK_READ), but this id is not in the cache, so there is no subject or time to show — and fetching them is the request that would mark it read.',
343
- hint: 'Run ofw_sync_messages first: it walks list pages, not bodies, so it learns the subject and sent time without marking anything read. Then call ofw_get_message again.',
351
+ hint: UNSEEN_ID_HINT,
344
352
  });
345
353
  }
346
354
  // The preview never passes through jsonResponse, so normalize here: sentAt
@@ -410,6 +418,11 @@ function withholdBody(row) {
410
418
  * we cannot know without making the request that stamps it. Syncing first
411
419
  * (which reads list pages, not bodies) resolves it.
412
420
  */
421
+ /** The folder a gate row was SIGHTED in (sightingGateRow), or null for a cached row. */
422
+ function sightedIn(row) {
423
+ const where = row.listData?.sightedInFolder;
424
+ return typeof where === 'string' ? where : null;
425
+ }
413
426
  export function markReadVerdict(cached, requested) {
414
427
  const ceiling = getAllowMarkRead();
415
428
  if (ceiling && (requested ?? true))
@@ -426,10 +439,12 @@ export function markReadVerdict(cached, requested) {
426
439
  messageId: cached?.id ?? null,
427
440
  reason: cached === null
428
441
  ? 'This id is not in the cache, so whether reading it would mark it read is unknowable without making the request that would.'
429
- : 'This is an unread inbox message; fetching its body would mark it read on OurFamilyWizard.',
442
+ : sightedIn(cached) !== null
443
+ ? `This is an unread message in the "${sightedIn(cached)}" folder (per OurFamilyWizard's folder listing); fetching its body would mark it read on OurFamilyWizard.`
444
+ : 'This is an unread inbox message; fetching its body would mark it read on OurFamilyWizard.',
430
445
  note: `Refused because ${because}. Reading a message for the first time stamps a "First Viewed" timestamp that your co-parent can see and that forms part of the record — it cannot be undone. To read it anyway, call again with allowMarkRead:true${ceiling ? '' : ' (which this deployment does not permit — clear OFW_ALLOW_MARK_READ to re-enable)'}.`,
431
446
  ...(cached === null
432
- ? { hint: 'Run ofw_sync_messages first: it walks list pages, not bodies, so it can tell you what this id is without stamping anything.' }
447
+ ? { hint: UNSEEN_ID_HINT }
433
448
  : { subject: cached.subject, fromUser: cached.fromUser, sentAt: cached.sentAt }),
434
449
  });
435
450
  }
@@ -479,7 +494,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
479
494
  const allowDrafts = writeMode !== 'none';
480
495
  server.registerTool('ofw_list_message_folders', {
481
496
  _meta: familyMeta('lookup'),
482
- description: 'List OurFamilyWizard message folders (inbox, sent, etc.) and their unread counts. Fetched LIVE from OFW, so the counts are current. Returns folder IDs needed to call ofw_list_messages. Does NOT return message content.',
497
+ description: 'List OurFamilyWizard message folders — system folders (Inbox, Sent, Archived, Action Items, …) and folders the user created — with their unread counts. Fetched LIVE from OFW, so the counts are current. Pass a folder\'s id or name to ofw_list_messages(folderId) to list the messages in it. Does NOT return message content.',
483
498
  annotations: { readOnlyHint: true, openWorldHint: true },
484
499
  }, async () => {
485
500
  const data = await client.request('GET', '/pub/v1/messageFolders?includeFolderCounts=true');
@@ -492,12 +507,12 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
492
507
  when: { start: 'since', end: 'until' },
493
508
  aliases: ['messages', 'inbox', 'co-parent', 'ofw', 'ourfamilywizard', 'new messages'],
494
509
  }),
495
- description: 'List messages from the local OurFamilyWizard cache. Supports filtering by folder, date range, and a substring query on subject+body. Pagination is offset-based (1-based `page`) but if you know what you want (a date range, a topic), prefer the filters over walking pages — the cache may have 1000+ messages. Results are newest-first by default; `sort:"oldest"` starts at the old end of a range instead of paging to it. Returns an explicit `complete` boolean describing the RESULT SET: true means "this is every message on OurFamilyWizard matching these filters as of freshness.asOf" — check it before asserting a count. An empty result from a cache that is not verified-fresh is REFUSED (result:"UNVERIFIED_EMPTY") rather than reported as an absence; pass autoRefresh:true to sync and answer instead. On a server-configured no-read day (OFW_READ_DAYS / OFW_NO_READ_DAYS) only unread inbox messages are protected: each keeps its sender, subject and time but carries body:null, bodyWithheld:true, withheldReason:"UNREAD_ON_NO_READ_DAY", and q matches it by subject only (bodySearchSkipped counts those); readingBlocked, ahead of the messages, appears only when something was withheld and says when reading resumes. Sent messages and inbox messages already read are returned and searched in full, exactly as on a reading day.' + OVERRIDE_DESCRIPTION,
510
+ description: 'List messages from the local OurFamilyWizard cache. Supports filtering by folder, date range, and a substring query on subject+body. Pagination is offset-based (1-based `page`) but if you know what you want (a date range, a topic), prefer the filters over walking pages — the cache may have 1000+ messages. Results are newest-first by default; `sort:"oldest"` starts at the old end of a range instead of paging to it. Returns an explicit `complete` boolean describing the RESULT SET: true means "this is every message on OurFamilyWizard matching these filters as of freshness.asOf" — check it before asserting a count. An empty result from a cache that is not verified-fresh is REFUSED (result:"UNVERIFIED_EMPTY") rather than reported as an absence; pass autoRefresh:true to sync and answer instead. On a server-configured no-read day (OFW_READ_DAYS / OFW_NO_READ_DAYS) only unread inbox messages are protected: each keeps its sender, subject and time but carries body:null, bodyWithheld:true, withheldReason:"UNREAD_ON_NO_READ_DAY", and q matches it by subject only (bodySearchSkipped counts those); readingBlocked, ahead of the messages, appears only when something was withheld and says when reading resumes. Sent messages and inbox messages already read are returned and searched in full, exactly as on a reading day. folderId may also name any other OurFamilyWizard folder (a user-created folder, Archived, Action Items, …) by id or name: that folder is not cached, so it is read live, one list page per call (at most 50), returning `folder` and each message\'s subject, sender, sentAt, recipients and OurFamilyWizard\'s own `read` flag — never a body, so it marks nothing read. since/until/q are refused there (UNSUPPORTED_FILTER); a folder id or name OurFamilyWizard does not have is refused as INVALID_FOLDER with `availableFolders`. Read a body with ofw_get_message(messageId).' + OVERRIDE_DESCRIPTION,
496
511
  // Read-only even with autoRefresh: guardedCacheRead's sync never fetches
497
512
  // unread inbox bodies, so a list call cannot stamp "First Viewed".
498
513
  annotations: { readOnlyHint: true, openWorldHint: true },
499
514
  inputSchema: z.object({
500
- folderId: z.string().describe('Folder name: "inbox", "sent", or "both" (default "both")').optional(),
515
+ folderId: z.string().describe('"inbox", "sent", or "both" (default "both") read the local cache. Any other OurFamilyWizard folder — one the user created, or Archived, Action Items, etc. — by its id or name from ofw_list_message_folders: read LIVE, one page at a time, with subjects/senders/dates but no bodies, and without since/until/q.').optional(),
501
516
  page: z.number().int().min(1).describe('Page number (default 1)').optional(),
502
517
  size: z.number().int().min(1).describe('Messages per page (default 50)').optional(),
503
518
  since: z.string().describe('ISO date or datetime — only messages with sent_at >= since (inclusive). A value with an offset or Z is compared as that instant; a naive value is read as the account\'s local time (DISPLAY_TZ)').optional(),
@@ -509,12 +524,89 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
509
524
  view: LIST_MESSAGES_VIEW,
510
525
  }),
511
526
  }, async (args) => {
527
+ // The instant this call began: a recipient view time read from OFW's detail
528
+ // at or after it is labelled `detail-this-call`, anything older came from
529
+ // the cache (withViewOrigin, issue #448).
530
+ const callStartedAt = Date.now();
512
531
  const page = args.page ?? 1;
513
532
  const size = args.size ?? 50;
514
533
  const sort = args.sort ?? 'newest';
515
534
  const brief = args.view === 'brief';
516
535
  const view = resolveView(brief ? undefined : args.view, MESSAGE_VIEWS);
517
536
  const folderArg = args.folderId ?? 'both';
537
+ /**
538
+ * A folder the cache does not hold, read LIVE (issue #453). One list page,
539
+ * no detail GETs: the list carries no body, so this marks nothing read and
540
+ * a no-read day has nothing to withhold. Nothing is cached.
541
+ */
542
+ const listLiveFolder = async (liveFolder) => {
543
+ // The cache filters run in SQL over cached rows; OFW's list endpoint has
544
+ // no equivalent, so a filter here would be silently ignored — and an
545
+ // unfiltered page read as a filtered one is a wrong answer, not a slow one.
546
+ const unsupported = ['since', 'until', 'q'].filter((k) => args[k] !== undefined);
547
+ if (unsupported.length > 0) {
548
+ return jsonErrorResponse({
549
+ result: 'UNSUPPORTED_FILTER',
550
+ reason: `${unsupported.join(', ')} ${unsupported.length === 1 ? 'is' : 'are'} not supported for the "${liveFolder.name ?? liveFolder.id}" folder: it is read live from OurFamilyWizard, not from the cache, and OurFamilyWizard's folder listing cannot filter.`,
551
+ remedy: 'Re-call without since/until/q and page through the folder (newest first, or sort:"oldest").',
552
+ complete: false,
553
+ note: 'No messages were looked up.',
554
+ });
555
+ }
556
+ // 50 is the page size the sync walks with, so OFW is known to honour it.
557
+ // A larger request that OFW silently capped would come back short and
558
+ // read as the LAST page, hiding every page after it.
559
+ const liveSize = Math.min(size, LIVE_FOLDER_MAX_PAGE);
560
+ const result = await fetchFolderPage(client, liveFolder, {
561
+ page, size: liveSize, sort, checkedAt: new Date(callStartedAt).toISOString(), full: args.view === 'full',
562
+ });
563
+ // Remember what the listing showed (subject, sender, time, OFW's read
564
+ // flag) so ofw_get_message's mark-read gates can judge these ids — the
565
+ // sync never walks this folder, so nothing else ever would.
566
+ await recordFolderSightings(cacheProvider(), result.messages, new Date(callStartedAt).toISOString());
567
+ const freshness = await buildFreshness(cacheProvider(), { source: 'live', folders: [] });
568
+ if (brief) {
569
+ const lines = result.messages.map((m) => folderMessageBrief(m, displayTimeZone()));
570
+ // OFW rarely reports a folder total, so "-- N of M shown" is not
571
+ // always available; a slice still has to say it is one.
572
+ return briefResult(result.hasMore && result.total === null
573
+ ? [...lines, `-- ${result.returned} shown, more on page ${result.nextPage}`]
574
+ : briefPage(lines, result.hasMore ? { shown: result.returned, total: result.total } : undefined), 'Message subjects and sender names are written by your co-parent and other OurFamilyWizard users.');
575
+ }
576
+ const complete = page === 1 && !result.hasMore && result.skipped === 0;
577
+ const label = liveFolder.name ?? liveFolder.id;
578
+ // Same key order as the cached path: paging state, notes and freshness
579
+ // ahead of `messages`, so a reader that stops early still learns it holds
580
+ // a slice.
581
+ const payload = {
582
+ complete,
583
+ hasMore: result.hasMore,
584
+ nextPage: result.nextPage,
585
+ returned: result.returned,
586
+ ...(result.total !== null ? { total: result.total } : {}),
587
+ page,
588
+ size: liveSize,
589
+ sort,
590
+ folder: liveFolder,
591
+ };
592
+ if (result.skipped > 0)
593
+ payload.skipped = result.skipped;
594
+ if (!complete) {
595
+ payload.completeNote = [
596
+ page !== 1 ? `this is page ${page}; earlier pages are not in this response` : null,
597
+ result.hasMore ? `more messages remain in "${label}" — call again with page:${result.nextPage}` : null,
598
+ result.skipped > 0 ? `${result.skipped} list item${result.skipped === 1 ? '' : 's'} carried no message id and ${result.skipped === 1 ? 'was' : 'were'} left out` : null,
599
+ ].filter((r) => r !== null)
600
+ .join('; ')
601
+ .concat('. Do not state a total or an absence from this result without resolving that first.');
602
+ }
603
+ payload.note = result.returned === 0 && complete
604
+ ? `The "${label}" folder holds no messages on OurFamilyWizard (read live just now).`
605
+ : `Read live from the "${label}" folder on OurFamilyWizard: subjects, senders and dates only — this folder is not cached, so no body is included and since/until/q do not apply. Fetch one with ofw_get_message(messageId); like any first read, that marks an unread message read on OurFamilyWizard. \`read\` is OurFamilyWizard's own list flag (null when it sent none).`;
606
+ payload.freshness = freshness;
607
+ payload.messages = result.messages;
608
+ return jsonResponse(payload);
609
+ };
518
610
  let folder;
519
611
  if (folderArg === 'inbox')
520
612
  folder = 'inbox';
@@ -523,16 +615,40 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
523
615
  else if (folderArg === 'both')
524
616
  folder = undefined;
525
617
  else {
526
- // A rejected argument is an ERROR, not a result. Returning `messages: []`
527
- // here — even with a note attached — hands back the one shape this whole
528
- // mechanism exists to eliminate: an empty list that looks like an answer.
529
- return jsonErrorResponse({
530
- result: 'INVALID_FOLDER',
531
- reason: `folderId must be "inbox", "sent", or "both" (got ${JSON.stringify(folderArg)}). Numeric OFW folder IDs are not supported by the cache.`,
532
- remedy: 'Re-call with folderId omitted (searches both) or set to one of the three accepted names.',
533
- complete: false,
534
- note: 'No lookup was performed. This says NOTHING about what is in the cache — do not read it as "no messages".',
535
- });
618
+ // Any other value names an OurFamilyWizard folder by id or name (issue
619
+ // #453). Inbox and sent still answer from the cache; anything else is
620
+ // read live, one list page at a time.
621
+ const resolved = await resolveMessageFolder(client, folderArg);
622
+ if (resolved.kind === 'cached')
623
+ folder = resolved.folder;
624
+ else if (resolved.kind === 'drafts') {
625
+ return jsonErrorResponse({
626
+ result: 'INVALID_FOLDER',
627
+ reason: `${JSON.stringify(folderArg)} is the Drafts folder, which ofw_list_messages does not list.`,
628
+ remedy: 'Call ofw_list_drafts instead: it verifies drafts against OurFamilyWizard and carries each draft\'s revision and draftKey.',
629
+ complete: false,
630
+ note: 'No messages were looked up. This says NOTHING about what is in the folder.',
631
+ });
632
+ }
633
+ else if (resolved.kind === 'unknown') {
634
+ // A rejected argument is an ERROR, not a result. Returning
635
+ // `messages: []` here — even with a note attached — hands back the one
636
+ // shape this whole mechanism exists to eliminate: an empty list that
637
+ // looks like an answer.
638
+ return jsonErrorResponse({
639
+ result: 'INVALID_FOLDER',
640
+ reason: resolved.ambiguous
641
+ ? `${resolved.available.length} folders are named ${JSON.stringify(folderArg.trim())}; pass one of their ids instead.`
642
+ : `There is no OurFamilyWizard folder with the id or name ${JSON.stringify(folderArg)}.`,
643
+ remedy: 'Re-call with folderId "inbox", "sent", "both", or the id or name of one of availableFolders (ofw_list_message_folders lists them with counts).',
644
+ availableFolders: resolved.available,
645
+ complete: false,
646
+ note: 'No messages were looked up. This says NOTHING about what is in any folder — do not read it as "no messages".',
647
+ });
648
+ }
649
+ else {
650
+ return listLiveFolder(resolved.folder);
651
+ }
536
652
  }
537
653
  // sent_at is stored as OFW's naive local wall clock, so the bounds are
538
654
  // compared as strings. Convert an offset/Z bound to that same form first —
@@ -578,7 +694,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
578
694
  // can be stale (a message read after it was first scraped), so `read`
579
695
  // is derived from the record's own `viewedAt`/`fetchedBodyAt` and
580
696
  // `listData` is forced to agree — see withReadState.
581
- const messages = (await cache.listMessages({ ...filter, page, size, sort })).map((m) => withReadState(m));
697
+ const messages = (await cache.listMessages({ ...filter, page, size, sort })).map((m) => withViewOrigin(withReadState(m), callStartedAt));
582
698
  // Served from the local cache, so the result must say how old it is and
583
699
  // whether anything vouches for it — a caller cannot state current state
584
700
  // from this payload without either re-reading or surfacing the caveat.
@@ -684,7 +800,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
684
800
  });
685
801
  server.registerTool('ofw_get_message', {
686
802
  _meta: familyMeta('lookup'),
687
- description: 'Get a single OurFamilyWizard message OR draft by ID. Reads from local cache when available; otherwise fetches from OFW — and for an UNREAD INBOX message that fetch marks it read and stamps a "First Viewed" time the co-parent can see, which is part of the record and cannot be undone. Pass allowMarkRead:false to refuse such a fetch instead (cached bodies, sent messages and already-read messages are unaffected, because none of them stamp anything). For ids that match a draft (in the drafts cache), the response carries folder="drafts" and the body/subject/recipients reflect the drafts cache (which ofw_sync_messages keeps fresh) — drafts have no `fromUser`, and `sentAt`/`fetchedBodyAt` mirror the draft\'s `modifiedAt`. For inbox/sent messages, folder is "inbox" or "sent" as before. On a server-configured no-read day (OFW_READ_DAYS / OFW_NO_READ_DAYS) only an UNREAD inbox message is protected: its body is withheld (body:null, bodyWithheld:true, withheldReason:"UNREAD_ON_NO_READ_DAY", readingBlocked says when reading resumes) and OFW is never contacted for it; an id not in the cache is refused, since fetching it could mark it read. Sent messages and inbox messages already read are returned exactly as on a reading day. When the server runs with OFW_CONFIRM_MARK_READ=true, opening an unread inbox message first shows its subject, sender and sent time and asks the user to confirm marking it read: a confirmation prompt where the client supports one; otherwise the first call fetches NOTHING and returns that preview plus a confirmToken, and only a repeat call with that token opens the message (see MCP_CONFIRM_MODE). Show the user the preview and wait for their yes before repeating the call.' + OVERRIDE_DESCRIPTION,
803
+ description: 'Get a single OurFamilyWizard message OR draft by ID. Reads from local cache when available; otherwise fetches from OFW — and for an UNREAD INBOX message that fetch marks it read and stamps a "First Viewed" time the co-parent can see, which is part of the record and cannot be undone. Pass allowMarkRead:false to refuse such a fetch instead (cached bodies, sent messages and already-read messages are unaffected, because none of them stamp anything). For ids that match a draft (in the drafts cache), the response carries folder="drafts" and the body/subject/recipients reflect the drafts cache (which ofw_sync_messages keeps fresh) — drafts have no `fromUser`, and `sentAt`/`fetchedBodyAt` mirror the draft\'s `modifiedAt`. For inbox/sent messages, folder is "inbox" or "sent" as before. A message in any other folder (Archived, Action Items, a folder the user created) comes back with folder:"other", folderId and folderName, no `read` verdict (received vs sent cannot be told from the folder; see recipients[].viewedAt), and is not cached (each read is live); after ofw_list_messages(folderId) has listed that folder, the mark-read safeguards below judge such a message by that listing\'s read flag, so it can be opened, confirmed or withheld like an inbox message instead of being refused as unknown. On a server-configured no-read day (OFW_READ_DAYS / OFW_NO_READ_DAYS) only an UNREAD inbox message is protected: its body is withheld (body:null, bodyWithheld:true, withheldReason:"UNREAD_ON_NO_READ_DAY", readingBlocked says when reading resumes) and OFW is never contacted for it; an id not in the cache is refused, since fetching it could mark it read. Sent messages and inbox messages already read are returned exactly as on a reading day. When the server runs with OFW_CONFIRM_MARK_READ=true, opening an unread inbox message first shows its subject, sender and sent time and asks the user to confirm marking it read: a confirmation prompt where the client supports one; otherwise the first call fetches NOTHING and returns that preview plus a confirmToken, and only a repeat call with that token opens the message (see MCP_CONFIRM_MODE). Show the user the preview and wait for their yes before repeating the call. Each recipient\'s `viewedAt` carries its provenance: `viewedAtOrigin` is "detail-this-call" (read from OurFamilyWizard during this call), "detail-cached" (from an earlier read — see `viewedAtCheckedAt`), "list" (only the list was seen, so a null `viewedAt` means UNKNOWN, not unviewed) or "unrecorded". `viewedPlaceholder` is OurFamilyWizard\'s raw 1970 placeholder, kept as source data — it is never a view time.' + OVERRIDE_DESCRIPTION,
688
804
  annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true },
689
805
  inputSchema: z.object({
690
806
  messageId: z.string().describe('Message ID (also accepts draft IDs — drafts are routed via the drafts cache)'),
@@ -696,6 +812,10 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
696
812
  confirmToken: confirmTokenParam,
697
813
  }),
698
814
  }, async (args, ctx) => {
815
+ // The instant this call began: a recipient view time read from OFW's detail
816
+ // at or after it is labelled `detail-this-call`, anything older came from
817
+ // the cache (withViewOrigin, issue #448).
818
+ const callStartedAt = Date.now();
699
819
  const id = Number(args.messageId);
700
820
  const view = resolveView(args.view, MESSAGE_VIEWS);
701
821
  const cache = cacheProvider();
@@ -758,29 +878,48 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
758
878
  });
759
879
  }
760
880
  const cached = await cache.getMessage(id);
881
+ // A message in a folder the cache does not hold (Archived, a user folder)
882
+ // is known only from a live folder listing's sighting. It stands in for
883
+ // the cached row in every mark-read gate below — never stored, and never
884
+ // used as content: its body still comes from the live fetch.
885
+ const sighting = cached === null ? await getFolderSighting(cache, id) : null;
886
+ const gateRow = cached ?? (sighting === null ? null : sightingGateRow(id, sighting));
761
887
  // No-read day: protect an UNREAD INBOX message — answer from the cache
762
888
  // with its body withheld and never touch OFW, since its detail GET would
763
889
  // mark it read. An uncached id is refused: whether it is one is exactly
764
890
  // what cannot be known without that GET. Sent and already-read messages
765
891
  // fall through and are served as on any other day.
766
892
  const noReadDay = readingBlockedToday();
767
- const protectedToday = noReadDay !== null && (cached === null || isUnreadInbox(cached));
893
+ const protectedToday = noReadDay !== null && (gateRow === null || isUnreadInbox(gateRow));
768
894
  // The override is "used" only when it lifts the day for THIS message.
769
895
  const overriding = protectedToday && args.overrideNoReadDay === true;
770
896
  const blocked = protectedToday && !overriding ? noReadDay : null;
771
897
  if (blocked !== null) {
772
898
  if (cached === null) {
899
+ if (sighting !== null) {
900
+ // Seen in a folder listing as unread: say which message is being
901
+ // held back, as the cached path does, without a request.
902
+ return jsonErrorResponse({
903
+ ...blocked,
904
+ messageId: id,
905
+ subject: sighting.subject,
906
+ from: sighting.from,
907
+ sentAt: sighting.sentAt,
908
+ folderName: sighting.folderName,
909
+ hint: `OurFamilyWizard's listing of the "${sighting.folderName ?? sighting.folderId}" folder shows this message unread, and opening it would mark it read. Its body is withheld until reading resumes (or overrideNoReadDay:true, if the user explicitly asks).`,
910
+ });
911
+ }
773
912
  return jsonErrorResponse({
774
913
  ...blocked,
775
914
  messageId: id,
776
- hint: 'This id is not in the cache, so whether it is an unread inbox message cannot be told without the request that would mark it read. Run ofw_sync_messages (it never opens an unread inbox message) to see its subject, sender and date — and, if it is sent or already read, its body.',
915
+ hint: 'This id is not in the cache, so whether it is an unread inbox message cannot be told without the request that would mark it read. Run ofw_sync_messages (it never opens an unread inbox message) to see its subject, sender and date — and, if it is sent or already read, its body. If it is in another folder (Archived, Action Items, a folder you created), list that folder with ofw_list_messages(folderId: <its id or name>) instead.',
777
916
  });
778
917
  }
779
918
  const attachments = await cache.listAttachmentsForMessage(id);
780
919
  const freshness = await buildFreshness(cache, { source: 'cache', folders: [cached.folder] });
781
920
  return jsonResponse({
782
921
  readingBlocked: blocked,
783
- ...viewOne(view, withholdBody(withReadState(cached))),
922
+ ...viewOne(view, withholdBody(withViewOrigin(withReadState(cached), callStartedAt))),
784
923
  attachments,
785
924
  freshness,
786
925
  });
@@ -797,7 +936,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
797
936
  if (cached.folder === 'sent' && !hasRealView(cached.recipients)) {
798
937
  try {
799
938
  const detail = parseLenient(MessageDetailSchema, await client.request('GET', `/pub/v3/messages/${id}`), { label: 'ofw-mcp', context: 'GET /pub/v3/messages/{id} (view-status refresh)' });
800
- const recipients = mapRecipients(detail.recipients);
939
+ const recipients = mergeRecipients(cached.recipients, detailRecipients(detail.recipients, new Date().toISOString()));
801
940
  // Keep the raw listData read-flag in step with the refreshed
802
941
  // recipients so `showNeverViewed` can't contradict `viewedAt`.
803
942
  // (Spreading a null/absent listData is a no-op, so no guard needed.)
@@ -838,7 +977,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
838
977
  const freshness = await buildFreshness(cache, { source: 'cache', folders: [row.folder] });
839
978
  return jsonResponse({
840
979
  ...(overriding ? readOverrideFields('ofw_get_message', [row.id]) : {}),
841
- ...viewOne(view, withReadState(row)),
980
+ ...viewOne(view, withViewOrigin(withReadState(row), callStartedAt)),
842
981
  attachments,
843
982
  freshness,
844
983
  });
@@ -848,10 +987,10 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
848
987
  // unread INBOX message marks it read on OFW, stamping a "First Viewed"
849
988
  // time the co-parent can see. That is a court-visible, irreversible change
850
989
  // made as a side effect of an ordinary read, so it gets an explicit gate.
851
- const markReadCheck = markReadVerdict(cached, args.allowMarkRead);
990
+ const markReadCheck = markReadVerdict(gateRow, args.allowMarkRead);
852
991
  if (markReadCheck !== null)
853
992
  return markReadCheck;
854
- const confirmGate = await confirmMarkRead(ctx, cached, args, overriding);
993
+ const confirmGate = await confirmMarkRead(ctx, gateRow, args, overriding);
855
994
  if (confirmGate)
856
995
  return confirmGate;
857
996
  const detail = parseLenient(MessageDetailSchema, await client.request('GET', `/pub/v3/messages/${encodeURIComponent(args.messageId)}`), { label: 'ofw-mcp', context: 'GET /pub/v3/messages/{id} (ofw_get_message)' });
@@ -863,35 +1002,70 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
863
1002
  // a sent-scoped ofw_list_messages). When that mapping isn't known yet (no
864
1003
  // sync has run in this cache), fall back to 'inbox' as before.
865
1004
  let folder = cached?.folder ?? 'inbox';
1005
+ // Set when the detail places the message in a folder the cache does not
1006
+ // hold. Such a message is NOT cached: as 'inbox' it would appear in inbox
1007
+ // listings and counts it is not in, and no sync would ever correct it.
1008
+ let otherFolder = null;
866
1009
  if (!cached) {
867
- const sentFolderId = await cache.getMeta('sent_folder_id');
868
- if (sentFolderId !== null && detail.folder?.id != null && String(detail.folder.id) === sentFolderId) {
1010
+ const map = await readFolderIdMap(cache);
1011
+ const detailFolderId = detail.folder?.id == null ? null : String(detail.folder.id);
1012
+ if (map.sent !== null && detailFolderId === map.sent) {
869
1013
  folder = 'sent';
870
1014
  }
1015
+ else if (detailFolderId !== null && map.inbox !== null && map.sent !== null && detailFolderId !== map.inbox) {
1016
+ // Only when BOTH ids are known: with a partial map, "not the sent id"
1017
+ // cannot tell the inbox from anything else, so the old labelling stands.
1018
+ const detailName = detail.folder.name;
1019
+ otherFolder = {
1020
+ id: detailFolderId,
1021
+ name: typeof detailName === 'string' && detailName !== ''
1022
+ ? detailName
1023
+ : sighting !== null && sighting.folderId === detailFolderId ? sighting.folderName : null,
1024
+ };
1025
+ }
871
1026
  }
1027
+ const fetchedBodyAt = new Date().toISOString();
872
1028
  const row = {
873
1029
  id: detail.id,
874
1030
  folder,
875
1031
  subject: detail.subject,
876
1032
  fromUser: detail.from?.name ?? '',
877
1033
  sentAt: detail.date?.dateTime ?? nowNaiveWallClock(),
878
- recipients: mapRecipients(detail.recipients),
1034
+ recipients: mergeRecipients(cached?.recipients, detailRecipients(detail.recipients, fetchedBodyAt)),
879
1035
  body: detail.body ?? '',
880
- fetchedBodyAt: new Date().toISOString(),
1036
+ fetchedBodyAt,
881
1037
  replyToId: cached?.replyToId ?? null,
882
1038
  chainRootId: cached?.chainRootId ?? null,
883
1039
  listData: cached?.listData ?? detail,
884
1040
  };
885
- await cache.upsertMessage(row);
1041
+ if (otherFolder === null)
1042
+ await cache.upsertMessage(row);
886
1043
  if (Array.isArray(detail.files) && detail.files.length > 0) {
887
1044
  await fetchAttachmentMetaForMessage(client, detail.id, detail.files, cache);
888
1045
  }
889
1046
  const attachments = await cache.listAttachmentsForMessage(detail.id);
890
1047
  // Fetched live from OFW in this call — current by construction.
891
- const freshness = await buildFreshness(cache, { source: 'live', folders: [folder] });
1048
+ const freshness = await buildFreshness(cache, { source: 'live', folders: otherFolder === null ? [folder] : [] });
1049
+ // A copy: on the full rung viewOne hands back the row object itself.
1050
+ const shown = { ...viewOne(view, withViewOrigin(withReadState(row), callStartedAt)) };
1051
+ if (otherFolder !== null) {
1052
+ // The read derivation is folder-aware (received vs sent), and a message
1053
+ // in another folder could be either — so there is no verdict to give.
1054
+ // `read` is OMITTED rather than null, as on the drafts route (the other
1055
+ // folder this tool reports that is not inbox/sent): a caller already has
1056
+ // to handle its absence, and a new null type would be one more contract.
1057
+ // The recipients' viewedAt, read from the detail just now, is the evidence.
1058
+ delete shown.read;
1059
+ }
892
1060
  return jsonResponse({
893
1061
  ...(overriding ? readOverrideFields('ofw_get_message', [row.id]) : {}),
894
- ...viewOne(view, withReadState(row)),
1062
+ ...shown,
1063
+ ...(otherFolder === null ? {} : {
1064
+ folder: 'other',
1065
+ folderId: otherFolder.id,
1066
+ folderName: otherFolder.name,
1067
+ otherFolderNote: `This message is in the "${otherFolder.name ?? otherFolder.id}" folder, which this server does not sync, so it is not cached: every read of it is a live fetch. There is no \`read\` verdict, because whether it was received or sent cannot be told from the folder; recipients[].viewedAt is OurFamilyWizard's own record.`,
1068
+ }),
895
1069
  attachments,
896
1070
  freshness,
897
1071
  });
@@ -1174,7 +1348,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1174
1348
  // omitted or empty recipients array is "not echoed" (OFW routinely
1175
1349
  // echoes [] the way it does on drafts), and crying wolf on it would
1176
1350
  // retain the draft after every ordinary send.
1177
- const storedRecipients = mapRecipients(detail.recipients);
1351
+ const storedRecipients = mapRecipients(detail.recipients, { source: 'detail', checkedAt: new Date().toISOString() });
1178
1352
  if (Array.isArray(detail.recipients) && detail.recipients.length > 0) {
1179
1353
  const landed = new Set(storedRecipients.map((r) => r.userId));
1180
1354
  const missingRecipients = recipientIds.filter((rid) => !landed.has(rid));
package/dist/version.js CHANGED
@@ -4,4 +4,4 @@
4
4
  // package.json drift. Importing these instead of package.json keeps the whole
5
5
  // manifest — npm scripts included — out of dist/bundle.js.
6
6
  export const SERVER_NAME = 'ofw-mcp';
7
- export const VERSION = '2.29.0'; // x-release-please-version
7
+ export const VERSION = '2.30.0'; // x-release-please-version
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ofw-mcp",
3
- "version": "2.29.0",
3
+ "version": "2.30.0",
4
4
  "license": "MIT",
5
5
  "mcpName": "io.github.chrischall/ofw-mcp",
6
6
  "description": "OurFamilyWizard MCP server for Claude — developed and maintained by AI (Claude Code)",
package/server.json CHANGED
@@ -6,12 +6,12 @@
6
6
  "url": "https://github.com/chrischall/ofw-mcp",
7
7
  "source": "github"
8
8
  },
9
- "version": "2.29.0",
9
+ "version": "2.30.0",
10
10
  "packages": [
11
11
  {
12
12
  "registryType": "npm",
13
13
  "identifier": "ofw-mcp",
14
- "version": "2.29.0",
14
+ "version": "2.30.0",
15
15
  "transport": {
16
16
  "type": "stdio"
17
17
  },
@@ -92,8 +92,8 @@ Always pass `--config ~/.mcporter/mcporter.json` unless a local `config/mcporter
92
92
  |------|-------|
93
93
  | `ofw_sync_messages(folders?, deep?, fetchUnreadBodies?)` | Sync OFW → local cache. **Call first if the cache might be stale.** Never marks anything read unless `fetchUnreadBodies` is set. `newMessages` lists every message this call cached for the first time (newest first, with `read` and `bodyFetched`; `newMessagesTotal`/`newMessagesTruncated` when more than 50 arrived), so tell the user what arrived from that list. `unreadInbox` lists the new inbox messages that were unread when the sync began (`bodyFetched:false` = still unread). If the response leads with a `warning` and a `markedRead` list, the sync marked those messages read on OFW; tell the user, and stress any with `reason: "unexpected"`. With `fetchUnreadBodies` it may instead return a confirmation preview listing the unread messages it would open (server `OFW_CONFIRM_MARK_READ`): show the user that list and repeat with the `confirmToken` only on their yes. `unreadBodies.gate` names a server ceiling that refused. |
94
94
  | `ofw_list_message_folders` | List OFW folders with unread counts. Most reads use the cache; this is mainly for folder IDs and live unread counts. |
95
- | `ofw_list_messages(folderId?, since?, until?, q?, sort?, page?, size?, autoRefresh?, view?)` | Cache-backed list. Supports folder ("inbox"/"sent"/"both"), date range, and substring search. `sort:"oldest"` starts at the old end of a range instead of paging to it (default `"newest"`). Returns `complete` for the RESULT SET plus **`nextPage`** (null when done) — and the paging keys come FIRST in the JSON, before `messages`. `returned` carries the record count as a scalar, beside `total`. An **empty** result from a non-fresh cache is refused (`UNVERIFIED_EMPTY`) — pass `autoRefresh:true` to sync and answer instead. |
96
- | `ofw_get_message(messageId, allowMarkRead?, view?)` | Read a message OR draft body. Cache-first. Ids in the drafts cache return `folder: "drafts"`. ⚠️ Falls through to OFW for unread inbox messages, which marks them read AND stamps a "First Viewed" time the co-parent can see — irreversible. Pass `allowMarkRead:false` to refuse that fetch instead; cached, sent and already-read messages are unaffected. If the server runs with `OFW_CONFIRM_MARK_READ`, the first call returns a preview (subject, sender, sent time) instead of the body: show it to the user and repeat the call with its `confirmToken` only after they say yes. On a server-configured no-read day (`readingBlocked` / `READING_BLOCKED` in the response) the body is withheld (`bodyWithheld: true`) — report the sender, date and subject, say when `nextReadableDay` is, and do not try to work around it. |
95
+ | `ofw_list_messages(folderId?, since?, until?, q?, sort?, page?, size?, autoRefresh?, view?)` | Cache-backed list. Supports folder ("inbox"/"sent"/"both"), date range, and substring search. Any OTHER folder (user-created, Archived, Action Items) can be named by id or name from `ofw_list_message_folders`: it is read **live**, one page (≤50) per call, with subject/sender/date/`read` but **no bodies**, and `since`/`until`/`q` are refused there — fetch a body with `ofw_get_message`, which returns it as `folder: "other"` (with `folderName`, no `read` key — like a draft — and not cached). Listing the folder first is what lets `ofw_get_message` judge such a message under the mark-read safeguards (`OFW_ALLOW_MARK_READ=false`, `OFW_CONFIRM_MARK_READ`, no-read days) — an id it has never seen is refused there. `sort:"oldest"` starts at the old end of a range instead of paging to it (default `"newest"`). Returns `complete` for the RESULT SET plus **`nextPage`** (null when done) — and the paging keys come FIRST in the JSON, before `messages`. `returned` carries the record count as a scalar, beside `total`. An **empty** result from a non-fresh cache is refused (`UNVERIFIED_EMPTY`) — pass `autoRefresh:true` to sync and answer instead. |
96
+ | `ofw_get_message(messageId, allowMarkRead?, view?)` | Read a message OR draft body. Cache-first. Ids in the drafts cache return `folder: "drafts"`. ⚠️ Falls through to OFW for unread inbox messages, which marks them read AND stamps a "First Viewed" time the co-parent can see — irreversible. Pass `allowMarkRead:false` to refuse that fetch instead; cached, sent and already-read messages are unaffected. If the server runs with `OFW_CONFIRM_MARK_READ`, the first call returns a preview (subject, sender, sent time) instead of the body: show it to the user and repeat the call with its `confirmToken` only after they say yes. On a server-configured no-read day (`readingBlocked` / `READING_BLOCKED` in the response) the body is withheld (`bodyWithheld: true`) — report the sender, date and subject, say when `nextReadableDay` is, and do not try to work around it. When citing a "First Viewed" time, check the recipient's `viewedAtOrigin`: `detail-this-call` was read from OFW just now, `detail-cached` is carried forward from an earlier read (`viewedAtCheckedAt`), `list` means unknown. Never cite `viewedPlaceholder` (OFW's 1970 placeholder) as a view time. |
97
97
  | `ofw_send_message(draftId?, subject?, body?, bodyFormat?, recipientIds?, replyToId?, expectedRevision?, deleteDraftOnSuccess?, myFileIDs?, inlineAttachments?, blobKeys?, force?)` | Send a message — **the one irreversible operation**. Preferred path: pass `draftId` (+ `expectedRevision`) to send an existing draft **as it exists on the server** — the tool re-reads it from OFW first and refuses if it changed since you read it (or was already sent/deleted); `subject`/`body` become optional overrides. `recipientIds` is usually still required: OFW does not store recipients on drafts. After a **confirmed** send the draft is auto-deleted (`deleteDraftOnSuccess:false` to keep it); on any failure or ambiguity it is retained and the response says why (`draftRetained`). Response leads with `sentMessageId`, `draftKey`, `threaded`, `draftDeleted`. Compose from scratch by passing `subject`/`body`/`recipientIds` with no `draftId`. Sending a draft attaches its held files as they are (PRIVATE files attach fine); new files upload PRIVATE only after approval, and the response's `attachments.verified`/`missing` says what OFW actually attached. A replace without `recipientIds` keeps the draft's recipients. A draft with no `draftKey` says why (`draftKeyReason`). |
98
98
  | `ofw_get_unread_sent(page?, size?, autoRefresh?)` | Sent messages your co-parent hasn't read yet (from cache). Leads with `complete`/`hasMore`/`nextPage`, then `scanned`/`total`, then `unread`; an empty sent cache that is not fresh is refused rather than reported as "nothing sent". |
99
99
  | `ofw_list_drafts(page?, size?, verify?, autoRefresh?, view?)` | Leads with `complete`/`hasMore`/`nextPage`; `drafts` comes last. List saved drafts, **auto-verified**: when the cache is not verified-fresh a cheap drafts sync runs first (default `verify:true`), so one call answers server-confirmed. `verify:false` serves straight from cache. Each draft carries `serverConfirmed`, `revision` and `draftKey`. Returns `complete` — **check it before saying "you have N drafts"**. See [Freshness](#freshness). |
@@ -266,8 +266,8 @@ Editing a draft mints a **new OFW id every time** — `ofw_save_draft` replaces
266
266
  ## Workflows
267
267
 
268
268
  **Check inbox:**
269
- 1. `ofw_list_message_folders` → find inbox folder ID
270
- 2. `ofw_list_messages(folderId)` → list messages
269
+ 1. `ofw_list_messages(folderId: "inbox")` → list cached inbox messages
270
+ 2. For a folder the user filed messages into: `ofw_list_message_folders` → its id or name → `ofw_list_messages(folderId)` (read live)
271
271
  3. `ofw_get_message(messageId)` → read a specific message
272
272
 
273
273
  **Writing a message body:** OFW shows bodies as plain text — Markdown is never rendered. Write plain text: blank lines between paragraphs, `-` bullets, `1.` numbered lists, full `https://` links (those, emails and phone numbers become clickable). Any Markdown that slips in is converted before saving/sending (`bodyConversion` in the response says what changed; the send preview shows the converted text). `bodyFormat: "plain"` sends a body byte-for-byte.