mcp_rs_sdk/
error.rs

1//! Defines the custom error type for the MCP Rust SDK.
2use std::fmt;
3
4/// The primary error type for all fallible operations in the `mcp-rust-sdk`.
5#[derive(Debug)]
6pub enum McpError {
7    /// An error occurred during I/O operations (e.g., reading from stdin or writing to stdout).
8    Io(std::io::Error),
9    /// An error occurred during JSON serialization or deserialization.
10    Json(serde_json::Error),
11    /// An error returned by the user-provided handler function.
12    /// We wrap it in a Box to allow for any error type that implements `std::error::Error`.
13    Handler(Box<dyn std::error::Error + Send + Sync>),
14}
15
16impl fmt::Display for McpError {
17    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
18        match self {
19            McpError::Io(err) => write!(f, "I/O error: {}", err),
20            McpError::Json(err) => write!(f, "JSON processing error: {}", err),
21            McpError::Handler(err) => write!(f, "Handler error: {}", err),
22        }
23    }
24}
25
26impl std::error::Error for McpError {
27    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
28        match self {
29            McpError::Io(err) => Some(err),
30            McpError::Json(err) => Some(err),
31            McpError::Handler(err) => Some(err.as_ref()),
32        }
33    }
34}
35
36// Convenience implementations to convert from underlying error types.
37impl From<std::io::Error> for McpError {
38    fn from(err: std::io::Error) -> Self {
39        McpError::Io(err)
40    }
41}
42
43impl From<serde_json::Error> for McpError {
44    fn from(err: serde_json::Error) -> Self {
45        McpError::Json(err)
46    }
47}