turbomcp-protocol 3.0.9

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
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
//! # Protocol Validation
//!
//! This module provides comprehensive validation for MCP protocol messages,
//! ensuring data integrity and specification compliance.

use regex::Regex;
use serde_json::Value;
use std::collections::{HashMap, HashSet};
use std::sync::LazyLock;

use crate::jsonrpc::{JsonRpcNotification, JsonRpcRequest, JsonRpcResponse};
use crate::types::*;

/// Cached regex for URI validation (compiled once)
static URI_REGEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^[a-zA-Z][a-zA-Z0-9+.-]*:").expect("Invalid URI regex pattern"));

/// Cached regex for method name validation (compiled once)
static METHOD_NAME_REGEX: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^[a-zA-Z][a-zA-Z0-9_/]*$").expect("Invalid method name regex pattern")
});

/// Protocol message validator
#[derive(Debug, Clone)]
pub struct ProtocolValidator {
    /// Validation rules
    rules: ValidationRules,
    /// Strict validation mode
    strict_mode: bool,
}

/// Validation rules configuration
#[derive(Debug, Clone)]
pub struct ValidationRules {
    /// Maximum message size in bytes
    pub max_message_size: usize,
    /// Maximum batch size
    pub max_batch_size: usize,
    /// Maximum string length
    pub max_string_length: usize,
    /// Maximum array length
    pub max_array_length: usize,
    /// Maximum object depth
    pub max_object_depth: usize,
    /// Required fields per message type
    pub required_fields: HashMap<String, HashSet<String>>,
}

impl ValidationRules {
    /// Get the URI validation regex (cached globally)
    #[inline]
    pub fn uri_regex(&self) -> &Regex {
        &URI_REGEX
    }

    /// Get the method name validation regex (cached globally)
    #[inline]
    pub fn method_name_regex(&self) -> &Regex {
        &METHOD_NAME_REGEX
    }
}

/// Validation result
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ValidationResult {
    /// Validation passed
    Valid,
    /// Validation passed with warnings
    ValidWithWarnings(Vec<ValidationWarning>),
    /// Validation failed
    Invalid(Vec<ValidationError>),
}

/// Validation warning
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValidationWarning {
    /// Warning code
    pub code: String,
    /// Warning message
    pub message: String,
    /// Field path (if applicable)
    pub field_path: Option<String>,
}

/// Validation error
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValidationError {
    /// Error code
    pub code: String,
    /// Error message
    pub message: String,
    /// Field path (if applicable)
    pub field_path: Option<String>,
}

/// Validation context for tracking state during validation
#[derive(Debug, Clone)]
struct ValidationContext {
    /// Current field path
    path: Vec<String>,
    /// Current object depth
    depth: usize,
    /// Accumulated warnings
    warnings: Vec<ValidationWarning>,
    /// Accumulated errors
    errors: Vec<ValidationError>,
}

impl Default for ValidationRules {
    fn default() -> Self {
        let mut required_fields = HashMap::new();

        // JSON-RPC required fields
        required_fields.insert(
            "request".to_string(),
            ["jsonrpc", "method", "id"]
                .iter()
                .map(|s| s.to_string())
                .collect(),
        );
        required_fields.insert(
            "response".to_string(),
            ["jsonrpc", "id"].iter().map(|s| s.to_string()).collect(),
        );
        required_fields.insert(
            "notification".to_string(),
            ["jsonrpc", "method"]
                .iter()
                .map(|s| s.to_string())
                .collect(),
        );

        // MCP message required fields
        required_fields.insert(
            "initialize".to_string(),
            ["protocolVersion", "capabilities", "clientInfo"]
                .iter()
                .map(|s| s.to_string())
                .collect(),
        );
        required_fields.insert(
            "tool".to_string(),
            ["name", "inputSchema"]
                .iter()
                .map(|s| s.to_string())
                .collect(),
        );
        required_fields.insert(
            "prompt".to_string(),
            ["name"].iter().map(|s| s.to_string()).collect(),
        );
        required_fields.insert(
            "resource".to_string(),
            ["uri", "name"].iter().map(|s| s.to_string()).collect(),
        );

        Self {
            max_message_size: 10 * 1024 * 1024, // 10MB
            max_batch_size: 100,
            max_string_length: 1024 * 1024, // 1MB
            max_array_length: 10000,
            max_object_depth: 32,
            required_fields,
        }
    }
}

