Spaces:
Running
Running
File size: 22,494 Bytes
42f5b98 |
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 |
"""Unified CLI for CodeRAG."""
import json
import os
import platform
import shutil
import sys
from pathlib import Path
from typing import Optional
import click
# Config directory and file
CONFIG_DIR = Path.home() / ".config" / "coderag"
CONFIG_FILE = CONFIG_DIR / "config.json"
def get_config() -> dict:
"""Load configuration from config file."""
if CONFIG_FILE.exists():
try:
return json.loads(CONFIG_FILE.read_text())
except Exception:
return {}
return {}
def save_config(config: dict) -> None:
"""Save configuration to config file."""
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
CONFIG_FILE.write_text(json.dumps(config, indent=2))
def get_claude_config_path() -> Optional[Path]:
"""Get Claude Desktop config path based on OS."""
system = platform.system()
if system == "Darwin": # macOS
return Path.home() / "Library" / "Application Support" / "Claude" / "claude_desktop_config.json"
elif system == "Linux":
return Path.home() / ".config" / "Claude" / "claude_desktop_config.json"
elif system == "Windows":
appdata = os.environ.get("APPDATA", "")
if appdata:
return Path(appdata) / "Claude" / "claude_desktop_config.json"
return None
@click.group()
@click.version_option(package_name="coderag")
def cli():
"""CodeRAG - RAG-based Q&A system for code repositories.
Use 'coderag setup' to configure, then 'coderag serve' to start.
For Claude Desktop integration, run 'coderag mcp-install'.
"""
pass
@cli.command()
@click.option("--provider", type=click.Choice(["groq", "openai", "anthropic", "openrouter", "together", "local"]),
default=None, help="LLM provider to use")
@click.option("--api-key", default=None, help="API key for the provider")
def setup(provider: Optional[str], api_key: Optional[str]):
"""Interactive setup wizard for CodeRAG.
Configures the LLM provider and API key. Configuration is saved to
~/.config/coderag/config.json and can be overridden by environment variables.
"""
config = get_config()
click.echo("\nπ§ CodeRAG Setup\n")
# Provider selection
if provider is None:
click.echo("Select your LLM provider:")
click.echo(" 1. groq (FREE, fast - recommended)")
click.echo(" 2. openai")
click.echo(" 3. anthropic")
click.echo(" 4. openrouter")
click.echo(" 5. together")
click.echo(" 6. local (requires GPU)")
choice = click.prompt("Enter choice", type=int, default=1)
providers = {1: "groq", 2: "openai", 3: "anthropic", 4: "openrouter", 5: "together", 6: "local"}
provider = providers.get(choice, "groq")
config["llm_provider"] = provider
# API key (not needed for local)
if provider != "local":
if api_key is None:
api_key_urls = {
"groq": "https://console.groq.com/keys",
"openai": "https://platform.openai.com/api-keys",
"anthropic": "https://console.anthropic.com/settings/keys",
"openrouter": "https://openrouter.ai/keys",
"together": "https://api.together.xyz/settings/api-keys",
}
url = api_key_urls.get(provider, "")
if url:
click.echo(f"\nGet your API key from: {url}")
api_key = click.prompt("Enter your API key", hide_input=True)
config["llm_api_key"] = api_key
# Validate API key
click.echo("\nβ³ Validating API key...")
if _validate_api_key(provider, api_key):
click.echo("β
API key is valid!")
else:
click.echo("β οΈ Could not validate API key. It may still work.")
else:
click.echo("\nβ οΈ Local mode requires a CUDA-capable GPU.")
# Save config
save_config(config)
click.echo(f"\nβ
Configuration saved to {CONFIG_FILE}")
# Next steps
click.echo("\nπ Next steps:")
click.echo(" 1. Run 'coderag serve' to start the web interface")
click.echo(" 2. Run 'coderag mcp-install' to integrate with Claude Desktop")
click.echo(" 3. Run 'coderag index <url>' to index a repository")
def _validate_api_key(provider: str, api_key: str) -> bool:
"""Validate API key by making a test request."""
try:
from openai import OpenAI
base_urls = {
"groq": "https://api.groq.com/openai/v1",
"openai": "https://api.openai.com/v1",
"openrouter": "https://openrouter.ai/api/v1",
"together": "https://api.together.xyz/v1",
}
if provider not in base_urls:
return True # Can't validate, assume OK
client = OpenAI(api_key=api_key, base_url=base_urls[provider])
client.models.list()
return True
except Exception:
return False
@cli.command()
@click.option("--host", default="0.0.0.0", help="Host to bind to")
@click.option("--port", default=8000, type=int, help="Port to bind to")
@click.option("--reload", is_flag=True, help="Enable auto-reload for development")
def serve(host: str, port: int, reload: bool):
"""Start the CodeRAG web server.
Starts the FastAPI server with Gradio UI, REST API, and MCP endpoint.
"""
# Apply config from file to environment
_apply_config_to_env()
import uvicorn
from coderag.main import create_app
from coderag.config import get_settings
settings = get_settings()
app = create_app()
click.echo(f"\nπ Starting CodeRAG server at http://{host}:{port}")
click.echo(" Press Ctrl+C to stop\n")
uvicorn.run(
app,
host=host,
port=port,
reload=reload,
log_level=settings.server.log_level,
)
@cli.command("mcp-run")
def mcp_run():
"""Run MCP server in stdio mode (for Claude Desktop).
This command is used by Claude Desktop to communicate with CodeRAG.
You typically don't need to run this manually.
"""
# Apply config from file to environment
_apply_config_to_env()
# Suppress all output except MCP protocol
import logging
logging.basicConfig(level=logging.WARNING, stream=sys.stderr)
import structlog
structlog.configure(
wrapper_class=structlog.make_filtering_bound_logger(logging.CRITICAL),
)
from coderag.mcp.server import create_mcp_server
mcp = create_mcp_server()
mcp.run(transport="stdio")
@cli.command("mcp-install")
@click.option("--dry-run", is_flag=True, help="Preview changes without applying")
def mcp_install(dry_run: bool):
"""Configure Claude Desktop to use CodeRAG MCP.
Automatically detects your OS and updates the Claude Desktop configuration
to include the CodeRAG MCP server.
"""
config_path = get_claude_config_path()
if config_path is None:
click.echo("β Could not determine Claude Desktop config location.")
click.echo(" Please manually add the MCP configuration.")
sys.exit(1)
click.echo(f"\nπ Claude Desktop config: {config_path}")
# Check if Claude Desktop is installed
if not config_path.parent.exists():
click.echo("\nβ Claude Desktop does not appear to be installed.")
click.echo(" Install it from: https://claude.ai/download")
sys.exit(1)
# Load existing config or create new
if config_path.exists():
try:
config = json.loads(config_path.read_text())
except json.JSONDecodeError:
click.echo("β οΈ Existing config is invalid JSON. Creating new config.")
config = {}
else:
config = {}
# Ensure mcpServers key exists
if "mcpServers" not in config:
config["mcpServers"] = {}
# Find the coderag-mcp command path
coderag_path = shutil.which("coderag")
if coderag_path is None:
# Fallback to python -m
python_path = sys.executable
mcp_command = [python_path, "-m", "coderag.mcp.cli"]
else:
mcp_command = [coderag_path, "mcp-run"]
# Prepare MCP server config
new_mcp_config = {
"command": mcp_command[0],
"args": mcp_command[1:] if len(mcp_command) > 1 else [],
}
# Check if already configured
existing = config["mcpServers"].get("coderag")
if existing == new_mcp_config:
click.echo("\nβ
CodeRAG MCP is already configured correctly!")
return
# Show diff
click.echo("\nπ Changes to be made:")
if existing:
click.echo(f" Update: mcpServers.coderag")
click.echo(f" From: {json.dumps(existing)}")
click.echo(f" To: {json.dumps(new_mcp_config)}")
else:
click.echo(f" Add: mcpServers.coderag = {json.dumps(new_mcp_config)}")
if dry_run:
click.echo("\nπ Dry run - no changes made.")
return
# Backup existing config
if config_path.exists():
backup_path = config_path.with_suffix(".json.backup")
shutil.copy(config_path, backup_path)
click.echo(f"\nπ¦ Backup saved to: {backup_path}")
# Apply changes
config["mcpServers"]["coderag"] = new_mcp_config
config_path.parent.mkdir(parents=True, exist_ok=True)
config_path.write_text(json.dumps(config, indent=2))
click.echo("\nβ
Claude Desktop configuration updated!")
click.echo("\nβ οΈ Please restart Claude Desktop to apply changes.")
@cli.command("index")
@click.argument("url")
@click.option("--branch", default="", help="Branch to index (default: main/master)")
def index(url: str, branch: str):
"""Index a GitHub repository.
URL: The GitHub repository URL to index.
Example: coderag index https://github.com/owner/repo
"""
# Apply config from file to environment
_apply_config_to_env()
import asyncio
from coderag.mcp.handlers import get_mcp_handlers
click.echo(f"\nπ¦ Indexing repository: {url}")
if branch:
click.echo(f" Branch: {branch}")
handlers = get_mcp_handlers()
async def run_index():
result = await handlers.index_repository(url=url, branch=branch)
return result
result = asyncio.run(run_index())
if result.get("success"):
click.echo(f"\nβ
Repository indexed successfully!")
click.echo(f" Repo ID: {result['repo_id']}")
click.echo(f" Name: {result['name']}")
click.echo(f" Files processed: {result['files_processed']}")
click.echo(f" Chunks indexed: {result['chunks_indexed']}")
click.echo(f"\n Use 'coderag query {result['repo_id'][:8]} \"your question\"' to query")
else:
click.echo(f"\nβ Indexing failed: {result.get('error', 'Unknown error')}")
sys.exit(1)
@cli.command("query")
@click.argument("repo_id")
@click.argument("question")
@click.option("--top-k", default=5, type=int, help="Number of chunks to retrieve")
@click.option("--format", "output_format", type=click.Choice(["text", "json"]), default="text", help="Output format")
def query(repo_id: str, question: str, top_k: int, output_format: str):
"""Ask a question about an indexed repository.
REPO_ID: Repository ID (full or first 8 characters)
QUESTION: Your question about the code
Example: coderag query abc12345 "How does authentication work?"
"""
# Apply config from file to environment
_apply_config_to_env()
import asyncio
from coderag.mcp.handlers import get_mcp_handlers
handlers = get_mcp_handlers()
async def run_query():
result = await handlers.query_code(repo_id=repo_id, question=question, top_k=top_k)
return result
click.echo(f"\nπ Querying: {question}\n")
result = asyncio.run(run_query())
if result.get("error"):
click.echo(f"β Error: {result['error']}")
sys.exit(1)
if output_format == "json":
click.echo(json.dumps(result, indent=2))
else:
click.echo("π Answer:\n")
click.echo(result.get("answer", "No answer generated."))
if result.get("citations"):
click.echo("\nπ Citations:")
for citation in result["citations"]:
click.echo(f" {citation}")
if result.get("evidence"):
click.echo("\nπ Evidence:")
for chunk in result["evidence"][:3]: # Show top 3
click.echo(f" - {chunk['file']}:{chunk['start_line']}-{chunk['end_line']} (relevance: {chunk['relevance']})")
@cli.command("repos")
@click.option("--format", "output_format", type=click.Choice(["text", "json"]), default="text", help="Output format")
def repos(output_format: str):
"""List all indexed repositories."""
# Apply config from file to environment
_apply_config_to_env()
import asyncio
from coderag.mcp.handlers import get_mcp_handlers
handlers = get_mcp_handlers()
async def run_list():
result = await handlers.list_repositories()
return result
result = asyncio.run(run_list())
if output_format == "json":
click.echo(json.dumps(result, indent=2))
else:
repos_list = result.get("repositories", [])
if not repos_list:
click.echo("\nπ No repositories indexed yet.")
click.echo(" Run 'coderag index <url>' to index a repository.")
return
click.echo(f"\nπ Indexed Repositories ({len(repos_list)}):\n")
for repo in repos_list:
status_icon = "β
" if repo["status"] == "ready" else "β³" if repo["status"] == "indexing" else "β"
click.echo(f" {status_icon} {repo['id'][:8]} {repo['name']} ({repo['branch']})")
click.echo(f" Chunks: {repo['chunk_count']} | Indexed: {repo.get('indexed_at', 'N/A')}")
@cli.command("update")
@click.argument("repo_id")
def update(repo_id: str):
"""Update an indexed repository with latest changes.
REPO_ID: Repository ID (full or first 8 characters)
Fetches the latest changes from GitHub and re-indexes only the modified files.
This is faster than a full re-index for repositories with frequent updates.
Example: coderag update abc12345
"""
# Apply config from file to environment
_apply_config_to_env()
import asyncio
from coderag.mcp.handlers import get_mcp_handlers
click.echo(f"\nπ Updating repository: {repo_id}\n")
handlers = get_mcp_handlers()
async def run_update():
result = await handlers.update_repository(repo_id=repo_id)
return result
result = asyncio.run(run_update())
if result.get("error"):
click.echo(f"β Error: {result['error']}")
sys.exit(1)
if result.get("message") == "Repository is already up to date":
click.echo("β
Repository is already up to date!")
else:
click.echo("β
Repository updated successfully!")
click.echo(f" Files changed: {result.get('files_changed', 0)}")
click.echo(f" - Added: {result.get('files_added', 0)}")
click.echo(f" - Modified: {result.get('files_modified', 0)}")
click.echo(f" - Deleted: {result.get('files_deleted', 0)}")
click.echo(f" Chunks added: {result.get('chunks_added', 0)}")
click.echo(f" Chunks deleted: {result.get('chunks_deleted', 0)}")
click.echo(f" Total chunks: {result.get('total_chunks', 0)}")
@cli.command("delete")
@click.argument("repo_id")
@click.option("--force", "-f", is_flag=True, help="Skip confirmation prompt")
def delete(repo_id: str, force: bool):
"""Delete an indexed repository.
REPO_ID: Repository ID (full or first 8 characters)
Removes the repository from the index and deletes all associated chunks
from the vector store.
Example: coderag delete abc12345
"""
# Apply config from file to environment
_apply_config_to_env()
import asyncio
from coderag.mcp.handlers import get_mcp_handlers
handlers = get_mcp_handlers()
# First get repo info for confirmation
async def get_repo_info():
result = await handlers.get_repository_info(repo_id=repo_id)
return result
info = asyncio.run(get_repo_info())
if info.get("error"):
click.echo(f"β Error: {info['error']}")
sys.exit(1)
repo_name = info.get("name", repo_id)
chunk_count = info.get("chunk_count", 0)
if not force:
click.echo(f"\nβ οΈ About to delete: {repo_name}")
click.echo(f" Chunks to delete: {chunk_count}")
if not click.confirm("\nAre you sure?"):
click.echo("Cancelled.")
return
async def run_delete():
result = await handlers.delete_repository(repo_id=repo_id)
return result
result = asyncio.run(run_delete())
if result.get("error"):
click.echo(f"β Error: {result['error']}")
sys.exit(1)
click.echo(f"\nβ
Repository deleted: {result.get('name', repo_id)}")
click.echo(f" Chunks removed: {result.get('chunks_deleted', 0)}")
@cli.command("clean")
@click.option("--force", "-f", is_flag=True, help="Skip confirmation prompt")
def clean(force: bool):
"""Clean up repositories with errors or stuck in indexing.
Removes all repositories that have status 'error' or have been stuck
in 'indexing' or 'pending' status for too long.
Example: coderag clean
"""
# Apply config from file to environment
_apply_config_to_env()
import asyncio
from coderag.mcp.handlers import get_mcp_handlers
handlers = get_mcp_handlers()
async def get_repos():
result = await handlers.list_repositories()
return result
result = asyncio.run(get_repos())
repos = result.get("repositories", [])
# Find repos to clean
to_clean = [r for r in repos if r["status"] in ("error", "indexing", "pending")]
if not to_clean:
click.echo("\nβ
No repositories need cleaning.")
return
click.echo(f"\nπ§Ή Found {len(to_clean)} repository(ies) to clean:\n")
for repo in to_clean:
status_icon = "β" if repo["status"] == "error" else "β³"
click.echo(f" {status_icon} {repo['id'][:8]} {repo['name']} ({repo['status']})")
if not force:
if not click.confirm(f"\nDelete these {len(to_clean)} repositories?"):
click.echo("Cancelled.")
return
# Delete each repo
deleted = 0
for repo in to_clean:
async def run_delete():
return await handlers.delete_repository(repo_id=repo["id"])
try:
result = asyncio.run(run_delete())
if result.get("success"):
deleted += 1
click.echo(f" β
Deleted: {repo['name']}")
else:
click.echo(f" β Failed: {repo['name']} - {result.get('error', 'Unknown')}")
except Exception as e:
click.echo(f" β Failed: {repo['name']} - {str(e)}")
click.echo(f"\nβ
Cleaned {deleted}/{len(to_clean)} repositories.")
@cli.command("doctor")
def doctor():
"""Diagnose common issues with CodeRAG setup.
Checks Python version, configuration, API key validity, and system components.
"""
click.echo("\nπ₯ CodeRAG Doctor\n")
all_ok = True
# Check Python version
py_version = sys.version_info
if py_version >= (3, 11):
click.echo(f"β
Python version: {py_version.major}.{py_version.minor}.{py_version.micro}")
else:
click.echo(f"β Python version: {py_version.major}.{py_version.minor}.{py_version.micro} (need 3.11+)")
all_ok = False
# Check config file
config = get_config()
if config:
click.echo(f"β
Config file exists: {CONFIG_FILE}")
if config.get("llm_provider"):
click.echo(f" Provider: {config['llm_provider']}")
else:
click.echo(f"β οΈ No config file. Run 'coderag setup' to configure.")
# Check API key
api_key = config.get("llm_api_key") or os.environ.get("MODEL_LLM_API_KEY")
provider = config.get("llm_provider") or os.environ.get("MODEL_LLM_PROVIDER", "groq")
if provider != "local":
if api_key:
click.echo(f"β
API key configured (provider: {provider})")
else:
click.echo(f"β No API key configured for {provider}")
all_ok = False
# Check CUDA
try:
import torch
if torch.cuda.is_available():
click.echo(f"β
CUDA available: {torch.cuda.get_device_name(0)}")
else:
click.echo("βΉοΈ CUDA not available (CPU mode for embeddings)")
except ImportError:
click.echo("β οΈ PyTorch not installed")
all_ok = False
# Check ChromaDB data directory
from coderag.config import get_settings
settings = get_settings()
chroma_path = settings.vectorstore.persist_directory
if chroma_path.exists():
click.echo(f"β
ChromaDB directory: {chroma_path}")
else:
click.echo(f"βΉοΈ ChromaDB directory will be created: {chroma_path}")
# Check Claude Desktop
claude_config = get_claude_config_path()
if claude_config and claude_config.exists():
try:
config_data = json.loads(claude_config.read_text())
if "coderag" in config_data.get("mcpServers", {}):
click.echo("β
Claude Desktop MCP configured")
else:
click.echo("βΉοΈ Claude Desktop installed but MCP not configured. Run 'coderag mcp-install'")
except Exception:
click.echo("β οΈ Claude Desktop config exists but could not be read")
else:
click.echo("βΉοΈ Claude Desktop not detected")
# Summary
if all_ok:
click.echo("\nβ
All checks passed!")
else:
click.echo("\nβ οΈ Some issues detected. See above for details.")
def _apply_config_to_env():
"""Apply configuration from config file to environment variables."""
config = get_config()
if config.get("llm_provider") and not os.environ.get("MODEL_LLM_PROVIDER"):
os.environ["MODEL_LLM_PROVIDER"] = config["llm_provider"]
if config.get("llm_api_key") and not os.environ.get("MODEL_LLM_API_KEY"):
os.environ["MODEL_LLM_API_KEY"] = config["llm_api_key"]
if config.get("embedding_device") and not os.environ.get("MODEL_EMBEDDING_DEVICE"):
os.environ["MODEL_EMBEDDING_DEVICE"] = config["embedding_device"]
def main():
"""Entry point for the CLI."""
cli()
if __name__ == "__main__":
main()
|