fallow-mcp 3.8.0

MCP server for fallow codebase intelligence (exposes fallow as typed tools to AI agents)
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
use crate::params::AuditParams;

use fallow_api::{
    AnalysisOptions, AuditGate, AuditOptions, run_audit as run_audit_api,
    serialize_audit_programmatic_json,
};
use rmcp::ErrorData as McpError;
use rmcp::model::{CallToolResult, ContentBlock};

use super::{
    VALID_AUDIT_GATES,
    api_runtime::{
        changed_since_from_param, env_diff_file, json_success, non_empty_path, non_empty_string,
        programmatic_error_body, run_api_blocking,
    },
    fallback_policy::{baseline_fallback_reason, filled, grouped_fallback_reason},
    push_global, push_remote_extends, push_scope, push_str_flag, run_tool, validation_error_body,
};

/// Run the `audit` tool through the typed API when parameters map cleanly to
/// the programmatic contract, falling back to the CLI for CLI-only surfaces.
pub async fn run_audit(binary: &str, params: AuditParams) -> Result<CallToolResult, McpError> {
    if !requires_cli_fallback(&params) {
        let options = match audit_options_from_params(&params) {
            Ok(options) => options,
            Err(msg) => return Ok(CallToolResult::error(vec![ContentBlock::text(msg)])),
        };
        let result = run_api_blocking("audit", move || {
            run_audit_api(&options).and_then(serialize_audit_programmatic_json)
        })
        .await?
        .map_or_else(
            |err| CallToolResult::error(vec![ContentBlock::text(programmatic_error_body(&err))]),
            |value| json_success(&value),
        );
        return Ok(result);
    }

    match build_audit_args(&params) {
        Ok(args) => run_tool(binary, "audit", &args).await,
        Err(msg) => Ok(CallToolResult::error(vec![ContentBlock::text(msg)])),
    }
}

pub fn run_audit_api_value(params: &AuditParams) -> Result<Option<serde_json::Value>, String> {
    if requires_cli_fallback(params) {
        return Ok(None);
    }
    let options = audit_options_from_params(params)?;
    run_audit_api(&options)
        .and_then(serialize_audit_programmatic_json)
        .map(Some)
        .map_err(|err| programmatic_error_body(&err))
}

/// Build CLI arguments for the `audit` tool.
pub fn build_audit_args(params: &AuditParams) -> Result<Vec<String>, String> {
    if let Some(ref gate) = params.gate
        && !VALID_AUDIT_GATES.contains(&gate.as_str())
    {
        return Err(validation_error_body(format!(
            "Invalid gate '{gate}'. Valid values: new-only, all"
        )));
    }

    let mut args = vec![
        "audit".to_string(),
        "--format".to_string(),
        "json".to_string(),
        "--quiet".to_string(),
        "--explain".to_string(),
    ];

    push_global(
        &mut args,
        params.root.as_deref(),
        params.config.as_deref(),
        params.no_cache,
        params.threads,
    );
    push_remote_extends(&mut args, params.allow_remote_extends);
    push_str_flag(&mut args, "--base", params.base.as_deref());
    push_scope(&mut args, params.production, params.workspace.as_deref());
    push_audit_production_flags(&mut args, params);
    if params.css == Some(false) {
        args.push("--no-css".to_string());
    }
    if params.css_deep == Some(true) {
        args.push("--css-deep".to_string());
    } else if params.css_deep == Some(false) {
        args.push("--no-css-deep".to_string());
    }
    push_str_flag(&mut args, "--group-by", params.group_by.as_deref());
    push_str_flag(&mut args, "--gate", params.gate.as_deref());
    push_audit_baseline_flags(&mut args, params);
    if params.explain_skipped == Some(true) {
        args.push("--explain-skipped".to_string());
    }
    push_audit_coverage_flags(&mut args, params);

    Ok(args)
}

/// Push the per-analysis production-mode flags for the `audit` tool.
fn push_audit_production_flags(args: &mut Vec<String>, params: &AuditParams) {
    if params.production_dead_code == Some(true) {
        args.push("--production-dead-code".to_string());
    }
    if params.production_health == Some(true) {
        args.push("--production-health".to_string());
    }
    if params.production_dupes == Some(true) {
        args.push("--production-dupes".to_string());
    }
}

