ofw-mcp 2.21.0 → 2.23.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/index.js CHANGED
@@ -38,11 +38,12 @@ const nodeAttachmentIO = new NodeAttachmentIO();
38
38
  // always succeeds before any credential check runs.
39
39
  const expenseRegistrar = (server, deps) => registerExpenseTools(server, deps, nodeAttachmentIO);
40
40
  const messageRegistrar = (server, deps) => registerMessageTools(server, deps, nodeCacheProvider, nodeAttachmentIO);
41
+ const calendarRegistrar = (server, deps) => registerCalendarTools(server, deps, nodeAttachmentIO);
41
42
  const tools = selectToolRegistrars({
42
43
  healthcheck: registerHealthcheckTools,
43
44
  user: registerUserTools,
44
45
  messages: messageRegistrar,
45
- calendar: registerCalendarTools,
46
+ calendar: calendarRegistrar,
46
47
  expenses: expenseRegistrar,
47
48
  journal: registerJournalTools,
48
49
  });
@@ -43,6 +43,25 @@ export function displayTimeZone() {
43
43
  return configured;
44
44
  return DEFAULT_DISPLAY_TZ;
45
45
  }
46
+ // A per-call zone (a tool's `timeZone` argument), falling back to
47
+ // displayTimeZone() when none is given. DISPLAY_TZ is deployment-wide, so on a
48
+ // host serving several accounts it cannot be every account's zone; this is how
49
+ // one call says which zone ITS account is in. Unlike DISPLAY_TZ, an unusable
50
+ // value throws rather than falling back: the caller asked for this zone, and
51
+ // answering in another one would be wrong while looking right. A fixed offset
52
+ // is refused for the same reason the deployment default is never one.
53
+ export function resolveTimeZoneArg(tz) {
54
+ const requested = tz?.trim();
55
+ if (!requested)
56
+ return displayTimeZone();
57
+ if (/^(?:UTC|GMT)?[+-]\d/i.test(requested)) {
58
+ throw new Error(`timeZone "${requested}" is a fixed offset, which is an hour wrong for half the year once DST changes. Pass an IANA zone such as America/Chicago.`);
59
+ }
60
+ if (!isValidTimeZone(requested)) {
61
+ throw new Error(`timeZone "${requested}" is not a recognised IANA zone. Pass one such as America/Chicago or Europe/London.`);
62
+ }
63
+ return requested;
64
+ }
46
65
  // Offset of `tz` at a given instant, as "+HH:MM"/"-HH:MM". Uses the IANA
47
66
  // database via Intl, so DST is handled per-instant rather than per-zone.
