hanzo-mcp 1.1.23

Hanzo MCP server — a hanzo-mcp binary serving 15 hand-written tools (fs, exec, code, git, fetch, workspace, computer, browser, think, memory, plan, tasks, mode, hanzo, search) over JSON-RPC
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
/// Unified code semantics tool (HIP-0300)
///
/// Handles semantic code operations:
/// - parse: Parse source to AST
/// - serialize: AST to text (round-trips parse→serialize)
/// - symbols: List symbols in file
/// - outline: Symbols with imports/exports
/// - definition: Go to definition
/// - references: Find all references
/// - search_symbol: Find symbols across project
/// - transform: Codemod → Patch
/// - summarize: Compress to summary
/// - metrics: Count files/lines by extension
/// - exports: Extract public exports
/// - types: Find type definitions
/// - hierarchy: Build class inheritance tree
/// - rename: Rename symbols across files
/// - grep_replace: Pattern replacement across files

use anyhow::{anyhow, Result};
use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::HashMap;
use std::path::Path;
use tree_sitter::{Language, Node, Parser};

const SKIP_DIRS: &[&str] = &[".git", "node_modules", "target", "dist", "__pycache__", ".venv", "venv"];

/// Actions for the code tool
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum CodeAction {
    Parse,
    Serialize,
    Symbols,
    Outline,
    Definition,
    References,
    SearchSymbol,
    Transform,
    Summarize,
    Metrics,
    Exports,
    Types,
    Hierarchy,
    Rename,
    GrepReplace,
    Help,
}

impl Default for CodeAction {
    fn default() -> Self {
        Self::Help
    }
}

impl std::str::FromStr for CodeAction {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self> {
        match s.to_lowercase().as_str() {
            "parse" | "ast" => Ok(Self::Parse),
            "serialize" => Ok(Self::Serialize),
            "symbols" => Ok(Self::Symbols),
            "outline" => Ok(Self::Outline),
            "definition" | "goto" => Ok(Self::Definition),
            "references" | "refs" => Ok(Self::References),
            "search_symbol" | "search" => Ok(Self::SearchSymbol),
            "transform" | "codemod" => Ok(Self::Transform),
            "summarize" | "summary" => Ok(Self::Summarize),
            "metrics" => Ok(Self::Metrics),
            "exports" => Ok(Self::Exports),
            "types" => Ok(Self::Types),
            "hierarchy" => Ok(Self::Hierarchy),
            "rename" => Ok(Self::Rename),
            "grep_replace" => Ok(Self::GrepReplace),
            "help" | "" => Ok(Self::Help),
            _ => Err(anyhow!("Unknown action: {}", s)),
        }
    }
}

/// Arguments for code tool
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CodeToolArgs {
    pub action: Option<String>,
    pub uri: Option<String>,
    pub path: Option<String>,
    pub symbol: Option<String>,
    pub language: Option<String>,
    pub query: Option<String>,
    pub spec: Option<String>,
    pub text: Option<String>,
    pub pattern: Option<String>,
    pub new_name: Option<String>,
    pub replacement: Option<String>,
    pub max_results: Option<usize>,
    pub scope: Option<String>,
    pub ast: Option<Value>,
}

/// Tool definition for MCP registration
pub struct CodeToolDefinition;

