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.",
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        };
268        let _permit = self.permit().await?;
269        let created = try_cal!(self.calendar.create_event(&calendar, &draft).await);
270        respond(
271            &WriteOut {
272                id: encode_resource(&created),
273                etag: None,
274            },
275            "event created".to_owned(),
276        )
277    }
278
279    /// Changes an event when its `ETag` still matches.
280    ///
281    /// # Errors
282    ///
283    /// Returns [`ErrorData::invalid_params`] when an id, `ETag` or time is not
284    /// usable, and a tool error when the event changed since it was read.
285    #[tool(
286        title = "Update event",
287        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.",
288        annotations(read_only_hint = false, destructive_hint = true, open_world_hint = true),
289        output_schema = rmcp::handler::server::tool::schema_for_output::<WriteOut>(),
290    )]
291    pub async fn calendar_update_event(
292        &self,
293        Parameters(params): Parameters<UpdateEventParams>,
294    ) -> Result<CallToolResult, ErrorData> {
295        self.reject_write()?;
296        let path = require_path(&params.id)?;
297        let etag = require_etag(&params.etag)?;
298        if params.start.is_some() != params.end.is_some() {
299            return Err(ErrorData::invalid_params(
300                "give both start and end, or neither",
301                None,
302            ));
303        }
304        let scope = match params.occurrence {
305            Some(recurrence_id) => {
306                if params.start.is_none() || params.end.is_none() {
307                    return Err(ErrorData::invalid_params(
308                        "changing one occurrence needs start and end",
309                        None,
310                    ));
311                }
312                UpdateScope::Occurrence { recurrence_id }
313            }
314            None => UpdateScope::Series,
315        };
316        let _permit = self.permit().await?;
317        // Left-out fields stay empty: the provider keeps what the event has. Copying
318        // them from the first occurrence would write that occurrence's values onto
319        // the whole series.
320        let draft = EventDraft {
321            summary: params.summary.unwrap_or_default(),
322            description: params.description,
323            start: params.start.unwrap_or_default(),
324            end: params.end.unwrap_or_default(),
325            time_zone: params.time_zone,
326        };
327        let fresh = try_cal!(
328            self.calendar
329                .update_event(&path, &etag, &draft, &scope)
330                .await
331        );
332        respond(
333            &WriteOut {
334                id: params.id,
335                etag: Some(fresh.as_str().to_owned()),
336            },
337            "event updated".to_owned(),
338        )
339    }
340
341    /// Deletes an event when its `ETag` still matches.
342    ///
343    /// # Errors
344    ///
345    /// Returns [`ErrorData::invalid_params`] when the id or `ETag` is not
346    /// usable, and a tool error when the event changed since it was read.
347    #[tool(
348        title = "Delete event",
349        description = "Deletes an event. Needs the etag from the last read; a changed event is refused.",
350        annotations(read_only_hint = false, destructive_hint = true, open_world_hint = true),
351        output_schema = rmcp::handler::server::tool::schema_for_output::<DeleteOut>(),
352    )]
353    pub async fn calendar_delete_event(
354        &self,
355        Parameters(params): Parameters<DeleteParams>,
356    ) -> Result<CallToolResult, ErrorData> {
357        self.reject_write()?;
358        let path = require_path(&params.id)?;
359        let etag = require_etag(&params.etag)?;
360        let _permit = self.permit().await?;
361        try_cal!(self.calendar.delete_event(&path, &etag).await);
362        respond(&DeleteOut { deleted: true }, "event deleted".to_owned())
363    }
364
365    /// Lists reminder lists, and says that upgraded lists are out of reach.
366    ///
367    /// # Errors
368    ///
369    /// Returns an MCP error when the lists cannot be read.
370    #[tool(
371        title = "List reminder lists",
372        description = "Lists reminder lists. Only old-style lists can be reached; the result says so. Names are as their owner set them.",
373        annotations(read_only_hint = true, destructive_hint = false, open_world_hint = true),
374        output_schema = rmcp::handler::server::tool::schema_for_output::<ReminderListsOut>(),
375    )]
376    pub async fn reminders_list_lists(&self) -> Result<CallToolResult, ErrorData> {
377        let _permit = self.permit().await?;
378        let lists = try_cal!(self.calendar.list_lists().await);
379        let listed: Vec<ReminderListOut> = lists
380            .iter()
381            .map(|list| ReminderListOut {
382                id: encode_resource(&list.path),
383                name: strip_hidden(&list.name),
384            })
385            .collect();
386        let summary = format!("{} lists. {UPGRADED_LISTS_NOTE}", listed.len());
387        respond(
388            &ReminderListsOut {
389                lists: listed,
390                note: UPGRADED_LISTS_NOTE,
391            },
392            summary,
393        )
394    }
395
396    /// Lists reminders, open ones unless completed ones are asked for.
397    ///
398    /// # Errors
399    ///
400    /// Returns [`ErrorData::invalid_params`] when the list id or page size is
401    /// not usable, and an MCP error when the reminders cannot be read.
402    #[tool(
403        title = "List reminders",
404        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.",
405        annotations(read_only_hint = true, destructive_hint = false, open_world_hint = true),
406        output_schema = rmcp::handler::server::tool::schema_for_output::<RemindersOut>(),
407    )]
408    pub async fn reminders_list(
409        &self,
410        Parameters(params): Parameters<ListRemindersParams>,
411    ) -> Result<CallToolResult, ErrorData> {
412        let limit = page_limit(params.limit)?;
413        let start_at = cursor_offset(params.cursor.as_deref())?;
414        let list = params.list.as_deref().map(require_path).transpose()?;
415        let filter = if params.include_completed.unwrap_or(false) {
416            CompletedFilter::All
417        } else {
418            CompletedFilter::Open
419        };
420        let _permit = self.permit().await?;
421        let listed = try_cal!(self.calendar.list(list.as_ref(), filter).await);
422        let (reminders, next_cursor) = page(listed.reminders, limit, start_at);
423        let summary = format!("{} reminders", reminders.len());
424        respond(
425            &RemindersOut {
426                reminders: reminders.iter().map(reminder_out).collect(),
427                next_cursor,
428                warnings: listed.warnings,
429            },
430            summary,
431        )
432    }
433
434    /// Creates a reminder in a task list.
435    ///
436    /// # Errors
437    ///
438    /// Returns [`ErrorData::invalid_params`] when the list id, due date or
439    /// priority is not usable, and an MCP error when it cannot be written.
440    #[tool(
441        title = "Create reminder",
442        description = "Creates a reminder in a reminder list.",
443        annotations(read_only_hint = false, destructive_hint = true, open_world_hint = true),
444        output_schema = rmcp::handler::server::tool::schema_for_output::<WriteOut>(),
445    )]
446    pub async fn reminders_create(
447        &self,
448        Parameters(params): Parameters<CreateReminderParams>,
449    ) -> Result<CallToolResult, ErrorData> {
450        self.reject_write()?;
451        let list = require_path(&params.list)?;
452        let draft = ReminderDraft {
453            title: params.title,
454            notes: params.notes.unwrap_or_default(),
455            due: params.due.filter(|due| !due.is_empty()),
456            priority: params.priority.filter(|priority| *priority != 0),
457            completed: false,
458        };
459        let _permit = self.permit().await?;
460        let created = try_cal!(self.calendar.create(&list, &draft).await);
461        respond(
462            &WriteOut {
463                id: encode_resource(&created),
464                etag: None,
465            },
466            "reminder created".to_owned(),
467        )
468    }
469
470    /// Changes a reminder when its `ETag` still matches. Completing is an update.
471    ///
472    /// # Errors
473    ///
474    /// Returns [`ErrorData::invalid_params`] when an id, `ETag`, due date or
475    /// priority is not usable, and a tool error when the reminder changed.
476    #[tool(
477        title = "Update reminder",
478        description = "Changes a reminder, including marking it completed. Needs the etag from the last read; a changed reminder is refused.",
479        annotations(read_only_hint = false, destructive_hint = true, open_world_hint = true),
480        output_schema = rmcp::handler::server::tool::schema_for_output::<WriteOut>(),
481    )]
482    pub async fn reminders_update(
483        &self,
484        Parameters(params): Parameters<UpdateReminderParams>,
485    ) -> Result<CallToolResult, ErrorData> {
486        self.reject_write()?;
487        let path = require_path(&params.id)?;
488        let etag = require_etag(&params.etag)?;
489        let _permit = self.permit().await?;
490        let current = try_cal!(self.calendar.get(&path).await);
491        let draft = ReminderDraft {
492            title: params.title.unwrap_or(current.title),
493            notes: params.notes.unwrap_or(current.notes),
494            due: match params.due {
495                None => current.due,
496                Some(due) if due.is_empty() => None,
497                Some(due) => Some(due),
498            },
499            priority: match params.priority {
500                None => current.priority,
501                Some(0) => None,
502                Some(priority) => Some(priority),
503            },
504            completed: params.completed.unwrap_or(current.completed),
505        };
506        let fresh = try_cal!(self.calendar.update(&path, &etag, &draft).await);
507        respond(
508            &WriteOut {
509                id: params.id,
510                etag: Some(fresh.as_str().to_owned()),
511            },
512            "reminder updated".to_owned(),
513        )
514    }
515
516    /// Deletes a reminder when its `ETag` still matches.
517    ///
518    /// # Errors
519    ///
520    /// Returns [`ErrorData::invalid_params`] when the id or `ETag` is not
521    /// usable, and a tool error when the reminder changed since it was read.
522    #[tool(
523        title = "Delete reminder",
524        description = "Deletes a reminder. Needs the etag from the last read; a changed reminder is refused.",
525        annotations(read_only_hint = false, destructive_hint = true, open_world_hint = true),
526        output_schema = rmcp::handler::server::tool::schema_for_output::<DeleteOut>(),
527    )]
528    pub async fn reminders_delete(
529        &self,
530        Parameters(params): Parameters<DeleteParams>,
531    ) -> Result<CallToolResult, ErrorData> {
532        self.reject_write()?;
533        let path = require_path(&params.id)?;
534        let etag = require_etag(&params.etag)?;
535        let _permit = self.permit().await?;
536        try_cal!(self.calendar.delete(&path, &etag).await);
537        respond(&DeleteOut { deleted: true }, "reminder deleted".to_owned())
538    }
539}
540
541pub(crate) fn require_path(id: &str) -> Result<ResourcePath, ErrorData> {
542    decode_resource(id).map_err(|_| ErrorData::invalid_params("invalid id", None))
543}
544
545pub(crate) fn require_etag(etag: &str) -> Result<ETag, ErrorData> {
546    ETag::try_from(etag).map_err(|_| ErrorData::invalid_params("invalid etag", None))
547}
548
549fn cursor_offset(cursor: Option<&str>) -> Result<usize, ErrorData> {
550    match cursor {
551        None => Ok(0),
552        Some(text) => text
553            .parse()
554            .map_err(|_| ErrorData::invalid_params("invalid cursor", None)),
555    }
556}
557
558/// One page of `items`, and the cursor for the next page when there is one.
559pub(crate) fn page<T>(items: Vec<T>, limit: u32, start: usize) -> (Vec<T>, Option<String>) {
560    let limit = usize::try_from(limit).unwrap_or(usize::MAX);
561    let end = start.saturating_add(limit);
562    let more = items.len() > end;
563    let shown = items.into_iter().skip(start).take(limit).collect();
564    (shown, more.then(|| end.to_string()))
565}
566
567/// The most characters of a description or note a tool returns, like a mail body.
568pub(crate) const BODY_LIMIT: usize = 40_000;
569
570/// `text` cut to [`BODY_LIMIT`] characters, with a marker saying how much is missing.
571pub(crate) fn capped(text: &str) -> String {
572    let Some((end, _)) = text.char_indices().nth(BODY_LIMIT) else {
573        return text.to_owned();
574    };
575    let missing = text[end..].chars().count();
576    format!("{}\n[truncated, {missing} more characters]", &text[..end])
577}
578
579fn event_out(event: &Event) -> EventOut {
580    EventOut {
581        id: encode_resource(&event.path),
582        etag: event.etag.as_str().to_owned(),
583        uid: event.uid.clone(),
584        summary: strip_hidden(&event.summary),
585        description: strip_hidden(&capped(&event.description)),
586        start: event.start.clone(),
587        end: event.end.clone(),
588        time_zone: event.time_zone.clone(),
589        all_day: event.all_day,
590        recurring: event.recurring,
591        recurrence_id: event.recurrence_id.clone(),
592        attendees: event.attendees.iter().map(|a| strip_hidden(a)).collect(),
593        alarms: event.alarms.clone(),
594    }
595}
596
597fn reminder_out(reminder: &Reminder) -> ReminderOut {
598    ReminderOut {
599        id: encode_resource(&reminder.path),
600        etag: reminder.etag.as_str().to_owned(),
601        title: strip_hidden(&reminder.title),
602        notes: strip_hidden(&capped(&reminder.notes)),
603        due: reminder.due.clone(),
604        priority: reminder.priority,
605        completed: reminder.completed,
606    }
607}