turbomcp-protocol 3.1.5

Complete MCP protocol implementation with types, traits, context management, and message handling
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
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
//! # JSON-RPC 2.0 Implementation
//!
//! This module provides a complete implementation of JSON-RPC 2.0 protocol
//! with support for batching, streaming, and MCP-specific extensions.

use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::Value;
use std::fmt;

use crate::types::RequestId;

/// JSON-RPC version constant
pub const JSONRPC_VERSION: &str = "2.0";

/// JSON-RPC version type
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct JsonRpcVersion;

impl Serialize for JsonRpcVersion {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(JSONRPC_VERSION)
    }
}

impl<'de> Deserialize<'de> for JsonRpcVersion {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let version = String::deserialize(deserializer)?;
        if version == JSONRPC_VERSION {
            Ok(JsonRpcVersion)
        } else {
            Err(serde::de::Error::custom(format!(
                "Invalid JSON-RPC version: expected '{JSONRPC_VERSION}', got '{version}'"
            )))
        }
    }
}

/// JSON-RPC request message
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JsonRpcRequest {
    /// JSON-RPC version
    pub jsonrpc: JsonRpcVersion,
    /// Request method name
    pub method: String,
    /// Request parameters
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub params: Option<Value>,
    /// Request identifier
    pub id: RequestId,
}

/// JSON-RPC response payload - ensures mutual exclusion of result and error.
///
/// Per JSON-RPC 2.0 §5: a response object MUST contain `result` xor `error`,
/// never both, never neither. The custom `Deserialize` impl enforces this:
/// `{}` (neither) and `{ "result": ..., "error": ... }` (both) both fail with
/// a clear, single-line error rather than serde's "missing field `result`"
/// or silently dropping `error` (which the previous `#[serde(untagged)]`
/// implementation would do — first variant wins).
#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub enum JsonRpcResponsePayload {
    /// Successful response with result
    Success {
        /// Response result
        result: Value,
    },
    /// Error response
    Error {
        /// Response error
        error: JsonRpcError,
    },
}

impl<'de> Deserialize<'de> for JsonRpcResponsePayload {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let mut object = serde_json::Map::<String, Value>::deserialize(deserializer)?;
        let result_present = object.contains_key("result");
        let error_present = object.contains_key("error");

        match (result_present, error_present) {
            (true, false) => Ok(Self::Success {
                result: object.remove("result").unwrap_or(Value::Null),
            }),
            (false, true) => {
                let error_value = object.remove("error").unwrap_or(Value::Null);
                let error =
                    JsonRpcError::deserialize(error_value).map_err(serde::de::Error::custom)?;
                Ok(Self::Error { error })
            }
            (true, true) => Err(serde::de::Error::custom(
                "JSON-RPC response must contain exactly one of `result` or `error`, not both",
            )),
            (false, false) => Err(serde::de::Error::custom(
                "JSON-RPC response must contain exactly one of `result` or `error`",
            )),
        }
    }
}

/// JSON-RPC response message
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JsonRpcResponse {
    /// JSON-RPC version
    pub jsonrpc: JsonRpcVersion,
    /// Response payload (either result or error, never both)
    #[serde(flatten)]
    pub payload: JsonRpcResponsePayload,
    /// Request identifier (required except for parse errors)
    pub id: ResponseId,
}

/// Response ID - handles the special case where parse errors have null ID
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ResponseId(pub Option<RequestId>);

impl ResponseId {
    /// Create a response ID for a normal response
    pub fn from_request(id: RequestId) -> Self {
        Self(Some(id))
    }

    /// Create a null response ID for parse errors
    pub fn null() -> Self {
        Self(None)
    }

    /// Get the request ID if present
    pub fn as_request_id(&self) -> Option<&RequestId> {
        self.0.as_ref()
    }

    /// Check if this is a null ID (parse error)
    pub fn is_null(&self) -> bool {
        self.0.is_none()
    }
}

