codegraphcontext-rust 0.5.5__cp311-cp311-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. codegraphcontext/__init__.py +2 -0
  2. codegraphcontext/__main__.py +5 -0
  3. codegraphcontext/_cgc_rust.cp311-win_amd64.pyd +0 -0
  4. codegraphcontext/cli/__init__.py +1 -0
  5. codegraphcontext/cli/cli_helpers.py +774 -0
  6. codegraphcontext/cli/config_manager.py +1051 -0
  7. codegraphcontext/cli/main.py +2386 -0
  8. codegraphcontext/cli/registry_commands.py +404 -0
  9. codegraphcontext/cli/setup_macos.py +93 -0
  10. codegraphcontext/cli/setup_wizard.py +991 -0
  11. codegraphcontext/cli/visualizer.py +50 -0
  12. codegraphcontext/core/__init__.py +165 -0
  13. codegraphcontext/core/bundle_registry.py +181 -0
  14. codegraphcontext/core/cgc_bundle.py +858 -0
  15. codegraphcontext/core/cgcignore.py +118 -0
  16. codegraphcontext/core/database.py +273 -0
  17. codegraphcontext/core/database_falkordb.py +480 -0
  18. codegraphcontext/core/database_falkordb_remote.py +199 -0
  19. codegraphcontext/core/database_kuzu.py +636 -0
  20. codegraphcontext/core/falkor_worker.py +132 -0
  21. codegraphcontext/core/jobs.py +132 -0
  22. codegraphcontext/core/watcher.py +260 -0
  23. codegraphcontext/prompts.py +125 -0
  24. codegraphcontext/server.py +471 -0
  25. codegraphcontext/tool_definitions.py +220 -0
  26. codegraphcontext/tools/__init__.py +0 -0
  27. codegraphcontext/tools/advanced_language_query_tool.py +103 -0
  28. codegraphcontext/tools/code_finder.py +1160 -0
  29. codegraphcontext/tools/graph_builder.py +337 -0
  30. codegraphcontext/tools/handlers/analysis_handlers.py +114 -0
  31. codegraphcontext/tools/handlers/indexing_handlers.py +116 -0
  32. codegraphcontext/tools/handlers/management_handlers.py +339 -0
  33. codegraphcontext/tools/handlers/query_handlers.py +83 -0
  34. codegraphcontext/tools/handlers/watcher_handlers.py +83 -0
  35. codegraphcontext/tools/indexing/__init__.py +1 -0
  36. codegraphcontext/tools/indexing/constants.py +25 -0
  37. codegraphcontext/tools/indexing/discovery.py +64 -0
  38. codegraphcontext/tools/indexing/engine.py +109 -0
  39. codegraphcontext/tools/indexing/persistence/__init__.py +3 -0
  40. codegraphcontext/tools/indexing/persistence/parquet_loader.py +643 -0
  41. codegraphcontext/tools/indexing/persistence/writer.py +1114 -0
  42. codegraphcontext/tools/indexing/pipeline.py +171 -0
  43. codegraphcontext/tools/indexing/pre_scan.py +105 -0
  44. codegraphcontext/tools/indexing/resolution/__init__.py +8 -0
  45. codegraphcontext/tools/indexing/resolution/calls.py +253 -0
  46. codegraphcontext/tools/indexing/resolution/inheritance.py +91 -0
  47. codegraphcontext/tools/indexing/sanitize.py +41 -0
  48. codegraphcontext/tools/indexing/schema.py +79 -0
  49. codegraphcontext/tools/indexing/schema_contract.py +44 -0
  50. codegraphcontext/tools/indexing/scip_pipeline.py +140 -0
  51. codegraphcontext/tools/languages/c.py +563 -0
  52. codegraphcontext/tools/languages/cpp.py +616 -0
  53. codegraphcontext/tools/languages/csharp.py +551 -0
  54. codegraphcontext/tools/languages/dart.py +378 -0
  55. codegraphcontext/tools/languages/elixir.py +460 -0
  56. codegraphcontext/tools/languages/go.py +499 -0
  57. codegraphcontext/tools/languages/haskell.py +426 -0
  58. codegraphcontext/tools/languages/java.py +500 -0
  59. codegraphcontext/tools/languages/javascript.py +589 -0
  60. codegraphcontext/tools/languages/kotlin.py +640 -0
  61. codegraphcontext/tools/languages/perl.py +260 -0
  62. codegraphcontext/tools/languages/php.py +519 -0
  63. codegraphcontext/tools/languages/python.py +576 -0
  64. codegraphcontext/tools/languages/ruby.py +537 -0
  65. codegraphcontext/tools/languages/rust.py +295 -0
  66. codegraphcontext/tools/languages/scala.py +519 -0
  67. codegraphcontext/tools/languages/swift.py +491 -0
  68. codegraphcontext/tools/languages/typescript.py +575 -0
  69. codegraphcontext/tools/languages/typescriptjsx.py +151 -0
  70. codegraphcontext/tools/package_resolver.py +472 -0
  71. codegraphcontext/tools/query_tool_languages/c_toolkit.py +5 -0
  72. codegraphcontext/tools/query_tool_languages/cpp_toolkit.py +87 -0
  73. codegraphcontext/tools/query_tool_languages/csharp_toolkit.py +5 -0
  74. codegraphcontext/tools/query_tool_languages/dart_toolkit.py +5 -0
  75. codegraphcontext/tools/query_tool_languages/go_toolkit.py +5 -0
  76. codegraphcontext/tools/query_tool_languages/haskell_toolkit.py +5 -0
  77. codegraphcontext/tools/query_tool_languages/java_toolkit.py +5 -0
  78. codegraphcontext/tools/query_tool_languages/javascript_toolkit.py +5 -0
  79. codegraphcontext/tools/query_tool_languages/perl_toolkit.py +5 -0
  80. codegraphcontext/tools/query_tool_languages/python_toolkit.py +5 -0
  81. codegraphcontext/tools/query_tool_languages/ruby_toolkit.py +5 -0
  82. codegraphcontext/tools/query_tool_languages/rust_toolkit.py +5 -0
  83. codegraphcontext/tools/query_tool_languages/scala_toolkit.py +5 -0
  84. codegraphcontext/tools/query_tool_languages/swift_toolkit.py +5 -0
  85. codegraphcontext/tools/query_tool_languages/typescript_toolkit.py +5 -0
  86. codegraphcontext/tools/scip_indexer.py +467 -0
  87. codegraphcontext/tools/scip_pb2.py +2455 -0
  88. codegraphcontext/tools/system.py +133 -0
  89. codegraphcontext/tools/tree_sitter_parser.py +103 -0
  90. codegraphcontext/utils/debug_log.py +90 -0
  91. codegraphcontext/utils/path_ignore.py +55 -0
  92. codegraphcontext/utils/repo_path.py +27 -0
  93. codegraphcontext/utils/tree_sitter_manager.py +285 -0
  94. codegraphcontext/utils/visualize_graph.py +0 -0
  95. codegraphcontext/viz/server.py +282 -0
  96. codegraphcontext_rust-0.5.5.dist-info/METADATA +537 -0
  97. codegraphcontext_rust-0.5.5.dist-info/RECORD +101 -0
  98. codegraphcontext_rust-0.5.5.dist-info/WHEEL +4 -0
  99. codegraphcontext_rust-0.5.5.dist-info/entry_points.txt +3 -0
  100. codegraphcontext_rust-0.5.5.dist-info/licenses/LICENSE +21 -0
  101. codegraphcontext_rust-0.5.5.dist-info/sboms/cgc-python.cyclonedx.json +2333 -0
