ofw-mcp 2.24.0 → 2.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.
package/dist/config.js CHANGED
@@ -174,9 +174,10 @@ export function getAllowMarkRead() {
174
174
  * inbox message silently: it shows the subject, sender and sent time and asks
175
175
  * the user to confirm — through the same gate as a send (an elicitation prompt
176
176
  * where the client supports one, otherwise the two-phase confirmToken flow).
177
- * The bulk paths that stamp (`ofw_sync_messages fetchUnreadBodies`, the
178
- * `allowMarkRead` probes of `ofw_check_freshness` / `ofw_status`) cannot ask
179
- * about each message, so they are switched off instead.
177
+ * `ofw_sync_messages fetchUnreadBodies` asks too: it syncs without stamping,
178
+ * then lists the cached unread messages it would open and waits for a yes.
179
+ * The `allowMarkRead` probes of `ofw_check_freshness` / `ofw_status` have no
180
+ * message to show before the request that stamps, so they are switched off.
180
181
  *
181
182
  * Default FALSE: unset is exactly the shipped behaviour. An unrecognized value
182
183
  * fails CLOSED to true, with a warning: someone who typed "ture" meant to turn
package/dist/sync.js CHANGED
@@ -528,6 +528,15 @@ export async function syncDrafts(client, draftsFolderId, store, budget) {
528
528
  await markFolderVerified(store, 'drafts', now);
529
529
  return { synced, done: true };
530
530
  }
531
+ /**
532
+ * The sync note for unread inbox messages cached without bodies. Exported so
533
+ * ofw_sync_messages can rewrite it after a confirmed open of some of them —
534
+ * a note still counting messages the same call opened would contradict
535
+ * `unreadInbox` in one payload.
536
+ */
537
+ export function unreadInboxNote(count) {
538
+ return `${count} unread inbox messages cached without bodies. Call ofw_get_message(id) to read them — this will mark them as read on OFW.`;
539
+ }
531
540
  export async function syncAll(client, opts, store) {
532
541
  const requested = opts.folders ?? ['inbox', 'sent', 'drafts'];
533
542
  // Drafts go FIRST. They are the only folder a destructive tool
@@ -616,7 +625,7 @@ export async function syncAll(client, opts, store) {
616
625
  notes.push('The drafts folder was NOT checked against OurFamilyWizard on this call (the request budget ran out first), so no drafts count is reported and the cached drafts are marked "unverified". Cached draft bodies may be behind the server. Call ofw_sync_messages again — or ofw_sync_messages with folders:["drafts"] — before editing or deleting a draft.');
617
626
  }
618
627
  if (unreadInbox.length > 0) {
619
- notes.push(`${unreadInbox.length} unread inbox messages cached without bodies. Call ofw_get_message(id) to read them — this will mark them as read on OFW.`);
628
+ notes.push(unreadInboxNote(unreadInbox.length));
620
629
  }
621
630
  if (notRefreshed.length > 0) {
622
631
  notes.push(`NOT checked against OurFamilyWizard on this call: ${notRefreshed.join(', ')}. No count is reported for ${notRefreshed.length > 1 ? 'those folders' : 'that folder'} — absence of a count means "not looked at", not "no changes". Cached contents may be behind the server; call ofw_sync_messages again to finish, or ofw_check_freshness for a cheap live confirmation.`);
@@ -1,5 +1,5 @@
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
4
  import { checkDraftFreshness, draftRevision, fetchServerDraft, staleDraftPayload, } from './draft-freshness.js';
5
5
  import { FOLDER_TYPE, newDraftKey, persistFolderIds, probeIds, resolveDraftKey } from './lifecycle.js';
@@ -205,8 +205,8 @@ function unverifiedEmptyResponse(input) {
205
205
  });
206
206
  }
207
207
  /**
208
- * Whether a BULK path may mark messages read right now (sync's
209
- * fetchUnreadBodies, the allowMarkRead probes): the OFW_ALLOW_MARK_READ
208
+ * Whether a BULK path may mark messages read right now without asking (the
209
+ * allowMarkRead probes; sync asks instead — see ofw_sync_messages): the OFW_ALLOW_MARK_READ
210
210
  * ceiling, today being a reading day (OFW_READ_DAYS / OFW_NO_READ_DAYS), and
211
211
  * OFW_CONFIRM_MARK_READ being off — those paths stamp many messages without
212
212
  * looking at any of them, so they have nothing to put in front of the user.
@@ -216,6 +216,60 @@ function unverifiedEmptyResponse(input) {
216
216
  function markReadPermitted() {
217
217
  return getAllowMarkRead() && readingBlockedToday() === null && !getConfirmMarkRead();
218
218
  }
219
+ /**
220
+ * Which deployment CEILING (not the confirmation prompt) refuses marking
221
+ * anything read right now, or null when none does. Unlike
222
+ * markReadPermitted(), OFW_CONFIRM_MARK_READ is not a refusal here — it is a
223
+ * question the caller can put to the user.
224
+ */
225
+ function markReadCeiling() {
226
+ if (!getAllowMarkRead()) {
227
+ return {
228
+ gate: 'OFW_ALLOW_MARK_READ',
229
+ 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.',
230
+ };
231
+ }
232
+ const blocked = readingBlockedToday();
233
+ if (blocked !== null) {
234
+ return {
235
+ gate: 'OFW_READ_DAYS',
236
+ 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.',
237
+ readingBlocked: blocked,
238
+ };
239
+ }
240
+ return null;
241
+ }
242
+ /** How many unread messages one confirmed sync opens — the prompt must stay readable. */
243
+ export const MAX_SYNC_OPEN_UNREAD = 25;
244
+ /**
245
+ * The cached unread INBOX messages a confirmed sync would open, newest first:
246
+ * no body yet, and `deriveRead` cannot rule out unread — exactly the rows whose
247
+ * detail GET stamps "First Viewed". Read from the cache rather than from the
248
+ * sync's own "new this walk" list, because the confirming call re-runs the sync
249
+ * and finds nothing new — the set must be the same on both phases for the
250
+ * approval to bind to it.
251
+ */
252
+ async function unreadCandidates(cache) {
253
+ const all = (await cache.listMessages({ folder: 'inbox', page: 1, size: 1000 }))
254
+ .filter((row) => row.body === null && !deriveRead(row));
255
+ return { rows: all.slice(0, MAX_SYNC_OPEN_UNREAD), remaining: Math.max(0, all.length - MAX_SYNC_OPEN_UNREAD) };
256
+ }
257
+ /**
258
+ * Fetch one unread inbox body and cache it — the request that marks it read.
259
+ * Only ever called after the confirmation gate approved this exact message.
260
+ */
261
+ async function openUnreadBody(client, cache, cached) {
262
+ 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)' });
263
+ await cache.upsertMessage({
264
+ ...cached,
265
+ recipients: detail.recipients ? mapRecipients(detail.recipients) : cached.recipients,
266
+ body: detail.body ?? '',
267
+ fetchedBodyAt: new Date().toISOString(),
268
+ });
269
+ if (Array.isArray(detail.files) && detail.files.length > 0) {
270
+ await fetchAttachmentMetaForMessage(client, cached.id, detail.files, cache);
271
+ }
272
+ }
219
273
  /**
220
274
  * OFW_CONFIRM_MARK_READ: before `ofw_get_message` fetches a body that would
221
275
  * mark an unread inbox message read, show the user which message it is and
@@ -1770,28 +1824,95 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1770
1824
  annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true },
1771
1825
  inputSchema: z.object({
1772
1826
  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(),
1827
+ 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
1828
  deep: z.boolean().describe('If true, walk every OFW page until empty regardless of cache state. Use to backfill gaps. Default false.').optional(),
1775
1829
  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(),
1830
+ confirmToken: confirmTokenParam,
1776
1831
  }),
1777
- }, async (args) => {
1832
+ }, async (args, ctx) => {
1778
1833
  const cache = cacheProvider();
1834
+ // Default from OFW_FETCH_UNREAD_BODIES (false unless set). Fetching those
1835
+ // bodies is exactly what stamps a First Viewed time on every unread
1836
+ // message it touches, so two gates stand in front of it:
1837
+ // 1. the CEILINGS — OFW_ALLOW_MARK_READ=false and a no-read day — refuse
1838
+ // outright, and the response says which one refused;
1839
+ // 2. OFW_CONFIRM_MARK_READ asks the user, naming every message it would
1840
+ // open, before a single one is fetched.
1841
+ // Only an INBOX sync can have unread bodies to fetch — sent messages carry
1842
+ // no read state of ours. A sent/drafts-only call has nothing to ask about,
1843
+ // and a prompt to open inbox messages there is one the caller never invited.
1844
+ const syncsInbox = (args.folders ?? ['inbox']).includes('inbox');
1845
+ const requested = syncsInbox && (args.fetchUnreadBodies ?? getFetchUnreadBodies());
1846
+ const ceiling = requested ? markReadCeiling() : null;
1847
+ const askFirst = requested && ceiling === null && getConfirmMarkRead();
1779
1848
  const result = await syncAll(client, {
1780
1849
  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()),
1850
+ // Under confirmation the sync itself never stamps: it walks list pages
1851
+ // only, and the approved bodies are opened below, one by one.
1852
+ fetchUnreadBodies: requested && ceiling === null && !askFirst,
1785
1853
  deep: args.deep,
1786
1854
  maxRequests: args.maxRequests ?? getSyncMaxRequests(),
1787
1855
  }, cache);
1856
+ let unreadBodies;
1857
+ if (ceiling !== null) {
1858
+ unreadBodies = { requested: true, fetched: false, ...ceiling };
1859
+ }
1860
+ else if (askFirst) {
1861
+ const { rows, remaining } = await unreadCandidates(cache);
1862
+ if (rows.length > 0) {
1863
+ const messages = rows.map((row) => ({
1864
+ messageId: row.id,
1865
+ subject: row.subject,
1866
+ from: senderOf(row),
1867
+ // The preview never passes through jsonResponse, so normalize here.
1868
+ ...normalizeTimestampsInValue({ sentAt: row.sentAt }),
1869
+ }));
1870
+ const lines = messages.map((m) => `"${m.subject}" — ${String(m.sentAtDisplay ?? m.sentAt)}`);
1871
+ const gate = await confirmWrite(ctx, {
1872
+ args,
1873
+ tool: 'ofw_sync_messages',
1874
+ action: 'ofw.message.mark_read',
1875
+ 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.`,
1876
+ target: 'messages:unread-inbox',
1877
+ // The approval binds to THIS set: a message arriving (or being read
1878
+ // elsewhere) between the preview and the confirming call changes
1879
+ // the revision, and the stale approval is refused.
1880
+ revision: rows.map((row) => row.id).join(','),
1881
+ payload: { messageIds: rows.map((row) => row.id), markRead: true },
1882
+ preview: {
1883
+ action: `Open ${rows.length} unread OurFamilyWizard message${rows.length === 1 ? '' : 's'} (marks ${rows.length === 1 ? 'it' : 'them'} READ)`,
1884
+ 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.',
1885
+ messages,
1886
+ ...(remaining > 0 ? { remaining } : {}),
1887
+ },
1888
+ confirmToken: args.confirmToken,
1889
+ });
1890
+ if (gate)
1891
+ return gate;
1892
+ for (const row of rows)
1893
+ await openUnreadBody(client, cache, row);
1894
+ }
1895
+ const opened = new Set(rows.map((row) => row.id));
1896
+ const before = result.unreadInbox.length;
1897
+ result.unreadInbox = result.unreadInbox.filter((hint) => !opened.has(hint.id));
1898
+ if (result.unreadInbox.length !== before) {
1899
+ // Keep the note in step with unreadInbox: one payload, one count.
1900
+ // syncAll always writes a note when it reports unread hints, and the
1901
+ // count only moved because there were some, so the note is present.
1902
+ const notes = result.note.split('\n\n').filter((n) => n !== unreadInboxNote(before));
1903
+ if (result.unreadInbox.length > 0)
1904
+ notes.push(unreadInboxNote(result.unreadInbox.length));
1905
+ result.note = notes.length > 0 ? notes.join('\n\n') : undefined;
1906
+ }
1907
+ unreadBodies = { requested: true, fetched: true, opened: [...opened], ...(remaining > 0 ? { remaining } : {}) };
1908
+ }
1788
1909
  // Freshness of the cache AS OF this sync completing — so a paused call
1789
1910
  // that skipped a folder says so here too, not just in `notRefreshed`.
1790
1911
  const freshness = await buildFreshness(cache, {
1791
1912
  source: 'cache',
1792
1913
  folders: args.folders ?? ['inbox', 'sent', 'drafts'],
1793
1914
  });
1794
- return jsonResponse({ ...result, freshness });
1915
+ return jsonResponse({ ...result, ...(unreadBodies ? { unreadBodies } : {}), freshness });
1795
1916
  });
1796
1917
  server.registerTool('ofw_check_freshness', {
1797
1918
  // Not read-only, and destructive: allowMarkRead:true probes unread inbox
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.25.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.25.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.25.0",
10
10
  "packages": [
11
11
  {
12
12
  "registryType": "npm",
13
13
  "identifier": "ofw-mcp",
14
- "version": "2.24.0",
14
+ "version": "2.25.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. |