pforge-runtime 0.1.4

Zero-boilerplate MCP server framework with EXTREME TDD methodology
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
use crate::{Error, Result};
#[cfg(test)]
use pforge_config::HandlerRef;
use pforge_config::{ResourceDef, ResourceOperation};
use regex::Regex;
use rustc_hash::FxHashMap;
use std::sync::Arc;

/// Resource handler trait for read/write/subscribe operations
#[async_trait::async_trait]
pub trait ResourceHandler: Send + Sync {
    /// Read resource content
    async fn read(&self, uri: &str, params: FxHashMap<String, String>) -> Result<Vec<u8>>;

    /// Write resource content (if supported)
    async fn write(
        &self,
        uri: &str,
        params: FxHashMap<String, String>,
        content: Vec<u8>,
    ) -> Result<()> {
        let _ = (uri, params, content);
        Err(Error::Handler("Write operation not supported".to_string()))
    }

    /// Subscribe to resource changes (if supported)
    async fn subscribe(&self, uri: &str, params: FxHashMap<String, String>) -> Result<()> {
        let _ = (uri, params);
        Err(Error::Handler(
            "Subscribe operation not supported".to_string(),
        ))
    }
}

/// Resource manager handles URI matching and dispatch
pub struct ResourceManager {
    resources: Vec<ResourceEntry>,
}

struct ResourceEntry {
    uri_template: String,
    pattern: Regex,
    param_names: Vec<String>,
    supports: Vec<ResourceOperation>,
    handler: Arc<dyn ResourceHandler>,
}

impl ResourceManager {
    pub fn new() -> Self {
        Self {
            resources: Vec::new(),
        }
    }

    /// Register a resource with URI template matching
    pub fn register(&mut self, def: ResourceDef, handler: Arc<dyn ResourceHandler>) -> Result<()> {
        let (pattern, param_names) = Self::compile_uri_template(&def.uri_template)?;

        self.resources.push(ResourceEntry {
            uri_template: def.uri_template,
            pattern,
            param_names,
            supports: def.supports,
            handler,
        });

        Ok(())
    }

    /// Match URI and extract parameters (internal use)
    fn match_uri(&self, uri: &str) -> Option<(&ResourceEntry, FxHashMap<String, String>)> {
        for entry in &self.resources {
            if let Some(captures) = entry.pattern.captures(uri) {
                let mut params = FxHashMap::default();

                for (i, name) in entry.param_names.iter().enumerate() {
                    if let Some(value) = captures.get(i + 1) {
                        params.insert(name.clone(), value.as_str().to_string());
                    }
                }

                return Some((entry, params));
            }
        }

        None
    }

    /// Read resource by URI
    pub async fn read(&self, uri: &str) -> Result<Vec<u8>> {
        let (entry, params) = self
            .match_uri(uri)
            .ok_or_else(|| Error::Handler(format!("No resource matches URI: {}", uri)))?;

        if !entry.supports.contains(&ResourceOperation::Read) {
            return Err(Error::Handler(format!(
                "Resource {} does not support read operation",
                entry.uri_template
            )));
        }

        entry.handler.read(uri, params).await
    }

    /// Write resource by URI
    pub async fn write(&self, uri: &str, content: Vec<u8>) -> Result<()> {
        let (entry, params) = self
            .match_uri(uri)
            .ok_or_else(|| Error::Handler(format!("No resource matches URI: {}", uri)))?;

        if !entry.supports.contains(&ResourceOperation::Write) {
            return Err(Error::Handler(format!(
                "Resource {} does not support write operation",
                entry.uri_template
            )));
        }

        entry.handler.write(uri, params, content).await
    }

    /// Subscribe to resource changes
    pub async fn subscribe(&self, uri: &str) -> Result<()> {
        let (entry, params) = self
            .match_uri(uri)
            .ok_or_else(|| Error::Handler(format!("No resource matches URI: {}", uri)))?;

        if !entry.supports.contains(&ResourceOperation::Subscribe) {
            return Err(Error::Handler(format!(
                "Resource {} does not support subscribe operation",
                entry.uri_template
            )));
        }

        entry.handler.subscribe(uri, params).await
    }