impl ProtocolValidator {
    /// Create a new validator with default rules
    pub fn new() -> Self {
        Self {
            rules: ValidationRules::default(),
            strict_mode: false,
        }
    }

    /// Enable strict validation mode
    pub fn with_strict_mode(mut self) -> Self {
        self.strict_mode = true;
        self
    }

    /// Set custom validation rules
    pub fn with_rules(mut self, rules: ValidationRules) -> Self {
        self.rules = rules;
        self
    }

    /// Validate a JSON-RPC request
    pub fn validate_request(&self, request: &JsonRpcRequest) -> ValidationResult {
        let mut ctx = ValidationContext::new();

        // Validate JSON-RPC structure (includes method name validation)
        self.validate_jsonrpc_request(request, &mut ctx);

        // Validate parameters based on method
        if let Some(params) = &request.params {
            self.validate_method_params(&request.method, params, &mut ctx);
        }

        ctx.into_result()
    }

    /// Validate a JSON-RPC response
    pub fn validate_response(&self, response: &JsonRpcResponse) -> ValidationResult {
        let mut ctx = ValidationContext::new();

        // Validate JSON-RPC structure
        self.validate_jsonrpc_response(response, &mut ctx);

        // Ensure either result or error is present (but not both)
        // Note: This validation is now enforced at the type level with JsonRpcResponsePayload enum
        // But we still validate for completeness
        match (response.result().is_some(), response.error().is_some()) {
            (true, true) => {
                ctx.add_error(
                    "RESPONSE_BOTH_RESULT_AND_ERROR",
                    "Response cannot have both result and error".to_string(),
                    None,
                );
            }
            (false, false) => {
                ctx.add_error(
                    "RESPONSE_MISSING_RESULT_OR_ERROR",
                    "Response must have either result or error".to_string(),
                    None,
                );
            }
            _ => {} // Valid
        }

        ctx.into_result()
    }

    /// Validate a JSON-RPC notification
    pub fn validate_notification(&self, notification: &JsonRpcNotification) -> ValidationResult {
        let mut ctx = ValidationContext::new();

        // Validate JSON-RPC structure
        self.validate_jsonrpc_notification(notification, &mut ctx);

        // Validate method name
        self.validate_method_name(&notification.method, &mut ctx);

        // Validate parameters based on method
        if let Some(params) = &notification.params {
            self.validate_method_params(&notification.method, params, &mut ctx);
        }

        ctx.into_result()
    }

    /// Validate MCP protocol types
    pub fn validate_tool(&self, tool: &Tool) -> ValidationResult {
        let mut ctx = ValidationContext::new();

        // Validate tool name
        if tool.name.is_empty() {
            ctx.add_error(
                "TOOL_EMPTY_NAME",
                "Tool name cannot be empty".to_string(),
                Some("name".to_string()),
            );
        }

        if tool.name.len() > self.rules.max_string_length {
            ctx.add_error(
                "TOOL_NAME_TOO_LONG",
                format!(
                    "Tool name exceeds maximum length of {}",
                    self.rules.max_string_length
                ),
                Some("name".to_string()),
            );
        }

        // Validate input schema
        self.validate_tool_input(&tool.input_schema, &mut ctx);

        ctx.into_result()
    }

    /// Validate a prompt
    pub fn validate_prompt(&self, prompt: &Prompt) -> ValidationResult {
        let mut ctx = ValidationContext::new();

        // Validate prompt name
        if prompt.name.is_empty() {
            ctx.add_error(
                "PROMPT_EMPTY_NAME",
                "Prompt name cannot be empty".to_string(),
                Some("name".to_string()),
            );
        }

        // Validate arguments if present
        if let Some(arguments) = &prompt.arguments
            && arguments.len() > self.rules.max_array_length
        {
            ctx.add_error(
                "PROMPT_TOO_MANY_ARGS",
                format!(
                    "Prompt has too many arguments (max: {})",
                    self.rules.max_array_length
                ),
                Some("arguments".to_string()),
            );
        }

        ctx.into_result()
    }

