agnix-mcp 0.12.2

MCP server for agnix - AI agent config linter
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
703
//! MCP server for agnix - AI agent config linter
//!
//! Exposes agnix validation as MCP tools for AI assistants.
//!
//! ## MCP Best Practices Implemented
//!
//! - **Clear tool descriptions**: Each tool has a detailed description explaining
//!   what it does, when to use it, and what it returns
//! - **Rich parameter schemas**: All parameters have descriptions with examples
//! - **Structured outputs**: Returns JSON with predictable schema for easy parsing
//! - **Error handling**: Proper error messages with context
//! - **Server metadata**: Provides name, version, and usage instructions

use agnix_core::{
    config::LintConfig,
    diagnostics::{Diagnostic, DiagnosticLevel},
    validate_file as core_validate_file, validate_project as core_validate_project,
};
use rmcp::{
    ServerHandler, ServiceExt,
    handler::server::{tool::ToolRouter, wrapper::Parameters},
    model::{
        CallToolResult, Content, ErrorData as McpError, Implementation, ProtocolVersion,
        ServerCapabilities, ServerInfo,
    },
    schemars, tool, tool_handler, tool_router,
    transport::stdio,
};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashSet;
use std::path::Path;

const TOOL_ALIASES: &[(&str, &str)] =
    &[("copilot", "github-copilot"), ("claudecode", "claude-code")];

const COMPAT_TOOL_NAMES: &[&str] = &["generic", "codex"];

/// Input for validate_file tool.
///
/// The `path` field accepts absolute or relative paths. Path safety is enforced
/// downstream by `safe_read_file()` (symlink rejection, size limits).
#[derive(Debug, Deserialize, schemars::JsonSchema)]
#[schemars(description = "Input for validating a single agent configuration file")]
pub struct ValidateFileInput {
    /// Path to the file to validate
    #[schemars(
        description = "Absolute or relative path to the agent configuration file (e.g., 'SKILL.md', '.claude/settings.json', 'mcp-config.json')"
    )]
    pub path: String,
    /// Tools to validate for (preferred over legacy target)
    #[schemars(
        description = "Tools to validate for. Accepts comma-separated string (e.g., 'claude-code,cursor,windsurf') or array (e.g., ['claude-code','cursor']). Uses canonical agnix tool names (case-insensitive), plus compatibility aliases (e.g., 'copilot', 'claudecode'). When non-empty, this overrides legacy target."
    )]
    pub tools: Option<ToolsInput>,
    /// Target tool for validation rules
    #[schemars(
        description = "Legacy single target for validation rules (deprecated). Options: 'generic' (default), 'claude-code', 'cursor', 'codex'. Used only when 'tools' is missing or empty."
    )]
    pub target: Option<String>,
}

/// Input for validate_project tool
#[derive(Debug, Deserialize, schemars::JsonSchema)]
#[schemars(description = "Input for validating all agent configs in a project directory")]
pub struct ValidateProjectInput {
    /// Path to the project directory
    #[schemars(
        description = "Path to the project directory to validate (e.g., '.' for current directory)"
    )]
    pub path: String,
    /// Tools to validate for (preferred over legacy target)
    #[schemars(
        description = "Tools to validate for. Accepts comma-separated string (e.g., 'claude-code,cursor,windsurf') or array (e.g., ['claude-code','cursor']). Uses canonical agnix tool names (case-insensitive), plus compatibility aliases (e.g., 'copilot', 'claudecode'). When non-empty, this overrides legacy target."
    )]
    pub tools: Option<ToolsInput>,
    /// Target tool for validation rules
    #[schemars(
        description = "Legacy single target for validation rules (deprecated). Options: 'generic' (default), 'claude-code', 'cursor', 'codex'. Used only when 'tools' is missing or empty."
    )]
    pub target: Option<String>,
}

/// Tools input for MCP validate tools.
///
/// Supports either comma-separated string or array syntax.
#[derive(Debug, Deserialize, schemars::JsonSchema)]
#[serde(untagged)]
pub enum ToolsInput {
    Csv(String),
    List(Vec<String>),
}

