@daywatch/mcp 0.1.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/README.md +113 -0
- package/dist/adapters/gcal.d.ts +7 -0
- package/dist/adapters/gcal.d.ts.map +1 -0
- package/dist/adapters/gcal.js +70 -0
- package/dist/adapters/gcal.js.map +1 -0
- package/dist/adapters/msft.d.ts +6 -0
- package/dist/adapters/msft.d.ts.map +1 -0
- package/dist/adapters/msft.js +59 -0
- package/dist/adapters/msft.js.map +1 -0
- package/dist/adapters/types.d.ts +96 -0
- package/dist/adapters/types.d.ts.map +1 -0
- package/dist/adapters/types.js +2 -0
- package/dist/adapters/types.js.map +1 -0
- package/dist/adapters/windows-timezones.d.ts +9 -0
- package/dist/adapters/windows-timezones.d.ts.map +1 -0
- package/dist/adapters/windows-timezones.js +81 -0
- package/dist/adapters/windows-timezones.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +7 -0
- package/dist/index.js.map +1 -0
- package/dist/server.d.ts +7 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +1258 -0
- package/dist/server.js.map +1 -0
- package/dist/state.d.ts +33 -0
- package/dist/state.d.ts.map +1 -0
- package/dist/state.js +127 -0
- package/dist/state.js.map +1 -0
- package/package.json +37 -0
package/dist/server.js
ADDED
|
@@ -0,0 +1,1258 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { RangeEvaluator, dateRange, scoreSchedule, } from '@daywatch/cal';
|
|
3
|
+
import { detectDataWindow, generateICS, parseICS } from '@daywatch/ical';
|
|
4
|
+
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
5
|
+
import { CallToolRequestSchema, ListToolsRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
|
|
6
|
+
import { gcalEventsToDateRanges } from './adapters/gcal.js';
|
|
7
|
+
import { msftEventsToDateRanges } from './adapters/msft.js';
|
|
8
|
+
import { CalendarSession } from './state.js';
|
|
9
|
+
const SERVER_INSTRUCTIONS = `Calendar computation engine powered by daywatch-cal. Handles RRULE expansion, timezone math, conflict detection, schedule scoring, and cross-calendar analysis.
|
|
10
|
+
|
|
11
|
+
WHEN TO USE NEO-RECKONING vs. A CALENDAR MCP (Google Calendar, Outlook, etc.):
|
|
12
|
+
|
|
13
|
+
If another calendar MCP is available (e.g., Google Calendar, Microsoft Graph), use it directly for simple queries and writes — listing events, creating/updating/deleting events, RSVPing, or finding free time within a single provider. Those MCPs have live API access and handle the basics well.
|
|
14
|
+
|
|
15
|
+
Use daywatch-cal when the task goes beyond what a single calendar MCP can do:
|
|
16
|
+
- CROSS-PROVIDER: Finding availability across people on different calendar systems (Alice on Google + Bob on Outlook + Chris from an .ics export). Load each into daywatch-cal with a distinct ID, then use find_common_availability.
|
|
17
|
+
- SCHEDULE QUALITY: score_schedule gives quantified metrics — conflict count, total free time, focus blocks (consecutive free hours), context switches. No calendar MCP offers this.
|
|
18
|
+
- WHAT-IF ANALYSIS: "What happens if I move standup to 2pm?" Load the calendar, use suggest_changes to preview the move with before/after scores — without touching the real calendar. Then use the source MCP to apply the winning option.
|
|
19
|
+
- CONFLICT DETAIL: find_conflicts returns the specific overlapping events with overlap duration. Calendar FreeBusy APIs only return opaque busy/free blocks.
|
|
20
|
+
- .ICS FILES: School calendars, conference schedules, Outlook exports, Apple Calendar exports — load_calendar_file or load_calendar with source "ics" handles RRULE expansion, timezone conversion, and all the edge cases. Never parse .ics in-context.
|
|
21
|
+
- RECURRENCE REASONING: Understanding recurrence patterns themselves (not just expanded instances). expand_range shows concrete occurrences; the pattern metadata is preserved for reasoning about schedule structure.
|
|
22
|
+
- OFFLINE / NO-AUTH: The user shares calendar data without granting API access. Neo-reckoning works on snapshots — no authentication needed.
|
|
23
|
+
|
|
24
|
+
TYPICAL AGENT WORKFLOW (when both daywatch-cal and a calendar MCP are available):
|
|
25
|
+
1. Fetch data from the source MCP (gcal_list_events, Microsoft Graph, etc.)
|
|
26
|
+
2. Load into daywatch-cal: load_calendar(source="gcal", data=<raw JSON>) or source="msft"
|
|
27
|
+
3. Analyze with daywatch-cal: find_conflicts, find_common_availability, score_schedule, suggest_changes
|
|
28
|
+
4. Act via the source MCP: gcal_create_event, gcal_update_event, etc.
|
|
29
|
+
|
|
30
|
+
Neo-reckoning is the thinking step between reading and writing. The source MCP is the hands.
|
|
31
|
+
|
|
32
|
+
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.
|
|
36
|
+
- Raw .ics text or pasted data → load_calendar with source "ics"
|
|
37
|
+
- Pre-built DateRange JSON → load_calendar with source "ranges"
|
|
38
|
+
- Data persists for the session — load once, query many times.
|
|
39
|
+
- load_calendar returns effective_window and sample_labels so you know what dates and events were loaded.
|
|
40
|
+
- The server auto-detects the right time window for historical calendars (e.g. a past school year).
|
|
41
|
+
|
|
42
|
+
ANALYZING:
|
|
43
|
+
- find_conflicts — overlapping events in a date range, with overlap details
|
|
44
|
+
- find_free_slots — open time on a specific day (defaults to 09:00–17:00)
|
|
45
|
+
- find_next_free_slot — first available slot of a given duration
|
|
46
|
+
- find_shared_events — meetings appearing in multiple loaded calendars (matched by event UID)
|
|
47
|
+
- find_common_availability — free slots across specified calendars over a date range
|
|
48
|
+
- score_schedule — quality metrics: conflicts, free time, focus blocks, context switches
|
|
49
|
+
- day_detail — full breakdown of a single day (timed slots + all-day events)
|
|
50
|
+
- expand_range — concrete occurrences of one recurring event
|
|
51
|
+
|
|
52
|
+
CROSS-CALENDAR ANALYSIS:
|
|
53
|
+
- Load multiple calendars with distinct IDs: load_calendar(id="alice", ...), load_calendar(id="bob", ...)
|
|
54
|
+
- Calendars can come from different providers — Google for one person, Outlook for another, .ics for a third
|
|
55
|
+
- find_shared_events identifies the same meeting across calendars by event UID
|
|
56
|
+
- find_common_availability finds free slots across all specified calendars
|
|
57
|
+
- Metadata from the source (attendees, response status, event type) is preserved — check it to understand context
|
|
58
|
+
- To reschedule a shared meeting: identify it with find_shared_events, find a new slot with find_common_availability, preview with suggest_changes, then use the source calendar MCP to make the actual change
|
|
59
|
+
|
|
60
|
+
OPTIMIZING:
|
|
61
|
+
- suggest_changes — preview moves/adds/removes with before/after scoring (read-only, does not affect real calendars)
|
|
62
|
+
- apply_changes — commit changes to daywatch-cal's session state after user approval
|
|
63
|
+
- generate_ics — export current state as .ics for reimport into any calendar app
|
|
64
|
+
- After optimizing in daywatch-cal, use the source calendar MCP (gcal_update_event, etc.) to apply changes to the real calendar
|
|
65
|
+
|
|
66
|
+
FORMATTING:
|
|
67
|
+
Dates: YYYY-MM-DD. Times: HH:mm (24-hour).
|
|
68
|
+
|
|
69
|
+
LARGE CALENDARS:
|
|
70
|
+
- Use window_from/window_to to limit the parse range when you know the relevant period.
|
|
71
|
+
- Query narrow date ranges (1–2 weeks) rather than broad multi-month windows.
|
|
72
|
+
- Use day_detail for single-day deep dives.
|
|
73
|
+
- find_conflicts, find_free_slots, day_detail, and expand_range accept a limit parameter.`;
|
|
74
|
+
const PROPOSED_CHANGE_SCHEMA = {
|
|
75
|
+
type: 'object',
|
|
76
|
+
properties: {
|
|
77
|
+
action: {
|
|
78
|
+
type: 'string',
|
|
79
|
+
enum: ['move', 'add', 'remove'],
|
|
80
|
+
description: 'Whether to move, add, or remove a range.',
|
|
81
|
+
},
|
|
82
|
+
range_id: {
|
|
83
|
+
type: 'string',
|
|
84
|
+
description: 'The range id to mutate for move/remove actions.',
|
|
85
|
+
},
|
|
86
|
+
updates: {
|
|
87
|
+
type: 'object',
|
|
88
|
+
properties: {
|
|
89
|
+
startTime: { type: 'string' },
|
|
90
|
+
endTime: { type: 'string' },
|
|
91
|
+
date: { type: 'string' },
|
|
92
|
+
fromDate: { type: 'string' },
|
|
93
|
+
toDate: { type: 'string' },
|
|
94
|
+
},
|
|
95
|
+
description: 'Updated values to apply to an existing range.',
|
|
96
|
+
},
|
|
97
|
+
new_range: {
|
|
98
|
+
type: 'object',
|
|
99
|
+
description: 'A new DateRange to add for add actions.',
|
|
100
|
+
},
|
|
101
|
+
reason: {
|
|
102
|
+
type: 'string',
|
|
103
|
+
description: 'Human-readable rationale for the proposed change.',
|
|
104
|
+
},
|
|
105
|
+
},
|
|
106
|
+
required: ['action', 'reason'],
|
|
107
|
+
};
|
|
108
|
+
export const TOOLS = [
|
|
109
|
+
{
|
|
110
|
+
name: 'load_calendar',
|
|
111
|
+
description: 'Load calendar data from .ics text or DateRange[] JSON into the current session. Tip: set window_from/window_to to limit the parse range for large calendars.',
|
|
112
|
+
inputSchema: {
|
|
113
|
+
type: 'object',
|
|
114
|
+
properties: {
|
|
115
|
+
source: {
|
|
116
|
+
type: 'string',
|
|
117
|
+
enum: ['ics', 'ranges', 'gcal', 'msft'],
|
|
118
|
+
description: 'Data format: "ics" for .ics text, "ranges" for JSON DateRange array, "gcal" for Google Calendar MCP JSON, "msft" for Microsoft Graph Calendar API JSON.',
|
|
119
|
+
},
|
|
120
|
+
data: {
|
|
121
|
+
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.',
|
|
123
|
+
},
|
|
124
|
+
id: {
|
|
125
|
+
type: 'string',
|
|
126
|
+
description: 'Optional calendar identifier. Defaults to calendar-N.',
|
|
127
|
+
},
|
|
128
|
+
timezone: {
|
|
129
|
+
type: 'string',
|
|
130
|
+
description: 'Optional IANA timezone to use for the session evaluator.',
|
|
131
|
+
},
|
|
132
|
+
window_from: {
|
|
133
|
+
type: 'string',
|
|
134
|
+
description: 'Optional parse window start date (YYYY-MM-DD). Must be paired with window_to.',
|
|
135
|
+
},
|
|
136
|
+
window_to: {
|
|
137
|
+
type: 'string',
|
|
138
|
+
description: 'Optional parse window end date (YYYY-MM-DD). Must be paired with window_from.',
|
|
139
|
+
},
|
|
140
|
+
},
|
|
141
|
+
required: ['source', 'data'],
|
|
142
|
+
},
|
|
143
|
+
},
|
|
144
|
+
{
|
|
145
|
+
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.',
|
|
147
|
+
inputSchema: {
|
|
148
|
+
type: 'object',
|
|
149
|
+
properties: {
|
|
150
|
+
path: {
|
|
151
|
+
type: 'string',
|
|
152
|
+
description: 'Absolute path to the .ics file on disk.',
|
|
153
|
+
},
|
|
154
|
+
id: {
|
|
155
|
+
type: 'string',
|
|
156
|
+
description: 'Optional calendar identifier. Defaults to calendar-N.',
|
|
157
|
+
},
|
|
158
|
+
timezone: {
|
|
159
|
+
type: 'string',
|
|
160
|
+
description: 'Optional IANA timezone to use for the session evaluator.',
|
|
161
|
+
},
|
|
162
|
+
window_from: {
|
|
163
|
+
type: 'string',
|
|
164
|
+
description: 'Optional parse window start date (YYYY-MM-DD). Must be paired with window_to.',
|
|
165
|
+
},
|
|
166
|
+
window_to: {
|
|
167
|
+
type: 'string',
|
|
168
|
+
description: 'Optional parse window end date (YYYY-MM-DD). Must be paired with window_from.',
|
|
169
|
+
},
|
|
170
|
+
},
|
|
171
|
+
required: ['path'],
|
|
172
|
+
},
|
|
173
|
+
},
|
|
174
|
+
{
|
|
175
|
+
name: 'find_conflicts',
|
|
176
|
+
description: 'Find timed conflicts across loaded calendars within a date window.',
|
|
177
|
+
inputSchema: {
|
|
178
|
+
type: 'object',
|
|
179
|
+
properties: {
|
|
180
|
+
from: { type: 'string', description: 'Start of the search window as an ISO date.' },
|
|
181
|
+
to: { type: 'string', description: 'End of the search window as an ISO date.' },
|
|
182
|
+
calendars: {
|
|
183
|
+
type: 'array',
|
|
184
|
+
items: { type: 'string' },
|
|
185
|
+
description: 'Optional list of calendar ids to limit the search.',
|
|
186
|
+
},
|
|
187
|
+
limit: {
|
|
188
|
+
type: 'number',
|
|
189
|
+
description: 'Maximum conflicts to return. Defaults to 50.',
|
|
190
|
+
},
|
|
191
|
+
},
|
|
192
|
+
required: ['from', 'to'],
|
|
193
|
+
},
|
|
194
|
+
},
|
|
195
|
+
{
|
|
196
|
+
name: 'find_free_slots',
|
|
197
|
+
description: 'Find free time slots on a specific day within working-hour bounds.',
|
|
198
|
+
inputSchema: {
|
|
199
|
+
type: 'object',
|
|
200
|
+
properties: {
|
|
201
|
+
date: { type: 'string', description: 'Date to analyze, in YYYY-MM-DD format.' },
|
|
202
|
+
min_duration: {
|
|
203
|
+
type: 'number',
|
|
204
|
+
description: 'Minimum free-slot duration in minutes. Defaults to 30.',
|
|
205
|
+
},
|
|
206
|
+
day_start: {
|
|
207
|
+
type: 'string',
|
|
208
|
+
description: 'Start of the day window, in HH:mm format. Defaults to 09:00.',
|
|
209
|
+
},
|
|
210
|
+
day_end: {
|
|
211
|
+
type: 'string',
|
|
212
|
+
description: 'End of the day window, in HH:mm format. Defaults to 17:00.',
|
|
213
|
+
},
|
|
214
|
+
calendars: {
|
|
215
|
+
type: 'array',
|
|
216
|
+
items: { type: 'string' },
|
|
217
|
+
description: 'Optional list of calendar ids to limit the search.',
|
|
218
|
+
},
|
|
219
|
+
limit: {
|
|
220
|
+
type: 'number',
|
|
221
|
+
description: 'Maximum free slots to return. Defaults to 50.',
|
|
222
|
+
},
|
|
223
|
+
},
|
|
224
|
+
required: ['date'],
|
|
225
|
+
},
|
|
226
|
+
},
|
|
227
|
+
{
|
|
228
|
+
name: 'find_shared_events',
|
|
229
|
+
description: 'Find events that appear in two or more loaded calendars, grouped by shared event UID.',
|
|
230
|
+
inputSchema: {
|
|
231
|
+
type: 'object',
|
|
232
|
+
properties: {
|
|
233
|
+
calendars: {
|
|
234
|
+
type: 'array',
|
|
235
|
+
items: { type: 'string' },
|
|
236
|
+
description: 'Optional list of calendar ids to compare. Defaults to all loaded calendars.',
|
|
237
|
+
},
|
|
238
|
+
from: {
|
|
239
|
+
type: 'string',
|
|
240
|
+
description: 'Optional ISO date filter for the start of the search window.',
|
|
241
|
+
},
|
|
242
|
+
to: {
|
|
243
|
+
type: 'string',
|
|
244
|
+
description: 'Optional ISO date filter for the end of the search window.',
|
|
245
|
+
},
|
|
246
|
+
limit: {
|
|
247
|
+
type: 'number',
|
|
248
|
+
description: 'Maximum shared events to return. Defaults to 50.',
|
|
249
|
+
},
|
|
250
|
+
},
|
|
251
|
+
},
|
|
252
|
+
},
|
|
253
|
+
{
|
|
254
|
+
name: 'find_common_availability',
|
|
255
|
+
description: 'Find free time slots across specific calendars over a date range.',
|
|
256
|
+
inputSchema: {
|
|
257
|
+
type: 'object',
|
|
258
|
+
properties: {
|
|
259
|
+
calendars: {
|
|
260
|
+
type: 'array',
|
|
261
|
+
items: { type: 'string' },
|
|
262
|
+
description: 'Which calendar ids to check. Must include at least two calendars.',
|
|
263
|
+
},
|
|
264
|
+
from: { type: 'string', description: 'Start of the search window as an ISO date.' },
|
|
265
|
+
to: { type: 'string', description: 'End of the search window as an ISO date.' },
|
|
266
|
+
min_duration: {
|
|
267
|
+
type: 'number',
|
|
268
|
+
description: 'Minimum free-slot duration in minutes. Defaults to 30.',
|
|
269
|
+
},
|
|
270
|
+
day_start: {
|
|
271
|
+
type: 'string',
|
|
272
|
+
description: 'Start of the day window, in HH:mm format. Defaults to 09:00.',
|
|
273
|
+
},
|
|
274
|
+
day_end: {
|
|
275
|
+
type: 'string',
|
|
276
|
+
description: 'End of the day window, in HH:mm format. Defaults to 17:00.',
|
|
277
|
+
},
|
|
278
|
+
limit: {
|
|
279
|
+
type: 'number',
|
|
280
|
+
description: 'Maximum slots to return. Defaults to 20.',
|
|
281
|
+
},
|
|
282
|
+
},
|
|
283
|
+
required: ['calendars', 'from', 'to'],
|
|
284
|
+
},
|
|
285
|
+
},
|
|
286
|
+
{
|
|
287
|
+
name: 'find_next_free_slot',
|
|
288
|
+
description: 'Find the next available free slot within a date window.',
|
|
289
|
+
inputSchema: {
|
|
290
|
+
type: 'object',
|
|
291
|
+
properties: {
|
|
292
|
+
from: { type: 'string', description: 'Search window start as an ISO date.' },
|
|
293
|
+
to: { type: 'string', description: 'Search window end as an ISO date.' },
|
|
294
|
+
duration: { type: 'number', description: 'Required duration in minutes.' },
|
|
295
|
+
day_start: {
|
|
296
|
+
type: 'string',
|
|
297
|
+
description: 'Start of the daily search window, in HH:mm format.',
|
|
298
|
+
},
|
|
299
|
+
day_end: {
|
|
300
|
+
type: 'string',
|
|
301
|
+
description: 'End of the daily search window, in HH:mm format.',
|
|
302
|
+
},
|
|
303
|
+
calendars: {
|
|
304
|
+
type: 'array',
|
|
305
|
+
items: { type: 'string' },
|
|
306
|
+
description: 'Optional list of calendar ids to limit the search.',
|
|
307
|
+
},
|
|
308
|
+
},
|
|
309
|
+
required: ['from', 'to', 'duration'],
|
|
310
|
+
},
|
|
311
|
+
},
|
|
312
|
+
{
|
|
313
|
+
name: 'score_schedule',
|
|
314
|
+
description: 'Score a schedule window for conflicts, free time, focus blocks, and context switches.',
|
|
315
|
+
inputSchema: {
|
|
316
|
+
type: 'object',
|
|
317
|
+
properties: {
|
|
318
|
+
from: { type: 'string', description: 'Start of the scoring window as an ISO date.' },
|
|
319
|
+
to: { type: 'string', description: 'End of the scoring window as an ISO date.' },
|
|
320
|
+
focus_block_minutes: {
|
|
321
|
+
type: 'number',
|
|
322
|
+
description: 'Minimum uninterrupted free block counted as focus time. Defaults to 60.',
|
|
323
|
+
},
|
|
324
|
+
day_start: {
|
|
325
|
+
type: 'string',
|
|
326
|
+
description: 'Start of the working day, in HH:mm format.',
|
|
327
|
+
},
|
|
328
|
+
day_end: {
|
|
329
|
+
type: 'string',
|
|
330
|
+
description: 'End of the working day, in HH:mm format.',
|
|
331
|
+
},
|
|
332
|
+
calendars: {
|
|
333
|
+
type: 'array',
|
|
334
|
+
items: { type: 'string' },
|
|
335
|
+
description: 'Optional list of calendar ids to limit the analysis.',
|
|
336
|
+
},
|
|
337
|
+
},
|
|
338
|
+
required: ['from', 'to'],
|
|
339
|
+
},
|
|
340
|
+
},
|
|
341
|
+
{
|
|
342
|
+
name: 'day_detail',
|
|
343
|
+
description: 'Return timed slots and all-day ranges for a specific day.',
|
|
344
|
+
inputSchema: {
|
|
345
|
+
type: 'object',
|
|
346
|
+
properties: {
|
|
347
|
+
date: { type: 'string', description: 'Date to inspect, in YYYY-MM-DD format.' },
|
|
348
|
+
calendars: {
|
|
349
|
+
type: 'array',
|
|
350
|
+
items: { type: 'string' },
|
|
351
|
+
description: 'Optional list of calendar ids to limit the analysis.',
|
|
352
|
+
},
|
|
353
|
+
limit: {
|
|
354
|
+
type: 'number',
|
|
355
|
+
description: 'Maximum timed slots to return. Defaults to 50.',
|
|
356
|
+
},
|
|
357
|
+
},
|
|
358
|
+
required: ['date'],
|
|
359
|
+
},
|
|
360
|
+
},
|
|
361
|
+
{
|
|
362
|
+
name: 'expand_range',
|
|
363
|
+
description: 'Expand one stored DateRange into its concrete occurrences within a date window.',
|
|
364
|
+
inputSchema: {
|
|
365
|
+
type: 'object',
|
|
366
|
+
properties: {
|
|
367
|
+
range_id: { type: 'string', description: 'The DateRange id to expand.' },
|
|
368
|
+
from: { type: 'string', description: 'Window start as an ISO date.' },
|
|
369
|
+
to: { type: 'string', description: 'Window end as an ISO date.' },
|
|
370
|
+
limit: {
|
|
371
|
+
type: 'number',
|
|
372
|
+
description: 'Maximum occurrences to return. Defaults to 50.',
|
|
373
|
+
},
|
|
374
|
+
},
|
|
375
|
+
required: ['range_id', 'from', 'to'],
|
|
376
|
+
},
|
|
377
|
+
},
|
|
378
|
+
{
|
|
379
|
+
name: 'list_calendars',
|
|
380
|
+
description: 'List loaded calendars with their range counts and labels.',
|
|
381
|
+
inputSchema: {
|
|
382
|
+
type: 'object',
|
|
383
|
+
properties: {},
|
|
384
|
+
},
|
|
385
|
+
},
|
|
386
|
+
{
|
|
387
|
+
name: 'suggest_changes',
|
|
388
|
+
description: 'Preview schedule changes with before/after scoring and conflict counts without mutating session state.',
|
|
389
|
+
inputSchema: {
|
|
390
|
+
type: 'object',
|
|
391
|
+
properties: {
|
|
392
|
+
changes: {
|
|
393
|
+
type: 'array',
|
|
394
|
+
items: PROPOSED_CHANGE_SCHEMA,
|
|
395
|
+
description: 'Proposed change set to evaluate against the current session.',
|
|
396
|
+
},
|
|
397
|
+
from: {
|
|
398
|
+
type: 'string',
|
|
399
|
+
description: 'Optional scoring window start date. Defaults to earliest affected date minus 7 days.',
|
|
400
|
+
},
|
|
401
|
+
to: {
|
|
402
|
+
type: 'string',
|
|
403
|
+
description: 'Optional scoring window end date. Defaults to latest affected date plus 7 days.',
|
|
404
|
+
},
|
|
405
|
+
},
|
|
406
|
+
required: ['changes'],
|
|
407
|
+
},
|
|
408
|
+
},
|
|
409
|
+
{
|
|
410
|
+
name: 'apply_changes',
|
|
411
|
+
description: 'Apply schedule changes to the current session.',
|
|
412
|
+
inputSchema: {
|
|
413
|
+
type: 'object',
|
|
414
|
+
properties: {
|
|
415
|
+
changes: {
|
|
416
|
+
type: 'array',
|
|
417
|
+
items: PROPOSED_CHANGE_SCHEMA,
|
|
418
|
+
description: 'Proposed change set to apply to the current session.',
|
|
419
|
+
},
|
|
420
|
+
},
|
|
421
|
+
required: ['changes'],
|
|
422
|
+
},
|
|
423
|
+
},
|
|
424
|
+
{
|
|
425
|
+
name: 'generate_ics',
|
|
426
|
+
description: 'Export loaded calendar data as .ics text.',
|
|
427
|
+
inputSchema: {
|
|
428
|
+
type: 'object',
|
|
429
|
+
properties: {
|
|
430
|
+
calendars: {
|
|
431
|
+
type: 'array',
|
|
432
|
+
items: { type: 'string' },
|
|
433
|
+
description: 'Optional list of calendar ids to export.',
|
|
434
|
+
},
|
|
435
|
+
calendar_name: {
|
|
436
|
+
type: 'string',
|
|
437
|
+
description: 'Optional calendar name to set as X-WR-CALNAME.',
|
|
438
|
+
},
|
|
439
|
+
},
|
|
440
|
+
},
|
|
441
|
+
},
|
|
442
|
+
];
|
|
443
|
+
function jsonResult(value) {
|
|
444
|
+
const compact = JSON.stringify(value);
|
|
445
|
+
const text = compact.length > 4000 ? compact : JSON.stringify(value, null, 2);
|
|
446
|
+
return {
|
|
447
|
+
content: [
|
|
448
|
+
{
|
|
449
|
+
type: 'text',
|
|
450
|
+
text,
|
|
451
|
+
},
|
|
452
|
+
],
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
function errorResult(message) {
|
|
456
|
+
return {
|
|
457
|
+
content: [
|
|
458
|
+
{
|
|
459
|
+
type: 'text',
|
|
460
|
+
text: message,
|
|
461
|
+
},
|
|
462
|
+
],
|
|
463
|
+
isError: true,
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
function textResult(text) {
|
|
467
|
+
return {
|
|
468
|
+
content: [
|
|
469
|
+
{
|
|
470
|
+
type: 'text',
|
|
471
|
+
text,
|
|
472
|
+
},
|
|
473
|
+
],
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
function requireString(args, key) {
|
|
477
|
+
const value = args[key];
|
|
478
|
+
if (typeof value !== 'string' || value.trim() === '') {
|
|
479
|
+
throw new Error(`"${key}" must be a non-empty string.`);
|
|
480
|
+
}
|
|
481
|
+
return value;
|
|
482
|
+
}
|
|
483
|
+
function optionalString(args, key) {
|
|
484
|
+
const value = args[key];
|
|
485
|
+
if (value === undefined) {
|
|
486
|
+
return undefined;
|
|
487
|
+
}
|
|
488
|
+
if (typeof value !== 'string') {
|
|
489
|
+
throw new Error(`"${key}" must be a string when provided.`);
|
|
490
|
+
}
|
|
491
|
+
return value;
|
|
492
|
+
}
|
|
493
|
+
function optionalNumber(args, key, fallback) {
|
|
494
|
+
const value = args[key];
|
|
495
|
+
if (value === undefined) {
|
|
496
|
+
return fallback;
|
|
497
|
+
}
|
|
498
|
+
if (typeof value !== 'number' || Number.isNaN(value)) {
|
|
499
|
+
throw new Error(`"${key}" must be a number when provided.`);
|
|
500
|
+
}
|
|
501
|
+
return value;
|
|
502
|
+
}
|
|
503
|
+
function optionalLimit(args, fallback = 50) {
|
|
504
|
+
const value = optionalNumber(args, 'limit', fallback);
|
|
505
|
+
if (!Number.isInteger(value) || value < 0) {
|
|
506
|
+
throw new Error('"limit" must be a non-negative integer when provided.');
|
|
507
|
+
}
|
|
508
|
+
return value;
|
|
509
|
+
}
|
|
510
|
+
function optionalStringArray(args, key) {
|
|
511
|
+
const value = args[key];
|
|
512
|
+
if (value === undefined) {
|
|
513
|
+
return undefined;
|
|
514
|
+
}
|
|
515
|
+
if (!Array.isArray(value) || value.some(item => typeof item !== 'string')) {
|
|
516
|
+
throw new Error(`"${key}" must be an array of strings when provided.`);
|
|
517
|
+
}
|
|
518
|
+
return value;
|
|
519
|
+
}
|
|
520
|
+
function requireStringArray(args, key) {
|
|
521
|
+
const value = optionalStringArray(args, key);
|
|
522
|
+
if (!value || value.length === 0) {
|
|
523
|
+
throw new Error(`"${key}" must be a non-empty array of strings.`);
|
|
524
|
+
}
|
|
525
|
+
return value;
|
|
526
|
+
}
|
|
527
|
+
function requireRecord(value, label) {
|
|
528
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
529
|
+
throw new Error(`"${label}" must be an object.`);
|
|
530
|
+
}
|
|
531
|
+
return value;
|
|
532
|
+
}
|
|
533
|
+
function cloneRange(range) {
|
|
534
|
+
return structuredClone(range);
|
|
535
|
+
}
|
|
536
|
+
function parseProposedChangeUpdates(value) {
|
|
537
|
+
if (value === undefined) {
|
|
538
|
+
return undefined;
|
|
539
|
+
}
|
|
540
|
+
const record = requireRecord(value, 'updates');
|
|
541
|
+
return {
|
|
542
|
+
startTime: optionalString(record, 'startTime'),
|
|
543
|
+
endTime: optionalString(record, 'endTime'),
|
|
544
|
+
date: optionalString(record, 'date'),
|
|
545
|
+
fromDate: optionalString(record, 'fromDate'),
|
|
546
|
+
toDate: optionalString(record, 'toDate'),
|
|
547
|
+
};
|
|
548
|
+
}
|
|
549
|
+
function parseNewRange(value) {
|
|
550
|
+
if (value === undefined) {
|
|
551
|
+
return undefined;
|
|
552
|
+
}
|
|
553
|
+
const record = requireRecord(value, 'new_range');
|
|
554
|
+
const id = requireString(record, 'id');
|
|
555
|
+
const label = requireString(record, 'label');
|
|
556
|
+
return {
|
|
557
|
+
...record,
|
|
558
|
+
id,
|
|
559
|
+
label,
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
function parseProposedChanges(args) {
|
|
563
|
+
const value = args.changes;
|
|
564
|
+
if (!Array.isArray(value) || value.length === 0) {
|
|
565
|
+
throw new Error('"changes" must be a non-empty array.');
|
|
566
|
+
}
|
|
567
|
+
return value.map((item, index) => {
|
|
568
|
+
const record = requireRecord(item, `changes[${index}]`);
|
|
569
|
+
const action = requireString(record, 'action');
|
|
570
|
+
const reason = requireString(record, 'reason');
|
|
571
|
+
if (action !== 'move' && action !== 'add' && action !== 'remove') {
|
|
572
|
+
throw new Error(`changes[${index}].action must be "move", "add", or "remove".`);
|
|
573
|
+
}
|
|
574
|
+
return {
|
|
575
|
+
action,
|
|
576
|
+
range_id: optionalString(record, 'range_id'),
|
|
577
|
+
updates: parseProposedChangeUpdates(record.updates),
|
|
578
|
+
new_range: parseNewRange(record.new_range),
|
|
579
|
+
reason,
|
|
580
|
+
};
|
|
581
|
+
});
|
|
582
|
+
}
|
|
583
|
+
function parseDateArgument(value) {
|
|
584
|
+
const [year, month, day] = value.split('-').map(Number);
|
|
585
|
+
return new Date(year, month - 1, day);
|
|
586
|
+
}
|
|
587
|
+
function formatDateValue(date) {
|
|
588
|
+
return [
|
|
589
|
+
date.getFullYear(),
|
|
590
|
+
String(date.getMonth() + 1).padStart(2, '0'),
|
|
591
|
+
String(date.getDate()).padStart(2, '0'),
|
|
592
|
+
].join('-');
|
|
593
|
+
}
|
|
594
|
+
function formatWindow(window) {
|
|
595
|
+
return {
|
|
596
|
+
from: formatDateValue(window.from),
|
|
597
|
+
to: formatDateValue(window.to),
|
|
598
|
+
};
|
|
599
|
+
}
|
|
600
|
+
function truncateArray(items, key, limit) {
|
|
601
|
+
const truncated = items.length > limit;
|
|
602
|
+
return {
|
|
603
|
+
[key]: items.slice(0, limit),
|
|
604
|
+
total: items.length,
|
|
605
|
+
...(truncated
|
|
606
|
+
? {
|
|
607
|
+
truncated: true,
|
|
608
|
+
message: `Showing ${limit} of ${items.length}. Use a narrower window or increase limit.`,
|
|
609
|
+
}
|
|
610
|
+
: {}),
|
|
611
|
+
};
|
|
612
|
+
}
|
|
613
|
+
function collectUniqueLabels(ranges, limit) {
|
|
614
|
+
const labels = [...new Set(ranges.map(range => range.label))];
|
|
615
|
+
return {
|
|
616
|
+
labels: labels.slice(0, limit),
|
|
617
|
+
hasMore: labels.length > limit,
|
|
618
|
+
};
|
|
619
|
+
}
|
|
620
|
+
function requireLoadedCalendars(session, calendarIds) {
|
|
621
|
+
const uniqueIds = [...new Set(calendarIds)];
|
|
622
|
+
if (uniqueIds.length === 0) {
|
|
623
|
+
throw new Error('"calendars" must include at least one calendar id.');
|
|
624
|
+
}
|
|
625
|
+
const missing = uniqueIds.filter(calendarId => !session.calendars.has(calendarId));
|
|
626
|
+
if (missing.length > 0) {
|
|
627
|
+
throw new Error(`Unknown calendar id${missing.length === 1 ? '' : 's'}: ${missing.join(', ')}`);
|
|
628
|
+
}
|
|
629
|
+
return uniqueIds;
|
|
630
|
+
}
|
|
631
|
+
function getMetadataRecord(range) {
|
|
632
|
+
if (!range.metadata || typeof range.metadata !== 'object' || Array.isArray(range.metadata)) {
|
|
633
|
+
return undefined;
|
|
634
|
+
}
|
|
635
|
+
return range.metadata;
|
|
636
|
+
}
|
|
637
|
+
function readAttendees(value) {
|
|
638
|
+
if (!Array.isArray(value)) {
|
|
639
|
+
return undefined;
|
|
640
|
+
}
|
|
641
|
+
const attendees = value.flatMap((item) => {
|
|
642
|
+
if (typeof item !== 'object' || item === null || Array.isArray(item)) {
|
|
643
|
+
return [];
|
|
644
|
+
}
|
|
645
|
+
const record = item;
|
|
646
|
+
if (typeof record.email !== 'string' || record.email.trim() === '') {
|
|
647
|
+
return [];
|
|
648
|
+
}
|
|
649
|
+
return [
|
|
650
|
+
{
|
|
651
|
+
email: record.email,
|
|
652
|
+
...(typeof record.name === 'string' && record.name.trim() !== '' ? { name: record.name } : {}),
|
|
653
|
+
...(typeof record.role === 'string' && record.role.trim() !== '' ? { role: record.role } : {}),
|
|
654
|
+
...(typeof record.status === 'string' && record.status.trim() !== '' ? { status: record.status } : {}),
|
|
655
|
+
},
|
|
656
|
+
];
|
|
657
|
+
});
|
|
658
|
+
return attendees.length > 0 ? attendees : undefined;
|
|
659
|
+
}
|
|
660
|
+
function readOrganizer(value) {
|
|
661
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
662
|
+
return undefined;
|
|
663
|
+
}
|
|
664
|
+
const record = value;
|
|
665
|
+
if (typeof record.email !== 'string' || record.email.trim() === '') {
|
|
666
|
+
return undefined;
|
|
667
|
+
}
|
|
668
|
+
return {
|
|
669
|
+
email: record.email,
|
|
670
|
+
...(typeof record.name === 'string' && record.name.trim() !== '' ? { name: record.name } : {}),
|
|
671
|
+
};
|
|
672
|
+
}
|
|
673
|
+
function getRangeAttendees(range) {
|
|
674
|
+
return readAttendees(getMetadataRecord(range)?.attendees);
|
|
675
|
+
}
|
|
676
|
+
function getRangeOrganizer(range) {
|
|
677
|
+
return readOrganizer(getMetadataRecord(range)?.organizer);
|
|
678
|
+
}
|
|
679
|
+
function mergeAttendees(ranges) {
|
|
680
|
+
const attendeesByEmail = new Map();
|
|
681
|
+
for (const range of ranges) {
|
|
682
|
+
for (const attendee of getRangeAttendees(range) ?? []) {
|
|
683
|
+
if (!attendeesByEmail.has(attendee.email)) {
|
|
684
|
+
attendeesByEmail.set(attendee.email, attendee);
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
const attendees = [...attendeesByEmail.values()];
|
|
689
|
+
return attendees.length > 0 ? attendees : undefined;
|
|
690
|
+
}
|
|
691
|
+
function getFirstOrganizer(ranges) {
|
|
692
|
+
for (const range of ranges) {
|
|
693
|
+
const organizer = getRangeOrganizer(range);
|
|
694
|
+
if (organizer) {
|
|
695
|
+
return organizer;
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
return undefined;
|
|
699
|
+
}
|
|
700
|
+
function buildRecurrenceSummary(range) {
|
|
701
|
+
const weekdayLabels = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
|
|
702
|
+
if (range.everyWeekday?.length) {
|
|
703
|
+
return `weekly on ${range.everyWeekday.map(day => weekdayLabels[day] ?? String(day)).join(', ')}`;
|
|
704
|
+
}
|
|
705
|
+
if (range.everyDate?.length) {
|
|
706
|
+
return `monthly on ${range.everyDate.join(', ')}`;
|
|
707
|
+
}
|
|
708
|
+
if (range.everyMonth?.length) {
|
|
709
|
+
return `yearly in months ${range.everyMonth.join(', ')}`;
|
|
710
|
+
}
|
|
711
|
+
return undefined;
|
|
712
|
+
}
|
|
713
|
+
function rangeOverlapsDateFilter(range, from, to) {
|
|
714
|
+
if (!from && !to) {
|
|
715
|
+
return true;
|
|
716
|
+
}
|
|
717
|
+
const windowFrom = from ?? to;
|
|
718
|
+
const windowTo = to ?? from;
|
|
719
|
+
if (range.dates?.length) {
|
|
720
|
+
return range.dates.some(date => date >= windowFrom && date <= windowTo);
|
|
721
|
+
}
|
|
722
|
+
if (range.toDate && range.toDate < windowFrom) {
|
|
723
|
+
return false;
|
|
724
|
+
}
|
|
725
|
+
if (range.fromDate && range.fromDate > windowTo) {
|
|
726
|
+
return false;
|
|
727
|
+
}
|
|
728
|
+
return true;
|
|
729
|
+
}
|
|
730
|
+
function shiftDay(dateStr, delta) {
|
|
731
|
+
const [year, month, day] = dateStr.split('-').map(Number);
|
|
732
|
+
const next = new Date(year, month - 1, day + delta);
|
|
733
|
+
return [
|
|
734
|
+
next.getFullYear(),
|
|
735
|
+
String(next.getMonth() + 1).padStart(2, '0'),
|
|
736
|
+
String(next.getDate()).padStart(2, '0'),
|
|
737
|
+
].join('-');
|
|
738
|
+
}
|
|
739
|
+
function buildDayDetail(evaluator, ranges, date) {
|
|
740
|
+
const timeSlots = [];
|
|
741
|
+
const allDayRanges = [];
|
|
742
|
+
for (const range of ranges) {
|
|
743
|
+
if (!evaluator.isDateInRange(date, range)) {
|
|
744
|
+
continue;
|
|
745
|
+
}
|
|
746
|
+
const slots = evaluator.getTimeSlots(date, range);
|
|
747
|
+
if (slots.length > 0) {
|
|
748
|
+
timeSlots.push(...slots);
|
|
749
|
+
continue;
|
|
750
|
+
}
|
|
751
|
+
const previousDate = shiftDay(date, -1);
|
|
752
|
+
const nextDate = shiftDay(date, 1);
|
|
753
|
+
const previousInRange = evaluator.isDateInRange(previousDate, range);
|
|
754
|
+
const nextInRange = evaluator.isDateInRange(nextDate, range);
|
|
755
|
+
allDayRanges.push({
|
|
756
|
+
rangeId: range.id,
|
|
757
|
+
label: range.label,
|
|
758
|
+
isStart: !previousInRange,
|
|
759
|
+
isEnd: !nextInRange,
|
|
760
|
+
isContinuation: previousInRange && nextInRange,
|
|
761
|
+
...(range.displayType !== undefined ? { displayType: range.displayType } : {}),
|
|
762
|
+
});
|
|
763
|
+
}
|
|
764
|
+
timeSlots.sort((left, right) => left.startTime.localeCompare(right.startTime));
|
|
765
|
+
return { timeSlots, allDayRanges };
|
|
766
|
+
}
|
|
767
|
+
function buildSharedEvents(session, calendarIds, from, to) {
|
|
768
|
+
const sharedEvents = [];
|
|
769
|
+
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();
|
|
772
|
+
if (distinctCalendars.length < 2) {
|
|
773
|
+
continue;
|
|
774
|
+
}
|
|
775
|
+
const representative = filteredEntries[0].range;
|
|
776
|
+
const ranges = filteredEntries.map(entry => entry.range);
|
|
777
|
+
const attendees = mergeAttendees(ranges);
|
|
778
|
+
const organizer = getFirstOrganizer(ranges);
|
|
779
|
+
const recurrenceSummary = buildRecurrenceSummary(representative);
|
|
780
|
+
sharedEvents.push({
|
|
781
|
+
id,
|
|
782
|
+
label: representative.label,
|
|
783
|
+
...(representative.startTime ? { startTime: representative.startTime } : {}),
|
|
784
|
+
...(representative.endTime ? { endTime: representative.endTime } : {}),
|
|
785
|
+
...(recurrenceSummary ? { recurrence_summary: recurrenceSummary } : {}),
|
|
786
|
+
found_in_calendars: distinctCalendars,
|
|
787
|
+
...(attendees ? { attendees } : {}),
|
|
788
|
+
...(organizer ? { organizer } : {}),
|
|
789
|
+
});
|
|
790
|
+
}
|
|
791
|
+
sharedEvents.sort((left, right) => left.label.localeCompare(right.label) || left.id.localeCompare(right.id));
|
|
792
|
+
return sharedEvents;
|
|
793
|
+
}
|
|
794
|
+
function buildCommonAvailability(evaluator, ranges, from, to, options) {
|
|
795
|
+
return dateRange(from, to).flatMap(date => evaluator.findFreeSlots(ranges, date, options).map(slot => ({
|
|
796
|
+
date: slot.date,
|
|
797
|
+
start: slot.startTime,
|
|
798
|
+
end: slot.endTime,
|
|
799
|
+
duration_minutes: slot.duration,
|
|
800
|
+
})));
|
|
801
|
+
}
|
|
802
|
+
function findRangeById(ranges, rangeId) {
|
|
803
|
+
return ranges.find(range => range.id === rangeId);
|
|
804
|
+
}
|
|
805
|
+
function applyDateUpdate(range, date) {
|
|
806
|
+
if (range.dates?.length) {
|
|
807
|
+
if (range.dates.length !== 1) {
|
|
808
|
+
throw new Error(`Range "${range.id}" cannot apply a single "date" update because it has multiple explicit dates.`);
|
|
809
|
+
}
|
|
810
|
+
return {
|
|
811
|
+
...range,
|
|
812
|
+
dates: [date],
|
|
813
|
+
fromDate: undefined,
|
|
814
|
+
toDate: undefined,
|
|
815
|
+
};
|
|
816
|
+
}
|
|
817
|
+
if (range.fromDate !== undefined || range.toDate !== undefined) {
|
|
818
|
+
return {
|
|
819
|
+
...range,
|
|
820
|
+
dates: undefined,
|
|
821
|
+
fromDate: range.fromDate !== undefined ? date : range.fromDate,
|
|
822
|
+
toDate: range.toDate !== undefined ? date : range.toDate,
|
|
823
|
+
};
|
|
824
|
+
}
|
|
825
|
+
return {
|
|
826
|
+
...range,
|
|
827
|
+
dates: [date],
|
|
828
|
+
fromDate: undefined,
|
|
829
|
+
toDate: undefined,
|
|
830
|
+
};
|
|
831
|
+
}
|
|
832
|
+
function applyMoveToRange(range, updates) {
|
|
833
|
+
if (!updates) {
|
|
834
|
+
throw new Error(`Move change for range "${range.id}" is missing "updates".`);
|
|
835
|
+
}
|
|
836
|
+
let nextRange = cloneRange(range);
|
|
837
|
+
if (updates.date) {
|
|
838
|
+
nextRange = applyDateUpdate(nextRange, updates.date);
|
|
839
|
+
}
|
|
840
|
+
const { date: _date, ...rest } = updates;
|
|
841
|
+
return {
|
|
842
|
+
...nextRange,
|
|
843
|
+
...rest,
|
|
844
|
+
};
|
|
845
|
+
}
|
|
846
|
+
function applyChangesToRanges(ranges, changes) {
|
|
847
|
+
let nextRanges = ranges.map(cloneRange);
|
|
848
|
+
let changesApplied = 0;
|
|
849
|
+
for (const change of changes) {
|
|
850
|
+
switch (change.action) {
|
|
851
|
+
case 'move': {
|
|
852
|
+
if (!change.range_id) {
|
|
853
|
+
throw new Error('Move changes require "range_id".');
|
|
854
|
+
}
|
|
855
|
+
const index = nextRanges.findIndex(range => range.id === change.range_id);
|
|
856
|
+
if (index === -1) {
|
|
857
|
+
throw new Error(`Range "${change.range_id}" was not found in the current session.`);
|
|
858
|
+
}
|
|
859
|
+
nextRanges[index] = applyMoveToRange(nextRanges[index], change.updates);
|
|
860
|
+
changesApplied += 1;
|
|
861
|
+
break;
|
|
862
|
+
}
|
|
863
|
+
case 'add': {
|
|
864
|
+
if (!change.new_range) {
|
|
865
|
+
throw new Error('Add changes require "new_range".');
|
|
866
|
+
}
|
|
867
|
+
nextRanges = [...nextRanges, cloneRange(change.new_range)];
|
|
868
|
+
changesApplied += 1;
|
|
869
|
+
break;
|
|
870
|
+
}
|
|
871
|
+
case 'remove': {
|
|
872
|
+
if (!change.range_id) {
|
|
873
|
+
throw new Error('Remove changes require "range_id".');
|
|
874
|
+
}
|
|
875
|
+
const filteredRanges = nextRanges.filter(range => range.id !== change.range_id);
|
|
876
|
+
if (filteredRanges.length === nextRanges.length) {
|
|
877
|
+
throw new Error(`Range "${change.range_id}" was not found in the current session.`);
|
|
878
|
+
}
|
|
879
|
+
nextRanges = filteredRanges;
|
|
880
|
+
changesApplied += 1;
|
|
881
|
+
break;
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
return { ranges: nextRanges, changesApplied };
|
|
886
|
+
}
|
|
887
|
+
function getRangeDateWindow(range) {
|
|
888
|
+
if (range.dates?.length) {
|
|
889
|
+
const sortedDates = [...range.dates].sort();
|
|
890
|
+
return {
|
|
891
|
+
from: sortedDates[0],
|
|
892
|
+
to: sortedDates[sortedDates.length - 1],
|
|
893
|
+
};
|
|
894
|
+
}
|
|
895
|
+
const dates = [range.fromDate, range.toDate].filter((value) => Boolean(value)).sort();
|
|
896
|
+
if (dates.length > 0) {
|
|
897
|
+
return {
|
|
898
|
+
from: dates[0],
|
|
899
|
+
to: dates[dates.length - 1],
|
|
900
|
+
};
|
|
901
|
+
}
|
|
902
|
+
return undefined;
|
|
903
|
+
}
|
|
904
|
+
function getDefaultSuggestionWindow(currentRanges, changes) {
|
|
905
|
+
const windows = [];
|
|
906
|
+
for (const change of changes) {
|
|
907
|
+
if (change.action === 'add') {
|
|
908
|
+
if (!change.new_range) {
|
|
909
|
+
throw new Error('Add changes require "new_range".');
|
|
910
|
+
}
|
|
911
|
+
const window = getRangeDateWindow(change.new_range);
|
|
912
|
+
if (window) {
|
|
913
|
+
windows.push(window);
|
|
914
|
+
}
|
|
915
|
+
continue;
|
|
916
|
+
}
|
|
917
|
+
if (!change.range_id) {
|
|
918
|
+
throw new Error(`${change.action === 'move' ? 'Move' : 'Remove'} changes require "range_id".`);
|
|
919
|
+
}
|
|
920
|
+
const range = findRangeById(currentRanges, change.range_id);
|
|
921
|
+
if (!range) {
|
|
922
|
+
throw new Error(`Range "${change.range_id}" was not found in the current session.`);
|
|
923
|
+
}
|
|
924
|
+
const originalWindow = getRangeDateWindow(range);
|
|
925
|
+
if (originalWindow) {
|
|
926
|
+
windows.push(originalWindow);
|
|
927
|
+
}
|
|
928
|
+
if (change.action === 'move') {
|
|
929
|
+
const movedWindow = getRangeDateWindow(applyMoveToRange(range, change.updates));
|
|
930
|
+
if (movedWindow) {
|
|
931
|
+
windows.push(movedWindow);
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
if (windows.length === 0) {
|
|
936
|
+
throw new Error('Could not infer a scoring window from the proposed changes. Provide "from" and "to".');
|
|
937
|
+
}
|
|
938
|
+
const earliest = windows.map(window => window.from).sort()[0];
|
|
939
|
+
const latest = windows.map(window => window.to).sort()[windows.length - 1];
|
|
940
|
+
return {
|
|
941
|
+
from: shiftDay(earliest, -7),
|
|
942
|
+
to: shiftDay(latest, 7),
|
|
943
|
+
};
|
|
944
|
+
}
|
|
945
|
+
function summarizeSchedule(evaluator, ranges, from, to) {
|
|
946
|
+
const fromDate = parseDateArgument(from);
|
|
947
|
+
const toDate = parseDateArgument(to);
|
|
948
|
+
return {
|
|
949
|
+
score: scoreSchedule(evaluator, ranges, fromDate, toDate),
|
|
950
|
+
conflicts: evaluator.findConflictsInWindow(ranges, fromDate, toDate).length,
|
|
951
|
+
};
|
|
952
|
+
}
|
|
953
|
+
function applyChangesToSession(session, changes) {
|
|
954
|
+
let changesApplied = 0;
|
|
955
|
+
for (const change of changes) {
|
|
956
|
+
switch (change.action) {
|
|
957
|
+
case 'move': {
|
|
958
|
+
if (!change.range_id) {
|
|
959
|
+
throw new Error('Move changes require "range_id".');
|
|
960
|
+
}
|
|
961
|
+
const calendarId = session.findRangeCalendar(change.range_id);
|
|
962
|
+
if (!calendarId) {
|
|
963
|
+
throw new Error(`Range "${change.range_id}" was not found in the current session.`);
|
|
964
|
+
}
|
|
965
|
+
const range = findRangeById(session.getAllRanges([calendarId]), change.range_id);
|
|
966
|
+
if (!range) {
|
|
967
|
+
throw new Error(`Range "${change.range_id}" was not found in the current session.`);
|
|
968
|
+
}
|
|
969
|
+
session.updateRange(change.range_id, applyMoveToRange(range, change.updates));
|
|
970
|
+
changesApplied += 1;
|
|
971
|
+
break;
|
|
972
|
+
}
|
|
973
|
+
case 'add': {
|
|
974
|
+
if (!change.new_range) {
|
|
975
|
+
throw new Error('Add changes require "new_range".');
|
|
976
|
+
}
|
|
977
|
+
const firstCalendarId = session.calendars.keys().next().value;
|
|
978
|
+
session.addRange(firstCalendarId ?? 'proposals', cloneRange(change.new_range));
|
|
979
|
+
changesApplied += 1;
|
|
980
|
+
break;
|
|
981
|
+
}
|
|
982
|
+
case 'remove': {
|
|
983
|
+
if (!change.range_id) {
|
|
984
|
+
throw new Error('Remove changes require "range_id".');
|
|
985
|
+
}
|
|
986
|
+
if (!session.removeRange(change.range_id)) {
|
|
987
|
+
throw new Error(`Range "${change.range_id}" was not found in the current session.`);
|
|
988
|
+
}
|
|
989
|
+
changesApplied += 1;
|
|
990
|
+
break;
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
return changesApplied;
|
|
995
|
+
}
|
|
996
|
+
function applyTimezone(session, timezone) {
|
|
997
|
+
if (!timezone) {
|
|
998
|
+
return;
|
|
999
|
+
}
|
|
1000
|
+
session.timezone = timezone;
|
|
1001
|
+
session.evaluator = new RangeEvaluator(timezone);
|
|
1002
|
+
}
|
|
1003
|
+
function getRanges(session, args) {
|
|
1004
|
+
return session.getAllRanges(optionalStringArray(args, 'calendars'));
|
|
1005
|
+
}
|
|
1006
|
+
function getParseWindow() {
|
|
1007
|
+
const from = new Date();
|
|
1008
|
+
from.setMonth(from.getMonth() - 1);
|
|
1009
|
+
const to = new Date();
|
|
1010
|
+
to.setMonth(to.getMonth() + 6);
|
|
1011
|
+
return { from, to };
|
|
1012
|
+
}
|
|
1013
|
+
function loadIcsData(icsText, requestedWindow) {
|
|
1014
|
+
const detectedWindow = detectDataWindow(icsText);
|
|
1015
|
+
let ranges = parseICS(icsText, requestedWindow);
|
|
1016
|
+
let effectiveWindow = requestedWindow;
|
|
1017
|
+
// If we got very few results but the data lives elsewhere, re-parse
|
|
1018
|
+
// with the detected window. Unbounded recurrences (no UNTIL) match
|
|
1019
|
+
// any window, so a small result count doesn't mean the window is right.
|
|
1020
|
+
if (detectedWindow && ranges.length < 10) {
|
|
1021
|
+
const detectedRanges = parseICS(icsText, detectedWindow);
|
|
1022
|
+
if (detectedRanges.length > ranges.length) {
|
|
1023
|
+
ranges = detectedRanges;
|
|
1024
|
+
effectiveWindow = detectedWindow;
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
return { ranges, effectiveWindow, detectedWindow };
|
|
1028
|
+
}
|
|
1029
|
+
function buildLoadResponse(session, ranges, calendarId, source, effectiveWindow, detectedWindow) {
|
|
1030
|
+
session.loadCalendar(calendarId, ranges, source);
|
|
1031
|
+
const labelSummary = collectUniqueLabels(ranges, 20);
|
|
1032
|
+
return jsonResult({
|
|
1033
|
+
calendars_loaded: session.calendars.size,
|
|
1034
|
+
ranges_loaded: ranges.length,
|
|
1035
|
+
calendar_id: calendarId,
|
|
1036
|
+
effective_window: formatWindow(effectiveWindow),
|
|
1037
|
+
detected_data_window: detectedWindow ? formatWindow(detectedWindow) : null,
|
|
1038
|
+
sample_labels: labelSummary.labels,
|
|
1039
|
+
has_more_labels: labelSummary.hasMore,
|
|
1040
|
+
});
|
|
1041
|
+
}
|
|
1042
|
+
export async function handleToolCall(session, name, rawArgs) {
|
|
1043
|
+
const args = rawArgs ?? {};
|
|
1044
|
+
try {
|
|
1045
|
+
switch (name) {
|
|
1046
|
+
case 'load_calendar': {
|
|
1047
|
+
const source = requireString(args, 'source');
|
|
1048
|
+
const data = requireString(args, 'data');
|
|
1049
|
+
const id = optionalString(args, 'id');
|
|
1050
|
+
const timezone = optionalString(args, 'timezone');
|
|
1051
|
+
const windowFrom = optionalString(args, 'window_from');
|
|
1052
|
+
const windowTo = optionalString(args, 'window_to');
|
|
1053
|
+
if (source !== 'ics' && source !== 'ranges' && source !== 'gcal' && source !== 'msft') {
|
|
1054
|
+
throw new Error('"source" must be "ics", "ranges", "gcal", or "msft".');
|
|
1055
|
+
}
|
|
1056
|
+
if ((windowFrom && !windowTo) || (!windowFrom && windowTo)) {
|
|
1057
|
+
throw new Error('"window_from" and "window_to" must be provided together.');
|
|
1058
|
+
}
|
|
1059
|
+
applyTimezone(session, timezone);
|
|
1060
|
+
const requestedWindow = windowFrom && windowTo
|
|
1061
|
+
? { from: parseDateArgument(windowFrom), to: parseDateArgument(windowTo) }
|
|
1062
|
+
: getParseWindow();
|
|
1063
|
+
const calendarId = session.createCalendarId(id);
|
|
1064
|
+
if (source === 'ics') {
|
|
1065
|
+
const result = loadIcsData(data, requestedWindow);
|
|
1066
|
+
return buildLoadResponse(session, result.ranges, calendarId, 'ics', result.effectiveWindow, result.detectedWindow);
|
|
1067
|
+
}
|
|
1068
|
+
if (source === 'gcal') {
|
|
1069
|
+
const parsed = JSON.parse(data);
|
|
1070
|
+
if (!Array.isArray(parsed)) {
|
|
1071
|
+
throw new Error('Google Calendar JSON must decode to an array of events.');
|
|
1072
|
+
}
|
|
1073
|
+
const ranges = gcalEventsToDateRanges(parsed);
|
|
1074
|
+
return buildLoadResponse(session, ranges, calendarId, 'gcal', requestedWindow, null);
|
|
1075
|
+
}
|
|
1076
|
+
if (source === 'msft') {
|
|
1077
|
+
const parsed = JSON.parse(data);
|
|
1078
|
+
if (!Array.isArray(parsed)) {
|
|
1079
|
+
throw new Error('Microsoft Graph JSON must decode to an array of events.');
|
|
1080
|
+
}
|
|
1081
|
+
const ranges = msftEventsToDateRanges(parsed);
|
|
1082
|
+
return buildLoadResponse(session, ranges, calendarId, 'msft', requestedWindow, null);
|
|
1083
|
+
}
|
|
1084
|
+
const parsed = JSON.parse(data);
|
|
1085
|
+
if (!Array.isArray(parsed)) {
|
|
1086
|
+
throw new Error('Range JSON must decode to an array.');
|
|
1087
|
+
}
|
|
1088
|
+
return buildLoadResponse(session, parsed, calendarId, 'ranges', requestedWindow, null);
|
|
1089
|
+
}
|
|
1090
|
+
case 'load_calendar_file': {
|
|
1091
|
+
const filePath = requireString(args, 'path');
|
|
1092
|
+
const id = optionalString(args, 'id');
|
|
1093
|
+
const timezone = optionalString(args, 'timezone');
|
|
1094
|
+
const windowFrom = optionalString(args, 'window_from');
|
|
1095
|
+
const windowTo = optionalString(args, 'window_to');
|
|
1096
|
+
if ((windowFrom && !windowTo) || (!windowFrom && windowTo)) {
|
|
1097
|
+
throw new Error('"window_from" and "window_to" must be provided together.');
|
|
1098
|
+
}
|
|
1099
|
+
applyTimezone(session, timezone);
|
|
1100
|
+
const data = readFileSync(filePath, 'utf8');
|
|
1101
|
+
const requestedWindow = windowFrom && windowTo
|
|
1102
|
+
? { from: parseDateArgument(windowFrom), to: parseDateArgument(windowTo) }
|
|
1103
|
+
: getParseWindow();
|
|
1104
|
+
const calendarId = session.createCalendarId(id);
|
|
1105
|
+
const result = loadIcsData(data, requestedWindow);
|
|
1106
|
+
return buildLoadResponse(session, result.ranges, calendarId, 'ics', result.effectiveWindow, result.detectedWindow);
|
|
1107
|
+
}
|
|
1108
|
+
case 'find_conflicts': {
|
|
1109
|
+
const from = requireString(args, 'from');
|
|
1110
|
+
const to = requireString(args, 'to');
|
|
1111
|
+
const ranges = getRanges(session, args);
|
|
1112
|
+
const limit = optionalLimit(args);
|
|
1113
|
+
const conflicts = session.evaluator.findConflictsInWindow(ranges, parseDateArgument(from), parseDateArgument(to));
|
|
1114
|
+
return jsonResult(truncateArray(conflicts, 'conflicts', limit));
|
|
1115
|
+
}
|
|
1116
|
+
case 'find_free_slots': {
|
|
1117
|
+
const date = requireString(args, 'date');
|
|
1118
|
+
const ranges = getRanges(session, args);
|
|
1119
|
+
const limit = optionalLimit(args);
|
|
1120
|
+
const freeSlots = session.evaluator.findFreeSlots(ranges, date, {
|
|
1121
|
+
minDuration: optionalNumber(args, 'min_duration', 30),
|
|
1122
|
+
dayStart: optionalString(args, 'day_start') ?? '09:00',
|
|
1123
|
+
dayEnd: optionalString(args, 'day_end') ?? '17:00',
|
|
1124
|
+
});
|
|
1125
|
+
return jsonResult(truncateArray(freeSlots, 'free_slots', limit));
|
|
1126
|
+
}
|
|
1127
|
+
case 'find_shared_events': {
|
|
1128
|
+
const requestedCalendars = optionalStringArray(args, 'calendars');
|
|
1129
|
+
const calendarsCompared = requestedCalendars
|
|
1130
|
+
? requireLoadedCalendars(session, requestedCalendars)
|
|
1131
|
+
: [...session.calendars.keys()];
|
|
1132
|
+
const from = optionalString(args, 'from');
|
|
1133
|
+
const to = optionalString(args, 'to');
|
|
1134
|
+
const limit = optionalLimit(args);
|
|
1135
|
+
const sharedEvents = buildSharedEvents(session, calendarsCompared, from, to);
|
|
1136
|
+
return jsonResult({
|
|
1137
|
+
...truncateArray(sharedEvents, 'shared_events', limit),
|
|
1138
|
+
calendars_compared: calendarsCompared,
|
|
1139
|
+
});
|
|
1140
|
+
}
|
|
1141
|
+
case 'find_common_availability': {
|
|
1142
|
+
const calendars = requireLoadedCalendars(session, requireStringArray(args, 'calendars'));
|
|
1143
|
+
if (calendars.length < 2) {
|
|
1144
|
+
throw new Error('"calendars" must include at least two calendar ids.');
|
|
1145
|
+
}
|
|
1146
|
+
const from = requireString(args, 'from');
|
|
1147
|
+
const to = requireString(args, 'to');
|
|
1148
|
+
const limit = optionalLimit(args, 20);
|
|
1149
|
+
const ranges = session.getAllRanges(calendars);
|
|
1150
|
+
const commonSlots = buildCommonAvailability(session.evaluator, ranges, from, to, {
|
|
1151
|
+
minDuration: optionalNumber(args, 'min_duration', 30),
|
|
1152
|
+
dayStart: optionalString(args, 'day_start') ?? '09:00',
|
|
1153
|
+
dayEnd: optionalString(args, 'day_end') ?? '17:00',
|
|
1154
|
+
});
|
|
1155
|
+
return jsonResult({
|
|
1156
|
+
...truncateArray(commonSlots, 'common_slots', limit),
|
|
1157
|
+
calendars_checked: calendars,
|
|
1158
|
+
search_window: { from, to },
|
|
1159
|
+
});
|
|
1160
|
+
}
|
|
1161
|
+
case 'find_next_free_slot': {
|
|
1162
|
+
const from = requireString(args, 'from');
|
|
1163
|
+
const to = requireString(args, 'to');
|
|
1164
|
+
const duration = optionalNumber(args, 'duration', Number.NaN);
|
|
1165
|
+
const ranges = getRanges(session, args);
|
|
1166
|
+
if (Number.isNaN(duration)) {
|
|
1167
|
+
throw new Error('"duration" must be provided.');
|
|
1168
|
+
}
|
|
1169
|
+
return jsonResult(session.evaluator.findNextFreeSlot(ranges, parseDateArgument(from), parseDateArgument(to), duration, {
|
|
1170
|
+
dayStart: optionalString(args, 'day_start'),
|
|
1171
|
+
dayEnd: optionalString(args, 'day_end'),
|
|
1172
|
+
}));
|
|
1173
|
+
}
|
|
1174
|
+
case 'score_schedule': {
|
|
1175
|
+
const from = requireString(args, 'from');
|
|
1176
|
+
const to = requireString(args, 'to');
|
|
1177
|
+
const ranges = getRanges(session, args);
|
|
1178
|
+
return jsonResult(scoreSchedule(session.evaluator, ranges, parseDateArgument(from), parseDateArgument(to), {
|
|
1179
|
+
focusBlockMinutes: optionalNumber(args, 'focus_block_minutes', 60),
|
|
1180
|
+
dayStart: optionalString(args, 'day_start'),
|
|
1181
|
+
dayEnd: optionalString(args, 'day_end'),
|
|
1182
|
+
}));
|
|
1183
|
+
}
|
|
1184
|
+
case 'day_detail': {
|
|
1185
|
+
const date = requireString(args, 'date');
|
|
1186
|
+
const ranges = getRanges(session, args);
|
|
1187
|
+
const limit = optionalLimit(args);
|
|
1188
|
+
const detail = buildDayDetail(session.evaluator, ranges, date);
|
|
1189
|
+
const truncatedTimeSlots = truncateArray(detail.timeSlots, 'timeSlots', limit);
|
|
1190
|
+
return jsonResult({
|
|
1191
|
+
...truncatedTimeSlots,
|
|
1192
|
+
allDayRanges: detail.allDayRanges,
|
|
1193
|
+
total_time_slots: detail.timeSlots.length,
|
|
1194
|
+
});
|
|
1195
|
+
}
|
|
1196
|
+
case 'expand_range': {
|
|
1197
|
+
const rangeId = requireString(args, 'range_id');
|
|
1198
|
+
const from = requireString(args, 'from');
|
|
1199
|
+
const to = requireString(args, 'to');
|
|
1200
|
+
const limit = optionalLimit(args);
|
|
1201
|
+
const range = session.getAllRanges().find(candidate => candidate.id === rangeId);
|
|
1202
|
+
if (!range) {
|
|
1203
|
+
throw new Error(`Range "${rangeId}" was not found in the current session.`);
|
|
1204
|
+
}
|
|
1205
|
+
const occurrences = session.evaluator.expand(range, parseDateArgument(from), parseDateArgument(to));
|
|
1206
|
+
return jsonResult(truncateArray(occurrences, 'occurrences', limit));
|
|
1207
|
+
}
|
|
1208
|
+
case 'list_calendars': {
|
|
1209
|
+
return jsonResult(session.getCalendarSummary());
|
|
1210
|
+
}
|
|
1211
|
+
case 'suggest_changes': {
|
|
1212
|
+
const changes = parseProposedChanges(args);
|
|
1213
|
+
const currentRanges = session.getAllRanges();
|
|
1214
|
+
const defaultWindow = getDefaultSuggestionWindow(currentRanges, changes);
|
|
1215
|
+
const from = optionalString(args, 'from') ?? defaultWindow.from;
|
|
1216
|
+
const to = optionalString(args, 'to') ?? defaultWindow.to;
|
|
1217
|
+
const preview = applyChangesToRanges(currentRanges, changes);
|
|
1218
|
+
return jsonResult({
|
|
1219
|
+
before: summarizeSchedule(session.evaluator, currentRanges, from, to),
|
|
1220
|
+
after: summarizeSchedule(session.evaluator, preview.ranges, from, to),
|
|
1221
|
+
changes_applied: preview.changesApplied,
|
|
1222
|
+
});
|
|
1223
|
+
}
|
|
1224
|
+
case 'apply_changes': {
|
|
1225
|
+
const changes = parseProposedChanges(args);
|
|
1226
|
+
const changesApplied = applyChangesToSession(session, changes);
|
|
1227
|
+
return jsonResult({
|
|
1228
|
+
changes_applied: changesApplied,
|
|
1229
|
+
total_ranges: session.getAllRanges().length,
|
|
1230
|
+
});
|
|
1231
|
+
}
|
|
1232
|
+
case 'generate_ics': {
|
|
1233
|
+
const ranges = getRanges(session, args);
|
|
1234
|
+
const calendarName = optionalString(args, 'calendar_name');
|
|
1235
|
+
return textResult(generateICS(ranges, { calendarName }));
|
|
1236
|
+
}
|
|
1237
|
+
default:
|
|
1238
|
+
return errorResult(`Unknown tool: ${name}`);
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
catch (error) {
|
|
1242
|
+
return errorResult(error instanceof Error ? error.message : String(error));
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
export function createServer(session = new CalendarSession()) {
|
|
1246
|
+
const server = new Server({ name: 'daywatch-mcp', version: '0.1.0' }, {
|
|
1247
|
+
capabilities: {
|
|
1248
|
+
tools: {},
|
|
1249
|
+
},
|
|
1250
|
+
instructions: SERVER_INSTRUCTIONS,
|
|
1251
|
+
});
|
|
1252
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
1253
|
+
tools: TOOLS,
|
|
1254
|
+
}));
|
|
1255
|
+
server.setRequestHandler(CallToolRequestSchema, async (request) => handleToolCall(session, request.params.name, request.params.arguments));
|
|
1256
|
+
return server;
|
|
1257
|
+
}
|
|
1258
|
+
//# sourceMappingURL=server.js.map
|