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
//! SARIF output format for GitHub Code Scanning integration
//!
//! SARIF (Static Analysis Results Interchange Format) 2.1.0 types
//! for CI/CD integration with GitHub, GitLab, and other platforms.

#![allow(dead_code)] // Types are defined for future SARIF output implementation

use serde::{Deserialize, Serialize};

/// SARIF 2.1.0 compatible report
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SarifReport {
    #[serde(rename = "$schema")]
    pub schema: String,
    pub version: String,
    pub runs: Vec<SarifRun>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SarifRun {
    pub tool: SarifTool,
    pub results: Vec<SarifResult>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SarifTool {
    pub driver: SarifDriver,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SarifDriver {
    pub name: String,
    pub version: String,
    #[serde(rename = "informationUri")]
    pub information_uri: String,
    pub rules: Vec<SarifRule>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SarifRule {
    pub id: String,
    pub name: String,
    #[serde(rename = "shortDescription")]
    pub short_description: SarifMessage,
    #[serde(rename = "fullDescription")]
    pub full_description: SarifMessage,
    #[serde(rename = "defaultConfiguration")]
    pub default_configuration: SarifConfiguration,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SarifMessage {
    pub text: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SarifConfiguration {
    pub level: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SarifResult {
    #[serde(rename = "ruleId")]
    pub rule_id: String,
    pub level: String,
    pub message: SarifMessage,
    pub locations: Vec<SarifLocation>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SarifLocation {
    #[serde(rename = "physicalLocation")]
    pub physical_location: SarifPhysicalLocation,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SarifPhysicalLocation {
    #[serde(rename = "artifactLocation")]
    pub artifact_location: SarifArtifactLocation,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SarifArtifactLocation {
    pub uri: String,
}

impl SarifReport {
    pub fn new() -> Self {
        Self {
            schema: "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json".to_string(),
            version: "2.1.0".to_string(),
            runs: vec![],
        }
    }

    /// Create a SARIF report from security scan results
    pub fn from_scan_results(results: &crate::scanner::ScanResults) -> Self {
        // Collect unique rules from findings
        let mut rules: Vec<SarifRule> = Vec::new();
        let mut seen_rules: std::collections::HashSet<String> = std::collections::HashSet::new();

        for finding in &results.findings {
            if !seen_rules.contains(&finding.rule_id) {
                seen_rules.insert(finding.rule_id.clone());
                rules.push(SarifRule {
                    id: finding.rule_id.clone(),
                    name: finding.title.clone(),
                    short_description: SarifMessage {
                        text: finding.title.clone(),
                    },
                    full_description: SarifMessage {
                        text: finding.description.clone(),
                    },
                    default_configuration: SarifConfiguration {
                        level: finding.severity.sarif_level().to_string(),
                    },
                });
            }
        }

        // Convert findings to SARIF results
        let sarif_results: Vec<SarifResult> = results
            .findings
            .iter()
            .map(|f| {
                // Build location URI from finding location
                let uri = if f.location.identifier.is_empty() {
                    format!("{}/{}", f.location.component, results.server)
                } else {
                    format!("{}/{}", f.location.component, f.location.identifier)
                };

                SarifResult {
                    rule_id: f.rule_id.clone(),
                    level: f.severity.sarif_level().to_string(),
                    message: SarifMessage {
                        text: format!(
                            "{}: {}{}",
                            f.title,
                            f.description,
                            if f.remediation.is_empty() {
                                String::new()
                            } else {
                                format!(" Remediation: {}", f.remediation)
                            }
                        ),
                    },
                    locations: vec![SarifLocation {
                        physical_location: SarifPhysicalLocation {
                            artifact_location: SarifArtifactLocation { uri },
                        },
                    }],
                }
            })
            .collect();

        Self {
            schema: "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json".to_string(),
            version: "2.1.0".to_string(),
            runs: vec![SarifRun {
                tool: SarifTool {
                    driver: SarifDriver {
                        name: "mcplint".to_string(),
                        version: env!("CARGO_PKG_VERSION").to_string(),
                        information_uri: "https://github.com/quanticsoul4772/mcplint".to_string(),
                        rules,
                    },
                },
                results: sarif_results,
            }],
        }
    }

    /// Create a SARIF report from validation results
    pub fn from_validation_results(results: &crate::validator::ValidationResults) -> Self {
        use crate::validator::ValidationSeverity;

        // Collect unique rules from results
        let mut rules: Vec<SarifRule> = Vec::new();
        let mut seen_rules: std::collections::HashSet<String> = std::collections::HashSet::new();

        for result in &results.results {
            if !seen_rules.contains(&result.rule_id) {
                seen_rules.insert(result.rule_id.clone());
                rules.push(SarifRule {
                    id: result.rule_id.clone(),
                    name: result.rule_name.clone(),
                    short_description: SarifMessage {
                        text: result.rule_name.clone(),
                    },
                    full_description: SarifMessage {
                        text: result
                            .message
                            .clone()
                            .unwrap_or_else(|| result.rule_name.clone()),
                    },
                    default_configuration: SarifConfiguration {
                        level: match result.severity {
                            ValidationSeverity::Fail => "error".to_string(),
                            ValidationSeverity::Warning => "warning".to_string(),
                            _ => "note".to_string(),
                        },
                    },
                });
            }
        }

        // Convert results to SARIF results (only failures and warnings)
        let sarif_results: Vec<SarifResult> = results
            .results
            .iter()
            .filter(|r| {
                matches!(
                    r.severity,
                    ValidationSeverity::Fail | ValidationSeverity::Warning
                )
            })
            .map(|r| SarifResult {
                rule_id: r.rule_id.clone(),
                level: match r.severity {
                    ValidationSeverity::Fail => "error".to_string(),
                    ValidationSeverity::Warning => "warning".to_string(),
                    _ => "note".to_string(),
                },
                message: SarifMessage {
                    text: format!("{}: {}", r.rule_name, r.message.clone().unwrap_or_default()),
                },
                locations: vec![SarifLocation {
                    physical_location: SarifPhysicalLocation {
                        artifact_location: SarifArtifactLocation {
                            uri: results.server.clone(),
                        },
                    },
                }],
            })
            .collect();

        Self {
            schema: "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json".to_string(),
            version: "2.1.0".to_string(),
            runs: vec![SarifRun {
                tool: SarifTool {
                    driver: SarifDriver {
                        name: "mcplint".to_string(),
                        version: env!("CARGO_PKG_VERSION").to_string(),
                        information_uri: "https://github.com/quanticsoul4772/mcplint".to_string(),
                        rules,
                    },
                },
                results: sarif_results,
            }],
        }
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::scanner::{Finding, FindingLocation, ScanProfile, ScanResults, Severity};
    use crate::validator::{ValidationResult, ValidationResults, ValidationSeverity};

    #[test]
    fn sarif_report_new() {
        let report = SarifReport::new();
        assert_eq!(report.version, "2.1.0");
        assert!(report.schema.contains("sarif-schema-2.1.0"));
        assert!(report.runs.is_empty());
    }

    #[test]
    fn sarif_report_default() {
        let report = SarifReport::default();
        assert_eq!(report.version, "2.1.0");
    }

    #[test]
    fn sarif_message_creation() {
        let msg = SarifMessage {
            text: "Test message".to_string(),
        };
        assert_eq!(msg.text, "Test message");
    }

    #[test]
    fn sarif_configuration_creation() {
        let config = SarifConfiguration {
            level: "error".to_string(),
        };
        assert_eq!(config.level, "error");
    }

    #[test]
    fn sarif_rule_creation() {
        let rule = SarifRule {
            id: "TEST-001".to_string(),
            name: "Test Rule".to_string(),
            short_description: SarifMessage {
                text: "Short desc".to_string(),
            },
            full_description: SarifMessage {
                text: "Full description".to_string(),
            },
            default_configuration: SarifConfiguration {
                level: "warning".to_string(),
            },
        };
        assert_eq!(rule.id, "TEST-001");
        assert_eq!(rule.name, "Test Rule");
    }

    #[test]
    fn sarif_location_creation() {
        let location = SarifLocation {
            physical_location: SarifPhysicalLocation {
                artifact_location: SarifArtifactLocation {
                    uri: "file:///test.js".to_string(),
                },
            },
        };
        assert_eq!(
            location.physical_location.artifact_location.uri,
            "file:///test.js"
        );
    }

    #[test]
    fn sarif_result_creation() {
        let result = SarifResult {
            rule_id: "TEST-001".to_string(),
            level: "error".to_string(),
            message: SarifMessage {
                text: "Test finding".to_string(),
            },
            locations: vec![SarifLocation {
                physical_location: SarifPhysicalLocation {
                    artifact_location: SarifArtifactLocation {
                        uri: "test.js".to_string(),
                    },
                },
            }],
        };
        assert_eq!(result.rule_id, "TEST-001");
        assert_eq!(result.level, "error");
    }

    fn make_validation_result(
        rule_id: &str,
        rule_name: &str,
        severity: ValidationSeverity,
        message: Option<&str>,
    ) -> ValidationResult {
        ValidationResult {
            rule_id: rule_id.to_string(),
            rule_name: rule_name.to_string(),
            category: "protocol".to_string(),
            severity,
            message: message.map(|s| s.to_string()),
            details: vec![],
            duration_ms: 100,
        }
    }

    fn make_empty_results() -> ValidationResults {
        ValidationResults {
            server: "test-server".to_string(),
            protocol_version: Some("2024-11-05".to_string()),
            capabilities: None,
            results: vec![],
            passed: 0,
            failed: 0,
            warnings: 0,
            total_duration_ms: 0,
        }
    }

    #[test]
    fn sarif_from_validation_results_empty() {
        let results = make_empty_results();
        let sarif = SarifReport::from_validation_results(&results);
        assert_eq!(sarif.runs.len(), 1);
        assert!(sarif.runs[0].results.is_empty());
    }

    #[test]
    fn sarif_from_validation_results_with_failures() {
        let mut results = make_empty_results();
        results.results = vec![
            make_validation_result(
                "PROTO-001",
                "Test Rule",
                ValidationSeverity::Fail,
                Some("Failed validation"),
            ),
            make_validation_result(
                "PROTO-002",
                "Warning Rule",
                ValidationSeverity::Warning,
                Some("Warning message"),
            ),
        ];
        results.failed = 1;
        results.warnings = 1;

        let sarif = SarifReport::from_validation_results(&results);
        assert_eq!(sarif.runs.len(), 1);
        assert_eq!(sarif.runs[0].results.len(), 2);
        assert_eq!(sarif.runs[0].tool.driver.rules.len(), 2);
    }

    #[test]
    fn sarif_from_validation_results_filters_pass() {
        let mut results = make_empty_results();
        results.results = vec![
            make_validation_result("PROTO-001", "Pass Rule", ValidationSeverity::Pass, None),
            make_validation_result(
                "PROTO-002",
                "Fail Rule",
                ValidationSeverity::Fail,
                Some("Error"),
            ),
        ];
        results.passed = 1;
        results.failed = 1;

        let sarif = SarifReport::from_validation_results(&results);
        // Only failures and warnings should be in results
        assert_eq!(sarif.runs[0].results.len(), 1);
        assert_eq!(sarif.runs[0].results[0].rule_id, "PROTO-002");
    }

    #[test]
    fn sarif_serialization() {
        let report = SarifReport::new();
        let json = serde_json::to_string(&report).unwrap();
        assert!(json.contains("2.1.0"));
        assert!(json.contains("$schema"));
    }

    #[test]
    fn sarif_deserialization() {
        let json = r#"{
            "$schema": "https://example.com/schema.json",
            "version": "2.1.0",
            "runs": []
        }"#;
        let report: SarifReport = serde_json::from_str(json).unwrap();
        assert_eq!(report.version, "2.1.0");
    }

    #[test]
    fn sarif_driver_info() {
        let results = make_empty_results();
        let sarif = SarifReport::from_validation_results(&results);
        assert_eq!(sarif.runs[0].tool.driver.name, "mcplint");
        assert!(sarif.runs[0].tool.driver.information_uri.contains("github"));
    }

    // =========================================================================
    // Tests for from_scan_results()
    // =========================================================================

    fn make_scan_finding(
        rule_id: &str,
        severity: Severity,
        title: &str,
        description: &str,
        component: &str,
        identifier: &str,
    ) -> Finding {
        Finding::new(rule_id, severity, title, description).with_location(FindingLocation {
            component: component.to_string(),
            identifier: identifier.to_string(),
            context: None,
        })
    }

    fn make_empty_scan_results() -> ScanResults {
        ScanResults::new("test-server", ScanProfile::Standard)
    }

    #[test]
    fn sarif_from_scan_results_empty() {
        let results = make_empty_scan_results();
        let sarif = SarifReport::from_scan_results(&results);

        assert_eq!(sarif.version, "2.1.0");
        assert_eq!(sarif.runs.len(), 1);
        assert!(sarif.runs[0].results.is_empty());
        assert!(sarif.runs[0].tool.driver.rules.is_empty());
    }

    #[test]
    fn sarif_from_scan_results_with_findings() {
        let mut results = make_empty_scan_results();
        results.add_finding(make_scan_finding(
            "MCP-INJ-001",
            Severity::Critical,
            "Command Injection",
            "Detected command injection vulnerability",
            "tool",
            "shell_exec",
        ));

        let sarif = SarifReport::from_scan_results(&results);

        assert_eq!(sarif.runs.len(), 1);
        assert_eq!(sarif.runs[0].results.len(), 1);
        assert_eq!(sarif.runs[0].tool.driver.rules.len(), 1);

        // Check the result
        let result = &sarif.runs[0].results[0];
        assert_eq!(result.rule_id, "MCP-INJ-001");
        assert_eq!(result.level, "error"); // Critical maps to error
        assert!(result.message.text.contains("Command Injection"));

        // Check the rule
        let rule = &sarif.runs[0].tool.driver.rules[0];
        assert_eq!(rule.id, "MCP-INJ-001");
        assert_eq!(rule.name, "Command Injection");
    }

    #[test]
    fn sarif_from_scan_results_severity_mapping() {
        let mut results = make_empty_scan_results();

        // Add findings with different severities
        results.add_finding(make_scan_finding(
            "TEST-001",
            Severity::Critical,
            "Critical Issue",
            "Desc",
            "tool",
            "t1",
        ));
        results.add_finding(make_scan_finding(
            "TEST-002",
            Severity::High,
            "High Issue",
            "Desc",
            "tool",
            "t2",
        ));
        results.add_finding(make_scan_finding(
            "TEST-003",
            Severity::Medium,
            "Medium Issue",
            "Desc",
            "tool",
            "t3",
        ));
        results.add_finding(make_scan_finding(
            "TEST-004",
            Severity::Low,
            "Low Issue",
            "Desc",
            "tool",
            "t4",
        ));
        results.add_finding(make_scan_finding(
            "TEST-005",
            Severity::Info,
            "Info Issue",
            "Desc",
            "tool",
            "t5",
        ));

        let sarif = SarifReport::from_scan_results(&results);

        // Verify SARIF levels
        assert_eq!(sarif.runs[0].results[0].level, "error"); // Critical
        assert_eq!(sarif.runs[0].results[1].level, "error"); // High
        assert_eq!(sarif.runs[0].results[2].level, "warning"); // Medium
        assert_eq!(sarif.runs[0].results[3].level, "note"); // Low
        assert_eq!(sarif.runs[0].results[4].level, "note"); // Info
    }

    #[test]
    fn sarif_from_scan_results_deduplicates_rules() {
        let mut results = make_empty_scan_results();

        // Add multiple findings with the same rule_id
        results.add_finding(make_scan_finding(
            "MCP-INJ-001",
            Severity::High,
            "Injection",
            "Desc",
            "tool",
            "tool_a",
        ));
        results.add_finding(make_scan_finding(
            "MCP-INJ-001",
            Severity::High,
            "Injection",
            "Desc",
            "tool",
            "tool_b",
        ));
        results.add_finding(make_scan_finding(
            "MCP-INJ-001",
            Severity::High,
            "Injection",
            "Desc",
            "tool",
            "tool_c",
        ));

        let sarif = SarifReport::from_scan_results(&results);

        // Should have 3 results but only 1 rule
        assert_eq!(sarif.runs[0].results.len(), 3);
        assert_eq!(sarif.runs[0].tool.driver.rules.len(), 1);
    }

    #[test]
    fn sarif_from_scan_results_location_uri() {
        let mut results = make_empty_scan_results();
        results.add_finding(make_scan_finding(
            "TEST-001",
            Severity::High,
            "Issue",
            "Desc",
            "tool",
            "dangerous_tool",
        ));

        let sarif = SarifReport::from_scan_results(&results);

        let location = &sarif.runs[0].results[0].locations[0];
        assert_eq!(
            location.physical_location.artifact_location.uri,
            "tool/dangerous_tool"
        );
    }

    #[test]
    fn sarif_from_scan_results_includes_remediation() {
        let mut results = make_empty_scan_results();
        let finding = Finding::new("TEST-001", Severity::High, "Issue", "Description of issue")
            .with_location(FindingLocation::tool("test_tool"))
            .with_remediation("Sanitize all user inputs");
        results.add_finding(finding);

        let sarif = SarifReport::from_scan_results(&results);

        let message = &sarif.runs[0].results[0].message.text;
        assert!(message.contains("Remediation: Sanitize all user inputs"));
    }

    #[test]
    fn sarif_from_scan_results_serializes_correctly() {
        let mut results = make_empty_scan_results();
        results.add_finding(make_scan_finding(
            "MCP-INJ-001",
            Severity::Critical,
            "Test Issue",
            "Test Description",
            "tool",
            "test_tool",
        ));

        let sarif = SarifReport::from_scan_results(&results);
        let json = serde_json::to_string_pretty(&sarif).unwrap();

        // Verify the JSON contains expected fields
        assert!(json.contains("\"$schema\""));
        assert!(json.contains("\"version\": \"2.1.0\""));
        assert!(json.contains("\"ruleId\": \"MCP-INJ-001\""));
        assert!(json.contains("\"level\": \"error\""));
        assert!(json.contains("\"mcplint\""));
    }

    #[test]
    fn sarif_from_scan_results_empty_identifier() {
        let mut results = make_empty_scan_results();
        results.add_finding(
            Finding::new("TEST-001", Severity::Medium, "Issue", "Desc").with_location(
                FindingLocation {
                    component: "server".to_string(),
                    identifier: String::new(),
                    context: None,
                },
            ),
        );

        let sarif = SarifReport::from_scan_results(&results);

        // Should fall back to server name in URI
        let location = &sarif.runs[0].results[0].locations[0];
        assert_eq!(
            location.physical_location.artifact_location.uri,
            "server/test-server"
        );
    }
}