turul-mcp-server 0.3.18

High-level framework for building Model Context Protocol (MCP) servers
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
//! URI Template System for Dynamic Resources
//!
//! This module provides RFC 6570-inspired URI template support for dynamic MCP resources.
//! It enables patterns like `file:///user/{user_id}.json` with strict validation.

use regex::Regex;
use std::collections::HashMap;

use crate::McpResult;
use turul_mcp_protocol::McpError;

/// A compiled URI template with validation rules
#[derive(Debug, Clone)]
pub struct UriTemplate {
    /// Original template pattern
    pattern: String,
    /// Compiled regex for matching and extracting variables
    regex: Regex,
    /// Variable names in order of appearance
    variables: Vec<String>,
    /// Validation rules for each variable
    validators: HashMap<String, VariableValidator>,
    /// MIME type mapping based on file extension
    mime_type: Option<String>,
}

/// Validation rules for template variables
#[derive(Debug, Clone)]
pub struct VariableValidator {
    /// Regex pattern for valid values
    pattern: Regex,
    /// Human-readable description of valid format
    description: String,
    /// Maximum length
    max_length: usize,
}

impl VariableValidator {
    /// Create validator for user IDs (alphanumeric, underscore, hyphen)
    pub fn user_id() -> Self {
        Self {
            pattern: Regex::new(r"^[A-Za-z0-9_-]{1,128}$").unwrap(),
            description: "alphanumeric characters, underscore, and hyphen (1-128 chars)"
                .to_string(),
            max_length: 128,
        }
    }

    /// Create validator for image formats
    pub fn image_format() -> Self {
        Self {
            pattern: Regex::new(r"^(png|jpg|jpeg|webp|svg)$").unwrap(),
            description: "valid image format: png, jpg, jpeg, webp, svg".to_string(),
            max_length: 8,
        }
    }

    /// Create validator for document formats
    pub fn document_format() -> Self {
        Self {
            pattern: Regex::new(r"^(pdf|txt|md|json|xml|html)$").unwrap(),
            description: "valid document format: pdf, txt, md, json, xml, html".to_string(),
            max_length: 8,
        }
    }

    /// Create custom validator
    pub fn custom(pattern: &str, description: String, max_length: usize) -> McpResult<Self> {
        let regex = Regex::new(pattern)
            .map_err(|e| McpError::tool_execution(&format!("Invalid regex pattern: {}", e)))?;

        Ok(Self {
            pattern: regex,
            description,
            max_length,
        })
    }

    /// Validate a variable value
    pub fn validate(&self, value: &str) -> Result<(), String> {
        if value.len() > self.max_length {
            return Err(format!(
                "Value too long: {} characters (max {})",
                value.len(),
                self.max_length
            ));
        }

        if !self.pattern.is_match(value) {
            return Err(format!("Invalid format. Expected: {}", self.description));
        }

        Ok(())
    }
}

impl UriTemplate {
    /// Create a new URI template with automatic MIME type detection
    pub fn new(pattern: &str) -> McpResult<Self> {
        let mut template = Self {
            pattern: pattern.to_string(),
            regex: Regex::new("").unwrap(), // Placeholder
            variables: Vec::new(),
            validators: HashMap::new(),
            mime_type: Self::detect_mime_type(pattern),
        };

        template.compile()?;
        Ok(template)
    }

    /// Create template with explicit MIME type
    pub fn with_mime_type(pattern: &str, mime_type: &str) -> McpResult<Self> {
        let mut template = Self::new(pattern)?;
        template.mime_type = Some(mime_type.to_string());
        Ok(template)
    }

    /// Add validation rule for a variable
    pub fn with_validator(mut self, variable: &str, validator: VariableValidator) -> Self {
        self.validators.insert(variable.to_string(), validator);
        self
    }

    /// Compile the template pattern into a regex
    fn compile(&mut self) -> McpResult<()> {
        // Extract variables from pattern like {user_id}
        let var_regex = Regex::new(r"\{([^}]+)\}").unwrap();
        let mut regex_pattern = regex::escape(&self.pattern);

        for captures in var_regex.captures_iter(&self.pattern) {
            let var_name = captures.get(1).unwrap().as_str();
            self.variables.push(var_name.to_string());

            // Replace {var_name} with capture group
            let escaped_var = regex::escape(&format!("{{{}}}", var_name));
            regex_pattern = regex_pattern.replace(&escaped_var, "([^/]+)");
        }

        // Anchor the pattern
        regex_pattern = format!("^{}$", regex_pattern);

        self.regex = Regex::new(&regex_pattern)
            .map_err(|e| McpError::tool_execution(&format!("Failed to compile template: {}", e)))?;

        Ok(())
    }

