tower-mcp-types 0.10.1

MCP protocol and error types for tower-mcp (no runtime dependencies)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
//! Error types for MCP
//!
//! ## JSON-RPC Error Codes
//!
//! Standard JSON-RPC 2.0 error codes are defined in the specification:
//! <https://www.jsonrpc.org/specification#error_object>
//!
//! | Code   | Message          | Meaning                                  |
//! |--------|------------------|------------------------------------------|
//! | -32700 | Parse error      | Invalid JSON was received                |
//! | -32600 | Invalid Request  | The JSON sent is not a valid Request     |
//! | -32601 | Method not found | The method does not exist / is not available |
//! | -32602 | Invalid params   | Invalid method parameter(s)              |
//! | -32603 | Internal error   | Internal JSON-RPC error                  |
//!
//! ## MCP-Specific Error Codes
//!
//! MCP uses the server error range (-32000 to -32099) for protocol-specific errors:
//!
//! | Code   | Name            | Meaning                                  |
//! |--------|-----------------|------------------------------------------|
//! | -32000 | ConnectionClosed| Transport connection was closed          |
//! | -32001 | RequestTimeout  | Request exceeded timeout                 |
//! | -32002 | ResourceNotFound| Resource not found                       |
//! | -32003 | AlreadySubscribed| Resource already subscribed             |
//! | -32004 | NotSubscribed   | Resource not subscribed (for unsubscribe)|
//! | -32005 | SessionNotFound | Session not found or expired             |
//! | -32006 | SessionRequired | MCP-Session-Id header is required        |
//! | -32007 | Forbidden       | Access forbidden (insufficient scope)    |
//! | -32042 | UrlElicitationRequired | URL elicitation required          |

use serde::{Deserialize, Serialize};

/// Type-erased error type used for middleware composition.
///
/// This is the standard error type in the tower ecosystem, used by
/// [`tower`](https://docs.rs/tower), [`tower-http`](https://docs.rs/tower-http),
/// and other tower-compatible crates.
pub type BoxError = Box<dyn std::error::Error + Send + Sync>;

/// Standard JSON-RPC error codes
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(i32)]
#[non_exhaustive]
pub enum ErrorCode {
    /// Invalid JSON was received
    ParseError = -32700,
    /// The JSON sent is not a valid Request object
    InvalidRequest = -32600,
    /// The method does not exist / is not available
    MethodNotFound = -32601,
    /// Invalid method parameter(s)
    InvalidParams = -32602,
    /// Internal JSON-RPC error
    InternalError = -32603,
}

/// MCP-specific error codes (in the -32000 to -32099 range)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(i32)]
#[non_exhaustive]
pub enum McpErrorCode {
    /// Transport connection was closed
    ConnectionClosed = -32000,
    /// Request exceeded timeout
    RequestTimeout = -32001,
    /// Resource not found
    ResourceNotFound = -32002,
    /// Resource already subscribed
    AlreadySubscribed = -32003,
    /// Resource not subscribed (for unsubscribe)
    NotSubscribed = -32004,
    /// Session not found or expired - client should re-initialize
    SessionNotFound = -32005,
    /// Session ID is required but was not provided
    SessionRequired = -32006,
    /// Access forbidden (insufficient scope or authorization)
    Forbidden = -32007,
    /// URL elicitation is required before processing the request
    UrlElicitationRequired = -32042,
}

impl McpErrorCode {
    pub fn code(self) -> i32 {
        self as i32
    }
}

impl ErrorCode {
    pub fn code(self) -> i32 {
        self as i32
    }
}

/// JSON-RPC error object
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JsonRpcError {
    pub code: i32,
    pub message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<serde_json::Value>,
}