/// Push the per-sub-analysis baseline flags for the `audit` tool.
fn push_audit_baseline_flags(args: &mut Vec<String>, params: &AuditParams) {
    push_str_flag(
        args,
        "--dead-code-baseline",
        params.dead_code_baseline.as_deref(),
    );
    push_str_flag(args, "--health-baseline", params.health_baseline.as_deref());
    push_str_flag(args, "--dupes-baseline", params.dupes_baseline.as_deref());
}

/// Push the coverage, entry-export, and runtime-coverage flags for `audit`.
fn push_audit_coverage_flags(args: &mut Vec<String>, params: &AuditParams) {
    if let Some(max_crap) = params.max_crap {
        args.extend(["--max-crap".to_string(), format!("{max_crap}")]);
    }
    push_str_flag(args, "--coverage", params.coverage.as_deref());
    push_str_flag(args, "--coverage-root", params.coverage_root.as_deref());
    if params.include_entry_exports == Some(true) {
        args.push("--include-entry-exports".to_string());
    }
    push_str_flag(
        args,
        "--runtime-coverage",
        params.runtime_coverage.as_deref(),
    );
    if let Some(min_invocations_hot) = params.min_invocations_hot {
        args.extend([
            "--min-invocations-hot".to_string(),
            format!("{min_invocations_hot}"),
        ]);
    }
}

fn requires_cli_fallback(params: &AuditParams) -> bool {
    cli_fallback_reason(params).is_some()
}

fn cli_fallback_reason(params: &AuditParams) -> Option<&'static str> {
    let gate = params.gate.as_deref().unwrap_or("new-only");
    if !VALID_AUDIT_GATES.contains(&gate) {
        return Some("invalid gate");
    }
    baseline_fallback_reason(params.dead_code_baseline.as_deref(), None)
        .or_else(|| baseline_fallback_reason(params.health_baseline.as_deref(), None))
        .or_else(|| baseline_fallback_reason(params.dupes_baseline.as_deref(), None))
        .or_else(|| grouped_fallback_reason(params.group_by.as_deref()))
        .map(|_| "baseline or grouped output")
        .or_else(|| (params.explain_skipped == Some(true)).then_some("duplication skipped notes"))
        .or_else(|| filled(params.runtime_coverage.as_deref()).then_some("runtime coverage"))
}

fn audit_options_from_params(params: &AuditParams) -> Result<AuditOptions, String> {
    let gate = audit_gate_from_param(params.gate.as_deref())?;
    Ok(AuditOptions {
        analysis: AnalysisOptions {
            root: non_empty_path(params.root.as_deref()),
            config_path: non_empty_path(params.config.as_deref()),
            allow_remote_extends: params.allow_remote_extends.unwrap_or(false),
            no_cache: params.no_cache.unwrap_or(false),
            threads: params.threads,
            diff_file: env_diff_file(),
            production: params.production.unwrap_or(false),
            production_override: params.production,
            changed_since: changed_since_from_param(None),
            workspace: non_empty_string(params.workspace.as_deref()).map(|value| vec![value]),
            changed_workspaces: None,
            explain: true,
        },
        base: non_empty_string(params.base.as_deref()),
        production: params.production.unwrap_or(false),
        production_dead_code: params.production_dead_code,
        production_health: params.production_health,
        production_dupes: params.production_dupes,
        css: params.css,
        css_deep: params.css_deep,
        gate,
        max_crap: params.max_crap,
        coverage: non_empty_path(params.coverage.as_deref()),
        coverage_root: non_empty_path(params.coverage_root.as_deref()),
        include_entry_exports: params.include_entry_exports.unwrap_or(false),
        runtime_coverage: non_empty_path(params.runtime_coverage.as_deref()),
        min_invocations_hot: params.min_invocations_hot.unwrap_or(100),
    })
}

