ast-outline 2.0.0

Fast, AST-based structural outline for source files. Built for LLM coding agents and humans.
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
//! MCP tool catalogue and dispatch — wraps the existing CLI render functions.

use serde::Deserialize;
use serde_json::{json, Value};
use std::path::PathBuf;

use crate::core::{
    self, DigestOptions, MapOptions,
};

/// Static descriptors returned to clients via `tools/list`.
pub fn list() -> Value {
    json!({
        "tools": [
            {
                "name": "map",
                "description": "AST-based structural map of source files — signatures with line ranges, no method bodies. Returns text by default (5–10× smaller than reading the file). Set `json: true` for the machine-readable schema `ast-outline.map.v1`.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "paths": {
                            "type": "array",
                            "items": { "type": "string" },
                            "description": "Files or directories to map.",
                            "minItems": 1
                        },
                        "no_private": { "type": "boolean", "description": "Hide private declarations." },
                        "no_fields":  { "type": "boolean", "description": "Hide field declarations." },
                        "no_docs":    { "type": "boolean", "description": "Hide doc comments." },
                        "no_attrs":   { "type": "boolean", "description": "Hide attributes / decorators." },
                        "no_lines":   { "type": "boolean", "description": "Hide line-range suffixes." },
                        "glob":       { "type": "string",  "description": "Glob filter applied during directory walk." },
                        "json":       { "type": "boolean", "description": "Return JSON (schema `ast-outline.map.v1`) instead of text." }
                    },
                    "required": ["paths"]
                }
            },
            {
                "name": "digest",
                "description": "One-page module map for an unfamiliar directory: every file's types and public methods. Returns text by default; set `json: true` for `ast-outline.map.v1`.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "paths": {
                            "type": "array",
                            "items": { "type": "string" },
                            "description": "Files or directories to digest.",
                            "minItems": 1
                        },
                        "include_private": { "type": "boolean" },
                        "include_fields":  { "type": "boolean" },
                        "max_members":     { "type": "integer", "description": "Cap members per type (default 50)." },
                        "json":            { "type": "boolean" }
                    },
                    "required": ["paths"]
                }
            },
            {
                "name": "show",
                "description": "Extract source of one or more symbols from a single file. Suffix matching: `TakeDamage`, or `Player.TakeDamage` when ambiguous. For markdown the symbol is a heading. Returns text by default; set `json: true` for `ast-outline.show.v1`.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "path":    { "type": "string", "description": "File to search." },
                        "symbols": {
                            "type": "array",
                            "items": { "type": "string" },
                            "description": "One or more symbol names to extract.",
                            "minItems": 1
                        },
                        "json":    { "type": "boolean" }
                    },
                    "required": ["path", "symbols"]
                }
            },
            {
                "name": "implements",
                "description": "Find subclasses / implementations of a type using AST matching. Transitive by default — set `direct: true` for level-1 only. Returns text by default; set `json: true` for `ast-outline.implements.v1`.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "target": { "type": "string", "description": "Type name to look up." },
                        "paths":  {
                            "type": "array",
                            "items": { "type": "string" },
                            "description": "Files or directories to search.",
                            "minItems": 1
                        },
                        "direct": { "type": "boolean", "description": "Direct subtypes only (skip transitive)." },
                        "json":   { "type": "boolean" }
                    },
                    "required": ["target", "paths"]
                }
            },
            {
                "name": "surface",
                "description": "True public API surface — resolves `pub use` re-exports (Rust) and `__all__` (Python) to compute exactly what a downstream user sees, not just every `pub`/non-underscore item per file. Falls back to visibility-filtered output for Java/C#/Go/Kotlin (no real re-export concept). Returns text by default; set `json: true` for `ast-outline.surface.v1`.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "path":            { "type": "string",  "description": "Crate root file, package init, or directory to auto-detect (default \".\")." },
                        "tree":            { "type": "boolean", "description": "Render as a hierarchical tree grouped by module." },
                        "include_chain":   { "type": "boolean", "description": "Append the via-chain on each entry (text mode only)." },
                        "max_depth":       { "type": "integer", "description": "Recursion guard for re-export chains (default 16)." },
                        "include_private": { "type": "boolean", "description": "Include private items — only meaningful for the fallback resolver." },
                        "lang":            { "type": "string",  "description": "Force a resolver: `rust`, `python`, or `fallback`." },
                        "json":            { "type": "boolean" }
                    }
                }
            },
            {
                "name": "deps",
                "description": "Forward import-graph traversal: what does this file import (transitively)? Builds a per-repo dep graph at `.ast-outline/deps/graph.bin` on first call, then reuses it. Returns text by default; set `json: true` for `ast-outline.deps.v1`.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "file":    { "type": "string",  "description": "Path to the file whose imports to follow." },
                        "depth":   { "type": "integer", "description": "Max BFS depth (default 3).", "minimum": 1 },
                        "external": { "type": "boolean", "description": "Include unresolved (external) imports." },
                        "rebuild": { "type": "boolean", "description": "Drop the cached graph and rebuild." },
                        "json":    { "type": "boolean" }
                    },
                    "required": ["file"]
                }
            },
            {
                "name": "reverse_deps",
                "description": "Reverse import-graph: who imports this file (transitively)? Useful for refactor blast-radius assessment. Returns text by default; set `json: true` for `ast-outline.reverse-deps.v1`.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "file":    { "type": "string",  "description": "Path to the file whose importers to find." },
                        "depth":   { "type": "integer", "description": "Max BFS depth (default 3).", "minimum": 1 },
                        "limit":   { "type": "integer", "description": "Cap result count (default 200).", "minimum": 1 },
                        "rebuild": { "type": "boolean" },
                        "json":    { "type": "boolean" }
                    },
                    "required": ["file"]
                }
            },
            {
                "name": "cycles",
                "description": "Find import cycles via Tarjan SCC. Returns the list of strongly-connected components with `len > 1` (or singletons with self-edges). Returns text by default; set `json: true` for `ast-outline.cycles.v1`. Exits non-zero when cycles exist (useful for CI gates).",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "path":     { "type": "string",  "description": "Repo root (default \".\")." },
                        "min_size": { "type": "integer", "description": "Drop SCCs smaller than this (default 2).", "minimum": 1 },
                        "rebuild":  { "type": "boolean" },
                        "json":     { "type": "boolean" }
                    }
                }
            },
            {
                "name": "graph",
                "description": "Emit the file-level dependency graph. Returns text by default; set `json: true` for `ast-outline.graph.v1`.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "path":             { "type": "string",  "description": "Repo root (default \".\")." },
                        "json":             { "type": "boolean", "description": "Return JSON (schema `ast-outline.graph.v1`) instead of text." },
                        "include_external": { "type": "boolean", "description": "Include unresolved imports in JSON output." },
                        "rebuild":          { "type": "boolean" }
                    }
                }
            },
            {
                "name": "search",
                "description": "Hybrid BM25 + dense semantic search over the repo. First call builds a per-repo index at `.ast-outline/index/` (one-time, ~seconds for typical repos). Returns text by default; set `json: true` for `ast-outline.search.v1`.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "query":     { "type": "string",  "description": "Search query (free-form text or symbol name)." },
                        "path":      { "type": "string",  "description": "Repo root to search in (default \".\")." },
                        "top_k":     { "type": "integer", "description": "Max results to return (default 10).", "minimum": 1 },
                        "alpha":     { "type": "number",  "description": "Override semantic-vs-BM25 weight (0.0=pure BM25, 1.0=pure semantic). Default auto-detects from query type." },
                        "languages": { "type": "array", "items": { "type": "string" }, "description": "Restrict to chunks of these languages (e.g. [\"rust\", \"python\"])." },
                        "json":      { "type": "boolean", "description": "Return JSON (schema `ast-outline.search.v1`) instead of text." }
                    },
                    "required": ["query"]
                }
            },
            {
                "name": "find_related",
                "description": "Find chunks semantically similar to a given file:line. Useful for navigating to related code. Returns text by default; set `json: true` for `ast-outline.related.v1`.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "path":  { "type": "string",  "description": "Repo-relative path of the source chunk." },
                        "line":  { "type": "integer", "description": "1-indexed line within `path`.", "minimum": 1 },
                        "root":  { "type": "string",  "description": "Repo root containing the index (default \".\")." },
                        "top_k": { "type": "integer", "description": "Max results (default 10).", "minimum": 1 },
                        "json":  { "type": "boolean" }
                    },
                    "required": ["path", "line"]
                }
            },
            {
                "name": "index",
                "description": "Build, refresh, or inspect the per-repo search index. With `stats: true` returns index stats. With `rebuild: true` drops the cache and rebuilds. Otherwise just opens (and incrementally refreshes if files changed). Returns text by default; set `json: true` for `ast-outline.index-stats.v1`.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "path":    { "type": "string",  "description": "Repo root (default \".\")." },
                        "rebuild": { "type": "boolean", "description": "Drop existing cache and rebuild." },
                        "stats":   { "type": "boolean", "description": "Print index stats and return." },
                        "json":    { "type": "boolean" }
                    }
                }
            }
        ]
    })
}

