use std::borrow::Cow;
use ibridge_core::CoreError;
use rmcp::model::ErrorData;
#[derive(Debug)]
#[non_exhaustive]
pub enum MappedError {
Rpc(ErrorData),
Tool(Cow<'static, str>),
}
#[must_use]
pub fn map_core_error(error: &CoreError) -> MappedError {
match error {
CoreError::InvalidInput(message) => {
MappedError::Rpc(ErrorData::invalid_params(message.clone(), None))
}
CoreError::NotFound => {
MappedError::Tool(Cow::Borrowed("not found; check the id and fetch it again"))
}
CoreError::Conflict => {
MappedError::Tool(Cow::Borrowed("changed since you read it; fetch it again"))
}
CoreError::Forbidden => MappedError::Tool(Cow::Borrowed(
"iCloud refused this change; the calendar or address book may be read-only, or the item may not be valid",
)),
CoreError::Auth => {
MappedError::Tool(Cow::Borrowed("authentication failed; run ibridge login"))
}
_ => MappedError::Rpc(ErrorData::internal_error("internal error", None)),
}
}
#[cfg(test)]
mod tests {
use ibridge_core::CoreError;
use rmcp::model::ErrorCode;
use super::{MappedError, map_core_error};
#[test]
fn forbidden_is_a_tool_error_that_does_not_ask_to_reconnect() {
let MappedError::Tool(message) = map_core_error(&CoreError::Forbidden) else {
panic!("a refused change is a tool error the model can read");
};
assert!(
message.contains("read-only") && !message.contains("login"),
"the message names the cause and not the password, got {message}"
);
}
#[test]
fn error_map_hides_server_text() {
let raw = "NO [ALERT] password=hunter2 imap banner from the server";
let mapped = map_core_error(&CoreError::Protocol(raw.to_owned()));
let MappedError::Rpc(data) = mapped else {
panic!("a protocol failure is an internal error");
};
let rendered = format!("{data} {:?}", data.data);
assert!(
!rendered.contains("hunter2") && !rendered.contains("imap banner"),
"raw server text leaked into the MCP error: {rendered}"
);
assert_eq!(
data.code,
ErrorCode::INTERNAL_ERROR,
"a protocol failure is an internal error, got {}",
data.code.0
);
}
}