1use ibridge_core::{
6 CalendarProvider, Contact, ContactDraft, ContactList, ContactQuery, ContactUpdate,
7 ContactsProvider, CoreError, ETag, GroupChange, LabeledValue, RemindersProvider, ResourcePath,
8 encode_resource,
9};
10use rmcp::handler::server::wrapper::Parameters;
11use rmcp::model::{CallToolResult, ErrorData};
12use rmcp::tool;
13use rmcp::tool_router;
14
15use crate::calendar_dto::{DeleteOut, DeleteParams, GetByIdParams, WriteOut};
16use crate::calendar_tools::{capped, require_etag, require_path};
17use crate::contacts_dto::{
18 ContactListOut, ContactOut, CreateContactParams, GroupOut, LabeledOut, MembershipOut,
19 SearchContactsParams, SetGroupMembershipParams, UpdateContactParams,
20};
21use crate::handler::{IbridgeServer, mapped, page_limit, respond};
22use crate::mail_api::MailApi;
23use crate::sanitize::strip_hidden;
24
25pub(crate) const CONTACTS_TOOLS: &[&str] = &[
26 "contacts_create",
27 "contacts_delete",
28 "contacts_get",
29 "contacts_search",
30 "contacts_set_group_membership",
31 "contacts_update",
32];
33
34pub(crate) const CONTACTS_WRITE_TOOLS: &[&str] = &[
35 "contacts_create",
36 "contacts_delete",
37 "contacts_set_group_membership",
38 "contacts_update",
39];
40
41#[derive(Debug, Clone, Copy, Default)]
43pub struct NoContacts;
44
45fn off<T>() -> Result<T, CoreError> {
46 Err(CoreError::Unsupported("contacts is not enabled"))
47}
48
49#[expect(
50 clippy::unused_async_trait_impl,
51 reason = "the stand-in answers without waiting"
52)]
53impl ContactsProvider for NoContacts {
54 async fn search(&self, _query: &ContactQuery) -> Result<ContactList, CoreError> {
55 off()
56 }
57 async fn get(&self, _path: &ResourcePath) -> Result<Contact, CoreError> {
58 off()
59 }
60 async fn create(&self, _draft: &ContactDraft) -> Result<ResourcePath, CoreError> {
61 off()
62 }
63 async fn update(
64 &self,
65 _path: &ResourcePath,
66 _etag: &ETag,
67 _update: &ContactUpdate,
68 ) -> Result<ETag, CoreError> {
69 off()
70 }
71 async fn delete(&self, _path: &ResourcePath, _etag: &ETag) -> Result<(), CoreError> {
72 off()
73 }
74 async fn set_group_membership(
75 &self,
76 _group: &ResourcePath,
77 _contact: &ResourcePath,
78 _change: GroupChange,
79 ) -> Result<(), CoreError> {
80 off()
81 }
82}
83
84macro_rules! try_contacts {
85 ($call:expr) => {
86 match $call {
87 Ok(value) => value,
88 Err(error) => return mapped(&error),
89 }
90 };
91}
92
93#[tool_router(router = contacts_router, vis = "pub(crate)")]
94impl<M, C, K> IbridgeServer<M, C, K>
95where
96 M: MailApi + Send + Sync + 'static,
97 C: CalendarProvider + RemindersProvider + Send + Sync + 'static,
98 K: ContactsProvider + Send + Sync + 'static,
99{
100 #[tool(
107 title = "Search contacts",
108 description = "Searches contacts by name, email address or phone number. Matching is done by this server, not by iCloud. Names, labels and notes are as stored on each card.",
109 annotations(read_only_hint = true, destructive_hint = false, open_world_hint = true),
110 output_schema = rmcp::handler::server::tool::schema_for_output::<ContactListOut>(),
111 )]
112 pub async fn contacts_search(
113 &self,
114 Parameters(params): Parameters<SearchContactsParams>,
115 ) -> Result<CallToolResult, ErrorData> {
116 let limit = page_limit(params.limit)?;
117 if params.query.trim().is_empty() {
118 return Err(ErrorData::invalid_params(
119 "query must be a name, an email address or a phone number",
120 None,
121 ));
122 }
123 let query = ContactQuery {
124 text: params.query,
125 limit,
126 include_groups: params.include_groups.unwrap_or(false),
127 };
128 let _permit = self.permit().await?;
129 let found = try_contacts!(self.contacts.search(&query).await);
130 let summary = if found.warnings == 0 {
131 format!("{} contacts", found.contacts.len())
132 } else {
133 format!(
134 "{} contacts, {} skipped",
135 found.contacts.len(),
136 found.warnings
137 )
138 };
139 respond(
140 &ContactListOut {
141 contacts: found.contacts.iter().map(contact_out).collect(),
142 warnings: found.warnings,
143 },
144 summary,
145 )
146 }
147
148 #[tool(
155 title = "Get contact",
156 description = "Fetches one contact in full: labels, note, company and the groups it is in. Names, labels and notes are as stored on the card.",
157 annotations(read_only_hint = true, destructive_hint = false, open_world_hint = true),
158 output_schema = rmcp::handler::server::tool::schema_for_output::<ContactOut>(),
159 )]
160 pub async fn contacts_get(
161 &self,
162 Parameters(params): Parameters<GetByIdParams>,
163 ) -> Result<CallToolResult, ErrorData> {
164 let path = require_path(¶ms.id)?;
165 let _permit = self.permit().await?;
166 let contact = try_contacts!(self.contacts.get(&path).await);
167 respond(&contact_out(&contact), "contact".to_owned())
168 }
169
170 #[tool(
177 title = "Create contact",
178 description = "Creates a contact from a name, email addresses and phone numbers.",
179 annotations(read_only_hint = false, destructive_hint = true, open_world_hint = true),
180 output_schema = rmcp::handler::server::tool::schema_for_output::<WriteOut>(),
181 )]
182 pub async fn contacts_create(
183 &self,
184 Parameters(params): Parameters<CreateContactParams>,
185 ) -> Result<CallToolResult, ErrorData> {
186 self.reject_write()?;
187 let draft = ContactDraft {
188 full_name: params.full_name,
189 emails: params.emails,
190 phones: params.phones,
191 };
192 let _permit = self.permit().await?;
193 let path = try_contacts!(self.contacts.create(&draft).await);
194 respond(
195 &WriteOut {
196 id: encode_resource(&path),
197 etag: None,
198 },
199 "contact created".to_owned(),
200 )
201 }
202
203 #[tool(
210 title = "Update contact",
211 description = "Changes a contact. Needs the etag from the last read; a changed contact is refused. Fields you omit, and everything else on the card, are kept.",
212 annotations(read_only_hint = false, destructive_hint = true, open_world_hint = true),
213 output_schema = rmcp::handler::server::tool::schema_for_output::<WriteOut>(),
214 )]
215 pub async fn contacts_update(
216 &self,
217 Parameters(params): Parameters<UpdateContactParams>,
218 ) -> Result<CallToolResult, ErrorData> {
219 self.reject_write()?;
220 let path = require_path(¶ms.id)?;
221 let etag = require_etag(¶ms.etag)?;
222 let _permit = self.permit().await?;
223 let changes = ContactUpdate {
225 full_name: params.full_name,
226 emails: params.emails,
227 phones: params.phones,
228 };
229 let new_etag = try_contacts!(self.contacts.update(&path, &etag, &changes).await);
230 respond(
231 &WriteOut {
232 id: params.id,
233 etag: Some(new_etag.as_str().to_owned()),
234 },
235 "contact updated".to_owned(),
236 )
237 }
238
239 #[tool(
246 title = "Delete contact",
247 description = "Deletes a contact. Needs the etag from the last read. iCloud ignores the etag on delete, so the card is read again and compared first; a small race window remains between that read and the delete.",
248 annotations(read_only_hint = false, destructive_hint = true, open_world_hint = true),
249 output_schema = rmcp::handler::server::tool::schema_for_output::<DeleteOut>(),
250 )]
251 pub async fn contacts_delete(
252 &self,
253 Parameters(params): Parameters<DeleteParams>,
254 ) -> Result<CallToolResult, ErrorData> {
255 self.reject_write()?;
256 let path = require_path(¶ms.id)?;
257 let etag = require_etag(¶ms.etag)?;
258 let _permit = self.permit().await?;
259 try_contacts!(self.contacts.delete(&path, &etag).await);
260 respond(&DeleteOut { deleted: true }, "contact deleted".to_owned())
261 }
262
263 #[tool(
270 title = "Change contact group membership",
271 description = "Adds a contact to an existing group or removes it, by rewriting the group card. Groups cannot be created or deleted.",
272 annotations(read_only_hint = false, destructive_hint = true, open_world_hint = true),
273 output_schema = rmcp::handler::server::tool::schema_for_output::<MembershipOut>(),
274 )]
275 pub async fn contacts_set_group_membership(
276 &self,
277 Parameters(params): Parameters<SetGroupMembershipParams>,
278 ) -> Result<CallToolResult, ErrorData> {
279 self.reject_write()?;
280 let change = match params.action.as_str() {
281 "add" => GroupChange::Add,
282 "remove" => GroupChange::Remove,
283 _ => {
284 return Err(ErrorData::invalid_params(
285 "action must be add or remove",
286 None,
287 ));
288 }
289 };
290 let group = require_path(¶ms.group)?;
291 let contact = require_path(¶ms.contact)?;
292 let _permit = self.permit().await?;
293 try_contacts!(
294 self.contacts
295 .set_group_membership(&group, &contact, change)
296 .await
297 );
298 respond(&MembershipOut { updated: true }, "group updated".to_owned())
299 }
300}
301
302fn labeled_out(value: &LabeledValue) -> LabeledOut {
303 LabeledOut {
304 value: strip_hidden(&value.value),
305 label: value.label.as_deref().map(strip_hidden),
306 }
307}
308
309fn contact_out(contact: &Contact) -> ContactOut {
310 ContactOut {
311 id: encode_resource(&contact.path),
312 etag: contact.etag.as_str().to_owned(),
313 name: strip_hidden(&contact.full_name),
314 emails: contact.emails.iter().map(labeled_out).collect(),
315 phones: contact.phones.iter().map(labeled_out).collect(),
316 organization: contact.organization.as_deref().map(strip_hidden),
317 note: contact
318 .note
319 .as_deref()
320 .map(|note| strip_hidden(&capped(note))),
321 is_group: contact.is_group,
322 groups: contact
323 .groups
324 .iter()
325 .map(|group| GroupOut {
326 id: encode_resource(&group.path),
327 name: strip_hidden(&group.name),
328 })
329 .collect(),
330 }
331}