    /// Detect MIME type from file extension in pattern
    fn detect_mime_type(pattern: &str) -> Option<String> {
        if let Some(ext_start) = pattern.rfind('.') {
            let ext = &pattern[ext_start + 1..];
            // Remove any template variables from extension
            let ext = ext.split('}').next().unwrap_or(ext);

            match ext {
                "json" => Some("application/json".to_string()),
                "txt" => Some("text/plain".to_string()),
                "md" => Some("text/markdown".to_string()),
                "html" => Some("text/html".to_string()),
                "xml" => Some("application/xml".to_string()),
                "pdf" => Some("application/pdf".to_string()),
                "png" => Some("image/png".to_string()),
                "jpg" | "jpeg" => Some("image/jpeg".to_string()),
                "webp" => Some("image/webp".to_string()),
                "svg" => Some("image/svg+xml".to_string()),
                _ => None,
            }
        } else {
            None
        }
    }

    /// Resolve template with variables to create actual URI
    pub fn resolve(&self, variables: &HashMap<String, String>) -> McpResult<String> {
        let mut result = self.pattern.clone();

        // Validate all required variables are provided
        for var_name in &self.variables {
            let value = variables
                .get(var_name)
                .ok_or_else(|| McpError::missing_param(var_name))?;

            // Apply validation if rules exist
            if let Some(validator) = self.validators.get(var_name) {
                validator.validate(value).map_err(|e| {
                    McpError::invalid_param_type(var_name, &validator.description, &e)
                })?;
            }

            // Replace variable in pattern
            result = result.replace(&format!("{{{}}}", var_name), value);
        }

        Ok(result)
    }

    /// Extract variables from a URI that matches this template
    pub fn extract(&self, uri: &str) -> McpResult<HashMap<String, String>> {
        let captures = self
            .regex
            .captures(uri)
            .ok_or_else(|| McpError::invalid_param_type("uri", "URI matching template", uri))?;

        let mut variables = HashMap::new();

        for (i, var_name) in self.variables.iter().enumerate() {
            if let Some(value) = captures.get(i + 1) {
                // URL-decode per RFC 6570 — template variables are percent-encoded in URIs
                let value = urlencoding::decode(value.as_str())
                    .map_err(|e| {
                        McpError::invalid_param_type(
                            var_name,
                            "valid UTF-8 after percent-decoding",
                            &e.to_string(),
                        )
                    })?
                    .into_owned();

                // Validate decoded value
                if let Some(validator) = self.validators.get(var_name) {
                    validator.validate(&value).map_err(|e| {
                        McpError::invalid_param_type(var_name, &validator.description, &e)
                    })?;
                }

                variables.insert(var_name.clone(), value);
            }
        }

        Ok(variables)
    }

    /// Check if a URI matches this template
    pub fn matches(&self, uri: &str) -> bool {
        self.regex.is_match(uri)
    }

    /// Get the MIME type for this template
    pub fn mime_type(&self) -> Option<&str> {
        self.mime_type.as_deref()
    }

    /// Get the original pattern
    pub fn pattern(&self) -> &str {
        &self.pattern
    }

    /// Get variable names
    pub fn variables(&self) -> &[String] {
        &self.variables
    }
}

/// Registry for managing URI templates
#[derive(Debug, Default)]
pub struct UriTemplateRegistry {
    templates: Vec<UriTemplate>,
}

impl UriTemplateRegistry {
    /// Create a new empty registry
    pub fn new() -> Self {
        Self::default()
    }

    /// Register a URI template
    pub fn register(&mut self, template: UriTemplate) {
        self.templates.push(template);
    }

    /// Find template that matches the given URI
    pub fn find_matching(&self, uri: &str) -> Option<&UriTemplate> {
        self.templates.iter().find(|t| t.matches(uri))
    }

    /// Get all registered templates
    pub fn templates(&self) -> &[UriTemplate] {
        &self.templates
    }

