leindex 1.6.0

LeIndex MCP and semantic code search engine for AI tools and large codebases
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
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
// CLI Interface
//
// This module provides the command-line interface for LeIndex.

use crate::cli::leindex::LeIndex;
use crate::cli::mcp::handlers::{all_tool_handlers, ToolHandler};
use crate::cli::mcp::protocol::{JsonRpcRequest, JsonRpcResponse};
use crate::cli::mcp::McpServer;
use crate::cli::registry::{ProjectRegistry, DEFAULT_MAX_PROJECTS};
use crate::phase::{run_phase_analysis, DocsMode, FormatMode, PhaseOptions, PhaseSelection};
use anyhow::Context;
use anyhow::Result as AnyhowResult;
use clap::{error::ErrorKind, Parser, Subcommand};
use serde_json::{Map, Value};
use std::fs;
use std::net::SocketAddr;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::sync::Arc;
use tracing::{info, warn};

const POST_INSTALL_SKIP_ENV: &str = "LEINDEX_SKIP_POST_INSTALL_HOOK";
const POST_INSTALL_STAR_MARKER: &str = ".github-starred";
const POST_INSTALL_VERSION_MARKER: &str = ".post-install-version";
const REPO_STAR_ENDPOINT: &str = "user/starred/scooter-lacroix/LeIndex";

/// LeIndex - Code Search and Analysis Engine
#[derive(Parser, Debug)]
#[command(name = "leindex")]
#[command(author = "LeIndex Contributors")]
#[command(version = env!("CARGO_PKG_VERSION"))]
#[command(about = "Index, search, and analyze codebases with semantic understanding", long_about = None)]
#[command(subcommand_required = false)]
#[command(arg_required_else_help = false)]
pub struct Cli {
    /// Path to the project directory
    #[arg(global = true, long = "project", short = 'p')]
    pub project_path: Option<PathBuf>,

    /// Enable verbose logging
    #[arg(global = true, long = "verbose", short = 'v')]
    pub verbose: bool,

    /// Compatibility flag for some AI tools (defaults to MCP stdio mode)
    #[arg(long = "stdio")]
    pub stdio: bool,

    /// Subcommand to execute
    #[command(subcommand)]
    pub command: Option<Commands>,
}

/// Available CLI commands
#[derive(Subcommand, Debug)]
pub enum Commands {
    /// Index a project for code search and analysis
    #[command(visible_alias = "leindex_index")]
    Index {
        /// Path to the project directory
        #[arg(value_name = "PATH")]
        path: PathBuf,

        /// Force re-indexing even if already indexed
        #[arg(long = "force")]
        force: bool,

        /// Show detailed progress
        #[arg(long = "progress")]
        progress: bool,
    },

    /// Search indexed code
    #[command(visible_alias = "leindex_search")]
    Search {
        /// Search query
        #[arg(value_name = "QUERY")]
        query: String,

        /// Maximum number of results to return
        #[arg(long = "top-k", default_value = "10")]
        top_k: usize,
    },

    /// Perform deep analysis with context expansion
    #[command(visible_alias = "leindex_deep_analyze")]
    Analyze {
        /// Analysis query
        #[arg(value_name = "QUERY")]
        query: String,

        /// Maximum tokens for context expansion
        #[arg(long = "tokens", default_value = "2000")]
        token_budget: usize,
    },

    /// Expand context around a symbol or node
    #[command(visible_alias = "leindex_context")]
    Context {
        /// Symbol or node ID to expand
        #[arg(value_name = "NODE_ID")]
        node_id: String,

        /// Maximum tokens for context expansion
        #[arg(long = "tokens", default_value = "2000")]
        token_budget: usize,
    },

    /// Run additive 5-phase analysis workflow
    #[command(visible_aliases = ["leindex_phase_analysis", "phase_analysis"])]
    Phase {
        /// Specific phase to run (1..5)
        #[arg(long = "phase")]
        phase: Option<u8>,

        /// Run all phases (1..5)
        #[arg(long = "all", default_value_t = false)]
        all: bool,

        /// Formatting mode: ultra|balanced|verbose
        #[arg(long = "mode", default_value = "balanced")]
        mode: String,

        /// Path to analyze (defaults to current/global project)
        #[arg(long = "path")]
        path: Option<PathBuf>,

        /// Maximum files to consider
        #[arg(long = "max-files", default_value = "2000")]
        max_files: usize,

        /// Maximum focus files in phase 3
        #[arg(long = "max-focus-files", default_value = "20")]
        max_focus_files: usize,

        /// Top-N entries for ranking phases
        #[arg(long = "top-n", default_value = "10")]
        top_n: usize,

        /// Maximum output characters
        #[arg(long = "max-chars", default_value = "12000")]
        max_output_chars: usize,

        /// Explicitly opt in to Markdown/Text analysis
        #[arg(long = "include-docs", default_value_t = false)]
        include_docs: bool,

        /// Docs mode: off|markdown|text|all
        #[arg(long = "docs-mode", default_value = "off")]
        docs_mode: String,

        /// Disable incremental freshness checks (forces full refresh)
        #[arg(long = "no-incremental-refresh", default_value_t = false)]
        no_incremental_refresh: bool,
    },

    /// Show system diagnostics
    #[command(visible_alias = "leindex_diagnostics")]
    Diagnostics,

    /// List, inspect, or run the MCP tool surface directly from the CLI
    #[command(disable_help_subcommand = true)]
    Tools {
        /// Tool action to perform
        #[command(subcommand)]
        command: ToolCommands,
    },

    /// Start MCP server for AI assistant integration
    Serve {
        /// Host address to bind to
        #[arg(long = "host", default_value = "127.0.0.1")]
        host: String,

        /// Port to listen on (default: 47268, override with LEINDEX_PORT env var)
        #[arg(long = "port", default_value = "47268")]
        port: u16,
    },

    /// Run MCP server in stdio mode (for AI tool subprocess integration)
    Mcp {
        /// Compatibility flag for some AI tools
        #[arg(long = "stdio")]
        stdio: bool,
    },