    /// Validate a resource
    pub fn validate_resource(&self, resource: &Resource) -> ValidationResult {
        let mut ctx = ValidationContext::new();

        // Validate URI length (defense-in-depth before regex)
        if resource.uri.len() > self.rules.max_string_length {
            ctx.add_error(
                "RESOURCE_URI_TOO_LONG",
                format!(
                    "Resource URI exceeds maximum length of {}",
                    self.rules.max_string_length
                ),
                Some("uri".to_string()),
            );
        }

        // Validate URI format
        if !self.rules.uri_regex().is_match(&resource.uri) {
            ctx.add_error(
                "RESOURCE_INVALID_URI",
                format!("Invalid URI format: {}", resource.uri),
                Some("uri".to_string()),
            );
        }

        // Validate name
        if resource.name.is_empty() {
            ctx.add_error(
                "RESOURCE_EMPTY_NAME",
                "Resource name cannot be empty".to_string(),
                Some("name".to_string()),
            );
        }

        ctx.into_result()
    }

    /// Validate initialization request
    pub fn validate_initialize_request(&self, request: &InitializeRequest) -> ValidationResult {
        let mut ctx = ValidationContext::new();

        // Validate protocol version
        if !crate::SUPPORTED_VERSIONS.contains(&request.protocol_version.as_str()) {
            ctx.add_warning(
                "UNSUPPORTED_PROTOCOL_VERSION",
                format!(
                    "Protocol version {} is not officially supported",
                    request.protocol_version
                ),
                Some("protocolVersion".to_string()),
            );
        }

        // Validate client info
        if request.client_info.name.is_empty() {
            ctx.add_error(
                "EMPTY_CLIENT_NAME",
                "Client name cannot be empty".to_string(),
                Some("clientInfo.name".to_string()),
            );
        }

        if request.client_info.version.is_empty() {
            ctx.add_error(
                "EMPTY_CLIENT_VERSION",
                "Client version cannot be empty".to_string(),
                Some("clientInfo.version".to_string()),
            );
        }

        ctx.into_result()
    }

    /// Validate model preferences (priority ranges must be 0.0-1.0)
    ///
    /// Per the current MCP schema, priority values must be in range [0.0, 1.0].
    pub fn validate_model_preferences(
        &self,
        prefs: &crate::types::ModelPreferences,
    ) -> ValidationResult {
        let mut ctx = ValidationContext::new();

        // Validate each priority field
        let priorities = [
            ("costPriority", prefs.cost_priority),
            ("speedPriority", prefs.speed_priority),
            ("intelligencePriority", prefs.intelligence_priority),
        ];

        for (name, value) in priorities {
            if let Some(v) = value
                && !(0.0..=1.0).contains(&v)
            {
                ctx.add_error(
                    "PRIORITY_OUT_OF_RANGE",
                    format!(
                        "{} must be between 0.0 and 1.0 (inclusive), got {}",
                        name, v
                    ),
                    Some(name.to_string()),
                );
            }
        }

        ctx.into_result()
    }

    /// Validate elicitation result (content required for 'accept' action)
    ///
    /// Per the current MCP schema, content is only present when action is `accept`.
    pub fn validate_elicit_result(&self, result: &crate::types::ElicitResult) -> ValidationResult {
        let mut ctx = ValidationContext::new();

        use crate::types::ElicitationAction;

        match result.action {
            ElicitationAction::Accept => {
                if result.content.is_none() {
                    ctx.add_error(
                        "MISSING_CONTENT_ON_ACCEPT",
                        "ElicitResult must have content when action is 'accept'".to_string(),
                        Some("content".to_string()),
                    );
                }
            }
            ElicitationAction::Decline | ElicitationAction::Cancel => {
                if result.content.is_some() {
                    ctx.add_warning(
                        "UNEXPECTED_CONTENT",
                        format!(
                            "Content should not be present when action is '{:?}'",
                            result.action
                        ),
                        Some("content".to_string()),
                    );
                }
            }
        }

        ctx.into_result()
    }