impl JsonRpcError {
    pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
        Self {
            code: code.code(),
            message: message.into(),
            data: None,
        }
    }

    pub fn with_data(mut self, data: serde_json::Value) -> Self {
        self.data = Some(data);
        self
    }

    pub fn parse_error(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::ParseError, message)
    }

    pub fn invalid_request(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::InvalidRequest, message)
    }

    pub fn method_not_found(method: &str) -> Self {
        Self::new(
            ErrorCode::MethodNotFound,
            format!("Method not found: {}", method),
        )
    }

    pub fn invalid_params(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::InvalidParams, message)
    }

    pub fn internal_error(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::InternalError, message)
    }

    /// Create an MCP-specific error
    pub fn mcp_error(code: McpErrorCode, message: impl Into<String>) -> Self {
        Self {
            code: code.code(),
            message: message.into(),
            data: None,
        }
    }

    /// Connection was closed
    pub fn connection_closed(message: impl Into<String>) -> Self {
        Self::mcp_error(McpErrorCode::ConnectionClosed, message)
    }

    /// Request timed out
    pub fn request_timeout(message: impl Into<String>) -> Self {
        Self::mcp_error(McpErrorCode::RequestTimeout, message)
    }

    /// Resource not found
    pub fn resource_not_found(uri: &str) -> Self {
        Self::mcp_error(
            McpErrorCode::ResourceNotFound,
            format!("Resource not found: {}", uri),
        )
    }

    /// Resource already subscribed
    pub fn already_subscribed(uri: &str) -> Self {
        Self::mcp_error(
            McpErrorCode::AlreadySubscribed,
            format!("Already subscribed to: {}", uri),
        )
    }

    /// Resource not subscribed
    pub fn not_subscribed(uri: &str) -> Self {
        Self::mcp_error(
            McpErrorCode::NotSubscribed,
            format!("Not subscribed to: {}", uri),
        )
    }

    /// Session not found or expired
    ///
    /// Clients receiving this error should re-initialize the connection.
    /// The session may have expired due to inactivity or server restart.
    pub fn session_not_found() -> Self {
        Self::mcp_error(
            McpErrorCode::SessionNotFound,
            "Session not found or expired. Please re-initialize the connection.",
        )
    }

    /// Session not found with a specific session ID
    pub fn session_not_found_with_id(session_id: &str) -> Self {
        Self::mcp_error(
            McpErrorCode::SessionNotFound,
            format!(
                "Session '{}' not found or expired. Please re-initialize the connection.",
                session_id
            ),
        )
    }

    /// Session ID is required
    pub fn session_required() -> Self {
        Self::mcp_error(
            McpErrorCode::SessionRequired,
            "MCP-Session-Id header is required for this request.",
        )
    }

    /// Access forbidden (insufficient scope or authorization)
    pub fn forbidden(message: impl Into<String>) -> Self {
        Self::mcp_error(McpErrorCode::Forbidden, message)
    }

    /// URL elicitation is required before processing the request
    pub fn url_elicitation_required(message: impl Into<String>) -> Self {
        Self::mcp_error(McpErrorCode::UrlElicitationRequired, message)
    }
}

/// Tool execution error with context
#[derive(Debug)]
pub struct ToolError {
    /// The tool name that failed
    pub tool: Option<String>,
    /// Error message
    pub message: String,
    /// Source error if any
    pub source: Option<BoxError>,
}

impl std::fmt::Display for ToolError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(tool) = &self.tool {
            write!(f, "Tool '{}' error: {}", tool, self.message)
        } else {
            write!(f, "Tool error: {}", self.message)
        }
    }
}

impl std::error::Error for ToolError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.source
            .as_ref()
            .map(|e| e.as_ref() as &(dyn std::error::Error + 'static))
    }
}

impl ToolError {
    /// Create a new tool error with just a message
    pub fn new(message: impl Into<String>) -> Self {
        Self {
            tool: None,
            message: message.into(),
            source: None,
        }
    }

    /// Create a tool error with the tool name
    pub fn with_tool(tool: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            tool: Some(tool.into()),
            message: message.into(),
            source: None,
        }
    }

    /// Add a source error
    pub fn with_source(mut self, source: impl std::error::Error + Send + Sync + 'static) -> Self {
        self.source = Some(Box::new(source));
        self
    }
}