48
67
  function offsetAt(instant, tz) {
@@ -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
  /**
@@ -21,15 +21,17 @@ import { normalizeTimestampsInValue } from '../timestamps.js';
21
21
  // content, and `JSON.stringify` never touches them; the rule is pinned by
22
22
  // tests here and in mcp-utils, so do not replace this with a text-level
23
23
  // minifier.
24
- export function jsonResponse(data) {
25
- return minifiedResult(normalizeTimestampsInValue(data));
24
+ //
25
+ // `tz` is a per-call zone (resolveTimeZoneArg); omitted, DISPLAY_TZ applies.
26
+ export function jsonResponse(data, tz) {
27
+ return minifiedResult(normalizeTimestampsInValue(data, tz));
26
28
  }
27
29
  // Raw-string tool result. Wrapper over @chrischall/mcp-utils' `rawTextResult`.
28
30
  export const textResponse = rawTextResult;
29
31
  // The JSON half of a mixed text response, through the same seam as
30
32
  // jsonResponse: timestamps normalized, no formatting whitespace.
31
- export function jsonText(data) {
32
- return JSON.stringify(normalizeTimestampsInValue(data));
33
+ export function jsonText(data, tz) {
34
+ return JSON.stringify(normalizeTimestampsInValue(data, tz));
33
35
  }
34
36
  // A write tool's result: its transparency NOTEs/WARNINGs (null entries are
35
37
  // skipped) ahead of the structured payload, or `fallback` when OFW returned
@@ -9,7 +9,7 @@
9
9
  // Keeping the interface here means src/tools/messages.ts imports nothing from
10
10
  // node:fs.
11
11
  import { chmodSync, readFileSync, realpathSync, statSync, mkdirSync, unlinkSync } from 'node:fs';
12
- import { basename, dirname, extname, isAbsolute, relative, resolve, sep } from 'node:path';
12
+ import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
13
13
  import { getDefaultAttachmentsDir, getUploadDir } from '../config.js';
14
14
  import { assertPathWithinRoots, expandPath, fileBlob, FileWriteRefusedError, sniffMimeBytes, writeFileSafe, } from '@chrischall/mcp-utils';
15
15
  /**
@@ -20,6 +20,26 @@ export function isWithin(root, candidate) {
20
20
  const rel = relative(root, candidate);
21
21
  return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel);
22
22
  }
23
+ /**
24
+ * Where a tool's `saveTo` lands: inside `root` (the attachments directory),
25
+ * or refused. A relative path resolves against `root`, a leading `~` expands,
26
+ * and a trailing separator names a directory to put `defaultName` in. Lexical
27
+ * only — `writeDownload` re-checks the real path, symlinks resolved, at write
28
+ * time. The write is the boundary; this is the early, legible refusal.
29
+ */
30
+ export function resolveSaveDest(root, saveTo, defaultName) {
31
+ if (!saveTo)
32
+ return join(root, defaultName);
33
+ const isDirArg = saveTo.endsWith('/') || saveTo.endsWith('\\');
34
+ // expandPath resolves a relative path against the process cwd; resolve it
35
+ // against the root instead, and only expand a leading ~.
36
+ const abs = resolve(root, saveTo.startsWith('~') ? expandPath(saveTo) : saveTo);
37
+ const dest = isDirArg ? join(abs, defaultName) : abs;
38
+ if (!isWithin(root, dest)) {
39
+ throw new Error(`Refusing to save to ${dest}: it is outside the attachments directory (${root}). Files can only be written inside it — pass a path or subdirectory under it, or set OFW_ATTACHMENTS_DIR to move it.`);
40
+ }
41
+ return dest;
42
+ }
23
43
  // Lightweight mime sniff from extension. OFW re-derives mime from the filename
24
44
  // server-side anyway, so this is just a polite Content-Type for the Blob.
25
45
  const MIME_BY_EXT = {
@@ -0,0 +1,250 @@
1
+ // OFW calendar → iCalendar (RFC 5545), plus the `types` filter shared with
2
+ // ofw_list_events' JSON path.
3
+ //
4
+ // What the detailed calendar endpoint actually returns (verified live
5
+ // 2026-10-28, sixteen months of one account): `calendarItems` holding EVENT
6
+ // rows (real ids, title, start/end), CONNECTED_EVENT rows (events from a
7
+ // subscribed outside calendar), and TRANSITION rows — the custody handoffs —
8
+ // beside `guardianData`, a per-day grid of who has the children. On that
9
+ // account TRANSITIONs were 68 of 71 items. OFW's own web export ("you will not
10
+ // be able to export your parenting schedule") leaves them out; here they are
11
+ // the point, so each run between two handoffs becomes one "Parenting time"
12
+ // event.
13
+ //
14
+ // TRANSITION quirks this file is built around:
15
+ // - every one carries `id: 1`, so a UID has to be derived, not copied;
16
+ // - each has a start and no end — a period is the gap to the NEXT handoff;
17
+ // - the first and last rows of a response are window-edge sentinels, with a
18
+ // null `transitionStartParent` (head) or `transitionEndParent` (tail), at a
19
+ // time OFW picks near the requested range, not at a real handoff.
20
+ //
21
+ // Times arrive as naive wall clock in the account's zone. They are read with
22
+ // parseTimestampValue in the caller's zone, the same reading every JSON
23
+ // response gets, and written in UTC, so no VTIMEZONE block is needed and every
24
+ // importer agrees on the instant.
25
+ import { parseTimestampValue } from '../timestamps.js';
26
+ export const CALENDAR_ITEM_TYPES = ['EVENT', 'CONNECTED_EVENT', 'TRANSITION', 'SCHEDULE'];
27
+ const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
28
+ function itemsOf(data) {
29
+ const items = isObject(data) ? data.calendarItems : undefined;
30
+ return Array.isArray(items) ? items.filter(isObject) : [];
31
+ }
32
+ /**
33
+ * Keep only the named item types. `SCHEDULE` names the `guardianData` grid
34
+ * (its entries are typed SCHEDULE), which is dropped unless asked for — it is
35
+ * most of a response's weight. No filter (or an empty one) returns the payload
36
+ * itself, so the default response is unchanged.
37
+ */
38
+ export function filterCalendarTypes(data, types) {
39
+ if (!types?.length || !isObject(data))
40
+ return data;
41
+ const wanted = new Set(types);
42
+ const { calendarItems: _items, guardianData, ...rest } = data;
43
+ const out = { ...rest };
44
+ if (Array.isArray(data.calendarItems)) {
45
+ out.calendarItems = data.calendarItems.filter((i) => isObject(i) && wanted.has(String(i.type)));
46
+ }
47
+ if (wanted.has('SCHEDULE') && guardianData !== undefined)
48
+ out.guardianData = guardianData;
49
+ return out;
50
+ }
51
+ function escapeText(value) {
52
+ return value.replace(/\\/g, '\\\\').replace(/\r\n|\r|\n/g, '\\n').replace(/;/g, '\\;').replace(/,/g, '\\,');
53
+ }
54
+ // RFC 5545 §3.1: lines longer than 75 OCTETS fold with CRLF + space, and a
55
+ // fold must not split a multi-byte UTF-8 character.
56
+ function fold(line) {
57
+ const out = [];
58
+ let current = '';
59
+ let size = 0;
60
+ for (const char of line) {
61
+ const bytes = Buffer.byteLength(char, 'utf8');
62
+ if (size + bytes > 75) {
63
+ out.push(current);
64
+ current = ' ';
65
+ size = 1;
66
+ }
67
+ current += char;
68
+ size += bytes;
69
+ }
70
+ out.push(current);
71
+ return out.join('\r\n');
72
+ }
73
+ const utcStamp = (d) => d.toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '');
74
+ function dateTimeOf(item, field) {
75
+ const value = item[field];
76
+ return isObject(value) && typeof value.dateTime === 'string' ? value.dateTime : undefined;
77
+ }
78
+ function instantOf(item, field, tz) {
79
+ const raw = dateTimeOf(item, field);
80
+ return raw === undefined ? null : parseTimestampValue(field, raw, tz);
81
+ }
82
+ // An all-day event's calendar date is the wall date OFW wrote (it pads all-day
83
+ // events with placeholder times, so the time part means nothing).
84
+ function wallDateOf(item, field) {
85
+ const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(dateTimeOf(item, field) ?? '');
86
+ return m && parseTimestampValue(field, `${m[0]}T00:00:00`, 'UTC') ? `${m[1]}${m[2]}${m[3]}` : null;
87
+ }
88
+ function nextDay(yyyymmdd) {
89
+ const d = new Date(Date.UTC(Number(yyyymmdd.slice(0, 4)), Number(yyyymmdd.slice(4, 6)) - 1, Number(yyyymmdd.slice(6)) + 1));
90
+ return d.toISOString().slice(0, 10).replace(/-/g, '');
91
+ }
92
+ const idOf = (item) => Number.isSafeInteger(item.id) && item.id > 0 ? item.id : null;
93
+ function parentOf(value) {
94
+ if (!isObject(value) || typeof value.userId !== 'number')
95
+ return null;
96
+ const name = typeof value.name === 'string' && value.name.trim() ? value.name.trim() : `parent ${value.userId}`;
97
+ return { userId: value.userId, name };
98
+ }
99
+ export function buildCalendarIcs(data, opts) {
100
+ const tz = opts.timeZone;
101
+ const stamp = utcStamp(opts.now ?? new Date());
102
+ const omitted = [];
103
+ const vevents = [];
104
+ // UID → what it was issued for, so a second row with the same identity is
105
+ // either told apart (by start) or recognised as the same event twice.
106
+ const issued = new Map();
107
+ let events = 0;
108
+ let custodyPeriods = 0;
109
+ const vevent = (uid, props) => ['BEGIN:VEVENT', `UID:${uid}@ofw-mcp`, `DTSTAMP:${stamp}`, ...props, 'END:VEVENT'];
110
+ const transitions = [];
111
+ for (const item of itemsOf(data)) {
112
+ const type = typeof item.type === 'string' ? item.type : null;
113
+ // A TRANSITION's id is always 1 — reporting it would name nothing.
114
+ const id = type === 'TRANSITION' ? null : idOf(item);
115
+ const omit = (reason) => omitted.push({ type, id, reason });
116
+ if (type === 'TRANSITION') {
117
+ const at = instantOf(item, 'startDate', tz);
118
+ if (!at) {
119
+ omit('unreadable_time');
120
+ continue;
121
+ }
122
+ transitions.push({ at, from: parentOf(item.transitionStartParent), to: parentOf(item.transitionEndParent) });
123
+ continue;
124
+ }
125
+ if (type !== 'EVENT' && type !== 'CONNECTED_EVENT') {
126
+ omit('unsupported_type');
127
+ continue;
128
+ }
129
+ if (id === null) {
130
+ omit('no_id');
131
+ continue;
132
+ }
133
+ let when;
134
+ let startKey;
135
+ let signature;
136
+ if (item.allDay === true) {
137
+ const start = wallDateOf(item, 'startDate');
138
+ const end = wallDateOf(item, 'endDate');
139
+ if (!start || !end) {
140
+ omit('unreadable_time');
141
+ continue;
142
+ }
143
+ if (end < start) {
144
+ omit('ends_before_start');
145
+ continue;
146
+ }
147
+ // DTEND is exclusive for DATE values: a one-day event ends the next day.
148
+ when = [`DTSTART;VALUE=DATE:${start}`, `DTEND;VALUE=DATE:${nextDay(end)}`];
149
+ startKey = start;
150
+ signature = `${start}/${end}`;
151
+ }
152
+ else {
153
+ const start = instantOf(item, 'startDate', tz);
154
+ const end = instantOf(item, 'endDate', tz);
155
+ if (!start || !end) {
156
+ omit('unreadable_time');
157
+ continue;
158
+ }
159
+ if (end < start) {
160
+ omit('ends_before_start');
161
+ continue;
162
+ }
163
+ when = [`DTSTART:${utcStamp(start)}`, `DTEND:${utcStamp(end)}`];
164
+ startKey = utcStamp(start);
165
+ signature = `${startKey}/${utcStamp(end)}`;
166
+ }
167
+ const title = typeof item.title === 'string' && item.title.trim() ? item.title : '(untitled)';
168
+ signature += `/${title}`;
169
+ // A connected event's id is only unique within its subscription.
170
+ const base = type === 'EVENT'
171
+ ? `ofw-event-${id}`
172
+ : `ofw-connected-${String(item.connectedCalendarSubscriptionId ?? 'unknown')}-${id}`;
173
+ // Occurrences of a repeating event share an id, so each is keyed by its
174
+ // start; a one-off keeps the bare id, so re-importing after an edit to
175
+ // its time updates the event rather than duplicating it.
176
+ let uid = item.repeating === true ? `${base}-${startKey}` : base;
177
+ if (issued.has(uid)) {
178
+ if (issued.get(uid) === signature) {
179
+ omit('duplicate');
180
+ continue;
181
+ }
182
+ uid = `${base}-${startKey}`;
183
+ if (issued.has(uid)) {
184
+ omit('duplicate');
185
+ continue;
186
+ }
187
+ }
188
+ issued.set(uid, signature);
189
+ const props = [...when, `SUMMARY:${escapeText(title)}`];
190
+ if (typeof item.location === 'string' && item.location.trim())
191
+ props.push(`LOCATION:${escapeText(item.location)}`);
192
+ if (typeof item.notes === 'string' && item.notes.trim())
193
+ props.push(`DESCRIPTION:${escapeText(item.notes)}`);
194
+ vevents.push(vevent(uid, props));
195
+ events += 1;
196
+ }
197
+ // Custody periods: each handoff opens a period for the parent it hands TO,
198
+ // which the next handoff closes. OFW does not promise row order.
199
+ transitions.sort((a, b) => a.at.getTime() - b.at.getTime());
200
+ transitions.forEach((t, i) => {
201
+ const owner = t.to;
202
+ if (!owner)
203
+ return; // a tail sentinel (or a gap) opens nothing
204
+ const next = transitions[i + 1];
205
+ if (!next) {
206
+ omitted.push({ type: 'TRANSITION', id: null, reason: 'no_end' });
207
+ return;
208
+ }
209
+ if (next.from && next.from.userId !== owner.userId) {
210
+ omitted.push({ type: 'TRANSITION', id: null, reason: 'handoff_mismatch' });
211
+ return;
212
+ }
213
+ const clippedHead = t.from === null;
214
+ const clippedTail = next.to === null;
215
+ // A head-clipped period's start is the window edge, not a handoff, so its
216
+ // identity hangs off its real END instead — otherwise every export with a
217
+ // different start date would mint a different UID for the same period.
218
+ const uid = clippedHead
219
+ ? `ofw-custody-${owner.userId}-until-${utcStamp(next.at)}`
220
+ : `ofw-custody-${owner.userId}-${utcStamp(t.at)}`;
221
+ const notes = [
222
+ clippedHead ? 'Starts before the exported range.' : `Handoff from ${t.from.name}.`,
223
+ ...(clippedTail ? ['Continues past the exported range.'] : []),
224
+ ];
225
+ vevents.push(vevent(uid, [
226
+ `DTSTART:${utcStamp(t.at)}`,
227
+ `DTEND:${utcStamp(next.at)}`,
228
+ `SUMMARY:${escapeText(`Parenting time: ${owner.name}`)}`,
229
+ `DESCRIPTION:${escapeText(notes.join(' '))}`,
230
+ 'TRANSP:TRANSPARENT',
231
+ ]));
232
+ custodyPeriods += 1;
233
+ });
234
+ const lines = [
235
+ 'BEGIN:VCALENDAR',
236
+ 'VERSION:2.0',
237
+ 'PRODID:-//ofw-mcp//Calendar//EN',
238
+ 'CALSCALE:GREGORIAN',
239
+ 'METHOD:PUBLISH',
240
+ 'X-WR-CALNAME:OurFamilyWizard',
241
+ `X-WR-TIMEZONE:${tz}`,
242
+ ...vevents.flat(),
243
+ 'END:VCALENDAR',
244
+ ];
245
+ return {
246
+ ics: lines.map(fold).join('\r\n') + '\r\n',
247
+ counts: { events, custodyPeriods, omitted: omitted.length },
248
+ omitted,
249
+ };
250
+ }
@@ -1,8 +1,14 @@
1
1
  import { z } from 'zod';
2
- import { jsonResponse, requestWrite, textResponse, UnconfirmedWriteError, unconfirmedWriteResponse } from './_shared.js';
2
+ import { jsonResponse, jsonText, requestWrite, textResponse, UnconfirmedWriteError, unconfirmedWriteResponse } from './_shared.js';
3
3
  import { CONFIRM_NOTE, confirmTokenParam, confirmWrite, stateRevision } from './_confirm.js';
4
- import { getCalendarWritesAllowed } from '../config.js';
4
+ import { getAttachmentsDir, getCalendarWritesAllowed } from '../config.js';
5
5
  import { parseLenient } from '@chrischall/mcp-utils';
6
+ import { blobStoreFromEnv } from '@chrischall/mcp-utils/export';
7
+ import { randomUUID } from 'node:crypto';
8
+ import { resolve } from 'node:path';
9
+ import { NodeAttachmentIO, resolveSaveDest } from './attachments.js';
10
+ import { buildCalendarIcs, CALENDAR_ITEM_TYPES, filterCalendarTypes } from './calendar-ics.js';
11
+ import { formatInstant, resolveTimeZoneArg } from '../timestamps.js';
6
12
  // OFW's real event-write API (reverse-engineered from the web app bundle):
7
13
  // POST /pub/v3/events create — 201 with the full event
8
14
  // GET /pub/v3/events/{eventRecurrenceId} detail
@@ -146,22 +152,128 @@ function namesIn(d) {
146
152
  }
147
153
  return names;
148
154
  }