/// JSON-RPC notification message (no response expected)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JsonRpcNotification {
    /// JSON-RPC version
    pub jsonrpc: JsonRpcVersion,
    /// Notification method name
    pub method: String,
    /// Notification parameters
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub params: Option<Value>,
}

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

impl JsonRpcError {
    /// JSON-RPC 2.0 §5.1 reserves -32768..-32000 (the "Server error" range goes from
    /// -32099 to -32000 inclusive). Custom server errors must fall in that range;
    /// other application-level errors should be conveyed via `data`, not via codes
    /// outside the reserved space, to avoid colliding with future spec assignments.
    const SERVER_ERROR_RANGE: std::ops::RangeInclusive<i32> = -32099..=-32000;
    /// Reserved codes already standardized (parse/invalid request/method not
    /// found/invalid params/internal error). Outside the server-error range but
    /// always allowed because they're spec-mandated.
    const STANDARD_CODES: &'static [i32] = &[-32700, -32600, -32601, -32602, -32603];

    /// Create a new JSON-RPC error.
    ///
    /// Custom application errors should use codes in `-32099..=-32000` (the server
    /// error range). Codes outside that range and outside the well-known standard
    /// codes are accepted but logged at WARN — they may collide with future spec
    /// assignments. Use [`Self::with_validated_code`] to fail-fast instead.
    pub fn new(code: i32, message: impl Into<String>) -> Self {
        if !Self::is_valid_code(code) {
            tracing::warn!(
                code,
                "JSON-RPC error code outside reserved server-error range -32099..=-32000 \
                 and not a standardized JSON-RPC 2.0 code; this risks colliding with \
                 future spec assignments"
            );
        }
        Self {
            code,
            message: Self::cap_message(message.into()),
            data: None,
        }
    }