    /// Start the frontend dashboard
    Dashboard {
        /// Port to run the dashboard on (default: 5173)
        #[arg(long = "port", default_value = "5173")]
        port: u16,

        /// Build for production instead of dev server
        #[arg(long = "prod")]
        prod: bool,
    },
}

/// Subcommands for inspecting and executing MCP tools from the CLI.
#[derive(Subcommand, Debug)]
pub enum ToolCommands {
    /// List every MCP/CLI tool name and description
    List,

    /// Show comprehensive help for a tool
    Help {
        /// Tool name (for example: leindex_project_map, project_map, or project-map)
        name: String,
    },

    /// Print the JSON argument schema for a tool
    Schema {
        /// Tool name (for example: leindex_project_map, project_map, or project-map)
        name: String,
    },

    /// Execute a tool by name with JSON arguments
    Run {
        /// Tool name (for example: leindex_project_map, project_map, or project-map)
        name: String,

        /// JSON object of tool arguments
        #[arg(long = "args", default_value = "{}")]
        args_json: String,

        /// Additional key=value arguments merged on top of --args
        #[arg(long = "set", value_name = "KEY=VALUE")]
        set: Vec<String>,
    },
}

impl Cli {
    /// Run the CLI
    pub async fn run(self) -> AnyhowResult<()> {
        // Initialize logging
        init_logging_impl(self.verbose);

        // Get global project path
        let global_project = self.project_path;

        // Execute the appropriate command
        // Default to Mcp if no command is provided or if --stdio is set
        let command = if self.stdio {
            Commands::Mcp { stdio: true }
        } else {
            self.command.unwrap_or(Commands::Mcp { stdio: false })
        };

        maybe_complete_post_install_actions(&command);

        match command {
            Commands::Index {
                path,
                force,
                progress,
            } => cmd_index_impl(path, force, progress).await,
            Commands::Search { query, top_k } => {
                cmd_search_impl(query, top_k, global_project).await
            }
            Commands::Analyze {
                query,
                token_budget,
            } => cmd_analyze_impl(query, token_budget, global_project).await,
            Commands::Context {
                node_id,
                token_budget,
            } => cmd_context_impl(node_id, token_budget, global_project).await,
            Commands::Phase {
                phase,
                all,
                mode,
                path,
                max_files,
                max_focus_files,
                top_n,
                max_output_chars,
                include_docs,
                docs_mode,
                no_incremental_refresh,
            } => {
                cmd_phase_impl(
                    phase,
                    all,
                    mode,
                    path,
                    global_project,
                    max_files,
                    max_focus_files,
                    top_n,
                    max_output_chars,
                    include_docs,
                    docs_mode,
                    no_incremental_refresh,
                )
                .await
            }
            Commands::Diagnostics => cmd_diagnostics_impl(global_project).await,
            Commands::Tools { command } => cmd_tools_impl(command, global_project).await,
            Commands::Serve { host, port } => cmd_serve_impl(host, port).await,
            Commands::Mcp { .. } => cmd_mcp_stdio_impl(global_project).await,
            Commands::Dashboard { port, prod } => cmd_dashboard_impl(port, prod).await,
        }
    }
}

/// Initialize logging implementation
fn init_logging_impl(verbose: bool) {
    let level = if verbose {
        tracing::Level::DEBUG
    } else {
        tracing::Level::INFO
    };

    let subscriber = tracing_subscriber::fmt()
        .with_max_level(level)
        .with_writer(std::io::stderr)
        .finish();

    let _ = tracing::subscriber::set_global_default(subscriber);
}

fn maybe_complete_post_install_actions(command: &Commands) {
    if std::env::var_os(POST_INSTALL_SKIP_ENV).is_some()
        || matches!(command, Commands::Mcp { .. })
        || !running_from_cargo_bin()
    {
        return;
    }

    let leindex_home = match resolve_leindex_home() {
        Ok(path) => path,
        Err(error) => {
            warn!("Post-install actions skipped: {}", error);
            return;
        }
    };

    if post_install_is_current(&leindex_home) {
        return;
    }

    if let Err(error) = complete_post_install_actions(command, &leindex_home) {
        warn!("Post-install actions skipped: {}", error);
    }
}

fn complete_post_install_actions(
    command: &Commands,
    leindex_home: &std::path::Path,
) -> AnyhowResult<()> {
    fs::create_dir_all(leindex_home).context("failed to create LEINDEX_HOME")?;
    cleanup_legacy_user_installations(leindex_home);

    let marker_path = leindex_home.join(POST_INSTALL_STAR_MARKER);
    if !marker_path.exists() {
        emit_post_install_message(command, "Thank you for installing LeIndex.");

        if try_star_repo() {
            emit_post_install_message(command, "Starred scooter-lacroix/LeIndex on GitHub.");
            fs::write(&marker_path, b"starred\n").context("failed to persist star marker")?;
        } else {
            emit_post_install_message(
                command,
                "Could not star the GitHub repo automatically. If GitHub CLI is signed in, run: gh api -X PUT user/starred/scooter-lacroix/LeIndex",
            );
            fs::write(&marker_path, b"prompted\n").context("failed to persist star marker")?;
        }
    }

    warn_if_path_is_shadowed(command);
    write_post_install_version_marker(leindex_home)?;

    Ok(())
}

fn resolve_leindex_home() -> AnyhowResult<PathBuf> {
    if let Ok(path) = std::env::var("LEINDEX_HOME") {
        return Ok(PathBuf::from(path));
    }

    let home = dirs::home_dir().context("HOME is not available")?;
    Ok(home.join(".leindex"))
}

fn post_install_is_current(leindex_home: &std::path::Path) -> bool {
    let marker_path = leindex_home.join(POST_INSTALL_VERSION_MARKER);
    match fs::read_to_string(marker_path) {
        Ok(version) => version.trim() == env!("CARGO_PKG_VERSION"),
        Err(_) => false,
    }
}