149
- export function registerCalendarTools(server, client) {
155
+ const calendarRangeFields = {
156
+ startDate: z.string().describe('Start date YYYY-MM-DD'),
157
+ endDate: z.string().describe('End date YYYY-MM-DD'),
158
+ types: z.array(z.enum(CALENDAR_ITEM_TYPES)).describe('Keep only these: EVENT, CONNECTED_EVENT (from a subscribed outside calendar), TRANSITION (custody handoffs; in .ics they become "Parenting time" periods), SCHEDULE (the per-day custody grid, JSON only). Default: everything').optional(),
159
+ timeZone: z.string().describe("IANA zone of the user's OFW account, e.g. America/Chicago. OFW reports wall-clock times with no zone; this is the zone they are read and shown in. Default: the server's DISPLAY_TZ").optional(),
160
+ };
161
+ // GET /pub/v1/calendar/detailed, verified live 2026-10-28. Loose and lenient:
162
+ // only what the .ics builder reads, so a drift warns on stderr instead of
163
+ // quietly yielding an empty calendar. (The basic variant is a different shape
164
+ // and is passed through unvalidated, as it always was.)
165
+ const detailedCalendarSchema = z.looseObject({
166
+ calendarItems: z.array(z.looseObject({ type: z.string(), startDate: z.looseObject({ dateTime: z.string() }) })),
167
+ });
168
+ async function readDetailedCalendar(client, startDate, endDate) {
169
+ const path = `/pub/v1/calendar/detailed?startDate=${encodeURIComponent(startDate)}&endDate=${encodeURIComponent(endDate)}`;
170
+ return parseLenient(detailedCalendarSchema, await client.request('GET', path), { label: 'ofw-mcp', context: 'GET /pub/v1/calendar/detailed' });
171
+ }
172
+ // The JSON block every .ics delivery leads with. Counts come first, so a reader
173
+ // that stops early still learns what the calendar holds and what it dropped.
174
+ function icsSummary(built, args, timeZone) {
175
+ return {
176
+ format: 'ics',
177
+ events: built.counts.events,
178
+ custodyPeriods: built.counts.custodyPeriods,
179
+ omittedCount: built.counts.omitted,
180
+ startDate: args.startDate,
181
+ endDate: args.endDate,
182
+ timeZone,
183
+ ...(args.types?.length ? { types: args.types } : {}),
184
+ ...(built.omitted.length ? { omitted: built.omitted } : {}),
185
+ snapshot: 'Static: it does not update when OurFamilyWizard changes. Re-importing a later export updates events in place.',
186
+ };
187
+ }
188
+ export function registerCalendarTools(server, client, attachmentIO = new NodeAttachmentIO()) {
150
189
  // Calendar writes land on the court-visible record with no draft stage, but
151
190
  // events are reversible — 'all' mode, or 'drafts' + OFW_CALENDAR_WRITES=true.
152
191
  const allowWrites = getCalendarWritesAllowed();
153
192
  server.registerTool('ofw_list_events', {
154
- description: 'List OurFamilyWizard calendar events in a date range',
193
+ description: "List OurFamilyWizard calendar items in a date range: events, connected (subscribed outside-calendar) events, custody handoffs (TRANSITION) and the per-day custody grid (guardianData, type SCHEDULE). Pass `types` to keep only some of them — the custody grid is most of a response's weight, so leave SCHEDULE out unless you need who-has-the-children per day. Times are OFW wall clock in the account's zone, rendered with an offset in `timeZone` (default: the server's DISPLAY_TZ). format:\"ics\" returns an iCalendar (.ics) text you can show or save — events, all-day events, and each custody period as a \"Parenting time\" event — after a short JSON summary of what was included and what was left out. To get a file or download link instead, use ofw_save_calendar_ics.",
155
194
  annotations: { readOnlyHint: true, openWorldHint: true },
156
195
  inputSchema: z.object({
157
- startDate: z.string().describe('Start date YYYY-MM-DD'),
158
- endDate: z.string().describe('End date YYYY-MM-DD'),
159
- detailed: z.boolean().describe('Return full event details (default false)').optional(),
196
+ ...calendarRangeFields,
197
+ detailed: z.boolean().describe('Return full event details (default false). Ignored for format:"ics", which always reads the detailed calendar').optional(),
198
+ format: z.enum(['json', 'ics']).describe('json (default): the OFW payload. ics: a summary block, then the iCalendar text').optional(),
160
199
  }),
161
200
  }, async (args) => {
162
- const variant = args.detailed ? 'detailed' : 'basic';
163
- const data = await client.request('GET', `/pub/v1/calendar/${variant}?startDate=${encodeURIComponent(args.startDate)}&endDate=${encodeURIComponent(args.endDate)}`);
164
- return jsonResponse(data);
201
+ const timeZone = resolveTimeZoneArg(args.timeZone);
202
+ const ics = args.format === 'ics';
203
+ const raw = await (ics || args.detailed
204
+ ? readDetailedCalendar(client, args.startDate, args.endDate)
205
+ : client.request('GET', `/pub/v1/calendar/basic?startDate=${encodeURIComponent(args.startDate)}&endDate=${encodeURIComponent(args.endDate)}`));
206
+ const data = filterCalendarTypes(raw, args.types);
207
+ if (ics) {
208
+ const built = buildCalendarIcs(data, { timeZone });
209
+ return {
210
+ content: [
211
+ { type: 'text', text: jsonText(icsSummary(built, args, timeZone), timeZone) },
212
+ { type: 'text', text: built.ics },
213
+ ],
214
+ };
215
+ }
216
+ return jsonResponse(data, timeZone);
217
+ });
218
+ // File delivery lives on its own tool so ofw_list_events stays read-only:
219
+ // hosts auto-approve a read, and a tool that MAY write a file is not one.
220
+ server.registerTool('ofw_save_calendar_ics', {
221
+ description: "Save an OurFamilyWizard date range as an iCalendar (.ics) file the user can import into Google, Apple or Outlook calendar — events, all-day events, and each custody period as a \"Parenting time\" event (OFW's own export leaves the parenting schedule out). Same filters as ofw_list_events. On a hosted connector the file is uploaded and you get a private download link that expires (default 1 hour); locally it is written inside the attachments directory (OFW_ATTACHMENTS_DIR, default ~/Downloads/ofw-mcp) and you get its path. Never overwrites an existing file. The file is a snapshot: it does not update when OFW changes, and re-importing a later export updates events in place (stable UIDs).",
222
+ // Additive: it adds a new local file (or a new uploaded object) and never
223
+ // replaces one. Nothing reaches OFW.
224
+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true },
225
+ inputSchema: z.object({
226
+ ...calendarRangeFields,
227
+ saveTo: z.string().describe('Local installs only: path or directory (trailing /) INSIDE the attachments directory; relative paths resolve against it. Default: <attachments dir>/ofw-calendar-<start>_<end>-<time>.ics. Ignored on a hosted connector').optional(),
228
+ linkMinutes: z.number().int().min(1).max(1440).describe('Hosted connector only: how long the download link works, in minutes (default 60, max 1440)').optional(),
229
+ }),
230
+ }, async (args) => {
231
+ const timeZone = resolveTimeZoneArg(args.timeZone);
232
+ const data = filterCalendarTypes(await readDetailedCalendar(client, args.startDate, args.endDate), args.types);
233
+ const now = new Date();
234
+ const built = buildCalendarIcs(data, { timeZone, now });
235
+ const summary = icsSummary(built, args, timeZone);
236
+ const fileName = `ofw-calendar-${args.startDate}_${args.endDate}-${now.toISOString().replace(/[-:]/g, '').slice(0, 15)}Z.ics`;
237
+ // mcp-host hands a hosted child its blob store; its disk is the runner's,
238
+ // which nobody can open, so the link is the deliverable there. A local
239
+ // install has no blob store and writes to disk.
240
+ const blob = blobStoreFromEnv();
241
+ if (blob) {
242
+ // The random segment keeps the link unguessable; the readable last
243
+ // segment is the name a browser saves the download under.
244
+ const key = `calendar/${randomUUID()}/${fileName}`;
245
+ await blob.put(key, built.ics, 'text/calendar');
246
+ const link = blob.signGetUrl(key, { ttlMs: (args.linkMinutes ?? 60) * 60_000 });
247
+ return jsonResponse({
248
+ delivered: 'link',
249
+ url: link.url,
250
+ expiresAt: formatInstant(new Date(link.expiresAtMs), timeZone).iso,
251
+ ...summary,
252
+ note: `Private link to the .ics — anyone holding it can download the file until it expires, so give it only to the user.${args.saveTo ? ' saveTo is ignored on a hosted connector.' : ''}`,
253
+ }, timeZone);
254
+ }
255
+ if (!attachmentIO.supportsDisk) {
256
+ return {
257
+ content: [
258
+ { type: 'text', text: jsonText({ delivered: 'inline', forcedInline: true, ...summary, note: 'No disk or download store on this deployment, so the calendar is returned inline instead.' }, timeZone) },
259
+ { type: 'text', text: built.ics },
260
+ ],
261
+ };
262
+ }
263
+ const root = resolve(getAttachmentsDir());
264
+ const path = resolveSaveDest(root, args.saveTo, fileName);
265
+ try {
266
+ await attachmentIO.writeDownload(path, Buffer.from(built.ics, 'utf8'), { root, overwrite: false });
267
+ }
268
+ catch (e) {
269
+ // writeDownload's refusal names the download tool's force:true, which
270
+ // this tool does not have — an export never replaces a file.
271
+ if (e instanceof Error && /already exists/.test(e.message)) {
272
+ throw new Error(`Refusing to overwrite ${path}: a file already exists there. Choose another saveTo, or omit it for a fresh timestamped name.`);
273
+ }
274
+ throw e;
275
+ }
276
+ return jsonResponse({ delivered: 'disk', path, ...summary }, timeZone);
165
277
  });
166
278
  if (allowWrites)
167
279
  server.registerTool('ofw_create_event', {