ofw-mcp 2.20.5 → 2.21.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.
@@ -158,8 +158,14 @@ function buildMessageFilter(opts) {
158
158
  }
159
159
  if (opts.q !== undefined && opts.q.length > 0) {
160
160
  const pattern = `%${opts.q}%`;
161
- wheres.push('(subject LIKE ? OR body LIKE ?)');
162
- params.push(pattern, pattern);
161
+ if (opts.qSubjectOnly) {
162
+ wheres.push('subject LIKE ?');
163
+ params.push(pattern);
164
+ }
165
+ else {
166
+ wheres.push('(subject LIKE ? OR body LIKE ?)');
167
+ params.push(pattern, pattern);
168
+ }
163
169
  }
164
170
  return {
165
171
  where: wheres.length > 0 ? `WHERE ${wheres.join(' AND ')}` : '',
@@ -0,0 +1,127 @@
1
+ // Days on which message CONTENT may be read.
2
+ //
3
+ // Some co-parenting arrangements (a court order, a parenting-plan clause, or
4
+ // just a personal rule) limit when OFW messages are read — e.g. "check OFW on
5
+ // Mondays and Thursdays only". On the other days it is fine to see THAT a
6
+ // message arrived, who sent it and its subject, but not to read it — and above
7
+ // all not to mark it read, which stamps a co-parent-visible "First Viewed"
8
+ // time on the record that cannot be undone.
9
+ //
10
+ // Two env vars, either or both:
11
+ // OFW_READ_DAYS allow list — reading is permitted ONLY on these days
12
+ // OFW_NO_READ_DAYS deny list — reading is refused on these days
13
+ // Each is a comma/space-separated list of tokens:
14
+ // mon … sun / monday … sunday a weekday, every week
15
+ // 2026-12-25 one calendar date
16
+ // 2026-12-24..2026-12-31 an inclusive date range
17
+ // A day is readable when (no allow list, or the day is on it) AND the day is
18
+ // not on the deny list — so the deny list carves exceptions out of the allow
19
+ // list. Unset/blank both → every day is readable (the default).
20
+ //
21
+ // "Today" is the calendar day in DISPLAY_TZ, the account's own zone — the same
22
+ // zone every *Display timestamp renders in — never the host's UTC clock, which
23
+ // would flip the day hours early or late.
24
+ //
25
+ // An unparseable token fails CLOSED (every day blocked) with a stderr warning:
26
+ // someone who wrote "Thrusday" meant to restrict reading, and silently
27
+ // ignoring the typo would keep reading on the day they meant to keep clear.
28
+ import { readEnvVar } from '@chrischall/mcp-utils';
29
+ import { displayTimeZone } from './timestamps.js';
30
+ const WEEKDAYS = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
31
+ const WEEKDAY_LABELS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
32
+ const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
33
+ function isRealDate(s) {
34
+ if (!DATE_RE.test(s))
35
+ return false;
36
+ const [y, m, d] = s.split('-').map(Number);
37
+ const dt = new Date(Date.UTC(y, m - 1, d));
38
+ return dt.getUTCFullYear() === y && dt.getUTCMonth() === m - 1 && dt.getUTCDate() === d;
39
+ }
40
+ function parseList(raw) {
41
+ const set = { weekdays: new Set(), ranges: [] };
42
+ const invalid = [];
43
+ for (const token of raw.split(/[\s,;]+/).filter((t) => t.length > 0)) {
44
+ const lower = token.toLowerCase();
45
+ const weekday = WEEKDAYS.findIndex((w) => w === lower || (lower.length >= 3 && w.startsWith(lower)));
46
+ if (weekday !== -1) {
47
+ set.weekdays.add(weekday);
48
+ continue;
49
+ }
50
+ const [from, to, ...rest] = token.split('..');
51
+ const end = to ?? from;
52
+ if (rest.length === 0 && isRealDate(from) && isRealDate(end) && from <= end) {
53
+ set.ranges.push([from, end]);
54
+ continue;
55
+ }
56
+ invalid.push(token);
57
+ }
58
+ return { set, invalid };
59
+ }
60
+ function contains(set, date, weekday) {
61
+ return set.weekdays.has(weekday) || set.ranges.some(([from, to]) => date >= from && date <= to);
62
+ }
63
+ /** The configured policy, or null when neither env var is set (always readable). */
64
+ export function getReadDayPolicy() {
65
+ const allowRaw = readEnvVar('OFW_READ_DAYS');
66
+ const denyRaw = readEnvVar('OFW_NO_READ_DAYS');
67
+ if (allowRaw === undefined && denyRaw === undefined)
68
+ return null;
69
+ const allow = allowRaw === undefined ? null : parseList(allowRaw);
70
+ const deny = denyRaw === undefined ? null : parseList(denyRaw);
71
+ const invalid = [...(allow?.invalid ?? []), ...(deny?.invalid ?? [])];
72
+ if (invalid.length > 0) {
73
+ // stdio transport: stderr only — stdout is reserved for JSON-RPC.
74
+ console.error(`[ofw-mcp] Unrecognized OFW_READ_DAYS / OFW_NO_READ_DAYS token(s) ${invalid.map((t) => JSON.stringify(t)).join(', ')} — failing closed: message content is withheld on EVERY day until this is fixed. Valid tokens: weekday names (mon, monday, …), YYYY-MM-DD, or YYYY-MM-DD..YYYY-MM-DD.`);
75
+ }
76
+ return { allow: allow?.set ?? null, deny: deny?.set ?? null, invalid };
77
+ }
78
+ function isReadable(policy, date, weekday) {
79
+ if (policy.invalid.length > 0)
80
+ return false;
81
+ if (policy.allow !== null && !contains(policy.allow, date, weekday))
82
+ return false;
83
+ return !(policy.deny !== null && contains(policy.deny, date, weekday));
84
+ }
85
+ // Calendar date (YYYY-MM-DD) of `instant` in `tz`.
86
+ function localDate(instant, tz) {
87
+ // en-CA formats as YYYY-MM-DD.
88
+ return new Intl.DateTimeFormat('en-CA', { timeZone: tz, year: 'numeric', month: '2-digit', day: '2-digit' }).format(instant);
89
+ }
90
+ // Calendar arithmetic on a YYYY-MM-DD string, in UTC so DST never skews it.
91
+ function addDays(date, n) {
92
+ const [y, m, d] = date.split('-').map(Number);
93
+ const dt = new Date(Date.UTC(y, m - 1, d + n));
94
+ return { date: dt.toISOString().slice(0, 10), weekday: dt.getUTCDay() };
95
+ }
96
+ /**
97
+ * Null when message content may be read today; otherwise a description of why
98
+ * not, suitable for embedding in a tool response.
99
+ */
100
+ export function readingBlockedToday(now = new Date()) {
101
+ const policy = getReadDayPolicy();
102
+ if (policy === null)
103
+ return null;
104
+ const timeZone = displayTimeZone();
105
+ const today = addDays(localDate(now, timeZone), 0);
106
+ if (isReadable(policy, today.date, today.weekday))
107
+ return null;
108
+ let nextReadableDay = null;
109
+ for (let i = 1; i <= 366; i++) {
110
+ const day = addDays(today.date, i);
111
+ if (isReadable(policy, day.date, day.weekday)) {
112
+ nextReadableDay = `${WEEKDAY_LABELS[day.weekday]} ${day.date}`;
113
+ break;
114
+ }
115
+ }
116
+ const reason = policy.invalid.length > 0
117
+ ? `OFW_READ_DAYS / OFW_NO_READ_DAYS contains unrecognized value(s) ${policy.invalid.map((t) => JSON.stringify(t)).join(', ')}, so reading is blocked on every day until the setting is fixed.`
118
+ : `Today (${WEEKDAY_LABELS[today.weekday]} ${today.date}, ${timeZone}) is not a message-reading day under this server's OFW_READ_DAYS / OFW_NO_READ_DAYS setting.`;
119
+ return {
120
+ error: 'READING_BLOCKED',
121
+ today: today.date,
122
+ weekday: WEEKDAY_LABELS[today.weekday],
123
+ timeZone,
124
+ reason: `${reason} You may see that messages arrived, who sent them, when, and their subjects — but message bodies and attachments are withheld, and nothing may be marked read on OurFamilyWizard. This is a deployment setting; no per-call argument can override it.`,
125
+ nextReadableDay,
126
+ };
127
+ }
@@ -1,4 +1,4 @@
1
- import { createFileStatePersistence, resolveStateFile, } from '@chrischall/mcp-utils/session';
1
+ import { createFileStatePersistence, isBearerTokens, resolveStateFile, } from '@chrischall/mcp-utils/session';
2
2
  import { readEnvVar, parseBoolEnv } from '@chrischall/mcp-utils';
3
3
  /**
4
4
  * Where the OFW session token is cached between runs.
@@ -19,16 +19,6 @@ export function sessionCachePath(env = process.env) {
19
19
  fileName: 'session.json',
20
20
  });
21
21
  }
22
- /** Only a token pair is ever stored — never the username or password. */
23
- function isTokens(raw) {
24
- if (raw === null || typeof raw !== 'object')
25
- return false;
26
- const t = raw;
27
- return (typeof t.accessToken === 'string' &&
28
- t.accessToken !== '' &&
29
- typeof t.expiresAt === 'number' &&
30
- (t.refreshToken === undefined || typeof t.refreshToken === 'string'));
31
- }
32
22
  /**
33
23
  * The session cache, or `null` when it must not be used.
34
24
  *
@@ -62,7 +52,7 @@ export function createSessionCache(opts = {}) {
62
52
  // password may contain spaces, so a space-joined pair could collide with
63
53
  // a different pair by shifting the boundary between the two halves.
64
54
  boundTo: [username.trim().toLowerCase(), password].join('\u0000'),
65
- validate: (raw) => (isTokens(raw) ? raw : null),
55
+ validate: (raw) => (isBearerTokens(raw) ? raw : null),
66
56
  });
67
57
  }
68
58
  /**
package/dist/sync.js CHANGED
@@ -2,6 +2,7 @@ import { z } from 'zod';
2
2
  import { ApiRecipientSchema, hasRealView, mapRecipients, threadedReplyTo } from './tools/_shared.js';
3
3
  import { parseLenient } from '@chrischall/mcp-utils';
4
4
  import { nowNaiveWallClock } from './timestamps.js';
5
+ import { readingBlockedToday } from './read-days.js';
5
6
  // Each OFW message detail returns `files: [fileId, ...]`. We fetch the metadata
6
7
  // for each file id (cheap JSON call) so the model can see filenames/mime types
7
8
  // without downloading bytes. Bytes are pulled lazily by ofw_download_attachment.
@@ -155,7 +156,34 @@ async function walkPages(client, folder, folderId, opts, store) {
155
156
  if (newestId === null || item.id > newestId)
156
157
  newestId = item.id;
157
158
  const existing = existingById.get(item.id);
159
+ const isInboxUnread = folder === 'inbox' && item.showNeverViewed === true;
158
160
  if (existing) {
161
+ // Heal a row cached without its body — typically one listed on a
162
+ // no-read day — once fetching it can stamp nothing: a sent message, or
163
+ // an inbox message OFW already reports as read. An unread inbox body
164
+ // stays the caller's explicit choice (ofw_get_message), as before.
165
+ if (opts.fetchBodies && existing.body === null && !isInboxUnread) {
166
+ if (!budget.take()) {
167
+ pageBudgetHit = true;
168
+ break;
169
+ }
170
+ const detail = parseLenient(DetailResponseSchema, await client.request('GET', `/pub/v3/messages/${item.id}`), { label: 'ofw-mcp', context: 'GET /pub/v3/messages/{id} (body backfill)' });
171
+ toUpsert.push({
172
+ ...existing,
173
+ body: detail.body ?? '',
174
+ fetchedBodyAt: new Date().toISOString(),
175
+ recipients: mapRecipients(detail.recipients ?? item.recipients),
176
+ listData: item,
177
+ });
178
+ synced++;
179
+ // Counts as new: a forward pass must keep walking past a page it
180
+ // still had work on, or older withheld rows would never be reached.
181
+ pageHadNewItem = true;
182
+ if (Array.isArray(detail.files) && detail.files.length > 0) {
183
+ await fetchAttachmentMetaBudgeted(client, item.id, detail.files, store, budget);
184
+ }
185
+ continue;
186
+ }
159
187
  // A sent message's read status changes AFTER it's first cached, when
160
188
  // the recipient opens it — so we can't just skip existing rows. The
161
189
  // list item carries the reliable `showNeverViewed` boolean but only an
@@ -163,7 +191,7 @@ async function walkPages(client, folder, folderId, opts, store) {
163
191
  // on the detail endpoint. So when a sent message has flipped to read
164
192
  // and we don't yet hold a real viewed time, re-fetch detail to capture
165
193
  // it (no body re-fetch — only the recipient view fields can change).
166
- if (folder === 'sent' && item.showNeverViewed === false && !hasRealView(existing.recipients)) {
194
+ if (opts.fetchBodies && folder === 'sent' && item.showNeverViewed === false && !hasRealView(existing.recipients)) {
167
195
  if (!budget.take()) {
168
196
  pageBudgetHit = true;
169
197
  break;
@@ -175,8 +203,7 @@ async function walkPages(client, folder, folderId, opts, store) {
175
203
  continue;
176
204
  }
177
205
  pageHadNewItem = true;
178
- const isInboxUnread = folder === 'inbox' && item.showNeverViewed === true;
179
- const shouldFetchBody = !isInboxUnread || opts.fetchUnreadBodies;
206
+ const shouldFetchBody = opts.fetchBodies && (!isInboxUnread || opts.fetchUnreadBodies);
180
207
  let body = null;
181
208
  let fetchedBodyAt = null;
182
209
  let detailFileIds = [];
@@ -200,7 +227,7 @@ async function walkPages(client, folder, folderId, opts, store) {
200
227
  detailFileIds = detail.files;
201
228
  }
202
229
  }
203
- else {
230
+ else if (isInboxUnread) {
204
231
  unread.push({
205
232
  id: item.id,
206
233
  subject: item.subject,
@@ -266,6 +293,7 @@ async function walkPages(client, folder, folderId, opts, store) {
266
293
  * waited months can wait one more call.
267
294
  */
268
295
  export async function syncMessageFolder(client, folder, folderId, opts, store) {
296
+ const fetchBodies = opts.fetchBodies ?? true;
269
297
  // No budget → unbounded (local stdio): every take() succeeds, so an ordinary
270
298
  // sync is byte-for-byte the original unbounded walk (forward pass only).
271
299
  const budget = opts.budget ?? makeBudget(Number.POSITIVE_INFINITY);
@@ -275,6 +303,7 @@ export async function syncMessageFolder(client, folder, folderId, opts, store) {
275
303
  startPage: 1,
276
304
  stopAtCachedPage: true,
277
305
  fetchUnreadBodies: opts.fetchUnreadBodies,
306
+ fetchBodies,
278
307
  budget,
279
308
  }, store);
280
309
  let synced = fwd.synced;
@@ -325,6 +354,7 @@ export async function syncMessageFolder(client, folder, folderId, opts, store) {
325
354
  startPage: savedResume ?? fwd.nextPage,
326
355
  stopAtCachedPage: false,
327
356
  fetchUnreadBodies: opts.fetchUnreadBodies,
357
+ fetchBodies,
328
358
  budget,
329
359
  }, store);