/// Input for get_rule_docs tool
#[derive(Debug, Deserialize, schemars::JsonSchema)]
#[schemars(description = "Input for looking up a specific validation rule")]
pub struct GetRuleDocsInput {
    /// Rule ID
    #[schemars(
        description = "Rule ID to look up documentation for. Format: PREFIX-NUMBER (e.g., 'AS-004', 'CC-SK-001', 'PE-003', 'MCP-001')"
    )]
    pub rule_id: String,
}

/// Diagnostic output for JSON serialization
#[derive(Debug, Serialize, schemars::JsonSchema)]
struct DiagnosticOutput {
    /// File path where the issue was found
    file: String,
    /// Line number (1-based)
    line: usize,
    /// Column number (1-based)
    column: usize,
    /// Severity level: error, warning, or info
    level: String,
    /// Rule ID (e.g., AS-004)
    rule: String,
    /// Human-readable message describing the issue
    message: String,
    /// Suggested fix or help text
    suggestion: Option<String>,
    /// Whether this issue can be auto-fixed
    fixable: bool,
    /// Rule category from the rules catalog (e.g., "agent-skills")
    #[serde(skip_serializing_if = "Option::is_none")]
    category: Option<String>,
    /// Rule severity from the rules catalog (e.g., "HIGH", "MEDIUM", "LOW").
    /// Named `rule_severity` to avoid confusion with the `level` field.
    #[serde(skip_serializing_if = "Option::is_none")]
    rule_severity: Option<String>,
    /// Tool this rule specifically applies to (e.g., "claude-code")
    #[serde(skip_serializing_if = "Option::is_none")]
    applies_to_tool: Option<String>,
}

impl From<&Diagnostic> for DiagnosticOutput {
    fn from(d: &Diagnostic) -> Self {
        Self {
            file: d.file.display().to_string(),
            line: d.line,
            column: d.column,
            level: match d.level {
                DiagnosticLevel::Error => "error",
                DiagnosticLevel::Warning => "warning",
                DiagnosticLevel::Info => "info",
            }
            .to_string(),
            rule: d.rule.clone(),
            message: d.message.clone(),
            suggestion: d.suggestion.clone(),
            fixable: !d.fixes.is_empty(),
            category: d.metadata.as_ref().map(|m| m.category.clone()),
            rule_severity: d.metadata.as_ref().map(|m| m.severity.clone()),
            applies_to_tool: d.metadata.as_ref().and_then(|m| m.applies_to_tool.clone()),
        }
    }
}

/// Validation result output
#[derive(Debug, Serialize, schemars::JsonSchema)]
struct ValidationResult {
    /// Path that was validated
    path: String,
    /// Number of files checked
    files_checked: usize,
    /// Number of errors found
    errors: usize,
    /// Number of warnings found
    warnings: usize,
    /// Number of issues that can be auto-fixed
    fixable: usize,
    /// List of diagnostics
    diagnostics: Vec<DiagnosticOutput>,
}

/// Rule info for listing
#[derive(Debug, Serialize, schemars::JsonSchema)]
struct RuleInfo {
    /// Rule ID (e.g., AS-004)
    id: String,
    /// Human-readable name
    name: String,
}

/// Rules list output
#[derive(Debug, Serialize, schemars::JsonSchema)]
struct RulesListOutput {
    /// Total number of rules
    count: usize,
    /// List of rules
    rules: Vec<RuleInfo>,
}

fn parse_target(target: Option<String>) -> agnix_core::config::TargetTool {
    use agnix_core::config::TargetTool;

    match target.as_deref() {
        Some("claude-code") | Some("claudecode") => TargetTool::ClaudeCode,
        Some("cursor") => TargetTool::Cursor,
        Some("codex") => TargetTool::Codex,
        _ => TargetTool::Generic,
    }
}

fn normalize_tool_entry(value: &str) -> Option<String> {
    let trimmed = value.trim();
    if trimmed.is_empty() {
        None
    } else {
        Some(trimmed.to_ascii_lowercase())
    }
}