    /// Validate elicitation schema structure
    ///
    /// Per the current MCP spec, schemas must be flat objects with primitive properties only.
    pub fn validate_elicitation_schema(
        &self,
        schema: &crate::types::ElicitationSchema,
    ) -> ValidationResult {
        let mut ctx = ValidationContext::new();

        // Schema type must be "object" (schema.json:585)
        if schema.schema_type != "object" {
            ctx.add_error(
                "SCHEMA_NOT_OBJECT",
                format!(
                    "Elicitation schema type must be 'object', got '{}'",
                    schema.schema_type
                ),
                Some("type".to_string()),
            );
        }

        // Validate additionalProperties = false (flat constraint)
        if let Some(additional) = schema.additional_properties
            && additional
        {
            ctx.add_warning(
                "ADDITIONAL_PROPERTIES_NOT_RECOMMENDED",
                "Elicitation schemas should have additionalProperties=false for flat structure"
                    .to_string(),
                Some("additionalProperties".to_string()),
            );
        }

        // Validate properties
        for (key, prop) in &schema.properties {
            self.validate_primitive_schema(prop, &format!("properties.{}", key), &mut ctx);
        }

        ctx.into_result()
    }

    /// Validate primitive schema definition
    fn validate_primitive_schema(
        &self,
        schema: &crate::types::PrimitiveSchemaDefinition,
        field_path: &str,
        ctx: &mut ValidationContext,
    ) {
        use crate::types::PrimitiveSchemaDefinition;

        match schema {
            PrimitiveSchemaDefinition::String {
                enum_values,
                enum_names,
                format,
                ..
            } => {
                // Validate enum/enumNames length match (schema.json:679-708)
                if let (Some(values), Some(names)) = (enum_values, enum_names)
                    && values.len() != names.len()
                {
                    ctx.add_error(
                        "ENUM_NAMES_LENGTH_MISMATCH",
                        format!(
                            "enum and enumNames arrays must have equal length: {} vs {}",
                            values.len(),
                            names.len()
                        ),
                        Some(format!("{}.enumNames", field_path)),
                    );
                }

                // Validate format if present (schema.json:2244-2251)
                if let Some(fmt) = format {
                    let valid_formats = ["email", "uri", "date", "date-time"];
                    if !valid_formats.contains(&fmt.as_str()) {
                        ctx.add_warning(
                            "UNKNOWN_STRING_FORMAT",
                            format!(
                                "Unknown format '{}', expected one of: {:?}",
                                fmt, valid_formats
                            ),
                            Some(format!("{}.format", field_path)),
                        );
                    }
                }
            }
            PrimitiveSchemaDefinition::Number { .. }
            | PrimitiveSchemaDefinition::Integer { .. } => {
                // Number/Integer validation could go here
            }
            PrimitiveSchemaDefinition::Boolean { .. } => {
                // Boolean validation could go here
            }
        }
    }

    /// Validate string value against format constraints
    ///
    /// Validates email, uri, date, and date-time formats per the current MCP spec.
    pub fn validate_string_format(value: &str, format: &str) -> std::result::Result<(), String> {
        match format {
            "email" => {
                // RFC 5322 basic validation
                if !value.contains('@') || !value.contains('.') {
                    return Err(format!("Invalid email format: {}", value));
                }
                let parts: Vec<&str> = value.split('@').collect();
                if parts.len() != 2 || parts[0].is_empty() || parts[1].is_empty() {
                    return Err(format!("Invalid email format: {}", value));
                }
            }
            "uri" => {
                // Basic URI validation - must have a scheme
                if !value.contains("://") && !value.starts_with('/') {
                    return Err(format!("Invalid URI format: {}", value));
                }
            }
            "date" => {
                // ISO 8601 date format: YYYY-MM-DD
                let parts: Vec<&str> = value.split('-').collect();
                if parts.len() != 3 {
                    return Err("Date must be in ISO 8601 format (YYYY-MM-DD)".to_string());
                }
                if parts[0].len() != 4 || parts[1].len() != 2 || parts[2].len() != 2 {
                    return Err("Date must be in ISO 8601 format (YYYY-MM-DD)".to_string());
                }
                // Basic numeric check
                for part in parts {
                    if !part.chars().all(|c| c.is_ascii_digit()) {
                        return Err("Date components must be numeric".to_string());
                    }
                }
            }
            "date-time" => {
                // ISO 8601 datetime format: YYYY-MM-DDTHH:MM:SS[.sss][Z|±HH:MM]
                if !value.contains('T') {
                    return Err("DateTime must contain 'T' separator (ISO 8601 format)".to_string());
                }
                let parts: Vec<&str> = value.split('T').collect();
                if parts.len() != 2 {
                    return Err("DateTime must be in ISO 8601 format".to_string());
                }
                // Validate date part
                Self::validate_string_format(parts[0], "date")?;
                // Time part should have colons
                if !parts[1].contains(':') {
                    return Err("Time component must contain ':'".to_string());
                }
            }
            _ => {
                // Unknown formats don't fail validation (forward compatibility)
            }
        }
        Ok(())
    }