    /// Compile URI template to regex pattern
    /// Example: "file:///{path}" -> r"^file:///(.+)$" with param_names = ["path"]
    /// Uses non-greedy matching to handle multiple parameters correctly
    fn compile_uri_template(template: &str) -> Result<(Regex, Vec<String>)> {
        let mut pattern = String::from("^");
        let mut param_names = Vec::new();
        let mut chars = template.chars().peekable();

        while let Some(ch) = chars.next() {
            if ch == '{' {
                // Extract parameter name
                let mut param_name = String::new();
                while let Some(&next_ch) = chars.peek() {
                    if next_ch == '}' {
                        chars.next(); // consume '}'
                        break;
                    }
                    param_name.push(chars.next().unwrap());
                }

                if param_name.is_empty() {
                    return Err(Error::Handler(
                        "Empty parameter name in URI template".to_string(),
                    ));
                }

                param_names.push(param_name);

                // Check what comes after the parameter
                // If there's a '/' after, match non-greedy up to next '/'
                // Otherwise, match greedy to end
                if chars.peek() == Some(&'/') {
                    pattern.push_str("([^/]+)"); // Segment matching
                } else {
                    pattern.push_str("(.+)"); // Greedy path matching
                }
            } else {
                // Escape regex special characters
                if ".*+?^$[](){}|\\".contains(ch) {
                    pattern.push('\\');
                }
                pattern.push(ch);
            }
        }

        pattern.push('$');

        let regex = Regex::new(&pattern)
            .map_err(|e| Error::Handler(format!("Invalid URI template regex: {}", e)))?;

        Ok((regex, param_names))
    }