fn write_post_install_version_marker(leindex_home: &std::path::Path) -> AnyhowResult<()> {
    let marker_path = leindex_home.join(POST_INSTALL_VERSION_MARKER);
    fs::write(marker_path, format!("{}\n", env!("CARGO_PKG_VERSION")))
        .context("failed to persist post-install marker")
}

fn cleanup_legacy_user_installations(leindex_home: &std::path::Path) {
    let Some(home) = dirs::home_dir() else {
        return;
    };

    let binary_name = platform_binary_name("leindex");
    let legacy_local_bin = home.join(".local").join("bin").join(&binary_name);
    if legacy_local_bin.exists() {
        match fs::remove_file(&legacy_local_bin) {
            Ok(_) => info!("Removed legacy install at {}", legacy_local_bin.display()),
            Err(error) => warn!(
                "Failed to remove legacy install at {}: {}",
                legacy_local_bin.display(),
                error
            ),
        }
    }

    let legacy_home_bin = leindex_home.join("bin").join(binary_name);
    if legacy_home_bin.exists() {
        match fs::remove_file(&legacy_home_bin) {
            Ok(_) => info!("Removed legacy install at {}", legacy_home_bin.display()),
            Err(error) => warn!(
                "Failed to remove legacy install at {}: {}",
                legacy_home_bin.display(),
                error
            ),
        }
    }
}

fn running_from_cargo_bin() -> bool {
    let Ok(current_exe) = std::env::current_exe() else {
        return false;
    };

    let cargo_home = cargo_home_dir();

    let Some(cargo_home) = cargo_home else {
        return false;
    };

    current_exe == cargo_home.join("bin").join(platform_binary_name("leindex"))
}

fn resolve_path_binary(binary_name: &str) -> Option<PathBuf> {
    let path_var = std::env::var_os("PATH")?;
    for entry in std::env::split_paths(&path_var) {
        let candidate = entry.join(binary_name);
        if candidate.is_file() {
            return Some(candidate);
        }

        if cfg!(windows) {
            let exe_candidate = entry.join(platform_binary_name(binary_name));
            if exe_candidate.is_file() {
                return Some(exe_candidate);
            }
        }
    }
    None
}

fn warn_if_path_is_shadowed(command: &Commands) {
    let Ok(current_exe) = std::env::current_exe() else {
        return;
    };

    let Some(resolved) = resolve_path_binary("leindex") else {
        return;
    };

    if resolved == current_exe {
        return;
    }

    emit_post_install_message(
        command,
        &format!(
            "`leindex` currently resolves to {} instead of {}. Remove the older binary or move {} earlier in PATH.",
            resolved.display(),
            current_exe.display(),
            cargo_bin_dir()
                .unwrap_or_else(|| current_exe.parent().unwrap_or_else(|| std::path::Path::new(".")).to_path_buf())
                .display()
        ),
    );
}

fn cargo_home_dir() -> Option<PathBuf> {
    std::env::var("CARGO_HOME")
        .map(PathBuf::from)
        .ok()
        .or_else(|| dirs::home_dir().map(|home| home.join(".cargo")))
}

fn cargo_bin_dir() -> Option<PathBuf> {
    cargo_home_dir().map(|cargo_home| cargo_home.join("bin"))
}

fn platform_binary_name(binary_name: &str) -> String {
    if cfg!(windows) {
        format!("{}.exe", binary_name)
    } else {
        binary_name.to_string()
    }
}

fn try_star_repo() -> bool {
    let auth_ok = Command::new("gh")
        .args(["auth", "status"])
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .map(|status| status.success())
        .unwrap_or(false);

    if !auth_ok {
        return false;
    }

    Command::new("gh")
        .args([
            "api",
            "-X",
            "PUT",
            "-H",
            "Accept: application/vnd.github+json",
            REPO_STAR_ENDPOINT,
        ])
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .map(|status| status.success())
        .unwrap_or(false)
}

fn emit_post_install_message(command: &Commands, message: &str) {
    if matches!(command, Commands::Serve { .. } | Commands::Dashboard { .. }) {
        info!("{}", message);
    } else {
        eprintln!("{}", message);
    }
}

/// Get project path from explicit path or current directory
fn get_project_path(explicit: Option<PathBuf>) -> PathBuf {
    explicit.unwrap_or_else(|| std::env::current_dir().unwrap())
}

/// Index command implementation
async fn cmd_index_impl(path: PathBuf, force: bool, _progress: bool) -> AnyhowResult<()> {
    let canonical_path = path
        .canonicalize()
        .context("Failed to canonicalize project path")?;

    info!("Indexing project at: {}", canonical_path.display());

    // Check if already indexed (unless force)
    // TODO: Add force check logic

    // Create LeIndex and index the project
    let mut leindex = LeIndex::new(&canonical_path).context("Failed to create LeIndex instance")?;

    let stats = tokio::task::spawn_blocking(move || leindex.index_project(force))
        .await
        .context("Indexing task failed")?
        .context("Indexing failed")?;

    // Print results
    println!("\n✓ Indexing complete!");
    println!("  Files parsed: {}", stats.files_parsed);
    println!("  Successful: {}", stats.successful_parses);
    println!("  Failed: {}", stats.failed_parses);
    println!("  Signatures: {}", stats.total_signatures);
    println!("  PDG nodes: {}", stats.pdg_nodes);
    println!("  PDG edges: {}", stats.pdg_edges);
    println!("  Indexed nodes: {}", stats.indexed_nodes);
    println!("  Time: {}ms", stats.indexing_time_ms);

    Ok(())
}

