ofw-mcp 2.20.6 → 2.22.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
+ }
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
  }
@@ -12,8 +12,10 @@ export const CONFIRM_NOTE = 'Asks the user to confirm first: a confirmation prom
12
12
  * docs/CLIENT-BEHAVIOUR.md) gets the two-phase token flow governed by
13
13
  * `MCP_CONFIRM_MODE`: phase 1 performs no write and returns the preview plus a
14
14
  * `confirmToken`; only a repeat call with that token proceeds. The token is
15
- * bound to this tool, the target, its revision and the exact payload, is
16
- * single-use and expires (`MCP_CONFIRM_TTL_SECONDS`).
15
+ * bound to this tool/action, the target, its revision, exact payload, preview
16
+ * and caller arguments on BOTH rails. The fallback token is single-use and
17
+ * expires (`MCP_CONFIRM_TTL_SECONDS`); elicitation state uses the same TTL.
18
+ * Outstanding approvals minted before this binding change must be renewed.
17
19
  *
18
20
  * Call it on EVERY invocation with the freshly-built payload and a freshly
19
21
  * read revision — the caller's own re-read is what makes a stale token fail.
@@ -24,6 +26,17 @@ export const CONFIRM_NOTE = 'Asks the user to confirm first: a confirmation prom
24
26
  * return unchanged.
25
27
  */
