mcplint 0.4.0

MCP Server Testing, Fuzzing, and Security Scanning Platform
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
//! Crash Detection - Detect and classify crashes and hangs
//!
//! Analyzes responses from MCP servers to detect crashes,
//! hangs, and other interesting behaviors.

use serde::{Deserialize, Serialize};
use serde_json::Value;

use super::corpus::{CrashType, InterestingReason};

/// Detects and classifies crashes/hangs/errors
pub struct CrashDetector {
    /// Timeout threshold in milliseconds
    timeout_ms: u64,
}

impl CrashDetector {
    /// Create a new crash detector
    pub fn new(timeout_ms: u64) -> Self {
        Self { timeout_ms }
    }

    /// Analyze a fuzz response for crash indicators
    pub fn analyze(&self, response: &FuzzResponse) -> CrashAnalysis {
        match &response.result {
            FuzzResponseResult::Success(value) => self.analyze_success(value),
            FuzzResponseResult::Error(e) => self.classify_error(e),
            FuzzResponseResult::Timeout => CrashAnalysis::Hang(HangInfo {
                timeout_ms: self.timeout_ms,
            }),
            FuzzResponseResult::ConnectionLost(reason) => CrashAnalysis::Crash(CrashInfo {
                crash_type: CrashType::ConnectionDrop,
                message: reason.clone(),
                stack_trace: None,
            }),
            FuzzResponseResult::ProcessExit(code) => {
                let crash_type = match *code {
                    139 => CrashType::Segfault,         // SIGSEGV
                    134 => CrashType::AssertionFailure, // SIGABRT
                    137 => CrashType::OutOfMemory,      // SIGKILL (often OOM)
                    _ => {
                        if *code != 0 {
                            CrashType::Panic
                        } else {
                            return CrashAnalysis::None;
                        }
                    }
                };

                CrashAnalysis::Crash(CrashInfo {
                    crash_type,
                    message: format!("Process exited with code {}", code),
                    stack_trace: None,
                })
            }
        }
    }

    /// Analyze successful response for interesting patterns
    fn analyze_success(&self, value: &Value) -> CrashAnalysis {
        // Check for error-like content in success response
        if let Some(obj) = value.as_object() {
            // Some servers return errors in result field
            if obj.contains_key("error") || obj.contains_key("errorCode") {
                return CrashAnalysis::Interesting(InterestingReason::UnexpectedSuccess);
            }

            // Check for stack traces in result
            if let Some(s) = obj.get("message").and_then(|m| m.as_str()) {
                if s.contains("panic") || s.contains("stack backtrace") || s.contains("Error:") {
                    return CrashAnalysis::Interesting(InterestingReason::ProtocolViolation);
                }
            }
        }

        CrashAnalysis::None
    }