fn canonicalize_tool(value: &str) -> Option<&'static str> {
    match value {
        v if v.eq_ignore_ascii_case("generic") => Some("generic"),
        v if v.eq_ignore_ascii_case("codex") => Some("codex"),
        _ => TOOL_ALIASES
            .iter()
            .find(|(alias, _)| value.eq_ignore_ascii_case(alias))
            .map(|(_, canonical)| *canonical)
            .or_else(|| agnix_rules::normalize_tool_name(value)),
    }
}

fn supported_tool_names() -> Vec<&'static str> {
    let mut tools = agnix_rules::valid_tools().to_vec();
    for compat in COMPAT_TOOL_NAMES {
        if !tools.contains(compat) {
            tools.push(compat);
        }
    }
    tools.sort_unstable();
    tools
}

fn alias_help() -> String {
    TOOL_ALIASES
        .iter()
        .map(|(alias, canonical)| format!("{} -> {}", alias, canonical))
        .collect::<Vec<_>>()
        .join(", ")
}

fn parse_tools(tools: Option<ToolsInput>) -> Result<Vec<String>, McpError> {
    let raw: Vec<String> = match tools {
        None => Vec::new(),
        Some(ToolsInput::Csv(csv)) => csv.split(',').filter_map(normalize_tool_entry).collect(),
        Some(ToolsInput::List(list)) => list
            .into_iter()
            .filter_map(|entry| normalize_tool_entry(&entry))
            .collect(),
    };

    if raw.is_empty() {
        return Ok(Vec::new());
    }

    let mut seen = HashSet::new();
    let mut normalized = Vec::new();
    for tool in raw {
        let canonical = canonicalize_tool(&tool).ok_or_else(|| {
            make_invalid_params(format!(
                "Unknown tool '{}'. Valid values: {}. Aliases: {}.",
                tool,
                supported_tool_names().join(", "),
                alias_help()
            ))
        })?;
        if seen.insert(canonical) {
            normalized.push(canonical.to_string());
        }
    }

    Ok(normalized)
}

fn apply_tool_selection(
    config: &mut LintConfig,
    tools: Option<ToolsInput>,
    target: Option<String>,
) -> Result<(), McpError> {
    let parsed_tools = parse_tools(tools)?;
    if parsed_tools.is_empty() {
        config.tools_mut().clear();
        config.set_target(parse_target(target));
    } else {
        config.set_target(agnix_core::config::TargetTool::Generic);
        config.set_tools(parsed_tools);
    }

    Ok(())
}

fn diagnostics_to_result(
    path: &str,
    diagnostics: Vec<Diagnostic>,
    files_checked: usize,
) -> ValidationResult {
    let errors = diagnostics
        .iter()
        .filter(|d| matches!(d.level, DiagnosticLevel::Error))
        .count();
    let warnings = diagnostics
        .iter()
        .filter(|d| matches!(d.level, DiagnosticLevel::Warning))
        .count();
    let fixable = diagnostics.iter().filter(|d| !d.fixes.is_empty()).count();

    ValidationResult {
        path: path.to_string(),
        files_checked,
        errors,
        warnings,
        fixable,
        diagnostics: diagnostics.iter().map(DiagnosticOutput::from).collect(),
    }
}

fn make_error(msg: String) -> McpError {
    McpError::internal_error(msg, None::<Value>)
}

fn make_invalid_params(msg: String) -> McpError {
    McpError::invalid_params(msg, None::<Value>)
}

/// Agnix MCP Server - validates AI agent configurations
///
/// Provides tools to validate SKILL.md, CLAUDE.md, AGENTS.md, hooks,
/// MCP configs, and more against 168 rules.

#[derive(Debug, Clone)]
pub struct AgnixServer {
    tool_router: ToolRouter<AgnixServer>,
}

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

#[tool_router]
impl AgnixServer {
    pub fn new() -> Self {
        Self {
            tool_router: Self::tool_router(),
        }
    }

