heliosdb-nano 3.30.0

PostgreSQL-compatible embedded database with TDE + ZKE encryption, HNSW vector search, Product Quantization, git-like branching, time-travel queries, materialized views, row-level security, and 50+ enterprise features
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
//! Auto-registered MCP tools that surface the `code_graph::lsp_*`
//! functions over the JSON-RPC dispatcher.
//!
//! Loading this module is purely a side effect: each `mcp_tool!` call
//! submits an [`auto_register::McpExtensionTool`] entry to the
//! process-wide inventory at startup, which `tools::list_tools` and
//! `tools::call_tool` consult automatically.
//!
//! Adding a new LSP-shaped tool is a one-block change in this file —
//! no edits to `tools.rs` required. That's the FR 5 promise.

use serde::Deserialize;
use serde_json::{json, Value as JsonValue};

use crate::code_graph::{
    self, ast_diff, lsp_body_diff, lsp_references_diff, AsOfRef, CallDirection, DefinitionHint,
    RenameApplyOptions,
};
use crate::{EmbeddedDatabase, Value};

use super::auto_register::McpExtensionTool;
use super::tools::ToolOutcome;

// ---- helios_lsp_definition -------------------------------------------

#[derive(Debug, Deserialize)]
struct DefArgs {
    name: String,
    #[serde(default)]
    hint_file: Option<String>,
    #[serde(default)]
    hint_kind: Option<String>,
}

fn lsp_definition_handler(
    db: Option<&EmbeddedDatabase>,
    args: JsonValue,
) -> ToolOutcome {
    let Some(db) = db else {
        return ToolOutcome::err("helios_lsp_definition requires a database connection");
    };
    let input: DefArgs = match serde_json::from_value(args) {
        Ok(v) => v,
        Err(e) => return ToolOutcome::err(format!("invalid arguments: {e}")),
    };
    let hint = DefinitionHint {
        hint_file: input.hint_file,
        hint_kind: input.hint_kind,
    };
    match code_graph::lsp_definition(db, &input.name, &hint) {
        Ok(rows) => ToolOutcome::ok(json!({
            "name": input.name,
            "count": rows.len(),
            "rows": rows
                .iter()
                .map(|r| json!({
                    "symbol_id": r.symbol_id,
                    "path": r.path,
                    "line": r.line,
                    "signature": r.signature,
                    "qualified": r.qualified,
                    "score": r.score,
                }))
                .collect::<Vec<_>>(),
        })),
        Err(e) => ToolOutcome::err(format!("lsp_definition failed: {e}")),
    }
}

inventory::submit! {
    McpExtensionTool {
        name: "helios_lsp_definition",
        description: "Locate where a symbol is defined, with optional file/kind hints.",
        schema: lsp_definition_schema,
        handler: lsp_definition_handler,
    }
}

fn lsp_definition_schema() -> JsonValue {
    json!({
        "type": "object",
        "properties": {
            "name":      { "type": "string", "description": "Symbol name to resolve" },
            "hint_file": { "type": "string", "description": "Optional path filter" },
            "hint_kind": { "type": "string", "description": "Optional kind filter (function / struct / …)" }
        },
        "required": ["name"]
    })
}

// ---- helios_lsp_references -------------------------------------------

#[derive(Debug, Deserialize)]
struct RefsArgs {
    symbol_id: i64,
}

fn lsp_references_handler(
    db: Option<&EmbeddedDatabase>,
    args: JsonValue,
) -> ToolOutcome {
    let Some(db) = db else {
        return ToolOutcome::err("helios_lsp_references requires a database connection");
    };
    let input: RefsArgs = match serde_json::from_value(args) {
        Ok(v) => v,
        Err(e) => return ToolOutcome::err(format!("invalid arguments: {e}")),
    };
    match code_graph::lsp_references(db, input.symbol_id) {
        Ok(rows) => ToolOutcome::ok(json!({
            "symbol_id": input.symbol_id,
            "count": rows.len(),
            "rows": rows
                .iter()
                .map(|r| json!({
                    "file_id": r.file_id,
                    "path": r.path,
                    "line": r.line,
                    "kind": r.kind,
                    "caller_symbol_id": r.caller_symbol_id,
                }))
                .collect::<Vec<_>>(),
        })),
        Err(e) => ToolOutcome::err(format!("lsp_references failed: {e}")),
    }
}

