tower-mcp-types 0.11.0

Standalone MCP protocol types -- no Tower/Tokio required, WASM-safe, re-exported by tower-mcp
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
//! 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. Codes assigned by the spec are marked **spec**; codes used only by
//! this implementation (in the JSON-RPC "implementation-defined" subrange) are
//! marked *impl*.
//!
//! | Code   | Name                          | Source | Meaning                              |
//! |--------|-------------------------------|--------|--------------------------------------|
//! | -32000 | ConnectionClosed              | *impl* | Transport connection was closed      |
//! | -32001 | HeaderMismatch                | **spec** (SEP-2243) | HTTP headers do not match the request body, or required headers are missing/malformed |
//! | -32002 | ResourceNotFound              | *deprecated* | **SEP-2164** reassigned to -32602; variant kept for backcompat |
//! | -32003 | MissingRequiredClientCapability | **spec** (SEP-2575) | Client lacks a capability required by the request |
//! | -32004 | UnsupportedProtocolVersion    | **spec** (SEP-2575) | Server does not support the request's protocol version |
//! | -32005 | SessionNotFound               | *impl* | Session not found or expired (legacy; deprecated by SEP-2567) |
//! | -32006 | SessionRequired               | *impl* | Mcp-Session-Id header required (legacy; deprecated by SEP-2567) |
//! | -32007 | Forbidden                     | *impl* | Access forbidden (insufficient scope)|
//! | -32008 | AlreadySubscribed             | *impl* | Resource already subscribed (moved from -32003 to avoid collision with SEP-2575) |
//! | -32009 | NotSubscribed                 | *impl* | Resource not subscribed (moved from -32004 to avoid collision with SEP-2575) |
//! | -32010 | RequestTimeout                | *impl* | Request exceeded timeout (moved from -32001 to avoid collision with SEP-2243) |
//! | -32042 | UrlElicitationRequired        | TS SDK | 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).
///
/// Codes marked **spec** are assigned by an MCP SEP. Others are
/// implementation-defined within the JSON-RPC server-error range; using them
/// is permitted by JSON-RPC 2.0 but they are not part of the MCP wire spec.
///
/// Recently-changed assignments:
/// - `MissingRequiredClientCapability` (-32003) and `UnsupportedProtocolVersion`
///   (-32004) are spec assignments from SEP-2575.
/// - `AlreadySubscribed` and `NotSubscribed` previously occupied -32003 and
///   -32004; they moved to -32008 and -32009 to make room. **This is a
///   breaking change on the wire** for any subscribe/unsubscribe responses
///   that relied on the old codes.
/// - `HeaderMismatch` (-32001) is a spec assignment from SEP-2243 (HTTP
///   header standardization). `RequestTimeout` previously occupied -32001
///   and moved to -32010 to make room. **This is a breaking change on the
///   wire** for any consumers matching on the old `RequestTimeout` code.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(i32)]
#[non_exhaustive]
pub enum McpErrorCode {
    /// Transport connection was closed.
    ConnectionClosed = -32000,
    /// SEP-2243: HTTP headers (e.g. `Mcp-Method`, `Mcp-Name`,
    /// `Mcp-Param-*`) do not match the corresponding values in the request
    /// body, or a required header is missing or malformed.
    ///
    /// Use [`JsonRpcError::header_mismatch`] to construct.
    HeaderMismatch = -32001,
    /// Resource not found.
    ///
    /// **Deprecated**: SEP-2164 (FINAL) moves this to the standard JSON-RPC
    /// `InvalidParams` code (-32602). The
    /// [`JsonRpcError::resource_not_found`] constructor now emits -32602.
    /// The enum variant is retained so existing pattern matches on
    /// `McpErrorCode::ResourceNotFound` keep compiling, but the variant's
    /// numeric value is no longer what the constructor produces.
    #[deprecated(
        since = "0.12.0",
        note = "SEP-2164 reassigned resource-not-found to InvalidParams (-32602). \
                Use JsonRpcError::resource_not_found or ErrorCode::InvalidParams."
    )]
    ResourceNotFound = -32002,
    /// SEP-2575: client capabilities advertised on the request do not
    /// include a capability required by the called method.
    MissingRequiredClientCapability = -32003,
    /// SEP-2575: server does not support the protocol version the client
    /// requested (via `MCP-Protocol-Version` header or per-request `_meta`).
    /// Use [`JsonRpcError::unsupported_protocol_version`] to construct.
    UnsupportedProtocolVersion = -32004,
    /// Session not found or expired -- client should re-initialize.
    ///
    /// SEP-2567 deprecates sessions entirely. This code stays for the
    /// 2025-11-25 protocol path; sessionless deployments will never emit it.
    SessionNotFound = -32005,
    /// Session ID is required but was not provided.
    ///
    /// SEP-2567 deprecates sessions entirely. Same caveat as `SessionNotFound`.
    SessionRequired = -32006,
    /// Access forbidden (insufficient scope or authorization).
    Forbidden = -32007,
    /// Resource already subscribed. Moved from -32003 to avoid the
    /// SEP-2575 `MissingRequiredClientCapability` collision.
    AlreadySubscribed = -32008,
    /// Resource not subscribed (for unsubscribe). Moved from -32004 to
    /// avoid the SEP-2575 `UnsupportedProtocolVersion` collision.
    NotSubscribed = -32009,
    /// Request exceeded timeout. Moved from -32001 to avoid the SEP-2243
    /// `HeaderMismatch` collision.
    RequestTimeout = -32010,
    /// 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. Per SEP-2164 (FINAL) this now uses the
    /// standard JSON-RPC `InvalidParams` code (-32602) rather than the
    /// legacy MCP-specific [`McpErrorCode::ResourceNotFound`] (-32002).
    /// The resource URI is a parameter, so missing-parameter and
    /// unknown-resource-URI are the same error class.
    pub fn resource_not_found(uri: &str) -> Self {
        Self::new(
            ErrorCode::InvalidParams,
            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)
    }

    /// SEP-2243: HTTP headers do not match the request body, or a required
    /// header is missing or malformed.
    ///
    /// Servers using the Streamable HTTP transport return this error code
    /// (with HTTP status `400 Bad Request`) when any of the following hold:
    ///
    /// - A required standard header (`Mcp-Method`, `Mcp-Name`) is missing
    ///   for the corresponding method.
    /// - A header value does not match the request body value.
    /// - A `Mcp-Param-{Name}` Base64-encoded value cannot be decoded.
    /// - A header value contains invalid characters.
    pub fn header_mismatch(message: impl Into<String>) -> Self {
        Self::mcp_error(McpErrorCode::HeaderMismatch, message)
    }

    /// SEP-2575: server does not support the protocol version the client
    /// requested. The error data carries both the AS-supported versions
    /// and the version the client asked for, matching the spec shape:
    ///
    /// ```text
    /// data: { supported: [...], requested: "..." }
    /// ```
    pub fn unsupported_protocol_version(
        requested: impl Into<String>,
        supported: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        let data = UnsupportedProtocolVersionData {
            supported: supported.into_iter().map(Into::into).collect(),
            requested: requested.into(),
        };
        Self {
            code: McpErrorCode::UnsupportedProtocolVersion.code(),
            message: format!(
                "Unsupported protocol version: {} (supported: {})",
                data.requested,
                data.supported.join(", "),
            ),
            data: Some(
                serde_json::to_value(&data)
                    .expect("UnsupportedProtocolVersionData is serializable"),
            ),
        }
    }
}

