things3-cli 1.0.0

CLI tool for Things 3 with integrated MCP server
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
//! Comprehensive tests for the MCP middleware system

use std::time::Duration;
use things3_cli::mcp::{
    middleware::{
        LoggingConfig, LoggingMiddleware, McpMiddleware, MiddlewareChain, MiddlewareConfig,
        MiddlewareContext, MiddlewareResult, PerformanceConfig, PerformanceMiddleware,
        SecurityConfig, ValidationConfig, ValidationMiddleware,
    },
    CallToolRequest, CallToolResult, Content, McpError, McpResult,
};
use things3_core::ThingsConfig;
use tokio::time::sleep;

/// Test middleware that counts requests
#[derive(Clone)]
struct CountingMiddleware {
    name: String,
    priority: i32,
    before_count: std::sync::Arc<std::sync::atomic::AtomicUsize>,
    after_count: std::sync::Arc<std::sync::atomic::AtomicUsize>,
    error_count: std::sync::Arc<std::sync::atomic::AtomicUsize>,
}

impl CountingMiddleware {
    fn new(name: &str, priority: i32) -> Self {
        Self {
            name: name.to_string(),
            priority,
            before_count: std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)),
            after_count: std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)),
            error_count: std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)),
        }
    }

    fn get_before_count(&self) -> usize {
        self.before_count.load(std::sync::atomic::Ordering::Relaxed)
    }

    fn get_after_count(&self) -> usize {
        self.after_count.load(std::sync::atomic::Ordering::Relaxed)
    }

    #[allow(dead_code)]
    fn get_error_count(&self) -> usize {
        self.error_count.load(std::sync::atomic::Ordering::Relaxed)
    }
}

#[async_trait::async_trait]
impl McpMiddleware for CountingMiddleware {
    fn name(&self) -> &str {
        &self.name
    }

    fn priority(&self) -> i32 {
        self.priority
    }

    async fn before_request(
        &self,
        _request: &CallToolRequest,
        _context: &mut MiddlewareContext,
    ) -> McpResult<MiddlewareResult> {
        self.before_count
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        Ok(MiddlewareResult::Continue)
    }

    async fn after_request(
        &self,
        _request: &CallToolRequest,
        _response: &mut CallToolResult,
        _context: &mut MiddlewareContext,
    ) -> McpResult<MiddlewareResult> {
        self.after_count
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        Ok(MiddlewareResult::Continue)
    }

    async fn on_error(
        &self,
        _request: &CallToolRequest,
        _error: &McpError,
        _context: &mut MiddlewareContext,
    ) -> McpResult<MiddlewareResult> {
        self.error_count
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        Ok(MiddlewareResult::Continue)
    }
}

/// Test middleware that stops execution
struct StoppingMiddleware {
    name: String,
    priority: i32,
    stop_after: usize,
    call_count: std::sync::atomic::AtomicUsize,
}

impl StoppingMiddleware {
    fn new(name: &str, priority: i32, stop_after: usize) -> Self {
        Self {
            name: name.to_string(),
            priority,
            stop_after,
            call_count: std::sync::atomic::AtomicUsize::new(0),
        }
    }
}

#[async_trait::async_trait]
impl McpMiddleware for StoppingMiddleware {
    fn name(&self) -> &str {
        &self.name
    }

    fn priority(&self) -> i32 {
        self.priority
    }

    async fn before_request(
        &self,
        _request: &CallToolRequest,
        _context: &mut MiddlewareContext,
    ) -> McpResult<MiddlewareResult> {
        let count = self
            .call_count
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);

        if count >= self.stop_after {
            Ok(MiddlewareResult::Stop(CallToolResult {
                content: vec![Content::Text {
                    text: "Stopped by middleware".to_string(),
                }],
                is_error: false,
            }))
        } else {
            Ok(MiddlewareResult::Continue)
        }
    }
}

/// Test middleware that modifies responses
struct ResponseModifyingMiddleware {
    name: String,
    priority: i32,
    prefix: String,
}

impl ResponseModifyingMiddleware {
    fn new(name: &str, priority: i32, prefix: &str) -> Self {
        Self {
            name: name.to_string(),
            priority,
            prefix: prefix.to_string(),
        }
    }
}

#[async_trait::async_trait]
impl McpMiddleware for ResponseModifyingMiddleware {
    fn name(&self) -> &str {
        &self.name
    }

    fn priority(&self) -> i32 {
        self.priority
    }

    async fn after_request(
        &self,
        _request: &CallToolRequest,
        response: &mut CallToolResult,
        _context: &mut MiddlewareContext,
    ) -> McpResult<MiddlewareResult> {
        if let Some(Content::Text { text }) = response.content.first_mut() {
            *text = format!("{}{}", self.prefix, text);
        }
        Ok(MiddlewareResult::Continue)
    }
}

