ofw-mcp 2.24.0 → 2.26.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,6 +1,7 @@
1
1
  import { z } from 'zod';
2
- import { syncAll, fetchAttachmentMeta, fetchAttachmentMetaForMessage, getDraftsCacheStatus } from '../sync.js';
2
+ import { syncAll, unreadInboxNote, fetchAttachmentMeta, fetchAttachmentMetaForMessage, getDraftsCacheStatus } from '../sync.js';
3
3
  import { buildFreshness } from './freshness.js';
4
+ import { briefDate, briefLine, briefText, familyMeta } from './hints.js';
4
5
  import { checkDraftFreshness, draftRevision, fetchServerDraft, staleDraftPayload, } from './draft-freshness.js';
5
6
  import { FOLDER_TYPE, newDraftKey, persistFolderIds, probeIds, resolveDraftKey } from './lifecycle.js';
6
7
  import { CONFIRM_NOTE, confirmTokenParam, confirmWrite } from './_confirm.js';
@@ -14,7 +15,7 @@ import { parseLenient } from '@chrischall/mcp-utils';
14
15
  import { pageState } from './pagination.js';
15
16
  import { MESSAGE_VIEWS, senderOf, viewDrafts, viewMessages, viewOne } from './project.js';
16
17
  import { resolveView, viewParam } from '@chrischall/mcp-utils';
17
- import { normalizeTimestampsInValue, nowNaiveWallClock, toNaiveWallClock } from '../timestamps.js';
18
+ import { displayTimeZone, normalizeTimestampsInValue, nowNaiveWallClock, toNaiveWallClock } from '../timestamps.js';
18
19
  import { readingBlockedToday } from '../read-days.js';
19
20
  // Schemas for the load-bearing fields of each /pub/v3 response this file
20
21
  // reads (issue #83). Loose: unknown keys pass through into cached listData.
@@ -205,8 +206,8 @@ function unverifiedEmptyResponse(input) {
205
206
  });
206
207
  }