inventory::submit! {
    McpExtensionTool {
        name: "helios_lsp_references",
        description: "List every call/use site of the given symbol.",
        schema: lsp_references_schema,
        handler: lsp_references_handler,
    }
}

fn lsp_references_schema() -> JsonValue {
    json!({
        "type": "object",
        "properties": {
            "symbol_id": { "type": "integer", "description": "Target symbol's node_id" }
        },
        "required": ["symbol_id"]
    })
}

// ---- helios_lsp_call_hierarchy ---------------------------------------

#[derive(Debug, Deserialize)]
struct CallArgs {
    symbol_id: i64,
    #[serde(default = "default_direction")]
    direction: String,
    #[serde(default = "default_depth")]
    depth: u32,
}

fn default_direction() -> String { "outgoing".to_string() }
fn default_depth() -> u32 { 3 }

fn lsp_call_hierarchy_handler(
    db: Option<&EmbeddedDatabase>,
    args: JsonValue,
) -> ToolOutcome {
    let Some(db) = db else {
        return ToolOutcome::err("helios_lsp_call_hierarchy requires a database connection");
    };
    let input: CallArgs = match serde_json::from_value(args) {
        Ok(v) => v,
        Err(e) => return ToolOutcome::err(format!("invalid arguments: {e}")),
    };
    let direction = match input.direction.to_ascii_lowercase().as_str() {
        "incoming" | "callers" | "in" => CallDirection::Incoming,
        "outgoing" | "callees" | "out" => CallDirection::Outgoing,
        other => return ToolOutcome::err(format!("unknown direction '{other}'")),
    };
    match code_graph::lsp_call_hierarchy(db, input.symbol_id, direction, input.depth) {
        Ok(rows) => ToolOutcome::ok(json!({
            "symbol_id": input.symbol_id,
            "direction": format!("{direction:?}"),
            "depth": input.depth,
            "count": rows.len(),
            "rows": rows
                .iter()
                .map(|r| json!({
                    "depth": r.depth,
                    "symbol_id": r.symbol_id,
                    "qualified": r.qualified,
                    "path": r.path,
                    "line": r.line,
                }))
                .collect::<Vec<_>>(),
        })),
        Err(e) => ToolOutcome::err(format!("lsp_call_hierarchy failed: {e}")),
    }
}

inventory::submit! {
    McpExtensionTool {
        name: "helios_lsp_call_hierarchy",
        description: "BFS-style call tree rooted at a symbol (incoming or outgoing).",
        schema: lsp_call_hierarchy_schema,
        handler: lsp_call_hierarchy_handler,
    }
}

fn lsp_call_hierarchy_schema() -> JsonValue {
    json!({
        "type": "object",
        "properties": {
            "symbol_id": { "type": "integer" },
            "direction": { "type": "string", "enum": ["incoming", "outgoing"], "default": "outgoing" },
            "depth":     { "type": "integer", "default": 3 }
        },
        "required": ["symbol_id"]
    })
}

// ---- helios_lsp_hover ------------------------------------------------

#[derive(Debug, Deserialize)]
struct HoverArgs {
    symbol_id: i64,
}