impl CodeToolDefinition {
    pub fn schema() -> Value {
        json!({
            "name": "code",
            "description": "Code semantics: parse, serialize, symbols, outline, definition, references, search_symbol, transform, summarize, metrics, exports, types, hierarchy, rename, grep_replace",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "action": {
                        "type": "string",
                        "enum": ["parse", "serialize", "symbols", "outline", "definition", "references", "search_symbol", "transform", "summarize", "metrics", "exports", "types", "hierarchy", "rename", "grep_replace", "help"],
                        "description": "Code action"
                    },
                    "uri": { "type": "string", "description": "File path" },
                    "path": { "type": "string", "description": "File or directory path (alias for uri)" },
                    "symbol": { "type": "string", "description": "Symbol name" },
                    "language": { "type": "string", "description": "Programming language" },
                    "query": { "type": "string", "description": "Search query or symbol name" },
                    "spec": { "type": "string", "description": "Transform specification" },
                    "text": { "type": "string", "description": "Raw text input" },
                    "pattern": { "type": "string", "description": "File glob pattern" },
                    "new_name": { "type": "string", "description": "New name for rename" },
                    "replacement": { "type": "string", "description": "Replacement for grep_replace" },
                    "max_results": { "type": "number", "default": 20 },
                    "scope": { "type": "string", "description": "Search scope" },
                    "ast": { "type": "object", "description": "Pre-parsed AST node to serialize back to text" }
                },
                "required": ["action"]
            }
        })
    }
}

/// Code tool implementation
pub struct CodeTool;

impl CodeTool {
    pub fn new() -> Self {
        Self
    }