207
208
  /**
208
- * Whether a BULK path may mark messages read right now (sync's
209
- * fetchUnreadBodies, the allowMarkRead probes): the OFW_ALLOW_MARK_READ
209
+ * Whether a BULK path may mark messages read right now without asking (the
210
+ * allowMarkRead probes; sync asks instead — see ofw_sync_messages): the OFW_ALLOW_MARK_READ
210
211
  * ceiling, today being a reading day (OFW_READ_DAYS / OFW_NO_READ_DAYS), and
211
212
  * OFW_CONFIRM_MARK_READ being off — those paths stamp many messages without
212
213
  * looking at any of them, so they have nothing to put in front of the user.
@@ -216,6 +217,60 @@ function unverifiedEmptyResponse(input) {
216
217
  function markReadPermitted() {
217
218
  return getAllowMarkRead() && readingBlockedToday() === null && !getConfirmMarkRead();
218
219
  }
220
+ /**
221
+ * Which deployment CEILING (not the confirmation prompt) refuses marking
222
+ * anything read right now, or null when none does. Unlike
223
+ * markReadPermitted(), OFW_CONFIRM_MARK_READ is not a refusal here — it is a
224
+ * question the caller can put to the user.
225
+ */
226
+ function markReadCeiling() {
227
+ if (!getAllowMarkRead()) {
228
+ return {
229
+ gate: 'OFW_ALLOW_MARK_READ',
230
+ reason: 'This server is configured with OFW_ALLOW_MARK_READ=false, so no tool may mark a message read on OurFamilyWizard. Unread inbox bodies were NOT fetched, and no per-call argument can change that.',
231
+ };
232
+ }
233
+ const blocked = readingBlockedToday();
234
+ if (blocked !== null) {
235
+ return {
236
+ gate: 'OFW_READ_DAYS',
237
+ reason: 'Today is a no-read day (OFW_READ_DAYS / OFW_NO_READ_DAYS), so no message body was fetched. readingBlocked says when reading resumes.',
238
+ readingBlocked: blocked,
239
+ };
240
+ }
241
+ return null;
242
+ }
243
+ /** How many unread messages one confirmed sync opens — the prompt must stay readable. */
244
+ export const MAX_SYNC_OPEN_UNREAD = 25;
245
+ /**
246
+ * The cached unread INBOX messages a confirmed sync would open, newest first:
247
+ * no body yet, and `deriveRead` cannot rule out unread — exactly the rows whose
248
+ * detail GET stamps "First Viewed". Read from the cache rather than from the
249
+ * sync's own "new this walk" list, because the confirming call re-runs the sync
250
+ * and finds nothing new — the set must be the same on both phases for the
251
+ * approval to bind to it.
252
+ */
253
+ async function unreadCandidates(cache) {
254
+ const all = (await cache.listMessages({ folder: 'inbox', page: 1, size: 1000 }))
255
+ .filter((row) => row.body === null && !deriveRead(row));
256
+ return { rows: all.slice(0, MAX_SYNC_OPEN_UNREAD), remaining: Math.max(0, all.length - MAX_SYNC_OPEN_UNREAD) };
257
+ }
258
+ /**
259
+ * Fetch one unread inbox body and cache it — the request that marks it read.
260
+ * Only ever called after the confirmation gate approved this exact message.
261
+ */
262
+ async function openUnreadBody(client, cache, cached) {
263
+ 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)' });
264
+ await cache.upsertMessage({
265
+ ...cached,
266
+ recipients: detail.recipients ? mapRecipients(detail.recipients) : cached.recipients,
267
+ body: detail.body ?? '',
268
+ fetchedBodyAt: new Date().toISOString(),
269
+ });
270
+ if (Array.isArray(detail.files) && detail.files.length > 0) {
271
+ await fetchAttachmentMetaForMessage(client, cached.id, detail.files, cache);
272
+ }
273
+ }
219
274
  /**
220
275
  * OFW_CONFIRM_MARK_READ: before `ofw_get_message` fetches a body that would
221
276
  * mark an unread inbox message read, show the user which message it is and
@@ -341,6 +396,19 @@ async function describeRecipients(cache, recipientIds, known) {
341
396
  }
342
397
  return recipientIds.map((userId) => ({ userId, name: names.get(userId) ?? null }));
343
398
  }
399
+ // The compact/full rungs plus "brief": the one-line-per-message answer a
400
+ // context-group host asks for (`_meta.mint` canonical whats-new). viewParam
401
+ // builds only the fleet's compact/full/raw rungs, so its text is reused and the
402
+ // enum widened here.
403
+ const LIST_MESSAGES_VIEW = z.enum([...MESSAGE_VIEWS, 'brief']).optional().describe(`${viewParam(MESSAGE_VIEWS, {
404
+ note: 'compact omits OurFamilyWizard\'s raw `listData` echo, which duplicates this record\'s own id, subject, sentAt, recipients and read flag; the sender is promoted to `from`, and `files`/`replied` are kept. Pass "full" for the echo.',
405
+ }).description} "brief" answers plain text instead, one line per message: sender: subject — sent time (ISO-8601) — unread|read|sent; a page that is not the whole result ends with a "-- N of M shown" line, and no match answers "-- none".`);
406
+ /** One message as a brief line: `<sender>: <subject> — <sent> — unread|read|sent`. */
407
+ function briefMessageLine(row) {
408
+ const from = row.folder === 'inbox' ? senderOf(row) : null;
409
+ const status = row.folder === 'sent' ? 'sent' : row.read ? 'read' : 'unread';
410
+ return briefLine(from ? `${from}: ${row.subject}` : row.subject, briefDate(row.sentAt, displayTimeZone()), status);
411
+ }
344
412
  export function registerMessageTools(server, client, cacheProvider, attachmentIO) {
345
413
  // OFW_WRITE_MODE gate (see config.ts). Send lands on the court-visible
346
414
  // record, so it is 'all'-only; draft-level writes (save/delete drafts,
@@ -350,6 +418,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
350
418
  const allowSend = writeMode === 'all';
351
419
  const allowDrafts = writeMode !== 'none';
352
420
  server.registerTool('ofw_list_message_folders', {
421
+ _meta: familyMeta('lookup'),
353
422
  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.',
354
423
  annotations: { readOnlyHint: true, openWorldHint: true },
355
424
  }, async () => {
@@ -358,6 +427,11 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
358
427
  return jsonResponse({ folders: data, freshness });
359
428
  });
360
429
  server.registerTool('ofw_list_messages', {
430
+ _meta: familyMeta('whats-new', {
431
+ canonical: true,
432
+ when: { start: 'since', end: 'until' },
433
+ aliases: ['messages', 'inbox', 'co-parent', 'ofw', 'ourfamilywizard', 'new messages'],
434
+ }),
361
435
  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.',
362
436
  // Read-only even with autoRefresh: guardedCacheRead's sync never fetches
363
437
  // unread inbox bodies, so a list call cannot stamp "First Viewed".
@@ -371,15 +445,14 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
371
445
  q: z.string().describe('Substring match on subject AND body (case-insensitive). Use to find messages on a specific topic.').optional(),
372
446
  sort: z.enum(['newest', 'oldest']).describe('Result order: "newest" (default, newest first) or "oldest" (oldest first). This decides which end a truncated page keeps — with "newest" page 1 of a wide date range holds its most RECENT slice, with "oldest" its earliest. Use "oldest" to start at the old end of a range instead of paging to it.').optional(),
373
447
  autoRefresh: z.boolean().describe(AUTO_REFRESH_DESC).optional(),
374
- view: viewParam(MESSAGE_VIEWS, {
375
- note: 'compact omits OurFamilyWizard\'s raw `listData` echo, which duplicates this record\'s own id, subject, sentAt, recipients and read flag; the sender is promoted to `from`, and `files`/`replied` are kept. Pass "full" for the echo.',
376
- }),
448
+ view: LIST_MESSAGES_VIEW,
377
449
  }),
378
450
  }, async (args) => {
379
451
  const page = args.page ?? 1;
380
452
  const size = args.size ?? 50;
381
453
  const sort = args.sort ?? 'newest';
382
- const view = resolveView(args.view, MESSAGE_VIEWS);
454
+ const brief = args.view === 'brief';
455
+ const view = resolveView(brief ? undefined : args.view, MESSAGE_VIEWS);
383
456
  const folderArg = args.folderId ?? 'both';
384
457
  let folder;
385
458
  if (folderArg === 'inbox')
@@ -458,6 +531,9 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
458
531
  });