    // Private validation methods

    fn validate_jsonrpc_request(&self, request: &JsonRpcRequest, ctx: &mut ValidationContext) {
        // Validate JSON-RPC version (implicitly "2.0" via JsonRpcVersion type)
        // This is handled by type system during deserialization

        // Validate method name - check length first, then format
        if request.method.is_empty() {
            ctx.add_error(
                "EMPTY_METHOD_NAME",
                "Method name cannot be empty".to_string(),
                Some("method".to_string()),
            );
        } else if request.method.len() > self.rules.max_string_length {
            ctx.add_error(
                "METHOD_NAME_TOO_LONG",
                format!(
                    "Method name exceeds maximum length of {}",
                    self.rules.max_string_length
                ),
                Some("method".to_string()),
            );
        } else if !utils::is_valid_method_name(&request.method) {
            ctx.add_error(
                "INVALID_METHOD_NAME",
                format!("Invalid method name format: '{}'", request.method),
                Some("method".to_string()),
            );
        }

        // Validate parameters if present
        if let Some(ref params) = request.params {
            self.validate_parameters(params, ctx);
        }

        // Request ID is always present for requests (enforced by type system)
        // Validate ID format if needed
        self.validate_request_id(&request.id, ctx);
    }

    fn validate_jsonrpc_response(&self, response: &JsonRpcResponse, ctx: &mut ValidationContext) {
        // Validate JSON-RPC version (implicitly "2.0" via JsonRpcVersion type)
        // This is handled by type system during deserialization

        // Validate response has either result or error (enforced by type system)
        // Our JsonRpcResponsePayload enum ensures mutual exclusion

        // Validate response ID
        self.validate_response_id(&response.id, ctx);

        // Validate error if present
        if let Some(error) = response.error() {
            self.validate_jsonrpc_error(error, ctx);
        }

        // Validate result structure if present
        if let Some(result) = response.result() {
            self.validate_result_value(result, ctx);
        }
    }

    fn validate_jsonrpc_notification(
        &self,
        notification: &JsonRpcNotification,
        ctx: &mut ValidationContext,
    ) {
        // Validate JSON-RPC version (implicitly "2.0" via JsonRpcVersion type)
        // This is handled by type system during deserialization

        // Validate method name - check length first, then format
        if notification.method.is_empty() {
            ctx.add_error(
                "EMPTY_METHOD_NAME",
                "Method name cannot be empty".to_string(),
                Some("method".to_string()),
            );
        } else if notification.method.len() > self.rules.max_string_length {
            ctx.add_error(
                "METHOD_NAME_TOO_LONG",
                format!(
                    "Method name exceeds maximum length of {}",
                    self.rules.max_string_length
                ),
                Some("method".to_string()),
            );
        } else if !utils::is_valid_method_name(&notification.method) {
            ctx.add_error(
                "INVALID_METHOD_NAME",
                format!("Invalid method name format: '{}'", notification.method),
                Some("method".to_string()),
            );
        }

        // Validate parameters if present
        if let Some(ref params) = notification.params {
            self.validate_parameters(params, ctx);
        }

        // Notifications do NOT have an ID field (enforced by type system)
    }

    fn validate_jsonrpc_error(
        &self,
        error: &crate::jsonrpc::JsonRpcError,
        ctx: &mut ValidationContext,
    ) {
        // Error codes should be in the valid range
        if error.code >= 0 {
            ctx.add_warning(
                "POSITIVE_ERROR_CODE",
                "Error codes should be negative according to JSON-RPC spec".to_string(),
                Some("error.code".to_string()),
            );
        }

        if error.message.is_empty() {
            ctx.add_error(
                "EMPTY_ERROR_MESSAGE",
                "Error message cannot be empty".to_string(),
                Some("error.message".to_string()),
            );
        }
    }

