pulseengine-mcp-protocol 0.17.1

[DEPRECATED] Use rmcp instead. MCP protocol types for PulseEngine.
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
//! Validation utilities for MCP protocol types

use crate::{Error, Result};
use jsonschema::{JSONSchema, ValidationError};
use serde_json::Value;
use std::collections::HashMap;
use uuid::Uuid;
use validator::Validate;

/// Protocol validation utilities
pub struct Validator;

impl Validator {
    /// Validate a UUID string
    ///
    /// # Errors
    ///
    /// Returns an error if the string is not a valid UUID format
    pub fn validate_uuid(uuid_str: &str) -> Result<Uuid> {
        uuid_str
            .parse::<Uuid>()
            .map_err(|e| Error::validation_error(format!("Invalid UUID: {e}")))
    }

    /// Validate that a string is not empty
    ///
    /// # Errors
    ///
    /// Returns an error if the string is empty or contains only whitespace
    pub fn validate_non_empty(value: &str, field_name: &str) -> Result<()> {
        if value.trim().is_empty() {
            Err(Error::validation_error(format!(
                "{field_name} cannot be empty"
            )))
        } else {
            Ok(())
        }
    }

    /// Validate a tool name (must be alphanumeric with underscores)
    ///
    /// # Errors
    ///
    /// Returns an error if the name is empty or contains invalid characters
    pub fn validate_tool_name(name: &str) -> Result<()> {
        Self::validate_non_empty(name, "Tool name")?;

        if !name
            .chars()
            .all(|c| c.is_alphanumeric() || c == '_' || c == '-')
        {
            return Err(Error::validation_error(
                "Tool name must contain only alphanumeric characters, underscores, and hyphens",
            ));
        }

        Ok(())
    }

    /// Validate a resource URI
    ///
    /// # Errors
    ///
    /// Returns an error if the URI is empty or contains control characters
    pub fn validate_resource_uri(uri: &str) -> Result<()> {
        Self::validate_non_empty(uri, "Resource URI")?;

        // Basic URI validation - must not contain control characters
        if uri.chars().any(char::is_control) {
            return Err(Error::validation_error(
                "Resource URI cannot contain control characters",
            ));
        }

        Ok(())
    }

    /// Validate a UI resource URI (MCP Apps Extension)
    ///
    /// UI resource URIs must use the `ui://` scheme and follow URI conventions.
    ///
    /// # Errors
    ///
    /// Returns an error if the URI doesn't start with `ui://` or is otherwise invalid
    pub fn validate_ui_resource_uri(uri: &str) -> Result<()> {
        Self::validate_resource_uri(uri)?;

        if !uri.starts_with("ui://") {
            return Err(Error::validation_error(
                "UI resource URI must start with 'ui://'",
            ));
        }

        // Ensure there's something after the scheme
        if uri.len() <= 5 {
            return Err(Error::validation_error(
                "UI resource URI must have a path after 'ui://'",
            ));
        }

        Ok(())
    }

    /// Check if a URI is a UI resource URI
    pub fn is_ui_resource_uri(uri: &str) -> bool {
        uri.starts_with("ui://")
    }

    /// Validate JSON schema
    ///
    /// # Errors
    ///
    /// Returns an error if the schema is not a valid JSON object with a type field
    pub fn validate_json_schema(schema: &Value) -> Result<()> {
        // Basic validation - ensure it's an object with a "type" field
        if let Some(obj) = schema.as_object() {
            if !obj.contains_key("type") {
                return Err(Error::validation_error(
                    "JSON schema must have a 'type' field",
                ));
            }
        } else {
            return Err(Error::validation_error("JSON schema must be an object"));
        }

        Ok(())
    }

