@daywatch/mcp 0.1.2 → 0.5.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/server.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { readFileSync } from 'node:fs';
2
- import { RangeEvaluator, dateRange, scoreSchedule, } from '@daywatch/cal';
2
+ import { RangeEvaluator, dateRange, isFreeRange, scoreSchedule, } from '@daywatch/cal';
3
3
  import { detectDataWindow, generateICS, parseICS } from '@daywatch/ical';
4
4
  import { Server } from '@modelcontextprotocol/sdk/server/index.js';
5
5
  import { CallToolRequestSchema, ListToolsRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
6
+ import { VERSION } from './_version.js';
6
7
  import { gcalEventsToDateRanges } from './adapters/gcal.js';
7
8
  import { msftEventsToDateRanges } from './adapters/msft.js';
8
9
  import { CalendarSession } from './state.js';
@@ -30,9 +31,11 @@ TYPICAL AGENT WORKFLOW (when both daywatch-cal and a calendar MCP are available)
30
31
  Neo-reckoning is the thinking step between reading and writing. The source MCP is the hands.
31
32
 
32
33
  LOADING DATA:
33
- - File on disk → load_calendar_file (pass the path — never read .ics files into conversation yourself)
34
- - Google Calendar → load_calendar with source "gcal" and the raw JSON array from gcal_list_events. Auto-filters transparent, declined, working-location events.
35
- - Microsoft Outlook / Office 365 → load_calendar with source "msft" and the raw JSON array from Microsoft Graph. Auto-filters free, workingElsewhere, declined, cancelled events. Maps Windows timezones to IANA.
34
+ - File on disk → load_calendar_file (pass the path). Handles .ics (default) and gcal/msft JSON via the "source" param — use it whenever the data is already on disk (e.g. a list_events result too large to pass inline); never read large calendar files into the conversation yourself.
35
+ - Feed URL (incident.io schedule feeds, published .ics links, webcal) → load_calendar_url with the url. The server fetches it directly — never fetch the feed yourself (curl/WebFetch) and paste it inline.
36
+ - Google Calendar → load_calendar with source "gcal" and the raw JSON array from gcal_list_events. Excludes declined, cancelled, working-location and birthday events; transparent/FYI events load with a transparency flag so conflict detection treats them as free.
37
+ - Microsoft Outlook / Office 365 → load_calendar with source "msft" and the raw JSON array from Microsoft Graph. Excludes declined, cancelled and seriesMaster events; free/workingElsewhere events load with a busy/free flag so conflict detection treats them as free. Maps Windows timezones to IANA.
38
+ - Always feed gcal/msft data through its native source. Do NOT pre-flatten it to "ranges" yourself — you lose the transparency carrying, the declined/working-location filtering, and the per-event timezone reconciliation, all of which silently corrupt conflict detection and scoring (wrong busy/free, events at the wrong wall-clock hour).
36
39
  - Raw .ics text or pasted data → load_calendar with source "ics"
37
40
  - Pre-built DateRange JSON → load_calendar with source "ranges"
38
41
  - Data persists for the session — load once, query many times.
@@ -40,6 +43,7 @@ LOADING DATA:
40
43
  - The server auto-detects the right time window for historical calendars (e.g. a past school year).
41
44
 
42
45
  ANALYZING:
46
+ - list_ranges — inventory of what's loaded: range ids, labels, date bounds, recurrence summaries. gcal/msft recurring-event instances are grouped into one row per series. Use this (not your own .ics parsing) to answer "what's in this calendar?"
43
47
  - find_conflicts — overlapping events in a date range, with overlap details
44
48
  - find_free_slots — open time on a specific day (defaults to 09:00–17:00)
45
49
  - find_next_free_slot — first available slot of a given duration
@@ -70,7 +74,8 @@ LARGE CALENDARS:
70
74
  - Use window_from/window_to to limit the parse range when you know the relevant period.
71
75
  - Query narrow date ranges (1–2 weeks) rather than broad multi-month windows.
72
76
  - Use day_detail for single-day deep dives.
73
- - find_conflicts, find_free_slots, day_detail, and expand_range accept a limit parameter.`;
77
+ - find_conflicts, find_free_slots, day_detail, and expand_range accept a limit parameter.
78
+ - If a source list_events result is too big to read back into context, it has almost always been saved to a file on disk — load it directly with load_calendar_file({path, source: "gcal" | "msft"}), which reads the file itself and never routes the contents through the conversation. It accepts either the raw result object ({events: [...]}) or a bare events array. Do NOT trim, flatten, or hand-convert it to fit inline. Only if the data is *not* on disk and must be inlined should you slice it by date window at the source (e.g. jq) and load with its native source — never "ranges".`;
74
79
  const PROPOSED_CHANGE_SCHEMA = {
75
80
  type: 'object',
76
81
  properties: {
@@ -119,7 +124,7 @@ export const TOOLS = [
119
124
  },
120
125
  data: {
121
126
  type: 'string',
122
- description: 'For source "ics": raw .ics calendar text. For source "ranges": JSON DateRange array (example: [{"id":"mtg1","label":"Team Sync","fromDate":"2026-03-30","toDate":"2026-03-30","startTime":"09:00","endTime":"10:00"}]). NOTE: use fromDate/toDate/startTime/endTime — NOT start/end. For source "gcal": JSON array from Google Calendar MCP gcal_list_events — events are auto-filtered (declined, transparent, working-location excluded) and converted to DateRange format. For source "msft": JSON array from Microsoft Graph Calendar API list events endpoint — events are auto-filtered (free, workingElsewhere, declined, cancelled, seriesMaster excluded) and Windows timezones are mapped to IANA.',
127
+ description: 'For source "ics": raw .ics calendar text. For source "ranges": JSON DateRange array (example: [{"id":"mtg1","label":"Team Sync","fromDate":"2026-03-30","toDate":"2026-03-30","startTime":"09:00","endTime":"10:00"}]). NOTE: use fromDate/toDate/startTime/endTime — NOT start/end. For source "gcal": JSON array from Google Calendar MCP gcal_list_events — declined, cancelled, working-location and birthday events are excluded, transparent events are kept with a transparency flag (free — never conflicts or occupies free slots), and everything is converted to DateRange format. For source "msft": JSON array from Microsoft Graph Calendar API list events endpoint — declined, cancelled and seriesMaster events are excluded, free/workingElsewhere events are kept with a busy/free flag (never conflicts or occupies free slots), and Windows timezones are mapped to IANA. IMPORTANT: pass gcal/msft events through their native source — do NOT hand-convert them to "ranges" yourself. Flattening drops the transparency/declined filtering and the per-event timezone reconciliation this tool does for you (events stored in a different tz than their UTC offset will land at the wrong wall-clock time). If the upstream list_events payload is too large to bring into context, do NOT pass it through `data` at all — it has usually been saved to a file, so use load_calendar_file({path, source}) which reads it off disk. Only when the data is not on disk and must be inlined: slice it by date window at the source (e.g. jq on the saved result) and feed that native gcal/msft JSON — keep start/end/timeZone, eventType, transparency, and attendee responseStatus; only the heavy fields (description, htmlLink, conferenceData) are safe to strip.',
123
128
  },
124
129
  id: {
125
130
  type: 'string',
@@ -143,13 +148,18 @@ export const TOOLS = [
143
148
  },
144
149
  {
145
150
  name: 'load_calendar_file',
146
- description: 'Load an .ics file from disk by path. Preferred over load_calendar when the user provides a file path — avoids passing large file contents through the conversation.',
151
+ description: 'Load a calendar file from disk by path — `.ics` text, or Google Calendar / Microsoft Graph JSON (set `source`). Preferred over load_calendar whenever the data is already on disk (e.g. a list_events result too large to pass inline) — it reads the file directly instead of routing the contents through the conversation. gcal/msft JSON may be either a bare array of events or the raw result object with an `events` array.',
147
152
  inputSchema: {
148
153
  type: 'object',
149
154
  properties: {
150
155
  path: {
151
156
  type: 'string',
152
- description: 'Absolute path to the .ics file on disk.',
157
+ description: 'Absolute path to the calendar file on disk.',
158
+ },
159
+ source: {
160
+ type: 'string',
161
+ enum: ['ics', 'gcal', 'msft'],
162
+ description: 'File format: "ics" (default) for .ics text, "gcal" for a Google Calendar list_events JSON file, "msft" for a Microsoft Graph events JSON file. gcal/msft are filtered and converted exactly as in load_calendar.',
153
163
  },
154
164
  id: {
155
165
  type: 'string',
@@ -171,9 +181,39 @@ export const TOOLS = [
171
181
  required: ['path'],
172
182
  },
173
183
  },
184
+ {
185
+ name: 'load_calendar_url',
186
+ description: 'Fetch an .ics calendar feed from a URL and load it into the current session — incident.io schedule feeds, published Google/Outlook .ics links, any https or webcal feed. The server fetches the URL itself: do NOT fetch the feed with curl/WebFetch and paste the text through load_calendar. Plain http is allowed only for localhost. Feed URLs often embed auth tokens; they are redacted from results and errors.',
187
+ inputSchema: {
188
+ type: 'object',
189
+ properties: {
190
+ url: {
191
+ type: 'string',
192
+ description: 'The feed URL. https or webcal (plain http is allowed for localhost only). Must return iCalendar (.ics) data.',
193
+ },
194
+ id: {
195
+ type: 'string',
196
+ description: 'Optional calendar identifier. Defaults to calendar-N.',
197
+ },
198
+ timezone: {
199
+ type: 'string',
200
+ description: 'Optional IANA timezone to use for the session evaluator.',
201
+ },
202
+ window_from: {
203
+ type: 'string',
204
+ description: 'Optional parse window start date (YYYY-MM-DD). Must be paired with window_to.',
205
+ },
206
+ window_to: {
207
+ type: 'string',
208
+ description: 'Optional parse window end date (YYYY-MM-DD). Must be paired with window_from.',
209
+ },
210
+ },
211
+ required: ['url'],
212
+ },
213
+ },
174
214
  {
175
215
  name: 'find_conflicts',
176
- description: 'Find timed conflicts across loaded calendars within a date window.',
216
+ description: 'Find timed conflicts across loaded calendars within a date window. Busy all-day spans count as full-day occupancy (00:00–24:00) and conflict with anything that day; free/transparent spans never conflict. Each side carries allDay/eventType metadata when present so severity can be graded.',
177
217
  inputSchema: {
178
218
  type: 'object',
179
219
  properties: {
@@ -419,6 +459,47 @@ export const TOOLS = [
419
459
  properties: {},
420
460
  },
421
461
  },
462
+ {
463
+ name: 'list_ranges',
464
+ description: 'List the stored DateRanges across loaded calendars with summary metadata — ids, labels, date bounds, recurrence summaries. Use after load_calendar to see what a calendar contains without expanding occurrences or re-parsing source data. Recurring-event instances from gcal/msft are grouped into one row per series by default (group_by "series"). Each calendar reports its effective_window — for ics sources, ranges with explicit dates may be clipped to that window.',
465
+ inputSchema: {
466
+ type: 'object',
467
+ properties: {
468
+ calendars: {
469
+ type: 'array',
470
+ items: { type: 'string' },
471
+ description: 'Optional list of calendar ids to include. Defaults to all loaded calendars.',
472
+ },
473
+ label_match: {
474
+ type: 'string',
475
+ description: 'Optional case-insensitive regular expression to filter rows by label.',
476
+ },
477
+ group_by: {
478
+ type: 'string',
479
+ enum: ['series', 'none'],
480
+ description: 'How to group gcal/msft recurring-event instances that share a series id. "series" (default) collapses them into one row with occurrence_count and a representative range_id; "none" returns one row per stored range.',
481
+ },
482
+ occurrence_unit: {
483
+ type: 'string',
484
+ enum: ['events', 'days'],
485
+ description: 'Unit for occurrence_count. "events" (default) counts individual occurrences — two instances or time slots on the same day count as 2. "days" counts distinct dates touched.',
486
+ },
487
+ count_within: {
488
+ type: 'object',
489
+ properties: {
490
+ from: { type: 'string', description: 'Window start as an ISO date (YYYY-MM-DD).' },
491
+ to: { type: 'string', description: 'Window end as an ISO date (YYYY-MM-DD).' },
492
+ },
493
+ required: ['from', 'to'],
494
+ description: 'Optional bounded window (max 2 years). When provided, recurring rows get occurrence_count, first_occurrence, and last_occurrence computed within this window. Does not filter rows. Omit it for a cheap structural listing.',
495
+ },
496
+ limit: {
497
+ type: 'number',
498
+ description: 'Maximum rows to return. Defaults to 50.',
499
+ },
500
+ },
501
+ },
502
+ },
422
503
  {
423
504
  name: 'suggest_changes',
424
505
  description: 'Preview schedule changes with before/after scoring and conflict counts without mutating session state.',
@@ -769,6 +850,160 @@ function rangeOverlapsDateFilter(range, from, to) {
769
850
  }
770
851
  return true;
771
852
  }
853
+ const MAX_COUNT_WINDOW_DAYS = 731;
854
+ const MAX_LABEL_MATCH_LENGTH = 256;
855
+ function hasRecurrencePattern(range) {
856
+ return Boolean(range.everyWeekday?.length ||
857
+ range.everyDate?.length ||
858
+ range.everyMonth?.length ||
859
+ range.everyHour?.length);
860
+ }
861
+ function getSeriesId(range) {
862
+ const metadata = getMetadataRecord(range);
863
+ const seriesId = metadata?.recurringEventId ?? metadata?.seriesMasterId;
864
+ return typeof seriesId === 'string' && seriesId !== '' ? seriesId : undefined;
865
+ }
866
+ function buildListRangeRow(calendarId, range, isPattern) {
867
+ const window = getRangeDateWindow(range);
868
+ const unbounded = isPattern && !range.toDate && !range.dates?.length;
869
+ const recurrenceSummary = buildRecurrenceSummary(range);
870
+ const metadata = getMetadataRecord(range);
871
+ const attendees = getRangeAttendees(range);
872
+ const organizer = getRangeOrganizer(range);
873
+ return {
874
+ calendar_id: calendarId,
875
+ range_id: range.id,
876
+ label: range.label,
877
+ ...(window?.from ? { from_date: window.from } : {}),
878
+ ...(unbounded ? { to_date: null, unbounded: true } : window?.to ? { to_date: window.to } : {}),
879
+ ...(recurrenceSummary ? { recurrence_summary: recurrenceSummary } : {}),
880
+ ...(range.startTime ? { start_time: range.startTime } : {}),
881
+ ...(range.endTime ? { end_time: range.endTime } : {}),
882
+ all_day: !range.startTime && !range.everyHour?.length,
883
+ ...(range.timezone !== undefined ? { timezone: range.timezone } : {}),
884
+ ...(range.dates?.length
885
+ ? { occurrence_count: range.dates.length }
886
+ : isPattern
887
+ ? {}
888
+ : { occurrence_count: 1 }),
889
+ ...(typeof metadata?.location === 'string' ? { location: metadata.location } : {}),
890
+ ...(typeof metadata?.status === 'string' ? { status: metadata.status } : {}),
891
+ ...(isFreeRange(range) ? { transparent: true } : {}),
892
+ ...(attendees ? { has_attendees: true } : {}),
893
+ ...(organizer ? { organizer_email: organizer.email } : {}),
894
+ };
895
+ }
896
+ function countByUnit(occurrenceDates, unit) {
897
+ return unit === 'days' ? new Set(occurrenceDates).size : occurrenceDates.length;
898
+ }
899
+ function buildSeriesGroupEntry(calendarId, seriesId, instances, unit) {
900
+ const sorted = [...instances].sort((left, right) => (getRangeDateWindow(left)?.from ?? '').localeCompare(getRangeDateWindow(right)?.from ?? ''));
901
+ const representative = sorted[0];
902
+ const fromDates = sorted
903
+ .map((range) => getRangeDateWindow(range)?.from)
904
+ .filter((value) => Boolean(value));
905
+ const toDates = sorted
906
+ .map((range) => getRangeDateWindow(range)?.to)
907
+ .filter((value) => Boolean(value))
908
+ .sort();
909
+ return {
910
+ row: {
911
+ ...buildListRangeRow(calendarId, representative, hasRecurrencePattern(representative)),
912
+ series_id: seriesId,
913
+ ...(fromDates.length > 0 ? { from_date: fromDates[0] } : {}),
914
+ ...(toDates.length > 0 ? { to_date: toDates[toDates.length - 1] } : {}),
915
+ occurrence_count: unit === 'days' ? countByUnit(fromDates, 'days') : sorted.length,
916
+ },
917
+ ranges: sorted,
918
+ isPattern: false,
919
+ };
920
+ }
921
+ function buildListRangeEntries(session, calendarIds, options) {
922
+ const entries = [];
923
+ for (const calendarId of calendarIds) {
924
+ // calendarIds are pre-validated, so the calendar always exists.
925
+ const calendar = session.calendars.get(calendarId);
926
+ const labelRegex = options.labelRegex;
927
+ const matching = labelRegex
928
+ ? calendar.ranges.filter((range) => labelRegex.test(range.label))
929
+ : calendar.ranges;
930
+ const seriesGroups = new Map();
931
+ for (const range of matching) {
932
+ const seriesId = options.groupBy === 'series' ? getSeriesId(range) : undefined;
933
+ if (!seriesId) {
934
+ const isPattern = hasRecurrencePattern(range);
935
+ entries.push({
936
+ row: buildListRangeRow(calendarId, range, isPattern),
937
+ ranges: [range],
938
+ isPattern,
939
+ });
940
+ continue;
941
+ }
942
+ const group = seriesGroups.get(seriesId);
943
+ if (group) {
944
+ group.push(range);
945
+ }
946
+ else {
947
+ seriesGroups.set(seriesId, [range]);
948
+ }
949
+ }
950
+ for (const [seriesId, instances] of seriesGroups) {
951
+ entries.push(buildSeriesGroupEntry(calendarId, seriesId, instances, options.unit));
952
+ }
953
+ }
954
+ return entries;
955
+ }
956
+ function annotateOccurrences(evaluator, entry, from, to, unit) {
957
+ const withOccurrenceDates = (occurrenceDates) => ({
958
+ ...entry.row,
959
+ occurrence_count: countByUnit(occurrenceDates, unit),
960
+ ...(occurrenceDates.length > 0
961
+ ? {
962
+ first_occurrence: occurrenceDates[0],
963
+ last_occurrence: occurrenceDates[occurrenceDates.length - 1],
964
+ }
965
+ : {}),
966
+ });
967
+ if (entry.row.series_id) {
968
+ const overlapping = entry.ranges.filter((range) => rangeOverlapsDateFilter(range, from, to));
969
+ return withOccurrenceDates(overlapping
970
+ .map((range) => getRangeDateWindow(range)?.from)
971
+ .filter((value) => Boolean(value))
972
+ .sort());
973
+ }
974
+ const range = entry.ranges[0];
975
+ if (range.dates?.length) {
976
+ return withOccurrenceDates(range.dates.filter((date) => date >= from && date <= to).sort());
977
+ }
978
+ if (entry.isPattern) {
979
+ const occurrences = evaluator.expand(range, parseDateArgument(from), parseDateArgument(to));
980
+ return withOccurrenceDates(occurrences.map((occurrence) => occurrence.date).sort());
981
+ }
982
+ // Single non-recurring event: one occurrence if its span touches the window.
983
+ const window = getRangeDateWindow(range);
984
+ return withOccurrenceDates(window && rangeOverlapsDateFilter(range, from, to) ? [window.from] : []);
985
+ }
986
+ function parseCountWithin(value) {
987
+ if (value === undefined) {
988
+ return undefined;
989
+ }
990
+ const record = requireRecord(value, 'count_within');
991
+ const from = requireString(record, 'from');
992
+ const to = requireString(record, 'to');
993
+ const fromDate = parseDateArgument(from);
994
+ const toDate = parseDateArgument(to);
995
+ if (Number.isNaN(fromDate.getTime()) || Number.isNaN(toDate.getTime())) {
996
+ throw new Error('"count_within" dates must be valid YYYY-MM-DD values.');
997
+ }
998
+ if (toDate < fromDate) {
999
+ throw new Error('"count_within.to" must not be before "count_within.from".');
1000
+ }
1001
+ const spanDays = Math.round((toDate.getTime() - fromDate.getTime()) / 86_400_000);
1002
+ if (spanDays > MAX_COUNT_WINDOW_DAYS) {
1003
+ throw new Error(`"count_within" must span at most ${MAX_COUNT_WINDOW_DAYS} days. Use a narrower window.`);
1004
+ }
1005
+ return { from, to };
1006
+ }
772
1007
  function shiftDay(dateStr, delta) {
773
1008
  const [year, month, day] = dateStr.split('-').map(Number);
774
1009
  const next = new Date(year, month - 1, day + delta);
@@ -1070,8 +1305,195 @@ function loadIcsData(icsText, requestedWindow) {
1070
1305
  }
1071
1306
  return { ranges, effectiveWindow, detectedWindow };
1072
1307
  }
1308
+ const FEED_FETCH_TIMEOUT_MS = 30_000;
1309
+ const MAX_FEED_BYTES = 20 * 1024 * 1024;
1310
+ const MAX_FEED_REDIRECTS = 5;
1311
+ const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
1312
+ // Feed URLs often embed auth tokens (incident.io puts one in the path), so
1313
+ // anything echoed back to the caller hides long path segments and the query.
1314
+ function redactFeedUrl(raw) {
1315
+ let url;
1316
+ try {
1317
+ url = new URL(raw);
1318
+ }
1319
+ catch {
1320
+ return '<invalid url>';
1321
+ }
1322
+ const path = url.pathname
1323
+ .split('/')
1324
+ .map((segment) => (segment.length > 16 ? '…' : segment))
1325
+ .join('/');
1326
+ return `${url.origin}${path}${url.search ? '?…' : ''}`;
1327
+ }
1328
+ function isLoopbackHost(hostname) {
1329
+ // URL#hostname keeps the brackets on IPv6 literals, so '[::1]' is the form
1330
+ // that reaches us; shorthand IPv4 literals (127.1, 0x7f000001) are already
1331
+ // normalized to 127.0.0.1 by the URL parser.
1332
+ return (hostname === 'localhost' ||
1333
+ hostname.endsWith('.localhost') ||
1334
+ hostname === '127.0.0.1' ||
1335
+ hostname === '[::1]');
1336
+ }
1337
+ function parseFeedUrl(raw) {
1338
+ let url;
1339
+ try {
1340
+ url = new URL(raw);
1341
+ }
1342
+ catch {
1343
+ throw new Error('"url" is not a valid URL.');
1344
+ }
1345
+ // webcal:// is how calendar apps advertise .ics feeds; it is plain https.
1346
+ if (url.protocol === 'webcal:') {
1347
+ url = new URL(url.href.replace(/^webcal:/, 'https:'));
1348
+ }
1349
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') {
1350
+ throw new Error(`"url" must be an https or webcal URL. Got "${url.protocol}//".`);
1351
+ }
1352
+ if (url.protocol === 'http:' && !isLoopbackHost(url.hostname)) {
1353
+ throw new Error('Plain http is only allowed for localhost — feed URLs often carry auth tokens. Use https.');
1354
+ }
1355
+ return url;
1356
+ }
1357
+ async function readBodyCapped(response, redactedUrl) {
1358
+ if (!response.body) {
1359
+ return '';
1360
+ }
1361
+ const reader = response.body.getReader();
1362
+ const chunks = [];
1363
+ let totalBytes = 0;
1364
+ for (;;) {
1365
+ const { done, value } = await reader.read();
1366
+ if (done) {
1367
+ break;
1368
+ }
1369
+ totalBytes += value.byteLength;
1370
+ if (totalBytes > MAX_FEED_BYTES) {
1371
+ await reader.cancel();
1372
+ throw new Error(`Response from ${redactedUrl} exceeded the ${MAX_FEED_BYTES / 1024 / 1024} MB feed size limit.`);
1373
+ }
1374
+ chunks.push(value);
1375
+ }
1376
+ const merged = new Uint8Array(totalBytes);
1377
+ let offset = 0;
1378
+ for (const chunk of chunks) {
1379
+ merged.set(chunk, offset);
1380
+ offset += chunk.byteLength;
1381
+ }
1382
+ return new TextDecoder().decode(merged);
1383
+ }
1384
+ function isTimeoutError(error) {
1385
+ return (error instanceof DOMException && (error.name === 'TimeoutError' || error.name === 'AbortError'));
1386
+ }
1387
+ function describeFetchFailure(error) {
1388
+ const cause = error.cause;
1389
+ return cause?.code ?? cause?.message ?? (error instanceof Error ? error.message : String(error));
1390
+ }
1391
+ async function fetchFeedText(initialUrl) {
1392
+ let url = initialUrl;
1393
+ let redirects = 0;
1394
+ for (;;) {
1395
+ const redactedUrl = redactFeedUrl(url.href);
1396
+ let response;
1397
+ try {
1398
+ response = await fetch(url, {
1399
+ redirect: 'manual',
1400
+ signal: AbortSignal.timeout(FEED_FETCH_TIMEOUT_MS),
1401
+ headers: {
1402
+ 'user-agent': `daywatch-mcp/${VERSION}`,
1403
+ accept: 'text/calendar, text/plain;q=0.9, */*;q=0.8',
1404
+ },
1405
+ });
1406
+ }
1407
+ catch (error) {
1408
+ if (isTimeoutError(error)) {
1409
+ throw new Error(`Request to ${redactedUrl} timed out after ${FEED_FETCH_TIMEOUT_MS / 1000}s.`);
1410
+ }
1411
+ throw new Error(`Could not reach ${redactedUrl}: ${describeFetchFailure(error)}`, {
1412
+ cause: error,
1413
+ });
1414
+ }
1415
+ // Redirects are followed manually so every hop is re-validated against
1416
+ // the same scheme/host policy as the initial URL — automatic following
1417
+ // would let an allowed URL redirect into disallowed http hosts.
1418
+ if (REDIRECT_STATUSES.has(response.status)) {
1419
+ await response.body?.cancel();
1420
+ const location = response.headers.get('location');
1421
+ if (!location) {
1422
+ throw new Error(`Request to ${redactedUrl} redirected (HTTP ${response.status}) without a Location header.`);
1423
+ }
1424
+ redirects += 1;
1425
+ if (redirects > MAX_FEED_REDIRECTS) {
1426
+ throw new Error(`Request to ${redactedUrl} exceeded ${MAX_FEED_REDIRECTS} redirects.`);
1427
+ }
1428
+ try {
1429
+ url = parseFeedUrl(new URL(location, url).href);
1430
+ }
1431
+ catch (error) {
1432
+ throw new Error(`Redirect from ${redactedUrl} points to a disallowed URL: ${error instanceof Error ? error.message : String(error)}`);
1433
+ }
1434
+ continue;
1435
+ }
1436
+ if (!response.ok) {
1437
+ const authHint = response.status === 401 || response.status === 403
1438
+ ? ' The feed may require a valid auth token in the URL.'
1439
+ : '';
1440
+ throw new Error(`Request to ${redactedUrl} failed with HTTP ${response.status}.${authHint}`);
1441
+ }
1442
+ let text;
1443
+ try {
1444
+ text = await readBodyCapped(response, redactedUrl);
1445
+ }
1446
+ catch (error) {
1447
+ if (isTimeoutError(error)) {
1448
+ throw new Error(`Request to ${redactedUrl} timed out after ${FEED_FETCH_TIMEOUT_MS / 1000}s.`);
1449
+ }
1450
+ if (error instanceof TypeError) {
1451
+ throw new Error(`Connection failed while downloading from ${redactedUrl}: ${describeFetchFailure(error)}`, { cause: error });
1452
+ }
1453
+ throw error;
1454
+ }
1455
+ return {
1456
+ text,
1457
+ contentType: response.headers.get('content-type') ?? '',
1458
+ redactedUrl,
1459
+ };
1460
+ }
1461
+ }
1462
+ // Sniff the body instead of trusting Content-Type — real-world feeds serve
1463
+ // text/calendar, text/plain, even application/octet-stream.
1464
+ function ensureIcsBody(text, contentType, redactedUrl) {
1465
+ // No BOM handling needed: TextDecoder in readBodyCapped already strips it.
1466
+ const trimmed = text.trimStart();
1467
+ if (trimmed === '') {
1468
+ throw new Error(`Fetched 0 bytes from ${redactedUrl} — the URL returned an empty response. Verify the feed URL (and its token) is correct.`);
1469
+ }
1470
+ if (!trimmed.startsWith('BEGIN:VCALENDAR')) {
1471
+ const head = trimmed.slice(0, 256).toLowerCase();
1472
+ if (head.startsWith('<!doctype') || head.startsWith('<html')) {
1473
+ throw new Error(`${redactedUrl} returned HTML (content-type: ${contentType || 'unknown'}) — likely a login or web page, not an .ics feed. The URL may require authentication.`);
1474
+ }
1475
+ throw new Error(`${redactedUrl} did not return iCalendar data (content-type: ${contentType || 'unknown'}; expected the body to start with BEGIN:VCALENDAR).`);
1476
+ }
1477
+ return trimmed;
1478
+ }
1479
+ // Accept either a bare event array or a provider result object that wraps one
1480
+ // (e.g. a saved gcal/msft list_events response: `{ events: [...] }`).
1481
+ function extractEventsArray(data, label) {
1482
+ const parsed = JSON.parse(data);
1483
+ if (Array.isArray(parsed)) {
1484
+ return parsed;
1485
+ }
1486
+ if (parsed !== null &&
1487
+ typeof parsed === 'object' &&
1488
+ Array.isArray(parsed.events)) {
1489
+ return parsed.events;
1490
+ }
1491
+ throw new Error(`${label} JSON must be an array of events, or an object with an "events" array.`);
1492
+ }
1073
1493
  function buildLoadResponse(session, ranges, calendarId, source, effectiveWindow, detectedWindow) {
1074
- session.loadCalendar(calendarId, ranges, source);
1494
+ // Only ics parsing clips data to a window; other sources load whole.
1495
+ const storedWindow = source === 'ics' ? formatWindow(effectiveWindow) : null;
1496
+ session.loadCalendar(calendarId, ranges, source, storedWindow);
1075
1497
  const labelSummary = collectUniqueLabels(ranges, 20);
1076
1498
  return jsonResult({
1077
1499
  calendars_loaded: session.calendars.size,
@@ -1136,10 +1558,14 @@ export async function handleToolCall(session, name, rawArgs) {
1136
1558
  }
1137
1559
  case 'load_calendar_file': {
1138
1560
  const filePath = requireString(args, 'path');
1561
+ const source = optionalString(args, 'source') ?? 'ics';
1139
1562
  const id = optionalString(args, 'id');
1140
1563
  const timezone = optionalString(args, 'timezone');
1141
1564
  const windowFrom = optionalString(args, 'window_from');
1142
1565
  const windowTo = optionalString(args, 'window_to');
1566
+ if (source !== 'ics' && source !== 'gcal' && source !== 'msft') {
1567
+ throw new Error('"source" must be "ics", "gcal", or "msft".');
1568
+ }
1143
1569
  if ((windowFrom && !windowTo) || (!windowFrom && windowTo)) {
1144
1570
  throw new Error('"window_from" and "window_to" must be provided together.');
1145
1571
  }
@@ -1152,7 +1578,39 @@ export async function handleToolCall(session, name, rawArgs) {
1152
1578
  }
1153
1579
  : getParseWindow();
1154
1580
  const calendarId = session.createCalendarId(id);
1155
- const result = loadIcsData(data, requestedWindow);
1581
+ if (source === 'ics') {
1582
+ const result = loadIcsData(data, requestedWindow);
1583
+ return buildLoadResponse(session, result.ranges, calendarId, 'ics', result.effectiveWindow, result.detectedWindow);
1584
+ }
1585
+ // gcal/msft: the file is often a raw list_events result object
1586
+ // ({events: [...]}) rather than a bare array — accept either.
1587
+ const events = extractEventsArray(data, source === 'gcal' ? 'Google Calendar' : 'Microsoft Graph');
1588
+ const ranges = source === 'gcal'
1589
+ ? gcalEventsToDateRanges(events)
1590
+ : msftEventsToDateRanges(events);
1591
+ return buildLoadResponse(session, ranges, calendarId, source, requestedWindow, null);
1592
+ }
1593
+ case 'load_calendar_url': {
1594
+ const rawUrl = requireString(args, 'url');
1595
+ const id = optionalString(args, 'id');
1596
+ const timezone = optionalString(args, 'timezone');
1597
+ const windowFrom = optionalString(args, 'window_from');
1598
+ const windowTo = optionalString(args, 'window_to');
1599
+ if ((windowFrom && !windowTo) || (!windowFrom && windowTo)) {
1600
+ throw new Error('"window_from" and "window_to" must be provided together.');
1601
+ }
1602
+ const url = parseFeedUrl(rawUrl);
1603
+ applyTimezone(session, timezone);
1604
+ const fetched = await fetchFeedText(url);
1605
+ const icsText = ensureIcsBody(fetched.text, fetched.contentType, fetched.redactedUrl);
1606
+ const requestedWindow = windowFrom && windowTo
1607
+ ? {
1608
+ from: parseDateArgument(windowFrom),
1609
+ to: parseDateArgument(windowTo),
1610
+ }
1611
+ : getParseWindow();
1612
+ const calendarId = session.createCalendarId(id);
1613
+ const result = loadIcsData(icsText, requestedWindow);
1156
1614
  return buildLoadResponse(session, result.ranges, calendarId, 'ics', result.effectiveWindow, result.detectedWindow);
1157
1615
  }
1158
1616
  case 'find_conflicts': {
@@ -1258,6 +1716,65 @@ export async function handleToolCall(session, name, rawArgs) {
1258
1716
  case 'list_calendars': {
1259
1717
  return jsonResult(session.getCalendarSummary());
1260
1718
  }
1719
+ case 'list_ranges': {
1720
+ const requestedCalendars = optionalStringArray(args, 'calendars');
1721
+ const calendarIds = requestedCalendars
1722
+ ? requireLoadedCalendars(session, requestedCalendars)
1723
+ : [...session.calendars.keys()];
1724
+ const labelMatch = optionalString(args, 'label_match');
1725
+ const groupBy = optionalString(args, 'group_by') ?? 'series';
1726
+ const occurrenceUnit = optionalString(args, 'occurrence_unit') ?? 'events';
1727
+ const countWithin = parseCountWithin(args.count_within);
1728
+ const limit = optionalLimit(args);
1729
+ if (groupBy !== 'series' && groupBy !== 'none') {
1730
+ throw new Error('"group_by" must be "series" or "none".');
1731
+ }
1732
+ if (occurrenceUnit !== 'events' && occurrenceUnit !== 'days') {
1733
+ throw new Error('"occurrence_unit" must be "events" or "days".');
1734
+ }
1735
+ let labelRegex;
1736
+ if (labelMatch !== undefined) {
1737
+ if (labelMatch.length > MAX_LABEL_MATCH_LENGTH) {
1738
+ throw new Error(`"label_match" must be at most ${MAX_LABEL_MATCH_LENGTH} characters.`);
1739
+ }
1740
+ try {
1741
+ labelRegex = new RegExp(labelMatch, 'i');
1742
+ }
1743
+ catch {
1744
+ throw new Error(`"label_match" is not a valid regular expression: ${labelMatch}`);
1745
+ }
1746
+ }
1747
+ const entries = buildListRangeEntries(session, calendarIds, {
1748
+ labelRegex,
1749
+ groupBy,
1750
+ unit: occurrenceUnit,
1751
+ });
1752
+ entries.sort((left, right) => (left.row.from_date ?? '9999-12-31').localeCompare(right.row.from_date ?? '9999-12-31') ||
1753
+ left.row.label.localeCompare(right.row.label) ||
1754
+ left.row.range_id.localeCompare(right.row.range_id));
1755
+ // Annotate only the returned page — sort order doesn't depend on it.
1756
+ const rows = entries
1757
+ .slice(0, limit)
1758
+ .map((entry) => countWithin
1759
+ ? annotateOccurrences(session.evaluator, entry, countWithin.from, countWithin.to, occurrenceUnit)
1760
+ : entry.row);
1761
+ return jsonResult({
1762
+ ranges: rows,
1763
+ total: entries.length,
1764
+ ...(entries.length > limit
1765
+ ? {
1766
+ truncated: true,
1767
+ message: `Showing ${limit} of ${entries.length}. Use label_match, calendars, or a higher limit.`,
1768
+ }
1769
+ : {}),
1770
+ timezone: session.timezone,
1771
+ calendars: calendarIds.map((calendarId) => ({
1772
+ id: calendarId,
1773
+ effective_window: session.calendars.get(calendarId)?.effectiveWindow ?? null,
1774
+ })),
1775
+ ...(countWithin ? { count_within: countWithin } : {}),
1776
+ });
1777
+ }
1261
1778
  case 'suggest_changes': {
1262
1779
  const changes = parseProposedChanges(args);
1263
1780
  const currentRanges = session.getAllRanges();
@@ -1293,7 +1810,7 @@ export async function handleToolCall(session, name, rawArgs) {
1293
1810
  }
1294
1811
  }
1295
1812
  export function createServer(session = new CalendarSession()) {
1296
- const server = new Server({ name: 'daywatch-mcp', version: '0.1.0' }, {
1813
+ const server = new Server({ name: 'daywatch-mcp', version: VERSION }, {
1297
1814
  capabilities: {
1298
1815
  tools: {},
1299
1816
  },