fn lsp_hover_handler(db: Option<&EmbeddedDatabase>, args: JsonValue) -> ToolOutcome {
    let Some(db) = db else {
        return ToolOutcome::err("helios_lsp_hover requires a database connection");
    };
    let input: HoverArgs = match serde_json::from_value(args) {
        Ok(v) => v,
        Err(e) => return ToolOutcome::err(format!("invalid arguments: {e}")),
    };
    match code_graph::lsp_hover(db, input.symbol_id) {
        Ok(Some(h)) => ToolOutcome::ok(json!({
            "symbol_id": input.symbol_id,
            "signature": h.signature,
            "doc": h.doc,
            "ai_summary": h.ai_summary,
        })),
        Ok(None) => ToolOutcome::ok(json!({
            "symbol_id": input.symbol_id,
            "found": false,
        })),
        Err(e) => ToolOutcome::err(format!("lsp_hover failed: {e}")),
    }
}

inventory::submit! {
    McpExtensionTool {
        name: "helios_lsp_hover",
        description: "Return the signature / doc / AI summary for a symbol.",
        schema: lsp_hover_schema,
        handler: lsp_hover_handler,
    }
}

fn lsp_hover_schema() -> JsonValue {
    json!({
        "type": "object",
        "properties": {
            "symbol_id": { "type": "integer" }
        },
        "required": ["symbol_id"]
    })
}

// ---- helios_lsp_document_symbols -------------------------------------

#[derive(Debug, Deserialize)]
struct DocSymArgs {
    /// File path as it appears in `_hdb_code_files.path`.
    path: String,
    /// Optional kind filter (e.g. ["function", "struct"]).
    #[serde(default)]
    kinds: Vec<String>,
}

fn lsp_document_symbols_handler(
    db: Option<&EmbeddedDatabase>,
    args: JsonValue,
) -> ToolOutcome {
    let Some(db) = db else {
        return ToolOutcome::err("helios_lsp_document_symbols requires a database connection");
    };
    let input: DocSymArgs = match serde_json::from_value(args) {
        Ok(v) => v,
        Err(e) => return ToolOutcome::err(format!("invalid arguments: {e}")),
    };
    let mut sql = String::from(
        "SELECT s.node_id, s.qualified, s.name, s.kind, s.signature, \
                s.line_start, s.line_end \
         FROM _hdb_code_symbols s \
         JOIN _hdb_code_files f ON f.node_id = s.file_id \
         WHERE f.path = $1",
    );
    if !input.kinds.is_empty() {
        sql.push_str(" AND s.kind IN (");
        for (i, _) in input.kinds.iter().enumerate() {
            if i > 0 { sql.push(','); }
            sql.push_str(&format!("${}", i + 2));
        }
        sql.push(')');
    }
    sql.push_str(" ORDER BY s.line_start, s.node_id");

    let mut params: Vec<Value> = vec![Value::String(input.path.clone())];
    for k in &input.kinds {
        params.push(Value::String(k.clone()));
    }
    let rows = match db.query_params(&sql, &params) {
        Ok(r) => r,
        Err(e) => return ToolOutcome::err(format!("document_symbols query failed: {e}")),
    };
    let symbols: Vec<JsonValue> = rows
        .iter()
        .map(|r| {
            json!({
                "symbol_id": value_to_i64(r.values.first()),
                "qualified": value_to_string(r.values.get(1)),
                "name":      value_to_string(r.values.get(2)),
                "kind":      value_to_string(r.values.get(3)),
                "signature": value_to_string(r.values.get(4)),
                "line_start": value_to_i64(r.values.get(5)),
                "line_end":   value_to_i64(r.values.get(6)),
            })
        })
        .collect();
    ToolOutcome::ok(json!({
        "path": input.path,
        "count": symbols.len(),
        "symbols": symbols,
    }))
}

inventory::submit! {
    McpExtensionTool {
        name: "helios_lsp_document_symbols",
        description: "File outline — list every symbol in `_hdb_code_files.path`, ordered by line.",
        schema: lsp_document_symbols_schema,
        handler: lsp_document_symbols_handler,
    }
}