    /// Validate a single agent configuration file
    #[tool(
        description = "Validate a single agent configuration file against agnix rules. Supports SKILL.md, CLAUDE.md, AGENTS.md, hooks.json, *.mcp.json, .cursor/rules/*.mdc, and other agent config files. Returns diagnostics with errors, warnings, auto-fix suggestions, and rule IDs for lookup."
    )]
    async fn validate_file(
        &self,
        Parameters(input): Parameters<ValidateFileInput>,
    ) -> Result<CallToolResult, McpError> {
        let mut config = LintConfig::default();
        apply_tool_selection(&mut config, input.tools, input.target)?;

        let file_path = Path::new(&input.path);

        let diagnostics = core_validate_file(file_path, &config)
            .map_err(|e| make_error(format!("Failed to validate file: {}", e)))?;

        let result = diagnostics_to_result(&input.path, diagnostics, 1);
        let json = serde_json::to_string_pretty(&result)
            .map_err(|e| make_error(format!("Failed to serialize result: {}", e)))?;

        Ok(CallToolResult::success(vec![Content::text(json)]))
    }

    /// Validate all agent configuration files in a project directory
    #[tool(
        description = "Validate all agent configuration files in a project directory. Recursively finds and validates SKILL.md, CLAUDE.md, AGENTS.md, hooks, MCP configs, Cursor rules, and more. Returns aggregated diagnostics for all files."
    )]
    async fn validate_project(
        &self,
        Parameters(input): Parameters<ValidateProjectInput>,
    ) -> Result<CallToolResult, McpError> {
        let mut config = LintConfig::default();
        apply_tool_selection(&mut config, input.tools, input.target)?;

        let validation_result = core_validate_project(Path::new(&input.path), &config)
            .map_err(|e| make_error(format!("Failed to validate project: {}", e)))?;

        let result = diagnostics_to_result(
            &input.path,
            validation_result.diagnostics,
            validation_result.files_checked,
        );
        let json = serde_json::to_string_pretty(&result)
            .map_err(|e| make_error(format!("Failed to serialize result: {}", e)))?;

        Ok(CallToolResult::success(vec![Content::text(json)]))
    }

    /// Get all available validation rules
    #[tool(
        description = "List all 168 validation rules available in agnix. Returns rule IDs and names organized by category (AS-* Agent Skills, CC-* Claude Code, MCP-* Model Context Protocol, COP-* Copilot, CUR-* Cursor, etc.)."
    )]
    async fn get_rules(&self) -> Result<CallToolResult, McpError> {
        let rules: Vec<RuleInfo> = agnix_rules::RULES_DATA
            .iter()
            .map(|(id, name)| RuleInfo {
                id: (*id).to_string(),
                name: (*name).to_string(),
            })
            .collect();

        let output = RulesListOutput {
            count: rules.len(),
            rules,
        };

        let json = serde_json::to_string_pretty(&output)
            .map_err(|e| make_error(format!("Failed to serialize rules: {}", e)))?;

        Ok(CallToolResult::success(vec![Content::text(json)]))
    }

    /// Get documentation for a specific rule
    #[tool(
        description = "Get the name of a specific validation rule by ID. Rule IDs follow patterns like AS-004 (Agent Skills), CC-SK-001 (Claude Code Skills), PE-003 (Prompt Engineering), MCP-001 (Model Context Protocol)."
    )]
    async fn get_rule_docs(
        &self,
        Parameters(input): Parameters<GetRuleDocsInput>,
    ) -> Result<CallToolResult, McpError> {
        let name = agnix_rules::get_rule_name(&input.rule_id).ok_or_else(|| {
            make_invalid_params(format!(
                "Rule not found: {}. Use get_rules to list all available rules.",
                input.rule_id
            ))
        })?;

        let output = RuleInfo {
            id: input.rule_id,
            name: name.to_string(),
        };

        let json = serde_json::to_string_pretty(&output)
            .map_err(|e| make_error(format!("Failed to serialize rule: {}", e)))?;

        Ok(CallToolResult::success(vec![Content::text(json)]))
    }
}

