pmcp 2.4.0

High-quality Rust SDK for Model Context Protocol (MCP) with full TypeScript SDK compatibility
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
//! Validation helpers for typed tools
//!
//! Provides ergonomic validation functions that return consistent Error::Validation errors
//! with optional machine-readable hints for client elicitation support.

use crate::{Error, Result};
use regex::Regex;
use serde_json::json;

/// Validation error with elicitation support
#[derive(Debug)]
pub struct ValidationError {
    /// Human-readable error message
    pub message: String,
    /// Machine-readable error code for elicitation
    pub code: Option<String>,
    /// Field that failed validation
    pub field: Option<String>,
    /// Expected format or value
    pub expected: Option<String>,
}

impl ValidationError {
    /// Create a validation error with elicitation hints
    pub fn elicit(
        code: impl Into<String>,
        field: impl Into<String>,
        expected: impl Into<String>,
    ) -> Error {
        let field_str = field.into();
        Error::Validation(
            json!({
                "message": format!("Validation failed for field '{}'", &field_str),
                "code": code.into(),
                "field": field_str,
                "expected": expected.into(),
                "elicit": true
            })
            .to_string(),
        )
    }

    /// Create a simple validation error
    pub fn simple(message: impl Into<String>) -> Error {
        Error::Validation(message.into())
    }
}

/// Validate that a value is within a range
///
/// # Example
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use pmcp::server::validation::validate_range;
///
/// let age = 25;
/// validate_range("age", &age, &18, &120)?;
/// # Ok(())
/// # }
/// ```
pub fn validate_range<T>(field: &str, value: &T, min: &T, max: &T) -> Result<()>
where
    T: PartialOrd + std::fmt::Display,
{
    if value < min || value > max {
        return Err(ValidationError::elicit(
            "out_of_range",
            field,
            format!("Value must be between {} and {}", min, max),
        ));
    }
    Ok(())
}

/// Validate that a value is one of an allowed set
///
/// # Example
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use pmcp::server::validation::validate_one_of;
///
/// let currency = "USD";
/// validate_one_of("currency", &currency, &["USD", "EUR", "GBP"])?;
/// # Ok(())
/// # }
/// ```
pub fn validate_one_of<T>(field: &str, value: &T, allowed: &[T]) -> Result<()>
where
    T: PartialEq + std::fmt::Display,
{
    if !allowed.contains(value) {
        let allowed_str = allowed
            .iter()
            .map(|v| v.to_string())
            .collect::<Vec<_>>()
            .join(", ");
        return Err(ValidationError::elicit(
            "invalid_choice",
            field,
            format!("Must be one of: {}", allowed_str),
        ));
    }
    Ok(())
}

/// Validate that a string matches a regex pattern
///
/// # Example
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use pmcp::server::validation::validate_regex;
///
/// let email = "user@example.com";
/// validate_regex("email", email, r"^[\w\.-]+@[\w\.-]+\.\w+$")?;
/// # Ok(())
/// # }
/// ```
pub fn validate_regex(field: &str, value: &str, pattern: &str) -> Result<()> {
    let regex = Regex::new(pattern)
        .map_err(|e| Error::Internal(format!("Invalid regex pattern '{}': {}", pattern, e)))?;

    if !regex.is_match(value) {
        return Err(ValidationError::elicit(
            "pattern_mismatch",
            field,
            format!("Must match pattern: {}", pattern),
        ));
    }
    Ok(())
}

/// Validate string length
///
/// # Example
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use pmcp::server::validation::validate_length;
///
/// let name = "John Doe";
/// validate_length("name", name, Some(2), Some(100))?;
/// # Ok(())
/// # }
/// ```
pub fn validate_length(
    field: &str,
    value: &str,
    min: Option<usize>,
    max: Option<usize>,
) -> Result<()> {
    let len = value.len();

    if let Some(min_len) = min {
        if len < min_len {
            return Err(ValidationError::elicit(
                "too_short",
                field,
                format!("Minimum length is {}", min_len),
            ));
        }
    }

    if let Some(max_len) = max {
        if len > max_len {
            return Err(ValidationError::elicit(
                "too_long",
                field,
                format!("Maximum length is {}", max_len),
            ));
        }
    }

    Ok(())
}

/// Validate email format
///
/// # Example
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use pmcp::server::validation::validate_email;
///
/// validate_email("email", "user@example.com")?;
/// # Ok(())
/// # }
/// ```
pub fn validate_email(field: &str, value: &str) -> Result<()> {
    // Basic email validation
    if !value.contains('@') || !value.contains('.') || value.len() < 5 {
        return Err(ValidationError::elicit(
            "invalid_email",
            field,
            "Valid email address (e.g., user@example.com)",
        ));
    }

    // More detailed validation
    let parts: Vec<&str> = value.split('@').collect();
    if parts.len() != 2 || parts[0].is_empty() || parts[1].is_empty() {
        return Err(ValidationError::elicit(
            "invalid_email",
            field,
            "Valid email address (e.g., user@example.com)",
        ));
    }

    Ok(())
}

