Skip to main content

ibridge_server/
handler.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Server handler. One server is one account, with at most four tool calls in flight.
4
5use std::fmt;
6use std::path::{Path, PathBuf};
7use std::sync::Arc;
8
9use ibridge_core::{
10    CalendarProvider, ContactsProvider, CoreError, Draft, FlagChange, MailSearch, Mailbox,
11    MailboxPath, MailboxRole, Message, MessageId, MessageSummary, OneClickFailure,
12    RemindersProvider, Unsubscribe, UnsubscribeMethod, decode, encode,
13};
14use rmcp::handler::server::tool::ToolRouter;
15use rmcp::handler::server::wrapper::Parameters;
16use rmcp::model::{CallToolResult, ContentBlock, ErrorData, Tool};
17use rmcp::{ServerHandler, tool, tool_handler, tool_router};
18use tokio::sync::{OwnedSemaphorePermit, Semaphore};
19
20use crate::account::{AccountSnapshot, ServiceStatus};
21use crate::calendar_tools::{CALENDAR_TOOLS, CALENDAR_WRITE_TOOLS, NoCalendar};
22use crate::contacts_tools::{CONTACTS_TOOLS, CONTACTS_WRITE_TOOLS, NoContacts};
23use crate::dto::{
24    AccountStatusOut, AttachmentInfoOut, AttachmentOut, FlagParams, FlagsOut, GetAttachmentParams,
25    GetMessageParams, IdOut, MailboxListOut, MailboxOut, MessageOut, MoveOut, MoveParams,
26    SaveAttachmentParams, SavedAttachmentOut, SearchHitOut, SearchOut, SearchParams, SendOut,
27    SendParams, ServiceOut, ServiceState, UnsubscribeMethodOut, UnsubscribeMethodParam,
28    UnsubscribeOut, UnsubscribeParams, UnsubscribeStatus, UnsubscribedOut,
29};
30use crate::error_map::{MappedError, map_core_error};
31use crate::mail_api::{MailApi, MailDest, Unsubscribed};
32use crate::sanitize::strip_hidden;
33use crate::save::{safe_name, save_unique};
34
35const MAX_IN_FLIGHT: usize = 4;
36const DEFAULT_LIMIT: u32 = 25;
37const MAX_LIMIT: u32 = 100;
38const SENT_COPY_WARNING: &str = "sent, but the copy was not saved to Sent Messages";
39const LINK_ONLY_NOTE: &str = "The sender offers only a web link and does not support one-click unsubscribe, so nothing was sent. The link is as the sender wrote it; open it in a browser to unsubscribe.";
40const MAILTO_NOT_SENT: &str = "The sender also offers an unsubscribe email; it was not sent automatically. To send it, call mail_unsubscribe again with `\"method\": \"mailto\"`.";
41const NO_OTHER_ROUTE: &str =
42    "The message offers no other unsubscribe route that can be used automatically.";
43const ONE_CLICK_NOTE: &str = "The sender's server accepted the one-click unsubscribe request. The sender decides when it takes effect.";
44const SAVE_ATTACHMENT: &str = "mail_save_attachment";
45const MAIL_TOOLS: &[&str] = &[
46    "mail_create_draft",
47    "mail_get_attachment",
48    "mail_get_message",
49    "mail_list_mailboxes",
50    "mail_move",
51    "mail_save_attachment",
52    "mail_search",
53    "mail_send",
54    "mail_set_flags",
55    "mail_unsubscribe",
56];
57const WRITE_TOOLS: &[&str] = &[
58    "mail_create_draft",
59    "mail_move",
60    "mail_save_attachment",
61    "mail_send",
62    "mail_set_flags",
63    "mail_unsubscribe",
64];
65
66macro_rules! try_mail {
67    ($call:expr) => {
68        match $call {
69            Ok(value) => value,
70            Err(error) => return mapped(&error),
71        }
72    };
73}
74
75/// Whether a service's tools are in the tool list.
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77enum Tools {
78    /// The tools are listed.
79    Shown,
80    /// The tools are hidden.
81    Hidden,
82}
83
84/// Which services' tools are listed, and where saved attachments go.
85#[derive(Debug, Clone)]
86struct Tools3 {
87    mail: Tools,
88    calendar: Tools,
89    contacts: Tools,
90    downloads: Option<Arc<Path>>,
91}
92
93/// Who may call write tools.
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95enum Access {
96    /// Write tools are hidden and rejected.
97    ReadOnly,
98    /// Read and write tools are available.
99    ReadWrite,
100}
101
102/// MCP server for one account.
103///
104/// At most four tool calls run at once. A read-only server omits write tools
105/// from the tool list and rejects a direct write call. Calendar and reminders
106/// tools appear once [`IbridgeServer::with_calendar`] gives the server a backend,
107/// and contacts tools once [`IbridgeServer::with_contacts`] does.
108pub struct IbridgeServer<M, C = NoCalendar, K = NoContacts> {
109    access: Access,
110    account: AccountSnapshot,
111    mail: Arc<M>,
112    pub(crate) calendar: Arc<C>,
113    pub(crate) contacts: Arc<K>,
114    mail_tools: Tools,
115    calendar_tools: Tools,
116    contacts_tools: Tools,
117    downloads: Option<Arc<Path>>,
118    gate: Arc<Semaphore>,
119    router: ToolRouter<Self>,
120}
121
122impl<M, C, K> fmt::Debug for IbridgeServer<M, C, K> {
123    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124        f.debug_struct("IbridgeServer")
125            .field("access", &self.access)
126            .field("account", &self.account)
127            .finish_non_exhaustive()
128    }
129}
130
131impl<M, C, K> Clone for IbridgeServer<M, C, K> {
132    fn clone(&self) -> Self {
133        Self {
134            access: self.access,
135            account: self.account.clone(),
136            mail: Arc::clone(&self.mail),
137            calendar: Arc::clone(&self.calendar),
138            contacts: Arc::clone(&self.contacts),
139            mail_tools: self.mail_tools,
140            calendar_tools: self.calendar_tools,
141            contacts_tools: self.contacts_tools,
142            downloads: self.downloads.clone(),
143            gate: Arc::clone(&self.gate),
144            router: self.router.clone(),
145        }
146    }
147}
148
149impl<M> IbridgeServer<M, NoCalendar, NoContacts>
150where
151    M: MailApi + Send + Sync + 'static,
152{
153    /// Hides write tools from the tool list and rejects write calls.
154    #[must_use]
155    pub fn read_only(account: AccountSnapshot, mail: Arc<M>) -> Self {
156        Self::build(
157            Access::ReadOnly,
158            account,
159            mail,
160            Arc::new(NoCalendar),
161            Arc::new(NoContacts),
162        )
163    }
164
165    /// Shows read and write tools.
166    #[must_use]
167    pub fn read_write(account: AccountSnapshot, mail: Arc<M>) -> Self {
168        Self::build(
169            Access::ReadWrite,
170            account,
171            mail,
172            Arc::new(NoCalendar),
173            Arc::new(NoContacts),
174        )
175    }
176}
177
178impl<M, C, K> IbridgeServer<M, C, K>
179where
180    M: MailApi + Send + Sync + 'static,
181    C: CalendarProvider + RemindersProvider + Send + Sync + 'static,
182    K: ContactsProvider + Send + Sync + 'static,
183{
184    /// Shows the calendar and reminders tools, backed by `calendar`.
185    #[must_use]
186    pub fn with_calendar<C2>(self, calendar: Arc<C2>) -> IbridgeServer<M, C2, K>
187    where
188        C2: CalendarProvider + RemindersProvider + Send + Sync + 'static,
189    {
190        IbridgeServer::<M, C2, K>::build_with(
191            self.access,
192            self.account,
193            self.mail,
194            calendar,
195            self.contacts,
196            Tools3 {
197                mail: self.mail_tools,
198                calendar: Tools::Shown,
199                contacts: self.contacts_tools,
200                downloads: self.downloads,
201            },
202        )
203    }
204
205    /// Shows the contacts tools, backed by `contacts`.
206    #[must_use]
207    pub fn with_contacts<K2>(self, contacts: Arc<K2>) -> IbridgeServer<M, C, K2>
208    where
209        K2: ContactsProvider + Send + Sync + 'static,
210    {
211        IbridgeServer::<M, C, K2>::build_with(
212            self.access,
213            self.account,
214            self.mail,
215            self.calendar,
216            contacts,
217            Tools3 {
218                mail: self.mail_tools,
219                calendar: self.calendar_tools,
220                contacts: Tools::Shown,
221                downloads: self.downloads,
222            },
223        )
224    }
225
226    /// Shows `mail_save_attachment`, which saves files into `dir`.
227    ///
228    /// Only the local run modes call this. A hosted server never writes to disk.
229    #[must_use]
230    pub fn with_downloads(mut self, dir: PathBuf) -> Self {
231        self.downloads = Some(Arc::from(dir));
232        if self.access == Access::ReadWrite && self.mail_tools == Tools::Shown {
233            self.router.enable_route(SAVE_ATTACHMENT);
234        }
235        self
236    }
237
238    /// Hides every contacts tool.
239    #[must_use]
240    pub fn without_contacts(mut self) -> Self {
241        for name in CONTACTS_TOOLS {
242            self.router.disable_route(*name);
243        }
244        self.contacts_tools = Tools::Hidden;
245        self
246    }
247
248    /// Hides every calendar and reminders tool.
249    #[must_use]
250    pub fn without_calendar(mut self) -> Self {
251        for name in CALENDAR_TOOLS {
252            self.router.disable_route(*name);
253        }
254        self.calendar_tools = Tools::Hidden;
255        self
256    }
257
258    /// Hides every mail tool. `account_status` stays.
259    #[must_use]
260    pub fn without_mail(mut self) -> Self {
261        for name in MAIL_TOOLS {
262            self.router.disable_route(*name);
263        }
264        self.mail_tools = Tools::Hidden;
265        self
266    }
267
268    /// Whether write tools are hidden.
269    #[must_use]
270    pub const fn is_read_only(&self) -> bool {
271        matches!(self.access, Access::ReadOnly)
272    }
273
274    /// Tools visible to the client, sorted by name.
275    #[must_use]
276    pub fn tools(&self) -> Vec<Tool> {
277        self.router.list_all()
278    }
279
280    fn build(
281        access: Access,
282        account: AccountSnapshot,
283        mail: Arc<M>,
284        calendar: Arc<C>,
285        contacts: Arc<K>,
286    ) -> Self {
287        let tools = Tools3 {
288            mail: Tools::Shown,
289            calendar: Tools::Hidden,
290            contacts: Tools::Hidden,
291            downloads: None,
292        };
293        Self::build_with(access, account, mail, calendar, contacts, tools)
294    }
295
296    fn build_with(
297        access: Access,
298        account: AccountSnapshot,
299        mail: Arc<M>,
300        calendar: Arc<C>,
301        contacts: Arc<K>,
302        tools: Tools3,
303    ) -> Self {
304        let Tools3 {
305            mail: mail_tools,
306            calendar: calendar_tools,
307            contacts: contacts_tools,
308            downloads,
309        } = tools;
310        let mut router = Self::tool_router() + Self::calendar_router() + Self::contacts_router();
311        let mut hidden: Vec<&str> = Vec::new();
312        if access == Access::ReadOnly {
313            hidden.extend(WRITE_TOOLS);
314            hidden.extend(CALENDAR_WRITE_TOOLS);
315            hidden.extend(CONTACTS_WRITE_TOOLS);
316        }
317        if mail_tools == Tools::Hidden {
318            hidden.extend(MAIL_TOOLS);
319        }
320        if downloads.is_none() {
321            hidden.push(SAVE_ATTACHMENT);
322        }
323        if calendar_tools == Tools::Hidden {
324            hidden.extend(CALENDAR_TOOLS);
325        }
326        if contacts_tools == Tools::Hidden {
327            hidden.extend(CONTACTS_TOOLS);
328        }
329        for name in hidden {
330            router.disable_route(name);
331        }
332        IbridgeServer {
333            access,
334            account,
335            mail,
336            calendar,
337            contacts,
338            mail_tools,
339            calendar_tools,
340            contacts_tools,
341            downloads,
342            gate: Arc::new(Semaphore::new(MAX_IN_FLIGHT)),
343            router,
344        }
345    }
346}
347
348#[tool_router]
349impl<M, C, K> IbridgeServer<M, C, K>
350where
351    M: MailApi + Send + Sync + 'static,
352    C: CalendarProvider + RemindersProvider + Send + Sync + 'static,
353    K: ContactsProvider + Send + Sync + 'static,
354{
355    /// Lists mailboxes with their roles and counts.
356    ///
357    /// # Errors
358    ///
359    /// Returns an MCP error when the mailbox list cannot be read.
360    #[tool(
361        title = "List mailboxes",
362        description = "Lists mailboxes with their roles and counts.",
363        annotations(read_only_hint = true, destructive_hint = false, open_world_hint = true),
364        output_schema = rmcp::handler::server::tool::schema_for_output::<MailboxListOut>(),
365    )]
366    pub async fn mail_list_mailboxes(&self) -> Result<CallToolResult, ErrorData> {
367        let _permit = self.permit().await?;
368        let mailboxes = try_mail!(self.mail.list_mailboxes().await);
369        let listed: Vec<MailboxOut> = mailboxes.iter().map(mailbox_out).collect();
370        let summary = format!("{} mailboxes", listed.len());
371        respond(&MailboxListOut { mailboxes: listed }, summary)
372    }
373
374    /// Searches messages, newest first.
375    ///
376    /// # Errors
377    ///
378    /// Returns [`ErrorData::invalid_params`] when the page size is above 100
379    /// or a filter is not usable, and an MCP error when the search cannot be run.
380    #[tool(
381        title = "Search mail",
382        description = "Searches messages, newest first. Subjects are as the sender wrote them.",
383        annotations(read_only_hint = true, destructive_hint = false, open_world_hint = true),
384        output_schema = rmcp::handler::server::tool::schema_for_output::<SearchOut>(),
385    )]
386    pub async fn mail_search(
387        &self,
388        Parameters(params): Parameters<SearchParams>,
389    ) -> Result<CallToolResult, ErrorData> {
390        let query = search_query(&params)?;
391        let _permit = self.permit().await?;
392        let page = try_mail!(self.mail.search(&query).await);
393        let summary = if page.warnings == 0 {
394            format!("{} messages", page.messages.len())
395        } else {
396            format!(
397                "{} messages, {} skipped",
398                page.messages.len(),
399                page.warnings
400            )
401        };
402        let messages = page.messages.iter().map(hit_out).collect();
403        respond(
404            &SearchOut {
405                messages,
406                next_cursor: page.next_cursor,
407                warnings: page.warnings,
408            },
409            summary,
410        )
411    }
412
413    /// Fetches one message, including its text and attachment list.
414    ///
415    /// # Errors
416    ///
417    /// Returns [`ErrorData::invalid_params`] when the id or offset is not usable,
418    /// and an MCP error when the message cannot be read.
419    #[tool(
420        title = "Get message",
421        description = "Fetches one message, including its text and attachment list. The subject and body are as the sender wrote them.",
422        annotations(read_only_hint = true, destructive_hint = false, open_world_hint = true),
423        output_schema = rmcp::handler::server::tool::schema_for_output::<MessageOut>(),
424    )]
425    pub async fn mail_get_message(
426        &self,
427        Parameters(params): Parameters<GetMessageParams>,
428    ) -> Result<CallToolResult, ErrorData> {
429        let id = require_id(&params.id)?;
430        let offset = body_offset(params.offset)?;
431        let _permit = self.permit().await?;
432        let fetched = try_mail!(self.mail.get_message(&id, offset).await);
433        let summary = format!("message from {}", fetched.message.from);
434        respond(&message_out(&fetched.message, fetched.next_offset), summary)
435    }
436
437    /// Fetches one attachment as text or as a small inline file.
438    ///
439    /// # Errors
440    ///
441    /// Returns [`ErrorData::invalid_params`] when the id or offset is not usable,
442    /// and an MCP error when the part cannot be read.
443    #[tool(
444        title = "Get attachment",
445        description = "Fetches one attachment as text or as a small inline file. The file name and text are as the sender wrote them.",
446        annotations(read_only_hint = true, destructive_hint = false, open_world_hint = true),
447        output_schema = rmcp::handler::server::tool::schema_for_output::<AttachmentOut>(),
448    )]
449    pub async fn mail_get_attachment(
450        &self,
451        Parameters(params): Parameters<GetAttachmentParams>,
452    ) -> Result<CallToolResult, ErrorData> {
453        let id = require_id(&params.id)?;
454        let offset = body_offset(params.offset)?;
455        let _permit = self.permit().await?;
456        let fetched = try_mail!(self.mail.get_attachment(&id, &params.part, offset).await);
457        let part = fetched.attachment;
458        let bytes_base64 = part
459            .bytes
460            .as_ref()
461            .map(|bytes| base64::Engine::encode(&base64::engine::general_purpose::STANDARD, bytes));
462        respond(
463            &AttachmentOut {
464                content_type: part.info.content_type,
465                name: strip_hidden(&part.info.name),
466                size: part.info.size,
467                text: part.text.as_deref().map(strip_hidden),
468                bytes_base64,
469                next_offset: widen(fetched.next_offset),
470            },
471            "attachment".to_owned(),
472        )
473    }
474
475    /// Saves one attachment into the download folder and returns its path.
476    ///
477    /// # Errors
478    ///
479    /// Returns [`ErrorData::invalid_params`] when the id is not usable, and an MCP
480    /// error when the part cannot be read or the file cannot be written.
481    #[tool(
482        title = "Save attachment to disk",
483        description = "Saves one attachment into the download folder and returns the file path. Local installs only.",
484        annotations(read_only_hint = false, destructive_hint = true, open_world_hint = true),
485        output_schema = rmcp::handler::server::tool::schema_for_output::<SavedAttachmentOut>(),
486    )]
487    pub async fn mail_save_attachment(
488        &self,
489        Parameters(params): Parameters<SaveAttachmentParams>,
490    ) -> Result<CallToolResult, ErrorData> {
491        self.reject_write()?;
492        let Some(dir) = self.downloads.clone() else {
493            return Err(ErrorData::invalid_params("tool not found", None));
494        };
495        let id = require_id(&params.id)?;
496        let _permit = self.permit().await?;
497        let file = try_mail!(self.mail.get_attachment_bytes(&id, &params.part).await);
498        let Some(bytes) = file.bytes else {
499            return mapped(&CoreError::Unsupported("saving attachments"));
500        };
501        let name = safe_name(&file.info.name, &file.info.part);
502        let size = u64::try_from(bytes.len()).unwrap_or(u64::MAX);
503        let written = tokio::task::spawn_blocking(move || save_unique(&dir, &name, &bytes))
504            .await
505            .map_err(|_| ErrorData::internal_error("internal error", None))?;
506        let path = match written {
507            Ok(path) => path,
508            Err(error) => {
509                return Ok(CallToolResult::error(vec![ContentBlock::text(format!(
510                    "the attachment could not be saved: {}",
511                    error.kind()
512                ))]));
513            }
514        };
515        respond(
516            &SavedAttachmentOut {
517                path: path.display().to_string(),
518                size,
519                content_type: file.info.content_type,
520            },
521            "attachment saved".to_owned(),
522        )
523    }
524
525    /// Saves a draft in Drafts.
526    ///
527    /// # Errors
528    ///
529    /// Returns [`ErrorData::invalid_params`] when the draft is not usable,
530    /// and an MCP error when the draft cannot be saved.
531    #[tool(
532        title = "Create draft",
533        description = "Saves a draft in Drafts.",
534        annotations(read_only_hint = false, destructive_hint = true, open_world_hint = true),
535        output_schema = rmcp::handler::server::tool::schema_for_output::<IdOut>(),
536    )]
537    pub async fn mail_create_draft(
538        &self,
539        Parameters(params): Parameters<SendParams>,
540    ) -> Result<CallToolResult, ErrorData> {
541        self.reject_write()?;
542        let draft = draft_from(&params)?;
543        let _permit = self.permit().await?;
544        let id = try_mail!(self.mail.create_draft(&draft).await);
545        let token = encode(&id);
546        respond(&IdOut { id: token }, "draft saved".to_owned())
547    }
548
549    /// Sends a message and saves a copy in Sent Messages.
550    ///
551    /// A failed Sent copy is a warning on a successful send, not a failed send.
552    ///
553    /// # Errors
554    ///
555    /// Returns [`ErrorData::invalid_params`] when the message is not usable,
556    /// and an MCP error when SMTP refuses the message.
557    #[tool(
558        title = "Send message",
559        description = "Sends a message and saves a copy in Sent Messages.",
560        annotations(read_only_hint = false, destructive_hint = true, open_world_hint = true),
561        output_schema = rmcp::handler::server::tool::schema_for_output::<SendOut>(),
562    )]
563    pub async fn mail_send(
564        &self,
565        Parameters(params): Parameters<SendParams>,
566    ) -> Result<CallToolResult, ErrorData> {
567        self.reject_write()?;
568        let draft = draft_from(&params)?;
569        let _permit = self.permit().await?;
570        let sent = try_mail!(self.mail.send(&draft).await);
571        let (id, warning, summary) = match sent.id {
572            Some(id) => (Some(encode(&id)), None, "sent".to_owned()),
573            None => (
574                None,
575                Some(SENT_COPY_WARNING.to_owned()),
576                SENT_COPY_WARNING.to_owned(),
577            ),
578        };
579        respond(&SendOut { id, warning }, summary)
580    }
581
582    /// Unsubscribes from the sender of a message, like an unsubscribe button in a mail app.
583    ///
584    /// The tool takes the message id and, optionally, which route to use. The address comes
585    /// from the message's own `List-Unsubscribe` header, which the sender wrote.
586    ///
587    /// # Errors
588    ///
589    /// Returns [`ErrorData::invalid_params`] when the id is not usable, and an MCP error
590    /// when the message cannot be read or SMTP refuses the email. A failed one-click POST is a tool error.
591    #[tool(
592        title = "Unsubscribe",
593        description = "Unsubscribes from the sender of a message, like an unsubscribe button. Takes the message id and an optional method (`one_click` or `mailto`); the address or link is never given by the caller, it is the sender's own from the message. By default, if the sender supports one-click unsubscribe (RFC 8058), the server POSTs the request to the sender's https link with no account credentials; a failure is reported and nothing else is sent, and `method: \"mailto\"` then sends the sender's unsubscribe email instead. Otherwise an unsubscribe email is sent from the account and a copy is saved in Sent Messages. If the sender offers only a web link, nothing is sent and the link is returned as the sender wrote it.",
594        annotations(
595            read_only_hint = false,
596            destructive_hint = true,
597            idempotent_hint = false,
598            open_world_hint = true
599        ),
600        output_schema = rmcp::handler::server::tool::schema_for_output::<UnsubscribedOut>(),
601    )]
602    pub async fn mail_unsubscribe(
603        &self,
604        Parameters(params): Parameters<UnsubscribeParams>,
605    ) -> Result<CallToolResult, ErrorData> {
606        self.reject_write()?;
607        let id = require_id(&params.id)?;
608        let _permit = self.permit().await?;
609        let method = params.method.map(|method| match method {
610            UnsubscribeMethodParam::OneClick => UnsubscribeMethod::OneClick,
611            UnsubscribeMethodParam::Mailto => UnsubscribeMethod::Mailto,
612        });
613        match try_mail!(self.mail.unsubscribe(&id, method).await) {
614            Unsubscribed::Emailed(sent) => {
615                let (id, warning, summary) = match sent.id {
616                    Some(id) => (Some(encode(&id)), None, "unsubscribe email sent".to_owned()),
617                    None => (
618                        None,
619                        Some(SENT_COPY_WARNING.to_owned()),
620                        SENT_COPY_WARNING.to_owned(),
621                    ),
622                };
623                respond(
624                    &UnsubscribedOut {
625                        status: UnsubscribeStatus::Emailed,
626                        id,
627                        warning,
628                        links: Vec::new(),
629                        note: "An unsubscribe email was sent to the sender. The sender decides when it takes effect.".to_owned(),
630                    },
631                    summary,
632                )
633            }
634            Unsubscribed::OneClicked => respond(
635                &UnsubscribedOut {
636                    status: UnsubscribeStatus::OneClick,
637                    id: None,
638                    warning: None,
639                    links: Vec::new(),
640                    note: ONE_CLICK_NOTE.to_owned(),
641                },
642                "one-click unsubscribe accepted".to_owned(),
643            ),
644            Unsubscribed::OneClickFailed {
645                failure,
646                mailto_offered,
647            } => {
648                let next = if mailto_offered {
649                    MAILTO_NOT_SENT
650                } else {
651                    NO_OTHER_ROUTE
652                };
653                Ok(CallToolResult::error(vec![ContentBlock::text(
654                    one_click_failed(failure, next),
655                )]))
656            }
657            Unsubscribed::Links(links) => respond(
658                &UnsubscribedOut {
659                    status: UnsubscribeStatus::LinkOnly,
660                    id: None,
661                    warning: None,
662                    links: links.iter().map(|link| strip_hidden(link)).collect(),
663                    note: LINK_ONLY_NOTE.to_owned(),
664                },
665                "only a web link is on offer".to_owned(),
666            ),
667            Unsubscribed::MethodNotOffered(method) => {
668                Ok(CallToolResult::error(vec![ContentBlock::text(
669                    method_not_offered(method),
670                )]))
671            }
672            _ => Ok(CallToolResult::error(vec![ContentBlock::text(
673                "this message does not offer unsubscribe: it has no usable List-Unsubscribe header",
674            )])),
675        }
676    }
677
678    /// Moves a message to a mailbox or a role.
679    ///
680    /// # Errors
681    ///
682    /// Returns [`ErrorData::invalid_params`] when the destination is not usable,
683    /// and an MCP error when the move cannot be done.
684    #[tool(
685        title = "Move message",
686        description = "Moves a message to a mailbox or a role.",
687        annotations(read_only_hint = false, destructive_hint = true, open_world_hint = true),
688        output_schema = rmcp::handler::server::tool::schema_for_output::<MoveOut>(),
689    )]
690    pub async fn mail_move(
691        &self,
692        Parameters(params): Parameters<MoveParams>,
693    ) -> Result<CallToolResult, ErrorData> {
694        self.reject_write()?;
695        let id = require_id(&params.id)?;
696        let destination = destination(&params)?;
697        let _permit = self.permit().await?;
698        try_mail!(self.mail.move_message(&id, &destination).await);
699        respond(&MoveOut { moved: true }, "moved".to_owned())
700    }
701
702    /// Sets or clears seen and flagged. The same call again changes nothing.
703    ///
704    /// # Errors
705    ///
706    /// Returns [`ErrorData::invalid_params`] when the id is not usable,
707    /// and an MCP error when the flags cannot be stored.
708    #[tool(
709        title = "Set message flags",
710        description = "Sets or clears seen and flagged. Repeating the same change does nothing more.",
711        annotations(
712            read_only_hint = false,
713            destructive_hint = true,
714            idempotent_hint = true,
715            open_world_hint = true
716        ),
717        output_schema = rmcp::handler::server::tool::schema_for_output::<FlagsOut>(),
718    )]
719    pub async fn mail_set_flags(
720        &self,
721        Parameters(params): Parameters<FlagParams>,
722    ) -> Result<CallToolResult, ErrorData> {
723        self.reject_write()?;
724        let id = require_id(&params.id)?;
725        let flags = FlagChange {
726            seen: params.seen,
727            flagged: params.flagged,
728        };
729        let _permit = self.permit().await?;
730        try_mail!(self.mail.set_flags(&id, &flags).await);
731        respond(&FlagsOut { updated: true }, "flags updated".to_owned())
732    }
733
734    /// Reports the signed-in address, each service, and the server version.
735    ///
736    /// # Errors
737    ///
738    /// Returns an MCP error when the status cannot be built.
739    #[tool(
740        title = "Get account status",
741        description = "Reports the signed-in address, each service, and the server version.",
742        annotations(read_only_hint = true, destructive_hint = false, open_world_hint = false),
743        output_schema = rmcp::handler::server::tool::schema_for_output::<AccountStatusOut>(),
744    )]
745    pub async fn account_status(&self) -> Result<CallToolResult, ErrorData> {
746        let _permit = self.permit().await?;
747        let status = AccountStatusOut {
748            apple_id: self.account.apple_id.as_str().to_owned(),
749            services: vec![
750                service_out("mail", &self.account.mail),
751                service_out("calendar", &self.account.calendar),
752                service_out("contacts", &self.account.contacts),
753            ],
754            version: env!("CARGO_PKG_VERSION"),
755        };
756        let summary = status_summary(&status);
757        respond(&status, summary)
758    }
759
760    pub(crate) fn reject_write(&self) -> Result<(), ErrorData> {
761        if self.access == Access::ReadOnly {
762            return Err(ErrorData::invalid_params("tool not found", None));
763        }
764        Ok(())
765    }
766
767    pub(crate) async fn permit(&self) -> Result<OwnedSemaphorePermit, ErrorData> {
768        Arc::clone(&self.gate)
769            .acquire_owned()
770            .await
771            .map_err(|_| ErrorData::internal_error("internal error", None))
772    }
773}
774
775pub(crate) fn respond<T: serde::Serialize>(
776    value: &T,
777    summary: String,
778) -> Result<CallToolResult, ErrorData> {
779    let json = serde_json::to_value(value)
780        .map_err(|_| ErrorData::internal_error("internal error", None))?;
781    let mut result = CallToolResult::structured(json);
782    // Claude reads the text content, not `structuredContent`. `structured` already put the
783    // serialized JSON in `content`, which the MCP spec asks for; the summary goes in front.
784    result.content.insert(0, ContentBlock::text(summary));
785    Ok(result)
786}
787
788pub(crate) fn mapped(error: &CoreError) -> Result<CallToolResult, ErrorData> {
789    match map_core_error(error) {
790        MappedError::Rpc(data) => Err(data),
791        MappedError::Tool(message) => Ok(CallToolResult::error(vec![ContentBlock::text(
792            message.into_owned(),
793        )])),
794    }
795}
796
797pub(crate) fn page_limit(limit: u32) -> Result<u32, ErrorData> {
798    if limit == 0 {
799        return Ok(DEFAULT_LIMIT);
800    }
801    if limit > MAX_LIMIT {
802        return Err(ErrorData::invalid_params("limit must be at most 100", None));
803    }
804    Ok(limit)
805}
806
807fn body_offset(offset: u64) -> Result<usize, ErrorData> {
808    usize::try_from(offset).map_err(|_| ErrorData::invalid_params("offset is too large", None))
809}
810
811fn require_id(token: &str) -> Result<MessageId, ErrorData> {
812    decode(token).map_err(|_| ErrorData::invalid_params("invalid message id", None))
813}
814
815fn require_path(path: &str) -> Result<MailboxPath, ErrorData> {
816    MailboxPath::try_from(path).map_err(|_| ErrorData::invalid_params("invalid mailbox path", None))
817}
818
819fn parse_role(name: &str) -> Result<MailboxRole, ErrorData> {
820    match name {
821        "inbox" => Ok(MailboxRole::Inbox),
822        "sent" => Ok(MailboxRole::Sent),
823        "drafts" => Ok(MailboxRole::Drafts),
824        "trash" => Ok(MailboxRole::Trash),
825        "junk" => Ok(MailboxRole::Junk),
826        "archive" => Ok(MailboxRole::Archive),
827        "notes" => Ok(MailboxRole::Notes),
828        _ => Err(ErrorData::invalid_params("unknown mailbox role", None)),
829    }
830}
831
832fn role_name(role: MailboxRole) -> &'static str {
833    match role {
834        MailboxRole::Inbox => "inbox",
835        MailboxRole::Sent => "sent",
836        MailboxRole::Drafts => "drafts",
837        MailboxRole::Trash => "trash",
838        MailboxRole::Junk => "junk",
839        MailboxRole::Archive => "archive",
840        MailboxRole::Notes => "notes",
841        MailboxRole::Other | _ => "other",
842    }
843}
844
845fn search_query(params: &SearchParams) -> Result<MailSearch, ErrorData> {
846    let mailbox = params.mailbox.as_deref().map(require_path).transpose()?;
847    let role = params.role.as_deref().map(parse_role).transpose()?;
848    Ok(MailSearch {
849        mailbox,
850        role,
851        from: params.from.clone(),
852        to: params.to.clone(),
853        subject: params.subject.clone(),
854        text: params.text.clone(),
855        since: params.since.clone(),
856        before: params.before.clone(),
857        unread_only: params.unread.unwrap_or(false),
858        flagged_only: params.flagged.unwrap_or(false),
859        limit: page_limit(params.limit)?,
860        cursor: params.cursor.clone(),
861    })
862}
863
864fn draft_from(params: &SendParams) -> Result<Draft, ErrorData> {
865    let reply_to = params.reply_to_id.as_deref().map(require_id).transpose()?;
866    Ok(Draft {
867        to: params.to.clone(),
868        subject: params.subject.clone(),
869        body: params.body.clone(),
870        from: params.from.clone(),
871        reply_to,
872    })
873}
874
875fn destination(params: &MoveParams) -> Result<MailDest, ErrorData> {
876    match (&params.mailbox, &params.role) {
877        (Some(path), None) => Ok(MailDest::Path(require_path(path)?)),
878        (None, Some(role)) => Ok(MailDest::Role(parse_role(role)?)),
879        _ => Err(ErrorData::invalid_params(
880            "move needs a mailbox or a role",
881            None,
882        )),
883    }
884}
885
886fn mailbox_out(mailbox: &Mailbox) -> MailboxOut {
887    MailboxOut {
888        path: mailbox.path.as_str().to_owned(),
889        role: role_name(mailbox.role).to_owned(),
890        total: mailbox.total,
891        unread: mailbox.unread,
892    }
893}
894
895fn hit_out(hit: &MessageSummary) -> SearchHitOut {
896    SearchHitOut {
897        id: encode(&hit.id),
898        from: strip_hidden(&hit.from),
899        subject: strip_hidden(&hit.subject),
900        date: hit.date.clone(),
901        unread: hit.unread,
902        flagged: hit.flagged,
903    }
904}
905
906fn message_out(message: &Message, next_offset: Option<usize>) -> MessageOut {
907    MessageOut {
908        id: encode(&message.id),
909        from: strip_hidden(&message.from),
910        to: message.to.iter().map(|to| strip_hidden(to)).collect(),
911        subject: strip_hidden(&message.subject),
912        date: message.date.clone(),
913        body: strip_hidden(&message.body),
914        attachments: message
915            .attachments
916            .iter()
917            .map(|info| AttachmentInfoOut {
918                part: info.part.clone(),
919                content_type: info.content_type.clone(),
920                size: info.size,
921                name: strip_hidden(&info.name),
922            })
923            .collect(),
924        unsubscribe: unsubscribe_out(message.unsubscribe.as_ref()),
925        next_offset: widen(next_offset),
926    }
927}
928
929/// The error for a `method` the message does not offer. Nothing was sent.
930fn method_not_offered(method: UnsubscribeMethod) -> String {
931    let name = match method {
932        UnsubscribeMethod::OneClick => "one-click unsubscribe",
933        UnsubscribeMethod::Mailto => "an unsubscribe email",
934        _ => "that unsubscribe method",
935    };
936    format!(
937        "this message does not offer {name}, so nothing was sent. Omit `method` to use what the message does offer."
938    )
939}
940
941/// What a failed one-click POST says: the failure class, that nothing else was sent, and
942/// what `next` says about other routes. Nothing in it comes from the server.
943fn one_click_failed(failure: OneClickFailure, next: &str) -> String {
944    format!("one-click unsubscribe failed: {failure}. Nothing was sent. {next}")
945}
946
947fn unsubscribe_out(options: Option<&Unsubscribe>) -> UnsubscribeOut {
948    let methods: Vec<UnsubscribeMethodOut> = options
949        .map_or_default(Unsubscribe::methods)
950        .into_iter()
951        .filter_map(|method| match method {
952            UnsubscribeMethod::OneClick => Some(UnsubscribeMethodOut::OneClick),
953            UnsubscribeMethod::Mailto => Some(UnsubscribeMethodOut::Mailto),
954            UnsubscribeMethod::Link => Some(UnsubscribeMethodOut::Link),
955            _ => None,
956        })
957        .collect();
958    UnsubscribeOut {
959        available: !methods.is_empty(),
960        methods,
961    }
962}
963
964fn widen(offset: Option<usize>) -> Option<u64> {
965    offset.map(|offset| u64::try_from(offset).unwrap_or(u64::MAX))
966}
967
968fn service_out(name: &str, status: &ServiceStatus) -> ServiceOut {
969    match status {
970        ServiceStatus::On => ServiceOut {
971            name: name.to_owned(),
972            status: ServiceState::On,
973            reason: None,
974        },
975        ServiceStatus::Off { reason } => ServiceOut {
976            name: name.to_owned(),
977            status: ServiceState::Off,
978            reason: Some(reason.clone()),
979        },
980    }
981}
982
983fn status_summary(status: &AccountStatusOut) -> String {
984    let mut parts = Vec::with_capacity(status.services.len() + 2);
985    parts.push(format!("signed in as {}", status.apple_id));
986    for service in &status.services {
987        if let Some(reason) = &service.reason {
988            parts.push(format!("{} off: {reason}", service.name));
989        } else {
990            parts.push(format!("{} on", service.name));
991        }
992    }
993    parts.push(format!("version {}", status.version));
994    parts.join("; ")
995}
996
997#[expect(
998    clippy::unused_async_trait_impl,
999    reason = "the generated tool listing returns without waiting"
1000)]
1001#[tool_handler(router = self.router, name = "ibridge")]
1002impl<M, C, K> ServerHandler for IbridgeServer<M, C, K>
1003where
1004    M: MailApi + Send + Sync + 'static,
1005    C: CalendarProvider + RemindersProvider + Send + Sync + 'static,
1006    K: ContactsProvider + Send + Sync + 'static,
1007{
1008}