    /// Like [`Self::new`] but returns `Err` instead of warning when the code is out
    /// of the JSON-RPC 2.0 reserved or standardized ranges.
    pub fn with_validated_code(
        code: i32,
        message: impl Into<String>,
    ) -> Result<Self, &'static str> {
        if !Self::is_valid_code(code) {
            return Err(
                "JSON-RPC error code must be a standardized code or in the -32099..=-32000 server-error range",
            );
        }
        Ok(Self {
            code,
            message: Self::cap_message(message.into()),
            data: None,
        })
    }

    fn is_valid_code(code: i32) -> bool {
        Self::SERVER_ERROR_RANGE.contains(&code) || Self::STANDARD_CODES.contains(&code)
    }

    /// Soft cap on the on-wire `message` field, in bytes.
    ///
    /// JSON-RPC error messages routinely include user-supplied `details` (see
    /// `invalid_params`, `parse_error_with_details`, `invalid_request_with_reason`).
    /// A naive caller passing a multi-MiB payload would amplify the response
    /// and risk leaking the offending input back to a third party. We truncate
    /// at a UTF-8 char boundary and append a `…[truncated, N bytes elided]`
    /// suffix; the `data` field carries the same cap.
    const MESSAGE_BYTE_CAP: usize = 1024;

    /// Truncate `s` at a UTF-8 char boundary, preserving the first
    /// `MESSAGE_BYTE_CAP` bytes and appending an ellipsis with the elision
    /// count. Cheap no-op for short messages.
    fn cap_message(s: String) -> String {
        if s.len() <= Self::MESSAGE_BYTE_CAP {
            return s;
        }
        let mut end = Self::MESSAGE_BYTE_CAP;
        while end > 0 && !s.is_char_boundary(end) {
            end -= 1;
        }
        let elided = s.len() - end;
        let mut out = String::with_capacity(end + 32);
        out.push_str(&s[..end]);
        out.push_str(&format!("…[truncated, {elided} bytes elided]"));
        out
    }

    /// Same cap applied to a `data` payload's string fields.
    fn cap_data_value(data: Value) -> Value {
        match data {
            Value::String(s) => Value::String(Self::cap_message(s)),
            Value::Array(values) => {
                Value::Array(values.into_iter().map(Self::cap_data_value).collect())
            }
            Value::Object(map) => {
                let capped = map
                    .into_iter()
                    .map(|(k, v)| (k, Self::cap_data_value(v)))
                    .collect();
                Value::Object(capped)
            }
            other => other,
        }
    }

    /// Create a new JSON-RPC error with additional data
    pub fn with_data(code: i32, message: impl Into<String>, data: Value) -> Self {
        if !Self::is_valid_code(code) {
            tracing::warn!(
                code,
                "JSON-RPC error code outside reserved server-error range -32099..=-32000"
            );
        }
        Self {
            code,
            message: Self::cap_message(message.into()),
            data: Some(Self::cap_data_value(data)),
        }
    }

    /// Create a parse error (-32700)
    pub fn parse_error() -> Self {
        Self::new(-32700, "Parse error")
    }

    /// Create a parse error with details
    pub fn parse_error_with_details(details: impl Into<String>) -> Self {
        Self::with_data(
            -32700,
            "Parse error",
            serde_json::json!({ "details": details.into() }),
        )
    }

    /// Create an invalid request error (-32600)
    pub fn invalid_request() -> Self {
        Self::new(-32600, "Invalid Request")
    }

    /// Create an invalid request error with reason
    pub fn invalid_request_with_reason(reason: impl Into<String>) -> Self {
        Self::with_data(
            -32600,
            "Invalid Request",
            serde_json::json!({ "reason": reason.into() }),
        )
    }

    /// Create a method not found error (-32601)
    pub fn method_not_found(method: &str) -> Self {
        Self::new(-32601, format!("Method not found: {method}"))
    }

    /// Create an invalid params error (-32602)
    pub fn invalid_params(details: &str) -> Self {
        Self::new(-32602, format!("Invalid params: {details}"))
    }

    /// Create an internal error (-32603)
    pub fn internal_error(details: &str) -> Self {
        Self::new(-32603, format!("Internal error: {details}"))
    }

    /// Check if this is a parse error
    pub fn is_parse_error(&self) -> bool {
        self.code == -32700
    }

    /// Check if this is an invalid request error
    pub fn is_invalid_request(&self) -> bool {
        self.code == -32600
    }

    /// Check if this is a method-not-found error (-32601)
    pub fn is_method_not_found(&self) -> bool {
        self.code == -32601
    }

    /// Check if this is an invalid-params error (-32602)
    pub fn is_invalid_params(&self) -> bool {
        self.code == -32602
    }

    /// Check if this is an internal error (-32603)
    pub fn is_internal_error(&self) -> bool {
        self.code == -32603
    }

    /// Check if this code falls in JSON-RPC 2.0's implementation-defined
    /// server-error range `-32099..=-32000` (§5.1).
    pub fn is_server_error(&self) -> bool {
        (-32099..=-32000).contains(&self.code)
    }

    /// Get the error code
    pub fn code(&self) -> i32 {
        self.code
    }

    /// Classify this error against the JSON-RPC standard error enum.
    /// Returns `None` for codes outside the JSON-RPC reserved range.
    pub fn standard_kind(&self) -> Option<JsonRpcErrorCode> {
        match self.code {
            -32700 => Some(JsonRpcErrorCode::ParseError),
            -32600 => Some(JsonRpcErrorCode::InvalidRequest),
            -32601 => Some(JsonRpcErrorCode::MethodNotFound),
            -32602 => Some(JsonRpcErrorCode::InvalidParams),
            -32603 => Some(JsonRpcErrorCode::InternalError),
            _ => None,
        }
    }
}