26
28
  export function confirmWrite(ctx, opts) {
29
+ // mcp-utils binds elicitation acceptance to args, NOT subject(). Carry the
30
+ // effective approval state into both rails; caller args alone omit fields
31
+ // inherited from fresh reads. Strip the phase-2 token before nesting args
32
+ // (the helper only strips a top-level confirmToken).
33
+ const { confirmToken: _confirmToken, ...args } = opts.args;
34
+ const subject = {
35
+ target: opts.target,
36
+ ...(opts.revision !== undefined ? { revision: opts.revision } : {}),
37
+ payload: opts.payload,
38
+ preview: opts.preview,
39
+ };
27
40
  return requireConfirmationWithFallback(ctx, confirmationFromEnv({
28
41
  action: opts.action,
29
42
  message: opts.message,
@@ -33,14 +46,9 @@ export function confirmWrite(ctx, opts) {
33
46
  // One OFW account per process (OFW_USERNAME / the captured session), so
34
47
  // there is no principal to distinguish; mcp-utils 3 makes saying so explicit.
35
48
  account: undefined,
36
- args: opts.args,
49
+ args: { tool: opts.tool, action: opts.action, args, ...subject },
37
50
  confirmToken: opts.confirmToken,
38
- subject: () => ({
39
- target: opts.target,
40
- ...(opts.revision !== undefined ? { revision: opts.revision } : {}),
41
- payload: opts.payload,
42
- preview: opts.preview,
43
- }),
51
+ subject: () => subject,
44
52
  }));
45
53
  }
46
54
  /**
@@ -0,0 +1,117 @@
1
+ import { parseLenient } from '@chrischall/mcp-utils';
2
+ import { z } from 'zod';
3
+ import { CONFIRM_NOTE, confirmTokenParam, confirmWrite, stateRevision } from './_confirm.js';
4
+ import { jsonErrorResponse, jsonResponse, requestWrite, UnconfirmedWriteError, unconfirmedWriteResponse } from './_shared.js';
5
+ // Allow ordinary binary floating point representations of exact cents, but
6
+ // never round a genuinely fractional cent or accept an unsafe monetary value.
7
+ const money = z.number().nonnegative().refine((v) => Number.isSafeInteger(Math.round(v * 100))
8
+ && v === Math.round(v * 100) / 100, 'Must be an exact, safe cent amount');
9
+ const id = z.number().int().positive();
10
+ const detailSchema = z.looseObject({
11
+ id, title: z.string().min(1).refine((v) => v.trim().length > 0), author: z.looseObject({ userId: id }),
12
+ payer: z.looseObject({ userId: id }), private: z.boolean(), paymentType: z.string(),
13
+ amount: z.looseObject({ total: money.refine((v) => v > 0), totalOwed: money, leftToPay: money }),
14
+ status: z.string().min(1), statusInfo: z.looseObject({ baseStatus: z.string(), subStatus: z.literal('NONE') }),
15
+ category: z.looseObject({ id, split: z.looseObject({ parentSplit: z.string(), coparentSplit: z.string() }) }),
16
+ children: z.array(z.looseObject({ userId: id })).min(1),
17
+ }).refine((d) => d.amount.leftToPay <= d.amount.totalOwed && d.amount.totalOwed <= d.amount.total, 'Inconsistent expense balances');
18
+ // All fields outside the expected status/balance transition stay protected.
19
+ // OFW's amount display fields describe the current balance and legitimately
20
+ // change with settlement; the numeric purchase/owed totals remain immutable.
21
+ // Unknown fields outside these known derived displays remain protected too.
22
+ function immutableRevision(d) {
23
+ const { status: _status, statusInfo: _info, paymentType: _type, amount, ...rest } = d;
24
+ const { leftToPay: _balance, leftToPayFmt: _balanceFmt, description: _description, color: _color, ...amountRest } = amount;
25
+ return stateRevision({ ...rest, amount: amountRest });
26
+ }
27
+ /** Registered only by the full expense surface in write mode all. */
28
+ export function registerExpenseReimbursementTool(server, client) {
29
+ server.registerTool('ofw_mark_expense_reimbursed', {
30
+ description: 'Irreversibly mark the FULL remaining expense balance reimbursed externally. Records an already completed outside-OFW reimbursement only: does NOT send money or use bank/payment endpoints; no partial amounts. Requires expectedRemainingAmount (currency units, positive exact cents) matching the current leftToPay, NOT the full expense total. Reads the current expense, binds the entire detail to confirmation, rechecks immediately before writing, then verifies paid status and unchanged fields. Cannot be undone. On EXPENSE_REIMBURSEMENT_UNCONFIRMED, mayHaveLanded=true: inspect the OFW Expenses log before any retry; never replay blindly. ' + CONFIRM_NOTE,
31
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
32
+ inputSchema: z.object({
33
+ expenseId: id.describe('Existing expense entity id'),
34
+ expectedRemainingAmount: money.refine((v) => v > 0, 'Must be positive').describe('Full remaining external reimbursement in currency units (e.g. 48.50); must match leftToPay, not the expense total'),
35
+ confirmToken: confirmTokenParam,
36
+ }),
37
+ }, async (args, ctx) => {
38
+ const path = `/pub/v2/expense/expenses/${args.expenseId}`;
39
+ const read = async () => {
40
+ const d = parseLenient(detailSchema, await client.request('GET', path), { label: 'ofw-mcp', context: `GET ${path} (mark reimbursed)`, mode: 'strict' });
41
+ if (d.id !== args.expenseId)
42
+ throw new Error('Expense id does not match the requested expense');
43
+ return d;
44
+ };
45
+ let current;
46
+ try {
47
+ current = await read();
48
+ }
49
+ catch {
50
+ return jsonErrorResponse({ result: 'EXPENSE_REIMBURSEMENT_REFUSED', expenseId: args.expenseId,
51
+ reason: 'Could not safely read the expense identity, status, parties and balances. Nothing was sent.' });
52
+ }
53
+ const base = current.statusInfo.baseStatus;
54
+ if (base === 'PAID' && current.amount.leftToPay === 0) {
55
+ return jsonResponse({ result: 'ALREADY_PAID', expenseId: args.expenseId, changed: false,
56
+ note: 'OFW already reports paid with zero remaining balance. No write or money transfer was performed.' });
57
+ }
58
+ if (!['OPEN', 'APPROVED', 'PARTIAL'].includes(base) || current.amount.leftToPay <= 0) {
59
+ return jsonErrorResponse({ result: 'EXPENSE_REIMBURSEMENT_REFUSED', expenseId: args.expenseId,
60
+ reason: 'Only OPEN, APPROVED or PARTIAL expenses with subStatus NONE and positive remaining balance are supported. Nothing was sent.' });
61
+ }
62
+ if (Math.round(current.amount.leftToPay * 100) !== Math.round(args.expectedRemainingAmount * 100)) {
63
+ return jsonErrorResponse({ result: 'EXPENSE_REMAINING_AMOUNT_MISMATCH', expenseId: args.expenseId,
64
+ expectedRemainingAmount: args.expectedRemainingAmount, remainingAmount: current.amount.leftToPay,
65
+ total: current.amount.total, reason: 'Approve the full remaining balance, not the original expense total or a partial payment. Nothing was sent.' });
66
+ }
67
+ const payload = { status: 'MARKED_REIMBURSED' };
68
+ const revision = stateRevision(current);
69
+ const gate = await confirmWrite(ctx, {
70
+ args, tool: 'ofw_mark_expense_reimbursed', action: 'ofw.expense.mark-reimbursed',
71
+ target: `expense:${args.expenseId}`, revision, payload, confirmToken: args.confirmToken,
72
+ message: `Mark "${current.title}" fully reimbursed externally (${current.amount.leftToPay}). This cannot be undone and does not transfer money.`,
73
+ preview: { expenseId: args.expenseId, title: current.title, authorUserId: current.author.userId,
74
+ payerUserId: current.payer.userId, category: current.category, children: current.children,
75
+ private: current.private, total: current.amount.total, totalOwed: current.amount.totalOwed,
76
+ remainingAmount: current.amount.leftToPay, status: current.status, statusInfo: current.statusInfo,
77
+ paymentType: current.paymentType,
78
+ warning: 'Mark the FULL remaining balance reimbursed outside OFW. This cannot be undone. No money is transferred; no bank/payment action is performed.' },
79
+ });
80
+ if (gate)
81
+ return gate;
82
+ try {
83
+ if (stateRevision(await read()) !== revision) {
84
+ return jsonErrorResponse({ result: 'EXPENSE_CHANGED', expenseId: args.expenseId,
85
+ reason: 'The expense changed after confirmation. Nothing was sent. Review it again before confirming.' });
86
+ }
87
+ }
88
+ catch {
89
+ return jsonErrorResponse({ result: 'EXPENSE_REIMBURSEMENT_REFUSED', expenseId: args.expenseId,
90
+ reason: 'The immediate pre-write check failed. Nothing was sent.' });
91
+ }
92
+ try {
93
+ await requestWrite(client, 'PUT', `${path}/status`, payload);
94
+ }
95
+ catch (e) {
96
+ if (!(e instanceof UnconfirmedWriteError))
97
+ throw e;
98
+ return unconfirmedWriteResponse(e, { result: 'EXPENSE_REIMBURSEMENT_UNCONFIRMED',
99
+ what: `mark expense ${args.expenseId} reimbursed`, checkWith: 'the Expenses log on ourfamilywizard.com' });
100
+ }
101
+ try {
102
+ const after = await read();
103
+ if (after.statusInfo.baseStatus !== 'PAID' || after.amount.leftToPay !== 0
104
+ || after.paymentType !== 'Marked reimbursed' || immutableRevision(after) !== immutableRevision(current)) {
105
+ throw new Error('Paid status, external reimbursement marker, zero balance or unchanged expense fields could not be verified');
106
+ }
107
+ return jsonResponse({ result: 'EXPENSE_MARKED_REIMBURSED', expenseId: args.expenseId,
108
+ verified: true, reimbursedAmount: current.amount.leftToPay, remainingAmount: 0, moneyTransferred: false });
109
+ }
110
+ catch (e) {
111
+ return unconfirmedWriteResponse(new UnconfirmedWriteError(args.expenseId, e), {
112
+ result: 'EXPENSE_REIMBURSEMENT_UNCONFIRMED', what: `verify reimbursement of expense ${args.expenseId}`,
113
+ checkWith: 'the Expenses log on ourfamilywizard.com'
114
+ });
115
+ }
116
+ });
117
+ }
@@ -6,6 +6,7 @@ import { readUpstreamPaging } from './pagination.js';
6
6
  import { getExpenseUploadOnly, getWriteMode } from '../config.js';
7
7
  import { parseLenient } from '@chrischall/mcp-utils';
8
8
  import { RECEIPT_HOST_SUFFIX } from '../protocol.js';
9
+ import { registerExpenseReimbursementTool } from './expense-reimbursement.js';
9
10
  const UploadedExpenseFileSchema = z.looseObject({
10
11
  fileId: z.number(),
11
12
  fileName: z.string().optional(),
@@ -202,6 +203,8 @@ export function registerExpenseTools(server, client, attachmentIO) {
202
203
  ? 'the Expenses log on ourfamilywizard.com (ofw_list_expenses is not available in this deployment)'
203
204
  : 'ofw_list_expenses';
204
205
  const allowWrites = writeMode === 'all';
206
+ if (allowWrites && !uploadOnly)
207
+ registerExpenseReimbursementTool(server, client);
205
208
  // The receipt is uploaded SHARED (the only share class OFW accepts in an
206
209
  // expense's fileIds), and a SHARED My Files entry is co-parent-visible at
207
210
  // once — so, like ofw_upload_attachment's SHARED path, it needs mode 'all'.
@@ -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.6'; // x-release-please-version
7
+ export const VERSION = '2.22.0'; // x-release-please-version