/// Result of dispatching a tool — either textual content or an error message
/// surfaced as `isError: true` on the MCP response.
pub enum CallResult {
    Text(String),
    Error(String),
}

pub fn call(name: &str, args: Value) -> CallResult {
    match name {
        "map"          => run_map(args),
        "digest"       => run_digest(args),
        "show"         => run_show(args),
        "implements"   => run_implements(args),
        "surface"      => run_surface(args),
        "deps"         => run_deps(args),
        "reverse_deps" => run_reverse_deps(args),
        "cycles"       => run_cycles(args),
        "graph"        => run_graph(args),
        "search"       => crate::search::mcp::run_search(args),
        "find_related" => crate::search::mcp::run_find_related(args),
        "index"        => crate::search::mcp::run_index(args),
        other => CallResult::Error(format!("unknown tool: {}", other)),
    }
}

#[derive(Deserialize, Default)]
struct MapArgs {
    paths: Vec<PathBuf>,
    #[serde(default)] no_private: bool,
    #[serde(default)] no_fields: bool,
    #[serde(default)] no_docs: bool,
    #[serde(default)] no_attrs: bool,
    #[serde(default)] no_lines: bool,
    #[serde(default)] glob: Option<String>,
    #[serde(default)] json: bool,
}

fn run_map(args: Value) -> CallResult {
    let a: MapArgs = match serde_json::from_value(args) {
        Ok(v) => v,
        Err(e) => return CallResult::Error(format!("invalid arguments: {}", e)),
    };
    if a.paths.is_empty() {
        return CallResult::Error("`paths` must not be empty".into());
    }
    let results = crate::walk_and_parse(&a.paths, a.glob.as_deref());
    let opts = MapOptions {
        include_private: !a.no_private,
        include_fields: !a.no_fields,
        include_docs: !a.no_docs,
        include_attributes: !a.no_attrs,
        include_line_numbers: !a.no_lines,
        max_doc_lines: 6,
        max_members: None,
    };
    if a.json {
        CallResult::Text(core::render_json_map(&results, &opts, true))
    } else {
        let mut out = String::new();
        for res in &results {
            out.push_str(&core::render_map(res, &opts));
            out.push('\n');
        }
        CallResult::Text(out)
    }
}

