-
-
Notifications
You must be signed in to change notification settings - Fork 499
Expand file tree
/
Copy pathmain.py
More file actions
2247 lines (1869 loc) · 84.5 KB
/
main.py
File metadata and controls
2247 lines (1869 loc) · 84.5 KB
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
# src/codegraphcontext/cli/main.py
"""
This module defines the command-line interface (CLI) for the CodeGraphContext application.
It uses the Typer library to create a user-friendly and well-documented CLI.
Commands:
- mcp setup: Runs an interactive wizard to configure the MCP client.
- mcp start: Launches the main MCP server.
- help: Displays help information.
- version: Show the installed version.
"""
import typer
from rich.console import Console
from rich.table import Table
from rich import box
from typing import Optional
import asyncio
import logging
import json
import os
from pathlib import Path
from dotenv import load_dotenv, find_dotenv, set_key
from importlib.metadata import version as pkg_version, PackageNotFoundError
from codegraphcontext.server import MCPServer
from codegraphcontext.core.database import DatabaseManager
from .setup_wizard import run_neo4j_setup_wizard, configure_mcp_client
from . import config_manager
# Import the new helper functions
from .cli_helpers import (
index_helper,
add_package_helper,
list_repos_helper,
delete_helper,
cypher_helper,
cypher_helper_visual,
visualize_helper,
reindex_helper,
clean_helper,
stats_helper,
_initialize_services,
watch_helper,
unwatch_helper,
list_watching_helper,
)
# Set the log level for the noisy neo4j, asyncio, and urllib3 loggers to keep the output clean.
# Get the log level from config, defaulting to WARNING
def _configure_library_loggers():
"""Configure third-party library loggers based on config setting."""
try:
log_level_str = config_manager.get_config_value('LIBRARY_LOG_LEVEL')
if log_level_str is None:
log_level_str = 'WARNING'
log_level_str = str(log_level_str).upper()
log_level = getattr(logging, log_level_str, logging.WARNING)
except (AttributeError, Exception):
log_level = logging.WARNING
logging.getLogger("neo4j").setLevel(log_level)
logging.getLogger("asyncio").setLevel(log_level)
logging.getLogger("urllib3").setLevel(log_level)
_configure_library_loggers()
# Import visualization module
from .visualizer import (
visualize_call_graph,
visualize_call_chain,
visualize_dependencies,
visualize_inheritance_tree,
visualize_overrides,
visualize_search_results,
check_visual_flag,
)
# Initialize the Typer app and Rich console for formatted output.
app = typer.Typer(
name="cgc",
help="CodeGraphContext: An MCP server for AI-powered code analysis.\n\n[DEPRECATED] 'cgc start' is deprecated. Use 'cgc mcp start' instead.",
add_completion=True,
)
console = Console(stderr=True)
# Configure basic logging for the application.
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(name)s - %(message)s')
def get_version() -> str:
"""
Try to read version from the installed package metadata.
Fallback to a dev version if not installed.
"""
try:
return pkg_version("codegraphcontext") # must match [project].name in pyproject.toml
except PackageNotFoundError:
return "0.0.0 (dev)"
# Create MCP command group
mcp_app = typer.Typer(help="MCP client configuration commands")
app.add_typer(mcp_app, name="mcp")
@mcp_app.command("setup")
def mcp_setup():
"""
Configure MCP Client (IDE/CLI Integration).
Sets up CodeGraphContext integration with your IDE or CLI tool:
- VS Code, Cursor, Windsurf
- Claude Desktop, Gemini CLI
- Cline, RooCode, Amazon Q Developer
Works with FalkorDB by default (no database setup needed).
"""
console.print("\n[bold cyan]MCP Client Setup[/bold cyan]")
console.print("Configure your IDE or CLI tool to use CodeGraphContext.\n")
configure_mcp_client()
@mcp_app.command("start")
def mcp_start():
"""
Start the CodeGraphContext MCP server.
Starts the server which listens for JSON-RPC requests from stdin.
This is used by IDE integrations (VS Code, Cursor, etc.).
"""
console.print("[bold green]Starting CodeGraphContext Server...[/bold green]")
_load_credentials()
server = None
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
# Initialize and run the main server.
server = MCPServer(loop=loop)
loop.run_until_complete(server.run())
except ValueError as e:
# This typically happens if credentials are still not found after all checks.
console.print(f"[bold red]Configuration Error:[/bold red] {e}")
console.print("Please run `cgc neo4j setup` or use FalkorDB (default).")
except KeyboardInterrupt:
# Handle graceful shutdown on Ctrl+C.
console.print("\n[bold yellow]Server stopped by user.[/bold yellow]")
finally:
# Ensure server and event loop are properly closed.
if server:
server.shutdown()
loop.close()
@mcp_app.command("tools")
def mcp_tools():
"""
List all available MCP tools.
Shows all tools that can be called by AI assistants through the MCP interface.
"""
_load_credentials()
console.print("[bold green]Available MCP Tools:[/bold green]")
try:
# Instantiate the server to access the tool definitions.
server = MCPServer()
tools = server.tools.values()
table = Table(show_header=True, header_style="bold magenta")
table.add_column("Tool Name", style="dim", width=30)
table.add_column("Description")
for tool in sorted(tools, key=lambda t: t['name']):
table.add_row(tool['name'], tool['description'])
console.print(table)
except ValueError as e:
console.print(f"[bold red]Error loading tools:[/bold red] {e}")
console.print("Please ensure your database is configured correctly.")
except Exception as e:
console.print(f"[bold red]An unexpected error occurred:[/bold red] {e}")
# Abbreviation for mcp setup
@app.command("m", rich_help_panel="Shortcuts")
def mcp_setup_alias():
"""Shortcut for 'cgc mcp setup'"""
mcp_setup()
# Create Neo4j command group
neo4j_app = typer.Typer(help="Neo4j database configuration commands")
app.add_typer(neo4j_app, name="neo4j")
@neo4j_app.command("setup")
def neo4j_setup():
"""
Configure Neo4j Database Connection.
Choose from multiple setup options:
- Local (Docker-based, recommended)
- Local (Binary installation on Linux)
- Hosted (Neo4j AuraDB or remote instance)
- Connect to existing Neo4j instance
Note: This is optional. CodeGraphContext works with FalkorDB by default.
"""
console.print("\n[bold cyan]Neo4j Database Setup[/bold cyan]")
console.print("Configure Neo4j database connection for CodeGraphContext.\n")
run_neo4j_setup_wizard()
# Abbreviation for neo4j setup
@app.command("n", rich_help_panel="Shortcuts")
def neo4j_setup_alias():
"""Shortcut for 'cgc neo4j setup'"""
neo4j_setup()
# ============================================================================
# CREDENTIALS LOADING PRECEDENCE
# ============================================================================
def _load_credentials():
"""
Loads configuration and credentials from various sources into environment variables.
Uses per-variable precedence - each variable is loaded from the highest priority source.
Priority order (highest to lowest):
1. Local `mcp.json` env vars (highest - explicit MCP server config)
2. Local `.env` in project directory (high - project-specific overrides)
3. Global `~/.codegraphcontext/.env` (lowest - user defaults)
"""
from dotenv import dotenv_values
from codegraphcontext.cli.config_manager import ensure_config_dir
# Capture DATABASE_TYPE from actual shell env BEFORE we load .env files.
# If the user ran `DATABASE_TYPE=falkordb cgc …` we must not let
# DEFAULT_DATABASE=neo4j in .env steal priority later.
shell_db_type = os.environ.get('DATABASE_TYPE')
if shell_db_type and not os.environ.get('CGC_RUNTIME_DB_TYPE'):
os.environ['CGC_RUNTIME_DB_TYPE'] = shell_db_type
# Ensure config directory exists (lazy initialization)
ensure_config_dir()
# Collect all config sources in reverse priority order (lowest to highest)
config_sources = []
config_source_names = []
# 3. Global .env file (lowest priority - user defaults)
global_env_path = Path.home() / ".codegraphcontext" / ".env"
if global_env_path.exists():
try:
config_sources.append(dotenv_values(str(global_env_path)))
config_source_names.append(str(global_env_path))
except Exception as e:
console.print(f"[yellow]Warning: Could not load global .env: {e}[/yellow]")
# 2. Local project .env (higher priority - project-specific overrides)
try:
dotenv_path = find_dotenv(usecwd=True, raise_error_if_not_found=False)
if dotenv_path:
config_sources.append(dotenv_values(dotenv_path))
config_source_names.append(str(dotenv_path))
except Exception as e:
console.print(f"[yellow]Warning: Could not load .env from current directory: {e}[/yellow]")
# 1. Local mcp.json (highest priority - explicit MCP server config)
mcp_file_path = Path.cwd() / "mcp.json"
if mcp_file_path.exists():
try:
with open(mcp_file_path, "r") as f:
mcp_config = json.load(f)
server_env = mcp_config.get("mcpServers", {}).get("CodeGraphContext", {}).get("env", {})
if server_env:
config_sources.append(server_env)
config_source_names.append("mcp.json")
except Exception as e:
console.print(f"[yellow]Warning: Could not load mcp.json: {e}[/yellow]")
# Merge all configs with proper precedence (later sources override earlier ones)
merged_config = {}
for config in config_sources:
merged_config.update(config)
# Apply merged config to environment.
# IMPORTANT: DB-selection keys set in the shell must win over .env defaults.
# E.g. `DATABASE_TYPE=falkordb cgc index …` must not be overridden by
# DEFAULT_DATABASE=neo4j sitting in ~/.codegraphcontext/.env
DB_OVERRIDE_KEYS = {"DATABASE_TYPE", "CGC_RUNTIME_DB_TYPE", "DEFAULT_DATABASE"}
for key, value in merged_config.items():
if value is not None: # Only set non-None values
# Never let .env clobber a DB-type key that the user already set in the shell
if key in DB_OVERRIDE_KEYS and key in os.environ:
continue
os.environ[key] = str(value)
# Report what was loaded
if config_source_names:
if len(config_source_names) == 1:
console.print(f"[dim]Loaded configuration from: {config_source_names[-1]}[/dim]")
else:
console.print(f"[dim]Loaded configuration from: {', '.join(config_source_names)} (highest priority: {config_source_names[-1]})[/dim]")
else:
console.print("[yellow]No configuration file found. Using defaults.[/yellow]")
# Show which database is actually being used.
# When DATABASE_TYPE is explicitly set, trust it. When it's left to auto-
# detect, call get_database_manager() so the banner can never lie: e.g. if
# falkordblite is installed but its native .so is missing (frozen bundle),
# the factory falls back to KùzuDB and we display that correctly.
runtime_db = os.environ.get("CGC_RUNTIME_DB_TYPE")
explicit_db = (
runtime_db
or os.environ.get("DEFAULT_DATABASE")
or os.environ.get("DATABASE_TYPE")
)
if explicit_db:
default_db = explicit_db.lower()
else:
# No explicit choice — ask the factory which backend it will use
try:
from codegraphcontext.core import get_database_manager
_mgr = get_database_manager()
default_db = _mgr.get_backend_type() # e.g. 'falkordb' / 'kuzudb'
except Exception:
# Factory failed entirely — still show a best-guess
from codegraphcontext.core import _is_falkordb_available
default_db = "falkordb" if _is_falkordb_available() else "kuzudb"
if default_db == "neo4j":
has_neo4j_creds = all([
os.environ.get("NEO4J_URI"),
os.environ.get("NEO4J_USERNAME"),
os.environ.get("NEO4J_PASSWORD")
])
if has_neo4j_creds:
neo4j_db = os.environ.get("NEO4J_DATABASE")
if neo4j_db:
console.print(f"[cyan]Using database: Neo4j (database: {neo4j_db})[/cyan]")
else:
console.print("[cyan]Using database: Neo4j[/cyan]")
else:
console.print("[yellow]⚠ DEFAULT_DATABASE=neo4j but credentials not found. Falling back to default.[/yellow]")
elif default_db == "falkordb":
console.print("[cyan]Using database: FalkorDB Lite[/cyan]")
elif default_db == "kuzudb":
console.print("[cyan]Using database: KùzuDB[/cyan]")
elif default_db == "falkordb-remote":
host = os.environ.get("FALKORDB_HOST")
if host:
console.print(f"[cyan]Using database: FalkorDB Remote ({host})[/cyan]")
else:
console.print("[yellow]⚠ DATABASE_TYPE=falkordb-remote but FALKORDB_HOST not set.[/yellow]")
elif default_db == "falkordb":
if os.environ.get("FALKORDB_HOST"):
console.print(f"[cyan]Using database: FalkorDB Remote ({os.environ.get('FALKORDB_HOST')})[/cyan]")
else:
console.print("[cyan]Using database: FalkorDB[/cyan]")
else:
console.print(f"[cyan]Using database: {default_db}[/cyan]")
# ============================================================================
# CONFIG COMMAND GROUP
# ============================================================================
config_app = typer.Typer(help="Manage configuration settings")
app.add_typer(config_app, name="config")
@config_app.command("show")
def config_show():
"""
Display current configuration settings.
Shows all configuration values including database, indexing options,
logging settings, and performance tuning parameters.
"""
config_manager.show_config()
@config_app.command("set")
def config_set(
key: str = typer.Argument(..., help="Configuration key to set"),
value: str = typer.Argument(..., help="Value to set")
):
"""
Set a configuration value.
Examples:
cgc config set DEFAULT_DATABASE neo4j
cgc config set INDEX_VARIABLES false
cgc config set MAX_FILE_SIZE_MB 20
cgc config set DEBUG_LOGS true
"""
config_manager.set_config_value(key, value)
@config_app.command("reset")
def config_reset():
"""
Reset all configuration to default values.
This will restore all settings to their defaults.
Your current configuration will be backed up.
"""
if typer.confirm("Are you sure you want to reset all configuration to defaults?", default=False):
config_manager.reset_config()
else:
console.print("[yellow]Reset cancelled[/yellow]")
@config_app.command("db")
def config_db(backend: str = typer.Argument(..., help="Database backend: 'neo4j' or 'falkordb'")):
"""
Quickly switch the default database backend.
Shortcut for 'cgc config set DEFAULT_DATABASE <backend>'.
Examples:
cgc config db neo4j
cgc config db falkordb
"""
backend = backend.lower()
if backend not in ['falkordb', 'falkordb-remote', 'neo4j']:
console.print(f"[bold red]Invalid backend: {backend}[/bold red]")
console.print("Must be 'falkordb', 'falkordb-remote', or 'neo4j'")
raise typer.Exit(code=1)
config_manager.set_config_value("DEFAULT_DATABASE", backend)
console.print(f"[green]✔ Default database switched to {backend}[/green]")
# ============================================================================
# BUNDLE COMMAND GROUP - Pre-indexed Graph Snapshots
# ============================================================================
bundle_app = typer.Typer(help="Create and load pre-indexed graph bundles")
app.add_typer(bundle_app, name="bundle")
@bundle_app.command("export")
def bundle_export(
output: str = typer.Argument(..., help="Output path for the .cgc bundle file"),
repo: Optional[str] = typer.Option(None, "--repo", "-r", help="Specific repository path to export (default: export all)"),
no_stats: bool = typer.Option(False, "--no-stats", help="Skip statistics generation")
):
"""
Export the current graph to a portable .cgc bundle.
Creates a pre-indexed graph snapshot that can be distributed and loaded
instantly without re-indexing. Perfect for sharing famous repositories.
Examples:
cgc bundle export numpy.cgc --repo /path/to/numpy
cgc bundle export my-project.cgc
cgc bundle export all-repos.cgc --no-stats
"""
_load_credentials()
from codegraphcontext.core.cgc_bundle import CGCBundle
services = _initialize_services()
if not all(services):
return
db_manager, graph_builder, code_finder = services
try:
output_path = Path(output)
repo_path = Path(repo).resolve() if repo else None
console.print(f"[cyan]Exporting graph to {output_path}...[/cyan]")
if repo_path:
console.print(f"[dim]Repository: {repo_path}[/dim]")
else:
console.print(f"[dim]Exporting all repositories[/dim]")
bundle = CGCBundle(db_manager)
success, message = bundle.export_to_bundle(
output_path,
repo_path=repo_path,
include_stats=not no_stats
)
if success:
console.print(f"[bold green]{message}[/bold green]")
else:
console.print(f"[bold red]Export failed: {message}[/bold red]")
raise typer.Exit(code=1)
finally:
db_manager.close_driver()
@bundle_app.command("import")
def bundle_import(
bundle_file: str = typer.Argument(..., help="Path to the .cgc bundle file to import"),
clear: bool = typer.Option(False, "--clear", help="Clear existing graph data before importing")
):
"""
Import a .cgc bundle into the current database.
Loads a pre-indexed graph snapshot into your database. Use --clear to
replace all existing data with the bundle contents.
Examples:
cgc bundle import numpy.cgc
cgc bundle import my-project.cgc --clear
"""
_load_credentials()
from codegraphcontext.core.cgc_bundle import CGCBundle
services = _initialize_services()
if not all(services):
return
db_manager, graph_builder, code_finder = services
try:
bundle_path = Path(bundle_file)
if not bundle_path.exists():
console.print(f"[bold red]Bundle file not found: {bundle_path}[/bold red]")
raise typer.Exit(code=1)
if clear:
console.print("[yellow]⚠️ Warning: This will clear all existing graph data![/yellow]")
if not typer.confirm("Are you sure you want to continue?", default=False):
console.print("[yellow]Import cancelled[/yellow]")
return
console.print(f"[cyan]Importing bundle from {bundle_path}...[/cyan]")
bundle = CGCBundle(db_manager)
success, message = bundle.import_from_bundle(
bundle_path,
clear_existing=clear
)
if success:
console.print(f"[bold green]{message}[/bold green]")
else:
console.print(f"[bold red]Import failed: {message}[/bold red]")
raise typer.Exit(code=1)
finally:
db_manager.close_driver()
@bundle_app.command("load")
def bundle_load(
bundle_name: str = typer.Argument(..., help="Bundle name or path to load (e.g., 'numpy' or 'numpy.cgc')"),
clear: bool = typer.Option(False, "--clear", help="Clear existing graph data before loading")
):
"""
Load a pre-indexed bundle (download if needed, then import).
This is a convenience command that will:
1. Check if the bundle exists locally
2. Download from registry if not found
3. Import the bundle into the database
Examples:
cgc load numpy
cgc load numpy.cgc --clear
cgc load /path/to/bundle.cgc
"""
_load_credentials()
bundle_path = Path(bundle_name)
# If it's an absolute path or has .cgc extension and exists, use it directly
if bundle_path.is_absolute() or (bundle_path.suffix == '.cgc' and bundle_path.exists()):
bundle_import(str(bundle_path), clear=clear)
return
# Add .cgc extension if not present
if not bundle_path.suffix:
bundle_path = Path(f"{bundle_name}.cgc")
# Check if exists locally
if bundle_path.exists():
console.print(f"[dim]Found local bundle: {bundle_path}[/dim]")
bundle_import(str(bundle_path), clear=clear)
return
# Try to download from registry
console.print(f"[yellow]Bundle '{bundle_name}' not found locally.[/yellow]")
console.print(f"[cyan]Attempting to download from registry...[/cyan]")
try:
from .registry_commands import download_bundle
# Extract just the name (without .cgc extension)
name = bundle_path.stem
# Download the bundle
downloaded_path = download_bundle(name, output_dir=None, auto_load=True)
if downloaded_path:
# Import the downloaded bundle
bundle_import(downloaded_path, clear=clear)
else:
console.print(f"[bold red]Failed to download bundle '{name}'[/bold red]")
raise typer.Exit(code=1)
except Exception as e:
console.print(f"[bold red]Error: {e}[/bold red]")
console.print(f"[dim]Use 'cgc registry list' to see available bundles[/dim]")
raise typer.Exit(code=1)
# Shortcut commands at root level
@app.command("export", rich_help_panel="Bundle Shortcuts")
def export_shortcut(
output: str = typer.Argument(..., help="Output path for the .cgc bundle file"),
repo: Optional[str] = typer.Option(None, "--repo", "-r", help="Specific repository path to export")
):
"""Shortcut for 'cgc bundle export'"""
bundle_export(output, repo, False)
@app.command("load", rich_help_panel="Bundle Shortcuts")
def load_shortcut(
bundle_name: str = typer.Argument(..., help="Bundle name or path to load"),
clear: bool = typer.Option(False, "--clear", help="Clear existing graph data before loading")
):
"""Shortcut for 'cgc bundle load'"""
bundle_load(bundle_name, clear)
# ============================================================================
# REGISTRY COMMAND GROUP - Browse and Download Bundles
# ============================================================================
registry_app = typer.Typer(help="Browse and download bundles from the registry")
app.add_typer(registry_app, name="registry")
@registry_app.command("list")
def registry_list(
verbose: bool = typer.Option(False, "--verbose", "-v", help="Show detailed information including download URLs"),
unique: bool = typer.Option(False, "--unique", "-u", help="Show only one version per package (most recent)")
):
"""
List all available bundles in the registry.
Shows bundles from both weekly pre-indexed releases and on-demand generations.
By default, shows all versions. Use --unique to see only the most recent version per package.
Examples:
cgc registry list
cgc registry list --verbose
cgc registry list --unique
"""
from .registry_commands import list_bundles
list_bundles(verbose=verbose, unique=unique)
@registry_app.command("search")
def registry_search(
query: str = typer.Argument(..., help="Search query (matches name, repository, or description)")
):
"""
Search for bundles in the registry.
Searches bundle names, repositories, and descriptions for matches.
Examples:
cgc registry search numpy
cgc registry search web
cgc registry search http
"""
from .registry_commands import search_bundles
search_bundles(query)
@registry_app.command("download")
def registry_download(
name: str = typer.Argument(..., help="Bundle name to download (e.g., 'numpy')"),
output_dir: Optional[str] = typer.Option(None, "--output", "-o", help="Output directory (default: current directory)"),
load: bool = typer.Option(False, "--load", "-l", help="Automatically load the bundle after downloading")
):
"""
Download a bundle from the registry.
Downloads the specified bundle to the current directory or specified output directory.
Use --load to automatically import the bundle after downloading.
Examples:
cgc registry download numpy
cgc registry download pandas --output ./bundles
cgc registry download fastapi --load
"""
from .registry_commands import download_bundle
bundle_path = download_bundle(name, output_dir, auto_load=load)
if load and bundle_path:
console.print(f"\n[cyan]Loading bundle...[/cyan]")
bundle_import(bundle_path, clear=False)
@registry_app.command("request")
def registry_request(
repo_url: str = typer.Argument(..., help="GitHub repository URL to index"),
wait: bool = typer.Option(False, "--wait", "-w", help="Wait for generation to complete (not yet implemented)")
):
"""
Request on-demand generation of a bundle.
Submits a request to generate a bundle for the specified GitHub repository.
The bundle will be available in the registry after 5-10 minutes.
Examples:
cgc registry request https://github.com/encode/httpx
cgc registry request https://github.com/pallets/flask
"""
from .registry_commands import request_bundle
request_bundle(repo_url, wait=wait)
# ============================================================================
# DOCTOR DIAGNOSTIC COMMAND
# ============================================================================
@app.command()
def doctor():
"""
Run diagnostics to check system health and configuration.
Checks:
- Configuration validity
- Database connectivity
- Tree-sitter installation
- Required dependencies
- File permissions
"""
console.print("[bold cyan]🏥 Running CodeGraphContext Diagnostics...[/bold cyan]\n")
all_checks_passed = True
# 1. Check configuration
console.print("[bold]1. Checking Configuration...[/bold]")
try:
config = config_manager.load_config()
# Check if config file actually exists
if config_manager.CONFIG_FILE.exists():
console.print(f" [green]✓[/green] Configuration loaded from {config_manager.CONFIG_FILE}")
else:
console.print(f" [yellow]ℹ[/yellow] No config file found, using defaults")
console.print(f" [dim]Config will be created at: {config_manager.CONFIG_FILE}[/dim]")
# Validate each config value
invalid_configs = []
for key, value in config.items():
is_valid, error_msg = config_manager.validate_config_value(key, value)
if not is_valid:
invalid_configs.append(f"{key}: {error_msg}")
if invalid_configs:
console.print(f" [red]✗[/red] Invalid configuration values found:")
for err in invalid_configs:
console.print(f" - {err}")
all_checks_passed = False
else:
console.print(f" [green]✓[/green] All configuration values are valid")
except Exception as e:
console.print(f" [red]✗[/red] Configuration error: {e}")
all_checks_passed = False
# 2. Check database connectivity
console.print("\n[bold]2. Checking Database Connection...[/bold]")
try:
_load_credentials()
default_db = config.get("DEFAULT_DATABASE", "falkordb")
console.print(f" Default database: {default_db}")
if default_db == "neo4j":
uri = os.environ.get("NEO4J_URI")
username = os.environ.get("NEO4J_USERNAME")
password = os.environ.get("NEO4J_PASSWORD")
if uri and username and password:
console.print(f" [cyan]Testing Neo4j connection to {uri}...[/cyan]")
is_connected, error_msg = DatabaseManager.test_connection(uri, username, password, database=os.environ.get("NEO4J_DATABASE"))
if is_connected:
console.print(f" [green]✓[/green] Neo4j connection successful")
else:
console.print(f" [red]✗[/red] Neo4j connection failed: {error_msg}")
all_checks_passed = False
else:
console.print(f" [yellow]⚠[/yellow] Neo4j credentials not set. Run 'cgc neo4j setup'")
else:
# FalkorDB
try:
import falkordb
console.print(f" [green]✓[/green] FalkorDB Lite is installed")
except ImportError:
console.print(f" [yellow]⚠[/yellow] FalkorDB Lite not installed (Python 3.12+ only)")
console.print(f" Run: pip install falkordblite")
except Exception as e:
console.print(f" [red]✗[/red] Database check error: {e}")
all_checks_passed = False
# 3. Check tree-sitter installation
console.print("\n[bold]3. Checking Tree-Sitter Installation...[/bold]")
try:
from tree_sitter import Language, Parser
console.print(f" [green]✓[/green] tree-sitter is installed")
try:
from tree_sitter_language_pack import get_language
console.print(f" [green]✓[/green] tree-sitter-language-pack is installed")
# Test a few languages
test_langs = ["python", "javascript", "typescript"]
for lang in test_langs:
try:
get_language(lang)
console.print(f" [green]✓[/green] {lang} parser available")
except Exception:
console.print(f" [yellow]⚠[/yellow] {lang} parser not available")
except ImportError:
console.print(f" [red]✗[/red] tree-sitter-language-pack not installed")
all_checks_passed = False
except ImportError as e:
console.print(f" [red]✗[/red] tree-sitter not installed: {e}")
all_checks_passed = False
# 4. Check file permissions
console.print("\n[bold]4. Checking File Permissions...[/bold]")
try:
config_dir = config_manager.CONFIG_DIR
if config_dir.exists():
console.print(f" [green]✓[/green] Config directory exists: {config_dir}")
# Check if writable
test_file = config_dir / ".test_write"
try:
test_file.touch()
test_file.unlink()
console.print(f" [green]✓[/green] Config directory is writable")
except Exception as e:
console.print(f" [red]✗[/red] Config directory not writable: {e}")
all_checks_passed = False
else:
console.print(f" [yellow]⚠[/yellow] Config directory doesn't exist, will be created on first use")
except Exception as e:
console.print(f" [red]✗[/red] Permission check error: {e}")
all_checks_passed = False
# 5. Check cgc command availability
console.print("\n[bold]5. Checking CGC Command...[/bold]")
import shutil
cgc_path = shutil.which("cgc")
if cgc_path:
console.print(f" [green]✓[/green] cgc command found at: {cgc_path}")
else:
console.print(f" [yellow]⚠[/yellow] cgc command not in PATH (using python -m cgc)")
# Final summary
console.print("\n" + "=" * 60)
if all_checks_passed:
console.print("[bold green]✅ All diagnostics passed! System is healthy.[/bold green]")
else:
console.print("[bold yellow]⚠️ Some issues detected. Please review the output above.[/bold yellow]")
console.print("\n[cyan]Common fixes:[/cyan]")
console.print(" • For Neo4j issues: Run 'cgc neo4j setup'")
console.print(" • For missing packages: pip install codegraphcontext")
console.print(" • For config issues: Run 'cgc config reset'")
console.print("=" * 60 + "\n")
@app.command()
def start():
"""
[DEPRECATED] Use 'cgc mcp start' instead. This command will be removed in a future version.
"""
console.print("[yellow]⚠️ 'cgc start' is deprecated. Use 'cgc mcp start' instead.[/yellow]")
mcp_start()
@app.command()
def index(
path: Optional[str] = typer.Argument(None, help="Path to the directory or file to index. Defaults to the current directory."),
force: bool = typer.Option(False, "--force", "-f", help="Force re-index (delete existing and rebuild)")
):
"""
Indexes a directory or file by adding it to the code graph.
If no path is provided, it indexes the current directory.
Use --force to delete the existing index and rebuild from scratch.
"""
_load_credentials()
if path is None:
path = str(Path.cwd())
if force:
console.print("[yellow]Force re-indexing (--force flag detected)[/yellow]")
reindex_helper(path)
else:
index_helper(path)
@app.command()
def clean():
"""
Remove orphaned nodes and relationships from the database.
This will clean up nodes that are not connected to any repository,
helping to keep your database tidy and performant.
"""
_load_credentials()
clean_helper()
@app.command()
def stats(path: Optional[str] = typer.Argument(None, help="Path to show stats for. Omit for overall stats.")):
"""
Show indexing statistics.
If a path is provided, shows stats for that specific repository.
Otherwise, shows overall database statistics.
"""
_load_credentials()
if path:
path = str(Path(path).resolve())
stats_helper(path)
@app.command()
def delete(
path: Optional[str] = typer.Argument(None, help="Path of the repository to delete from the code graph."),
all_repos: bool = typer.Option(False, "--all", help="Delete all indexed repositories")
):
"""
Deletes a repository from the code graph.
Use --all to delete all repositories at once (requires confirmation).
Examples:
cgc delete ./my-project # Delete specific repository
cgc delete --all # Delete all repositories
"""
_load_credentials()
if all_repos:
# Delete all repositories
services = _initialize_services()
if not all(services):
return
db_manager, graph_builder, code_finder = services
try:
# Get list of repositories
repos = code_finder.list_indexed_repositories()
if not repos:
console.print("[yellow]No repositories to delete.[/yellow]")
return
# Show what will be deleted
console.print(f"\n[bold red]⚠️ WARNING: You are about to delete ALL {len(repos)} repositories![/bold red]\n")
table = Table(show_header=True, header_style="bold magenta")
table.add_column("Name", style="cyan")
table.add_column("Path", style="dim")
for repo in repos:
table.add_row(repo.get("name", ""), repo.get("path", ""))
console.print(table)
console.print()
# Double confirmation
if not typer.confirm("Are you sure you want to delete ALL repositories?", default=False):
console.print("[yellow]Deletion cancelled.[/yellow]")
return
console.print("[yellow]Please type 'delete all' to confirm:[/yellow] ", end="")
confirmation = input()
if confirmation.strip().lower() != "delete all":
console.print("[yellow]Deletion cancelled. Confirmation text did not match.[/yellow]")
return
# Delete all repositories
console.print("\n[cyan]Deleting all repositories...[/cyan]")
deleted_count = 0
for repo in repos:
repo_path = repo.get("path", "")
try:
graph_builder.delete_repository_from_graph(repo_path)
console.print(f"[green]✓[/green] Deleted: {repo.get('name', '')}")
deleted_count += 1
except Exception as e:
console.print(f"[red]✗[/red] Failed to delete {repo.get('name', '')}: {e}")
console.print(f"\n[bold green]Successfully deleted {deleted_count}/{len(repos)} repositories![/bold green]")
finally:
db_manager.close_driver()
else:
# Delete specific repository
if not path:
console.print("[red]Error: Please provide a path or use --all to delete all repositories[/red]")
console.print("Usage: cgc delete <path> or cgc delete --all")
raise typer.Exit(code=1)
delete_helper(path)
@app.command()
def visualize(
repo: Optional[str] = typer.Option(None, "--repo", "-r", help="Path to the repository to visualize."),
port: int = typer.Option(8000, "--port", "-p", help="Port to run the visualizer server on.")
):