330
360
  synced += bf.synced;
@@ -514,6 +544,9 @@ export async function syncAll(client, opts, store) {
514
544
  // ONE budget shared across resolveFolderIds and every requested folder, in
515
545
  // order — so the whole invocation stays under the hosting subrequest cap.
516
546
  const budget = makeBudget(opts.maxRequests ?? Number.POSITIVE_INFINITY);
547
+ // Decided HERE, not by each caller, so every path into a sync — the tool,
548
+ // a read's autoRefresh, ofw_status — honours a no-read day (read-days.ts).
549
+ const readingBlocked = readingBlockedToday() !== null;
517
550
  // resolveFolderIds always makes exactly one request; the tool guarantees
518
551
  // maxRequests >= 1, so this unit is always available (result intentionally
519
552
  // ignored — we account for it without a branch that can't be reached).
@@ -541,7 +574,8 @@ export async function syncAll(client, opts, store) {
541
574
  for (const folder of folders) {
542
575
  if (folder === 'inbox') {
543
576
  const r = await syncMessageFolder(client, 'inbox', ids.inbox, {
544
- fetchUnreadBodies: opts.fetchUnreadBodies ?? false,
577
+ fetchUnreadBodies: !readingBlocked && (opts.fetchUnreadBodies ?? false),
578
+ fetchBodies: !readingBlocked,
545
579
  deep: opts.deep ?? false,
546
580
  budget,
547
581
  }, store);
@@ -553,6 +587,7 @@ export async function syncAll(client, opts, store) {
553
587
  else if (folder === 'sent') {
554
588
  const r = await syncMessageFolder(client, 'sent', ids.sent, {
555
589
  fetchUnreadBodies: false,
590
+ fetchBodies: !readingBlocked,
556
591
  deep: opts.deep ?? false,
557
592
  budget,
558
593
  }, store);
@@ -574,6 +609,9 @@ export async function syncAll(client, opts, store) {
574
609
  }
575
610
  }
576
611
  const notes = [];
612
+ if (readingBlocked) {
613
+ notes.push('Today is a no-read day (OFW_READ_DAYS / OFW_NO_READ_DAYS): new inbox and sent messages were cached from the list only — sender, date and subject — and no message body was downloaded. The first sync on a reading day fills in bodies that can be fetched without marking anything read.');
614
+ }
577
615
  if (draftsUnverified) {
578
616
  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.');
579
617
  }
@@ -594,6 +632,7 @@ export async function syncAll(client, opts, store) {
594
632
  syncComplete: done,
595
633
  refreshed,
596
634
  notRefreshed,
635
+ ...(readingBlocked ? { bodiesWithheld: true } : {}),
597
636
  ...(note ? { note } : {}),
598
637
  };
599
638
  }
@@ -15,6 +15,7 @@ import { pageState } from './pagination.js';
15
15
  import { MESSAGE_VIEWS, viewDrafts, viewMessages, viewOne } from './project.js';
16
16
  import { resolveView, viewParam } from '@chrischall/mcp-utils';
17
17
  import { nowNaiveWallClock, toNaiveWallClock } from '../timestamps.js';
18
+ import { readingBlockedToday } from '../read-days.js';
18
19
  // Schemas for the load-bearing fields of each /pub/v3 response this file
19
20
  // reads (issue #83). Loose: unknown keys pass through into cached listData.
20
21
  const DateSchema = z.looseObject({ dateTime: z.string() });
@@ -203,6 +204,28 @@ function unverifiedEmptyResponse(input) {
203
204
  ...input.extra,
204
205
  });
205
206
  }
207
+ /**
208
+ * Whether ANY tool may mark a message read right now: the OFW_ALLOW_MARK_READ
209
+ * ceiling, AND today being a reading day (OFW_READ_DAYS / OFW_NO_READ_DAYS).
210
+ * Both are deployment settings a per-call argument cannot raise.
211
+ */
212
+ function markReadPermitted() {
213
+ return getAllowMarkRead() && readingBlockedToday() === null;
214
+ }
215
+ /**
216
+ * A message row with its content removed, for a no-read day. The body goes,
217
+ * and so do the copies of it OFW's list payload carries (`preview`, `body`) —
218
+ * otherwise `view:"full"` would hand back the first lines anyway. Everything
219
+ * that says a message ARRIVED (subject, sender, dates, read state) stays.
220
+ */
221
+ function withholdBody(row) {
222
+ let listData = row.listData;
223
+ if (listData !== null && typeof listData === 'object' && !Array.isArray(listData)) {
224
+ const { preview: _preview, body: _body, ...rest } = listData;
225
+ listData = rest;
226
+ }
227
+ return { ...row, body: null, listData, bodyWithheld: true };
228
+ }
206
229
  /**
207
230
  * Decide whether fetching this message's body from OFW would stamp the record,
208
231
  * and refuse when the caller (or the deployment) has opted out of that.
@@ -351,7 +374,10 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
351
374
  }
352
375
  const cache = cacheProvider();
353
376
  const folders = folder === undefined ? ['inbox', 'sent'] : [folder];
354
- const filter = { folder, since: bounds.since, until: bounds.until, q: args.q };
377
+ // On a no-read day `q` matches subjects only: a body match would tell the
378
+ // caller what a message says without ever returning it.
379
+ const blocked = readingBlockedToday();
380
+ const filter = { folder, since: bounds.since, until: bounds.until, q: args.q, qSubjectOnly: blocked !== null };
355
381
  const { value, refreshed, unverifiedEmpty } = await guardedCacheRead({
356
382
  client,
357
383
  cache,
@@ -429,16 +455,21 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
429
455
  if (refreshed) {
430
456
  payload.autoRefreshed = true;
431
457
  }
458
+ if (blocked !== null) {
459
+ // Ahead of `messages`, for the same reason the paging state is: a reader
460
+ // that stops early must still learn that every body below is withheld.
461
+ payload.readingBlocked = blocked;
462
+ }
432
463
  payload.freshness = freshness;
433
464
  // Projected HERE, at the last possible moment, so `returned`, `complete`
434
465
  // and every note above are computed from the rows themselves — a
435
466
  // projection must never be able to change what the response claims about
436
467
  // its own contents.
437
- payload.messages = viewMessages(view, messages);
468
+ payload.messages = viewMessages(view, blocked === null ? messages : messages.map(withholdBody));
438
469
  return jsonResponse(payload);
439
470
  });
440
471
  server.registerTool('ofw_get_message', {
441
- 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.',
472
+ 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.',
442
473
  annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true },
443
474
  inputSchema: z.object({
444
475
  messageId: z.string().describe('Message ID (also accepts draft IDs — drafts are routed via the drafts cache)'),
@@ -503,6 +534,26 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
503
534
  });
504
535
  }
505
536
  const cached = await cache.getMessage(id);
537
+ // No-read day: answer from the cache with the body withheld, and never
538
+ // touch OFW — any detail GET here could mark an unread message read.
539
+ const blocked = readingBlockedToday();
540
+ if (blocked !== null) {
541
+ if (cached === null) {
542
+ return jsonErrorResponse({
543
+ ...blocked,
544
+ messageId: id,
545
+ hint: 'This id is not in the cache. Run ofw_sync_messages (it walks list pages, not bodies, and marks nothing read) to see its subject, sender and date.',
546
+ });
547
+ }
548
+ const attachments = await cache.listAttachmentsForMessage(id);
549
+ const freshness = await buildFreshness(cache, { source: 'cache', folders: [cached.folder] });
550
+ return jsonResponse({
551
+ readingBlocked: blocked,
552
+ ...viewOne(view, withholdBody(withReadState(cached))),
553
+ attachments,
554
+ freshness,
555
+ });
556
+ }
506
557
  if (cached && cached.body !== null) {
507
558
  let row = cached;
508
559
  // Refresh view status for a sent message we still believe is unviewed:
@@ -1557,6 +1608,27 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1557
1608
  const forcedInline = inline && !requestedInline;
1558
1609
  const deliveryOptions = { extract: args.extract, maxChars: args.maxChars, parts: args.parts };
1559
1610
  let cached = await cache.getAttachment(fileId);
1611
+ // No-read day: an attachment is message content. Only a file the cache
1612
+ // knows belongs to the account holder's own DRAFTS is released; anything
1613
+ // linked to an inbox/sent message — or that the cache cannot place at all
1614
+ // — is refused before any request is made.
1615
+ const blocked = readingBlockedToday();
1616
+ if (blocked !== null) {
1617
+ const linked = (cached?.messageIds ?? []).filter((mid) => mid !== 0);
1618
+ let draftOnly = linked.length > 0;
1619
+ for (const mid of linked) {
1620
+ if ((await cache.getDraft(mid)) === null)
1621
+ draftOnly = false;
1622
+ }
1623
+ if (!draftOnly) {
1624
+ return jsonErrorResponse({
1625
+ ...blocked,
1626
+ fileId,
1627
+ ...(cached ? { fileName: cached.fileName } : {}),
1628
+ hint: 'Attachments on received or sent messages (or files this cache cannot place) are withheld on a no-read day. Download it on the next reading day.',
1629
+ });
1630
+ }
1631
+ }
1560
1632
  if (!cached) {
1561
1633
  // Not in cache. Fetch metadata and store under the messageId=0
1562
1634
  // sentinel — gets re-linked if a message later references this file.
@@ -1654,7 +1726,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1654
1726
  server.registerTool('ofw_sync_messages', {
1655
1727
  // Destructive: fetchUnreadBodies:true stamps a co-parent-visible "First
1656
1728
  // Viewed" time on every unread inbox message it touches — irreversible.
1657
- 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).',
1729
+ 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.',
1658
1730
  annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true },
1659
1731
  inputSchema: z.object({
1660
1732
  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(),
@@ -1669,7 +1741,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1669
1741
  // Default from OFW_FETCH_UNREAD_BODIES (false unless set), and capped by
1670
1742
  // the OFW_ALLOW_MARK_READ ceiling — fetching those bodies is exactly what
1671
1743
  // stamps a First Viewed time on every unread message it touches.
1672
- fetchUnreadBodies: getAllowMarkRead() && (args.fetchUnreadBodies ?? getFetchUnreadBodies()),
1744
+ fetchUnreadBodies: markReadPermitted() && (args.fetchUnreadBodies ?? getFetchUnreadBodies()),
1673
1745
  deep: args.deep,
1674
1746
  maxRequests: args.maxRequests ?? getSyncMaxRequests(),
1675
1747
  }, cache);
@@ -1696,7 +1768,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1696
1768
  // The server-wide ceiling wins: a per-call allowMarkRead:true (or an
1697
1769
  // instruction injected into one) must not be able to stamp the record on a
1698
1770
  // deployment configured to never do so.
1699
- const allowMarkRead = getAllowMarkRead() && (args.allowMarkRead ?? false);
1771
+ const allowMarkRead = markReadPermitted() && (args.allowMarkRead ?? false);
1700
1772
  const requestedIds = args.messageIds ?? [];
1701
1773
  const ids = requestedIds.slice(0, MAX_FRESHNESS_IDS);
1702
1774
  // Folders default to "all three" only when the caller asked about nothing
@@ -1783,7 +1855,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1783
1855
  }),
1784
1856
  }, async (args) => {
1785
1857
  const cache = cacheProvider();
1786
- const allowMarkRead = getAllowMarkRead() && (args.allowMarkRead ?? false);
1858
+ const allowMarkRead = markReadPermitted() && (args.allowMarkRead ?? false);
1787
1859
  const requestedIds = args.ids ?? [];
1788
1860
  const requestedKeys = args.draftKeys ?? [];
1789
1861
  // A bare ofw_status() is meant to be the "here is where everything stands"
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.20.5'; // x-release-please-version
7
+ export const VERSION = '2.21.0'; // x-release-please-version
package/mint.yaml CHANGED
@@ -4,6 +4,15 @@ slug: ofw
4
4
  summary: >-
5
5
  OurFamilyWizard co-parenting tools for Claude — messages, calendar,
6
6
  expenses, and journal
7
+ examples:
8
+ - prompt: >-
9
+ Summarize the OurFamilyWizard messages from my co-parent this week and
10
+ list anything that needs a reply.
11
+ note: Reads your inbox; first-time reads mark a message viewed in OFW.
12
+ - prompt: >-
13
+ What's on our shared OFW calendar for the next two weeks?
14
+ - prompt: >-
15
+ How much do I owe and how much have I paid in OFW expenses?
7
16
  #
8
17
  # Hosting note (a comment, not user-facing summary text): this is a
9
18
  # BROWSER-BRIDGE MCP — it reaches its site through the user's signed-in
@@ -75,6 +84,18 @@ env:
75
84
  Default "false". Whether ofw_sync_messages fetches unread inbox bodies by
76
85
  default (each fetch stamps a First Viewed time). Capped by
77
86
  OFW_ALLOW_MARK_READ.
87
+ - name: OFW_READ_DAYS
88
+ required: false
89
+ help: >-
90
+ Allow list of days message content may be read, e.g. "mon,thu" (weekday
91
+ names, YYYY-MM-DD, or YYYY-MM-DD..YYYY-MM-DD, in DISPLAY_TZ). On other
92
+ days senders, dates and subjects stay visible, but bodies and attachments
93
+ are withheld and nothing is marked read. Unset = every day.
94
+ - name: OFW_NO_READ_DAYS
95
+ required: false
96
+ help: >-
97
+ Deny list of days message content may NOT be read (same format as
98
+ OFW_READ_DAYS; wins over it). Unset = none.
78
99
  - name: OFW_INLINE_ATTACHMENTS
79
100
  required: false
80
101
  help: >-
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ofw-mcp",
3
- "version": "2.20.5",
3
+ "version": "2.21.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)",
@@ -34,7 +34,7 @@
34
34
  "typecheck": "tsc -p tsconfig.json --noEmit"
35
35
  },
36
36
  "dependencies": {
37
- "@chrischall/mcp-utils": "^3.0.3",
37
+ "@chrischall/mcp-utils": "^3.1.0",
38
38
  "@fetchproxy/bootstrap": "^3.6.2",
39
39
  "@modelcontextprotocol/server": "^2.3.0",
40
40
  "dotenv": "^18.0.0",
@@ -47,5 +47,9 @@
47
47
  "esbuild": "^0.28.0",
48
48
  "typescript": "^7.0.2",
49
49
  "vitest": "^5.0.0"
50
+ },
51
+ "allowScripts": {
52
+ "esbuild": false,
53
+ "fsevents": false
50
54
  }
51
55
  }
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.20.5",
9
+ "version": "2.21.0",
10
10
  "packages": [
11
11
  {
12
12
  "registryType": "npm",
13
13
  "identifier": "ofw-mcp",
14
- "version": "2.20.5",
14
+ "version": "2.21.0",
15
15
  "transport": {
16
16
  "type": "stdio"
17
17
  },
@@ -53,6 +53,18 @@
53
53
  "isRequired": false,
54
54
  "format": "string"
55
55
  },
56
+ {
57
+ "name": "OFW_READ_DAYS",
58
+ "description": "Allow list of days message content may be read, e.g. \"mon,thu\" (weekdays, YYYY-MM-DD, or YYYY-MM-DD..YYYY-MM-DD, in DISPLAY_TZ). Other days: subjects only, nothing marked read. Unset = every day.",
59
+ "isRequired": false,
60
+ "format": "string"
61
+ },
62
+ {
63
+ "name": "OFW_NO_READ_DAYS",
64
+ "description": "Deny list of days message content may NOT be read (same format as OFW_READ_DAYS; wins over it). Unset = none.",
65
+ "isRequired": false,
66
+ "format": "string"
67
+ },
56
68
  {
57
69
  "name": "OFW_SESSION_CACHE",
58
70
  "description": "Set to false to disable the on-disk session cache and re-authenticate on every process start. Defaults to enabled.",
@@ -93,7 +93,7 @@ Always pass `--config ~/.mcporter/mcporter.json` unless a local `config/mcporter
93
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). |
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
- | `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. |
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. 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. |
97
97
  | `ofw_send_message(draftId?, subject?, body?, recipientIds?, replyToId?, expectedRevision?, deleteDraftOnSuccess?, myFileIDs?, 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`. |
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). |