    /// Classify error response
    fn classify_error(&self, error: &JsonRpcError) -> CrashAnalysis {
        // Check for crash indicators in error message
        let message = &error.message;

        // Panic detection
        if message.contains("panic")
            || message.contains("panicked at")
            || message.contains("stack backtrace")
            || message.contains("thread 'main' panicked")
        {
            return CrashAnalysis::Crash(CrashInfo {
                crash_type: CrashType::Panic,
                message: message.clone(),
                stack_trace: Self::extract_stack_trace(message),
            });
        }

        // Memory error detection
        if message.contains("out of memory")
            || message.contains("allocation")
            || message.contains("memory exhausted")
            || message.contains("OOM")
        {
            return CrashAnalysis::Crash(CrashInfo {
                crash_type: CrashType::OutOfMemory,
                message: message.clone(),
                stack_trace: None,
            });
        }

        // Assertion failure detection
        if message.contains("assertion failed")
            || message.contains("assert!")
            || message.contains("debug_assert")
        {
            return CrashAnalysis::Crash(CrashInfo {
                crash_type: CrashType::AssertionFailure,
                message: message.clone(),
                stack_trace: Self::extract_stack_trace(message),
            });
        }

        // Segfault detection
        if message.contains("SIGSEGV")
            || message.contains("segmentation fault")
            || message.contains("invalid memory")
            || message.contains("null pointer")
        {
            return CrashAnalysis::Crash(CrashInfo {
                crash_type: CrashType::Segfault,
                message: message.clone(),
                stack_trace: Self::extract_stack_trace(message),
            });
        }

        // Check for interesting (non-crash) conditions
        match error.code {
            // Standard JSON-RPC errors
            -32700 => CrashAnalysis::Interesting(InterestingReason::ProtocolViolation), // Parse error
            -32600 => CrashAnalysis::Interesting(InterestingReason::ProtocolViolation), // Invalid request
            -32601 => CrashAnalysis::None, // Method not found (expected for fuzzing)
            -32602 => CrashAnalysis::None, // Invalid params (expected)
            -32603 => {
                // Internal error - might be interesting
                if message.len() > 100 {
                    // Verbose internal error might leak info
                    CrashAnalysis::Interesting(InterestingReason::ProtocolViolation)
                } else {
                    CrashAnalysis::None
                }
            }
            // Non-standard error codes are interesting
            code if !((-32099..=-32000).contains(&code) || (-32768..=-32600).contains(&code)) => {
                CrashAnalysis::Interesting(InterestingReason::NewErrorCode)
            }
            _ => CrashAnalysis::None,
        }
    }

    /// Extract stack trace from error message
    fn extract_stack_trace(message: &str) -> Option<String> {
        // Look for common stack trace patterns
        if let Some(idx) = message.find("stack backtrace:") {
            return Some(message[idx..].to_string());
        }
        if let Some(idx) = message.find("at ") {
            let remainder = &message[idx..];
            if remainder.contains(".rs:") {
                return Some(remainder.to_string());
            }
        }
        None
    }
}

/// Result of a fuzz request
#[derive(Debug, Clone)]
pub struct FuzzResponse {
    /// The result of the request
    pub result: FuzzResponseResult,
    /// Response time in milliseconds
    pub response_time_ms: u64,
}

impl FuzzResponse {
    /// Create a success response
    pub fn success(value: Value) -> Self {
        Self {
            result: FuzzResponseResult::Success(value),
            response_time_ms: 0,
        }
    }

    /// Create an error response
    pub fn error(code: i32, message: impl Into<String>) -> Self {
        Self {
            result: FuzzResponseResult::Error(JsonRpcError {
                code,
                message: message.into(),
                data: None,
            }),
            response_time_ms: 0,
        }
    }

    /// Create a timeout response
    pub fn timeout() -> Self {
        Self {
            result: FuzzResponseResult::Timeout,
            response_time_ms: 0,
        }
    }

    /// Create a connection lost response
    pub fn connection_lost(reason: impl Into<String>) -> Self {
        Self {
            result: FuzzResponseResult::ConnectionLost(reason.into()),
            response_time_ms: 0,
        }
    }

    /// Create a process exit response
    pub fn process_exit(code: i32) -> Self {
        Self {
            result: FuzzResponseResult::ProcessExit(code),
            response_time_ms: 0,
        }
    }

    /// Set response time
    pub fn with_time(mut self, ms: u64) -> Self {
        self.response_time_ms = ms;
        self
    }

    /// Create from a JSON-RPC response
    pub fn from_jsonrpc(value: &Value) -> Self {
        if let Some(result) = value.get("result") {
            return Self::success(result.clone());
        }

        if let Some(error) = value.get("error") {
            let code = error.get("code").and_then(|c| c.as_i64()).unwrap_or(-32603) as i32;
            let message = error
                .get("message")
                .and_then(|m| m.as_str())
                .unwrap_or("Unknown error")
                .to_string();
            let data = error.get("data").cloned();

            return Self {
                result: FuzzResponseResult::Error(JsonRpcError {
                    code,
                    message,
                    data,
                }),
                response_time_ms: 0,
            };
        }

        Self::error(-32603, "Invalid JSON-RPC response")
    }
}