/// Standard JSON-RPC error codes
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum JsonRpcErrorCode {
    /// Parse error (-32700)
    ParseError,
    /// Invalid request (-32600)
    InvalidRequest,
    /// Method not found (-32601)
    MethodNotFound,
    /// Invalid params (-32602)
    InvalidParams,
    /// Internal error (-32603)
    InternalError,
    /// Application-defined error
    ApplicationError(i32),
}

impl JsonRpcErrorCode {
    /// Get the numeric error code
    pub fn code(&self) -> i32 {
        match self {
            Self::ParseError => -32700,
            Self::InvalidRequest => -32600,
            Self::MethodNotFound => -32601,
            Self::InvalidParams => -32602,
            Self::InternalError => -32603,
            Self::ApplicationError(code) => *code,
        }
    }

    /// Get the standard error message
    pub fn message(&self) -> &'static str {
        match self {
            Self::ParseError => "Parse error",
            Self::InvalidRequest => "Invalid Request",
            Self::MethodNotFound => "Method not found",
            Self::InvalidParams => "Invalid params",
            Self::InternalError => "Internal error",
            Self::ApplicationError(_) => "Application error",
        }
    }
}

impl fmt::Display for JsonRpcErrorCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} ({})", self.message(), self.code())
    }
}

impl From<JsonRpcErrorCode> for JsonRpcError {
    fn from(code: JsonRpcErrorCode) -> Self {
        Self {
            code: code.code(),
            message: code.message().to_string(),
            data: None,
        }
    }
}

impl From<i32> for JsonRpcErrorCode {
    fn from(code: i32) -> Self {
        match code {
            -32700 => Self::ParseError,
            -32600 => Self::InvalidRequest,
            -32601 => Self::MethodNotFound,
            -32602 => Self::InvalidParams,
            -32603 => Self::InternalError,
            other => Self::ApplicationError(other),
        }
    }
}

/// JSON-RPC message type (union of request, response, notification)
///
/// Per the current MCP specification, batch operations are not supported.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum JsonRpcMessage {
    /// Request message
    Request(JsonRpcRequest),
    /// Response message
    Response(JsonRpcResponse),
    /// Notification message
    Notification(JsonRpcNotification),
}

impl JsonRpcRequest {
    /// Create a new JSON-RPC request
    pub fn new(method: String, params: Option<Value>, id: RequestId) -> Self {
        Self {
            jsonrpc: JsonRpcVersion,
            method,
            params,
            id,
        }
    }

    /// Create a request with no parameters
    pub fn without_params(method: String, id: RequestId) -> Self {
        Self::new(method, None, id)
    }

    /// Create a request with parameters
    pub fn with_params<P: Serialize>(
        method: String,
        params: P,
        id: RequestId,
    ) -> Result<Self, serde_json::Error> {
        let params_value = serde_json::to_value(params)?;
        Ok(Self::new(method, Some(params_value), id))
    }
}

impl JsonRpcResponse {
    /// Create a successful response
    pub fn success(result: Value, id: RequestId) -> Self {
        Self {
            jsonrpc: JsonRpcVersion,
            payload: JsonRpcResponsePayload::Success { result },
            id: ResponseId::from_request(id),
        }
    }

    /// Create an error response with request ID
    pub fn error_response(error: JsonRpcError, id: RequestId) -> Self {
        Self {
            jsonrpc: JsonRpcVersion,
            payload: JsonRpcResponsePayload::Error { error },
            id: ResponseId::from_request(id),
        }
    }

    /// Create a parse error response (id is null)
    pub fn parse_error(message: Option<String>) -> Self {
        let error = JsonRpcError {
            code: JsonRpcErrorCode::ParseError.code(),
            message: message.unwrap_or_else(|| JsonRpcErrorCode::ParseError.message().to_string()),
            data: None,
        };
        Self {
            jsonrpc: JsonRpcVersion,
            payload: JsonRpcResponsePayload::Error { error },
            id: ResponseId::null(),
        }
    }

    /// Check if this is a successful response
    pub fn is_success(&self) -> bool {
        matches!(self.payload, JsonRpcResponsePayload::Success { .. })
    }

