1use 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, RemindersProvider, decode,
12 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,
28};
29use crate::error_map::{MappedError, map_core_error};
30use crate::mail_api::{MailApi, MailDest};
31use crate::sanitize::strip_hidden;
32use crate::save::{safe_name, save_unique};
33
34const MAX_IN_FLIGHT: usize = 4;
35const DEFAULT_LIMIT: u32 = 25;
36const MAX_LIMIT: u32 = 100;
37const SENT_COPY_WARNING: &str = "sent, but the copy was not saved to Sent Messages";
38const SAVE_ATTACHMENT: &str = "mail_save_attachment";
39const MAIL_TOOLS: &[&str] = &[
40 "mail_create_draft",
41 "mail_get_attachment",
42 "mail_get_message",
43 "mail_list_mailboxes",
44 "mail_move",
45 "mail_save_attachment",
46 "mail_search",
47 "mail_send",
48 "mail_set_flags",
49];
50const WRITE_TOOLS: &[&str] = &[
51 "mail_create_draft",
52 "mail_move",
53 "mail_save_attachment",
54 "mail_send",
55 "mail_set_flags",
56];
57
58macro_rules! try_mail {
59 ($call:expr) => {
60 match $call {
61 Ok(value) => value,
62 Err(error) => return mapped(&error),
63 }
64 };
65}
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69enum Tools {
70 Shown,
72 Hidden,
74}
75
76#[derive(Debug, Clone)]
78struct Tools3 {
79 mail: Tools,
80 calendar: Tools,
81 contacts: Tools,
82 downloads: Option<Arc<Path>>,
83}
84
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87enum Access {
88 ReadOnly,
90 ReadWrite,
92}
93
94pub struct IbridgeServer<M, C = NoCalendar, K = NoContacts> {
101 access: Access,
102 account: AccountSnapshot,
103 mail: Arc<M>,
104 pub(crate) calendar: Arc<C>,
105 pub(crate) contacts: Arc<K>,
106 mail_tools: Tools,
107 calendar_tools: Tools,
108 contacts_tools: Tools,
109 downloads: Option<Arc<Path>>,
110 gate: Arc<Semaphore>,
111 router: ToolRouter<Self>,
112}
113
114impl<M, C, K> fmt::Debug for IbridgeServer<M, C, K> {
115 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116 f.debug_struct("IbridgeServer")
117 .field("access", &self.access)
118 .field("account", &self.account)
119 .finish_non_exhaustive()
120 }
121}
122
123impl<M, C, K> Clone for IbridgeServer<M, C, K> {
124 fn clone(&self) -> Self {
125 Self {
126 access: self.access,
127 account: self.account.clone(),
128 mail: Arc::clone(&self.mail),
129 calendar: Arc::clone(&self.calendar),
130 contacts: Arc::clone(&self.contacts),
131 mail_tools: self.mail_tools,
132 calendar_tools: self.calendar_tools,
133 contacts_tools: self.contacts_tools,
134 downloads: self.downloads.clone(),
135 gate: Arc::clone(&self.gate),
136 router: self.router.clone(),
137 }
138 }
139}
140
141impl<M> IbridgeServer<M, NoCalendar, NoContacts>
142where
143 M: MailApi + Send + Sync + 'static,
144{
145 #[must_use]
147 pub fn read_only(account: AccountSnapshot, mail: Arc<M>) -> Self {
148 Self::build(
149 Access::ReadOnly,
150 account,
151 mail,
152 Arc::new(NoCalendar),
153 Arc::new(NoContacts),
154 )
155 }
156
157 #[must_use]
159 pub fn read_write(account: AccountSnapshot, mail: Arc<M>) -> Self {
160 Self::build(
161 Access::ReadWrite,
162 account,
163 mail,
164 Arc::new(NoCalendar),
165 Arc::new(NoContacts),
166 )
167 }
168}
169
170impl<M, C, K> IbridgeServer<M, C, K>
171where
172 M: MailApi + Send + Sync + 'static,
173 C: CalendarProvider + RemindersProvider + Send + Sync + 'static,
174 K: ContactsProvider + Send + Sync + 'static,
175{
176 #[must_use]
178 pub fn with_calendar<C2>(self, calendar: Arc<C2>) -> IbridgeServer<M, C2, K>
179 where
180 C2: CalendarProvider + RemindersProvider + Send + Sync + 'static,
181 {
182 IbridgeServer::<M, C2, K>::build_with(
183 self.access,
184 self.account,
185 self.mail,
186 calendar,
187 self.contacts,
188 Tools3 {
189 mail: self.mail_tools,
190 calendar: Tools::Shown,
191 contacts: self.contacts_tools,
192 downloads: self.downloads,
193 },
194 )
195 }
196
197 #[must_use]
199 pub fn with_contacts<K2>(self, contacts: Arc<K2>) -> IbridgeServer<M, C, K2>
200 where
201 K2: ContactsProvider + Send + Sync + 'static,
202 {
203 IbridgeServer::<M, C, K2>::build_with(
204 self.access,
205 self.account,
206 self.mail,
207 self.calendar,
208 contacts,
209 Tools3 {
210 mail: self.mail_tools,
211 calendar: self.calendar_tools,
212 contacts: Tools::Shown,
213 downloads: self.downloads,
214 },
215 )
216 }
217
218 #[must_use]
222 pub fn with_downloads(mut self, dir: PathBuf) -> Self {
223 self.downloads = Some(Arc::from(dir));
224 if self.access == Access::ReadWrite && self.mail_tools == Tools::Shown {
225 self.router.enable_route(SAVE_ATTACHMENT);
226 }
227 self
228 }
229
230 #[must_use]
232 pub fn without_contacts(mut self) -> Self {
233 for name in CONTACTS_TOOLS {
234 self.router.disable_route(*name);
235 }
236 self.contacts_tools = Tools::Hidden;
237 self
238 }
239
240 #[must_use]
242 pub fn without_calendar(mut self) -> Self {
243 for name in CALENDAR_TOOLS {
244 self.router.disable_route(*name);
245 }
246 self.calendar_tools = Tools::Hidden;
247 self
248 }
249
250 #[must_use]
252 pub fn without_mail(mut self) -> Self {
253 for name in MAIL_TOOLS {
254 self.router.disable_route(*name);
255 }
256 self.mail_tools = Tools::Hidden;
257 self
258 }
259
260 #[must_use]
262 pub const fn is_read_only(&self) -> bool {
263 matches!(self.access, Access::ReadOnly)
264 }
265
266 #[must_use]
268 pub fn tools(&self) -> Vec<Tool> {
269 self.router.list_all()
270 }
271
272 fn build(
273 access: Access,
274 account: AccountSnapshot,
275 mail: Arc<M>,
276 calendar: Arc<C>,
277 contacts: Arc<K>,
278 ) -> Self {
279 let tools = Tools3 {
280 mail: Tools::Shown,
281 calendar: Tools::Hidden,
282 contacts: Tools::Hidden,
283 downloads: None,
284 };
285 Self::build_with(access, account, mail, calendar, contacts, tools)
286 }
287
288 fn build_with(
289 access: Access,
290 account: AccountSnapshot,
291 mail: Arc<M>,
292 calendar: Arc<C>,
293 contacts: Arc<K>,
294 tools: Tools3,
295 ) -> Self {
296 let Tools3 {
297 mail: mail_tools,
298 calendar: calendar_tools,
299 contacts: contacts_tools,
300 downloads,
301 } = tools;
302 let mut router = Self::tool_router() + Self::calendar_router() + Self::contacts_router();
303 let mut hidden: Vec<&str> = Vec::new();
304 if access == Access::ReadOnly {
305 hidden.extend(WRITE_TOOLS);
306 hidden.extend(CALENDAR_WRITE_TOOLS);
307 hidden.extend(CONTACTS_WRITE_TOOLS);
308 }
309 if mail_tools == Tools::Hidden {
310 hidden.extend(MAIL_TOOLS);
311 }
312 if downloads.is_none() {
313 hidden.push(SAVE_ATTACHMENT);
314 }
315 if calendar_tools == Tools::Hidden {
316 hidden.extend(CALENDAR_TOOLS);
317 }
318 if contacts_tools == Tools::Hidden {
319 hidden.extend(CONTACTS_TOOLS);
320 }
321 for name in hidden {
322 router.disable_route(name);
323 }
324 IbridgeServer {
325 access,
326 account,
327 mail,
328 calendar,
329 contacts,
330 mail_tools,
331 calendar_tools,
332 contacts_tools,
333 downloads,
334 gate: Arc::new(Semaphore::new(MAX_IN_FLIGHT)),
335 router,
336 }
337 }
338}
339
340#[tool_router]
341impl<M, C, K> IbridgeServer<M, C, K>
342where
343 M: MailApi + Send + Sync + 'static,
344 C: CalendarProvider + RemindersProvider + Send + Sync + 'static,
345 K: ContactsProvider + Send + Sync + 'static,
346{
347 #[tool(
353 title = "List mailboxes",
354 description = "Lists mailboxes with their roles and counts.",
355 annotations(read_only_hint = true, destructive_hint = false, open_world_hint = true),
356 output_schema = rmcp::handler::server::tool::schema_for_output::<MailboxListOut>(),
357 )]
358 pub async fn mail_list_mailboxes(&self) -> Result<CallToolResult, ErrorData> {
359 let _permit = self.permit().await?;
360 let mailboxes = try_mail!(self.mail.list_mailboxes().await);
361 let listed: Vec<MailboxOut> = mailboxes.iter().map(mailbox_out).collect();
362 let summary = format!("{} mailboxes", listed.len());
363 respond(&MailboxListOut { mailboxes: listed }, summary)
364 }
365
366 #[tool(
373 title = "Search mail",
374 description = "Searches messages, newest first. Subjects are as the sender wrote them.",
375 annotations(read_only_hint = true, destructive_hint = false, open_world_hint = true),
376 output_schema = rmcp::handler::server::tool::schema_for_output::<SearchOut>(),
377 )]
378 pub async fn mail_search(
379 &self,
380 Parameters(params): Parameters<SearchParams>,
381 ) -> Result<CallToolResult, ErrorData> {
382 let query = search_query(¶ms)?;
383 let _permit = self.permit().await?;
384 let page = try_mail!(self.mail.search(&query).await);
385 let summary = if page.warnings == 0 {
386 format!("{} messages", page.messages.len())
387 } else {
388 format!(
389 "{} messages, {} skipped",
390 page.messages.len(),
391 page.warnings
392 )
393 };
394 let messages = page.messages.iter().map(hit_out).collect();
395 respond(
396 &SearchOut {
397 messages,
398 next_cursor: page.next_cursor,
399 warnings: page.warnings,
400 },
401 summary,
402 )
403 }
404
405 #[tool(
412 title = "Get message",
413 description = "Fetches one message, including its text and attachment list. The subject and body are as the sender wrote them.",
414 annotations(read_only_hint = true, destructive_hint = false, open_world_hint = true),
415 output_schema = rmcp::handler::server::tool::schema_for_output::<MessageOut>(),
416 )]
417 pub async fn mail_get_message(
418 &self,
419 Parameters(params): Parameters<GetMessageParams>,
420 ) -> Result<CallToolResult, ErrorData> {
421 let id = require_id(¶ms.id)?;
422 let offset = body_offset(params.offset)?;
423 let _permit = self.permit().await?;
424 let fetched = try_mail!(self.mail.get_message(&id, offset).await);
425 let summary = format!("message from {}", fetched.message.from);
426 respond(&message_out(&fetched.message, fetched.next_offset), summary)
427 }
428
429 #[tool(
436 title = "Get attachment",
437 description = "Fetches one attachment as text or as a small inline file. The file name and text are as the sender wrote them.",
438 annotations(read_only_hint = true, destructive_hint = false, open_world_hint = true),
439 output_schema = rmcp::handler::server::tool::schema_for_output::<AttachmentOut>(),
440 )]
441 pub async fn mail_get_attachment(
442 &self,
443 Parameters(params): Parameters<GetAttachmentParams>,
444 ) -> Result<CallToolResult, ErrorData> {
445 let id = require_id(¶ms.id)?;
446 let offset = body_offset(params.offset)?;
447 let _permit = self.permit().await?;
448 let fetched = try_mail!(self.mail.get_attachment(&id, ¶ms.part, offset).await);
449 let part = fetched.attachment;
450 let bytes_base64 = part
451 .bytes
452 .as_ref()
453 .map(|bytes| base64::Engine::encode(&base64::engine::general_purpose::STANDARD, bytes));
454 respond(
455 &AttachmentOut {
456 content_type: part.info.content_type,
457 name: strip_hidden(&part.info.name),
458 size: part.info.size,
459 text: part.text.as_deref().map(strip_hidden),
460 bytes_base64,
461 next_offset: widen(fetched.next_offset),
462 },
463 "attachment".to_owned(),
464 )
465 }
466
467 #[tool(
474 title = "Save attachment to disk",
475 description = "Saves one attachment into the download folder and returns the file path. Local installs only.",
476 annotations(read_only_hint = false, destructive_hint = true, open_world_hint = true),
477 output_schema = rmcp::handler::server::tool::schema_for_output::<SavedAttachmentOut>(),
478 )]
479 pub async fn mail_save_attachment(
480 &self,
481 Parameters(params): Parameters<SaveAttachmentParams>,
482 ) -> Result<CallToolResult, ErrorData> {
483 self.reject_write()?;
484 let Some(dir) = self.downloads.clone() else {
485 return Err(ErrorData::invalid_params("tool not found", None));
486 };
487 let id = require_id(¶ms.id)?;
488 let _permit = self.permit().await?;
489 let file = try_mail!(self.mail.get_attachment_bytes(&id, ¶ms.part).await);
490 let Some(bytes) = file.bytes else {
491 return mapped(&CoreError::Unsupported("saving attachments"));
492 };
493 let name = safe_name(&file.info.name, &file.info.part);
494 let size = u64::try_from(bytes.len()).unwrap_or(u64::MAX);
495 let written = tokio::task::spawn_blocking(move || save_unique(&dir, &name, &bytes))
496 .await
497 .map_err(|_| ErrorData::internal_error("internal error", None))?;
498 let path = match written {
499 Ok(path) => path,
500 Err(error) => {
501 return Ok(CallToolResult::error(vec![ContentBlock::text(format!(
502 "the attachment could not be saved: {}",
503 error.kind()
504 ))]));
505 }
506 };
507 respond(
508 &SavedAttachmentOut {
509 path: path.display().to_string(),
510 size,
511 content_type: file.info.content_type,
512 },
513 "attachment saved".to_owned(),
514 )
515 }
516
517 #[tool(
524 title = "Create draft",
525 description = "Saves a draft in Drafts.",
526 annotations(read_only_hint = false, destructive_hint = true, open_world_hint = true),
527 output_schema = rmcp::handler::server::tool::schema_for_output::<IdOut>(),
528 )]
529 pub async fn mail_create_draft(
530 &self,
531 Parameters(params): Parameters<SendParams>,
532 ) -> Result<CallToolResult, ErrorData> {
533 self.reject_write()?;
534 let draft = draft_from(¶ms)?;
535 let _permit = self.permit().await?;
536 let id = try_mail!(self.mail.create_draft(&draft).await);
537 let token = encode(&id);
538 respond(&IdOut { id: token }, "draft saved".to_owned())
539 }
540
541 #[tool(
550 title = "Send message",
551 description = "Sends a message and saves a copy in Sent Messages.",
552 annotations(read_only_hint = false, destructive_hint = true, open_world_hint = true),
553 output_schema = rmcp::handler::server::tool::schema_for_output::<SendOut>(),
554 )]
555 pub async fn mail_send(
556 &self,
557 Parameters(params): Parameters<SendParams>,
558 ) -> Result<CallToolResult, ErrorData> {
559 self.reject_write()?;
560 let draft = draft_from(¶ms)?;
561 let _permit = self.permit().await?;
562 let sent = try_mail!(self.mail.send(&draft).await);
563 let (id, warning, summary) = match sent.id {
564 Some(id) => (Some(encode(&id)), None, "sent".to_owned()),
565 None => (
566 None,
567 Some(SENT_COPY_WARNING.to_owned()),
568 SENT_COPY_WARNING.to_owned(),
569 ),
570 };
571 respond(&SendOut { id, warning }, summary)
572 }
573
574 #[tool(
581 title = "Move message",
582 description = "Moves a message to a mailbox or a role.",
583 annotations(read_only_hint = false, destructive_hint = true, open_world_hint = true),
584 output_schema = rmcp::handler::server::tool::schema_for_output::<MoveOut>(),
585 )]
586 pub async fn mail_move(
587 &self,
588 Parameters(params): Parameters<MoveParams>,
589 ) -> Result<CallToolResult, ErrorData> {
590 self.reject_write()?;
591 let id = require_id(¶ms.id)?;
592 let destination = destination(¶ms)?;
593 let _permit = self.permit().await?;
594 try_mail!(self.mail.move_message(&id, &destination).await);
595 respond(&MoveOut { moved: true }, "moved".to_owned())
596 }
597
598 #[tool(
605 title = "Set message flags",
606 description = "Sets or clears seen and flagged. Repeating the same change does nothing more.",
607 annotations(
608 read_only_hint = false,
609 destructive_hint = true,
610 idempotent_hint = true,
611 open_world_hint = true
612 ),
613 output_schema = rmcp::handler::server::tool::schema_for_output::<FlagsOut>(),
614 )]
615 pub async fn mail_set_flags(
616 &self,
617 Parameters(params): Parameters<FlagParams>,
618 ) -> Result<CallToolResult, ErrorData> {
619 self.reject_write()?;
620 let id = require_id(¶ms.id)?;
621 let flags = FlagChange {
622 seen: params.seen,
623 flagged: params.flagged,
624 };
625 let _permit = self.permit().await?;
626 try_mail!(self.mail.set_flags(&id, &flags).await);
627 respond(&FlagsOut { updated: true }, "flags updated".to_owned())
628 }
629
630 #[tool(
636 title = "Get account status",
637 description = "Reports the signed-in address, each service, and the server version.",
638 annotations(read_only_hint = true, destructive_hint = false, open_world_hint = false),
639 output_schema = rmcp::handler::server::tool::schema_for_output::<AccountStatusOut>(),
640 )]
641 pub async fn account_status(&self) -> Result<CallToolResult, ErrorData> {
642 let _permit = self.permit().await?;
643 let status = AccountStatusOut {
644 apple_id: self.account.apple_id.as_str().to_owned(),
645 services: vec![
646 service_out("mail", &self.account.mail),
647 service_out("calendar", &self.account.calendar),
648 service_out("contacts", &self.account.contacts),
649 ],
650 version: env!("CARGO_PKG_VERSION"),
651 };
652 let summary = status_summary(&status);
653 respond(&status, summary)
654 }
655
656 pub(crate) fn reject_write(&self) -> Result<(), ErrorData> {
657 if self.access == Access::ReadOnly {
658 return Err(ErrorData::invalid_params("tool not found", None));
659 }
660 Ok(())
661 }
662
663 pub(crate) async fn permit(&self) -> Result<OwnedSemaphorePermit, ErrorData> {
664 Arc::clone(&self.gate)
665 .acquire_owned()
666 .await
667 .map_err(|_| ErrorData::internal_error("internal error", None))
668 }
669}
670
671pub(crate) fn respond<T: serde::Serialize>(
672 value: &T,
673 summary: String,
674) -> Result<CallToolResult, ErrorData> {
675 let json = serde_json::to_value(value)
676 .map_err(|_| ErrorData::internal_error("internal error", None))?;
677 let mut result = CallToolResult::structured(json);
678 result.content.insert(0, ContentBlock::text(summary));
681 Ok(result)
682}
683
684pub(crate) fn mapped(error: &CoreError) -> Result<CallToolResult, ErrorData> {
685 match map_core_error(error) {
686 MappedError::Rpc(data) => Err(data),
687 MappedError::Tool(message) => Ok(CallToolResult::error(vec![ContentBlock::text(
688 message.into_owned(),
689 )])),
690 }
691}
692
693pub(crate) fn page_limit(limit: u32) -> Result<u32, ErrorData> {
694 if limit == 0 {
695 return Ok(DEFAULT_LIMIT);
696 }
697 if limit > MAX_LIMIT {
698 return Err(ErrorData::invalid_params("limit must be at most 100", None));
699 }
700 Ok(limit)
701}
702
703fn body_offset(offset: u64) -> Result<usize, ErrorData> {
704 usize::try_from(offset).map_err(|_| ErrorData::invalid_params("offset is too large", None))
705}
706
707fn require_id(token: &str) -> Result<MessageId, ErrorData> {
708 decode(token).map_err(|_| ErrorData::invalid_params("invalid message id", None))
709}
710
711fn require_path(path: &str) -> Result<MailboxPath, ErrorData> {
712 MailboxPath::try_from(path).map_err(|_| ErrorData::invalid_params("invalid mailbox path", None))
713}
714
715fn parse_role(name: &str) -> Result<MailboxRole, ErrorData> {
716 match name {
717 "inbox" => Ok(MailboxRole::Inbox),
718 "sent" => Ok(MailboxRole::Sent),
719 "drafts" => Ok(MailboxRole::Drafts),
720 "trash" => Ok(MailboxRole::Trash),
721 "junk" => Ok(MailboxRole::Junk),
722 "archive" => Ok(MailboxRole::Archive),
723 "notes" => Ok(MailboxRole::Notes),
724 _ => Err(ErrorData::invalid_params("unknown mailbox role", None)),
725 }
726}
727
728fn role_name(role: MailboxRole) -> &'static str {
729 match role {
730 MailboxRole::Inbox => "inbox",
731 MailboxRole::Sent => "sent",
732 MailboxRole::Drafts => "drafts",
733 MailboxRole::Trash => "trash",
734 MailboxRole::Junk => "junk",
735 MailboxRole::Archive => "archive",
736 MailboxRole::Notes => "notes",
737 MailboxRole::Other | _ => "other",
738 }
739}
740
741fn search_query(params: &SearchParams) -> Result<MailSearch, ErrorData> {
742 let mailbox = params.mailbox.as_deref().map(require_path).transpose()?;
743 let role = params.role.as_deref().map(parse_role).transpose()?;
744 Ok(MailSearch {
745 mailbox,
746 role,
747 from: params.from.clone(),
748 to: params.to.clone(),
749 subject: params.subject.clone(),
750 text: params.text.clone(),
751 since: params.since.clone(),
752 before: params.before.clone(),
753 unread_only: params.unread.unwrap_or(false),
754 flagged_only: params.flagged.unwrap_or(false),
755 limit: page_limit(params.limit)?,
756 cursor: params.cursor.clone(),
757 })
758}
759
760fn draft_from(params: &SendParams) -> Result<Draft, ErrorData> {
761 let reply_to = params.reply_to_id.as_deref().map(require_id).transpose()?;
762 Ok(Draft {
763 to: params.to.clone(),
764 subject: params.subject.clone(),
765 body: params.body.clone(),
766 from: params.from.clone(),
767 reply_to,
768 })
769}
770
771fn destination(params: &MoveParams) -> Result<MailDest, ErrorData> {
772 match (¶ms.mailbox, ¶ms.role) {
773 (Some(path), None) => Ok(MailDest::Path(require_path(path)?)),
774 (None, Some(role)) => Ok(MailDest::Role(parse_role(role)?)),
775 _ => Err(ErrorData::invalid_params(
776 "move needs a mailbox or a role",
777 None,
778 )),
779 }
780}
781
782fn mailbox_out(mailbox: &Mailbox) -> MailboxOut {
783 MailboxOut {
784 path: mailbox.path.as_str().to_owned(),
785 role: role_name(mailbox.role).to_owned(),
786 total: mailbox.total,
787 unread: mailbox.unread,
788 }
789}
790
791fn hit_out(hit: &MessageSummary) -> SearchHitOut {
792 SearchHitOut {
793 id: encode(&hit.id),
794 from: strip_hidden(&hit.from),
795 subject: strip_hidden(&hit.subject),
796 date: hit.date.clone(),
797 unread: hit.unread,
798 flagged: hit.flagged,
799 }
800}
801
802fn message_out(message: &Message, next_offset: Option<usize>) -> MessageOut {
803 MessageOut {
804 id: encode(&message.id),
805 from: strip_hidden(&message.from),
806 to: message.to.iter().map(|to| strip_hidden(to)).collect(),
807 subject: strip_hidden(&message.subject),
808 date: message.date.clone(),
809 body: strip_hidden(&message.body),
810 attachments: message
811 .attachments
812 .iter()
813 .map(|info| AttachmentInfoOut {
814 part: info.part.clone(),
815 content_type: info.content_type.clone(),
816 size: info.size,
817 name: strip_hidden(&info.name),
818 })
819 .collect(),
820 next_offset: widen(next_offset),
821 }
822}
823
824fn widen(offset: Option<usize>) -> Option<u64> {
825 offset.map(|offset| u64::try_from(offset).unwrap_or(u64::MAX))
826}
827
828fn service_out(name: &str, status: &ServiceStatus) -> ServiceOut {
829 match status {
830 ServiceStatus::On => ServiceOut {
831 name: name.to_owned(),
832 status: ServiceState::On,
833 reason: None,
834 },
835 ServiceStatus::Off { reason } => ServiceOut {
836 name: name.to_owned(),
837 status: ServiceState::Off,
838 reason: Some(reason.clone()),
839 },
840 }
841}
842
843fn status_summary(status: &AccountStatusOut) -> String {
844 let mut parts = Vec::with_capacity(status.services.len() + 2);
845 parts.push(format!("signed in as {}", status.apple_id));
846 for service in &status.services {
847 if let Some(reason) = &service.reason {
848 parts.push(format!("{} off: {reason}", service.name));
849 } else {
850 parts.push(format!("{} on", service.name));
851 }
852 }
853 parts.push(format!("version {}", status.version));
854 parts.join("; ")
855}
856
857#[expect(
858 clippy::unused_async_trait_impl,
859 reason = "the generated tool listing returns without waiting"
860)]
861#[tool_handler(router = self.router, name = "ibridge")]
862impl<M, C, K> ServerHandler for IbridgeServer<M, C, K>
863where
864 M: MailApi + Send + Sync + 'static,
865 C: CalendarProvider + RemindersProvider + Send + Sync + 'static,
866 K: ContactsProvider + Send + Sync + 'static,
867{
868}