fn lsp_document_symbols_schema() -> JsonValue {
    json!({
        "type": "object",
        "properties": {
            "path":  { "type": "string", "description": "File path as stored in _hdb_code_files.path" },
            "kinds": { "type": "array",  "items": { "type": "string" }, "description": "Optional kind filter" }
        },
        "required": ["path"]
    })
}

// ---- helios_lsp_rename_preview ---------------------------------------

#[derive(Debug, Deserialize)]
struct RenameArgs {
    symbol_id: i64,
    new_name: String,
}

fn lsp_rename_preview_handler(
    db: Option<&EmbeddedDatabase>,
    args: JsonValue,
) -> ToolOutcome {
    let Some(db) = db else {
        return ToolOutcome::err("helios_lsp_rename_preview requires a database connection");
    };
    let input: RenameArgs = match serde_json::from_value(args) {
        Ok(v) => v,
        Err(e) => return ToolOutcome::err(format!("invalid arguments: {e}")),
    };
    if input.new_name.trim().is_empty() {
        return ToolOutcome::err("new_name must not be empty");
    }
    // Pull definition site for the requested symbol_id.
    let def_rows = match db.query_params(
        "SELECT s.qualified, s.name, s.kind, f.path, s.line_start, s.signature \
         FROM _hdb_code_symbols s \
         JOIN _hdb_code_files f ON f.node_id = s.file_id \
         WHERE s.node_id = $1",
        &[Value::Int8(input.symbol_id)],
    ) {
        Ok(r) => r,
        Err(e) => return ToolOutcome::err(format!("rename_preview lookup failed: {e}")),
    };
    let Some(def) = def_rows.first() else {
        return ToolOutcome::ok(json!({
            "symbol_id": input.symbol_id,
            "new_name": input.new_name,
            "found": false,
            "edits": [],
        }));
    };

    let qualified = value_to_string(def.values.first()).unwrap_or_default();
    let old_name = value_to_string(def.values.get(1)).unwrap_or_default();
    let kind = value_to_string(def.values.get(2)).unwrap_or_default();
    let def_path = value_to_string(def.values.get(3)).unwrap_or_default();
    let def_line = value_to_i64(def.values.get(4)).unwrap_or(0);
    let signature = value_to_string(def.values.get(5)).unwrap_or_default();

    // Pull every reference site that points at this symbol.
    let ref_rows = match code_graph::lsp_references(db, input.symbol_id) {
        Ok(r) => r,
        Err(e) => return ToolOutcome::err(format!("rename_preview refs failed: {e}")),
    };

    // Build an edit list. Phase-1 preview is line-granular: each
    // reference site is one edit at (path, line) replacing `old_name`
    // with `new_name`. Caller is responsible for actually rewriting.
    let mut edits: Vec<JsonValue> = Vec::new();
    edits.push(json!({
        "kind": "definition",
        "path": def_path,
        "line": def_line,
        "old_name": old_name,
        "new_name": input.new_name,
        "signature": signature,
    }));
    for r in &ref_rows {
        edits.push(json!({
            "kind": "reference",
            "path": r.path,
            "line": r.line,
            "ref_kind": r.kind,
            "old_name": old_name,
            "new_name": input.new_name,
            "caller_symbol_id": r.caller_symbol_id,
        }));
    }

    ToolOutcome::ok(json!({
        "symbol_id": input.symbol_id,
        "qualified": qualified,
        "kind": kind,
        "old_name": old_name,
        "new_name": input.new_name,
        "found": true,
        "edit_count": edits.len(),
        "edits": edits,
        "applied": false,
        "note": "preview-only: nothing written. Apply manually or via a follow-up tool.",
    }))
}

inventory::submit! {
    McpExtensionTool {
        name: "helios_lsp_rename_preview",
        description: "Preview a symbol rename — collects definition + every reference site \
                      and returns the edit list. Read-only; no source rewrite.",
        schema: lsp_rename_preview_schema,
        handler: lsp_rename_preview_handler,
    }
}