    /// Check if this is an error response
    pub fn is_error(&self) -> bool {
        matches!(self.payload, JsonRpcResponsePayload::Error { .. })
    }

    /// Get the result if this is a success response
    pub fn result(&self) -> Option<&Value> {
        match &self.payload {
            JsonRpcResponsePayload::Success { result } => Some(result),
            JsonRpcResponsePayload::Error { .. } => None,
        }
    }

    /// Get the error if this is an error response
    pub fn error(&self) -> Option<&JsonRpcError> {
        match &self.payload {
            JsonRpcResponsePayload::Success { .. } => None,
            JsonRpcResponsePayload::Error { error } => Some(error),
        }
    }

    /// Get the request ID if this is not a parse error
    pub fn request_id(&self) -> Option<&RequestId> {
        self.id.as_request_id()
    }

    /// Check if this response is for a parse error (has null ID)
    pub fn is_parse_error(&self) -> bool {
        self.id.is_null()
    }

    /// Get mutable reference to result if this is a success response
    pub fn result_mut(&mut self) -> Option<&mut Value> {
        match &mut self.payload {
            JsonRpcResponsePayload::Success { result } => Some(result),
            JsonRpcResponsePayload::Error { .. } => None,
        }
    }

    /// Get mutable reference to error if this is an error response
    pub fn error_mut(&mut self) -> Option<&mut JsonRpcError> {
        match &mut self.payload {
            JsonRpcResponsePayload::Success { .. } => None,
            JsonRpcResponsePayload::Error { error } => Some(error),
        }
    }

    /// Set the result for this response (converts to success response)
    pub fn set_result(&mut self, result: Value) {
        self.payload = JsonRpcResponsePayload::Success { result };
    }

    /// Set the error for this response (converts to error response)
    pub fn set_error(&mut self, error: JsonRpcError) {
        self.payload = JsonRpcResponsePayload::Error { error };
    }
}

impl JsonRpcNotification {
    /// Create a new JSON-RPC notification
    pub fn new(method: String, params: Option<Value>) -> Self {
        Self {
            jsonrpc: JsonRpcVersion,
            method,
            params,
        }
    }

    /// Create a notification with no parameters
    pub fn without_params(method: String) -> Self {
        Self::new(method, None)
    }

    /// Create a notification with parameters
    pub fn with_params<P: Serialize>(method: String, params: P) -> Result<Self, serde_json::Error> {
        let params_value = serde_json::to_value(params)?;
        Ok(Self::new(method, Some(params_value)))
    }
}

/// Utility functions for JSON-RPC message handling
pub mod utils {
    use super::*;

    /// Error returned by [`parse_message_typed`] for the cases the untagged
    /// `JsonRpcMessage` enum can't distinguish on its own.
    ///
    /// `JsonRpcMessage` is `#[serde(untagged)]` over Request/Response/Notification.
    /// A top-level JSON array (a JSON-RPC §7 batch) fails serde's variant
    /// match with a generic "data did not match any variant" diagnostic;
    /// MCP 2025-11-25 deprecates batches, so callers want to respond with a
    /// clear `-32600 Invalid Request` rather than echoing serde's text.
    #[derive(Debug)]
    pub enum ParseMessageError {
        /// Top-level JSON array (deprecated batch shape).
        BatchUnsupported,
        /// Anything else (parse error, unknown variant, etc.).
        Json(serde_json::Error),
    }