#[derive(Deserialize, Default)]
struct DigestArgs {
    paths: Vec<PathBuf>,
    #[serde(default)] include_private: bool,
    #[serde(default)] include_fields: bool,
    #[serde(default = "default_max_members")] max_members: usize,
    #[serde(default)] json: bool,
}

fn default_max_members() -> usize { 50 }

fn run_digest(args: Value) -> CallResult {
    let a: DigestArgs = match serde_json::from_value(args) {
        Ok(v) => v,
        Err(e) => return CallResult::Error(format!("invalid arguments: {}", e)),
    };
    if a.paths.is_empty() {
        return CallResult::Error("`paths` must not be empty".into());
    }
    let results = crate::walk_and_parse(&a.paths, None);
    if a.json {
        let opts = MapOptions {
            include_private: a.include_private,
            include_fields: a.include_fields,
            include_docs: true,
            include_attributes: true,
            include_line_numbers: true,
            max_doc_lines: 6,
            max_members: Some(a.max_members),
        };
        CallResult::Text(core::render_json_map(&results, &opts, true))
    } else {
        let opts = DigestOptions {
            include_private: a.include_private,
            include_fields: a.include_fields,
            max_members_per_type: a.max_members,
            max_heading_depth: 3,
        };
        let root = if a.paths.len() == 1 && a.paths[0].is_dir() {
            Some(a.paths[0].as_path())
        } else {
            None
        };
        CallResult::Text(core::render_digest(&results, &opts, root))
    }
}

#[derive(Deserialize)]
struct ShowArgs {
    path: PathBuf,
    symbols: Vec<String>,
    #[serde(default)] json: bool,
}