/// Search command implementation
async fn cmd_search_impl(
    query: String,
    top_k: usize,
    project: Option<PathBuf>,
) -> AnyhowResult<()> {
    let project_path = get_project_path(project);
    let canonical_path = project_path
        .canonicalize()
        .context("Failed to canonicalize project path")?;

    info!("Searching for: {}", query);

    // Create LeIndex and try to load from storage
    let mut leindex = LeIndex::new(&canonical_path).context("Failed to create LeIndex instance")?;

    // Load from storage if available
    if let Err(e) = leindex.load_from_storage() {
        warn!("Failed to load from storage: {}", e);
        warn!("Project may not be indexed. Run 'leindex index' first.");
    }

    // Perform search
    let results = leindex
        .search(&query, top_k, None)
        .context("Search failed")?;

    if results.is_empty() {
        println!("No results found for: {}", query);
        return Ok(());
    }

    // Print results
    println!("\nFound {} result(s) for: '{}'\n", results.len(), query);
    for (i, result) in results.iter().enumerate() {
        println!("{}. {} ({})", i + 1, result.symbol_name, result.file_path);
        println!("   ID: {}", result.node_id);
        println!("   Overall Score: {:.2}", result.score.overall);
        println!(
            "   Explanation: [Semantic: {:.2}, Text: {:.2}, Structural: {:.2}]",
            result.score.semantic, result.score.text_match, result.score.structural
        );
        if let Some(context) = &result.context {
            let context_preview = if context.len() > 100 {
                format!("{}...", &context[..100])
            } else {
                context.clone()
            };
            println!("   Context: {}", context_preview);
        }
        println!();
    }

    Ok(())
}

/// Analyze command implementation
async fn cmd_analyze_impl(
    query: String,
    token_budget: usize,
    project: Option<PathBuf>,
) -> AnyhowResult<()> {
    let project_path = get_project_path(project);
    let canonical_path = project_path
        .canonicalize()
        .context("Failed to canonicalize project path")?;

    info!("Analyzing: {}", query);

    // Create LeIndex and try to load from storage
    let mut leindex = LeIndex::new(&canonical_path).context("Failed to create LeIndex instance")?;

    // Load from storage if available
    if let Err(e) = leindex.load_from_storage() {
        warn!("Failed to load from storage: {}", e);
        warn!("Project may not be indexed. Run 'leindex index' first.");
    }

    // Perform analysis
    let result = leindex
        .analyze(&query, token_budget)
        .context("Analysis failed")?;

    // Print results
    println!("\nAnalysis Results for: '{}'", query);
    println!("Found {} entry point(s)", result.results.len());
    println!("Tokens used: {}", result.tokens_used);
    println!("Processing time: {}ms\n", result.processing_time_ms);

    if let Some(context) = &result.context {
        println!("Context:");
        println!("{}", context);
    }

    Ok(())
}

/// Context command implementation
async fn cmd_context_impl(
    node_id: String,
    token_budget: usize,
    project: Option<PathBuf>,
) -> AnyhowResult<()> {
    let args = merge_tool_args(
        serde_json::json!({
            "node_id": node_id,
            "token_budget": token_budget
        }),
        &[],
        project.as_ref(),
    )?;

    let value = execute_tool_handler("leindex_context", args, project).await?;
    print_json_value(&value)?;
    Ok(())
}

/// Phase command implementation
#[allow(clippy::too_many_arguments)]
async fn cmd_phase_impl(
    phase: Option<u8>,
    all: bool,
    mode: String,
    path: Option<PathBuf>,
    project: Option<PathBuf>,
    max_files: usize,
    max_focus_files: usize,
    top_n: usize,
    max_output_chars: usize,
    include_docs: bool,
    docs_mode: String,
    no_incremental_refresh: bool,
) -> AnyhowResult<()> {
    if !all && phase.is_none() {
        anyhow::bail!("Specify either --phase <1..5> or --all");
    }

    if all && phase.is_some() {
        anyhow::bail!("Use either --phase or --all, not both");
    }

    let target_path = path
        .or(project)
        .unwrap_or_else(|| std::env::current_dir().unwrap());
    let canonical_path = target_path
        .canonicalize()
        .context("Failed to canonicalize phase analysis path")?;

    let (root, focus_files) = if canonical_path.is_file() {
        let parent = canonical_path
            .parent()
            .map(PathBuf::from)
            .ok_or_else(|| anyhow::anyhow!("phase analysis file path has no parent directory"))?;
        (parent, vec![canonical_path.clone()])
    } else {
        (canonical_path, Vec::new())
    };

    let parsed_mode = FormatMode::parse(&mode)
        .ok_or_else(|| anyhow::anyhow!("Invalid mode '{}'. Use ultra|balanced|verbose", mode))?;

    let parsed_docs_mode = DocsMode::parse(&docs_mode).ok_or_else(|| {
        anyhow::anyhow!(
            "Invalid docs mode '{}'. Use off|markdown|text|all",
            docs_mode
        )
    })?;

    let selection = if all {
        PhaseSelection::All
    } else {
        let p = phase.unwrap();
        PhaseSelection::from_number(p)
            .ok_or_else(|| anyhow::anyhow!("Invalid phase '{}'. Use 1..5", p))?
    };

    let options = PhaseOptions {
        root,
        focus_files,
        mode: parsed_mode,
        max_files,
        max_focus_files,
        top_n,
        max_output_chars,
        use_incremental_refresh: !no_incremental_refresh,
        include_docs,
        docs_mode: parsed_docs_mode,
        hotspot_keywords: PhaseOptions::default().hotspot_keywords,
    };

    let report = tokio::task::spawn_blocking(move || run_phase_analysis(options, selection))
        .await
        .context("Phase task failed")??;

    println!("{}", report.formatted_output);
    Ok(())
}