    impl core::fmt::Display for ParseMessageError {
        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            match self {
                Self::BatchUnsupported => {
                    f.write_str("JSON-RPC batches are not supported in MCP 2025-11-25")
                }
                Self::Json(e) => write!(f, "{e}"),
            }
        }
    }

    impl std::error::Error for ParseMessageError {
        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
            match self {
                Self::BatchUnsupported => None,
                Self::Json(e) => Some(e),
            }
        }
    }

    impl From<serde_json::Error> for ParseMessageError {
        fn from(e: serde_json::Error) -> Self {
            Self::Json(e)
        }
    }

    /// Parse a JSON-RPC message from a string.
    ///
    /// Kept on the original signature for backwards compatibility — callers
    /// who need to distinguish "batch not supported" from generic parse
    /// errors should use [`parse_message_typed`].
    pub fn parse_message(json: &str) -> Result<JsonRpcMessage, serde_json::Error> {
        serde_json::from_str(json)
    }

    /// Parse a JSON-RPC message and surface batch arrays as a distinct error.
    ///
    /// Returns `ParseMessageError::BatchUnsupported` when the input's first
    /// non-whitespace byte is `[` (a JSON array). Otherwise behaves like
    /// [`parse_message`]. Callers can map the typed error to a JSON-RPC
    /// `-32600 Invalid Request` response with the stable message.
    pub fn parse_message_typed(json: &str) -> Result<JsonRpcMessage, ParseMessageError> {
        if json.trim_start().as_bytes().first() == Some(&b'[') {
            return Err(ParseMessageError::BatchUnsupported);
        }
        Ok(serde_json::from_str(json)?)
    }

    /// Serialize a JSON-RPC message to a string
    pub fn serialize_message(message: &JsonRpcMessage) -> Result<String, serde_json::Error> {
        serde_json::to_string(message)
    }

    /// Extract the method name from a JSON-RPC message string
    pub fn extract_method(json: &str) -> Option<String> {
        // Simple regex-free method extraction for performance
        if let Ok(value) = serde_json::from_str::<serde_json::Value>(json)
            && let Some(method) = value.get("method")
        {
            return method.as_str().map(String::from);
        }
        None
    }
}

/// HTTP boundary types for lenient JSON-RPC parsing
///
/// These types are designed for parsing JSON-RPC messages at HTTP boundaries where
/// the input may not be strictly compliant. They accept any valid JSON structure
/// and can be converted to the canonical types after validation.
///
/// # Usage
///
/// ```rust
/// use turbomcp_protocol::jsonrpc::http::{HttpJsonRpcRequest, HttpJsonRpcResponse};
/// use turbomcp_protocol::jsonrpc::JsonRpcError;
///
/// // Parse lenient request
/// let raw_json = r#"{"jsonrpc":"2.0","method":"test","id":1}"#;
/// let request: HttpJsonRpcRequest = serde_json::from_str(raw_json).unwrap();
///
/// // Validate and use
/// if request.jsonrpc != "2.0" {
///     // Return error with the id we managed to extract
/// }
/// ```
pub mod http {
    use serde::{Deserialize, Serialize};
    use serde_json::Value;

    /// Lenient JSON-RPC request for HTTP boundary parsing
    ///
    /// This type accepts any string for `jsonrpc` and any JSON value for `id`,
    /// allowing proper error handling when clients send non-compliant requests.
    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct HttpJsonRpcRequest {
        /// JSON-RPC version (should be "2.0" but accepts any string for error handling)
        pub jsonrpc: String,
        /// Request ID (can be string, number, or null)
        #[serde(default)]
        pub id: Option<Value>,
        /// Method name
        pub method: String,
        /// Method parameters
        #[serde(default)]
        pub params: Option<Value>,
    }

    impl HttpJsonRpcRequest {
        /// Check if this is a valid JSON-RPC 2.0 request
        pub fn is_valid(&self) -> bool {
            self.jsonrpc == "2.0" && !self.method.is_empty()
        }

        /// Check if this is a notification (no id)
        pub fn is_notification(&self) -> bool {
            self.id.is_none()
        }

        /// Get the id as a string if it's a string, or convert number to string
        pub fn id_string(&self) -> Option<String> {
            self.id.as_ref().map(|v| match v {
                Value::String(s) => s.clone(),
                Value::Number(n) => n.to_string(),
                _ => v.to_string(),
            })
        }
    }