    fn validate_method_name(&self, method: &str, ctx: &mut ValidationContext) {
        if method.is_empty() {
            ctx.add_error(
                "EMPTY_METHOD_NAME",
                "Method name cannot be empty".to_string(),
                Some("method".to_string()),
            );
            return;
        }

        if !self.rules.method_name_regex().is_match(method) {
            ctx.add_error(
                "INVALID_METHOD_NAME",
                format!("Invalid method name format: {method}"),
                Some("method".to_string()),
            );
        }
    }

    fn validate_method_params(&self, method: &str, params: &Value, ctx: &mut ValidationContext) {
        ctx.push_path("params".to_string());

        match method {
            "initialize" => self.validate_value_structure(params, "initialize", ctx),
            "tools/list" => {
                // Should be empty object or null
                if !params.is_null() && !params.as_object().is_some_and(|obj| obj.is_empty()) {
                    ctx.add_warning(
                        "UNEXPECTED_PARAMS",
                        "tools/list should not have parameters".to_string(),
                        None,
                    );
                }
            }
            "tools/call" => self.validate_value_structure(params, "call_tool", ctx),
            _ => {
                // Unknown method - validate basic structure
                self.validate_value_structure(params, "generic", ctx);
            }
        }

        ctx.pop_path();
    }

    fn validate_tool_input(&self, input: &ToolInputSchema, ctx: &mut ValidationContext) {
        ctx.push_path("inputSchema".to_string());

        // Validate schema type
        if input.schema_type != "object" {
            ctx.add_warning(
                "NON_OBJECT_SCHEMA",
                "Tool input schema should typically be 'object'".to_string(),
                Some("type".to_string()),
            );
        }

        ctx.pop_path();
    }

    fn validate_value_structure(
        &self,
        value: &Value,
        _expected_type: &str,
        ctx: &mut ValidationContext,
    ) {
        // Prevent infinite recursion
        if ctx.depth > self.rules.max_object_depth {
            ctx.add_error(
                "MAX_DEPTH_EXCEEDED",
                format!(
                    "Maximum object depth ({}) exceeded",
                    self.rules.max_object_depth
                ),
                None,
            );
            return;
        }

        match value {
            Value::Object(obj) => {
                ctx.depth += 1;
                for (key, val) in obj {
                    ctx.push_path(key.clone());
                    self.validate_value_structure(val, "unknown", ctx);
                    ctx.pop_path();
                }
                ctx.depth -= 1;
            }
            Value::Array(arr) => {
                if arr.len() > self.rules.max_array_length {
                    ctx.add_error(
                        "ARRAY_TOO_LONG",
                        format!(
                            "Array exceeds maximum length of {}",
                            self.rules.max_array_length
                        ),
                        None,
                    );
                }

                for (index, val) in arr.iter().enumerate() {
                    ctx.push_path(index.to_string());
                    self.validate_value_structure(val, "unknown", ctx);
                    ctx.pop_path();
                }
            }
            Value::String(s) => {
                if s.len() > self.rules.max_string_length {
                    ctx.add_error(
                        "STRING_TOO_LONG",
                        format!(
                            "String exceeds maximum length of {}",
                            self.rules.max_string_length
                        ),
                        None,
                    );
                }
            }
            _ => {} // Other types are fine
        }
    }

    fn validate_parameters(&self, params: &Value, ctx: &mut ValidationContext) {
        // Validate parameter structure depth and content
        self.validate_value_structure(params, "params", ctx);

        // Additional parameter-specific validation
        match params {
            Value::Array(arr) => {
                // Validate array parameters length
                if arr.len() > self.rules.max_array_length {
                    ctx.add_error(
                        "PARAMS_ARRAY_TOO_LONG",
                        format!(
                            "Parameter array exceeds maximum length of {}",
                            self.rules.max_array_length
                        ),
                        Some("params".to_string()),
                    );
                }
            }
            _ => {
                // Other parameter types are acceptable
            }
        }
    }