/// Diagnostics command implementation
async fn cmd_diagnostics_impl(project: Option<PathBuf>) -> AnyhowResult<()> {
    let project_path = get_project_path(project);
    let canonical_path = project_path
        .canonicalize()
        .context("Failed to canonicalize project path")?;

    info!("Fetching diagnostics");

    // Create LeIndex and try to load from storage
    let mut leindex = LeIndex::new(&canonical_path).context("Failed to create LeIndex instance")?;

    // Load from storage if available
    if let Err(e) = leindex.load_from_storage() {
        warn!("Failed to load from storage: {}", e);
    }

    // Get diagnostics
    let diag = leindex
        .get_diagnostics()
        .context("Failed to get diagnostics")?;

    // Print diagnostics
    println!("\nLeIndex Diagnostics\n");
    println!("Project: {}", diag.project_id);
    println!("Path: {}", diag.project_path);
    println!("\nIndex Statistics:");
    println!("  Files parsed: {}", diag.stats.files_parsed);
    println!("  Successful: {}", diag.stats.successful_parses);
    println!("  Failed: {}", diag.stats.failed_parses);
    println!("  Total signatures: {}", diag.stats.total_signatures);
    println!("  PDG nodes: {}", diag.stats.pdg_nodes);
    println!("  PDG edges: {}", diag.stats.pdg_edges);
    println!("  Indexed nodes: {}", diag.stats.indexed_nodes);
    println!("\nMemory Usage:");
    println!(
        "  Current: {:.2} MB",
        diag.memory_usage_bytes as f64 / 1024.0 / 1024.0
    );
    println!(
        "  Total: {:.2} MB",
        diag.total_memory_bytes as f64 / 1024.0 / 1024.0
    );
    println!("  Usage: {:.1}%", diag.memory_usage_percent);
    if diag.memory_threshold_exceeded {
        println!("  ⚠️  Memory threshold exceeded!");
    }

    Ok(())
}

async fn cmd_tools_impl(command: ToolCommands, project: Option<PathBuf>) -> AnyhowResult<()> {
    match command {
        ToolCommands::List => {
            for handler in all_tool_handlers() {
                println!("{}\t{}", handler.name(), handler.description());
            }
            Ok(())
        }
        ToolCommands::Help { name } => {
            let handler = find_tool_handler(&name)
                .ok_or_else(|| anyhow::anyhow!("Unknown tool '{}'", name))?;
            print_tool_help(&handler);
            Ok(())
        }
        ToolCommands::Schema { name } => {
            let handler = find_tool_handler(&name)
                .ok_or_else(|| anyhow::anyhow!("Unknown tool '{}'", name))?;
            print_json_value(&handler.argument_schema())?;
            Ok(())
        }
        ToolCommands::Run {
            name,
            args_json,
            set,
        } => {
            let args = merge_tool_args(parse_tool_args_json(&args_json)?, &set, project.as_ref())?;
            let value = execute_tool_handler(&name, args, project).await?;
            print_json_value(&value)?;
            Ok(())
        }
    }
}

/// Serve command implementation - Start MCP server
async fn cmd_serve_impl(host: String, port: u16) -> AnyhowResult<()> {
    // Check for environment variable override (for customization via LEINDEX_PORT)
    let port = if let Ok(env_port) = std::env::var("LEINDEX_PORT") {
        env_port.parse::<u16>().unwrap_or(port)
    } else {
        port
    };

    // Parse the address
    let addr: SocketAddr = format!("{}:{}", host, port)
        .parse()
        .context("Invalid address or port")?;

    info!("Starting MCP server on {}", addr);

    // Create a default LeIndex instance for the server
    // The server will use the current directory as the project path
    let current_dir = std::env::current_dir().context("Failed to get current directory")?;

    let leindex = LeIndex::new(&current_dir).context("Failed to create LeIndex instance")?;

    // Create and run the MCP server
    let server = McpServer::with_address(addr, leindex).context("Failed to create MCP server")?;

    println!("\nLeIndex MCP Server\n");
    println!("Server starting on http://{}\n", addr);
    println!("Available endpoints:");
    println!("  POST /mcp           - JSON-RPC 2.0 endpoint");
    println!("  GET  /mcp/tools/list - List available tools");
    println!("  GET  /health         - Health check");
    println!("\nConfiguration:");
    println!("  Port: {} (override with LEINDEX_PORT env var)", port);
    println!("\nPress Ctrl+C to stop the server\n");

    server.run().await.context("Server error")?;

    Ok(())
}

