@daywatch/mcp 0.1.1 → 0.4.1
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/CHANGELOG.md +66 -0
- package/README.md +39 -0
- package/dist/_version.d.ts +2 -0
- package/dist/_version.d.ts.map +1 -0
- package/dist/_version.js +2 -0
- package/dist/_version.js.map +1 -0
- package/dist/adapters/gcal.d.ts.map +1 -1
- package/dist/adapters/gcal.js +11 -1
- package/dist/adapters/gcal.js.map +1 -1
- package/dist/adapters/msft.d.ts.map +1 -1
- package/dist/adapters/msft.js +12 -2
- package/dist/adapters/msft.js.map +1 -1
- package/dist/adapters/types.d.ts.map +1 -1
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +608 -41
- package/dist/server.js.map +1 -1
- package/dist/state.d.ts +16 -1
- package/dist/state.d.ts.map +1 -1
- package/dist/state.js +11 -8
- package/dist/state.js.map +1 -1
- package/package.json +9 -5
package/dist/server.js
CHANGED
|
@@ -3,6 +3,7 @@ import { RangeEvaluator, dateRange, 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
|
|
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.
|
|
34
36
|
- Google Calendar → load_calendar with source "gcal" and the raw JSON array from gcal_list_events. Auto-filters transparent, declined, working-location events.
|
|
35
37
|
- 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.
|
|
38
|
+
- Always feed gcal/msft data through its native source. Do NOT pre-flatten it to "ranges" yourself — you lose the transparency/declined filtering and the per-event timezone reconciliation, both of which silently corrupt 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 — 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. 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
|
|
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
|
|
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 auto-filtered and converted exactly as in load_calendar.',
|
|
153
163
|
},
|
|
154
164
|
id: {
|
|
155
165
|
type: 'string',
|
|
@@ -171,14 +181,50 @@ 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
216
|
description: 'Find timed conflicts across loaded calendars within a date window.',
|
|
177
217
|
inputSchema: {
|
|
178
218
|
type: 'object',
|
|
179
219
|
properties: {
|
|
180
|
-
from: {
|
|
181
|
-
|
|
220
|
+
from: {
|
|
221
|
+
type: 'string',
|
|
222
|
+
description: 'Start of the search window as an ISO date.',
|
|
223
|
+
},
|
|
224
|
+
to: {
|
|
225
|
+
type: 'string',
|
|
226
|
+
description: 'End of the search window as an ISO date.',
|
|
227
|
+
},
|
|
182
228
|
calendars: {
|
|
183
229
|
type: 'array',
|
|
184
230
|
items: { type: 'string' },
|
|
@@ -198,7 +244,10 @@ export const TOOLS = [
|
|
|
198
244
|
inputSchema: {
|
|
199
245
|
type: 'object',
|
|
200
246
|
properties: {
|
|
201
|
-
date: {
|
|
247
|
+
date: {
|
|
248
|
+
type: 'string',
|
|
249
|
+
description: 'Date to analyze, in YYYY-MM-DD format.',
|
|
250
|
+
},
|
|
202
251
|
min_duration: {
|
|
203
252
|
type: 'number',
|
|
204
253
|
description: 'Minimum free-slot duration in minutes. Defaults to 30.',
|
|
@@ -261,8 +310,14 @@ export const TOOLS = [
|
|
|
261
310
|
items: { type: 'string' },
|
|
262
311
|
description: 'Which calendar ids to check. Must include at least two calendars.',
|
|
263
312
|
},
|
|
264
|
-
from: {
|
|
265
|
-
|
|
313
|
+
from: {
|
|
314
|
+
type: 'string',
|
|
315
|
+
description: 'Start of the search window as an ISO date.',
|
|
316
|
+
},
|
|
317
|
+
to: {
|
|
318
|
+
type: 'string',
|
|
319
|
+
description: 'End of the search window as an ISO date.',
|
|
320
|
+
},
|
|
266
321
|
min_duration: {
|
|
267
322
|
type: 'number',
|
|
268
323
|
description: 'Minimum free-slot duration in minutes. Defaults to 30.',
|
|
@@ -289,9 +344,18 @@ export const TOOLS = [
|
|
|
289
344
|
inputSchema: {
|
|
290
345
|
type: 'object',
|
|
291
346
|
properties: {
|
|
292
|
-
from: {
|
|
293
|
-
|
|
294
|
-
|
|
347
|
+
from: {
|
|
348
|
+
type: 'string',
|
|
349
|
+
description: 'Search window start as an ISO date.',
|
|
350
|
+
},
|
|
351
|
+
to: {
|
|
352
|
+
type: 'string',
|
|
353
|
+
description: 'Search window end as an ISO date.',
|
|
354
|
+
},
|
|
355
|
+
duration: {
|
|
356
|
+
type: 'number',
|
|
357
|
+
description: 'Required duration in minutes.',
|
|
358
|
+
},
|
|
295
359
|
day_start: {
|
|
296
360
|
type: 'string',
|
|
297
361
|
description: 'Start of the daily search window, in HH:mm format.',
|
|
@@ -315,8 +379,14 @@ export const TOOLS = [
|
|
|
315
379
|
inputSchema: {
|
|
316
380
|
type: 'object',
|
|
317
381
|
properties: {
|
|
318
|
-
from: {
|
|
319
|
-
|
|
382
|
+
from: {
|
|
383
|
+
type: 'string',
|
|
384
|
+
description: 'Start of the scoring window as an ISO date.',
|
|
385
|
+
},
|
|
386
|
+
to: {
|
|
387
|
+
type: 'string',
|
|
388
|
+
description: 'End of the scoring window as an ISO date.',
|
|
389
|
+
},
|
|
320
390
|
focus_block_minutes: {
|
|
321
391
|
type: 'number',
|
|
322
392
|
description: 'Minimum uninterrupted free block counted as focus time. Defaults to 60.',
|
|
@@ -344,7 +414,10 @@ export const TOOLS = [
|
|
|
344
414
|
inputSchema: {
|
|
345
415
|
type: 'object',
|
|
346
416
|
properties: {
|
|
347
|
-
date: {
|
|
417
|
+
date: {
|
|
418
|
+
type: 'string',
|
|
419
|
+
description: 'Date to inspect, in YYYY-MM-DD format.',
|
|
420
|
+
},
|
|
348
421
|
calendars: {
|
|
349
422
|
type: 'array',
|
|
350
423
|
items: { type: 'string' },
|
|
@@ -364,7 +437,10 @@ export const TOOLS = [
|
|
|
364
437
|
inputSchema: {
|
|
365
438
|
type: 'object',
|
|
366
439
|
properties: {
|
|
367
|
-
range_id: {
|
|
440
|
+
range_id: {
|
|
441
|
+
type: 'string',
|
|
442
|
+
description: 'The DateRange id to expand.',
|
|
443
|
+
},
|
|
368
444
|
from: { type: 'string', description: 'Window start as an ISO date.' },
|
|
369
445
|
to: { type: 'string', description: 'Window end as an ISO date.' },
|
|
370
446
|
limit: {
|
|
@@ -383,6 +459,47 @@ export const TOOLS = [
|
|
|
383
459
|
properties: {},
|
|
384
460
|
},
|
|
385
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
|
+
},
|
|
386
503
|
{
|
|
387
504
|
name: 'suggest_changes',
|
|
388
505
|
description: 'Preview schedule changes with before/after scoring and conflict counts without mutating session state.',
|
|
@@ -512,7 +629,7 @@ function optionalStringArray(args, key) {
|
|
|
512
629
|
if (value === undefined) {
|
|
513
630
|
return undefined;
|
|
514
631
|
}
|
|
515
|
-
if (!Array.isArray(value) || value.some(item => typeof item !== 'string')) {
|
|
632
|
+
if (!Array.isArray(value) || value.some((item) => typeof item !== 'string')) {
|
|
516
633
|
throw new Error(`"${key}" must be an array of strings when provided.`);
|
|
517
634
|
}
|
|
518
635
|
return value;
|
|
@@ -611,7 +728,7 @@ function truncateArray(items, key, limit) {
|
|
|
611
728
|
};
|
|
612
729
|
}
|
|
613
730
|
function collectUniqueLabels(ranges, limit) {
|
|
614
|
-
const labels = [...new Set(ranges.map(range => range.label))];
|
|
731
|
+
const labels = [...new Set(ranges.map((range) => range.label))];
|
|
615
732
|
return {
|
|
616
733
|
labels: labels.slice(0, limit),
|
|
617
734
|
hasMore: labels.length > limit,
|
|
@@ -622,7 +739,7 @@ function requireLoadedCalendars(session, calendarIds) {
|
|
|
622
739
|
if (uniqueIds.length === 0) {
|
|
623
740
|
throw new Error('"calendars" must include at least one calendar id.');
|
|
624
741
|
}
|
|
625
|
-
const missing = uniqueIds.filter(calendarId => !session.calendars.has(calendarId));
|
|
742
|
+
const missing = uniqueIds.filter((calendarId) => !session.calendars.has(calendarId));
|
|
626
743
|
if (missing.length > 0) {
|
|
627
744
|
throw new Error(`Unknown calendar id${missing.length === 1 ? '' : 's'}: ${missing.join(', ')}`);
|
|
628
745
|
}
|
|
@@ -649,9 +766,15 @@ function readAttendees(value) {
|
|
|
649
766
|
return [
|
|
650
767
|
{
|
|
651
768
|
email: record.email,
|
|
652
|
-
...(typeof record.name === 'string' && record.name.trim() !== ''
|
|
653
|
-
|
|
654
|
-
|
|
769
|
+
...(typeof record.name === 'string' && record.name.trim() !== ''
|
|
770
|
+
? { name: record.name }
|
|
771
|
+
: {}),
|
|
772
|
+
...(typeof record.role === 'string' && record.role.trim() !== ''
|
|
773
|
+
? { role: record.role }
|
|
774
|
+
: {}),
|
|
775
|
+
...(typeof record.status === 'string' && record.status.trim() !== ''
|
|
776
|
+
? { status: record.status }
|
|
777
|
+
: {}),
|
|
655
778
|
},
|
|
656
779
|
];
|
|
657
780
|
});
|
|
@@ -700,7 +823,7 @@ function getFirstOrganizer(ranges) {
|
|
|
700
823
|
function buildRecurrenceSummary(range) {
|
|
701
824
|
const weekdayLabels = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
|
|
702
825
|
if (range.everyWeekday?.length) {
|
|
703
|
-
return `weekly on ${range.everyWeekday.map(day => weekdayLabels[day] ?? String(day)).join(', ')}`;
|
|
826
|
+
return `weekly on ${range.everyWeekday.map((day) => weekdayLabels[day] ?? String(day)).join(', ')}`;
|
|
704
827
|
}
|
|
705
828
|
if (range.everyDate?.length) {
|
|
706
829
|
return `monthly on ${range.everyDate.join(', ')}`;
|
|
@@ -717,7 +840,7 @@ function rangeOverlapsDateFilter(range, from, to) {
|
|
|
717
840
|
const windowFrom = from ?? to;
|
|
718
841
|
const windowTo = to ?? from;
|
|
719
842
|
if (range.dates?.length) {
|
|
720
|
-
return range.dates.some(date => date >= windowFrom && date <= windowTo);
|
|
843
|
+
return range.dates.some((date) => date >= windowFrom && date <= windowTo);
|
|
721
844
|
}
|
|
722
845
|
if (range.toDate && range.toDate < windowFrom) {
|
|
723
846
|
return false;
|
|
@@ -727,6 +850,160 @@ function rangeOverlapsDateFilter(range, from, to) {
|
|
|
727
850
|
}
|
|
728
851
|
return true;
|
|
729
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
|
+
...(metadata?.transparent === true ? { 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
|
+
}
|
|
730
1007
|
function shiftDay(dateStr, delta) {
|
|
731
1008
|
const [year, month, day] = dateStr.split('-').map(Number);
|
|
732
1009
|
const next = new Date(year, month - 1, day + delta);
|
|
@@ -767,13 +1044,13 @@ function buildDayDetail(evaluator, ranges, date) {
|
|
|
767
1044
|
function buildSharedEvents(session, calendarIds, from, to) {
|
|
768
1045
|
const sharedEvents = [];
|
|
769
1046
|
for (const [id, entries] of session.groupRangesByIdAcrossCalendars(calendarIds)) {
|
|
770
|
-
const filteredEntries = entries.filter(entry => rangeOverlapsDateFilter(entry.range, from, to));
|
|
771
|
-
const distinctCalendars = [...new Set(filteredEntries.map(entry => entry.calendarId))].sort();
|
|
1047
|
+
const filteredEntries = entries.filter((entry) => rangeOverlapsDateFilter(entry.range, from, to));
|
|
1048
|
+
const distinctCalendars = [...new Set(filteredEntries.map((entry) => entry.calendarId))].sort();
|
|
772
1049
|
if (distinctCalendars.length < 2) {
|
|
773
1050
|
continue;
|
|
774
1051
|
}
|
|
775
1052
|
const representative = filteredEntries[0].range;
|
|
776
|
-
const ranges = filteredEntries.map(entry => entry.range);
|
|
1053
|
+
const ranges = filteredEntries.map((entry) => entry.range);
|
|
777
1054
|
const attendees = mergeAttendees(ranges);
|
|
778
1055
|
const organizer = getFirstOrganizer(ranges);
|
|
779
1056
|
const recurrenceSummary = buildRecurrenceSummary(representative);
|
|
@@ -792,7 +1069,7 @@ function buildSharedEvents(session, calendarIds, from, to) {
|
|
|
792
1069
|
return sharedEvents;
|
|
793
1070
|
}
|
|
794
1071
|
function buildCommonAvailability(evaluator, ranges, from, to, options) {
|
|
795
|
-
return dateRange(from, to).flatMap(date => evaluator.findFreeSlots(ranges, date, options).map(slot => ({
|
|
1072
|
+
return dateRange(from, to).flatMap((date) => evaluator.findFreeSlots(ranges, date, options).map((slot) => ({
|
|
796
1073
|
date: slot.date,
|
|
797
1074
|
start: slot.startTime,
|
|
798
1075
|
end: slot.endTime,
|
|
@@ -800,7 +1077,7 @@ function buildCommonAvailability(evaluator, ranges, from, to, options) {
|
|
|
800
1077
|
})));
|
|
801
1078
|
}
|
|
802
1079
|
function findRangeById(ranges, rangeId) {
|
|
803
|
-
return ranges.find(range => range.id === rangeId);
|
|
1080
|
+
return ranges.find((range) => range.id === rangeId);
|
|
804
1081
|
}
|
|
805
1082
|
function applyDateUpdate(range, date) {
|
|
806
1083
|
if (range.dates?.length) {
|
|
@@ -852,7 +1129,7 @@ function applyChangesToRanges(ranges, changes) {
|
|
|
852
1129
|
if (!change.range_id) {
|
|
853
1130
|
throw new Error('Move changes require "range_id".');
|
|
854
1131
|
}
|
|
855
|
-
const index = nextRanges.findIndex(range => range.id === change.range_id);
|
|
1132
|
+
const index = nextRanges.findIndex((range) => range.id === change.range_id);
|
|
856
1133
|
if (index === -1) {
|
|
857
1134
|
throw new Error(`Range "${change.range_id}" was not found in the current session.`);
|
|
858
1135
|
}
|
|
@@ -872,7 +1149,7 @@ function applyChangesToRanges(ranges, changes) {
|
|
|
872
1149
|
if (!change.range_id) {
|
|
873
1150
|
throw new Error('Remove changes require "range_id".');
|
|
874
1151
|
}
|
|
875
|
-
const filteredRanges = nextRanges.filter(range => range.id !== change.range_id);
|
|
1152
|
+
const filteredRanges = nextRanges.filter((range) => range.id !== change.range_id);
|
|
876
1153
|
if (filteredRanges.length === nextRanges.length) {
|
|
877
1154
|
throw new Error(`Range "${change.range_id}" was not found in the current session.`);
|
|
878
1155
|
}
|
|
@@ -892,7 +1169,9 @@ function getRangeDateWindow(range) {
|
|
|
892
1169
|
to: sortedDates[sortedDates.length - 1],
|
|
893
1170
|
};
|
|
894
1171
|
}
|
|
895
|
-
const dates = [range.fromDate, range.toDate]
|
|
1172
|
+
const dates = [range.fromDate, range.toDate]
|
|
1173
|
+
.filter((value) => Boolean(value))
|
|
1174
|
+
.sort();
|
|
896
1175
|
if (dates.length > 0) {
|
|
897
1176
|
return {
|
|
898
1177
|
from: dates[0],
|
|
@@ -935,8 +1214,8 @@ function getDefaultSuggestionWindow(currentRanges, changes) {
|
|
|
935
1214
|
if (windows.length === 0) {
|
|
936
1215
|
throw new Error('Could not infer a scoring window from the proposed changes. Provide "from" and "to".');
|
|
937
1216
|
}
|
|
938
|
-
const earliest = windows.map(window => window.from).sort()[0];
|
|
939
|
-
const latest = windows.map(window => window.to).sort()[windows.length - 1];
|
|
1217
|
+
const earliest = windows.map((window) => window.from).sort()[0];
|
|
1218
|
+
const latest = windows.map((window) => window.to).sort()[windows.length - 1];
|
|
940
1219
|
return {
|
|
941
1220
|
from: shiftDay(earliest, -7),
|
|
942
1221
|
to: shiftDay(latest, 7),
|
|
@@ -1026,8 +1305,195 @@ function loadIcsData(icsText, requestedWindow) {
|
|
|
1026
1305
|
}
|
|
1027
1306
|
return { ranges, effectiveWindow, detectedWindow };
|
|
1028
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
|
+
}
|
|
1029
1493
|
function buildLoadResponse(session, ranges, calendarId, source, effectiveWindow, detectedWindow) {
|
|
1030
|
-
|
|
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);
|
|
1031
1497
|
const labelSummary = collectUniqueLabels(ranges, 20);
|
|
1032
1498
|
return jsonResult({
|
|
1033
1499
|
calendars_loaded: session.calendars.size,
|
|
@@ -1058,7 +1524,10 @@ export async function handleToolCall(session, name, rawArgs) {
|
|
|
1058
1524
|
}
|
|
1059
1525
|
applyTimezone(session, timezone);
|
|
1060
1526
|
const requestedWindow = windowFrom && windowTo
|
|
1061
|
-
? {
|
|
1527
|
+
? {
|
|
1528
|
+
from: parseDateArgument(windowFrom),
|
|
1529
|
+
to: parseDateArgument(windowTo),
|
|
1530
|
+
}
|
|
1062
1531
|
: getParseWindow();
|
|
1063
1532
|
const calendarId = session.createCalendarId(id);
|
|
1064
1533
|
if (source === 'ics') {
|
|
@@ -1089,20 +1558,59 @@ export async function handleToolCall(session, name, rawArgs) {
|
|
|
1089
1558
|
}
|
|
1090
1559
|
case 'load_calendar_file': {
|
|
1091
1560
|
const filePath = requireString(args, 'path');
|
|
1561
|
+
const source = optionalString(args, 'source') ?? 'ics';
|
|
1092
1562
|
const id = optionalString(args, 'id');
|
|
1093
1563
|
const timezone = optionalString(args, 'timezone');
|
|
1094
1564
|
const windowFrom = optionalString(args, 'window_from');
|
|
1095
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
|
+
}
|
|
1096
1569
|
if ((windowFrom && !windowTo) || (!windowFrom && windowTo)) {
|
|
1097
1570
|
throw new Error('"window_from" and "window_to" must be provided together.');
|
|
1098
1571
|
}
|
|
1099
1572
|
applyTimezone(session, timezone);
|
|
1100
1573
|
const data = readFileSync(filePath, 'utf8');
|
|
1101
1574
|
const requestedWindow = windowFrom && windowTo
|
|
1102
|
-
? {
|
|
1575
|
+
? {
|
|
1576
|
+
from: parseDateArgument(windowFrom),
|
|
1577
|
+
to: parseDateArgument(windowTo),
|
|
1578
|
+
}
|
|
1103
1579
|
: getParseWindow();
|
|
1104
1580
|
const calendarId = session.createCalendarId(id);
|
|
1105
|
-
|
|
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);
|
|
1106
1614
|
return buildLoadResponse(session, result.ranges, calendarId, 'ics', result.effectiveWindow, result.detectedWindow);
|
|
1107
1615
|
}
|
|
1108
1616
|
case 'find_conflicts': {
|
|
@@ -1198,7 +1706,7 @@ export async function handleToolCall(session, name, rawArgs) {
|
|
|
1198
1706
|
const from = requireString(args, 'from');
|
|
1199
1707
|
const to = requireString(args, 'to');
|
|
1200
1708
|
const limit = optionalLimit(args);
|
|
1201
|
-
const range = session.getAllRanges().find(candidate => candidate.id === rangeId);
|
|
1709
|
+
const range = session.getAllRanges().find((candidate) => candidate.id === rangeId);
|
|
1202
1710
|
if (!range) {
|
|
1203
1711
|
throw new Error(`Range "${rangeId}" was not found in the current session.`);
|
|
1204
1712
|
}
|
|
@@ -1208,6 +1716,65 @@ export async function handleToolCall(session, name, rawArgs) {
|
|
|
1208
1716
|
case 'list_calendars': {
|
|
1209
1717
|
return jsonResult(session.getCalendarSummary());
|
|
1210
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
|
+
}
|
|
1211
1778
|
case 'suggest_changes': {
|
|
1212
1779
|
const changes = parseProposedChanges(args);
|
|
1213
1780
|
const currentRanges = session.getAllRanges();
|
|
@@ -1243,7 +1810,7 @@ export async function handleToolCall(session, name, rawArgs) {
|
|
|
1243
1810
|
}
|
|
1244
1811
|
}
|
|
1245
1812
|
export function createServer(session = new CalendarSession()) {
|
|
1246
|
-
const server = new Server({ name: 'daywatch-mcp', version:
|
|
1813
|
+
const server = new Server({ name: 'daywatch-mcp', version: VERSION }, {
|
|
1247
1814
|
capabilities: {
|
|
1248
1815
|
tools: {},
|
|
1249
1816
|
},
|