    /// Validate tool arguments against a schema
    ///
    /// # Errors
    ///
    /// Returns an error if required arguments are missing from the provided arguments
    pub fn validate_tool_arguments(args: &HashMap<String, Value>, schema: &Value) -> Result<()> {
        // Basic validation - check required properties if defined
        if let Some(schema_obj) = schema.as_object()
            && let Some(_properties) = schema_obj.get("properties").and_then(|p| p.as_object())
            && let Some(required) = schema_obj.get("required").and_then(|r| r.as_array())
        {
            for req_field in required {
                if let Some(field_name) = req_field.as_str()
                    && !args.contains_key(field_name)
                {
                    return Err(Error::validation_error(format!(
                        "Required argument '{field_name}' is missing"
                    )));
                }
            }
        }

        Ok(())
    }

    /// Validate pagination parameters
    ///
    /// # Errors
    ///
    /// Returns an error if cursor is empty, limit is 0, or limit exceeds 1000
    pub fn validate_pagination(cursor: Option<&str>, limit: Option<u32>) -> Result<()> {
        if let Some(cursor_val) = cursor {
            Self::validate_non_empty(cursor_val, "Cursor")?;
        }

        if let Some(limit_val) = limit {
            if limit_val == 0 {
                return Err(Error::validation_error("Limit must be greater than 0"));
            }
            if limit_val > 1000 {
                return Err(Error::validation_error("Limit cannot exceed 1000"));
            }
        }

        Ok(())
    }

    /// Validate prompt name
    ///
    /// # Errors
    ///
    /// Returns an error if the name is empty or contains invalid characters
    pub fn validate_prompt_name(name: &str) -> Result<()> {
        Self::validate_non_empty(name, "Prompt name")?;

        if !name
            .chars()
            .all(|c| c.is_alphanumeric() || c == '_' || c == '-' || c == '.')
        {
            return Err(Error::validation_error(
                "Prompt name must contain only alphanumeric characters, underscores, hyphens, and dots",
            ));
        }

        Ok(())
    }

    /// Validate a struct using the validator crate
    ///
    /// # Errors
    ///
    /// Returns an error if the struct fails validation according to its validation rules
    pub fn validate_struct<T: Validate>(item: &T) -> Result<()> {
        item.validate()
            .map_err(|e| Error::validation_error(e.to_string()))
    }

    /// Validate structured content against a JSON schema
    ///
    /// # Errors
    ///
    /// Returns an error if the content doesn't match the schema or if the schema is invalid
    pub fn validate_structured_content(content: &Value, output_schema: &Value) -> Result<()> {
        // First validate that the schema itself is valid
        Self::validate_json_schema(output_schema)?;

        // Compile the schema
        let schema = JSONSchema::compile(output_schema)
            .map_err(|e| Error::validation_error(format!("Invalid JSON schema: {e}")))?;

        // Validate the content against the schema
        if let Err(errors) = schema.validate(content) {
            let error_messages: Vec<String> = errors
                .map(|e| format!("{}: {}", e.instance_path, e))
                .collect();
            return Err(Error::validation_error(format!(
                "Structured content validation failed: {}",
                error_messages.join(", ")
            )));
        }

        Ok(())
    }

    /// Validate that a tool's output schema is properly defined
    ///
    /// # Errors
    ///
    /// Returns an error if the output schema is invalid or incompatible with MCP requirements
    pub fn validate_tool_output_schema(output_schema: &Value) -> Result<()> {
        // Basic JSON schema validation
        Self::validate_json_schema(output_schema)?;

        // Additional MCP-specific validations for tool output schemas
        if let Some(obj) = output_schema.as_object() {
            // Ensure the schema describes structured data (object or array)
            if let Some(schema_type) = obj.get("type").and_then(|t| t.as_str()) {
                match schema_type {
                    "object" | "array" => {
                        // Valid structured types
                    }
                    "string" | "number" | "integer" | "boolean" | "null" => {
                        return Err(Error::validation_error(
                            "Tool output schema should define structured data (object or array), not primitive types",
                        ));
                    }
                    _ => {
                        return Err(Error::validation_error(
                            "Invalid type specified in tool output schema",
                        ));
                    }
                }
            }

            // Check for required properties in object schemas
            if obj.get("type").and_then(|t| t.as_str()) == Some("object") {
                if let Some(properties) = obj.get("properties") {
                    if !properties.is_object() {
                        return Err(Error::validation_error(
                            "Object schema properties must be an object",
                        ));
                    }
                } else {
                    return Err(Error::validation_error(
                        "Object schema must define properties",
                    ));
                }
            }
        }

        Ok(())
    }