/// Validate URL format
///
/// # Example
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use pmcp::server::validation::validate_url;
///
/// validate_url("website", "https://example.com")?;
/// # Ok(())
/// # }
/// ```
pub fn validate_url(field: &str, value: &str) -> Result<()> {
    if !value.starts_with("http://") && !value.starts_with("https://") {
        return Err(ValidationError::elicit(
            "invalid_url",
            field,
            "Valid URL starting with http:// or https://",
        ));
    }

    // Basic URL structure check
    if value.len() < 10 || !value[8..].contains('.') {
        return Err(ValidationError::elicit(
            "invalid_url",
            field,
            "Valid URL (e.g., https://example.com)",
        ));
    }

    Ok(())
}

/// Validate that a path is safe (no traversal)
///
/// # Example
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use pmcp::server::validation::validate_safe_path;
///
/// validate_safe_path("filepath", "/tmp/myfile.txt", Some("/tmp/"))?;
/// # Ok(())
/// # }
/// ```
pub fn validate_safe_path(field: &str, path: &str, allowed_prefix: Option<&str>) -> Result<()> {
    // Check for path traversal
    if path.contains("..") {
        return Err(ValidationError::elicit(
            "path_traversal",
            field,
            "Path must not contain '..'",
        ));
    }

    // Check for null bytes
    if path.contains('\0') {
        return Err(ValidationError::elicit(
            "invalid_path",
            field,
            "Path must not contain null bytes",
        ));
    }

    // Check allowed prefix
    if let Some(prefix) = allowed_prefix {
        if !path.starts_with(prefix) {
            return Err(ValidationError::elicit(
                "path_not_allowed",
                field,
                format!("Path must start with '{}'", prefix),
            ));
        }
    }

    Ok(())
}

/// Validate that a value is not empty
///
/// # Example
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use pmcp::server::validation::validate_required;
///
/// validate_required("username", "john_doe")?;
/// # Ok(())
/// # }
/// ```
pub fn validate_required(field: &str, value: &str) -> Result<()> {
    if value.trim().is_empty() {
        return Err(ValidationError::elicit(
            "required_field",
            field,
            "This field is required",
        ));
    }
    Ok(())
}

/// Validate array/vec size
///
/// # Example
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use pmcp::server::validation::validate_array_size;
///
/// let items = vec!["a", "b", "c"];
/// validate_array_size("items", &items, Some(1), Some(10))?;
/// # Ok(())
/// # }
/// ```
pub fn validate_array_size<T>(
    field: &str,
    items: &[T],
    min: Option<usize>,
    max: Option<usize>,
) -> Result<()> {
    let len = items.len();

    if let Some(min_len) = min {
        if len < min_len {
            return Err(ValidationError::elicit(
                "too_few_items",
                field,
                format!("Minimum {} items required", min_len),
            ));
        }
    }

    if let Some(max_len) = max {
        if len > max_len {
            return Err(ValidationError::elicit(
                "too_many_items",
                field,
                format!("Maximum {} items allowed", max_len),
            ));
        }
    }

    Ok(())
}

/// Validate numeric percentage (0-100)
///
/// # Example
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use pmcp::server::validation::validate_percentage;
///
/// validate_percentage("discount", 25.5)?;
/// # Ok(())
/// # }
/// ```
pub fn validate_percentage(field: &str, value: f64) -> Result<()> {
    if !(0.0..=100.0).contains(&value) {
        return Err(ValidationError::elicit(
            "invalid_percentage",
            field,
            "Value must be between 0 and 100",
        ));
    }
    Ok(())
}

/// Builder for complex validations
///
/// # Example
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use pmcp::server::validation::Validator;
///
/// let mut v = Validator::new();
/// v.field("age", 25).range(&18, &120);
/// v.field("email", "user@example.com").email();
/// v.field("country", "US").one_of(&["US", "UK", "CA"]);
/// v.validate()?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct Validator {
    errors: Vec<Error>,
}

impl Validator {
    /// Create a new validator
    pub fn new() -> Self {
        Self { errors: Vec::new() }
    }

    /// Start validating a field
    pub fn field<'a, T>(&'a mut self, name: &'a str, value: T) -> FieldValidator<'a, T> {
        FieldValidator {
            validator: self,
            name,
            value,
        }
    }

    /// Check if validation passed
    pub fn is_valid(&self) -> bool {
        self.errors.is_empty()
    }