#[tool_handler]
impl ServerHandler for AgnixServer {
    fn get_info(&self) -> ServerInfo {
        ServerInfo {
            protocol_version: ProtocolVersion::V_2024_11_05,
            capabilities: ServerCapabilities::builder().enable_tools().build(),
            server_info: Implementation {
                name: "agnix".into(),
                version: env!("CARGO_PKG_VERSION").into(),
                ..Default::default()
            },
            instructions: Some(
                "Agnix - AI agent configuration linter.\n\n\
                 Validates SKILL.md, CLAUDE.md, AGENTS.md, hooks, MCP configs, \
                 Cursor rules, and more against 168 rules.\n\n\
                 Tools:\n\
                 - validate_project: Validate all agent configs in a directory\n\
                 - validate_file: Validate a single config file\n\
                 - get_rules: List all 168 validation rules\n\
                 - get_rule_docs: Get details about a specific rule\n\n\
                 Preferred input: tools (CSV string or array)\n\
                 Legacy fallback: target\n\
                 Supported tools are derived from agnix rule metadata"
                    .to_string(),
            ),
        }
    }
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    // Initialize logging to stderr (stdout is for MCP protocol)
    tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::from_default_env()
                .add_directive(tracing::Level::WARN.into()),
        )
        .with_writer(std::io::stderr)
        .init();

    // Create and run MCP server on stdio
    let server = AgnixServer::new();
    let service = server.serve(stdio()).await?;

    // Wait for shutdown
    service.waiting().await?;

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::{
        ToolsInput, ValidateFileInput, ValidateProjectInput, apply_tool_selection, parse_tools,
    };
    use agnix_core::LintConfig;
    use agnix_core::config::TargetTool;
    use serde_json::json;

    #[test]
    fn test_parse_tools_csv_trims_and_discards_empty_entries() {
        let tools = parse_tools(Some(ToolsInput::Csv(
            "claude-code, cursor, ,codex,, ".to_string(),
        )))
        .expect("valid tools should parse");
        assert_eq!(tools, vec!["claude-code", "cursor", "codex"]);
    }

    #[test]
    fn test_parse_tools_array_trims_and_discards_empty_entries() {
        let tools = parse_tools(Some(ToolsInput::List(vec![
            " claude-code ".to_string(),
            "".to_string(),
            " cursor".to_string(),
            "   ".to_string(),
        ])))
        .expect("valid tools should parse");
        assert_eq!(tools, vec!["claude-code", "cursor"]);
    }

    #[test]
    fn test_parse_tools_canonicalizes_and_deduplicates_entries() {
        let tools = parse_tools(Some(ToolsInput::List(vec![
            "copilot".to_string(),
            "github-copilot".to_string(),
            "claudecode".to_string(),
            "claude-code".to_string(),
            "cursor".to_string(),
            "CURSOR".to_string(),
        ])))
        .expect("valid tools should parse");
        assert_eq!(tools, vec!["github-copilot", "claude-code", "cursor"]);
    }

    #[test]
    fn test_parse_tools_allows_compat_tool_names() {
        let tools = parse_tools(Some(ToolsInput::Csv("generic,codex".to_string())))
            .expect("generic and codex should be accepted for compatibility");
        assert_eq!(tools, vec!["generic", "codex"]);
    }

    #[test]
    fn test_parse_tools_rejects_unknown_tools() {
        let result = parse_tools(Some(ToolsInput::List(vec!["claud-code".to_string()])));
        assert!(result.is_err());
    }

    #[test]
    fn test_apply_tool_selection_falls_back_to_target_when_tools_empty() {
        let mut config = LintConfig::default();
        apply_tool_selection(
            &mut config,
            Some(ToolsInput::Csv(" , ".to_string())),
            Some("cursor".to_string()),
        )
        .expect("empty tools should fall back to target");

        assert!(config.tools().is_empty());
        assert_eq!(config.target(), TargetTool::Cursor);
    }

    #[test]
    fn test_apply_tool_selection_falls_back_to_target_when_tools_missing() {
        let mut config = LintConfig::default();
        apply_tool_selection(&mut config, None, Some("claude-code".to_string()))
            .expect("missing tools should fall back to target");

        assert!(config.tools().is_empty());
        assert_eq!(config.target(), TargetTool::ClaudeCode);
    }

    #[test]
    fn test_apply_tool_selection_falls_back_to_target_when_tools_empty_list() {
        let mut config = LintConfig::default();
        apply_tool_selection(
            &mut config,
            Some(ToolsInput::List(vec![])),
            Some("codex".to_string()),
        )
        .expect("empty list should fall back to target");

        assert!(config.tools().is_empty());
        assert_eq!(config.target(), TargetTool::Codex);
    }

    #[test]
    fn test_apply_tool_selection_clears_existing_tools_on_fallback() {
        let mut config = LintConfig::default();
        config.set_tools(vec!["cursor".to_string()]);

        apply_tool_selection(
            &mut config,
            Some(ToolsInput::Csv(" ".to_string())),
            Some("claude-code".to_string()),
        )
        .expect("empty tools should trigger fallback and clear stale tools");

        assert!(config.tools().is_empty());
        assert_eq!(config.target(), TargetTool::ClaudeCode);
    }

    #[test]
    fn test_apply_tool_selection_prefers_tools_over_target() {
        let mut config = LintConfig::default();
        config.set_target(TargetTool::Cursor);
        apply_tool_selection(
            &mut config,
            Some(ToolsInput::Csv("claude-code,cursor".to_string())),
            Some("codex".to_string()),
        )
        .expect("valid tools should override target");

        assert_eq!(config.tools(), &["claude-code", "cursor"]);
        // target remains default; tools array drives filtering precedence in core.
        assert_eq!(config.target(), TargetTool::Generic);
    }

    #[test]
    fn test_apply_tool_selection_rejects_unknown_tools() {
        let mut config = LintConfig::default();
        let result = apply_tool_selection(
            &mut config,
            Some(ToolsInput::Csv("unknown-tool".to_string())),
            Some("claude-code".to_string()),
        );
        assert!(result.is_err());
        assert!(config.tools().is_empty());
        assert_eq!(config.target(), TargetTool::Generic);
    }

    #[test]
    fn test_validate_file_input_deserializes_csv_tools_payload() {
        let input: ValidateFileInput = serde_json::from_value(json!({
            "path": "SKILL.md",
            "tools": "claude-code,cursor",
            "target": "codex"
        }))
        .expect("tools CSV payload should deserialize");

        match input.tools {
            Some(ToolsInput::Csv(value)) => assert_eq!(value, "claude-code,cursor"),
            _ => panic!("expected CSV tools variant"),
        }
        assert_eq!(input.target.as_deref(), Some("codex"));
    }

    #[test]
    fn test_validate_file_input_deserializes_array_tools_payload() {
        let input: ValidateFileInput = serde_json::from_value(json!({
            "path": "SKILL.md",
            "tools": ["claude-code", "cursor"]
        }))
        .expect("tools array payload should deserialize");

        match input.tools {
            Some(ToolsInput::List(values)) => {
                assert_eq!(values, vec!["claude-code", "cursor"]);
            }
            _ => panic!("expected array tools variant"),
        }
        assert!(input.target.is_none());
    }

    #[test]
    fn test_validate_project_input_deserializes_csv_tools_payload() {
        let input: ValidateProjectInput = serde_json::from_value(json!({
            "path": ".",
            "tools": "claude-code,cursor"
        }))
        .expect("project CSV tools payload should deserialize");

        match input.tools {
            Some(ToolsInput::Csv(value)) => assert_eq!(value, "claude-code,cursor"),
            _ => panic!("expected CSV tools variant"),
        }
    }

    #[test]
    fn test_validate_project_input_deserializes_array_tools_payload() {
        let input: ValidateProjectInput = serde_json::from_value(json!({
            "path": ".",
            "tools": ["claude-code", "cursor"]
        }))
        .expect("project array tools payload should deserialize");

        match input.tools {
            Some(ToolsInput::List(values)) => {
                assert_eq!(values, vec!["claude-code", "cursor"]);
            }
            _ => panic!("expected array tools variant"),
        }
    }
}