/// MCP stdio command implementation - Run MCP server in stdio mode
/// This mode allows AI tools to start LeIndex as a subprocess for automatic integration
async fn cmd_mcp_stdio_impl(project: Option<PathBuf>) -> AnyhowResult<()> {
    use crate::cli::mcp::protocol::{JsonRpcError, JsonRpcMessage, JsonRpcResponse};
    use std::io::{self, BufRead, Read, Write};

    let project_path = get_project_path(project);
    let canonical_path = project_path
        .canonicalize()
        .context("Failed to canonicalize project path")?;

    info!(
        "Starting LeIndex MCP stdio server for project: {}",
        canonical_path.display()
    );

    // Create LeIndex instance
    let mut leindex = LeIndex::new(&canonical_path).context("Failed to create LeIndex instance")?;

    // Try to load from storage, but don't fail if not indexed yet
    let _ = leindex.load_from_storage();

    // Initialize global state for handlers
    let registry = Arc::new(ProjectRegistry::with_initial_project(
        DEFAULT_MAX_PROJECTS,
        leindex,
    ));
    let _ = crate::cli::mcp::server::SERVER_STATE.set(registry.clone());

    // Initialize handlers
    let _ = crate::cli::mcp::server::HANDLERS.set(all_tool_handlers());

    eprintln!("[INFO] LeIndex MCP stdio server starting");
    eprintln!("[INFO] Project: {}", canonical_path.display());
    eprintln!("[INFO] Reading JSON-RPC from stdin, writing to stdout");
    eprintln!("[INFO] Press Ctrl+C to stop\n");

    let stdin = io::stdin();
    let mut stdout = io::stdout().lock();
    let mut reader = io::BufReader::new(stdin.lock());
    let mut use_content_length = false;

    loop {
        let mut line = String::new();
        let bytes = match reader.read_line(&mut line) {
            Ok(b) => b,
            Err(e) => {
                eprintln!("[ERROR] Failed to read stdin: {}", e);
                continue;
            }
        };
        if bytes == 0 {
            break;
        }

        let line_trim = line.trim_end();
        if line_trim.is_empty() {
            continue;
        }

        let (json_payload, framed) = if line_trim
            .to_ascii_lowercase()
            .starts_with("content-length:")
        {
            let len_str = line_trim.split(':').nth(1).unwrap_or("").trim();
            let length: usize = match len_str.parse() {
                Ok(v) => v,
                Err(e) => {
                    eprintln!("[ERROR] Invalid Content-Length header: {}", e);
                    continue;
                }
            };

            // Consume remaining header lines until blank line
            loop {
                let mut header = String::new();
                if reader.read_line(&mut header).unwrap_or(0) == 0 {
                    break;
                }
                if header.trim().is_empty() {
                    break;
                }
            }

            let mut buf = vec![0u8; length];
            if let Err(e) = reader.read_exact(&mut buf) {
                eprintln!("[ERROR] Failed to read JSON payload: {}", e);
                break;
            }

            (String::from_utf8_lossy(&buf).to_string(), true)
        } else {
            (line_trim.to_string(), false)
        };

        use_content_length = use_content_length || framed;

        // Parse JSON-RPC message (request or notification)
        let message = match JsonRpcMessage::from_json(&json_payload) {
            Ok(m) => m,
            Err(e) => {
                let error_response = JsonRpcResponse::error(serde_json::Value::Null, e);
                let response = serde_json::to_string(&error_response).unwrap_or_default();
                if use_content_length {
                    let _ = writeln!(
                        stdout,
                        "Content-Length: {}\r\n\r\n{}",
                        response.len(),
                        response
                    );
                } else if writeln!(stdout, "{}", response).is_err() {
                    break;
                }
                let _ = stdout.flush();
                continue;
            }
        };

        // Handle based on message type
        match message {
            JsonRpcMessage::Notification(notification) => {
                eprintln!(
                    "[INFO] Received notification: {} (type: {})",
                    notification.method,
                    notification.notification_type()
                );
                continue;
            }
            JsonRpcMessage::Request(request) => {
                let request_id = request.id.clone().unwrap_or(serde_json::Value::Null);

                let response = match handle_mcp_request(request, project_path.clone()).await {
                    Ok(r) => r,
                    Err(e) => JsonRpcResponse::error(
                        request_id,
                        JsonRpcError::internal_error(e.to_string()),
                    ),
                };

                let response_json = match serde_json::to_string(&response) {
                    Ok(j) => j,
                    Err(e) => {
                        format!("{{\"jsonrpc\":\"2.0\",\"id\":null,\"error\":{{\"code\":-32700,\"message\":\"Failed to serialize response: {}\"}}}}", e)
                    }
                };

                if use_content_length {
                    if writeln!(
                        stdout,
                        "Content-Length: {}\r\n\r\n{}",
                        response_json.len(),
                        response_json
                    )
                    .is_err()
                    {
                        eprintln!("[ERROR] Failed to write to stdout");
                        break;
                    }
                } else if writeln!(stdout, "{}", response_json).is_err() {
                    eprintln!("[ERROR] Failed to write to stdout");
                    break;
                }
                let _ = stdout.flush();
            }
        }
    }

    Ok(())
}

fn parse_tool_args_json(args_json: &str) -> AnyhowResult<Value> {
    let value: Value =
        serde_json::from_str(args_json).context("Tool arguments must be valid JSON")?;
    if !value.is_object() {
        anyhow::bail!("Tool arguments must be a JSON object");
    }
    Ok(value)
}

fn merge_tool_args(
    args: Value,
    set_args: &[String],
    project: Option<&PathBuf>,
) -> AnyhowResult<Value> {
    let mut object = match args {
        Value::Object(map) => map,
        _ => Map::new(),
    };

    for entry in set_args {
        let (key, raw_value) = entry
            .split_once('=')
            .ok_or_else(|| anyhow::anyhow!("Invalid --set '{}'. Use KEY=VALUE", entry))?;
        let value = serde_json::from_str(raw_value)
            .unwrap_or_else(|_| Value::String(raw_value.to_string()));
        object.insert(key.to_string(), value);
    }

    if let Some(project) = project {
        if !object.contains_key("project_path") {
            let canonical = project.canonicalize().unwrap_or_else(|_| project.clone());
            object.insert(
                "project_path".to_string(),
                Value::String(canonical.display().to_string()),
            );
        }
    }

    Ok(Value::Object(object))
}

fn print_json_value(value: &Value) -> AnyhowResult<()> {
    println!(
        "{}",
        serde_json::to_string_pretty(value).context("Failed to format JSON output")?
    );
    Ok(())
}

fn print_tool_help(handler: &ToolHandler) {
    let schema = handler.argument_schema();
    let normalized = normalize_tool_name(handler.name());
    let short_name = normalized
        .strip_prefix("leindex_")
        .unwrap_or(normalized.as_str())
        .to_string();
    let kebab_short = short_name.replace('_', "-");
    let kebab_full = normalized.replace('_', "-");

    println!("{}", handler.name());
    println!("{}", handler.description());
    println!();
    println!("Aliases:");
    println!("  {}", handler.name());
    if short_name != handler.name() {
        println!("  {}", short_name);
    }
    if kebab_short != short_name {
        println!("  {}", kebab_short);
    }
    if kebab_full != normalized && kebab_full != kebab_short {
        println!("  {}", kebab_full);
    }
    println!();
    println!("Usage:");
    println!("  leindex tools help {}", handler.name());
    println!("  leindex tools schema {}", handler.name());
    println!(
        "  leindex tools run {} --args '<json-object>'",
        handler.name()
    );
    println!(
        "  leindex tools run {} --set key=value --set other=true",
        handler.name()
    );

    if let Some(properties) = schema.get("properties").and_then(|v| v.as_object()) {
        println!();
        println!("Arguments:");

        let required = schema
            .get("required")
            .and_then(|v| v.as_array())
            .map(|items| {
                items
                    .iter()
                    .filter_map(|item| item.as_str())
                    .collect::<std::collections::HashSet<_>>()
            })
            .unwrap_or_default();

        for (name, property) in properties {
            let required_marker = if required.contains(name.as_str()) {
                "required"
            } else {
                "optional"
            };
            let property_type = property
                .get("type")
                .and_then(|v| v.as_str())
                .or_else(|| {
                    property
                        .get("oneOf")
                        .and_then(|v| v.as_array())
                        .map(|_| "multiple")
                })
                .unwrap_or("value");
            let description = property
                .get("description")
                .and_then(|v| v.as_str())
                .unwrap_or("");
            let default = property.get("default");

            println!("  {} ({}, {})", name, property_type, required_marker);
            if !description.is_empty() {
                println!("    {}", description);
            }
            if let Some(default) = default {
                println!("    default: {}", default);
            }
        }
    }

    println!();
    println!("Schema:");
    println!(
        "{}",
        serde_json::to_string_pretty(&schema).unwrap_or_else(|_| "{}".to_string())
    );
}

