Module error

Module error 

Source
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 miette for 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

ScenarioUseReason
Database connection failedMcpErrorInfrastructure issue
User provided invalid email formatToolOutput::errorLLM can fix input
Tool doesn’t existMcpErrorProtocol/discovery issue
Search returned no resultsToolOutput::text("No results")Expected outcome
API rate limit exceededToolOutput::error_with_suggestionTemporary, can retry
Authentication requiredMcpErrorConfiguration issue
Invalid number format in inputToolOutput::errorLLM 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§

HandshakeDetails
Details for handshake errors (boxed to reduce enum size).
InvalidParamsDetails
Details for invalid params errors (boxed to reduce enum size).
JsonRpcError
A JSON-RPC error response object.
ToolExecutionDetails
Details for tool execution errors (boxed to reduce enum size).
TransportContext
Additional context for transport errors.
TransportDetails
Details for transport errors (boxed to reduce enum size).

Enums§

McpError
The primary error type for the MCP SDK.
TransportErrorKind
Classification of transport errors.

Traits§

McpResultExt
Extension trait for adding context to Result types.

Type Aliases§

BoxError
Type alias for boxed errors that are Send + Sync.