    fn validate_request_id(&self, _id: &crate::types::RequestId, _ctx: &mut ValidationContext) {
        // Request ID validation
        // ID is always present for requests (enforced by type system)
        // Additional ID format validation could be added here if needed
    }

    fn validate_response_id(&self, id: &crate::jsonrpc::ResponseId, _ctx: &mut ValidationContext) {
        // Validate response ID semantics
        if id.is_null() {
            // Null ID is only valid for parse errors
            // This should be checked at a higher level when the error type is known
        }
        // Additional response ID validation could be added here
    }

    fn validate_result_value(&self, result: &Value, ctx: &mut ValidationContext) {
        // Validate result structure depth and content
        self.validate_value_structure(result, "result", ctx);

        // Additional result validation based on method type could be added here
        // For now, we just validate general structure
    }
}

impl Default for ProtocolValidator {
    fn default() -> Self {
        Self::new()
    }
}

impl ValidationContext {
    fn new() -> Self {
        Self {
            path: Vec::new(),
            depth: 0,
            warnings: Vec::new(),
            errors: Vec::new(),
        }
    }

    fn push_path(&mut self, segment: String) {
        self.path.push(segment);
    }

    fn pop_path(&mut self) {
        self.path.pop();
    }

    fn current_path(&self) -> Option<String> {
        if self.path.is_empty() {
            None
        } else {
            Some(self.path.join("."))
        }
    }

    fn add_error(&mut self, code: &str, message: String, field_path: Option<String>) {
        let path = field_path.or_else(|| self.current_path());
        self.errors.push(ValidationError {
            code: code.to_string(),
            message,
            field_path: path,
        });
    }

    fn add_warning(&mut self, code: &str, message: String, field_path: Option<String>) {
        let path = field_path.or_else(|| self.current_path());
        self.warnings.push(ValidationWarning {
            code: code.to_string(),
            message,
            field_path: path,
        });
    }

    fn into_result(self) -> ValidationResult {
        if !self.errors.is_empty() {
            ValidationResult::Invalid(self.errors)
        } else if !self.warnings.is_empty() {
            ValidationResult::ValidWithWarnings(self.warnings)
        } else {
            ValidationResult::Valid
        }
    }
}

impl ValidationResult {
    /// Check if validation passed (with or without warnings)
    pub fn is_valid(&self) -> bool {
        !matches!(self, ValidationResult::Invalid(_))
    }

    /// Check if validation failed
    pub fn is_invalid(&self) -> bool {
        matches!(self, ValidationResult::Invalid(_))
    }

    /// Check if validation has warnings
    pub fn has_warnings(&self) -> bool {
        matches!(self, ValidationResult::ValidWithWarnings(_))
    }

    /// Get warnings (if any)
    pub fn warnings(&self) -> &[ValidationWarning] {
        match self {
            ValidationResult::ValidWithWarnings(warnings) => warnings,
            _ => &[],
        }
    }

    /// Get errors (if any)
    pub fn errors(&self) -> &[ValidationError] {
        match self {
            ValidationResult::Invalid(errors) => errors,
            _ => &[],
        }
    }
}

/// Utility functions for validation
pub mod utils {
    use super::*;

    /// Create a validation error
    pub fn error(code: &str, message: &str) -> ValidationError {
        ValidationError {
            code: code.to_string(),
            message: message.to_string(),
            field_path: None,
        }
    }

    /// Create a validation warning
    pub fn warning(code: &str, message: &str) -> ValidationWarning {
        ValidationWarning {
            code: code.to_string(),
            message: message.to_string(),
            field_path: None,
        }
    }

    /// Check if a string is a valid URI
    pub fn is_valid_uri(uri: &str) -> bool {
        ValidationRules::default().uri_regex().is_match(uri)
    }

    /// Check if a string is a valid method name
    pub fn is_valid_method_name(method: &str) -> bool {
        ValidationRules::default()
            .method_name_regex()
            .is_match(method)
    }
}

// Comprehensive tests in separate file (tokio/axum pattern)
// This gives us:
// - Better organization (tests don't clutter the implementation)
// - Access to private items (tests are still part of the module)
// - Easy to find (tests.rs is in the same directory as validation.rs)
#[cfg(test)]
mod tests;