fn lsp_rename_preview_schema() -> JsonValue {
    json!({
        "type": "object",
        "properties": {
            "symbol_id": { "type": "integer" },
            "new_name":  { "type": "string" }
        },
        "required": ["symbol_id", "new_name"]
    })
}

// ---- helios_lsp_rename_apply -----------------------------------------

#[derive(Debug, Deserialize)]
struct RenameApplyArgs {
    symbol_id: i64,
    new_name: String,
    #[serde(default = "default_source_table")]
    source_table: String,
    #[serde(default)]
    dry_run: bool,
    #[serde(default = "default_strict")]
    strict_hash_check: bool,
}

fn default_strict() -> bool { true }
fn default_source_table() -> String { "src".to_string() }

fn lsp_rename_apply_handler(
    db: Option<&EmbeddedDatabase>,
    args: JsonValue,
) -> ToolOutcome {
    let Some(db) = db else {
        return ToolOutcome::err("helios_lsp_rename_apply requires a database connection");
    };
    let input: RenameApplyArgs = match serde_json::from_value(args) {
        Ok(v) => v,
        Err(e) => return ToolOutcome::err(format!("invalid arguments: {e}")),
    };
    let opts = RenameApplyOptions {
        source_table: input.source_table,
        dry_run: input.dry_run,
        strict_hash_check: input.strict_hash_check,
    };
    match code_graph::rename_apply(db, input.symbol_id, &input.new_name, &opts) {
        Ok(stats) => ToolOutcome::ok(json!({
            "symbol_id": input.symbol_id,
            "new_name": input.new_name,
            "files_modified": stats.files_modified,
            "occurrences_replaced": stats.occurrences_replaced,
            "applied": stats.applied,
            "conflicted_paths": stats.conflicted_paths,
        })),
        Err(e) => ToolOutcome::err(format!("rename_apply failed: {e}")),
    }
}

inventory::submit! {
    McpExtensionTool {
        name: "helios_lsp_rename_apply",
        description: "Apply a symbol rename — write replacements back to the source \
                      rows. Identifier-boundary aware; conflict-aware via sha256 hash \
                      check. Pair with helios_lsp_rename_preview for review-then-commit.",
        schema: lsp_rename_apply_schema,
        handler: lsp_rename_apply_handler,
    }
}

fn lsp_rename_apply_schema() -> JsonValue {
    json!({
        "type": "object",
        "properties": {
            "symbol_id":         { "type": "integer" },
            "new_name":          { "type": "string"  },
            "source_table":      { "type": "string", "default": "src",
                                    "description": "User table holding (path, content) source rows" },
            "dry_run":           { "type": "boolean", "default": false },
            "strict_hash_check": { "type": "boolean", "default": true }
        },
        "required": ["symbol_id", "new_name"]
    })
}

// ---- Diff tools (FR 3.3 wrappers) ------------------------------------

fn parse_as_of(v: &JsonValue) -> Result<AsOfRef, String> {
    if v.is_null() {
        return Ok(AsOfRef::Now);
    }
    if let Some(s) = v.as_str() {
        if s.eq_ignore_ascii_case("now") {
            return Ok(AsOfRef::Now);
        }
        return Err(format!(
            "as_of must be an object {{ commit | timestamp | now }}, got string '{s}'"
        ));
    }
    let obj = v.as_object().ok_or_else(|| {
        "as_of must be an object with one of: commit, timestamp, now=true".to_string()
    })?;
    if obj.get("now").and_then(|x| x.as_bool()) == Some(true) {
        return Ok(AsOfRef::Now);
    }
    if let Some(c) = obj.get("commit").and_then(|x| x.as_str()) {
        return Ok(AsOfRef::Commit(c.to_string()));
    }
    if let Some(t) = obj.get("timestamp").and_then(|x| x.as_str()) {
        return Ok(AsOfRef::Timestamp(t.to_string()));
    }
    Err("as_of must specify one of: commit, timestamp, now".to_string())
}