fn normalize_tool_name(name: &str) -> String {
    name.trim().to_ascii_lowercase().replace('-', "_")
}

fn find_tool_handler(name: &str) -> Option<ToolHandler> {
    let normalized = normalize_tool_name(name);

    all_tool_handlers().into_iter().find(|handler| {
        let handler_name = normalize_tool_name(handler.name());
        handler_name == normalized
            || handler_name
                .strip_prefix("leindex_")
                .map(|short| short == normalized)
                .unwrap_or(false)
    })
}

async fn execute_tool_handler(
    name: &str,
    args: Value,
    project: Option<PathBuf>,
) -> AnyhowResult<Value> {
    let handler =
        find_tool_handler(name).ok_or_else(|| anyhow::anyhow!("Unknown tool '{}'", name))?;
    let registry = build_tool_registry(project)?;
    handler
        .execute(&registry, args)
        .await
        .map_err(|error| anyhow::anyhow!("{}", error))
}

fn build_tool_registry(project: Option<PathBuf>) -> AnyhowResult<Arc<ProjectRegistry>> {
    let initial = get_project_path(project);
    let canonical = initial.canonicalize().with_context(|| {
        format!(
            "Failed to canonicalize project path '{}'",
            initial.display()
        )
    })?;
    let project_root = if canonical.is_file() {
        canonical
            .parent()
            .map(PathBuf::from)
            .ok_or_else(|| anyhow::anyhow!("File path '{}' has no parent", canonical.display()))?
    } else {
        canonical
    };

    let mut leindex =
        LeIndex::new(&project_root).context("Failed to create LeIndex instance for tool run")?;
    let _ = leindex.load_from_storage();

    Ok(Arc::new(ProjectRegistry::with_initial_project(
        DEFAULT_MAX_PROJECTS,
        leindex,
    )))
}

/// Dashboard command implementation - Start the frontend dashboard
async fn cmd_dashboard_impl(port: u16, prod: bool) -> AnyhowResult<()> {
    use std::process::Command;

    // Find the dashboard directory.
    let current_dir = std::env::current_dir().context("Failed to get current directory")?;
    let dashboard_path = {
        let mut candidates = Vec::new();

        // 1) Current directory.
        candidates.push(current_dir.join("dashboard"));

        // 2) Parent traversal for source checkouts.
        let mut parent = current_dir.as_path();
        for _ in 0..5 {
            if let Some(next) = parent.parent() {
                candidates.push(next.join("dashboard"));
                parent = next;
            } else {
                break;
            }
        }

        // 3) Explicit override for packaged installs.
        if let Ok(explicit) = std::env::var("LEINDEX_DASHBOARD_DIR") {
            candidates.push(PathBuf::from(explicit));
        }

        // 4) Installer default location.
        if let Ok(home) = std::env::var("HOME") {
            candidates.push(PathBuf::from(home).join(".leindex").join("dashboard"));
        }

        candidates
            .into_iter()
            .find(|path| path.exists() && path.is_dir())
            .ok_or_else(|| {
                anyhow::anyhow!(
                    "Dashboard directory not found. Checked current repo paths, LEINDEX_DASHBOARD_DIR, and ~/.leindex/dashboard."
                )
            })?
    };

    // Check if bun is installed
    let bun_exists = Command::new("bun")
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false);

    if !bun_exists {
        anyhow::bail!(
            "Bun is required to run the dashboard. Please install it first:\n  curl -fsSL https://bun.sh/install | bash"
        );
    }

    println!("\nLeIndex Dashboard\n");
    println!("Starting dashboard server...\n");

    if prod {
        // Build for production
        println!("Building dashboard for production...");
        let build_status = Command::new("bun")
            .current_dir(&dashboard_path)
            .arg("run")
            .arg("build")
            .status()
            .context("Failed to build dashboard")?;

        if !build_status.success() {
            anyhow::bail!("Dashboard build failed");
        }

        println!("\nDashboard built successfully!");
        println!("Built files: {}/dist", dashboard_path.display());
        println!("\nTo serve the production build, use:");
        println!("  cd {} && bun run start", dashboard_path.display());
    } else {
        // Start dev server
        println!("Dashboard will be available at: http://localhost:{}", port);
        println!("Press Ctrl+C to stop the server\n");

        let status = Command::new("bun")
            .current_dir(&dashboard_path)
            .arg("run")
            .arg("dev")
            .status()
            .context("Failed to start dashboard")?;

        if !status.success() {
            anyhow::bail!("Dashboard server exited with error");
        }
    }

    Ok(())
}