/// The result type of a fuzz response
#[derive(Debug, Clone)]
pub enum FuzzResponseResult {
    /// Successful response with result value
    Success(Value),
    /// Error response
    Error(JsonRpcError),
    /// Request timed out
    Timeout,
    /// Connection was lost
    ConnectionLost(String),
    /// Server process exited
    ProcessExit(i32),
}

/// JSON-RPC error structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JsonRpcError {
    /// Error code
    pub code: i32,
    /// Error message
    pub message: String,
    /// Optional error data
    pub data: Option<Value>,
}

/// Analysis result from crash detector
#[derive(Debug, Clone)]
pub enum CrashAnalysis {
    /// No crash or interesting behavior
    None,
    /// Crash detected
    Crash(CrashInfo),
    /// Hang detected
    Hang(HangInfo),
    /// Interesting (non-crash) behavior
    Interesting(InterestingReason),
}

impl CrashAnalysis {
    /// Check if this is a crash
    pub fn is_crash(&self) -> bool {
        matches!(self, CrashAnalysis::Crash(_))
    }

    /// Check if this is a hang
    pub fn is_hang(&self) -> bool {
        matches!(self, CrashAnalysis::Hang(_))
    }

    /// Check if this is interesting
    pub fn is_interesting(&self) -> bool {
        matches!(self, CrashAnalysis::Interesting(_))
    }
}

/// Information about a detected crash
#[derive(Debug, Clone)]
pub struct CrashInfo {
    /// Type of crash
    pub crash_type: CrashType,
    /// Error message
    pub message: String,
    /// Stack trace if available
    pub stack_trace: Option<String>,
}