#[derive(Debug, Deserialize)]
struct RefDiffArgs {
    symbol_id: i64,
    #[serde(default)]
    at_a: JsonValue,
    #[serde(default)]
    at_b: JsonValue,
}

fn lsp_references_diff_handler(
    db: Option<&EmbeddedDatabase>,
    args: JsonValue,
) -> ToolOutcome {
    let Some(db) = db else {
        return ToolOutcome::err("helios_lsp_references_diff requires a database connection");
    };
    let input: RefDiffArgs = match serde_json::from_value(args) {
        Ok(v) => v,
        Err(e) => return ToolOutcome::err(format!("invalid arguments: {e}")),
    };
    let a = match parse_as_of(&input.at_a) { Ok(x) => x, Err(e) => return ToolOutcome::err(e) };
    let b = match parse_as_of(&input.at_b) { Ok(x) => x, Err(e) => return ToolOutcome::err(e) };
    match lsp_references_diff(db, input.symbol_id, &a, &b) {
        Ok(rows) => ToolOutcome::ok(json!({
            "symbol_id": input.symbol_id,
            "count": rows.len(),
            "rows": rows
                .iter()
                .map(|r| json!({
                    "change": r.change.as_str(),
                    "path": r.path,
                    "line": r.line,
                    "caller_symbol_id": r.caller_symbol_id,
                }))
                .collect::<Vec<_>>(),
        })),
        Err(e) => ToolOutcome::err(format!("lsp_references_diff failed: {e}")),
    }
}

inventory::submit! {
    McpExtensionTool {
        name: "helios_lsp_references_diff",
        description: "Diff a symbol's reference set across two AS OF points.",
        schema: lsp_references_diff_schema,
        handler: lsp_references_diff_handler,
    }
}

fn as_of_schema_fragment() -> JsonValue {
    json!({
        "oneOf": [
            { "type": "string", "enum": ["now"] },
            { "type": "object", "properties": { "now":       { "type": "boolean" } }, "required": ["now"] },
            { "type": "object", "properties": { "commit":    { "type": "string"  } }, "required": ["commit"] },
            { "type": "object", "properties": { "timestamp": { "type": "string"  } }, "required": ["timestamp"] }
        ]
    })
}

fn lsp_references_diff_schema() -> JsonValue {
    json!({
        "type": "object",
        "properties": {
            "symbol_id": { "type": "integer" },
            "at_a":      as_of_schema_fragment(),
            "at_b":      as_of_schema_fragment()
        },
        "required": ["symbol_id"]
    })
}

#[derive(Debug, Deserialize)]
struct BodyDiffArgs {
    symbol_id: i64,
    #[serde(default)]
    at_a: JsonValue,
    #[serde(default)]
    at_b: JsonValue,
}

fn lsp_body_diff_handler(db: Option<&EmbeddedDatabase>, args: JsonValue) -> ToolOutcome {
    let Some(db) = db else {
        return ToolOutcome::err("helios_lsp_body_diff requires a database connection");
    };
    let input: BodyDiffArgs = match serde_json::from_value(args) {
        Ok(v) => v,
        Err(e) => return ToolOutcome::err(format!("invalid arguments: {e}")),
    };
    let a = match parse_as_of(&input.at_a) { Ok(x) => x, Err(e) => return ToolOutcome::err(e) };
    let b = match parse_as_of(&input.at_b) { Ok(x) => x, Err(e) => return ToolOutcome::err(e) };
    match lsp_body_diff(db, input.symbol_id, &a, &b) {
        Ok(rows) => ToolOutcome::ok(json!({
            "symbol_id": input.symbol_id,
            "count": rows.len(),
            "lines": rows
                .iter()
                .map(|r| json!({
                    "line_a": r.line_a,
                    "line_b": r.line_b,
                    "op": r.op.as_str(),
                    "text": r.text,
                }))
                .collect::<Vec<_>>(),
        })),
        Err(e) => ToolOutcome::err(format!("lsp_body_diff failed: {e}")),
    }
}