/// tower-mcp error type
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    #[error("JSON-RPC error: {0:?}")]
    JsonRpc(JsonRpcError),

    #[error("Serialization error: {0}")]
    Serialization(#[from] serde_json::Error),

    /// A tool execution error.
    ///
    /// When returned from a tool handler, this variant is mapped to JSON-RPC
    /// error code `-32603` (Internal Error) in the router's `Service::call`
    /// implementation. The `ToolError` message becomes the JSON-RPC error message.
    #[error("{0}")]
    Tool(#[from] ToolError),

    #[error("Transport error: {0}")]
    Transport(String),

    /// The server indicated the session has expired or is not found.
    ///
    /// This corresponds to JSON-RPC error code `-32005` (SessionNotFound)
    /// or an HTTP 404 response when a session ID was attached.
    /// Clients should re-initialize the connection.
    #[error("Session expired")]
    SessionExpired,

    #[error("Internal error: {0}")]
    Internal(String),
}

impl Error {
    /// Create a simple tool error from a string (for backwards compatibility)
    pub fn tool(message: impl Into<String>) -> Self {
        Error::Tool(ToolError::new(message))
    }

    /// Create a tool error with the tool name
    pub fn tool_with_name(tool: impl Into<String>, message: impl Into<String>) -> Self {
        Error::Tool(ToolError::with_tool(tool, message))
    }

    /// Create a tool error from any `Display` type.
    ///
    /// This is useful for converting errors in a `map_err` chain:
    ///
    /// ```rust
    /// # use tower_mcp_types::Error;
    /// # fn example() -> Result<(), Error> {
    /// let result: Result<(), std::io::Error> = Err(std::io::Error::other("oops"));
    /// result.map_err(Error::tool_from)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn tool_from<E: std::fmt::Display>(err: E) -> Self {
        Error::Tool(ToolError::new(err.to_string()))
    }

    /// Create a tool error with context prefix.
    ///
    /// This is useful for adding context when converting errors.
    /// For a more ergonomic API, see [`ResultExt::tool_context`] which can be
    /// called directly on `Result` values:
    ///
    /// ```rust
    /// # use tower_mcp_types::error::ResultExt;
    /// # fn example() -> tower_mcp_types::Result<()> {
    /// let result: Result<(), std::io::Error> = Err(std::io::Error::other("connection refused"));
    /// result.tool_context("API request failed")?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn tool_context<E: std::fmt::Display>(context: impl Into<String>, err: E) -> Self {
        Error::Tool(ToolError::new(format!("{}: {}", context.into(), err)))
    }

    /// Create a JSON-RPC "Invalid params" error (`-32602`).
    ///
    /// Shorthand for `Error::JsonRpc(JsonRpcError::invalid_params(msg))`.
    ///
    /// ```rust
    /// # use tower_mcp_types::Error;
    /// let err = Error::invalid_params("missing required field 'name'");
    /// ```
    pub fn invalid_params(message: impl Into<String>) -> Self {
        Error::JsonRpc(JsonRpcError::invalid_params(message))
    }

    /// Create a JSON-RPC "Internal error" error (`-32603`).
    ///
    /// Shorthand for `Error::JsonRpc(JsonRpcError::internal_error(msg))`.
    ///
    /// ```rust
    /// # use tower_mcp_types::Error;
    /// let err = Error::internal("unexpected state");
    /// ```
    pub fn internal(message: impl Into<String>) -> Self {
        Error::JsonRpc(JsonRpcError::internal_error(message))
    }
}