fn audit_gate_from_param(value: Option<&str>) -> Result<AuditGate, String> {
    match value.unwrap_or("new-only") {
        "new-only" => Ok(AuditGate::NewOnly),
        "all" => Ok(AuditGate::All),
        other => Err(validation_error_body(format!(
            "Invalid gate '{other}'. Valid values: new-only, all"
        ))),
    }
}

#[cfg(test)]
mod tests {
    use std::process::Command;

    use rmcp::model::ContentBlock;

    use super::*;

    #[test]
    fn default_new_only_audit_uses_programmatic_api_route() {
        let params = AuditParams::default();
        assert!(!requires_cli_fallback(&params));
        let options = audit_options_from_params(&params).expect("audit options");
        assert_eq!(options.gate, AuditGate::NewOnly);
    }

    #[test]
    fn gate_all_audit_uses_programmatic_api_route() {
        let params = AuditParams {
            gate: Some("all".to_string()),
            ..AuditParams::default()
        };
        assert!(!requires_cli_fallback(&params));
        let options = audit_options_from_params(&params).expect("audit options");
        assert_eq!(options.gate, AuditGate::All);
        assert!(options.analysis.explain);
    }

    #[test]
    fn cli_only_audit_surfaces_keep_fallback() {
        let baseline = AuditParams {
            gate: Some("all".to_string()),
            dead_code_baseline: Some("baseline.json".to_string()),
            ..AuditParams::default()
        };
        let grouped = AuditParams {
            gate: Some("all".to_string()),
            group_by: Some("owner".to_string()),
            ..AuditParams::default()
        };
        let runtime = AuditParams {
            gate: Some("all".to_string()),
            runtime_coverage: Some("coverage".to_string()),
            ..AuditParams::default()
        };

        assert!(requires_cli_fallback(&baseline));
        assert!(requires_cli_fallback(&grouped));
        assert!(requires_cli_fallback(&runtime));
    }

    #[tokio::test]
    async fn run_audit_gate_all_api_path_returns_json_without_cli_binary() {
        let project = audit_fixture();

        let result = run_audit(
            "unused-binary-on-api-path",
            AuditParams {
                root: Some(project.path().display().to_string()),
                base: Some("HEAD".to_string()),
                gate: Some("all".to_string()),
                no_cache: Some(true),
                ..AuditParams::default()
            },
        )
        .await
        .expect("api result");

        assert_eq!(result.is_error, Some(false));
        let text = match &result.content[0] {
            ContentBlock::Text(text) => &text.text,
            _ => panic!("expected text content"),
        };
        let json: serde_json::Value = serde_json::from_str(text).expect("json");
        assert_eq!(json["kind"], "audit");
        assert_eq!(json["command"], "audit");
        assert!(json["dead_code"].is_object());
    }

    #[tokio::test]
    async fn run_audit_default_new_only_api_path_marks_introduced_without_cli_binary() {
        let project = audit_fixture();

        let result = run_audit(
            "unused-binary-on-api-path",
            AuditParams {
                root: Some(project.path().display().to_string()),
                base: Some("HEAD".to_string()),
                no_cache: Some(true),
                ..AuditParams::default()
            },
        )
        .await
        .expect("api result");

        assert_eq!(result.is_error, Some(false));
        let text = match &result.content[0] {
            ContentBlock::Text(text) => &text.text,
            _ => panic!("expected text content"),
        };
        let json: serde_json::Value = serde_json::from_str(text).expect("json");
        assert_eq!(json["kind"], "audit");
        assert_eq!(json["attribution"]["gate"], "new-only");
        assert_eq!(json["attribution"]["dead_code_introduced"], 1);
        assert_eq!(json["dead_code"]["unused_files"][0]["introduced"], true);
    }