fn run_show(args: Value) -> CallResult {
    let a: ShowArgs = match serde_json::from_value(args) {
        Ok(v) => v,
        Err(e) => return CallResult::Error(format!("invalid arguments: {}", e)),
    };
    if a.symbols.is_empty() {
        return CallResult::Error("`symbols` must not be empty".into());
    }
    let res = match crate::parse_file(&a.path) {
        Some(r) => r,
        None => return CallResult::Error(format!("could not parse file: {}", a.path.display())),
    };

    let mut seen = std::collections::HashSet::new();
    let mut all = Vec::new();
    for sym in &a.symbols {
        for m in core::find_symbols(&res, sym) {
            let key = (m.start_line, m.end_line, m.qualified_name.clone());
            if seen.insert(key) {
                all.push(m);
            }
        }
    }

    if a.json {
        CallResult::Text(core::render_json_show(&res, &all, true))
    } else {
        let mut out = String::new();
        for m in &all {
            out.push_str(&format!(
                "# {}:{}-{} {} ({})\n",
                res.path.display(), m.start_line, m.end_line, m.qualified_name, m.kind
            ));
            if !m.ancestor_signatures.is_empty() {
                out.push_str(&format!("# in: {}\n", m.ancestor_signatures.join("")));
            }
            out.push_str(&m.source);
            out.push('\n');
        }
        CallResult::Text(out)
    }
}

#[derive(Deserialize)]
struct ImplementsArgs {
    target: String,
    paths: Vec<PathBuf>,
    #[serde(default)] direct: bool,
    #[serde(default)] json: bool,
}

#[derive(Deserialize, Default)]
struct SurfaceArgs {
    #[serde(default = "default_surface_path")]
    path: PathBuf,
    #[serde(default)] tree: bool,
    #[serde(default)] include_chain: bool,
    #[serde(default = "default_surface_max_depth")] max_depth: usize,
    #[serde(default)] include_private: bool,
    #[serde(default)] lang: Option<String>,
    #[serde(default)] json: bool,
}

fn default_surface_path() -> PathBuf {
    PathBuf::from(".")
}
fn default_surface_max_depth() -> usize {
    16
}

fn run_surface(args: Value) -> CallResult {
    let a: SurfaceArgs = match serde_json::from_value(args) {
        Ok(v) => v,
        Err(e) => return CallResult::Error(format!("invalid arguments: {}", e)),
    };
    let lang_override = match a.lang {
        Some(s) => match crate::surface::LangOverride::parse(&s) {
            Some(l) => Some(l),
            None => return CallResult::Error(format!("unknown lang: {}", s)),
        },
        None => None,
    };
    let output = if a.json {
        crate::surface::OutputMode::Json { compact: false }
    } else if a.tree {
        crate::surface::OutputMode::Tree
    } else {
        crate::surface::OutputMode::Flat
    };
    let opts = crate::surface::SurfaceOptions {
        output,
        include_private: a.include_private,
        max_depth: a.max_depth,
        include_chain: a.include_chain,
        lang_override,
    };
    match crate::surface::resolve_surface(&a.path, &opts) {
        Ok(entries) => {
            CallResult::Text(crate::surface::render::render(&entries, output, a.include_chain))
        }
        Err(e) => CallResult::Error(format!("{e}")),
    }
}

fn run_implements(args: Value) -> CallResult {
    let a: ImplementsArgs = match serde_json::from_value(args) {
        Ok(v) => v,
        Err(e) => return CallResult::Error(format!("invalid arguments: {}", e)),
    };
    if a.paths.is_empty() {
        return CallResult::Error("`paths` must not be empty".into());
    }
    let results = crate::walk_and_parse(&a.paths, None);
    let transitive = !a.direct;
    let matches = core::find_implementations(&results, &a.target, transitive);

    if a.json {
        CallResult::Text(core::render_json_implements(&a.target, &matches, transitive, true))
    } else {
        let mut out = format!(
            "# {} match(es) for '{}' (incl. transitive):\n",
            matches.len(), a.target
        );
        for m in &matches {
            let via = if m.via.is_empty() {
                String::new()
            } else {
                format!(" [via {}]", m.via.last().unwrap())
            };
            out.push_str(&format!("{}:{}  {} {}{}\n", m.path, m.start_line, m.kind, m.name, via));
        }
        CallResult::Text(out)
    }
}

// ---- deps / reverse-deps / cycles / graph ----

#[derive(Deserialize, Default)]
struct DepsArgs {
    file: PathBuf,
    #[serde(default = "default_depth")] depth: usize,
    #[serde(default)] external: bool,
    #[serde(default)] rebuild: bool,
    #[serde(default)] json: bool,
}

#[derive(Deserialize, Default)]
struct ReverseDepsArgs {
    file: PathBuf,
    #[serde(default = "default_depth")] depth: usize,
    #[serde(default = "default_limit")] limit: usize,
    #[serde(default)] rebuild: bool,
    #[serde(default)] json: bool,
}