    /// Lenient JSON-RPC response for HTTP boundary
    ///
    /// Uses separate result/error fields for compatibility with various JSON-RPC
    /// implementations.
    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct HttpJsonRpcResponse {
        /// JSON-RPC version
        pub jsonrpc: String,
        /// Response ID
        #[serde(default)]
        pub id: Option<Value>,
        /// Success result
        #[serde(skip_serializing_if = "Option::is_none")]
        pub result: Option<Value>,
        /// Error information
        #[serde(skip_serializing_if = "Option::is_none")]
        pub error: Option<super::JsonRpcError>,
    }

    impl HttpJsonRpcResponse {
        /// Create a success response
        pub fn success(id: Option<Value>, result: Value) -> Self {
            Self {
                jsonrpc: "2.0".to_string(),
                id,
                result: Some(result),
                error: None,
            }
        }

        /// Create an error response
        pub fn error(id: Option<Value>, error: super::JsonRpcError) -> Self {
            Self {
                jsonrpc: "2.0".to_string(),
                id,
                result: None,
                error: Some(error),
            }
        }

        /// Create an error response from error code
        pub fn error_from_code(id: Option<Value>, code: i32, message: impl Into<String>) -> Self {
            Self::error(id, super::JsonRpcError::new(code, message))
        }

        /// Create an invalid request error response
        pub fn invalid_request(id: Option<Value>, reason: impl Into<String>) -> Self {
            Self::error(id, super::JsonRpcError::invalid_request_with_reason(reason))
        }

        /// Create a parse error response (id is always null for parse errors)
        pub fn parse_error(details: Option<String>) -> Self {
            Self::error(
                None,
                details
                    .map(super::JsonRpcError::parse_error_with_details)
                    .unwrap_or_else(super::JsonRpcError::parse_error),
            )
        }

        /// Create an internal error response
        pub fn internal_error(id: Option<Value>, details: &str) -> Self {
            Self::error(id, super::JsonRpcError::internal_error(details))
        }

        /// Create a method not found error response
        pub fn method_not_found(id: Option<Value>, method: &str) -> Self {
            Self::error(id, super::JsonRpcError::method_not_found(method))
        }

        /// Check if this is an error response
        pub fn is_error(&self) -> bool {
            self.error.is_some()
        }

        /// Check if this is a success response
        pub fn is_success(&self) -> bool {
            self.result.is_some() && self.error.is_none()
        }
    }

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

        #[test]
        fn test_http_request_parsing() {
            let json = r#"{"jsonrpc":"2.0","method":"test","id":1,"params":{"key":"value"}}"#;
            let request: HttpJsonRpcRequest = serde_json::from_str(json).unwrap();
            assert!(request.is_valid());
            assert!(!request.is_notification());
            assert_eq!(request.method, "test");
        }

        #[test]
        fn test_http_request_invalid_version() {
            let json = r#"{"jsonrpc":"1.0","method":"test","id":1}"#;
            let request: HttpJsonRpcRequest = serde_json::from_str(json).unwrap();
            assert!(!request.is_valid());
        }

        #[test]
        fn test_http_response_success() {
            let response = HttpJsonRpcResponse::success(
                Some(Value::Number(1.into())),
                serde_json::json!({"result": "ok"}),
            );
            assert!(response.is_success());
            assert!(!response.is_error());
        }

        #[test]
        fn test_http_response_error() {
            let response = HttpJsonRpcResponse::invalid_request(
                Some(Value::String("req-1".into())),
                "jsonrpc must be 2.0",
            );
            assert!(!response.is_success());
            assert!(response.is_error());
        }