/// Information about a detected hang
#[derive(Debug, Clone)]
pub struct HangInfo {
    /// Timeout that was exceeded
    pub timeout_ms: u64,
}

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

    #[test]
    fn detect_panic() {
        let detector = CrashDetector::new(5000);

        let response = FuzzResponse::error(-32603, "thread 'main' panicked at 'assertion failed'");

        let analysis = detector.analyze(&response);
        assert!(matches!(
            analysis,
            CrashAnalysis::Crash(CrashInfo {
                crash_type: CrashType::Panic,
                ..
            })
        ));
    }

    #[test]
    fn detect_oom() {
        let detector = CrashDetector::new(5000);

        let response = FuzzResponse::error(-32603, "out of memory: allocation failed");

        let analysis = detector.analyze(&response);
        assert!(matches!(
            analysis,
            CrashAnalysis::Crash(CrashInfo {
                crash_type: CrashType::OutOfMemory,
                ..
            })
        ));
    }

    #[test]
    fn detect_timeout() {
        let detector = CrashDetector::new(5000);

        let response = FuzzResponse::timeout();

        let analysis = detector.analyze(&response);
        assert!(matches!(analysis, CrashAnalysis::Hang(_)));
    }

    #[test]
    fn detect_process_exit() {
        let detector = CrashDetector::new(5000);

        let response = FuzzResponse::process_exit(139);

        let analysis = detector.analyze(&response);
        assert!(matches!(
            analysis,
            CrashAnalysis::Crash(CrashInfo {
                crash_type: CrashType::Segfault,
                ..
            })
        ));
    }

    #[test]
    fn normal_error_not_crash() {
        let detector = CrashDetector::new(5000);

        let response = FuzzResponse::error(-32601, "Method not found");

        let analysis = detector.analyze(&response);
        assert!(matches!(analysis, CrashAnalysis::None));
    }

    #[test]
    fn from_jsonrpc() {
        let success = serde_json::json!({
            "jsonrpc": "2.0",
            "result": {"data": "test"},
            "id": 1
        });

        let response = FuzzResponse::from_jsonrpc(&success);
        assert!(matches!(response.result, FuzzResponseResult::Success(_)));

        let error = serde_json::json!({
            "jsonrpc": "2.0",
            "error": {"code": -32601, "message": "Not found"},
            "id": 1
        });

        let response = FuzzResponse::from_jsonrpc(&error);
        assert!(matches!(response.result, FuzzResponseResult::Error(_)));
    }

    #[test]
    fn from_jsonrpc_invalid_response() {
        let invalid = serde_json::json!({
            "jsonrpc": "2.0",
            "id": 1
        });

        let response = FuzzResponse::from_jsonrpc(&invalid);
        assert!(matches!(response.result, FuzzResponseResult::Error(_)));
    }

    #[test]
    fn detect_assertion_failure() {
        let detector = CrashDetector::new(5000);
        let response = FuzzResponse::error(-32603, "assertion failed: x > 0");

        let analysis = detector.analyze(&response);
        assert!(matches!(
            analysis,
            CrashAnalysis::Crash(CrashInfo {
                crash_type: CrashType::AssertionFailure,
                ..
            })
        ));
    }

    #[test]
    fn detect_segfault() {
        let detector = CrashDetector::new(5000);
        let response = FuzzResponse::error(-32603, "SIGSEGV: segmentation fault");

        let analysis = detector.analyze(&response);
        assert!(matches!(
            analysis,
            CrashAnalysis::Crash(CrashInfo {
                crash_type: CrashType::Segfault,
                ..
            })
        ));
    }

    #[test]
    fn detect_null_pointer() {
        let detector = CrashDetector::new(5000);
        let response = FuzzResponse::error(-32603, "null pointer dereference");

        let analysis = detector.analyze(&response);
        assert!(matches!(
            analysis,
            CrashAnalysis::Crash(CrashInfo {
                crash_type: CrashType::Segfault,
                ..
            })
        ));
    }

    #[test]
    fn detect_connection_lost() {
        let detector = CrashDetector::new(5000);
        let response = FuzzResponse::connection_lost("connection reset by peer");

        let analysis = detector.analyze(&response);
        assert!(matches!(
            analysis,
            CrashAnalysis::Crash(CrashInfo {
                crash_type: CrashType::ConnectionDrop,
                ..
            })
        ));
    }

    #[test]
    fn detect_process_exit_abort() {
        let detector = CrashDetector::new(5000);
        let response = FuzzResponse::process_exit(134);

        let analysis = detector.analyze(&response);
        assert!(matches!(
            analysis,
            CrashAnalysis::Crash(CrashInfo {
                crash_type: CrashType::AssertionFailure,
                ..
            })
        ));
    }

    #[test]
    fn detect_process_exit_oom() {
        let detector = CrashDetector::new(5000);
        let response = FuzzResponse::process_exit(137);

        let analysis = detector.analyze(&response);
        assert!(matches!(
            analysis,
            CrashAnalysis::Crash(CrashInfo {
                crash_type: CrashType::OutOfMemory,
                ..
            })
        ));
    }

    #[test]
    fn detect_process_exit_success() {
        let detector = CrashDetector::new(5000);
        let response = FuzzResponse::process_exit(0);

        let analysis = detector.analyze(&response);
        assert!(matches!(analysis, CrashAnalysis::None));
    }

    #[test]
    fn detect_panic_with_stack_trace() {
        let detector = CrashDetector::new(5000);
        let response = FuzzResponse::error(
            -32603,
            "thread 'main' panicked at 'assertion failed'\nstack backtrace:\n  0: foo::bar\n",
        );

        let analysis = detector.analyze(&response);
        if let CrashAnalysis::Crash(info) = analysis {
            assert_eq!(info.crash_type, CrashType::Panic);
            assert!(info.stack_trace.is_some());
        } else {
            panic!("Expected Crash analysis");
        }
    }

    #[test]
    fn detect_interesting_parse_error() {
        let detector = CrashDetector::new(5000);
        let response = FuzzResponse::error(-32700, "Parse error");

        let analysis = detector.analyze(&response);
        assert!(matches!(
            analysis,
            CrashAnalysis::Interesting(InterestingReason::ProtocolViolation)
        ));
    }

    #[test]
    fn detect_interesting_invalid_request() {
        let detector = CrashDetector::new(5000);
        let response = FuzzResponse::error(-32600, "Invalid Request");

        let analysis = detector.analyze(&response);
        assert!(matches!(
            analysis,
            CrashAnalysis::Interesting(InterestingReason::ProtocolViolation)
        ));
    }

    #[test]
    fn detect_interesting_new_error_code() {
        let detector = CrashDetector::new(5000);
        // Non-standard error code
        let response = FuzzResponse::error(123, "Custom error");

        let analysis = detector.analyze(&response);
        assert!(matches!(
            analysis,
            CrashAnalysis::Interesting(InterestingReason::NewErrorCode)
        ));
    }

    #[test]
    fn detect_interesting_verbose_internal_error() {
        let detector = CrashDetector::new(5000);
        // Long internal error message might leak info
        let long_message = "Internal error: ".to_string() + &"x".repeat(100);
        let response = FuzzResponse::error(-32603, &long_message);

        let analysis = detector.analyze(&response);
        assert!(matches!(
            analysis,
            CrashAnalysis::Interesting(InterestingReason::ProtocolViolation)
        ));
    }

    #[test]
    fn analyze_success_with_error_content() {
        let detector = CrashDetector::new(5000);
        let response = FuzzResponse::success(serde_json::json!({
            "error": "Something went wrong",
            "errorCode": 500
        }));

        let analysis = detector.analyze(&response);
        assert!(matches!(
            analysis,
            CrashAnalysis::Interesting(InterestingReason::UnexpectedSuccess)
        ));
    }

    #[test]
    fn analyze_success_with_panic_message() {
        let detector = CrashDetector::new(5000);
        let response = FuzzResponse::success(serde_json::json!({
            "message": "panic occurred in handler"
        }));

        let analysis = detector.analyze(&response);
        assert!(matches!(
            analysis,
            CrashAnalysis::Interesting(InterestingReason::ProtocolViolation)
        ));
    }

    #[test]
    fn analyze_normal_success() {
        let detector = CrashDetector::new(5000);
        let response = FuzzResponse::success(serde_json::json!({
            "tools": []
        }));

        let analysis = detector.analyze(&response);
        assert!(matches!(analysis, CrashAnalysis::None));
    }

    #[test]
    fn crash_analysis_is_crash() {
        let analysis = CrashAnalysis::Crash(CrashInfo {
            crash_type: CrashType::Panic,
            message: "test".to_string(),
            stack_trace: None,
        });
        assert!(analysis.is_crash());
        assert!(!analysis.is_hang());
        assert!(!analysis.is_interesting());
    }

    #[test]
    fn crash_analysis_is_hang() {
        let analysis = CrashAnalysis::Hang(HangInfo { timeout_ms: 5000 });
        assert!(!analysis.is_crash());
        assert!(analysis.is_hang());
        assert!(!analysis.is_interesting());
    }

    #[test]
    fn crash_analysis_is_interesting() {
        let analysis = CrashAnalysis::Interesting(InterestingReason::NewCoverage);
        assert!(!analysis.is_crash());
        assert!(!analysis.is_hang());
        assert!(analysis.is_interesting());
    }

    #[test]
    fn fuzz_response_with_time() {
        let response = FuzzResponse::success(serde_json::json!({})).with_time(123);
        assert_eq!(response.response_time_ms, 123);
    }

    #[test]
    fn from_jsonrpc_error_with_data() {
        let error = serde_json::json!({
            "jsonrpc": "2.0",
            "error": {
                "code": -32603,
                "message": "Internal error",
                "data": {"details": "more info"}
            },
            "id": 1
        });

        let response = FuzzResponse::from_jsonrpc(&error);
        if let FuzzResponseResult::Error(e) = response.result {
            assert!(e.data.is_some());
        } else {
            panic!("Expected error response");
        }
    }
}