Expand description
Unified error handling for the MCP SDK.
This module provides a single, context-rich error type that replaces the nested error hierarchies found in other implementations.
§Design Philosophy
- Single error type: All errors flow through
McpError - Rich context: Errors preserve context through the entire call stack
- JSON-RPC compatible: Easy conversion to JSON-RPC error responses
- Diagnostic-friendly: Integrates with
miettefor detailed error reports - Size-optimized: Large error variants are boxed to keep
Result<T, McpError>small
§Error Handling Patterns
The SDK has two distinct error handling patterns for different scenarios:
§Pattern 1: Result<T, McpError> - For SDK/Framework Errors
Use Result<T, McpError> for errors that indicate something went wrong
with the MCP protocol, transport, or SDK internals:
- Transport failures: Connection lost, timeout, I/O errors
- Protocol errors: Invalid JSON-RPC, version mismatch, missing fields
- Resource not found: Requested resource/tool/prompt doesn’t exist
- Capability errors: Feature not supported by client/server
- Internal errors: Unexpected SDK state, serialization failures
These errors typically indicate the request cannot be completed and require intervention (reconnection, configuration change, bug fix).
async fn list_tools(&self) -> Result<Vec<Tool>, McpError> {
self.ensure_capability("tools", self.has_tools())?;
// Transport errors propagate as McpError
let result = self.request("tools/list", None).await?;
Ok(result.tools)
}§Pattern 2: ToolOutput::RecoverableError - For User/LLM-Correctable Errors
Use ToolOutput::error() for errors that the LLM
can potentially self-correct by adjusting its input:
- Validation failures: Invalid argument format, out-of-range values
- Business logic errors: Division by zero, empty query, invalid date
- Missing optional data: Lookup returned no results
- Rate limiting: Too many requests (suggest retry)
These errors are returned to the LLM with is_error: true in the response,
allowing the model to understand what went wrong and try again.
// #[tool(description = "Divide two numbers")]
async fn divide(&self, a: f64, b: f64) -> ToolOutput {
if b == 0.0 {
return ToolOutput::error_with_suggestion(
"Cannot divide by zero",
"Use a non-zero divisor",
);
}
ToolOutput::text((a / b).to_string())
}§Decision Guide
| Scenario | Use | Reason |
|---|---|---|
| Database connection failed | McpError | Infrastructure issue |
| User provided invalid email format | ToolOutput::error | LLM can fix input |
| Tool doesn’t exist | McpError | Protocol/discovery issue |
| Search returned no results | ToolOutput::text("No results") | Expected outcome |
| API rate limit exceeded | ToolOutput::error_with_suggestion | Temporary, can retry |
| Authentication required | McpError | Configuration issue |
| Invalid number format in input | ToolOutput::error | LLM can fix input |
§Context Chaining
For McpError, use context chaining to provide detailed diagnostics:
use mcpkit_core::error::{McpError, McpResultExt};
fn fetch_data() -> Result<String, McpError> {
let user_id = 42;
// Errors automatically get context
let result: Result<(), McpError> = Err(McpError::resource_not_found("user://42"));
result
.context("Failed to fetch user data")
.with_context(|| format!("User ID: {}", user_id))?;
Ok("data".to_string())
}Re-exports§
pub use codes::*;
Modules§
- codes
- Standard JSON-RPC and MCP error codes.
Structs§
- Handshake
Details - Details for handshake errors (boxed to reduce enum size).
- Invalid
Params Details - Details for invalid params errors (boxed to reduce enum size).
- Json
RpcError - A JSON-RPC error response object.
- Tool
Execution Details - Details for tool execution errors (boxed to reduce enum size).
- Transport
Context - Additional context for transport errors.
- Transport
Details - Details for transport errors (boxed to reduce enum size).
Enums§
- McpError
- The primary error type for the MCP SDK.
- Transport
Error Kind - Classification of transport errors.
Traits§
- McpResult
Ext - Extension trait for adding context to
Resulttypes.
Type Aliases§
- BoxError
- Type alias for boxed errors that are Send + Sync.