#[tokio::test]
async fn test_middleware_chain_basic_execution() {
    let chain = MiddlewareChain::new()
        .add_middleware(CountingMiddleware::new("counter1", 100))
        .add_middleware(CountingMiddleware::new("counter2", 200));

    let request = CallToolRequest {
        name: "test_tool".to_string(),
        arguments: Some(serde_json::json!({"param": "value"})),
    };

    let handler = |_req: CallToolRequest| async move {
        Ok(CallToolResult {
            content: vec![Content::Text {
                text: "Test response".to_string(),
            }],
            is_error: false,
        })
    };

    let result = chain.execute(request, handler).await;
    assert!(result.is_ok());
}

#[tokio::test]
async fn test_middleware_priority_ordering() {
    let counter1 = CountingMiddleware::new("counter1", 200);
    let counter2 = CountingMiddleware::new("counter2", 100);

    let chain = MiddlewareChain::new()
        .add_middleware(counter1.clone())
        .add_middleware(counter2.clone());

    let request = CallToolRequest {
        name: "test_tool".to_string(),
        arguments: None,
    };

    let handler = |_req: CallToolRequest| async move {
        Ok(CallToolResult {
            content: vec![Content::Text {
                text: "Test response".to_string(),
            }],
            is_error: false,
        })
    };

    let _result = chain.execute(request, handler).await;

    // Both middlewares should have been called
    assert_eq!(counter1.get_before_count(), 1);
    assert_eq!(counter1.get_after_count(), 1);
    assert_eq!(counter2.get_before_count(), 1);
    assert_eq!(counter2.get_after_count(), 1);
}

#[tokio::test]
async fn test_middleware_stop_execution() {
    let chain = MiddlewareChain::new()
        .add_middleware(StoppingMiddleware::new("stopper", 50, 0)) // Stop immediately
        .add_middleware(CountingMiddleware::new("counter", 100));

    let request = CallToolRequest {
        name: "test_tool".to_string(),
        arguments: None,
    };

    let handler = |_req: CallToolRequest| async move {
        Ok(CallToolResult {
            content: vec![Content::Text {
                text: "Should not reach here".to_string(),
            }],
            is_error: false,
        })
    };

    let result = chain.execute(request, handler).await;
    assert!(result.is_ok());

    let response = result.unwrap();
    assert_eq!(response.content[0].text(), "Stopped by middleware");
}

#[tokio::test]
async fn test_middleware_response_modification() {
    let chain = MiddlewareChain::new()
        .add_middleware(ResponseModifyingMiddleware::new(
            "modifier1",
            200,
            "[MOD1] ",
        ))
        .add_middleware(ResponseModifyingMiddleware::new(
            "modifier2",
            100,
            "[MOD2] ",
        ));

    let request = CallToolRequest {
        name: "test_tool".to_string(),
        arguments: None,
    };

    let handler = |_req: CallToolRequest| async move {
        Ok(CallToolResult {
            content: vec![Content::Text {
                text: "Original response".to_string(),
            }],
            is_error: false,
        })
    };

    let result = chain.execute(request, handler).await;
    assert!(result.is_ok());

    let response = result.unwrap();
    assert_eq!(
        response.content[0].text(),
        "[MOD1] [MOD2] Original response"
    );
}

#[tokio::test]
async fn test_validation_middleware() {
    let chain = MiddlewareChain::new()
        .add_middleware(ValidationMiddleware::strict())
        .add_middleware(CountingMiddleware::new("counter", 100));

    // Test valid request
    let valid_request = CallToolRequest {
        name: "valid_tool".to_string(),
        arguments: Some(serde_json::json!({"param": "value"})),
    };

    let handler = |_req: CallToolRequest| async move {
        Ok(CallToolResult {
            content: vec![Content::Text {
                text: "Valid response".to_string(),
            }],
            is_error: false,
        })
    };

    let result = chain.execute(valid_request, handler).await;
    assert!(result.is_ok());

    // Test invalid request (empty name)
    let invalid_request = CallToolRequest {
        name: String::new(),
        arguments: None,
    };

    let result = chain.execute(invalid_request, handler).await;
    assert!(result.is_err());
}

#[tokio::test]
async fn test_logging_middleware() {
    let chain = MiddlewareChain::new()
        .add_middleware(LoggingMiddleware::info())
        .add_middleware(CountingMiddleware::new("counter", 100));

    let request = CallToolRequest {
        name: "test_tool".to_string(),
        arguments: None,
    };

    let handler = |_req: CallToolRequest| async move {
        Ok(CallToolResult {
            content: vec![Content::Text {
                text: "Test response".to_string(),
            }],
            is_error: false,
        })
    };

    let result = chain.execute(request, handler).await;
    assert!(result.is_ok());
}

#[tokio::test]
async fn test_performance_middleware() {
    let chain = MiddlewareChain::new()
        .add_middleware(PerformanceMiddleware::with_threshold(
            Duration::from_millis(50),
        ))
        .add_middleware(CountingMiddleware::new("counter", 100));

    let request = CallToolRequest {
        name: "test_tool".to_string(),
        arguments: None,
    };

    let handler = |_req: CallToolRequest| async move {
        // Simulate slow operation
        sleep(Duration::from_millis(100)).await;
        Ok(CallToolResult {
            content: vec![Content::Text {
                text: "Slow response".to_string(),
            }],
            is_error: false,
        })
    };

    let result = chain.execute(request, handler).await;
    assert!(result.is_ok());
}