/// Extension trait for converting errors into tower-mcp tool errors.
///
/// Provides ergonomic error conversion methods on `Result` types,
/// similar to `anyhow::Context`. Import this trait to use `.tool_err()`
/// and `.tool_context()` on any `Result` whose error type implements `Display`.
///
/// # Examples
///
/// ```rust
/// use tower_mcp_types::error::ResultExt;
///
/// fn query_database() -> tower_mcp_types::Result<String> {
///     let result: Result<String, std::io::Error> =
///         Err(std::io::Error::other("connection refused"));
///     let value = result.tool_context("database query failed")?;
///     Ok(value)
/// }
/// ```
pub trait ResultExt<T> {
    /// Convert the error into a tool error.
    ///
    /// ```rust
    /// use tower_mcp_types::error::ResultExt;
    /// # fn example() -> tower_mcp_types::Result<()> {
    /// let value: Result<i32, std::io::Error> = Err(std::io::Error::other("timeout"));
    /// let value = value.tool_err()?;
    /// # Ok(())
    /// # }
    /// ```
    fn tool_err(self) -> std::result::Result<T, Error>;

    /// Convert the error into a tool error with additional context.
    ///
    /// ```rust
    /// use tower_mcp_types::error::ResultExt;
    /// # fn example() -> tower_mcp_types::Result<()> {
    /// let value: Result<i32, std::io::Error> = Err(std::io::Error::other("timeout"));
    /// let value = value.tool_context("database query failed")?;
    /// # Ok(())
    /// # }
    /// ```
    fn tool_context(self, context: impl Into<String>) -> std::result::Result<T, Error>;
}

impl<T, E: std::fmt::Display> ResultExt<T> for std::result::Result<T, E> {
    fn tool_err(self) -> std::result::Result<T, Error> {
        self.map_err(Error::tool_from)
    }

    fn tool_context(self, context: impl Into<String>) -> std::result::Result<T, Error> {
        self.map_err(|e| Error::tool_context(context, e))
    }
}

impl From<JsonRpcError> for Error {
    fn from(err: JsonRpcError) -> Self {
        Error::JsonRpc(err)
    }
}

impl From<std::convert::Infallible> for Error {
    fn from(err: std::convert::Infallible) -> Self {
        match err {}
    }
}

/// Result type alias for tower-mcp
pub type Result<T> = std::result::Result<T, Error>;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_box_error_from_io_error() {
        let io_err = std::io::Error::other("disk full");
        let boxed: BoxError = io_err.into();
        assert_eq!(boxed.to_string(), "disk full");
    }

    #[test]
    fn test_box_error_from_string() {
        let err: BoxError = "something went wrong".into();
        assert_eq!(err.to_string(), "something went wrong");
    }

    #[test]
    fn test_box_error_is_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<BoxError>();
    }

    #[test]
    fn test_tool_error_source_uses_box_error() {
        let io_err = std::io::Error::other("timeout");
        let tool_err = ToolError::new("failed").with_source(io_err);
        assert!(tool_err.source.is_some());
        assert_eq!(tool_err.source.unwrap().to_string(), "timeout");
    }

    #[test]
    fn test_result_ext_tool_err() {
        let result: std::result::Result<(), std::io::Error> =
            Err(std::io::Error::other("disk full"));
        let err = result.tool_err().unwrap_err();
        assert!(matches!(err, Error::Tool(_)));
        assert!(err.to_string().contains("disk full"));
    }

    #[test]
    fn test_result_ext_tool_context() {
        let result: std::result::Result<(), std::io::Error> =
            Err(std::io::Error::other("connection refused"));
        let err = result.tool_context("database query failed").unwrap_err();
        assert!(matches!(err, Error::Tool(_)));
        assert!(err.to_string().contains("database query failed"));
        assert!(err.to_string().contains("connection refused"));
    }

    #[test]
    fn test_result_ext_ok_passes_through() {
        let result: std::result::Result<i32, std::io::Error> = Ok(42);
        assert_eq!(result.tool_err().unwrap(), 42);
        let result: std::result::Result<i32, std::io::Error> = Ok(42);
        assert_eq!(result.tool_context("should not appear").unwrap(), 42);
    }
}