@@ -0,0 +1,991 @@
1
+ from InquirerPy import prompt
2
+ from rich.console import Console
3
+ import subprocess
4
+ import platform
5
+ import os
6
+ from pathlib import Path
7
+ import time
8
+ import json
9
+ import sys
10
+ import shutil
11
+ import yaml
12
+ from codegraphcontext.core.database import DatabaseManager
13
+
14
+ console = Console()
15
+
16
+ # Constants for Docker Neo4j setup
17
+ DEFAULT_NEO4J_URI = "neo4j://localhost:7687"
18
+ DEFAULT_NEO4J_USERNAME = "neo4j"
19
+ DEFAULT_NEO4J_BOLT_PORT = 7687
20
+ DEFAULT_NEO4J_HTTP_PORT = 7474
21
+
22
+ def _save_neo4j_credentials(creds):
23
+ """
24
+ Save Neo4j credentials to .env file (database setup only).
25
+ Does NOT generate MCP config or configure IDE.
26
+ """
27
+ from codegraphcontext.cli.config_manager import load_config, save_config, ensure_config_dir
28
+
29
+ ensure_config_dir()
30
+
31
+ # Load existing config (or defaults if no file exists)
32
+ config = load_config()
33
+
34
+ # Update Neo4j credentials
35
+ config["NEO4J_URI"] = creds.get('uri', '')
36
+ config["NEO4J_USERNAME"] = creds.get('username', 'neo4j')
37
+ config["NEO4J_PASSWORD"] = creds.get('password', '')
38
+
39
+ # Set default database to neo4j
40
+ config["DEFAULT_DATABASE"] = "neo4j"
41
+
42
+ # Save config (preserves all other settings)
43
+ save_config(config, preserve_db_credentials=False)
44
+
45
+ console.print("\n[bold green]✅ Neo4j setup complete![/bold green]")
46
+ console.print(f"[cyan]📝 Credentials saved to ~/.codegraphcontext/.env[/cyan]")
47
+ console.print(f"[cyan]🔧 Default database set to 'neo4j'[/cyan]")
48
+ console.print("\n[dim]You can now use cgc commands with Neo4j:[/dim]")
49
+ console.print("[dim] • cgc index . - Index your code[/dim]")
50
+ console.print("[dim] • cgc find function - Search your codebase[/dim]")
51
+ console.print("\n[dim]To use cgc as an MCP server in your IDE, run:[/dim]")
52
+ console.print("[dim] cgc mcp setup[/dim]")
53
+
54
+
55
+ def _generate_mcp_json(creds):
56
+ """Generates and prints the MCP JSON configuration."""
57
+ cgc_path = shutil.which("cgc") or sys.executable
58
+
59
+ if "python" in Path(cgc_path).name:
60
+ # fallback to running as module if no cgc binary is found
61
+ command = cgc_path
62
+ args = ["-m", "cgc", "mcp", "start"]
63
+ else:
64
+ command = cgc_path
65
+ args = ["mcp","start"]
66
+
67
+ mcp_config = {
68
+ "mcpServers": {
69
+ "CodeGraphContext": {
70
+ "command": command,
71
+ "args": args,
72
+ "env": {
73
+ "NEO4J_URI": creds.get("uri", ""),
74
+ "NEO4J_USERNAME": creds.get("username", "neo4j"),
75
+ "NEO4J_PASSWORD": creds.get("password", "")
76
+ },
77
+ "tools": {
78
+ "alwaysAllow": [
79
+ "add_code_to_graph", "add_package_to_graph",
80
+ "check_job_status", "list_jobs", "find_code",
81
+ "analyze_code_relationships", "watch_directory",
82
+ "find_dead_code", "execute_cypher_query",
83
+ "calculate_cyclomatic_complexity", "find_most_complex_functions",
84
+ "list_indexed_repositories", "delete_repository", "list_watched_paths",
85
+ "unwatch_directory", "visualize_graph_query"
86
+ ],
87
+ "disabled": False
88
+ },
89
+ "disabled": False,
90
+ "alwaysAllow": []
91
+ }
92
+ }
93
+ }
94
+
95
+ console.print("\n[bold green]Configuration successful![/bold green]")
96
+ console.print("Copy the following JSON and add it to your MCP server configuration file:")
97
+ console.print(json.dumps(mcp_config, indent=2))
98
+
99
+ # Also save to a file for convenience
100
+ mcp_file = Path.cwd() / "mcp.json"
101
+ with open(mcp_file, "w") as f:
102
+ json.dump(mcp_config, f, indent=2)
103
+ console.print(f"\n[cyan]For your convenience, the configuration has also been saved to: {mcp_file}[/cyan]")
104
+
105
+ # Also save credentials to .env using the proper function
106
+ _save_neo4j_credentials(creds)
107
+ _configure_ide(mcp_config)
108
+
109
+
110
+ def find_jetbrains_mcp_config():
111
+ bases = [
112
+ Path.home() / ".config" / "JetBrains",
113
+ Path.home() / "Library/Application Support/JetBrains",
114
+ Path.home() / "AppData/Roaming/JetBrains"
115
+ ]
116
+ configs = []
117
+ for base in bases:
118
+ if base.exists():
119
+ for folder in base.iterdir(): # each IDE/version
120
+ options = folder / "options"
121
+ mcp_file = options / "mcpServer.xml"
122
+ if mcp_file.exists():
123
+ configs.append(mcp_file)
124
+ print(mcp_file)
125
+ return configs
126
+
127
+
128
+ def convert_mcp_json_to_yaml():
129
+ json_path = Path.cwd() / "mcp.json"
130
+ yaml_path = Path.cwd() / "devfile.yaml"
131
+ if json_path.exists():
132
+ with open(json_path, "r") as json_file:
133
+ mcp_config = json.load(json_file)
134
+ with open(yaml_path, "w") as yaml_file:
135
+ yaml.dump(mcp_config, yaml_file, default_flow_style=False)
136
+ console.print(f"[green]Generated devfile.yaml for Amazon Q Developer at {yaml_path}[/green]")
137
+
138
+ def _print_opencode_mcp_instructions(mcp_config: dict) -> None:
139
+ """OpenCode manages MCP in its own UI; we only print the stdio snippet + doc link."""
140
+ console.print("\n[bold cyan]OpenCode[/bold cyan]")
141
+ console.print(
142
+ "Register a stdio MCP server in OpenCode using the same command, args, and env as below "
143
+ "(mirror your generated mcp.json so OpenCode and the CLI share one database)."
144
+ )
145
+ console.print(
146
+ "\n[dim]Vendor guide:[/dim] https://opencode.ai/docs/ko/mcp-servers/#_top"
147
+ )
148
+ console.print("\n[bold]Suggested MCP server JSON:[/bold]")
149
+ console.print(json.dumps(mcp_config, indent=2))
150
+
151
+
152
+ def _configure_ide(mcp_config):
153
+ """Asks user for their IDE and configures it automatically."""
154
+ questions = [
155
+ {
156
+ "type": "confirm",
157
+ "message": "Automatically configure your IDE/CLI (VS Code, Cursor, Windsurf, Claude, Gemini, Cline, RooCode, ChatGPT Codex, Amazon Q Developer, Aider, Kiro, Antigravity, OpenCode)?",
158
+ "name": "configure_ide",
159
+ "default": True,
160
+ }
161
+ ]
162
+ result = prompt(questions)
163
+ if not result or not result.get("configure_ide"):
164
+ console.print("\n[cyan]Skipping automatic IDE configuration. You can add the MCP server manually.[/cyan]")
165
+ return
166
+
167
+ ide_questions = [
168
+ {
169
+ "type": "list",
170
+ "message": "Choose your IDE/CLI to configure:",
171
+ "choices": ["VS Code", "Cursor", "Windsurf", "Claude code", "Gemini CLI", "ChatGPT Codex", "Cline", "RooCode", "Amazon Q Developer", "JetBrainsAI", "Aider", "Kiro", "Antigravity", "OpenCode", "None of the above"],
172
+ "name": "ide_choice",
173
+ }
174
+ ]
175
+ ide_result = prompt(ide_questions)
176
+ ide_choice = ide_result.get("ide_choice")
177
+
178
+ if not ide_choice or ide_choice == "None of the above":
179
+ console.print("\n[cyan]You can add the MCP server manually to your IDE/CLI.[/cyan]")
180
+ return
181
+
182
+ if ide_choice == "OpenCode":
183
+ _print_opencode_mcp_instructions(mcp_config)
184
+ console.print(
185
+ "\n[green]When you have pasted this into OpenCode, reload MCP and run "
186
+ "`cgc mcp start` from a terminal to verify the server starts cleanly.[/green]"
187
+ )
188
+ return
189
+
190
+ if ide_choice in ["VS Code", "Cursor", "Claude code", "Gemini CLI", "ChatGPT Codex", "Cline", "Windsurf", "RooCode", "Amazon Q Developer", "JetBrainsAI", "Aider", "Kiro", "Antigravity"]:
191
+ console.print(f"\n[bold cyan]Configuring for {ide_choice}...[/bold cyan]")
192
+
193
+ if ide_choice == "Amazon Q Developer":
194
+ convert_mcp_json_to_yaml()
195
+ return
196
+
197
+ config_paths = {
198
+ "VS Code": [
199
+ Path.home() / ".config" / "Code" / "User" / "settings.json",
200
+ Path.home() / "Library" / "Application Support" / "Code" / "User" / "settings.json",
201
+ Path.home() / "AppData" / "Roaming" / "Code" / "User" / "settings.json"
202
+ ],
203
+ "Cursor/CLI": [
204
+ Path.home() / ".cursor" / "settings.json",
205
+ Path.home() / ".config" / "cursor" / "settings.json",
206
+ Path.home() / "Library" / "Application Support" / "cursor" / "settings.json",
207
+ Path.home() / "AppData" / "Roaming" / "cursor" / "settings.json",
208
+ Path.home() / ".config" / "Cursor" / "User" / "settings.json",
209
+ ],
210
+ "Windsurf": [
211
+ Path.home() / ".windsurf" / "settings.json",
212
+ Path.home() / ".config" / "windsurf" / "settings.json",
213
+ Path.home() / "Library" / "Application Support" / "windsurf" / "settings.json",
214
+ Path.home() / "AppData" / "Roaming" / "windsurf" / "settings.json",
215
+ Path.home() / ".config" / "Windsurf" / "User" / "settings.json",
216
+ ],
217
+ "Claude code": [
218
+ Path.home() / ".claude.json"
219
+ ],
220
+ "Gemini CLI": [
221
+ Path.home() / ".gemini" / "settings.json"
222
+ ],
223
+ "ChatGPT Codex": [
224
+ Path.home() / ".openai" / "mcp_settings.json",
225
+ Path.home() / ".config" / "openai" / "settings.json",
226
+ Path.home() / "AppData" / "Roaming" / "OpenAI" / "settings.json"
227
+ ],
228
+ "Cline": [
229
+ Path.home() / ".config" / "Code" / "User" / "globalStorage" / "saoudrizwan.claude-dev" / "settings" / "cline_mcp_settings.json",
230
+ Path.home() / ".config" / "Code - OSS" / "User" / "globalStorage" / "saoudrizwan.claude-dev" / "settings" / "cline_mcp_settings.json",
231
+ Path.home() / "Library" / "Application Support" / "Code" / "User" / "globalStorage" / "saoudrizwan.claude-dev" / "settings" / "cline_mcp_settings.json",
232
+ Path.home() / "AppData" / "Roaming" / "Code" / "User" / "globalStorage" / "saoudrizwan.claude-dev" / "settings" / "cline_mcp_settings.json"
233
+ ],
234
+
235
+ "JetBrainsAI": find_jetbrains_mcp_config(), #only for jetbrains ide
236
+
237
+ "RooCode": [
238
+ Path.home() / ".config" / "Code" / "User" / "settings.json", # Linux
239
+ Path.home() / "AppData" / "Roaming" / "Code" / "User" / "settings.json", # Windows
240
+ Path.home() / "Library" / "Application Support" / "Code" / "User" / "settings.json" # macOS
241
+ ],
242
+ "Aider": [
243
+ Path.home() / ".aider" / "settings.json",
244
+ Path.home() / ".config" / "aider" / "settings.json",
245
+ Path.home() / "Library" / "Application Support" / "aider" / "settings.json",
246
+ Path.home() / "AppData" / "Roaming" / "aider" / "settings.json",
247
+ Path.home() / ".config" / "Aider" / "User" / "settings.json",
248
+ ],
249
+ "Kiro": [
250
+ Path.home() / ".kiro" / "settings" / "mcp.json", # macOS / Linux / Windows (user-level global)
251
+ Path.home() / ".config" / "kiro" / "settings" / "mcp.json", # Linux (XDG config)
252
+ Path.home() / "AppData" / "Roaming" / "Kiro" / "settings" / "mcp.json", # Windows
253
+ ],
254
+ "Antigravity": [
255
+ Path.home() / ".antigravity" / "mcp_settings.json", # macOS / Linux / Windows (user-level global)
256
+ Path.home() / ".config" / "antigravity" / "mcp_settings.json", # Linux (XDG config)
257
+ Path.home() / "AppData" / "Roaming" / "Antigravity" / "mcp_settings.json", # Windows
258
+ ]
259
+ }
260
+
261
+ target_path = None
262
+ paths_to_check = config_paths.get(ide_choice, [])
263
+ for path in paths_to_check:
264
+ if path.exists():
265
+ target_path = path
266
+ break
267
+
268
+ if not target_path:
269
+ # If file doesn't exist, check if parent directory exists
270
+ for path in paths_to_check:
271
+ if path.parent.exists():
272
+ target_path = path
273
+ break
274
+
275
+ if not target_path:
276
+ console.print(f"[yellow]Could not automatically find or create the configuration directory for {ide_choice}.[/yellow]")
277
+ console.print("Please add the MCP configuration manually from the `mcp.json` file generated above.")
278
+ return
279
+
280
+ console.print(f"Using configuration file at: {target_path}")
281
+
282
+ try:
283
+ with open(target_path, "r") as f:
284
+ try:
285
+ settings = json.load(f)
286
+ except json.JSONDecodeError:
287
+ settings = {}
288
+ except FileNotFoundError:
289
+ settings = {}
290
+
291
+ if not isinstance(settings, dict):
292
+ console.print(f"[red]Error: Configuration file at {target_path} is not a valid JSON object.[/red]")
293
+ return
294
+
295
+ if "mcpServers" not in settings:
296
+ settings["mcpServers"] = {}
297
+
298
+ settings["mcpServers"].update(mcp_config["mcpServers"])
299
+
300
+ try:
301
+ with open(target_path, "w") as f:
302
+ json.dump(settings, f, indent=2)
303
+ console.print(f"[green]Successfully updated {ide_choice} configuration.[/green]")
304
+ except Exception as e:
305
+ console.print(f"[red]Failed to write to configuration file: {e}[/red]")
306
+
307
+
308
+
309
+
310
+ def get_project_root() -> Path:
311
+ """Always return the directory where the user runs `cgc` (CWD)."""
312
+ return Path.cwd()
313
+
314
+ def run_command(command, console, shell=False, check=True, input_text=None):
315
+ """
316
+ Runs a command, captures its output, and handles execution.
317
+ Returns the completed process object on success, None on failure.
318
+ """
319
+ cmd_str = command if isinstance(command, str) else ' '.join(command)
320
+
321
+ # Mask passwords from being printed out
322
+ if "set-initial-password" in cmd_str:
323
+ import re
324
+ cmd_str = re.sub(r'(set-initial-password\s+)(\S+)', r'\g<1>********', cmd_str)
325
+
326
+ console.print(f"[cyan]$ {cmd_str}[/cyan]")
327
+ try:
328
+ process = subprocess.run(
329
+ command,
330
+ shell=shell,
331
+ check=check,
332
+ capture_output=True, # Always capture to control what gets displayed
333
+ text=True,
334
+ timeout=300,
335
+ input=input_text
336
+ )
337
+ return process
338
+ except subprocess.CalledProcessError as e:
339
+ console.print(f"[bold red]Error executing command:[/bold red] {cmd_str}")
340
+ if e.stdout:
341
+ console.print(f"[red]STDOUT: {e.stdout}[/red]")
342
+ if e.stderr:
343
+ console.print(f"[red]STDERR: {e.stderr}[/red]")
344
+ return None
345
+ except subprocess.TimeoutExpired:
346
+ console.print(f"[bold red]Command timed out:[/bold red] {cmd_str}")
347
+ return None
348
+
349
+ def run_neo4j_setup_wizard():
350
+ """Guides the user through setting up Neo4j database for CodeGraphContext."""
351
+ console.print("[bold cyan]Welcome to the Neo4j Setup Wizard![/bold cyan]")
352
+
353
+ questions = [
354
+ {
355
+ "type": "list",
356
+ "message": "Where do you want to setup your Neo4j database?",
357
+ "choices": [
358
+ "Local (Recommended: I'll help you run it on this machine)",
359
+ "Hosted (Connect to a remote database like AuraDB)",
360
+ "I already have an existing neo4j instance running.",
361
+ ],
362
+ "name": "db_location",
363
+ }
364
+ ]
365
+ result = prompt(questions)
366
+ db_location = result.get("db_location")
367
+
368
+ if db_location and "Hosted" in db_location:
369
+ setup_hosted_db()
370
+ elif db_location and "Local" in db_location:
371
+ setup_local_db()
372
+ elif db_location:
373
+ setup_existing_db()
374
+
375
+
376
+ def configure_mcp_client():
377
+ """
378
+ Configure MCP client (IDE/CLI) integration.
379
+ This function sets up the MCP server configuration for the user's IDE.
380
+ Includes all current configuration values in the env section.
381
+ """
382
+ console.print("[bold cyan]MCP Client Configuration[/bold cyan]\n")
383
+ console.print("This will configure CodeGraphContext integration with your IDE or CLI tool.")
384
+ console.print("CodeGraphContext works with FalkorDB by default (no database setup needed).\n")
385
+
386
+ # Load current configuration (includes project-local .env if present)
387
+ try:
388
+ from codegraphcontext.cli.config_manager import load_config
389
+ config = load_config()
390
+ except Exception as e:
391
+ console.print(f"[yellow]Warning: Could not load configuration: {e}[/yellow]")
392
+ config = {}
393
+
394
+ # Build env section with all configuration values
395
+ env_vars = {}
396
+
397
+ # Add database credentials if they exist
398
+ env_file = Path.home() / ".codegraphcontext" / ".env"
399
+ if env_file.exists():
400
+ try:
401
+ with open(env_file, "r") as f:
402
+ for line in f:
403
+ line = line.strip()
404
+ if line and not line.startswith("#") and "=" in line:
405
+ key, value = line.split("=", 1)
406
+ key = key.strip()
407
+ if key in ["NEO4J_URI", "NEO4J_USERNAME", "NEO4J_PASSWORD", "NEO4J_DATABASE"]:
408
+ env_vars[key] = value.strip()
409
+ except Exception:
410
+ pass
411
+
412
+ # Add all configuration values, converting relative paths to absolute
413
+ for key, value in config.items():
414
+ # Skip database credentials (already added above)
415
+ if key in ["NEO4J_URI", "NEO4J_USERNAME", "NEO4J_PASSWORD"]:
416
+ continue
417
+
418
+ # Convert relative paths to absolute for path-related configs
419
+ if "PATH" in key and value:
420
+ path_obj = Path(value)
421
+ if not path_obj.is_absolute():
422
+ value = str(path_obj.resolve())
423
+
424
+ env_vars[key] = value
425
+
426
+ # Generate MCP configuration
427
+ cgc_path = shutil.which("cgc") or sys.executable
428
+
429
+ if "python" in Path(cgc_path).name:
430
+ # fallback to running as module if no cgc binary is found
431
+ command = cgc_path
432
+ args = ["-m", "cgc", "mcp", "start"]
433
+ else:
434
+ command = cgc_path
435
+ args = ["mcp", "start"]
436
+
437
+ # Create MCP config with complete env section
438
+ mcp_config = {
439
+ "mcpServers": {
440
+ "CodeGraphContext": {
441
+ "command": command,
442
+ "args": args,
443
+ "env": env_vars,
444
+ "tools": {
445
+ "alwaysAllow": [
446
+ "add_code_to_graph", "add_package_to_graph",
447
+ "check_job_status", "list_jobs", "find_code",
448
+ "analyze_code_relationships", "watch_directory",
449
+ "find_dead_code", "execute_cypher_query",
450
+ "calculate_cyclomatic_complexity", "find_most_complex_functions",
451
+ "list_indexed_repositories", "delete_repository", "list_watched_paths",
452
+ "unwatch_directory", "visualize_graph_query"
453
+ ],
454
+ "disabled": False
455
+ },
456
+ "disabled": False,
457
+ "alwaysAllow": []
458
+ }
459
+ }
460
+ }
461
+
462
+ console.print("\n[bold green]Configuration generated![/bold green]")
463
+ console.print("Copy the following JSON and add it to your MCP server configuration file:")
464
+ console.print(json.dumps(mcp_config, indent=2))
465
+
466
+ # Save to file for convenience
467
+ mcp_file = Path.cwd() / "mcp.json"
468
+ with open(mcp_file, "w") as f:
469
+ json.dump(mcp_config, f, indent=2)
470
+ console.print(f"\n[cyan]Configuration saved to: {mcp_file}[/cyan]")
471
+
472
+ # Configure IDE automatically
473
+ _configure_ide(mcp_config)
474
+
475
+ console.print("\n[bold green]✅ MCP Client configuration complete![/bold green]")
476
+ console.print("[cyan]You can now run 'cgc mcp start' to launch the server.[/cyan]")
477
+ console.print("[yellow]💡 Tip: To update MCP config after changing settings, re-run 'cgc mcp setup'[/yellow]\n")
478
+
479
+
480
+ def find_latest_neo4j_creds_file():
481
+ """Finds the latest Neo4j credentials file in the Downloads folder."""
482
+ downloads_path = Path.home() / "Downloads"
483
+ if not downloads_path.exists():
484
+ return None
485
+
486
+ cred_files = list(downloads_path.glob("Neo4j*.txt"))
487
+ if not cred_files:
488
+ return None
489
+
490
+ latest_file = max(cred_files, key=lambda f: f.stat().st_mtime)
491
+ return latest_file
492
+
493
+
494
+ def setup_existing_db():
495
+ """Guides user to configure an existing Neo4j instance."""
496
+ console.print("\nTo connect to an existing Neo4j database, you'll need your connection credentials.")
497
+ console.print("If you don't have credentials for the database, you can create a new one using 'Local' installation in the previous menu.")
498
+
499
+ questions = [
500
+
501
+ {
502
+ "type": "list",
503
+ "message": "How would you like to add your Neo4j credentials?",
504
+ "choices": ["Add credentials from file", "Add credentials manually"],
505
+ "name": "cred_method",
506
+ }
507
+ ]
508
+ result = prompt(questions)
509
+ cred_method = result.get("cred_method")
510
+
511
+ creds = {}
512
+ if cred_method and "file" in cred_method:
513
+ latest_file = find_latest_neo4j_creds_file()
514
+ file_to_parse = None
515
+ if latest_file:
516
+ confirm_questions = [
517
+ {
518
+ "type": "confirm",
519
+ "message": f"Found a credentials file: {latest_file}. Use this file?",
520
+ "name": "use_latest",
521
+ "default": True,
522
+ }
523
+ ]
524
+ if prompt(confirm_questions).get("use_latest"):
525
+ file_to_parse = latest_file
526
+
527
+ if not file_to_parse:
528
+ path_questions = [
529
+ {"type": "input", "message": "Please enter the path to your credentials file:", "name": "cred_file_path"}
530
+ ]
531
+ file_path_str = prompt(path_questions).get("cred_file_path", "")
532
+ path = Path(file_path_str.strip())
533
+ if path.exists() and path.is_file():
534
+ file_to_parse = path
535
+ else:
536
+ console.print("[red]❌ The specified file path does not exist or is not a file.[/red]")
537
+ return
538
+
539
+ if file_to_parse:
540
+ try:
541
+ with open(file_to_parse, "r") as f:
542
+ for line in f:
543
+ if "=" in line:
544
+ key, value = line.strip().split("=", 1)
545
+ if key == "NEO4J_URI":
546
+ creds["uri"] = value
547
+ elif key == "NEO4J_USERNAME":
548
+ creds["username"] = value
549
+ elif key == "NEO4J_PASSWORD":
550
+ creds["password"] = value
551
+ except Exception as e:
552
+ console.print(f"[red]❌ Failed to parse credentials file: {e}[/red]")
553
+ return
554
+
555
+ elif cred_method: # Manual entry
556
+ console.print("Please enter your Neo4j connection details.")
557
+
558
+ # Loop until valid credentials are provided
559
+ while True:
560
+ questions = [
561
+ {"type": "input", "message": "URI (e.g., 'neo4j://localhost:7687'):", "name": "uri", "default": "neo4j://localhost:7687"},
562
+ {"type": "input", "message": "Username:", "name": "username", "default": "neo4j"},
563
+ {"type": "password", "message": "Password:", "name": "password"},
564
+ ]
565
+
566
+ manual_creds = prompt(questions)
567
+ if not manual_creds:
568
+ return # User cancelled
569
+
570
+ # Validate the user input
571
+ console.print("\n[cyan]🔍 Validating configuration...[/cyan]")
572
+ is_valid, validation_error = DatabaseManager.validate_config(
573
+ manual_creds.get("uri", ""),
574
+ manual_creds.get("username", ""),
575
+ manual_creds.get("password", "")
576
+ )
577
+
578
+ if not is_valid:
579
+ console.print(validation_error)
580
+ console.print("\n[red]❌ Invalid configuration. Please try again.[/red]\n")
581
+ continue # Ask for input again
582
+
583
+ console.print("[green]✅ Configuration format is valid[/green]")
584
+
585
+ # Test the connection
586
+ console.print("\n[cyan]🔗 Testing connection...[/cyan]")
587
+ is_connected, error_msg = DatabaseManager.test_connection(
588
+ manual_creds.get("uri", ""),
589
+ manual_creds.get("username", ""),
590
+ manual_creds.get("password", "")
591
+ )
592
+
593
+ if not is_connected:
594
+ console.print(error_msg)
595
+ retry = prompt([{"type": "confirm", "message": "Connection failed. Try again with different credentials?", "name": "retry", "default": True}])
596
+ if not retry.get("retry"):
597
+ return
598
+ continue # Ask for input again
599
+
600
+ console.print("[green]✅ Connection successful![/green]")
601
+ creds = manual_creds
602
+ break # Exit loop with valid credentials
603
+
604
+
605
+ if creds.get("uri") and creds.get("password"):
606
+ _save_neo4j_credentials(creds)
607
+ else:
608
+ console.print("[red]❌ Incomplete credentials. Please try again.[/red]")
609
+
610
+
611
+ def setup_hosted_db():
612
+ """Guides user to configure a remote Neo4j instance."""
613
+ console.print("\nTo connect to a hosted Neo4j database, you'll need your connection credentials.")
614
+ console.print("[yellow]Warning: You are configuring to connect to a remote/hosted Neo4j database. Ensure your credentials are secure.[/yellow]")
615
+ console.print("If you don't have a hosted database, you can create a free one at [bold blue]https://neo4j.com/product/auradb/[/bold blue] (click 'Start free').")
616
+
617
+ questions = [
618
+
619
+ {
620
+ "type": "list",
621
+ "message": "How would you like to add your Neo4j credentials?",
622
+ "choices": ["Add credentials from file", "Add credentials manually"],
623
+ "name": "cred_method",
624
+ }
625
+ ]
626
+ result = prompt(questions)
627
+ cred_method = result.get("cred_method")
628
+
629
+ creds = {}
630
+ if cred_method and "file" in cred_method:
631
+ latest_file = find_latest_neo4j_creds_file()
632
+ file_to_parse = None
633
+ if latest_file:
634
+ confirm_questions = [
635
+ {
636
+ "type": "confirm",
637
+ "message": f"Found a credentials file: {latest_file}. Use this file?",
638
+ "name": "use_latest",
639
+ "default": True,
640
+ }
641
+ ]
642
+ if prompt(confirm_questions).get("use_latest"):
643
+ file_to_parse = latest_file
644
+
645
+ if not file_to_parse:
646
+ path_questions = [
647
+ {"type": "input", "message": "Please enter the path to your credentials file:", "name": "cred_file_path"}
648
+ ]
649
+ file_path_str = prompt(path_questions).get("cred_file_path", "")
650
+ path = Path(file_path_str.strip())
651
+ if path.exists() and path.is_file():
652
+ file_to_parse = path
653
+ else:
654
+ console.print("[red]❌ The specified file path does not exist or is not a file.[/red]")
655
+ return
656
+
657
+ if file_to_parse:
658
+ try:
659
+ with open(file_to_parse, "r") as f:
660
+ for line in f:
661
+ if "=" in line:
662
+ key, value = line.strip().split("=", 1)
663
+ if key == "NEO4J_URI":
664
+ creds["uri"] = value
665
+ elif key == "NEO4J_USERNAME":
666
+ creds["username"] = value
667
+ elif key == "NEO4J_PASSWORD":
668
+ creds["password"] = value
669
+ except Exception as e:
670
+ console.print(f"[red]❌ Failed to parse credentials file: {e}[/red]")
671
+ return
672
+
673
+ elif cred_method: # Manual entry
674
+ console.print("Please enter your remote Neo4j connection details.")
675
+
676
+ # Loop until valid credentials are provided
677
+ while True:
678
+ questions = [
679
+ {"type": "input", "message": "URI (e.g., neo4j+s://xxxx.databases.neo4j.io):", "name": "uri"},
680
+ {"type": "input", "message": "Username:", "name": "username", "default": "neo4j"},
681
+ {"type": "password", "message": "Password:", "name": "password"},
682
+ ]
683
+
684
+ manual_creds = prompt(questions)
685
+ if not manual_creds:
686
+ return # User cancelled
687
+
688
+ # Validate the user input
689
+ console.print("\n[cyan]🔍 Validating configuration...[/cyan]")
690
+ is_valid, validation_error = DatabaseManager.validate_config(
691
+ manual_creds.get("uri", ""),
692
+ manual_creds.get("username", ""),
693
+ manual_creds.get("password", "")
694
+ )
695
+
696
+ if not is_valid:
697
+ console.print(validation_error)
698
+ console.print("\n[red]❌ Invalid configuration. Please try again.[/red]\n")
699
+ continue # Ask for input again
700
+
701
+ console.print("[green]✅ Configuration format is valid[/green]")
702
+
703
+ # Test the connection
704
+ console.print("\n[cyan]🔗 Testing connection...[/cyan]")
705
+ is_connected, error_msg = DatabaseManager.test_connection(
706
+ manual_creds.get("uri", ""),
707
+ manual_creds.get("username", ""),
708
+ manual_creds.get("password", "")
709
+ )
710
+
711
+ if not is_connected:
712
+ console.print(error_msg)
713
+ retry = prompt([{"type": "confirm", "message": "Connection failed. Try again with different credentials?", "name": "retry", "default": True}])
714
+ if not retry.get("retry"):
715
+ return
716
+ continue # Ask for input again
717
+
718
+ console.print("[green]✅ Connection successful![/green]")
719
+ creds = manual_creds
720
+ break
721
+
722
+
723
+ if creds.get("uri") and creds.get("password"):
724
+ _save_neo4j_credentials(creds)
725
+ else:
726
+ console.print("[red]❌ Incomplete credentials. Please try again.[/red]")
727
+
728
+ def setup_local_db():
729
+ """Guides user to set up a local Neo4j instance."""
730
+ questions = [
731
+ {
732
+ "type": "list",
733
+ "message": "How would you like to run Neo4j locally?",
734
+ "choices": ["Docker (Easiest)", "Local Binary (Advanced)"],
735
+ "name": "local_method",
736
+ }
737
+ ]
738
+ result = prompt(questions)
739
+ local_method = result.get("local_method")
740
+
741
+ if local_method and "Docker" in local_method:
742
+ setup_docker()
743
+ elif local_method:
744
+ if platform.system() == "Darwin":
745
+ # lazy import to avoid circular import
746
+ from .setup_macos import setup_macos_binary
747
+ setup_macos_binary(console, prompt, run_command, _save_neo4j_credentials)
748
+ else:
749
+ setup_local_binary()
750
+
751
+ def setup_docker():
752
+ """Creates Docker files and runs docker-compose for Neo4j."""
753
+ console.print("\n[bold cyan]Setting up Neo4j with Docker...[/bold cyan]")
754
+
755
+ # Prompt for password first
756
+ console.print("Please set a secure password for your Neo4j database:")
757
+ password_questions = [
758
+ {"type": "password", "message": "Enter Neo4j password:", "name": "password"},
759
+ {"type": "password", "message": "Confirm password:", "name": "password_confirm"},
760
+ ]
761
+
762
+ while True:
763
+ passwords = prompt(password_questions)
764
+ if not passwords:
765
+ return # User cancelled
766
+
767
+ password = passwords.get("password", "")
768
+ if password and password == passwords.get("password_confirm"):
769
+ break
770
+ console.print("[red]Passwords do not match or are empty. Please try again.[/red]")
771
+
772
+ # Create data directories
773
+ neo4j_dir = Path.cwd() / "neo4j_data"
774
+ for subdir in ["data", "logs", "conf", "plugins"]:
775
+ (neo4j_dir / subdir).mkdir(parents=True, exist_ok=True)
776
+
777
+ # Fixed docker-compose.yml content
778
+ docker_compose_content = f"""
779
+ services:
780
+ neo4j:
781
+ image: neo4j:5.21
782
+ container_name: neo4j-cgc
783
+ restart: unless-stopped
784
+ ports:
785
+ - "7474:7474"
786
+ - "7687:7687"
787
+ environment:
788
+ - NEO4J_AUTH=neo4j/{password}
789
+ - NEO4J_ACCEPT_LICENSE_AGREEMENT=yes
790
+ volumes:
791
+ - neo4j_data:/data
792
+ - neo4j_logs:/logs
793
+
794
+ volumes:
795
+ neo4j_data:
796
+ neo4j_logs:
797
+ """
798
+
799
+ # Write docker-compose.yml
800
+ compose_file = Path.cwd() / "docker-compose.yml"
801
+ with open(compose_file, "w") as f:
802
+ f.write(docker_compose_content)
803
+
804
+ console.print("[green]✅ docker-compose.yml created with secure password.[/green]")
805
+
806
+ # Validate configuration format before attempting Docker operations
807
+ console.print("\n[cyan]🔍 Validating configuration...[/cyan]")
808
+ is_valid, validation_error = DatabaseManager.validate_config(
809
+ DEFAULT_NEO4J_URI,
810
+ DEFAULT_NEO4J_USERNAME,
811
+ password
812
+ )
813
+
814
+ if not is_valid:
815
+ console.print(validation_error)
816
+ console.print("\n[red]❌ Configuration validation failed. Please fix the issues and try again.[/red]")
817
+ return
818
+
819
+ console.print("[green]✅ Configuration format is valid[/green]")
820
+
821
+ # Check if Docker is running
822
+ docker_check = run_command(["docker", "--version"], console, check=False)
823
+ if not docker_check:
824
+ console.print("[red]❌ Docker is not installed or not running. Please install Docker first.[/red]")
825
+ return
826
+
827
+ # Check if docker-compose is available
828
+ compose_check = run_command(["docker", "compose", "version"], console, check=False)
829
+ if not compose_check:
830
+ console.print("[red]❌ Docker Compose is not available. Please install Docker Compose.[/red]")
831
+ return
832
+
833
+ confirm_q = [{"type": "confirm", "message": "Ready to launch Neo4j in Docker?", "name": "proceed", "default": True}]
834
+ if not prompt(confirm_q).get("proceed"):
835
+ return
836
+
837
+ try:
838
+ # Pull the image first
839
+ console.print("[cyan]Pulling Neo4j Docker image...[/cyan]")
840
+ pull_process = run_command(["docker", "pull", "neo4j:5.21"], console, check=True)
841
+ if not pull_process:
842
+ console.print("[yellow]⚠️ Could not pull image, but continuing anyway...[/yellow]")
843
+
844
+ # Start containers
845
+ console.print("[cyan]Starting Neo4j container...[/cyan]")
846
+ docker_process = run_command(["docker", "compose", "up", "-d"], console, check=True)
847
+
848
+ if docker_process:
849
+ console.print("[bold green]🚀 Neo4j Docker container started successfully![/bold green]")
850
+
851
+ # Wait for Neo4j to be ready
852
+ console.print("[cyan]Waiting for Neo4j to be ready (this may take 30-60 seconds)...[/cyan]")
853
+
854
+ # Try to connect for up to 2 minutes
855
+ max_attempts = 24 # 24 * 5 seconds = 2 minutes
856
+ for attempt in range(max_attempts):
857
+ time.sleep(5)
858
+
859
+ # Check if container is still running
860
+ status_check = run_command(["docker", "compose", "ps", "-q", "neo4j"], console, check=False)
861
+ if not status_check or not status_check.stdout.strip():
862
+ console.print("[red]❌ Neo4j container stopped unexpectedly. Check logs with: docker compose logs neo4j[/red]")
863
+ return
864
+
865
+ # updated test_connection method
866
+ console.print(f"[yellow]Testing connection... (attempt {attempt + 1}/{max_attempts})[/yellow]")
867
+ is_connected, error_msg = DatabaseManager.test_connection(DEFAULT_NEO4J_URI, DEFAULT_NEO4J_USERNAME, password)
868
+
869
+ if is_connected:
870
+ console.print("[bold green]✅ Neo4j is ready and accepting connections![/bold green]")
871
+ connection_successful = True
872
+ break
873
+
874
+ else:
875
+ # Only show detailed error on last attempt
876
+ if attempt == max_attempts - 1:
877
+ console.print("\n[red]❌ Neo4j did not become ready within 2 minutes.[/red]")
878
+ console.print(error_msg)
879
+ console.print("\n[cyan]Troubleshooting:[/cyan]")
880
+ console.print(" • Check logs: docker compose logs neo4j")
881
+ console.print(" • Verify container is running: docker ps")
882
+ console.print(" • Try restarting: docker compose restart")
883
+ return
884
+
885
+ if not connection_successful:
886
+ return
887
+
888
+ # Generate MCP configuration
889
+ creds = {
890
+ "uri": DEFAULT_NEO4J_URI,
891
+ "username": DEFAULT_NEO4J_USERNAME,
892
+ "password": password
893
+ }
894
+
895
+ _save_neo4j_credentials(creds)
896
+
897
+ console.print("\n[bold green]🎉 Setup complete![/bold green]")
898
+ console.print("Neo4j is running at:")
899
+ console.print(" • Web interface: http://localhost:7474")
900
+ console.print(" • Bolt connection: neo4j://localhost:7687")
901
+ console.print("\n[cyan]Useful commands:[/cyan]")
902
+ console.print(" • Stop: docker compose down")
903
+ console.print(" • Restart: docker compose restart")
904
+ console.print(" • View logs: docker compose logs neo4j")
905
+
906
+ except Exception as e:
907
+ console.print(f"[bold red]❌ Failed to start Neo4j Docker container:[/bold red] {e}")
908
+ console.print("[cyan]Try checking the logs with: docker compose logs neo4j[/cyan]")
909
+
910
+ def setup_local_binary():
911
+ """Automates the installation and configuration of Neo4j on Ubuntu/Debian."""
912
+ os_name = platform.system()
913
+ console.print(f"Detected Operating System: [bold yellow]{os_name}[/bold yellow]")
914
+
915
+ if os_name != "Linux" or not os.path.exists("/etc/debian_version"):
916
+ console.print("[yellow]Automated installer is designed for Debian-based systems (like Ubuntu).[/yellow]")
917
+ console.print(f"For other systems, please follow the manual installation guide: [bold blue]https://neo4j.com/docs/operations-manual/current/installation/[/bold blue]")
918
+ return
919
+
920
+ console.print("[bold]Starting automated Neo4j installation for Ubuntu/Debian.[/bold]")
921
+ console.print("[yellow]This will run several commands with 'sudo'. You will be prompted for your password.[/yellow]")
922
+ confirm_q = [{"type": "confirm", "message": "Do you want to proceed?", "name": "proceed", "default": True}]
923
+ if not prompt(confirm_q).get("proceed"):
924
+ return
925
+
926
+ # Install latest Neo4j version instead of pinning to a specific version
927
+ # This prevents version conflicts and ensures users get the latest stable release
928
+ install_commands = [
929
+ ("Creating keyring directory", ["sudo", "mkdir", "-p", "/etc/apt/keyrings"]),
930
+ ("Adding Neo4j GPG key", "wget -qO- https://debian.neo4j.com/neotechnology.gpg.key | sudo gpg --dearmor --yes -o /etc/apt/keyrings/neotechnology.gpg", True),
931
+ ("Adding Neo4j repository", "echo 'deb [signed-by=/etc/apt/keyrings/neotechnology.gpg] https://debian.neo4j.com stable 5' | sudo tee /etc/apt/sources.list.d/neo4j.list > /dev/null", True),
932
+ ("Updating apt sources", ["sudo", "apt-get", "-qq", "update"]),
933
+ ("Installing latest Neo4j and Cypher Shell", ["sudo", "apt-get", "install", "-qq", "-y", "neo4j", "cypher-shell"])
934
+ ]
935
+
936
+ for desc, cmd, use_shell in [(c[0], c[1], c[2] if len(c) > 2 else False) for c in install_commands]:
937
+ console.print(f"\n[bold]Step: {desc}...[/bold]")
938
+ if not run_command(cmd, console, shell=use_shell):
939
+ console.print(f"[bold red]Failed on step: {desc}. Aborting installation.[/bold red]")
940
+ return
941
+
942
+ console.print("\n[bold green]Neo4j installed successfully![/bold green]")
943
+
944
+ console.print("\n[bold]Please set the initial password for the 'neo4j' user.""")
945
+
946
+ new_password = ""
947
+ while True:
948
+ questions = [
949
+ {"type": "password", "message": "Enter a new password for Neo4j:", "name": "password"},
950
+ {"type": "password", "message": "Confirm the new password:", "name": "password_confirm"},
951
+ ]
952
+ passwords = prompt(questions)
953
+ if not passwords: return # User cancelled
954
+ new_password = passwords.get("password")
955
+ if new_password and new_password == passwords.get("password_confirm"):
956
+ break
957
+ console.print("[red]Passwords do not match or are empty. Please try again.[/red]")
958
+
959
+ console.print("\n[bold]Stopping Neo4j to set the password...""")
960
+ if not run_command(["sudo", "systemctl", "stop", "neo4j"], console):
961
+ console.print("[bold red]Could not stop Neo4j service. Aborting.[/bold red]")
962
+ return
963
+
964
+ console.print("\n[bold]Setting initial password using neo4j-admin...""")
965
+ pw_command = ["sudo", "-u", "neo4j", "neo4j-admin", "dbms", "set-initial-password", new_password]
966
+ if not run_command(pw_command, console, check=True):
967
+ console.print("[bold red]Failed to set the initial password. Please check the logs.[/bold red]")
968
+ run_command(["sudo", "systemctl", "start", "neo4j"], console)
969
+ return
970
+
971
+ console.print("\n[bold]Starting Neo4j service...""")
972
+ if not run_command(["sudo", "systemctl", "start", "neo4j"], console):
973
+ console.print("[bold red]Failed to start Neo4j service after setting password.[/bold red]")
974
+ return
975
+
976
+ console.print("\n[bold]Enabling Neo4j service to start on boot...""")
977
+ if not run_command(["sudo", "systemctl", "enable", "neo4j"], console):
978
+ console.print("[bold yellow]Could not enable Neo4j service. You may need to start it manually after reboot.[/bold yellow]")
979
+
980
+ console.print("[bold green]Password set and service started.[/bold green]")
981
+
982
+ console.print("\n[yellow]Waiting 10 seconds for the database to become available...""")
983
+ time.sleep(10)
984
+
985
+ creds = {
986
+ "uri": "neo4j://localhost:7687",
987
+ "username": "neo4j",
988
+ "password": new_password
989
+ }
990
+ _save_neo4j_credentials(creds)
991
+ console.print("\n[bold green]All done! Your local Neo4j instance is ready to use.[/bold green]")