    /// List all registered resource templates
    pub fn list_templates(&self) -> Vec<&str> {
        self.resources
            .iter()
            .map(|e| e.uri_template.as_str())
            .collect()
    }
}

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

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

    struct TestResourceHandler {
        read_response: Vec<u8>,
    }

    #[async_trait::async_trait]
    impl ResourceHandler for TestResourceHandler {
        async fn read(&self, _uri: &str, _params: FxHashMap<String, String>) -> Result<Vec<u8>> {
            Ok(self.read_response.clone())
        }

        async fn write(
            &self,
            _uri: &str,
            _params: FxHashMap<String, String>,
            _content: Vec<u8>,
        ) -> Result<()> {
            Ok(())
        }
    }

    #[test]
    fn test_uri_template_compilation() {
        let (pattern, params) = ResourceManager::compile_uri_template("file:///{path}").unwrap();
        assert_eq!(params, vec!["path"]);

        let captures = pattern.captures("file:///home/user/test.txt").unwrap();
        assert_eq!(captures.get(1).unwrap().as_str(), "home/user/test.txt");
    }

    #[test]
    fn test_uri_template_multiple_params() {
        let (pattern, params) =
            ResourceManager::compile_uri_template("api://{service}/{resource}").unwrap();
        assert_eq!(params, vec!["service", "resource"]);

        let captures = pattern.captures("api://users/profile").unwrap();
        assert_eq!(captures.get(1).unwrap().as_str(), "users");
        assert_eq!(captures.get(2).unwrap().as_str(), "profile");
    }

    #[tokio::test]
    async fn test_resource_registration_and_matching() {
        let mut manager = ResourceManager::new();

        let def = ResourceDef {
            uri_template: "file:///{path}".to_string(),
            handler: HandlerRef {
                path: "test::handler".to_string(),
                inline: None,
            },
            supports: vec![ResourceOperation::Read],
        };

        let handler = Arc::new(TestResourceHandler {
            read_response: b"test content".to_vec(),
        });

        manager.register(def, handler).unwrap();

        let (entry, params) = manager.match_uri("file:///test.txt").unwrap();
        assert_eq!(entry.uri_template, "file:///{path}");
        assert_eq!(params.get("path").unwrap(), "test.txt");
    }

    #[tokio::test]
    async fn test_resource_read() {
        let mut manager = ResourceManager::new();

        let def = ResourceDef {
            uri_template: "file:///{path}".to_string(),
            handler: HandlerRef {
                path: "test::handler".to_string(),
                inline: None,
            },
            supports: vec![ResourceOperation::Read],
        };

        let handler = Arc::new(TestResourceHandler {
            read_response: b"hello world".to_vec(),
        });

        manager.register(def, handler).unwrap();

        let content = manager.read("file:///test.txt").await.unwrap();
        assert_eq!(content, b"hello world");
    }

    #[tokio::test]
    async fn test_resource_unsupported_operation() {
        let mut manager = ResourceManager::new();

        let def = ResourceDef {
            uri_template: "file:///{path}".to_string(),
            handler: HandlerRef {
                path: "test::handler".to_string(),
                inline: None,
            },
            supports: vec![ResourceOperation::Read],
        };

        let handler = Arc::new(TestResourceHandler {
            read_response: b"test".to_vec(),
        });

        manager.register(def, handler).unwrap();

        let result = manager.write("file:///test.txt", b"data".to_vec()).await;
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("does not support write"));
    }

    /// Test resource write when operation is supported
    #[tokio::test]
    async fn test_resource_write_supported() {
        let mut manager = ResourceManager::new();

        let def = ResourceDef {
            uri_template: "file:///{path}".to_string(),
            handler: HandlerRef {
                path: "test::handler".to_string(),
                inline: None,
            },
            supports: vec![ResourceOperation::Read, ResourceOperation::Write],
        };

        let handler = Arc::new(TestResourceHandler {
            read_response: b"test".to_vec(),
        });

        manager.register(def, handler).unwrap();

        // This should succeed - handler implements write returning Ok(())
        let result = manager.write("file:///test.txt", b"data".to_vec()).await;
        assert!(result.is_ok());
    }

    /// Handler that uses default write/subscribe implementations
    struct ReadOnlyResourceHandler;

    #[async_trait::async_trait]
    impl ResourceHandler for ReadOnlyResourceHandler {
        async fn read(&self, _uri: &str, _params: FxHashMap<String, String>) -> Result<Vec<u8>> {
            Ok(b"read only content".to_vec())
        }
        // Note: write and subscribe use DEFAULT implementations that return errors
    }

    /// Test that default write implementation returns error
    /// This catches the mutation: ResourceHandler::write -> Result<()> with Ok(())
    #[tokio::test]
    async fn test_default_write_returns_error() {
        let handler = ReadOnlyResourceHandler;
        let result = handler.write("uri", FxHashMap::default(), vec![]).await;
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Write operation not supported"));
    }

    /// Test that default subscribe implementation returns error
    #[tokio::test]
    async fn test_default_subscribe_returns_error() {
        let handler = ReadOnlyResourceHandler;
        let result = handler.subscribe("uri", FxHashMap::default()).await;
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Subscribe operation not supported"));
    }

    /// Test subscribe on unsupported resource
    #[tokio::test]
    async fn test_subscribe_not_supported() {
        let mut manager = ResourceManager::new();

        let def = ResourceDef {
            uri_template: "file:///{path}".to_string(),
            handler: HandlerRef {
                path: "test::handler".to_string(),
                inline: None,
            },
            supports: vec![ResourceOperation::Read], // No Subscribe support
        };

        let handler = Arc::new(TestResourceHandler {
            read_response: b"test".to_vec(),
        });

        manager.register(def, handler).unwrap();

        // Subscribe should fail - operation not supported
        let result = manager.subscribe("file:///test.txt").await;
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("does not support subscribe"));
    }

    /// Test subscribe on supported resource
    /// Handler that supports subscribe
    struct SubscribableResourceHandler;

    #[async_trait::async_trait]
    impl ResourceHandler for SubscribableResourceHandler {
        async fn read(&self, _uri: &str, _params: FxHashMap<String, String>) -> Result<Vec<u8>> {
            Ok(b"content".to_vec())
        }

        async fn subscribe(&self, _uri: &str, _params: FxHashMap<String, String>) -> Result<()> {
            Ok(())
        }
    }

    #[tokio::test]
    async fn test_subscribe_supported() {
        let mut manager = ResourceManager::new();

        let def = ResourceDef {
            uri_template: "events:///{topic}".to_string(),
            handler: HandlerRef {
                path: "test::handler".to_string(),
                inline: None,
            },
            supports: vec![ResourceOperation::Read, ResourceOperation::Subscribe],
        };

        let handler = Arc::new(SubscribableResourceHandler);
        manager.register(def, handler).unwrap();

        // Subscribe should succeed
        let result = manager.subscribe("events:///updates").await;
        assert!(result.is_ok());
    }
}