inventory::submit! {
    McpExtensionTool {
        name: "helios_lsp_body_diff",
        description: "Myers-LCS line-level diff of a symbol's signature across two AS OF points.",
        schema: lsp_body_diff_schema,
        handler: lsp_body_diff_handler,
    }
}

fn lsp_body_diff_schema() -> JsonValue {
    json!({
        "type": "object",
        "properties": {
            "symbol_id": { "type": "integer" },
            "at_a":      as_of_schema_fragment(),
            "at_b":      as_of_schema_fragment()
        },
        "required": ["symbol_id"]
    })
}

#[derive(Debug, Deserialize)]
struct AstDiffArgs {
    path: String,
    #[serde(default)]
    at_a: JsonValue,
    #[serde(default)]
    at_b: JsonValue,
}

fn ast_diff_handler(db: Option<&EmbeddedDatabase>, args: JsonValue) -> ToolOutcome {
    let Some(db) = db else {
        return ToolOutcome::err("helios_ast_diff requires a database connection");
    };
    let input: AstDiffArgs = match serde_json::from_value(args) {
        Ok(v) => v,
        Err(e) => return ToolOutcome::err(format!("invalid arguments: {e}")),
    };
    let a = match parse_as_of(&input.at_a) { Ok(x) => x, Err(e) => return ToolOutcome::err(e) };
    let b = match parse_as_of(&input.at_b) { Ok(x) => x, Err(e) => return ToolOutcome::err(e) };
    match ast_diff(db, &input.path, &a, &b) {
        Ok(rows) => ToolOutcome::ok(json!({
            "path": input.path,
            "count": rows.len(),
            "rows": rows
                .iter()
                .map(|r| json!({
                    "change": r.change.as_str(),
                    "kind": r.kind,
                    "qualified": r.qualified,
                    "line_a": r.line_a,
                    "line_b": r.line_b,
                }))
                .collect::<Vec<_>>(),
        })),
        Err(e) => ToolOutcome::err(format!("ast_diff failed: {e}")),
    }
}

inventory::submit! {
    McpExtensionTool {
        name: "helios_ast_diff",
        description: "File-level structural diff (added/removed/moved symbols) across two AS OF points.",
        schema: ast_diff_schema,
        handler: ast_diff_handler,
    }
}

fn ast_diff_schema() -> JsonValue {
    json!({
        "type": "object",
        "properties": {
            "path": { "type": "string" },
            "at_a": as_of_schema_fragment(),
            "at_b": as_of_schema_fragment()
        },
        "required": ["path"]
    })
}

// ---- Helpers ----------------------------------------------------------

fn value_to_string(v: Option<&Value>) -> Option<String> {
    match v {
        Some(Value::String(s)) => Some(s.clone()),
        _ => None,
    }
}

fn value_to_i64(v: Option<&Value>) -> Option<i64> {
    match v {
        Some(Value::Int2(n)) => Some(i64::from(*n)),
        Some(Value::Int4(n)) => Some(i64::from(*n)),
        Some(Value::Int8(n)) => Some(*n),
        _ => None,
    }
}

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

    #[test]
    fn all_lsp_tools_are_registered() {
        let names: Vec<_> = registered().map(|t| t.name).collect();
        for n in [
            "helios_lsp_definition",
            "helios_lsp_references",
            "helios_lsp_call_hierarchy",
            "helios_lsp_hover",
            "helios_lsp_document_symbols",
            "helios_lsp_rename_preview",
            "helios_lsp_rename_apply",
            "helios_lsp_references_diff",
            "helios_lsp_body_diff",
            "helios_ast_diff",
        ] {
            assert!(names.contains(&n), "missing {n} in {names:?}");
        }
    }
}