    /// Resolve a template pattern with variables
    pub fn resolve_pattern(
        &self,
        pattern: &str,
        variables: &HashMap<String, String>,
    ) -> McpResult<String> {
        let template = self
            .templates
            .iter()
            .find(|t| t.pattern() == pattern)
            .ok_or_else(|| {
                McpError::invalid_param_type("pattern", "registered template pattern", pattern)
            })?;

        template.resolve(variables)
    }
}

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

    #[test]
    fn test_user_id_validator() {
        let validator = VariableValidator::user_id();

        // Valid cases
        assert!(validator.validate("user123").is_ok());
        assert!(validator.validate("user_id").is_ok());
        assert!(validator.validate("user-name").is_ok());
        assert!(validator.validate("ABC123").is_ok());

        // Invalid cases
        assert!(validator.validate("user@example.com").is_err()); // @ not allowed
        assert!(validator.validate("user with spaces").is_err()); // spaces not allowed
        assert!(validator.validate("").is_err()); // empty not allowed
        assert!(validator.validate(&"a".repeat(129)).is_err()); // too long
    }

    #[test]
    fn test_image_format_validator() {
        let validator = VariableValidator::image_format();

        assert!(validator.validate("png").is_ok());
        assert!(validator.validate("jpg").is_ok());
        assert!(validator.validate("jpeg").is_ok());
        assert!(validator.validate("webp").is_ok());
        assert!(validator.validate("svg").is_ok());

        assert!(validator.validate("gif").is_err()); // not in allowlist
        assert!(validator.validate("PNG").is_err()); // case sensitive
        assert!(validator.validate("pdf").is_err()); // not an image
    }

    #[test]
    fn test_uri_template_creation() {
        let template = UriTemplate::new("file:///user/{user_id}.json").unwrap();
        assert_eq!(template.pattern(), "file:///user/{user_id}.json");
        assert_eq!(template.variables(), &["user_id"]);
        assert_eq!(template.mime_type(), Some("application/json"));
    }

    #[test]
    fn test_uri_template_resolution() {
        let template = UriTemplate::new("file:///user/{user_id}.json")
            .unwrap()
            .with_validator("user_id", VariableValidator::user_id());

        let mut vars = HashMap::new();
        vars.insert("user_id".to_string(), "alice123".to_string());

        let resolved = template.resolve(&vars).unwrap();
        assert_eq!(resolved, "file:///user/alice123.json");
    }

    #[test]
    fn test_uri_template_extraction() {
        let template = UriTemplate::new("file:///user/{user_id}.json")
            .unwrap()
            .with_validator("user_id", VariableValidator::user_id());

        let vars = template.extract("file:///user/alice123.json").unwrap();
        assert_eq!(vars.get("user_id"), Some(&"alice123".to_string()));
    }

    #[test]
    fn test_uri_template_validation_failure() {
        let template = UriTemplate::new("file:///user/{user_id}.json")
            .unwrap()
            .with_validator("user_id", VariableValidator::user_id());

        // Invalid user_id should fail extraction
        let result = template.extract("file:///user/invalid@user.json");
        assert!(result.is_err());
    }

    #[test]
    fn test_multiple_variables() {
        let template = UriTemplate::new("file:///user/{user_id}/avatar.{format}")
            .unwrap()
            .with_validator("user_id", VariableValidator::user_id())
            .with_validator("format", VariableValidator::image_format());

        let vars = template
            .extract("file:///user/alice123/avatar.png")
            .unwrap();
        assert_eq!(vars.get("user_id"), Some(&"alice123".to_string()));
        assert_eq!(vars.get("format"), Some(&"png".to_string()));
    }

    #[test]
    fn test_registry() {
        let mut registry = UriTemplateRegistry::new();

        let template1 = UriTemplate::new("file:///user/{user_id}.json").unwrap();
        let template2 = UriTemplate::new("file:///user/{user_id}/avatar.{format}").unwrap();

        registry.register(template1);
        registry.register(template2);

        let found = registry.find_matching("file:///user/alice123.json");
        assert!(found.is_some());
        assert_eq!(found.unwrap().pattern(), "file:///user/{user_id}.json");
    }

    #[test]
    fn test_mime_type_detection() {
        assert_eq!(
            UriTemplate::detect_mime_type("file.json"),
            Some("application/json".to_string())
        );
        assert_eq!(
            UriTemplate::detect_mime_type("file.pdf"),
            Some("application/pdf".to_string())
        );
        assert_eq!(
            UriTemplate::detect_mime_type("file.png"),
            Some("image/png".to_string())
        );
        assert_eq!(
            UriTemplate::detect_mime_type("file.txt"),
            Some("text/plain".to_string())
        );
        assert_eq!(UriTemplate::detect_mime_type("file.unknown"), None);
        assert_eq!(UriTemplate::detect_mime_type("file"), None);
    }

    #[test]
    fn test_extract_percent_encoded_hash() {
        let template = UriTemplate::new("custom://items/{item_id}").unwrap();

        // '#' → %23 in the URI
        let vars = template
            .extract("custom://items/PREFIX%23some-value")
            .unwrap();

        assert_eq!(
            vars.get("item_id"),
            Some(&"PREFIX#some-value".to_string()),
            "Percent-encoded '#' should be decoded to '#'"
        );
    }

    #[test]
    fn test_extract_unencoded_values_unchanged() {
        let template = UriTemplate::new("file:///user/{user_id}.json").unwrap();
        let vars = template.extract("file:///user/alice123.json").unwrap();
        assert_eq!(
            vars.get("user_id"),
            Some(&"alice123".to_string()),
            "Plain values should pass through unchanged"
        );
    }

    #[test]
    fn test_extract_percent_encoded_space() {
        let template = UriTemplate::new("file:///docs/{name}").unwrap();
        let vars = template.extract("file:///docs/my%20document").unwrap();
        assert_eq!(
            vars.get("name"),
            Some(&"my document".to_string()),
            "Percent-encoded space should be decoded"
        );
    }

    #[test]
    fn test_extract_percent_encoded_special_chars() {
        let template = UriTemplate::new("data://records/{record_id}").unwrap();

        // '@' → %40, '&' → %26
        let vars = template
            .extract("data://records/user%40host%26extra")
            .unwrap();

        assert_eq!(
            vars.get("record_id"),
            Some(&"user@host&extra".to_string()),
            "Multiple percent-encoded chars should all be decoded"
        );
    }
}