use crate::mcp::{Error, Result};
use rpc_router::{RpcError, RpcErrorResponse, RpcId, RpcResponse};
use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error as DeError};
#[derive(Debug, Clone)]
pub struct McpError {
pub id: RpcId,
pub error: RpcError,
}
impl McpError {
pub fn stringify(&self) -> Result<String> {
serde_json::to_string(&self).map_err(Error::custom_from_err)
}
pub fn stringify_pretty(&self) -> Result<String> {
serde_json::to_string_pretty(&self).map_err(Error::custom_from_err)
}
}
impl Serialize for McpError {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
let error_response = RpcErrorResponse {
id: self.id.clone(),
error: self.error.clone(), };
let rpc_response = RpcResponse::Error(error_response);
rpc_response.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for McpError {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let rpc_response = RpcResponse::deserialize(deserializer)?;
match rpc_response {
RpcResponse::Error(err) => Ok(McpError {
id: err.id,
error: err.error,
}),
RpcResponse::Success(success) => {
Err(DeError::custom(format!(
"Expected an error response, but got a success response: id={}",
success.id
)))
}
}
}
}