Skip to main content

ibridge_server/
calendar_tools.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Calendar and reminders tools.
4
5use ibridge_core::{
6    Calendar, CalendarProvider, CompletedFilter, ContactsProvider, CoreError, ETag, Event,
7    EventDraft, EventList, EventQuery, Reminder, ReminderDraft, ReminderList, ReminderPage,
8    RemindersProvider, ResourcePath, UPGRADED_LISTS_NOTE, UpdateScope, decode_resource,
9    encode_resource,
10};
11use rmcp::handler::server::wrapper::Parameters;
12use rmcp::model::{CallToolResult, ErrorData};
13use rmcp::tool;
14use rmcp::tool_router;
15
16use crate::calendar_dto::{
17    CalendarListOut, CalendarOut, CreateEventParams, CreateReminderParams, DeleteOut, DeleteParams,
18    EventListOut, EventOut, GetByIdParams, ListEventsParams, ListRemindersParams, ReminderListOut,
19    ReminderListsOut, ReminderOut, RemindersOut, UpdateEventParams, UpdateReminderParams, WriteOut,
20};
21use crate::handler::{IbridgeServer, mapped, page_limit, respond};
22use crate::mail_api::MailApi;
23use crate::sanitize::strip_hidden;
24
25pub(crate) const CALENDAR_TOOLS: &[&str] = &[
26    "calendar_create_event",
27    "calendar_delete_event",
28    "calendar_get_event",
29    "calendar_list_calendars",
30    "calendar_list_events",
31    "calendar_update_event",
32    "reminders_create",
33    "reminders_delete",
34    "reminders_list",
35    "reminders_list_lists",
36    "reminders_update",
37];
38
39pub(crate) const CALENDAR_WRITE_TOOLS: &[&str] = &[
40    "calendar_create_event",
41    "calendar_delete_event",
42    "calendar_update_event",
43    "reminders_create",
44    "reminders_delete",
45    "reminders_update",
46];
47
48/// The calendar backend of a server that has none. Its tools stay hidden.
49#[derive(Debug, Clone, Copy, Default)]
50pub struct NoCalendar;
51
52fn off<T>() -> Result<T, CoreError> {
53    Err(CoreError::Unsupported("calendar is not enabled"))
54}
55
56#[expect(
57    clippy::unused_async_trait_impl,
58    reason = "the stand-in answers without waiting"
59)]
60impl CalendarProvider for NoCalendar {
61    async fn list_calendars(&self) -> Result<Vec<Calendar>, CoreError> {
62        off()
63    }
64    async fn list_events(&self, _query: &EventQuery) -> Result<EventList, CoreError> {
65        off()
66    }
67    async fn get_event(&self, _path: &ResourcePath) -> Result<Event, CoreError> {
68        off()
69    }
70    async fn create_event(
71        &self,
72        _calendar: &ResourcePath,
73        _draft: &EventDraft,
74    ) -> Result<ResourcePath, CoreError> {
75        off()
76    }
77    async fn update_event(
78        &self,
79        _path: &ResourcePath,
80        _etag: &ETag,
81        _draft: &EventDraft,
82        _scope: &UpdateScope,
83    ) -> Result<ETag, CoreError> {
84        off()
85    }
86    async fn delete_event(&self, _path: &ResourcePath, _etag: &ETag) -> Result<(), CoreError> {
87        off()
88    }
89}
90
91#[expect(
92    clippy::unused_async_trait_impl,
93    reason = "the stand-in answers without waiting"
94)]
95impl RemindersProvider for NoCalendar {
96    async fn list_lists(&self) -> Result<Vec<ReminderList>, CoreError> {
97        off()
98    }
99    async fn list(
100        &self,
101        _list: Option<&ResourcePath>,
102        _completed: CompletedFilter,
103    ) -> Result<ReminderPage, CoreError> {
104        off()
105    }
106    async fn get(&self, _path: &ResourcePath) -> Result<Reminder, CoreError> {
107        off()
108    }
109    async fn create(
110        &self,
111        _list: &ResourcePath,
112        _draft: &ReminderDraft,
113    ) -> Result<ResourcePath, CoreError> {
114        off()
115    }
116    async fn update(
117        &self,
118        _path: &ResourcePath,
119        _etag: &ETag,
120        _draft: &ReminderDraft,
121    ) -> Result<ETag, CoreError> {
122        off()
123    }
124    async fn delete(&self, _path: &ResourcePath, _etag: &ETag) -> Result<(), CoreError> {
125        off()
126    }
127}
128
129macro_rules! try_cal {
130    ($call:expr) => {
131        match $call {
132            Ok(value) => value,
133            Err(error) => return mapped(&error),
134        }
135    };
136}
137
138#[tool_router(router = calendar_router, vis = "pub(crate)")]
139impl<M, C, K> IbridgeServer<M, C, K>
140where
141    M: MailApi + Send + Sync + 'static,
142    C: CalendarProvider + RemindersProvider + Send + Sync + 'static,
143    K: ContactsProvider + Send + Sync + 'static,
144{
145    /// Lists calendars and says whether each holds events, tasks or both.
146    ///
147    /// # Errors
148    ///
149    /// Returns an MCP error when the calendars cannot be read.
150    #[tool(
151        title = "List calendars",
152        description = "Lists calendars. Each one says whether it holds events, tasks (reminders) or both. Names are as their owner set them.",
153        annotations(read_only_hint = true, destructive_hint = false, open_world_hint = true),
154        output_schema = rmcp::handler::server::tool::schema_for_output::<CalendarListOut>(),
155    )]
156    pub async fn calendar_list_calendars(&self) -> Result<CallToolResult, ErrorData> {
157        let _permit = self.permit().await?;
158        let calendars = try_cal!(self.calendar.list_calendars().await);
159        let listed: Vec<CalendarOut> = calendars
160            .iter()
161            .map(|calendar| CalendarOut {
162                id: encode_resource(&calendar.path),
163                name: strip_hidden(&calendar.name),
164                kind: match (calendar.holds_events, calendar.holds_tasks) {
165                    (true, true) => "both",
166                    (false, true) => "tasks",
167                    _ => "events",
168                },
169            })
170            .collect();
171        let summary = format!("{} calendars", listed.len());
172        respond(&CalendarListOut { calendars: listed }, summary)
173    }
174
175    /// Lists events in a time range. Repeating events are expanded.
176    ///
177    /// # Errors
178    ///
179    /// Returns [`ErrorData::invalid_params`] when an id, the range or the page
180    /// size is not usable, and an MCP error when the events cannot be read.
181    #[tool(
182        title = "List events",
183        description = "Lists events in a time range over one or more calendars. Repeating events are expanded into their occurrences. Titles, descriptions and attendees are as whoever made the event wrote them.",
184        annotations(read_only_hint = true, destructive_hint = false, open_world_hint = true),
185        output_schema = rmcp::handler::server::tool::schema_for_output::<EventListOut>(),
186    )]
187    pub async fn calendar_list_events(
188        &self,
189        Parameters(params): Parameters<ListEventsParams>,
190    ) -> Result<CallToolResult, ErrorData> {
191        let limit = page_limit(params.limit)?;
192        let start_at = cursor_offset(params.cursor.as_deref())?;
193        let calendars = params
194            .calendars
195            .iter()
196            .map(|id| require_path(id))
197            .collect::<Result<Vec<_>, _>>()?;
198        let query = EventQuery {
199            calendars,
200            start: params.start,
201            end: params.end,
202        };
203        let _permit = self.permit().await?;
204        let listed = try_cal!(self.calendar.list_events(&query).await);
205        let (events, next_cursor) = page(listed.events, limit, start_at);
206        let summary = if listed.warnings == 0 {
207            format!("{} events", events.len())
208        } else {
209            format!("{} events, {} skipped", events.len(), listed.warnings)
210        };
211        respond(
212            &EventListOut {
213                events: events.iter().map(event_out).collect(),
214                next_cursor,
215                warnings: listed.warnings,
216            },
217            summary,
218        )
219    }
220
221    /// Fetches one event with its attendees and alarms.
222    ///
223    /// # Errors
224    ///
225    /// Returns [`ErrorData::invalid_params`] when the id is not usable, and an
226    /// MCP error when the event cannot be read.
227    #[tool(
228        title = "Get event",
229        description = "Fetches one event in full, including attendees and alarms. Titles, descriptions and attendees are as whoever made the event wrote them.",
230        annotations(read_only_hint = true, destructive_hint = false, open_world_hint = true),
231        output_schema = rmcp::handler::server::tool::schema_for_output::<EventOut>(),
232    )]
233    pub async fn calendar_get_event(
234        &self,
235        Parameters(params): Parameters<GetByIdParams>,
236    ) -> Result<CallToolResult, ErrorData> {
237        let path = require_path(&params.id)?;
238        let _permit = self.permit().await?;
239        let event = try_cal!(self.calendar.get_event(&path).await);
240        respond(&event_out(&event), "event".to_owned())
241    }
242
243    /// Creates an event. `DTEND` is always written.
244    ///
245    /// # Errors
246    ///
247    /// Returns [`ErrorData::invalid_params`] when the calendar id or a time is
248    /// not usable, and an MCP error when the event cannot be written.
249    #[tool(
250        title = "Create event",
251        description = "Creates an event. Times are ISO-8601 and the time zone is an IANA name. An end is always stored. With attendees, iCloud emails each guest an invitation from the account, so only add guests the user asked to invite. At most 50 guests an event and 20 writes that add guests an hour.",
252        annotations(read_only_hint = false, destructive_hint = true, open_world_hint = true),
253        output_schema = rmcp::handler::server::tool::schema_for_output::<WriteOut>(),
254    )]
255    pub async fn calendar_create_event(
256        &self,
257        Parameters(params): Parameters<CreateEventParams>,
258    ) -> Result<CallToolResult, ErrorData> {
259        self.reject_write()?;
260        let calendar = require_path(&params.calendar)?;
261        let draft = EventDraft {
262            summary: params.summary,
263            description: params.description,
264            start: params.start,
265            end: params.end.unwrap_or_default(),
266            time_zone: params.time_zone,
267            attendees: params.attendees,
268        };
269        let _permit = self.permit().await?;
270        let created = try_cal!(self.calendar.create_event(&calendar, &draft).await);
271        respond(
272            &WriteOut {
273                id: encode_resource(&created),
274                etag: None,
275            },
276            "event created".to_owned(),
277        )
278    }
279
280    /// Changes an event when its `ETag` still matches.
281    ///
282    /// # Errors
283    ///
284    /// Returns [`ErrorData::invalid_params`] when an id, `ETag` or time is not
285    /// usable, and a tool error when the event changed since it was read.
286    #[tool(
287        title = "Update event",
288        description = "Changes an event. Needs the etag from the last read; a changed event is refused. Applies to the whole series unless an occurrence is named. If the event has guests, iCloud emails them the change. Attendees replaces the guest list of the whole series: iCloud emails an invitation to each added guest and a cancellation to each removed one, so only change guests the user asked for. Only the organizer can change guests.",
289        annotations(read_only_hint = false, destructive_hint = true, open_world_hint = true),
290        output_schema = rmcp::handler::server::tool::schema_for_output::<WriteOut>(),
291    )]
292    pub async fn calendar_update_event(
293        &self,
294        Parameters(params): Parameters<UpdateEventParams>,
295    ) -> Result<CallToolResult, ErrorData> {
296        self.reject_write()?;
297        let path = require_path(&params.id)?;
298        let etag = require_etag(&params.etag)?;
299        if params.start.is_some() != params.end.is_some() {
300            return Err(ErrorData::invalid_params(
301                "give both start and end, or neither",
302                None,
303            ));
304        }
305        let scope = match params.occurrence {
306            Some(recurrence_id) => {
307                if params.start.is_none() || params.end.is_none() {
308                    return Err(ErrorData::invalid_params(
309                        "changing one occurrence needs start and end",
310                        None,
311                    ));
312                }
313                UpdateScope::Occurrence { recurrence_id }
314            }
315            None => UpdateScope::Series,
316        };
317        let _permit = self.permit().await?;
318        // Left-out fields stay empty: the provider keeps what the event has. Copying
319        // them from the first occurrence would write that occurrence's values onto
320        // the whole series.
321        let draft = EventDraft {
322            summary: params.summary.unwrap_or_default(),
323            description: params.description,
324            start: params.start.unwrap_or_default(),
325            end: params.end.unwrap_or_default(),
326            time_zone: params.time_zone,
327            attendees: params.attendees,
328        };
329        let fresh = try_cal!(
330            self.calendar
331                .update_event(&path, &etag, &draft, &scope)
332                .await
333        );
334        respond(
335            &WriteOut {
336                id: params.id,
337                etag: Some(fresh.as_str().to_owned()),
338            },
339            "event updated".to_owned(),
340        )
341    }
342
343    /// Deletes an event when its `ETag` still matches.
344    ///
345    /// # Errors
346    ///
347    /// Returns [`ErrorData::invalid_params`] when the id or `ETag` is not
348    /// usable, and a tool error when the event changed since it was read.
349    #[tool(
350        title = "Delete event",
351        description = "Deletes an event. Needs the etag from the last read; a changed event is refused. If the event has guests, iCloud emails them a cancellation.",
352        annotations(read_only_hint = false, destructive_hint = true, open_world_hint = true),
353        output_schema = rmcp::handler::server::tool::schema_for_output::<DeleteOut>(),
354    )]
355    pub async fn calendar_delete_event(
356        &self,
357        Parameters(params): Parameters<DeleteParams>,
358    ) -> Result<CallToolResult, ErrorData> {
359        self.reject_write()?;
360        let path = require_path(&params.id)?;
361        let etag = require_etag(&params.etag)?;
362        let _permit = self.permit().await?;
363        try_cal!(self.calendar.delete_event(&path, &etag).await);
364        respond(&DeleteOut { deleted: true }, "event deleted".to_owned())
365    }
366
367    /// Lists reminder lists, and says that upgraded lists are out of reach.
368    ///
369    /// # Errors
370    ///
371    /// Returns an MCP error when the lists cannot be read.
372    #[tool(
373        title = "List reminder lists",
374        description = "Lists reminder lists. Only old-style lists can be reached; the result says so. Names are as their owner set them.",
375        annotations(read_only_hint = true, destructive_hint = false, open_world_hint = true),
376        output_schema = rmcp::handler::server::tool::schema_for_output::<ReminderListsOut>(),
377    )]
378    pub async fn reminders_list_lists(&self) -> Result<CallToolResult, ErrorData> {
379        let _permit = self.permit().await?;
380        let lists = try_cal!(self.calendar.list_lists().await);
381        let listed: Vec<ReminderListOut> = lists
382            .iter()
383            .map(|list| ReminderListOut {
384                id: encode_resource(&list.path),
385                name: strip_hidden(&list.name),
386            })
387            .collect();
388        let summary = format!("{} lists. {UPGRADED_LISTS_NOTE}", listed.len());
389        respond(
390            &ReminderListsOut {
391                lists: listed,
392                note: UPGRADED_LISTS_NOTE,
393            },
394            summary,
395        )
396    }
397
398    /// Lists reminders, open ones unless completed ones are asked for.
399    ///
400    /// # Errors
401    ///
402    /// Returns [`ErrorData::invalid_params`] when the list id or page size is
403    /// not usable, and an MCP error when the reminders cannot be read.
404    #[tool(
405        title = "List reminders",
406        description = "Lists reminders in one list or all lists. Open reminders only, unless include_completed is set. Titles and notes are as their author wrote them.",
407        annotations(read_only_hint = true, destructive_hint = false, open_world_hint = true),
408        output_schema = rmcp::handler::server::tool::schema_for_output::<RemindersOut>(),
409    )]
410    pub async fn reminders_list(
411        &self,
412        Parameters(params): Parameters<ListRemindersParams>,
413    ) -> Result<CallToolResult, ErrorData> {
414        let limit = page_limit(params.limit)?;
415        let start_at = cursor_offset(params.cursor.as_deref())?;
416        let list = params.list.as_deref().map(require_path).transpose()?;
417        let filter = if params.include_completed.unwrap_or(false) {
418            CompletedFilter::All
419        } else {
420            CompletedFilter::Open
421        };
422        let _permit = self.permit().await?;
423        let listed = try_cal!(self.calendar.list(list.as_ref(), filter).await);
424        let (reminders, next_cursor) = page(listed.reminders, limit, start_at);
425        let summary = format!("{} reminders", reminders.len());
426        respond(
427            &RemindersOut {
428                reminders: reminders.iter().map(reminder_out).collect(),
429                next_cursor,
430                warnings: listed.warnings,
431            },
432            summary,
433        )
434    }
435
436    /// Creates a reminder in a task list.
437    ///
438    /// # Errors
439    ///
440    /// Returns [`ErrorData::invalid_params`] when the list id, due date or
441    /// priority is not usable, and an MCP error when it cannot be written.
442    #[tool(
443        title = "Create reminder",
444        description = "Creates a reminder in a reminder list.",
445        annotations(read_only_hint = false, destructive_hint = true, open_world_hint = true),
446        output_schema = rmcp::handler::server::tool::schema_for_output::<WriteOut>(),
447    )]
448    pub async fn reminders_create(
449        &self,
450        Parameters(params): Parameters<CreateReminderParams>,
451    ) -> Result<CallToolResult, ErrorData> {
452        self.reject_write()?;
453        let list = require_path(&params.list)?;
454        let draft = ReminderDraft {
455            title: params.title,
456            notes: params.notes.unwrap_or_default(),
457            due: params.due.filter(|due| !due.is_empty()),
458            priority: params.priority.filter(|priority| *priority != 0),
459            completed: false,
460        };
461        let _permit = self.permit().await?;
462        let created = try_cal!(self.calendar.create(&list, &draft).await);
463        respond(
464            &WriteOut {
465                id: encode_resource(&created),
466                etag: None,
467            },
468            "reminder created".to_owned(),
469        )
470    }
471
472    /// Changes a reminder when its `ETag` still matches. Completing is an update.
473    ///
474    /// # Errors
475    ///
476    /// Returns [`ErrorData::invalid_params`] when an id, `ETag`, due date or
477    /// priority is not usable, and a tool error when the reminder changed.
478    #[tool(
479        title = "Update reminder",
480        description = "Changes a reminder, including marking it completed. Needs the etag from the last read; a changed reminder is refused.",
481        annotations(read_only_hint = false, destructive_hint = true, open_world_hint = true),
482        output_schema = rmcp::handler::server::tool::schema_for_output::<WriteOut>(),
483    )]
484    pub async fn reminders_update(
485        &self,
486        Parameters(params): Parameters<UpdateReminderParams>,
487    ) -> Result<CallToolResult, ErrorData> {
488        self.reject_write()?;
489        let path = require_path(&params.id)?;
490        let etag = require_etag(&params.etag)?;
491        let _permit = self.permit().await?;
492        let current = try_cal!(self.calendar.get(&path).await);
493        let draft = ReminderDraft {
494            title: params.title.unwrap_or(current.title),
495            notes: params.notes.unwrap_or(current.notes),
496            due: match params.due {
497                None => current.due,
498                Some(due) if due.is_empty() => None,
499                Some(due) => Some(due),
500            },
501            priority: match params.priority {
502                None => current.priority,
503                Some(0) => None,
504                Some(priority) => Some(priority),
505            },
506            completed: params.completed.unwrap_or(current.completed),
507        };
508        let fresh = try_cal!(self.calendar.update(&path, &etag, &draft).await);
509        respond(
510            &WriteOut {
511                id: params.id,
512                etag: Some(fresh.as_str().to_owned()),
513            },
514            "reminder updated".to_owned(),
515        )
516    }
517
518    /// Deletes a reminder when its `ETag` still matches.
519    ///
520    /// # Errors
521    ///
522    /// Returns [`ErrorData::invalid_params`] when the id or `ETag` is not
523    /// usable, and a tool error when the reminder changed since it was read.
524    #[tool(
525        title = "Delete reminder",
526        description = "Deletes a reminder. Needs the etag from the last read; a changed reminder is refused.",
527        annotations(read_only_hint = false, destructive_hint = true, open_world_hint = true),
528        output_schema = rmcp::handler::server::tool::schema_for_output::<DeleteOut>(),
529    )]
530    pub async fn reminders_delete(
531        &self,
532        Parameters(params): Parameters<DeleteParams>,
533    ) -> Result<CallToolResult, ErrorData> {
534        self.reject_write()?;
535        let path = require_path(&params.id)?;
536        let etag = require_etag(&params.etag)?;
537        let _permit = self.permit().await?;
538        try_cal!(self.calendar.delete(&path, &etag).await);
539        respond(&DeleteOut { deleted: true }, "reminder deleted".to_owned())
540    }
541}
542
543pub(crate) fn require_path(id: &str) -> Result<ResourcePath, ErrorData> {
544    decode_resource(id).map_err(|_| ErrorData::invalid_params("invalid id", None))
545}
546
547pub(crate) fn require_etag(etag: &str) -> Result<ETag, ErrorData> {
548    ETag::try_from(etag).map_err(|_| ErrorData::invalid_params("invalid etag", None))
549}
550
551fn cursor_offset(cursor: Option<&str>) -> Result<usize, ErrorData> {
552    match cursor {
553        None => Ok(0),
554        Some(text) => text
555            .parse()
556            .map_err(|_| ErrorData::invalid_params("invalid cursor", None)),
557    }
558}
559
560/// One page of `items`, and the cursor for the next page when there is one.
561pub(crate) fn page<T>(items: Vec<T>, limit: u32, start: usize) -> (Vec<T>, Option<String>) {
562    let limit = usize::try_from(limit).unwrap_or(usize::MAX);
563    let end = start.saturating_add(limit);
564    let more = items.len() > end;
565    let shown = items.into_iter().skip(start).take(limit).collect();
566    (shown, more.then(|| end.to_string()))
567}
568
569/// The most characters of a description or note a tool returns, like a mail body.
570pub(crate) const BODY_LIMIT: usize = 40_000;
571
572/// `text` cut to [`BODY_LIMIT`] characters, with a marker saying how much is missing.
573pub(crate) fn capped(text: &str) -> String {
574    let Some((end, _)) = text.char_indices().nth(BODY_LIMIT) else {
575        return text.to_owned();
576    };
577    let missing = text[end..].chars().count();
578    format!("{}\n[truncated, {missing} more characters]", &text[..end])
579}
580
581fn event_out(event: &Event) -> EventOut {
582    EventOut {
583        id: encode_resource(&event.path),
584        etag: event.etag.as_str().to_owned(),
585        uid: event.uid.clone(),
586        summary: strip_hidden(&event.summary),
587        description: strip_hidden(&capped(&event.description)),
588        start: event.start.clone(),
589        end: event.end.clone(),
590        time_zone: event.time_zone.clone(),
591        all_day: event.all_day,
592        recurring: event.recurring,
593        recurrence_id: event.recurrence_id.clone(),
594        attendees: event.attendees.iter().map(|a| strip_hidden(a)).collect(),
595        alarms: event.alarms.clone(),
596    }
597}
598
599fn reminder_out(reminder: &Reminder) -> ReminderOut {
600    ReminderOut {
601        id: encode_resource(&reminder.path),
602        etag: reminder.etag.as_str().to_owned(),
603        title: strip_hidden(&reminder.title),
604        notes: strip_hidden(&capped(&reminder.notes)),
605        due: reminder.due.clone(),
606        priority: reminder.priority,
607        completed: reminder.completed,
608    }
609}