    #[test]
    fn audit_api_value_preserves_styling_gate_parity() {
        let project = audit_styling_fixture();
        std::fs::write(
            project.path().join("src/styles.css"),
            "#app .legacy .title { color: red; }\n.plain { color: blue; }\n",
        )
        .expect("write inherited-only change");

        let all = run_audit_api_value(&AuditParams {
            root: Some(project.path().display().to_string()),
            base: Some("HEAD".to_string()),
            gate: Some("all".to_string()),
            no_cache: Some(true),
            ..AuditParams::default()
        })
        .expect("all-gate MCP API value")
        .expect("typed API path");
        assert_eq!(all["verdict"], "fail");

        let new_only = run_audit_api_value(&AuditParams {
            root: Some(project.path().display().to_string()),
            base: Some("HEAD".to_string()),
            no_cache: Some(true),
            ..AuditParams::default()
        })
        .expect("new-only MCP API value")
        .expect("typed API path");
        assert_eq!(new_only["verdict"], "pass");
        assert_eq!(new_only["attribution"]["styling_introduced"], 0);
        assert_eq!(new_only["attribution"]["styling_inherited"], 1);
        assert_eq!(
            new_only["complexity"]["styling_findings"][0]["introduced"],
            false
        );

        std::fs::write(
            project.path().join("src/styles.css"),
            "#app .legacy .title { color: red; }\n.plain { color: blue; }\n#app .introduced .title { color: green; }\n",
        )
        .expect("write introduced styling change");
        let introduced = run_audit_api_value(&AuditParams {
            root: Some(project.path().display().to_string()),
            base: Some("HEAD".to_string()),
            no_cache: Some(true),
            ..AuditParams::default()
        })
        .expect("introduced MCP API value")
        .expect("typed API path");
        assert_eq!(introduced["verdict"], "fail");
        assert_eq!(introduced["attribution"]["styling_introduced"], 1);
        assert_eq!(introduced["attribution"]["styling_inherited"], 1);
        assert!(
            introduced["complexity"]["styling_findings"]
                .as_array()
                .expect("styling findings")
                .iter()
                .any(|finding| finding["line"] == 3 && finding["introduced"] == true)
        );
    }

    fn audit_fixture() -> tempfile::TempDir {
        let project = tempfile::tempdir().expect("project");
        std::fs::create_dir_all(project.path().join("src")).expect("create src");
        std::fs::write(
            project.path().join("package.json"),
            r#"{"name":"audit-api","type":"module","main":"src/index.ts"}"#,
        )
        .expect("write package");
        std::fs::write(
            project.path().join("src/index.ts"),
            "console.log('entry');\n",
        )
        .expect("write entry");
        git(project.path(), &["init"]);
        git(project.path(), &["add", "."]);
        git(
            project.path(),
            &[
                "-c",
                "user.email=test@example.com",
                "-c",
                "user.name=Test",
                "-c",
                "commit.gpgsign=false",
                "commit",
                "-m",
                "initial",
            ],
        );
        std::fs::write(
            project.path().join("src/feature.ts"),
            "export const unused = 1;\n",
        )
        .expect("write changed source");
        project
    }

    fn audit_styling_fixture() -> tempfile::TempDir {
        let project = tempfile::tempdir().expect("project");
        std::fs::create_dir_all(project.path().join("src")).expect("create src");
        std::fs::write(
            project.path().join("package.json"),
            r#"{"name":"audit-mcp-styling","type":"module","main":"src/index.ts"}"#,
        )
        .expect("write package");
        std::fs::write(
            project.path().join(".fallowrc.json"),
            r#"{"rules":{"css-selector-complexity":"error"}}"#,
        )
        .expect("write config");
        std::fs::write(
            project.path().join("src/index.ts"),
            "console.log('entry');\n",
        )
        .expect("write entry");
        std::fs::write(
            project.path().join("src/styles.css"),
            "#app .legacy .title { color: red; }\n",
        )
        .expect("write inherited styling");
        git(project.path(), &["init"]);
        git(project.path(), &["add", "."]);
        git(
            project.path(),
            &[
                "-c",
                "user.email=test@example.com",
                "-c",
                "user.name=Test",
                "-c",
                "commit.gpgsign=false",
                "commit",
                "-m",
                "initial",
            ],
        );
        project
    }

    fn git(root: &std::path::Path, args: &[&str]) {
        let status = Command::new("git")
            .args(args)
            .current_dir(root)
            .status()
            .expect("git command");
        assert!(status.success(), "git {args:?} failed");
    }
}