#[derive(Deserialize, Default)]
struct CyclesArgs {
    #[serde(default = "default_path")] path: PathBuf,
    #[serde(default = "default_min_size")] min_size: usize,
    #[serde(default)] rebuild: bool,
    #[serde(default)] json: bool,
}

#[derive(Deserialize, Default)]
struct GraphArgs {
    #[serde(default = "default_path")] path: PathBuf,
    #[serde(default)] json: bool,
    #[serde(default)] include_external: bool,
    #[serde(default)] rebuild: bool,
}

fn default_depth() -> usize { 3 }
fn default_limit() -> usize { 200 }
fn default_min_size() -> usize { 2 }
fn default_path() -> PathBuf { PathBuf::from(".") }

fn run_deps(args: Value) -> CallResult {
    let a: DepsArgs = match serde_json::from_value(args) {
        Ok(v) => v,
        Err(e) => return CallResult::Error(format!("invalid arguments: {}", e)),
    };
    let root = match crate::deps::cli::find_root_for(&a.file) {
        Ok(r) => r,
        Err(e) => return CallResult::Error(e),
    };
    let graph = match crate::deps::load_or_build(&root, a.rebuild) {
        Ok(g) => g,
        Err(e) => return CallResult::Error(e.to_string()),
    };
    let canon = match a.file.canonicalize() {
        Ok(c) => c,
        Err(e) => return CallResult::Error(format!("cannot resolve {}: {}", a.file.display(), e)),
    };
    let _ = a.external; // forwarded but only relevant to graph; deps text always shows what's resolved.
    let hits = crate::deps::traverse::forward(&graph, &canon, a.depth.max(1));
    if a.json {
        CallResult::Text(crate::deps::render::render_deps_json(&graph, &canon, &hits, true))
    } else {
        CallResult::Text(crate::deps::render::render_deps_text(&graph, &canon, &hits))
    }
}

fn run_reverse_deps(args: Value) -> CallResult {
    let a: ReverseDepsArgs = match serde_json::from_value(args) {
        Ok(v) => v,
        Err(e) => return CallResult::Error(format!("invalid arguments: {}", e)),
    };
    let root = match crate::deps::cli::find_root_for(&a.file) {
        Ok(r) => r,
        Err(e) => return CallResult::Error(e),
    };
    let graph = match crate::deps::load_or_build(&root, a.rebuild) {
        Ok(g) => g,
        Err(e) => return CallResult::Error(e.to_string()),
    };
    let canon = match a.file.canonicalize() {
        Ok(c) => c,
        Err(e) => return CallResult::Error(format!("cannot resolve {}: {}", a.file.display(), e)),
    };
    let hits = crate::deps::traverse::reverse(&graph, &canon, a.depth.max(1), a.limit);
    if a.json {
        CallResult::Text(crate::deps::render::render_reverse_deps_json(&graph, &canon, &hits, true))
    } else {
        CallResult::Text(crate::deps::render::render_reverse_deps_text(&graph, &canon, &hits))
    }
}

fn run_cycles(args: Value) -> CallResult {
    let a: CyclesArgs = match serde_json::from_value(args) {
        Ok(v) => v,
        Err(e) => return CallResult::Error(format!("invalid arguments: {}", e)),
    };
    let root = match a.path.canonicalize() {
        Ok(r) => r,
        Err(e) => return CallResult::Error(format!("cannot resolve {}: {}", a.path.display(), e)),
    };
    let graph = match crate::deps::load_or_build(&root, a.rebuild) {
        Ok(g) => g,
        Err(e) => return CallResult::Error(e.to_string()),
    };
    let cycles = crate::deps::scc::detect(&graph, a.min_size);
    if a.json {
        CallResult::Text(crate::deps::render::render_cycles_json(&graph, &cycles, true))
    } else {
        CallResult::Text(crate::deps::render::render_cycles_text(&graph, &cycles))
    }
}

fn run_graph(args: Value) -> CallResult {
    let a: GraphArgs = match serde_json::from_value(args) {
        Ok(v) => v,
        Err(e) => return CallResult::Error(format!("invalid arguments: {}", e)),
    };
    let root = match a.path.canonicalize() {
        Ok(r) => r,
        Err(e) => return CallResult::Error(format!("cannot resolve {}: {}", a.path.display(), e)),
    };
    let graph = match crate::deps::load_or_build(&root, a.rebuild) {
        Ok(g) => g,
        Err(e) => return CallResult::Error(e.to_string()),
    };
    let body = if a.json {
        crate::deps::render::render_graph_json(&graph, a.include_external, true)
    } else {
        crate::deps::render::render_graph_text(&graph)
    };
    CallResult::Text(body)
}