        #[test]
        fn test_http_response_serialization() {
            let response = HttpJsonRpcResponse::success(
                Some(Value::Number(1.into())),
                serde_json::json!({"data": "test"}),
            );
            let json = serde_json::to_string(&response).unwrap();
            assert!(json.contains(r#""jsonrpc":"2.0""#));
            assert!(json.contains(r#""result""#));
            assert!(!json.contains(r#""error""#));
        }
    }
}

// Additional integration-style tests live in `jsonrpc/tests.rs`. The split
// originated from a file refactor; both modules cover distinct cases (e.g.
// `tests.rs` exercises wire-shape regressions like `id:null` for parse errors)
// so neither should be dropped until they are merged.
#[cfg(test)]
#[path = "jsonrpc/tests.rs"]
mod extended_tests;

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

    #[test]
    fn test_jsonrpc_version() {
        let version = JsonRpcVersion;
        let json = serde_json::to_string(&version).unwrap();
        assert_eq!(json, "\"2.0\"");

        let parsed: JsonRpcVersion = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, version);
    }

    #[test]
    fn test_request_creation() {
        let request = JsonRpcRequest::new(
            "test_method".to_string(),
            Some(json!({"key": "value"})),
            RequestId::String("test-id".to_string()),
        );

        assert_eq!(request.method, "test_method");
        assert!(request.params.is_some());
    }

    #[test]
    fn test_response_creation() {
        let response = JsonRpcResponse::success(
            json!({"result": "success"}),
            RequestId::String("test-id".to_string()),
        );

        assert!(response.is_success());
        assert!(!response.is_error());
        assert!(response.result().is_some());
        assert!(response.error().is_none());
        assert!(!response.is_parse_error());
    }

    #[test]
    fn test_error_response() {
        let error = JsonRpcError::from(JsonRpcErrorCode::MethodNotFound);
        let response =
            JsonRpcResponse::error_response(error, RequestId::String("test-id".to_string()));

        assert!(!response.is_success());
        assert!(response.is_error());
        assert!(response.result().is_none());
        assert!(response.error().is_some());
        assert!(!response.is_parse_error());
    }

    #[test]
    fn test_response_payload_accepts_null_result() {
        let raw = r#"{"jsonrpc":"2.0","id":1,"result":null}"#;
        let response: JsonRpcResponse = serde_json::from_str(raw).unwrap();
        assert!(response.is_success());
        assert_eq!(response.result(), Some(&Value::Null));
    }

    #[test]
    fn test_parse_error_response() {
        let response = JsonRpcResponse::parse_error(Some("Invalid JSON".to_string()));

        assert!(!response.is_success());
        assert!(response.is_error());
        assert!(response.result().is_none());
        assert!(response.error().is_some());
        assert!(response.is_parse_error());
        assert!(response.request_id().is_none());

        // Verify the error details
        let error = response.error().unwrap();
        assert_eq!(error.code, JsonRpcErrorCode::ParseError.code());
        assert_eq!(error.message, "Invalid JSON");
    }

    #[test]
    fn test_notification() {
        let notification = JsonRpcNotification::without_params("test_notification".to_string());
        assert_eq!(notification.method, "test_notification");
        assert!(notification.params.is_none());
    }

    #[test]
    fn test_serialization() {
        let request = JsonRpcRequest::new(
            "test_method".to_string(),
            Some(json!({"param": "value"})),
            RequestId::String("123".to_string()),
        );

        let json = serde_json::to_string(&request).unwrap();
        let parsed: JsonRpcRequest = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed.method, request.method);
        assert_eq!(parsed.params, request.params);
    }

    #[test]
    fn test_utils() {
        let json = r#"{"jsonrpc":"2.0","method":"test","id":"123"}"#;
        assert_eq!(utils::extract_method(json), Some("test".to_string()));
    }

    #[test]
    fn test_error_codes() {
        let parse_error = JsonRpcErrorCode::ParseError;
        assert_eq!(parse_error.code(), -32700);
        assert_eq!(parse_error.message(), "Parse error");

        let app_error = JsonRpcErrorCode::ApplicationError(-32001);
        assert_eq!(app_error.code(), -32001);
    }
}