    /// Get validation result
    pub fn validate(self) -> Result<()> {
        if self.errors.is_empty() {
            Ok(())
        } else {
            // Return first error for simplicity
            Err(self.errors.into_iter().next().unwrap())
        }
    }

    /// Get all validation errors
    pub fn errors(&self) -> &[Error] {
        &self.errors
    }

    fn add_error(&mut self, error: Error) {
        self.errors.push(error);
    }
}

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

/// Field validator for chaining validations
#[derive(Debug)]
pub struct FieldValidator<'a, T> {
    validator: &'a mut Validator,
    name: &'a str,
    value: T,
}

impl<'a, T> FieldValidator<'a, T>
where
    T: PartialOrd + std::fmt::Display,
{
    /// Validate range
    pub fn range(self, min: &T, max: &T) -> &'a mut Validator {
        if let Err(e) = validate_range(self.name, &self.value, min, max) {
            self.validator.add_error(e);
        }
        self.validator
    }
}

impl<'a> FieldValidator<'a, &str> {
    /// Validate required
    pub fn required(self) -> &'a mut Validator {
        if let Err(e) = validate_required(self.name, self.value) {
            self.validator.add_error(e);
        }
        self.validator
    }

    /// Validate email
    pub fn email(self) -> &'a mut Validator {
        if let Err(e) = validate_email(self.name, self.value) {
            self.validator.add_error(e);
        }
        self.validator
    }

    /// Validate URL
    pub fn url(self) -> &'a mut Validator {
        if let Err(e) = validate_url(self.name, self.value) {
            self.validator.add_error(e);
        }
        self.validator
    }

    /// Validate regex pattern
    pub fn regex(self, pattern: &str) -> &'a mut Validator {
        if let Err(e) = validate_regex(self.name, self.value, pattern) {
            self.validator.add_error(e);
        }
        self.validator
    }

    /// Validate length
    pub fn length(self, min: Option<usize>, max: Option<usize>) -> &'a mut Validator {
        if let Err(e) = validate_length(self.name, self.value, min, max) {
            self.validator.add_error(e);
        }
        self.validator
    }

    /// Validate one of
    pub fn one_of(self, allowed: &[&str]) -> &'a mut Validator {
        if let Err(e) = validate_one_of(self.name, &self.value, allowed) {
            self.validator.add_error(e);
        }
        self.validator
    }

    /// Validate safe path
    pub fn safe_path(self, allowed_prefix: Option<&str>) -> &'a mut Validator {
        if let Err(e) = validate_safe_path(self.name, self.value, allowed_prefix) {
            self.validator.add_error(e);
        }
        self.validator
    }
}

impl<'a, T> FieldValidator<'a, &[T]> {
    /// Validate array size
    pub fn size(self, min: Option<usize>, max: Option<usize>) -> &'a mut Validator {
        if let Err(e) = validate_array_size(self.name, self.value, min, max) {
            self.validator.add_error(e);
        }
        self.validator
    }
}

impl<'a> FieldValidator<'a, f64> {
    /// Validate percentage
    pub fn percentage(self) -> &'a mut Validator {
        if let Err(e) = validate_percentage(self.name, self.value) {
            self.validator.add_error(e);
        }
        self.validator
    }
}

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

    #[test]
    fn test_validate_range() {
        assert!(validate_range("age", &25, &18, &65).is_ok());
        assert!(validate_range("age", &10, &18, &65).is_err());
        assert!(validate_range("age", &70, &18, &65).is_err());
    }

    #[test]
    fn test_validate_one_of() {
        assert!(validate_one_of("currency", &"USD", &["USD", "EUR", "GBP"]).is_ok());
        assert!(validate_one_of("currency", &"JPY", &["USD", "EUR", "GBP"]).is_err());
    }

    #[test]
    fn test_validate_email() {
        assert!(validate_email("email", "user@example.com").is_ok());
        assert!(validate_email("email", "invalid").is_err());
        assert!(validate_email("email", "@example.com").is_err());
        assert!(validate_email("email", "user@").is_err());
    }

    #[test]
    fn test_validate_safe_path() {
        assert!(validate_safe_path("path", "/tmp/file.txt", Some("/tmp/")).is_ok());
        assert!(validate_safe_path("path", "/tmp/../etc/passwd", None).is_err());
        assert!(validate_safe_path("path", "/etc/passwd", Some("/tmp/")).is_err());
    }

    #[test]
    fn test_validator_builder() {
        let mut v = Validator::new();
        v.field("age", 25).range(&18, &65);
        v.field("email", "user@example.com").email();
        let result = v.validate();

        assert!(result.is_ok());

        let mut v2 = Validator::new();
        v2.field("age", 10).range(&18, &65);
        let result = v2.validate();

        assert!(result.is_err());
    }
}