/// Handle a single MCP request and return the response
async fn handle_mcp_request(
    request: JsonRpcRequest,
    _project_path: PathBuf,
) -> anyhow::Result<JsonRpcResponse> {
    use crate::cli::mcp::server::{handle_tool_call, list_tools_json, HANDLERS, SERVER_STATE};

    let method_name = request.method.clone();
    let id = request.id.clone().unwrap_or(serde_json::Value::Null);

    // Get the global state and handlers
    let state = SERVER_STATE
        .get()
        .ok_or_else(|| anyhow::anyhow!("Server state not initialized"))?;

    let handlers = HANDLERS
        .get()
        .ok_or_else(|| anyhow::anyhow!("Handlers not initialized"))?;

    // Handle different methods
    match method_name.as_str() {
        "initialize" => {
            // MCP protocol initialization handshake
            // Return server capabilities with comprehensive description
            Ok(JsonRpcResponse::success(
                id,
                serde_json::json!({
                    "protocolVersion": "2024-11-05",
                    "capabilities": {
                        "tools": {
                            "listChanged": true
                        },
                        "prompts": {
                            "listChanged": true
                        },
                        "resources": {
                            "listChanged": true,
                            "subscribe": false
                        },
                        "logging": {},
                        "progress": true
                    },
                    "serverInfo": {
                        "name": "leindex",
                        "version": env!("CARGO_PKG_VERSION"),
                        "description": "LeIndex MCP Server - Semantic code indexing and analysis with PDG-based tools. Provides 18+ specialized tools for code comprehension: semantic search, symbol lookup, impact analysis, structural code queries, and intelligent editing. Uses Program Dependence Graphs for superior code understanding compared to traditional text-based tools."
                    }
                }),
            ))
        }

        "notifications/initialized" => {
            // Client notification sent after successful initialization
            // No response needed for notifications
            Ok(JsonRpcResponse::success(id, serde_json::json!({})))
        }
        "ping" => {
            // Simple health check
            Ok(JsonRpcResponse::success(id, serde_json::json!({})))
        }
        "tools/call" => {
            // Use the centralized tool call handler that formats for MCP
            let result = handle_tool_call(state, handlers, &request).await;
            Ok(JsonRpcResponse::from_result(id, result))
        }
        "tools/list" => {
            // List all available tools using centralized formatter
            Ok(JsonRpcResponse::success(id, list_tools_json(handlers)))
        }
        _ => Ok(JsonRpcResponse::error(
            id,
            crate::cli::mcp::protocol::JsonRpcError::method_not_found(method_name),
        )),
    }
}

/// Main entry point for the CLI
pub async fn main() -> AnyhowResult<()> {
    match Cli::try_parse() {
        Ok(cli) => cli.run().await,
        Err(err) => {
            if matches!(
                err.kind(),
                ErrorKind::DisplayHelp | ErrorKind::DisplayVersion
            ) {
                maybe_complete_post_install_actions(&Commands::Diagnostics);
            }
            err.exit()
        }
    }
}

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

    #[test]
    fn test_cli_parsing() {
        let cli = Cli::try_parse_from(["leindex", "index", "/path/to/project"]).unwrap();
        assert!(matches!(cli.command, Some(Commands::Index { .. })));
    }

    #[test]
    fn test_mcp_command_parsing() {
        let cli = Cli::try_parse_from(["leindex", "mcp"]).unwrap();
        assert!(matches!(cli.command, Some(Commands::Mcp { .. })));
    }

    #[test]
    fn test_stdio_flag_parsing() {
        let cli = Cli::try_parse_from(["leindex", "--stdio"]).unwrap();
        assert!(cli.stdio);
    }

    #[test]
    fn test_search_command() {
        let cli = Cli::try_parse_from(["leindex", "search", "test query"]).unwrap();
        match cli.command {
            Some(Commands::Search { query, top_k, .. }) => {
                assert_eq!(query, "test query");
                assert_eq!(top_k, 10);
            }
            _ => panic!("Expected Search command"),
        }
    }

    #[test]
    fn test_phase_command_parsing() {
        let cli =
            Cli::try_parse_from(["leindex", "phase", "--phase", "2", "--mode", "ultra"]).unwrap();
        match cli.command {
            Some(Commands::Phase {
                phase, all, mode, ..
            }) => {
                assert_eq!(phase, Some(2));
                assert!(!all);
                assert_eq!(mode, "ultra");
            }
            _ => panic!("Expected Phase command"),
        }
    }

    #[test]
    fn test_dashboard_command_parsing() {
        let cli = Cli::try_parse_from(["leindex", "dashboard"]).unwrap();
        match cli.command {
            Some(Commands::Dashboard { port, prod }) => {
                assert_eq!(port, 5173);
                assert!(!prod);
            }
            _ => panic!("Expected Dashboard command"),
        }
    }

    #[test]
    fn test_dashboard_command_with_port() {
        let cli = Cli::try_parse_from(["leindex", "dashboard", "--port", "3000"]).unwrap();
        match cli.command {
            Some(Commands::Dashboard { port, prod }) => {
                assert_eq!(port, 3000);
                assert!(!prod);
            }
            _ => panic!("Expected Dashboard command"),
        }
    }

    #[test]
    fn test_dashboard_command_prod() {
        let cli = Cli::try_parse_from(["leindex", "dashboard", "--prod"]).unwrap();
        match cli.command {
            Some(Commands::Dashboard { port, prod }) => {
                assert_eq!(port, 5173);
                assert!(prod);
            }
            _ => panic!("Expected Dashboard command"),
        }
    }

    #[test]
    fn test_tools_help_command_parsing() {
        let cli = Cli::try_parse_from(["leindex", "tools", "help", "project_map"]).unwrap();
        match cli.command {
            Some(Commands::Tools {
                command: ToolCommands::Help { name },
            }) => assert_eq!(name, "project_map"),
            _ => panic!("Expected tools help command"),
        }
    }

    #[test]
    fn test_tools_run_command_parsing() {
        let cli = Cli::try_parse_from([
            "leindex",
            "tools",
            "run",
            "project_map",
            "--args",
            "{\"depth\":1}",
            "--set",
            "include_symbols=true",
        ])
        .unwrap();

        match cli.command {
            Some(Commands::Tools {
                command:
                    ToolCommands::Run {
                        name,
                        args_json,
                        set,
                    },
            }) => {
                assert_eq!(name, "project_map");
                assert_eq!(args_json, "{\"depth\":1}");
                assert_eq!(set, vec!["include_symbols=true"]);
            }
            _ => panic!("Expected tools run command"),
        }
    }

    #[test]
    fn test_find_tool_handler_accepts_short_and_full_names() {
        assert!(find_tool_handler("leindex_project_map").is_some());
        assert!(find_tool_handler("project_map").is_some());
        assert!(find_tool_handler("project-map").is_some());
    }
}