#[tokio::test]
async fn test_middleware_error_handling() {
    let chain = MiddlewareChain::new().add_middleware(CountingMiddleware::new("counter", 100));

    let request = CallToolRequest {
        name: "test_tool".to_string(),
        arguments: None,
    };

    let handler =
        |_req: CallToolRequest| async move { Err(McpError::internal_error("Test error")) };

    let result = chain.execute(request, handler).await;
    assert!(result.is_err());
}

#[tokio::test]
async fn test_middleware_config_build_chain() {
    let config = MiddlewareConfig {
        logging: LoggingConfig {
            enabled: true,
            level: "debug".to_string(),
        },
        validation: ValidationConfig {
            enabled: true,
            strict_mode: true,
        },
        performance: PerformanceConfig {
            enabled: true,
            slow_request_threshold_ms: 500,
        },
        security: SecurityConfig::default(),
    };

    let chain = config.build_chain();
    assert!(!chain.is_empty());
    assert!(chain.len() >= 3); // Should have logging, validation, and performance
}

#[tokio::test]
async fn test_middleware_context_metadata() {
    let mut context = MiddlewareContext::new("test-123".to_string());

    // Test setting and getting metadata
    context.set_metadata("key1".to_string(), serde_json::json!("value1"));
    context.set_metadata("key2".to_string(), serde_json::json!(42));

    assert_eq!(
        context.get_metadata("key1"),
        Some(&serde_json::json!("value1"))
    );
    assert_eq!(context.get_metadata("key2"), Some(&serde_json::json!(42)));
    assert_eq!(context.get_metadata("nonexistent"), None);

    // Test elapsed time
    sleep(Duration::from_millis(10)).await;
    let elapsed = context.elapsed();
    assert!(elapsed >= Duration::from_millis(10));
}

#[tokio::test]
async fn test_middleware_chain_with_mcp_server() {
    // Create a test database (this would need to be mocked in a real test)
    // For now, we'll just test the middleware chain creation
    let _config = ThingsConfig::default();
    let middleware_config = MiddlewareConfig {
        logging: LoggingConfig {
            enabled: true,
            level: "info".to_string(),
        },
        validation: ValidationConfig {
            enabled: true,
            strict_mode: false,
        },
        performance: PerformanceConfig {
            enabled: true,
            slow_request_threshold_ms: 1000,
        },
        security: SecurityConfig::default(),
    };

    // Test that we can create a middleware chain
    let chain = middleware_config.build_chain();
    assert!(!chain.is_empty());

    // Test that we can execute a simple request
    let request = CallToolRequest {
        name: "test_tool".to_string(),
        arguments: Some(serde_json::json!({"param": "value"})),
    };

    let handler = |_req: CallToolRequest| async move {
        Ok(CallToolResult {
            content: vec![Content::Text {
                text: "Test response".to_string(),
            }],
            is_error: false,
        })
    };

    let result = chain.execute(request, handler).await;
    assert!(result.is_ok());
}

#[tokio::test]
async fn test_multiple_middleware_execution_order() {
    let counter1 = CountingMiddleware::new("counter1", 100);
    let counter2 = CountingMiddleware::new("counter2", 200);
    let counter3 = CountingMiddleware::new("counter3", 50);

    let chain = MiddlewareChain::new()
        .add_middleware(counter1.clone())
        .add_middleware(counter2.clone())
        .add_middleware(counter3.clone());

    let request = CallToolRequest {
        name: "test_tool".to_string(),
        arguments: None,
    };

    let handler = |_req: CallToolRequest| async move {
        Ok(CallToolResult {
            content: vec![Content::Text {
                text: "Test response".to_string(),
            }],
            is_error: false,
        })
    };

    let _result = chain.execute(request, handler).await;

    // All middlewares should have been called
    assert_eq!(counter1.get_before_count(), 1);
    assert_eq!(counter1.get_after_count(), 1);
    assert_eq!(counter2.get_before_count(), 1);
    assert_eq!(counter2.get_after_count(), 1);
    assert_eq!(counter3.get_before_count(), 1);
    assert_eq!(counter3.get_after_count(), 1);
}

#[tokio::test]
async fn test_middleware_chain_empty() {
    let chain = MiddlewareChain::new();
    assert!(chain.is_empty());
    assert_eq!(chain.len(), 0);

    let request = CallToolRequest {
        name: "test_tool".to_string(),
        arguments: None,
    };

    let handler = |_req: CallToolRequest| async move {
        Ok(CallToolResult {
            content: vec![Content::Text {
                text: "Test response".to_string(),
            }],
            is_error: false,
        })
    };

    let result = chain.execute(request, handler).await;
    assert!(result.is_ok());
}

// Helper trait for easier testing
trait ContentExt {
    fn text(&self) -> &str;
}

impl ContentExt for Content {
    fn text(&self) -> &str {
        match self {
            Content::Text { text } => text,
        }
    }
}