    /// Extract validation errors in a user-friendly format
    ///
    /// # Errors
    ///
    /// Returns formatted validation error messages
    pub fn format_validation_errors<'a>(
        errors: impl Iterator<Item = ValidationError<'a>>,
    ) -> String {
        let messages: Vec<String> = errors
            .map(|error| {
                let path_str = error.instance_path.to_string();
                if path_str.is_empty() {
                    error.to_string()
                } else {
                    format!("at '{path_str}': {error}")
                }
            })
            .collect();

        if messages.is_empty() {
            "Unknown validation error".to_string()
        } else {
            messages.join("; ")
        }
    }
}

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

    #[test]
    fn test_validate_uuid() {
        let valid_uuid = "550e8400-e29b-41d4-a716-446655440000";
        assert!(Validator::validate_uuid(valid_uuid).is_ok());

        let invalid_uuid = "not-a-uuid";
        assert!(Validator::validate_uuid(invalid_uuid).is_err());
    }

    #[test]
    fn test_validate_non_empty() {
        assert!(Validator::validate_non_empty("valid", "field").is_ok());
        assert!(Validator::validate_non_empty("", "field").is_err());
        assert!(Validator::validate_non_empty("   ", "field").is_err());
    }

    #[test]
    fn test_validate_tool_name() {
        assert!(Validator::validate_tool_name("valid_tool").is_ok());
        assert!(Validator::validate_tool_name("tool-name").is_ok());
        assert!(Validator::validate_tool_name("tool123").is_ok());
        assert!(Validator::validate_tool_name("").is_err());
        assert!(Validator::validate_tool_name("invalid tool").is_err());
        assert!(Validator::validate_tool_name("tool@name").is_err());
    }

    #[test]
    fn test_validate_json_schema() {
        let valid_schema = json!({"type": "object"});
        assert!(Validator::validate_json_schema(&valid_schema).is_ok());

        let invalid_schema = json!("not an object");
        assert!(Validator::validate_json_schema(&invalid_schema).is_err());

        let no_type_schema = json!({"properties": {}});
        assert!(Validator::validate_json_schema(&no_type_schema).is_err());
    }

    #[test]
    fn test_validate_pagination() {
        assert!(Validator::validate_pagination(None, None).is_ok());
        assert!(Validator::validate_pagination(Some("cursor"), Some(10)).is_ok());
        assert!(Validator::validate_pagination(Some(""), None).is_err());
        assert!(Validator::validate_pagination(None, Some(0)).is_err());
        assert!(Validator::validate_pagination(None, Some(1001)).is_err());
    }

    #[test]
    fn test_validate_resource_uri() {
        // Valid URIs
        assert!(Validator::validate_resource_uri("http://example.com/resource").is_ok());
        assert!(Validator::validate_resource_uri("file:///path/to/resource").is_ok());
        assert!(Validator::validate_resource_uri("custom://protocol/resource").is_ok());

        // Invalid URIs
        assert!(Validator::validate_resource_uri("").is_err());
        assert!(Validator::validate_resource_uri("   ").is_err());
        assert!(Validator::validate_resource_uri("uri\nwith\nnewlines").is_err());
        assert!(Validator::validate_resource_uri("uri\twith\ttabs").is_err());
        assert!(Validator::validate_resource_uri("uri\rwith\rcarriage\rreturns").is_err());
    }

    #[test]
    fn test_validate_prompt_name() {
        // Valid prompt names
        assert!(Validator::validate_prompt_name("valid_prompt").is_ok());
        assert!(Validator::validate_prompt_name("prompt-name").is_ok());
        assert!(Validator::validate_prompt_name("prompt.name").is_ok());
        assert!(Validator::validate_prompt_name("prompt123").is_ok());
        assert!(Validator::validate_prompt_name("Prompt_Name-123.test").is_ok());

        // Invalid prompt names
        assert!(Validator::validate_prompt_name("").is_err());
        assert!(Validator::validate_prompt_name("   ").is_err());
        assert!(Validator::validate_prompt_name("prompt name").is_err());
        assert!(Validator::validate_prompt_name("prompt@name").is_err());
        assert!(Validator::validate_prompt_name("prompt/name").is_err());
        assert!(Validator::validate_prompt_name("prompt:name").is_err());
    }

    #[test]
    fn test_validate_tool_arguments() {
        // Valid schema with no required fields
        let schema = json!({
            "type": "object",
            "properties": {
                "name": {"type": "string"},
                "age": {"type": "number"}
            }
        });
        let args = HashMap::new();
        assert!(Validator::validate_tool_arguments(&args, &schema).is_ok());

        // Valid schema with required fields - all present
        let schema = json!({
            "type": "object",
            "properties": {
                "name": {"type": "string"},
                "age": {"type": "number"}
            },
            "required": ["name"]
        });
        let mut args = HashMap::new();
        args.insert("name".to_string(), json!("John"));
        assert!(Validator::validate_tool_arguments(&args, &schema).is_ok());

        // Invalid - missing required field
        let args = HashMap::new();
        let result = Validator::validate_tool_arguments(&args, &schema);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .message
                .contains("Required argument 'name' is missing")
        );

        // Valid schema with multiple required fields
        let schema = json!({
            "type": "object",
            "properties": {
                "name": {"type": "string"},
                "age": {"type": "number"},
                "email": {"type": "string"}
            },
            "required": ["name", "email"]
        });
        let mut args = HashMap::new();
        args.insert("name".to_string(), json!("John"));
        args.insert("email".to_string(), json!("john@example.com"));
        assert!(Validator::validate_tool_arguments(&args, &schema).is_ok());

        // Invalid - missing one required field
        let mut args = HashMap::new();
        args.insert("name".to_string(), json!("John"));
        let result = Validator::validate_tool_arguments(&args, &schema);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .message
                .contains("Required argument 'email' is missing")
        );

        // Schema without properties
        let schema = json!({
            "type": "object"
        });
        let args = HashMap::new();
        assert!(Validator::validate_tool_arguments(&args, &schema).is_ok());

        // Schema with empty required array
        let schema = json!({
            "type": "object",
            "properties": {
                "name": {"type": "string"}
            },
            "required": []
        });
        let args = HashMap::new();
        assert!(Validator::validate_tool_arguments(&args, &schema).is_ok());

        // Schema with invalid required field (not a string)
        let schema = json!({
            "type": "object",
            "properties": {
                "name": {"type": "string"}
            },
            "required": [123]
        });
        let args = HashMap::new();
        assert!(Validator::validate_tool_arguments(&args, &schema).is_ok());
    }

    #[test]
    fn test_validate_structured_content() {
        // Valid structured content
        let content = json!({
            "name": "John Doe",
            "age": 30,
            "email": "john@example.com"
        });
        let schema = json!({
            "type": "object",
            "properties": {
                "name": {"type": "string"},
                "age": {"type": "integer", "minimum": 0},
                "email": {"type": "string", "format": "email"}
            },
            "required": ["name", "age"]
        });

        assert!(Validator::validate_structured_content(&content, &schema).is_ok());

        // Invalid content - missing required field
        let invalid_content = json!({
            "name": "John Doe"
        });
        let result = Validator::validate_structured_content(&invalid_content, &schema);
        assert!(result.is_err());
        assert!(result.unwrap_err().message.contains("validation failed"));

        // Invalid content - wrong type
        let invalid_content = json!({
            "name": "John Doe",
            "age": "thirty"
        });
        let result = Validator::validate_structured_content(&invalid_content, &schema);
        assert!(result.is_err());

        // Invalid schema - this should be a basic validation before attempting to compile
        let invalid_schema = json!({
            "type": "invalid_type"
        });
        let result = Validator::validate_structured_content(&content, &invalid_schema);
        assert!(result.is_err());
        // The error message can vary, but it should indicate schema validation failure
        let error_msg = result.unwrap_err().message;
        assert!(error_msg.contains("JSON schema") || error_msg.contains("Invalid"));
    }

    #[test]
    fn test_validate_tool_output_schema() {
        // Valid object schema
        let valid_object_schema = json!({
            "type": "object",
            "properties": {
                "result": {"type": "string"},
                "metadata": {"type": "object"}
            }
        });
        assert!(Validator::validate_tool_output_schema(&valid_object_schema).is_ok());

        // Valid array schema
        let valid_array_schema = json!({
            "type": "array",
            "items": {"type": "string"}
        });
        assert!(Validator::validate_tool_output_schema(&valid_array_schema).is_ok());

        // Invalid - primitive type
        let invalid_primitive_schema = json!({
            "type": "string"
        });
        let result = Validator::validate_tool_output_schema(&invalid_primitive_schema);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .message
                .contains("should define structured data")
        );

        // Invalid - object without properties
        let invalid_object_schema = json!({
            "type": "object"
        });
        let result = Validator::validate_tool_output_schema(&invalid_object_schema);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .message
                .contains("must define properties")
        );

        // Invalid - object with invalid properties
        let invalid_props_schema = json!({
            "type": "object",
            "properties": "not an object"
        });
        let result = Validator::validate_tool_output_schema(&invalid_props_schema);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .message
                .contains("properties must be an object")
        );

        // Invalid - missing type field
        let no_type_schema = json!({
            "properties": {}
        });
        let result = Validator::validate_tool_output_schema(&no_type_schema);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .message
                .contains("JSON schema must have a 'type' field")
        );
    }

    #[test]
    fn test_structured_content_with_arrays() {
        // Array content validation
        let content = json!([
            {"id": 1, "name": "Item 1"},
            {"id": 2, "name": "Item 2"}
        ]);
        let schema = json!({
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "id": {"type": "integer"},
                    "name": {"type": "string"}
                },
                "required": ["id", "name"]
            }
        });

        assert!(Validator::validate_structured_content(&content, &schema).is_ok());

        // Invalid array content
        let invalid_content = json!([
            {"id": 1, "name": "Item 1"},
            {"id": "not a number", "name": "Item 2"}
        ]);
        let result = Validator::validate_structured_content(&invalid_content, &schema);
        assert!(result.is_err());
    }

    #[test]
    fn test_nested_structured_content() {
        // Nested object validation
        let content = json!({
            "user": {
                "name": "John",
                "profile": {
                    "age": 30,
                    "preferences": ["reading", "coding"]
                }
            },
            "timestamp": "2023-01-01T00:00:00Z"
        });

        let schema = json!({
            "type": "object",
            "properties": {
                "user": {
                    "type": "object",
                    "properties": {
                        "name": {"type": "string"},
                        "profile": {
                            "type": "object",
                            "properties": {
                                "age": {"type": "integer"},
                                "preferences": {
                                    "type": "array",
                                    "items": {"type": "string"}
                                }
                            },
                            "required": ["age"]
                        }
                    },
                    "required": ["name", "profile"]
                },
                "timestamp": {"type": "string"}
            },
            "required": ["user"]
        });

        assert!(Validator::validate_structured_content(&content, &schema).is_ok());

        // Invalid nested content
        let invalid_content = json!({
            "user": {
                "name": "John",
                "profile": {
                    "preferences": ["reading", "coding"]
                    // Missing required "age" field
                }
            }
        });
        let result = Validator::validate_structured_content(&invalid_content, &schema);
        assert!(result.is_err());
    }

    #[test]
    fn test_format_validation_errors() {
        // This is a basic test since we can't easily create ValidationError instances
        // The function is mainly for internal use
        let empty_errors = std::iter::empty();
        let result = Validator::format_validation_errors(empty_errors);
        assert_eq!(result, "Unknown validation error");
    }

    #[test]
    fn test_call_tool_result_structured_validation() {
        use crate::model::{CallToolResult, Content};

        // Valid structured content
        let structured_data = json!({
            "result": "success",
            "data": {"count": 42}
        });
        let schema = json!({
            "type": "object",
            "properties": {
                "result": {"type": "string"},
                "data": {"type": "object"}
            },
            "required": ["result"]
        });

        let result =
            CallToolResult::structured(vec![Content::text("Operation completed")], structured_data);

        assert!(result.validate_structured_content(&schema).is_ok());

        // Invalid structured content
        let invalid_data = json!({
            "result": 123 // Should be string
        });
        let invalid_result =
            CallToolResult::structured(vec![Content::text("Operation completed")], invalid_data);

        assert!(invalid_result.validate_structured_content(&schema).is_err());

        // Result without structured content should pass validation
        let simple_result = CallToolResult::text("Simple result");
        assert!(simple_result.validate_structured_content(&schema).is_ok());
    }

    #[test]
    fn test_validate_uuid_edge_cases() {
        // Valid UUID formats
        assert!(Validator::validate_uuid("550e8400-e29b-41d4-a716-446655440000").is_ok());
        assert!(Validator::validate_uuid("6ba7b810-9dad-11d1-80b4-00c04fd430c8").is_ok());
        assert!(Validator::validate_uuid("123e4567-e89b-12d3-a456-426614174000").is_ok());

        // Invalid UUID formats
        assert!(Validator::validate_uuid("550e8400-e29b-41d4-a716-44665544000").is_err()); // Too short
        assert!(Validator::validate_uuid("550e8400-e29b-41d4-a716-4466554400000").is_err()); // Too long
        assert!(Validator::validate_uuid("550e8400-e29b-41d4-a716-44665544000g").is_err()); // Invalid character
        assert!(Validator::validate_uuid("550e8400e29b41d4a716446655440000").is_ok()); // No dashes (valid)
        assert!(Validator::validate_uuid("").is_err()); // Empty string
        assert!(Validator::validate_uuid("not-a-uuid-at-all").is_err()); // Random string
    }

    #[test]
    fn test_validate_non_empty_edge_cases() {
        // Valid non-empty strings
        assert!(Validator::validate_non_empty("valid", "field").is_ok());
        assert!(Validator::validate_non_empty("a", "field").is_ok());
        assert!(Validator::validate_non_empty("123", "field").is_ok());
        assert!(Validator::validate_non_empty("special!@#$%^&*()", "field").is_ok());
        assert!(Validator::validate_non_empty("  text  ", "field").is_ok()); // Whitespace around text is OK

        // Invalid empty strings
        let result = Validator::validate_non_empty("", "field");
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .message
                .contains("field cannot be empty")
        );

        let result = Validator::validate_non_empty("   ", "field");
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .message
                .contains("field cannot be empty")
        );

        let result = Validator::validate_non_empty("\t\n\r", "field");
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .message
                .contains("field cannot be empty")
        );

        // Test with different field names
        let result = Validator::validate_non_empty("", "tool_name");
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .message
                .contains("tool_name cannot be empty")
        );
    }

    #[test]
    fn test_validate_tool_name_edge_cases() {
        // Valid tool names
        assert!(Validator::validate_tool_name("a").is_ok());
        assert!(Validator::validate_tool_name("tool").is_ok());
        assert!(Validator::validate_tool_name("tool_name").is_ok());
        assert!(Validator::validate_tool_name("tool-name").is_ok());
        assert!(Validator::validate_tool_name("tool123").is_ok());
        assert!(Validator::validate_tool_name("123tool").is_ok());
        assert!(Validator::validate_tool_name("Tool_Name-123").is_ok());
        assert!(Validator::validate_tool_name("_tool").is_ok());
        assert!(Validator::validate_tool_name("tool_").is_ok());
        assert!(Validator::validate_tool_name("-tool").is_ok());
        assert!(Validator::validate_tool_name("tool-").is_ok());

        // Invalid tool names
        let result = Validator::validate_tool_name("");
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .message
                .contains("Tool name cannot be empty")
        );

        let result = Validator::validate_tool_name("   ");
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .message
                .contains("Tool name cannot be empty")
        );

        let result = Validator::validate_tool_name("tool name");
        assert!(result.is_err());
        assert!(result.unwrap_err().message.contains(
            "Tool name must contain only alphanumeric characters, underscores, and hyphens"
        ));

        let result = Validator::validate_tool_name("tool.name");
        assert!(result.is_err());
        assert!(result.unwrap_err().message.contains(
            "Tool name must contain only alphanumeric characters, underscores, and hyphens"
        ));

        let result = Validator::validate_tool_name("tool@name");
        assert!(result.is_err());
        assert!(result.unwrap_err().message.contains(
            "Tool name must contain only alphanumeric characters, underscores, and hyphens"
        ));

        let result = Validator::validate_tool_name("tool/name");
        assert!(result.is_err());
        assert!(result.unwrap_err().message.contains(
            "Tool name must contain only alphanumeric characters, underscores, and hyphens"
        ));
    }

    #[test]
    fn test_validate_json_schema_edge_cases() {
        // Valid schemas
        let valid_schema = json!({"type": "object"});
        assert!(Validator::validate_json_schema(&valid_schema).is_ok());

        let valid_schema = json!({
            "type": "object",
            "properties": {
                "name": {"type": "string"}
            }
        });
        assert!(Validator::validate_json_schema(&valid_schema).is_ok());

        let valid_schema = json!({
            "type": "string",
            "minLength": 1
        });
        assert!(Validator::validate_json_schema(&valid_schema).is_ok());

        // Invalid schemas
        let result = Validator::validate_json_schema(&json!("not an object"));
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .message
                .contains("JSON schema must be an object")
        );

        let result = Validator::validate_json_schema(&json!(123));
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .message
                .contains("JSON schema must be an object")
        );

        let result = Validator::validate_json_schema(&json!([]));
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .message
                .contains("JSON schema must be an object")
        );

        let result = Validator::validate_json_schema(&json!(null));
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .message
                .contains("JSON schema must be an object")
        );

        let result = Validator::validate_json_schema(&json!({"properties": {}}));
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .message
                .contains("JSON schema must have a 'type' field")
        );

        let result = Validator::validate_json_schema(&json!({}));
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .message
                .contains("JSON schema must have a 'type' field")
        );
    }

    #[test]
    fn test_validate_pagination_edge_cases() {
        // Valid pagination parameters
        assert!(Validator::validate_pagination(None, None).is_ok());
        assert!(Validator::validate_pagination(Some("cursor"), None).is_ok());
        assert!(Validator::validate_pagination(None, Some(1)).is_ok());
        assert!(Validator::validate_pagination(Some("cursor"), Some(1)).is_ok());
        assert!(Validator::validate_pagination(Some("cursor"), Some(1000)).is_ok());
        assert!(
            Validator::validate_pagination(
                Some("very-long-cursor-value-that-should-still-be-valid"),
                Some(500)
            )
            .is_ok()
        );

        // Invalid cursor values
        let result = Validator::validate_pagination(Some(""), None);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .message
                .contains("Cursor cannot be empty")
        );

        let result = Validator::validate_pagination(Some("   "), None);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .message
                .contains("Cursor cannot be empty")
        );

        let result = Validator::validate_pagination(Some("\t\n\r"), None);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .message
                .contains("Cursor cannot be empty")
        );

        // Invalid limit values
        let result = Validator::validate_pagination(None, Some(0));
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .message
                .contains("Limit must be greater than 0")
        );

        let result = Validator::validate_pagination(None, Some(1001));
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .message
                .contains("Limit cannot exceed 1000")
        );

        let result = Validator::validate_pagination(None, Some(u32::MAX));
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .message
                .contains("Limit cannot exceed 1000")
        );

        // Test with both invalid cursor and limit
        let result = Validator::validate_pagination(Some(""), Some(0));
        assert!(result.is_err());
        // Should fail on cursor first
        assert!(
            result
                .unwrap_err()
                .message
                .contains("Cursor cannot be empty")
        );

        let result = Validator::validate_pagination(Some("valid-cursor"), Some(0));
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .message
                .contains("Limit must be greater than 0")
        );
    }
}