/// SEP-2575 error data for `UnsupportedProtocolVersion` (-32004).
///
/// Wire shape per the draft schema:
/// ```json
/// {
///   "supported": ["2026-07-28", "2025-11-25"],
///   "requested": "2027-01-01"
/// }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UnsupportedProtocolVersionData {
    /// Protocol versions the server supports. The client should pick a
    /// mutually-supported version from this list and retry.
    pub supported: Vec<String>,
    /// The protocol version that was requested by the client.
    pub requested: String,
}

/// 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::*;

    // =========================================================================
    // SEP-2575 UnsupportedProtocolVersion (-32004) wire-format tests
    // =========================================================================

    #[test]
    fn unsupported_protocol_version_code_is_negative_32004() {
        assert_eq!(McpErrorCode::UnsupportedProtocolVersion.code(), -32004);
    }

    #[test]
    fn unsupported_protocol_version_constructor_has_spec_shape() {
        let err =
            JsonRpcError::unsupported_protocol_version("2027-01-01", ["2026-07-28", "2025-11-25"]);
        assert_eq!(err.code, -32004);
        let data = err.data.expect("data must be present");
        assert_eq!(
            data["supported"],
            serde_json::json!(["2026-07-28", "2025-11-25"])
        );
        assert_eq!(data["requested"], "2027-01-01");
        assert!(
            data.get("supportedVersions").is_none(),
            "spec field name is 'supported', not 'supportedVersions'"
        );
    }

    #[test]
    fn unsupported_protocol_version_data_round_trip() {
        let original = UnsupportedProtocolVersionData {
            supported: vec!["2026-07-28".into(), "2025-11-25".into()],
            requested: "2027-01-01".into(),
        };
        let json = serde_json::to_value(&original).unwrap();
        let parsed: UnsupportedProtocolVersionData = serde_json::from_value(json.clone()).unwrap();
        assert_eq!(parsed.supported, original.supported);
        assert_eq!(parsed.requested, original.requested);
    }

    // =========================================================================
    // SEP-2164: ResourceNotFound -> InvalidParams (-32602)
    // =========================================================================

    #[test]
    fn resource_not_found_constructor_uses_invalid_params() {
        let err = JsonRpcError::resource_not_found("file:///gone.txt");
        assert_eq!(err.code, ErrorCode::InvalidParams.code());
        assert_eq!(err.code, -32602);
        assert!(err.message.contains("file:///gone.txt"));
    }

    #[test]
    fn resource_not_found_serializes_with_spec_code() {
        let err = JsonRpcError::resource_not_found("urn:test:x");
        let json = serde_json::to_value(&err).unwrap();
        assert_eq!(json["code"], -32602);
    }

    // =========================================================================
    // Subscribe-code migration (avoid SEP-2575 collision)
    // =========================================================================

    #[test]
    fn subscribe_codes_moved_off_spec_assignments() {
        // -32003 and -32004 belong to SEP-2575 spec codes; our subscribe codes
        // moved to -32008/-32009 to avoid collision.
        assert_eq!(McpErrorCode::AlreadySubscribed.code(), -32008);
        assert_eq!(McpErrorCode::NotSubscribed.code(), -32009);
        assert_eq!(McpErrorCode::MissingRequiredClientCapability.code(), -32003);
        assert_eq!(McpErrorCode::UnsupportedProtocolVersion.code(), -32004);
    }

    // =========================================================================
    // SEP-2243 HeaderMismatch (-32001) wire-format tests
    // =========================================================================

    #[test]
    fn header_mismatch_code_is_negative_32001() {
        assert_eq!(McpErrorCode::HeaderMismatch.code(), -32001);
    }

    #[test]
    fn header_mismatch_constructor_uses_spec_code() {
        let err = JsonRpcError::header_mismatch(
            "Mcp-Name header value 'foo' does not match body value 'bar'",
        );
        assert_eq!(err.code, -32001);
        assert_eq!(err.code, McpErrorCode::HeaderMismatch.code());
        assert!(err.message.contains("Mcp-Name"));
    }

    #[test]
    fn request_timeout_moved_off_spec_assignment() {
        // SEP-2243 took -32001 for HeaderMismatch; our RequestTimeout
        // moved to -32010 to avoid collision.
        assert_eq!(McpErrorCode::RequestTimeout.code(), -32010);
        assert_eq!(McpErrorCode::HeaderMismatch.code(), -32001);
    }

    #[test]
    #[allow(deprecated)] // ResourceNotFound stays in the enum for backcompat
    fn no_two_mcp_codes_share_a_value() {
        let all = [
            McpErrorCode::ConnectionClosed.code(),
            McpErrorCode::HeaderMismatch.code(),
            McpErrorCode::RequestTimeout.code(),
            McpErrorCode::ResourceNotFound.code(),
            McpErrorCode::MissingRequiredClientCapability.code(),
            McpErrorCode::UnsupportedProtocolVersion.code(),
            McpErrorCode::SessionNotFound.code(),
            McpErrorCode::SessionRequired.code(),
            McpErrorCode::Forbidden.code(),
            McpErrorCode::AlreadySubscribed.code(),
            McpErrorCode::NotSubscribed.code(),
            McpErrorCode::UrlElicitationRequired.code(),
        ];
        let mut sorted = all.to_vec();
        sorted.sort_unstable();
        let original_len = sorted.len();
        sorted.dedup();
        assert_eq!(
            sorted.len(),
            original_len,
            "collision in McpErrorCode values: {:?}",
            all
        );
    }

    #[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);
    }
}