    fn resolve_uri<'a>(&self, args: &'a CodeToolArgs) -> Option<&'a str> {
        args.uri.as_deref().or(args.path.as_deref())
    }

    fn is_code_file(path: &Path) -> bool {
        matches!(
            path.extension().and_then(|e| e.to_str()),
            Some("rs" | "py" | "js" | "ts" | "tsx" | "jsx" | "go" | "java" | "c" | "cpp" | "h" | "hpp" | "rb" | "swift" | "kt" | "cs" | "lua" | "sh")
        )
    }

    fn should_skip(entry: &std::fs::DirEntry) -> bool {
        entry.file_name().to_str().map_or(false, |n| SKIP_DIRS.contains(&n))
    }

    fn walk_files(dir: &Path) -> Vec<std::path::PathBuf> {
        let mut files = Vec::new();
        fn walk(dir: &Path, files: &mut Vec<std::path::PathBuf>) {
            if let Ok(entries) = std::fs::read_dir(dir) {
                for entry in entries.flatten() {
                    let path = entry.path();
                    if path.is_dir() {
                        if !CodeTool::should_skip(&entry) {
                            walk(&path, files);
                        }
                    } else if CodeTool::is_code_file(&path) {
                        files.push(path);
                    }
                }
            }
        }
        walk(dir, &mut files);
        files
    }

    fn detect_symbol(line: &str) -> Option<(&'static str, String)> {
        let trimmed = line.trim();
        let kind = if trimmed.starts_with("fn ") || trimmed.starts_with("pub fn ") || trimmed.starts_with("async fn ") || trimmed.starts_with("pub async fn ") {
            Some("function")
        } else if trimmed.starts_with("struct ") || trimmed.starts_with("pub struct ") {
            Some("struct")
        } else if trimmed.starts_with("enum ") || trimmed.starts_with("pub enum ") {
            Some("enum")
        } else if trimmed.starts_with("trait ") || trimmed.starts_with("pub trait ") {
            Some("trait")
        } else if trimmed.starts_with("class ") || trimmed.starts_with("export class ") {
            Some("class")
        } else if trimmed.starts_with("def ") || trimmed.starts_with("async def ") {
            Some("function")
        } else if trimmed.starts_with("function ") || trimmed.starts_with("export function ") || trimmed.starts_with("async function ") {
            Some("function")
        } else if trimmed.starts_with("interface ") || trimmed.starts_with("export interface ") {
            Some("interface")
        } else if trimmed.starts_with("type ") || trimmed.starts_with("export type ") {
            Some("type")
        } else {
            None
        };

        kind.and_then(|k| {
            let skip = ["fn", "pub", "async", "struct", "enum", "trait", "class", "def", "function", "export", "interface", "type"];
            let name = trimmed.split_whitespace()
                .find(|w| !skip.contains(w))
                .unwrap_or("")
                .trim_end_matches(|c: char| !c.is_alphanumeric() && c != '_')
                .to_string();
            if name.is_empty() { None } else { Some((k, name)) }
        })
    }

    pub async fn execute(&self, args: CodeToolArgs) -> Result<Value> {
        let action: CodeAction = args.action
            .as_deref()
            .unwrap_or("help")
            .parse()?;

        match action {
            CodeAction::Parse => self.parse(&args).await,
            CodeAction::Serialize => self.serialize(&args).await,
            CodeAction::Symbols => self.symbols(&args).await,
            CodeAction::Outline => self.outline(&args).await,
            CodeAction::Definition => self.definition(&args).await,
            CodeAction::References => self.references(&args).await,
            CodeAction::SearchSymbol => self.search_symbol(&args).await,
            CodeAction::Transform => self.transform(&args).await,
            CodeAction::Summarize => self.summarize(&args).await,
            CodeAction::Metrics => self.metrics(&args).await,
            CodeAction::Exports => self.exports(&args).await,
            CodeAction::Types => self.types(&args).await,
            CodeAction::Hierarchy => self.hierarchy(&args).await,
            CodeAction::Rename => self.rename(&args).await,
            CodeAction::GrepReplace => self.grep_replace(&args).await,
            CodeAction::Help => Ok(self.help()),
        }
    }

    async fn parse(&self, args: &CodeToolArgs) -> Result<Value> {
        let uri = self.resolve_uri(args).ok_or_else(|| anyhow!("uri required"))?;
        let content = tokio::fs::read_to_string(uri).await?;
        let lines = content.lines().count();
        let lang = args.language.clone().unwrap_or_else(|| {
            Path::new(uri).extension().and_then(|e| e.to_str()).unwrap_or("text").to_string()
        });

        Ok(json!({
            "ok": true,
            "data": { "uri": uri, "language": lang, "lines": lines },
            "error": null,
            "meta": { "tool": "code", "action": "parse" }
        }))
    }

    /// Map a language name to its tree-sitter grammar.
    fn ts_language(name: &str) -> Option<Language> {
        Some(match name {
            "rust" => tree_sitter_rust::language(),
            "javascript" | "jsx" => tree_sitter_javascript::language(),
            "typescript" => tree_sitter_typescript::language_typescript(),
            "tsx" => tree_sitter_typescript::language_tsx(),
            "python" => tree_sitter_python::language(),
            "go" => tree_sitter_go::language(),
            "java" => tree_sitter_java::language(),
            "cpp" => tree_sitter_cpp::language(),
            "c" => tree_sitter_c::language(),
            _ => return None,
        })
    }

    /// Resolve a tree-sitter grammar name from a file extension or explicit hint.
    fn ts_lang_name(ext: &str) -> &'static str {
        match ext {
            "rs" => "rust",
            "js" | "mjs" | "cjs" => "javascript",
            "jsx" => "jsx",
            "ts" => "typescript",
            "tsx" => "tsx",
            "py" => "python",
            "go" => "go",
            "java" => "java",
            "cpp" | "cc" | "cxx" | "hpp" => "cpp",
            "c" | "h" => "c",
            _ => "unknown",
        }
    }

    /// Reconstruct source by walking leaf nodes and refilling the inter-leaf
    /// gaps (whitespace/comments-between) from the original bytes. Concatenating
    /// leaf ranges plus gaps yields the exact input, so parse→serialize round-trips.
    fn walk_leaves(node: Node, source: &str, out: &mut String, last_end: &mut usize) {
        if node.child_count() == 0 {
            let range = node.byte_range();
            if range.start > *last_end {
                out.push_str(&source[*last_end..range.start]);
            }
            out.push_str(&source[range.clone()]);
            *last_end = range.end;
            return;
        }
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            Self::walk_leaves(child, source, out, last_end);
        }
    }

    /// Collapse a Python-shaped AST node (`{text}` leaf, else `{children}`) to
    /// text, joining child fragments with a single space. Mirrors the SDK.
    fn ast_node_text(node: &Value) -> String {
        if let Some(text) = node.get("text").and_then(Value::as_str) {
            return text.to_string();
        }
        node.get("children")
            .and_then(Value::as_array)
            .map(|children| children.iter().map(Self::ast_node_text).collect::<Vec<_>>().join(" "))
            .unwrap_or_default()
    }

    async fn serialize(&self, args: &CodeToolArgs) -> Result<Value> {
        // Path 1 — a pre-parsed AST node was supplied: collapse it to text
        // exactly as the Python SDK does (leaf text joined by spaces).
        if let Some(ast) = &args.ast {
            let root = ast.get("root").unwrap_or(ast);
            let text = Self::ast_node_text(root);
            let lang = args.language.clone()
                .or_else(|| ast.get("lang").and_then(Value::as_str).map(str::to_string))
                .unwrap_or_else(|| "unknown".to_string());
            return Ok(json!({
                "ok": true,
                "data": { "text": text, "lang": lang, "method": "ast", "supported": true },
                "error": null,
                "meta": { "tool": "code", "action": "serialize" }
            }));
        }

        // Path 2 — round-trip: parse the source with tree-sitter, then
        // reconstruct it from the parsed tree's leaves.
        let source = if let Some(text) = &args.text {
            text.clone()
        } else if let Some(uri) = self.resolve_uri(args) {
            tokio::fs::read_to_string(uri).await?
        } else {
            return Err(anyhow!("ast, text, or uri required"));
        };

        let lang_name = args.language.clone().unwrap_or_else(|| {
            let ext = self.resolve_uri(args)
                .and_then(|u| Path::new(u).extension().and_then(|e| e.to_str()))
                .unwrap_or("");
            Self::ts_lang_name(ext).to_string()
        });

        let language = Self::ts_language(&lang_name)
            .ok_or_else(|| anyhow!("Unsupported language for serialize: {}", lang_name))?;
        let mut parser = Parser::new();
        parser.set_language(language).map_err(|e| anyhow!("set_language failed: {}", e))?;
        let tree = parser.parse(source.as_bytes(), None)
            .ok_or_else(|| anyhow!("Parse failed for language: {}", lang_name))?;

        let mut text = String::with_capacity(source.len());
        let mut last_end = 0usize;
        Self::walk_leaves(tree.root_node(), &source, &mut text, &mut last_end);
        if last_end < source.len() {
            text.push_str(&source[last_end..]);
        }

        Ok(json!({
            "ok": true,
            "data": {
                "text": text,
                "lang": lang_name,
                "method": "round_trip",
                "supported": true,
                "round_trip": text == source
            },
            "error": null,
            "meta": { "tool": "code", "action": "serialize" }
        }))
    }

    async fn symbols(&self, args: &CodeToolArgs) -> Result<Value> {
        let uri = self.resolve_uri(args).ok_or_else(|| anyhow!("uri required"))?;
        let content = args.text.clone().unwrap_or(tokio::fs::read_to_string(uri).await?);
        let mut symbols = Vec::new();

        for (i, line) in content.lines().enumerate() {
            if let Some((kind, name)) = Self::detect_symbol(line) {
                symbols.push(json!({ "name": name, "kind": kind, "line": i + 1 }));
            }
        }

        Ok(json!({
            "ok": true,
            "data": { "uri": uri, "symbols": symbols, "count": symbols.len() },
            "error": null,
            "meta": { "tool": "code", "action": "symbols" }
        }))
    }

    async fn outline(&self, args: &CodeToolArgs) -> Result<Value> {
        let uri = self.resolve_uri(args).ok_or_else(|| anyhow!("uri required"))?;
        let content = args.text.clone().unwrap_or(tokio::fs::read_to_string(uri).await?);
        let mut symbols = Vec::new();
        let mut imports = 0;

        for (i, line) in content.lines().enumerate() {
            let trimmed = line.trim();
            if trimmed.starts_with("import ") || trimmed.starts_with("from ") || trimmed.starts_with("use ") || trimmed.starts_with("require") {
                imports += 1;
            }
            if let Some((kind, name)) = Self::detect_symbol(line) {
                let exported = trimmed.starts_with("export ") || trimmed.starts_with("pub ");
                symbols.push(json!({ "name": name, "kind": kind, "line": i + 1, "exported": exported }));
            }
        }

        Ok(json!({
            "ok": true,
            "data": { "uri": uri, "symbols": symbols, "imports": imports, "lines": content.lines().count() },
            "error": null,
            "meta": { "tool": "code", "action": "outline" }
        }))
    }

    async fn definition(&self, args: &CodeToolArgs) -> Result<Value> {
        let uri = self.resolve_uri(args).ok_or_else(|| anyhow!("uri required"))?;
        let symbol = args.symbol.as_deref().or(args.query.as_deref()).ok_or_else(|| anyhow!("symbol or query required"))?;
        let content = tokio::fs::read_to_string(uri).await?;

        for (i, line) in content.lines().enumerate() {
            if line.contains(symbol) {
                if let Some(_) = Self::detect_symbol(line) {
                    return Ok(json!({
                        "ok": true,
                        "data": { "uri": uri, "symbol": symbol, "line": i + 1, "text": line.trim() },
                        "error": null,
                        "meta": { "tool": "code", "action": "definition" }
                    }));
                }
            }
        }

        Ok(json!({
            "ok": false,
            "data": null,
            "error": { "code": "NOT_FOUND", "message": format!("Symbol '{}' not found", symbol) },
            "meta": { "tool": "code", "action": "definition" }
        }))
    }

    async fn references(&self, args: &CodeToolArgs) -> Result<Value> {
        let symbol = args.symbol.as_deref().or(args.query.as_deref()).ok_or_else(|| anyhow!("symbol or query required"))?;
        let uri = self.resolve_uri(args).ok_or_else(|| anyhow!("uri required"))?;
        let content = tokio::fs::read_to_string(uri).await?;
        let mut refs = Vec::new();

        for (i, line) in content.lines().enumerate() {
            if line.contains(symbol) {
                refs.push(json!({ "line": i + 1, "text": line.trim() }));
            }
        }

        Ok(json!({
            "ok": true,
            "data": { "uri": uri, "symbol": symbol, "references": refs, "count": refs.len() },
            "error": null,
            "meta": { "tool": "code", "action": "references" }
        }))
    }

    async fn search_symbol(&self, args: &CodeToolArgs) -> Result<Value> {
        let query = args.query.as_deref().ok_or_else(|| anyhow!("query required"))?;
        let dir = self.resolve_uri(args).unwrap_or(".");
        let max = args.max_results.unwrap_or(20);
        let files = Self::walk_files(Path::new(dir));
        let mut results = Vec::new();

        for file in files {
            if results.len() >= max { break; }
            if let Ok(content) = std::fs::read_to_string(&file) {
                for (i, line) in content.lines().enumerate() {
                    if results.len() >= max { break; }
                    if line.contains(query) {
                        if Self::detect_symbol(line).is_some() || line.contains(query) {
                            let is_def = Self::detect_symbol(line).is_some();
                            results.push(json!({
                                "uri": file.display().to_string(),
                                "line": i + 1,
                                "text": line.trim(),
                                "type": if is_def { "definition" } else { "reference" }
                            }));
                        }
                    }
                }
            }
        }

        Ok(json!({
            "ok": true,
            "data": { "query": query, "results": results, "count": results.len() },
            "error": null,
            "meta": { "tool": "code", "action": "search_symbol" }
        }))
    }

    async fn transform(&self, _args: &CodeToolArgs) -> Result<Value> {
        Ok(json!({
            "ok": false,
            "data": null,
            "error": { "code": "NOT_IMPLEMENTED", "message": "Transform requires tree-sitter; use fs(action=apply_patch) for edits" },
            "meta": { "tool": "code", "action": "transform" }
        }))
    }

    async fn summarize(&self, args: &CodeToolArgs) -> Result<Value> {
        let uri = self.resolve_uri(args);
        let content = if let Some(text) = &args.text {
            text.clone()
        } else if let Some(uri) = uri {
            tokio::fs::read_to_string(uri).await?
        } else {
            return Err(anyhow!("uri or text required"));
        };

        let lines = content.lines().count();
        let chars = content.len();
        let words = content.split_whitespace().count();

        // Detect if it's a diff
        let is_diff = content.contains("---") && content.contains("+++");
        let summary = if is_diff {
            let adds = content.lines().filter(|l| l.starts_with('+') && !l.starts_with("+++")).count();
            let dels = content.lines().filter(|l| l.starts_with('-') && !l.starts_with("---")).count();
            format!("Diff: {} lines, {} additions, {} deletions", lines, adds, dels)
        } else {
            format!("{} lines, {} words, {} bytes", lines, words, chars)
        };

        Ok(json!({
            "ok": true,
            "data": { "uri": uri, "lines": lines, "chars": chars, "words": words, "summary": summary },
            "error": null,
            "meta": { "tool": "code", "action": "summarize" }
        }))
    }

    async fn metrics(&self, args: &CodeToolArgs) -> Result<Value> {
        let dir = self.resolve_uri(args).unwrap_or(".");
        let files = Self::walk_files(Path::new(dir));
        let mut by_ext: HashMap<String, (usize, usize)> = HashMap::new(); // (files, lines)
        let mut total_files = 0usize;
        let mut total_lines = 0usize;

        for file in files {
            if let Ok(content) = std::fs::read_to_string(&file) {
                let ext = file.extension().and_then(|e| e.to_str()).unwrap_or("other");
                let ext_key = format!(".{}", ext);
                let lines = content.lines().count();
                let entry = by_ext.entry(ext_key).or_insert((0, 0));
                entry.0 += 1;
                entry.1 += lines;
                total_files += 1;
                total_lines += lines;
            }
        }

        let by_extension: HashMap<String, Value> = by_ext.into_iter()
            .map(|(k, (f, l))| (k, json!({ "files": f, "lines": l })))
            .collect();

        Ok(json!({
            "ok": true,
            "data": { "total_files": total_files, "total_lines": total_lines, "by_extension": by_extension },
            "error": null,
            "meta": { "tool": "code", "action": "metrics" }
        }))
    }

    async fn exports(&self, args: &CodeToolArgs) -> Result<Value> {
        let uri = self.resolve_uri(args).ok_or_else(|| anyhow!("uri required"))?;
        let content = tokio::fs::read_to_string(uri).await?;
        let mut exports = Vec::new();

        for line in content.lines() {
            let trimmed = line.trim();
            if trimmed.starts_with("export ") || trimmed.starts_with("pub ") || trimmed.starts_with("__all__") {
                exports.push(trimmed.to_string());
            }
        }

        Ok(json!({
            "ok": true,
            "data": { "uri": uri, "exports": exports, "count": exports.len() },
            "error": null,
            "meta": { "tool": "code", "action": "exports" }
        }))
    }

    async fn types(&self, args: &CodeToolArgs) -> Result<Value> {
        let uri = self.resolve_uri(args).ok_or_else(|| anyhow!("uri required"))?;
        let content = tokio::fs::read_to_string(uri).await?;
        let mut type_defs = Vec::new();

        let re = Regex::new(r"(?:interface|type|enum|struct)\s+(\w+)").unwrap();
        for (i, line) in content.lines().enumerate() {
            if let Some(m) = re.captures(line) {
                type_defs.push(json!({
                    "name": m.get(1).map(|m| m.as_str()).unwrap_or(""),
                    "line": i + 1,
                    "text": line.trim()
                }));
            }
        }

        Ok(json!({
            "ok": true,
            "data": { "uri": uri, "types": type_defs, "count": type_defs.len() },
            "error": null,
            "meta": { "tool": "code", "action": "types" }
        }))
    }

    async fn hierarchy(&self, args: &CodeToolArgs) -> Result<Value> {
        let query = args.query.as_deref().ok_or_else(|| anyhow!("query (class name) required"))?;
        let dir = self.resolve_uri(args).unwrap_or(".");
        let files = Self::walk_files(Path::new(dir));
        let mut classes: HashMap<String, Vec<String>> = HashMap::new();

        let re = Regex::new(r"class\s+(\w+)(?:\s+extends\s+(\w+)|\s*\((\w+)\))?").unwrap();
        for file in files {
            if let Ok(content) = std::fs::read_to_string(&file) {
                for cap in re.captures_iter(&content) {
                    let name = cap.get(1).map(|m| m.as_str().to_string()).unwrap_or_default();
                    let parent = cap.get(2).or(cap.get(3)).map(|m| m.as_str().to_string());
                    classes.entry(name.clone()).or_default();
                    if let Some(p) = parent {
                        classes.entry(p.clone()).or_default().push(name);
                    }
                }
            }
        }

        fn build_tree(name: &str, classes: &HashMap<String, Vec<String>>, depth: usize) -> String {
            let mut out = "  ".repeat(depth) + name + "\n";
            if let Some(children) = classes.get(name) {
                for child in children {
                    out += &build_tree(child, classes, depth + 1);
                }
            }
            out
        }

        let tree = build_tree(query, &classes, 0);
        let children = classes.get(query).cloned().unwrap_or_default();

        Ok(json!({
            "ok": true,
            "data": { "root": query, "tree": tree, "children": children },
            "error": null,
            "meta": { "tool": "code", "action": "hierarchy" }
        }))
    }

    async fn rename(&self, args: &CodeToolArgs) -> Result<Value> {
        let query = args.query.as_deref().ok_or_else(|| anyhow!("query (old name) required"))?;
        let new_name = args.new_name.as_deref().ok_or_else(|| anyhow!("new_name required"))?;
        let dir = self.resolve_uri(args).unwrap_or(".");
        let files = Self::walk_files(Path::new(dir));
        let re = Regex::new(&format!(r"\b{}\b", regex::escape(query)))?;
        let mut total_changes = 0usize;
        let mut changed = Vec::new();

        for file in files {
            if let Ok(content) = std::fs::read_to_string(&file) {
                if re.is_match(&content) {
                    let count = re.find_iter(&content).count();
                    let updated = re.replace_all(&content, new_name).to_string();
                    std::fs::write(&file, &updated)?;
                    total_changes += count;
                    changed.push(format!("{}: {} replacements", file.display(), count));
                }
            }
        }

        Ok(json!({
            "ok": true,
            "data": { "old_name": query, "new_name": new_name, "files_changed": changed.len(), "total_replacements": total_changes, "changed": changed },
            "error": null,
            "meta": { "tool": "code", "action": "rename" }
        }))
    }

    async fn grep_replace(&self, args: &CodeToolArgs) -> Result<Value> {
        let pattern = args.query.as_deref().ok_or_else(|| anyhow!("query (pattern) required"))?;
        let replacement = args.replacement.as_deref().ok_or_else(|| anyhow!("replacement required"))?;
        let dir = self.resolve_uri(args).unwrap_or(".");
        let files = Self::walk_files(Path::new(dir));
        let re = Regex::new(pattern)?;
        let mut total_changes = 0usize;
        let mut changed = Vec::new();

        for file in files {
            if let Ok(content) = std::fs::read_to_string(&file) {
                if re.is_match(&content) {
                    let count = re.find_iter(&content).count();
                    let updated = re.replace_all(&content, replacement).to_string();
                    std::fs::write(&file, &updated)?;
                    total_changes += count;
                    changed.push(format!("{}: {}", file.display(), count));
                }
            }
        }

        Ok(json!({
            "ok": true,
            "data": { "pattern": pattern, "replacement": replacement, "files_changed": changed.len(), "total_replacements": total_changes, "changed": changed },
            "error": null,
            "meta": { "tool": "code", "action": "grep_replace" }
        }))
    }

    fn help(&self) -> Value {
        json!({
            "ok": true,
            "data": {
                "tool": "code",
                "actions": {
                    "parse": "Parse source to AST (requires uri)",
                    "serialize": "Convert AST to text (round-trip; requires ast, or text/uri)",
                    "symbols": "List symbols in file (requires uri)",
                    "outline": "Symbols with imports/exports (requires uri)",
                    "definition": "Go to symbol definition (requires uri, symbol/query)",
                    "references": "Find all references (requires uri, symbol/query)",
                    "search_symbol": "Find symbols across project (requires query)",
                    "transform": "Codemod → Patch (requires uri, spec)",
                    "summarize": "Compress to summary (requires uri or text)",
                    "metrics": "Count files/lines by extension (optional uri for dir)",
                    "exports": "Extract public exports (requires uri)",
                    "types": "Find type definitions (requires uri)",
                    "hierarchy": "Build class inheritance tree (requires query)",
                    "rename": "Rename symbols across files (requires query, new_name)",
                    "grep_replace": "Pattern replacement across files (requires query, replacement)"
                }
            },
            "error": null,
            "meta": { "tool": "code", "action": "help" }
        })
    }
}

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

    #[test]
    fn test_code_action_parse() {
        let action: CodeAction = "parse".parse().unwrap();
        assert_eq!(action, CodeAction::Parse);
    }

    #[test]
    fn test_code_action_aliases() {
        let action: CodeAction = "outline".parse().unwrap();
        assert_eq!(action, CodeAction::Outline);
        let action: CodeAction = "search".parse().unwrap();
        assert_eq!(action, CodeAction::SearchSymbol);
    }

    #[test]
    fn test_code_action_new_variants() {
        assert_eq!("metrics".parse::<CodeAction>().unwrap(), CodeAction::Metrics);
        assert_eq!("exports".parse::<CodeAction>().unwrap(), CodeAction::Exports);
        assert_eq!("types".parse::<CodeAction>().unwrap(), CodeAction::Types);
        assert_eq!("hierarchy".parse::<CodeAction>().unwrap(), CodeAction::Hierarchy);
        assert_eq!("rename".parse::<CodeAction>().unwrap(), CodeAction::Rename);
        assert_eq!("grep_replace".parse::<CodeAction>().unwrap(), CodeAction::GrepReplace);
        assert_eq!("serialize".parse::<CodeAction>().unwrap(), CodeAction::Serialize);
    }

    #[tokio::test]
    async fn test_serialize_round_trips_source() {
        let src = "fn main() {\n    let x = 1;\n    println!(\"{}\", x);\n}\n";
        let tool = CodeTool::new();
        let args = CodeToolArgs {
            action: Some("serialize".into()),
            text: Some(src.to_string()),
            language: Some("rust".into()),
            ..Default::default()
        };
        let out = tool.serialize(&args).await.unwrap();
        assert_eq!(out["data"]["text"].as_str().unwrap(), src);
        assert_eq!(out["data"]["round_trip"], json!(true));
        assert_eq!(out["data"]["method"], json!("round_trip"));
    }

    #[tokio::test]
    async fn test_serialize_from_ast_node() {
        let ast = json!({
            "lang": "python",
            "root": { "children": [ { "text": "x" }, { "text": "=" }, { "text": "1" } ] }
        });
        let tool = CodeTool::new();
        let args = CodeToolArgs {
            action: Some("serialize".into()),
            ast: Some(ast),
            ..Default::default()
        };
        let out = tool.serialize(&args).await.unwrap();
        assert_eq!(out["data"]["text"].as_str().unwrap(), "x = 1");
        assert_eq!(out["data"]["lang"], json!("python"));
        assert_eq!(out["data"]["method"], json!("ast"));
    }
}