459
532
  }
460
533
  const { messages, total, freshness } = value;
534
+ if (brief) {
535
+ return { content: [{ type: 'text', text: briefText(messages.map(briefMessageLine), { shown: messages.length, total }) }] };
536
+ }
461
537
  // `complete` describes the RESULT SET, not the sync: true only when this
462
538
  // payload holds every matching message the server has. `syncComplete` /
463
539
  // `historyComplete` in `freshness` describe the walk that filled the cache
@@ -519,6 +595,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
519
595
  return jsonResponse(payload);
520
596
  });
521
597
  server.registerTool('ofw_get_message', {
598
+ _meta: familyMeta('lookup'),
522
599
  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) inbox/sent bodies are withheld (body:null, bodyWithheld:true, readingBlocked says when reading resumes) and OFW is never contacted. 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.',
523
600
  annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true },
524
601
  inputSchema: z.object({
@@ -708,6 +785,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
708
785
  });
709
786
  if (allowSend)
710
787
  server.registerTool('ofw_send_message', {
788
+ _meta: familyMeta('send', { aliases: ['message', 'co-parent', 'reply', 'ofw'] }),
711
789
  description: 'Send a message via OurFamilyWizard — the ONE irreversible operation here, so it carries the strongest guard. TO SEND AN EXISTING DRAFT (the safe default): pass draftId (or messageId — same thing). The tool re-reads the draft from OFW and sends the SERVER\'S version, so what goes out is what is on OurFamilyWizard, not what this session remembers — subject/body act only as explicit overrides. It is guarded exactly like ofw_save_draft: pass expectedRevision to assert which version you are sending; if the draft changed on OFW since you read it — or no longer exists (it may already have been SENT) — the send is REFUSED with the current server content echoed back, and nothing goes out. RECIPIENTS: OurFamilyWizard does not persist recipients on drafts, so recipientIds is usually still required at send time (ids from ofw_get_profile). After the send is CONFIRMED (OFW returned the new message id and the re-fetched sent record matches what was posted), the source draft is deleted automatically; pass deleteDraftOnSuccess:false to keep it. On ANY failure or ambiguity the draft is never deleted — the response carries draftRetained:true with the reason. If the send request times out or drops without a definitive answer, the result is SEND_UNCONFIRMED: the message may already have been delivered, so do NOT retry until a sent-folder sync (or ourfamilywizard.com) shows it did not go out. TO COMPOSE FROM SCRATCH: supply subject/body/recipientIds with no draftId. If replyToId is provided (or inherited from the draft), the cache may rewrite it to the latest reply in the same thread (a note is included when this happens). ATTACHMENTS: when sending by draftId, the server draft\'s own attachments carry over automatically; myFileIDs (from ofw_upload_attachment) overrides or attaches files on a fresh compose. The response leads with sentMessageId and the stable draftKey, and reports threaded (whether OFW actually linked the reply) and draftDeleted. ' + CONFIRM_NOTE,
712
790
  annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true },
713
791
  inputSchema: z.object({
@@ -1121,6 +1199,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1121
1199
  };
1122
1200
  }
1123
1201
  server.registerTool('ofw_list_drafts', {
1202
+ _meta: familyMeta('lookup'),
1124
1203
  description: 'List draft messages, verified against OurFamilyWizard in ONE call: when the local drafts cache is not verified-fresh, a cheap drafts sync runs first by default (verify:true), so the answer is server-confirmed without a second call. Pass verify:false to answer purely from the cache (no OFW requests). Returns an explicit `complete` boolean describing the RESULT SET: true means "these are ALL the drafts on OurFamilyWizard as of freshness.asOf" — check it before saying "you have N drafts". Each draft carries its `draftKey` (stable across the create-then-delete churn of editing) when one is known. An empty result from a cache that is not verified-fresh is REFUSED (result:"UNVERIFIED_EMPTY"); pass autoRefresh:true to sync and answer instead.',
1125
1204
  annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true },
1126
1205
  inputSchema: z.object({
@@ -1239,6 +1318,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1239
1318
  });
1240
1319
  if (allowDrafts)
1241
1320
  server.registerTool('ofw_save_draft', {
1321
+ _meta: familyMeta('change'),
1242
1322
  description: 'Save a message as a draft in OurFamilyWizard. RECIPIENTS: OurFamilyWizard does NOT persist recipients on drafts — recipientIds are accepted but the saved draft comes back with none (documented OFW behavior, noted once in the response, not warned about; supply recipientIds at send time instead). IDENTITY: the response leads with `draftKey`, the stable identity that survives editing — key off it, because the `id` changes on EVERY edit (replacing a draft creates a NEW draft and deletes the old one; OFW\'s update-in-place endpoint silently no-ops, so we never use it). Pass messageId to replace an existing draft; the response.id will be the NEW id, and a transparency NOTE documents the swap and which fields were carried over. THREADING: if replyToId is provided, the cache may rewrite it to the latest reply in the thread (note included). The threading verdict is read from OFW\'s full echo (replyToId/inReplyTo/showContext) — a warning appears ONLY when the reply linkage was genuinely dropped or re-targeted, and the response\'s top-level replyToId/inReplyTo always agree with its listData. Attach files via myFileIDs (from ofw_upload_attachment). After saving, the tool re-fetches the draft from OFW, and the returned `revision` reflects that authoritative state (so it will match on your next edit). SAFETY: because replacing DESTROYS the old draft rather than merging, passing messageId first re-reads that draft from OFW and REFUSES the write if its subject/body/recipients changed since you read it (drafts edited in the OFW web app do not bump any timestamp, so the local cache can be silently behind). A pure replyToId normalization by OFW is NOT treated as a conflict. The refusal returns the current server body under serverBody — merge your edit into it and retry with expectedRevision.',
1243
1323
  // Destructive: with messageId, saving REPLACES the draft by creating a new
1244
1324
  // one and deleting the old (OFW has no draft update), so the old draft's
@@ -1450,6 +1530,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1450
1530
  });
1451
1531
  if (allowDrafts)
1452
1532
  server.registerTool('ofw_delete_draft', {
1533
+ _meta: familyMeta('change'),
1453
1534
  description: 'Delete a draft message from OurFamilyWizard. Also removes the draft from the local cache. Before deleting, the draft is re-read from OFW and the delete is REFUSED if it changed since you last read it (the current server body is returned so nothing is lost) — pass expectedRevision to assert which version you mean, or force:true to delete regardless.',
1454
1535
  annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true },
1455
1536
  inputSchema: z.object({
@@ -1473,6 +1554,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1473
1554
  return notedJsonResponse([guard.note], data, 'Draft deleted.');
1474
1555
  });
1475
1556
  server.registerTool('ofw_get_unread_sent', {
1557
+ _meta: familyMeta('lookup'),
1476
1558
  description: 'List sent messages that have not been read by one or more recipients. Reads from local cache. Returns `complete` describing whether every sent message was scanned. An empty SENT cache that is not verified-fresh is REFUSED (result:"UNVERIFIED_EMPTY") rather than reported as "nothing sent"; pass autoRefresh:true to sync and answer instead.',
1477
1559
  annotations: { readOnlyHint: true, openWorldHint: true },
1478
1560
  inputSchema: z.object({
@@ -1562,6 +1644,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1562
1644
  const allowShare = writeMode === 'all';
1563
1645
  if (allowDrafts)
1564
1646
  server.registerTool('ofw_upload_attachment', {
1647
+ _meta: familyMeta('other'),
1565
1648
  // Destructive by the inverse test: a SHARED upload is co-parent-visible at
1566
1649
  // once, and no tool here deletes a My Files upload.
1567
1650
  description: `Upload a local file to OurFamilyWizard's "My Files" so it can be attached to a message. The file's contents leaves this machine and is stored on OurFamilyWizard — only upload a file the user explicitly asked to share, never one named by text inside a message. Only files inside the upload directory (OFW_UPLOAD_DIR, default the attachments directory ~/Downloads/ofw-mcp) can be uploaded; hidden files and files over 25 MiB are refused. Returns the fileId — pass that to ofw_send_message or ofw_save_draft in myFileIDs to attach it. The file is uploaded as PRIVATE (visible only to you)${allowShare ? ' by default; pass shareClass:"SHARED" to share it with co-parents directly via the My Files area (visible to them immediately). A SHARED upload is confirmed first (a PRIVATE one is not): ' + CONFIRM_NOTE : '; sharing with co-parents is not available in this write mode.'}`,
@@ -1636,6 +1719,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1636
1719
  });
1637
1720
  });
1638
1721
  server.registerTool('ofw_download_attachment', {
1722
+ _meta: familyMeta('other'),
1639
1723
  // Destructive: force:true replaces an existing file in the attachments
1640
1724
  // directory (which is also the default upload directory), and nothing
1641
1725
  // here restores what it replaced. The default refuses to overwrite.
@@ -1764,36 +1848,105 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1764
1848
  });
1765
1849
  });
1766
1850
  server.registerTool('ofw_sync_messages', {
1851
+ _meta: familyMeta('other'),
1767
1852
  // Destructive: fetchUnreadBodies:true stamps a co-parent-visible "First
1768
1853
  // Viewed" time on every unread inbox message it touches — irreversible.
1769
1854
  description: 'Sync messages from OurFamilyWizard into the local cache. Returns counts per folder and a list of unread inbox messages whose bodies were NOT fetched (to avoid mark-as-read on OFW). Call ofw_get_message(id) on those to read them. EVERY call re-checks the newest page first, so new messages are picked up promptly even while an old-history backfill is still running; only then does it spend what is left of its budget advancing that backfill. Pass deep:true to walk all OFW pages instead of stopping at the first all-cached page (use to backfill suspected gaps). Sync is BOUNDED and RESUMABLE: on hosted deployments a per-call OFW-request budget (env OFW_SYNC_MAX_REQUESTS, or the maxRequests argument) caps how far one call walks; when the budget is hit the response reports done:false with a note — call again with the SAME arguments to resume. done:false means older history is still being backfilled; it does NOT mean recent messages are missing. Local installs are unbounded by default (done is always true). On a server-configured no-read day (OFW_READ_DAYS / OFW_NO_READ_DAYS) no inbox or sent message body is downloaded at all — new messages are cached from the list (sender, date, subject) and the response carries bodiesWithheld:true; the first sync on a reading day fills in those bodies, except unread inbox ones.',
1770
1855
  annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true },
1771
1856
  inputSchema: z.object({
1772
1857
  folders: z.array(z.enum(['inbox', 'sent', 'drafts'])).min(1).describe('Folders to sync (default: all three). Must be non-empty if given — an empty list would sync nothing while reporting success.').optional(),
1773
- fetchUnreadBodies: z.boolean().describe('If true, also fetch bodies for unread inbox messages — which marks each one READ on OurFamilyWizard and stamps a co-parent-visible "First Viewed" time that cannot be undone. Defaults to the OFW_FETCH_UNREAD_BODIES env var (false unless set), and is forced off entirely when OFW_ALLOW_MARK_READ=false.').optional(),
1858
+ fetchUnreadBodies: z.boolean().describe('If true, also fetch bodies for unread inbox messages — which marks each one READ on OurFamilyWizard and stamps a co-parent-visible "First Viewed" time that cannot be undone. Defaults to the OFW_FETCH_UNREAD_BODIES env var (false unless set). Applies only when the inbox is among the folders synced. Refused outright when OFW_ALLOW_MARK_READ=false or on a no-read day (the response\'s unreadBodies says which). When the server runs with OFW_CONFIRM_MARK_READ=true, the sync runs WITHOUT marking anything read and then asks the user to confirm opening the listed unread messages (newest ' + MAX_SYNC_OPEN_UNREAD + ' per call): a confirmation prompt where the client supports one; otherwise it returns that list plus a confirmToken, and only a repeat call with that token opens them. Show the user the list and wait for their yes.').optional(),
1774
1859
  deep: z.boolean().describe('If true, walk every OFW page until empty regardless of cache state. Use to backfill gaps. Default false.').optional(),
1775
1860
  maxRequests: z.number().int().min(1).describe('Maximum OFW requests this single call may make before pausing. When hit, the response reports done:false — call again with the same arguments to continue. Omit to use the server default (OFW_SYNC_MAX_REQUESTS, or unbounded on local installs).').optional(),
1861
+ confirmToken: confirmTokenParam,
1776
1862
  }),
1777
- }, async (args) => {
1863
+ }, async (args, ctx) => {
1778
1864
  const cache = cacheProvider();
1865
+ // Default from OFW_FETCH_UNREAD_BODIES (false unless set). Fetching those
1866
+ // bodies is exactly what stamps a First Viewed time on every unread
1867
+ // message it touches, so two gates stand in front of it:
1868
+ // 1. the CEILINGS — OFW_ALLOW_MARK_READ=false and a no-read day — refuse
1869
+ // outright, and the response says which one refused;
1870
+ // 2. OFW_CONFIRM_MARK_READ asks the user, naming every message it would
1871
+ // open, before a single one is fetched.
1872
+ // Only an INBOX sync can have unread bodies to fetch — sent messages carry
1873
+ // no read state of ours. A sent/drafts-only call has nothing to ask about,
1874
+ // and a prompt to open inbox messages there is one the caller never invited.
1875
+ const syncsInbox = (args.folders ?? ['inbox']).includes('inbox');
1876
+ const requested = syncsInbox && (args.fetchUnreadBodies ?? getFetchUnreadBodies());
1877
+ const ceiling = requested ? markReadCeiling() : null;
1878
+ const askFirst = requested && ceiling === null && getConfirmMarkRead();
1779
1879
  const result = await syncAll(client, {
1780
1880
  folders: args.folders,
1781
- // Default from OFW_FETCH_UNREAD_BODIES (false unless set), and capped by
1782
- // the OFW_ALLOW_MARK_READ ceiling — fetching those bodies is exactly what
1783
- // stamps a First Viewed time on every unread message it touches.
1784
- fetchUnreadBodies: markReadPermitted() && (args.fetchUnreadBodies ?? getFetchUnreadBodies()),
1881
+ // Under confirmation the sync itself never stamps: it walks list pages
1882
+ // only, and the approved bodies are opened below, one by one.
1883
+ fetchUnreadBodies: requested && ceiling === null && !askFirst,
1785
1884
  deep: args.deep,
1786
1885
  maxRequests: args.maxRequests ?? getSyncMaxRequests(),
1787
1886
  }, cache);
1887
+ let unreadBodies;
1888
+ if (ceiling !== null) {
1889
+ unreadBodies = { requested: true, fetched: false, ...ceiling };
1890
+ }
1891
+ else if (askFirst) {
1892
+ const { rows, remaining } = await unreadCandidates(cache);
1893
+ if (rows.length > 0) {
1894
+ const messages = rows.map((row) => ({
1895
+ messageId: row.id,
1896
+ subject: row.subject,
1897
+ from: senderOf(row),
1898
+ // The preview never passes through jsonResponse, so normalize here.
1899
+ ...normalizeTimestampsInValue({ sentAt: row.sentAt }),
1900
+ }));
1901
+ const lines = messages.map((m) => `"${m.subject}" — ${String(m.sentAtDisplay ?? m.sentAt)}`);
1902
+ const gate = await confirmWrite(ctx, {
1903
+ args,
1904
+ tool: 'ofw_sync_messages',
1905
+ action: 'ofw.message.mark_read',
1906
+ message: `Open ${rows.length} unread OurFamilyWizard message${rows.length === 1 ? '' : 's'} and mark ${rows.length === 1 ? 'it' : 'them'} read? ${lines.join('; ')}.${remaining > 0 ? ` (Older unread messages not listed here: ${remaining}; they wait for the next sync.)` : ''} Opening stamps a "First Viewed" time your co-parent can see; that cannot be undone.`,
1907
+ target: 'messages:unread-inbox',
1908
+ // The approval binds to THIS set: a message arriving (or being read
1909
+ // elsewhere) between the preview and the confirming call changes
1910
+ // the revision, and the stale approval is refused.
1911
+ revision: rows.map((row) => row.id).join(','),
1912
+ payload: { messageIds: rows.map((row) => row.id), markRead: true },
1913
+ preview: {
1914
+ action: `Open ${rows.length} unread OurFamilyWizard message${rows.length === 1 ? '' : 's'} (marks ${rows.length === 1 ? 'it' : 'them'} READ)`,
1915
+ warning: 'Opening these messages marks each one read on OurFamilyWizard and stamps a "First Viewed" time your co-parent can see. It is part of the record and cannot be undone. The sync itself already ran and marked nothing read.',
1916
+ messages,
1917
+ ...(remaining > 0 ? { remaining } : {}),
1918
+ },
1919
+ confirmToken: args.confirmToken,
1920
+ });
1921
+ if (gate)
1922
+ return gate;
1923
+ for (const row of rows)
1924
+ await openUnreadBody(client, cache, row);
1925
+ }
1926
+ const opened = new Set(rows.map((row) => row.id));
1927
+ const before = result.unreadInbox.length;
1928
+ result.unreadInbox = result.unreadInbox.filter((hint) => !opened.has(hint.id));
1929
+ if (result.unreadInbox.length !== before) {
1930
+ // Keep the note in step with unreadInbox: one payload, one count.
1931
+ // syncAll always writes a note when it reports unread hints, and the
1932
+ // count only moved because there were some, so the note is present.
1933
+ const notes = result.note.split('\n\n').filter((n) => n !== unreadInboxNote(before));
1934
+ if (result.unreadInbox.length > 0)
1935
+ notes.push(unreadInboxNote(result.unreadInbox.length));
1936
+ result.note = notes.length > 0 ? notes.join('\n\n') : undefined;
1937
+ }
1938
+ unreadBodies = { requested: true, fetched: true, opened: [...opened], ...(remaining > 0 ? { remaining } : {}) };
1939
+ }
1788
1940
  // Freshness of the cache AS OF this sync completing — so a paused call
1789
1941
  // that skipped a folder says so here too, not just in `notRefreshed`.
1790
1942
  const freshness = await buildFreshness(cache, {
1791
1943
  source: 'cache',
1792
1944
  folders: args.folders ?? ['inbox', 'sent', 'drafts'],
1793
1945
  });
1794
- return jsonResponse({ ...result, freshness });
1946
+ return jsonResponse({ ...result, ...(unreadBodies ? { unreadBodies } : {}), freshness });
1795
1947
  });
1796
1948
  server.registerTool('ofw_check_freshness', {
1949
+ _meta: familyMeta('other'),
1797
1950
  // Not read-only, and destructive: allowMarkRead:true probes unread inbox
1798
1951
  // ids by fetching them, which stamps an irreversible "First Viewed" time.
1799
1952
  description: 'Cheaply confirm whether the local cache still matches OurFamilyWizard, WITHOUT running a full sync. Use this before asserting anything about current state — especially "draft X is still sitting unsent". Costs one OFW request for the folder check plus one per messageId. For each folder it returns the live server count next to the cached count. For each id it returns a LIVE lifecycle `state` — "draft" | "sent" | "received" | "deleted" | "unknown" — alongside `folder`, `sentAt`, `existsOnServer` and a content comparison. `state` is the field that answers "is this still a draft?": a draft that has been SENT still exists on the server, so existsOnServer:true never distinguished the two. A cached draft whose state is no longer "draft" reports inSync:false even when its text is byte-identical. Content is compared by revision hash, because OFW draft timestamps do NOT change when a draft is edited in the web app. Does not fetch bodies into the cache, does not touch attachments, and does not depend on sync state. For draftKeys, or a full live draft inventory, use ofw_status.',
@@ -1883,6 +2036,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1883
2036
  return jsonResponse(payload);
1884
2037
  });
1885
2038
  server.registerTool('ofw_status', {
2039
+ _meta: familyMeta('other'),
1886
2040
  // Not read-only, and destructive, for the same reason as
1887
2041
  // ofw_check_freshness: allowMarkRead:true can stamp "First Viewed".
1888
2042
  description: 'ONE live call that answers "where does everything stand?". This is the call that should back any status summary about drafts or specific messages — never session memory, and never a cached read alone. With no arguments it returns the FULL current draft inventory, verified against OurFamilyWizard. Pass ids and/or draftKeys to get each one\'s live lifecycle `state` ("draft" | "sent" | "received" | "deleted" | "unknown") with `sentAt` and `viewedAt`. A draftKey is the stable identity ofw_save_draft returns: editing a draft mints a new OFW id every time (create-then-delete), so the key is the only way to ask "what happened to the thing I was working on?" — it resolves to the chain\'s current id and keeps resolving after the draft is SENT (state:"sent" with sentMessageId). The top-level `complete` is true ONLY when every part of this snapshot was verified live; if it is false, do not state a draft count or a lifecycle claim from this payload.',
@@ -1,6 +1,8 @@
1
1
  import { jsonResponse } from './_shared.js';
2
+ import { familyMeta } from './hints.js';
2
3
  export function registerUserTools(server, client) {
3
4
  server.registerTool('ofw_get_profile', {
5
+ _meta: familyMeta('lookup'),
4
6
  description: 'Get current user and co-parent profile information from OurFamilyWizard',
5
7
  annotations: { readOnlyHint: true, openWorldHint: true },
6
8
  }, async () => {
@@ -8,6 +10,7 @@ export function registerUserTools(server, client) {
8
10
  return jsonResponse(data);
9
11
  });
10
12
  server.registerTool('ofw_get_notifications', {
13
+ _meta: familyMeta('whats-new', { aliases: ['ofw', 'dashboard', 'unread', 'co-parent'] }),
11
14
  description: 'Get OurFamilyWizard dashboard summary: unread message count, upcoming events, outstanding expenses. Note: updates your last-seen status.',
12
15
  // Not read-only: this GET updates the last-seen status the co-parent can
13
16
  // see, a side effect the read tools deliberately avoid (see _shared.ts).
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.24.0'; // x-release-please-version
7
+ export const VERSION = '2.26.0'; // x-release-please-version
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ofw-mcp",
3
- "version": "2.24.0",
3
+ "version": "2.26.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.24.0",
9
+ "version": "2.26.0",
10
10
  "packages": [
11
11
  {
12
12
  "registryType": "npm",
13
13
  "identifier": "ofw-mcp",
14
- "version": "2.24.0",
14
+ "version": "2.26.0",
15
15
  "transport": {
16
16
  "type": "stdio"
17
17
  },
@@ -49,7 +49,7 @@
49
49
  },
50
50
  {
51
51
  "name": "OFW_CONFIRM_MARK_READ",
52
- "description": "Default \"false\". Set \"true\" to show an unread message's subject, sender and sent time and ask for confirmation before opening it marks it read. Also disables the bulk mark-read paths (sync fetchUnreadBodies, allowMarkRead probes).",
52
+ "description": "Default \"false\". Set \"true\" to show an unread message's subject, sender and sent time and ask for confirmation before opening it marks it read. Sync fetchUnreadBodies asks too; allowMarkRead probes are disabled.",
53
53
  "isRequired": false,
54
54
  "format": "string"
55
55
  },
@@ -90,7 +90,7 @@ Always pass `--config ~/.mcporter/mcporter.json` unless a local `config/mcporter
90
90
  ### Messages
91
91
  | Tool | Notes |
92
92
  |------|-------|
93
- | `ofw_sync_messages(folders?, deep?, fetchUnreadBodies?)` | Sync OFW → local cache. **Call first if the cache might be stale.** Returns unread inbox hints (bodies not fetched, to avoid mark-as-read). |
93
+ | `ofw_sync_messages(folders?, deep?, fetchUnreadBodies?)` | Sync OFW → local cache. **Call first if the cache might be stale.** Returns unread inbox hints (bodies not fetched, to avoid mark-as-read). 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
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
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. |
@@ -188,6 +188,31 @@ for when something already looks wrong.
188
188
  (`{id, subject, sentAt, unreadBy}`) that is already narrower than the
189
189
  projection.
190
190
 
191
+ ## In context groups
192
+
193
+ Every tool except `ofw_healthcheck` carries a `_meta.mint` hint in the
194
+ **family** group, so a host such as mcp-host can answer a "what's going on
195
+ with the family" ask across OFW and its sibling connectors. Two reads are
196
+ canonical, and both take `view: "brief"` (plain text, one line per item,
197
+ `title — <ISO date | no date> — <status>`). A line starting with `-- ` is a
198
+ note, not an item: `-- N of M shown` ends a page that is not the whole result
199
+ (walk `page`, or narrow the range), and `-- none` is the whole answer when
200
+ nothing matched:
201
+
202
+ - **What's new:** `ofw_list_messages`, its range on `since` / `until`. A line
203
+ is `sender: subject — sent — unread|read|sent`. It reads the local cache, so
204
+ the usual freshness rules apply (an unverified empty cache is still refused).
205
+ - **What's on:** `ofw_list_events`, its range on `startDate` / `endDate`. A
206
+ line is an event, an all-day item, an outside-calendar item or a custody
207
+ handoff; the per-day custody grid is never in the brief answer.
208
+
209
+ Neither declares a `subject`: OFW has no per-child argument to fan out over,
210
+ so a compound ask ("any new OFW messages, and what's on the custody calendar
211
+ this weekend?") is one call per canonical read, not one per child. Nothing
212
+ here answers a what's-due question. When the server authenticates through the
213
+ browser bridge rather than `OFW_USERNAME`/`OFW_PASSWORD`, the group answers
214
+ "needs your browser open" until a signed-in OurFamilyWizard tab is reachable.
215
+
191
216
  ## Freshness, completeness, and lifecycle
192
217
 
193
218
  Message and draft reads come from a local cache, so **a result can be stale without looking stale**. Three separate questions, three separate signals — do not substitute one for another: