Update README.md
Browse files112334567879109101112131415161718191112211314231516251718192027282930313233342122363738394023244243252645272847293031323334353637505152535455565758596061626364656667686970717273747576773839404142818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371384344140141142143144145146147148149150151152454615447481561571581591601611621634950515253545516616716816917017117217317417517617717817918018118218318418518618756575859191192193606119562631971981992002012022032042052062072082092102112126465214215216217218219220666722268692242252262272282292302317071233727323523623723874757677782407980242243244818224683842488586250251252253878889909125625725825926026126226326426592932679495269969727127227327498992761001012782792802812822831021031041051061071081091102851111122871131142892902912922931151162951171182971191201211221231242993003013023033043051251263073083093103113123133143153163173183191271281291303231311323251331343271351363293303311371381391401411421433331441453353363373381461473401481493423433443451501511521533473483493501541553521561571581593543553561601613583593601621631641653621661673641681691701713663673681721733703711741751763733741771783763773783791791803813821811821831841851863841871883863873883891891901911923933943953963973983994004014024034044054064074084094104111931944134144154161951964184194201971981992002014232022034252042052062072082094284294304314324334344354364374384394404414424434444454464474484494504514524534544554564572104594604612112122132142152164644652174674682182194704714722202212222234754762242252264792272284814822292302314844854862324884894902332344922352364944954964974984995005015025035045055065075082372382395102402412425122432442455145155162462475185195202482492505232512525252532545272552562572582595302605325332612625355362632645385395405415425432652665452672685475482692705505512712725535542732745565572752762772785605615622792802812822835655662845685692852865715725735745755762872882892902912922932942952962972982995795803003015833023035855865875885895905915925935945953043055973063075996006016026036043083093103116076086096106116126133123136156163143153163176196206213183196233203213226266276283233243253266306316326333273283293303316353323333343353363371 unmodified line339340341342343344345346347647348349350351352353354355356357358654655656657658659660661662663664665359360667668669670361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391675676677392393679680681682683684394395396397398399400401402403404405406688689690407408692693694695696697698409410411412413414415416417702418419704420421706707708709422423424425426427428429430431432433434435713436437715438439717718719440441721442443723724725444445727446447729730731732733734735736737448739449450741742743451452745453454455456457458459460461462# π€ AI Codebase Assistant β Complete Documentation# AI Codebase Assistant
> An AI-powered developer tool that ingests any local code repository, answers questions about it using RAG (Retrieval-Augmented Generation), detects bugs, measures complexity, generates docs, proposes new files, and integrates with the GitHub MCP API β all from an interactive CLI.An AI-powered developer tool that lets you interact with an entire code repository using **RAG (Retrieval-Augmented Generation)** and LLMs.
It can answer questions about your codebase, detect potential bugs, analyze code complexity, explain functions, generate documentation, create new files, and interact with GitHub through the GitHub MCP API.
---
## Table of Contents## Features
1. [Project Overview](#1-project-overview)2. [Repository Structure](#2-repository-structure)3. [Architecture & Flow](#3-architecture--flow)4. [Component Deep-Dive](#4-component-deep-dive)5. [Setup & Installation](#5-setup--installation)6. [Configuration (.env)](#6-configuration-env)7. [Running the CLI](#7-running-the-cli)8. [CLI Features β All 9 Options](#8-cli-features--all-9-options)9. [REST API](#9-rest-api)10. [Key Design Decisions & Bug Fixes](#10-key-design-decisions--bug-fixes)11. [Extending the Project](#11-extending-the-project)### Codebase Question Answering
---Ask natural-language questions about your repository.
## 1. Project Overview**Example:**
The **AI Codebase Assistant** is a local developer tool that:```textHow does authentication work?```
- π **Ingests** any code repository (Python, JS, TS, Java, Go, Markdown)- π **Answers questions** about the code using RAG + LLM- π **Detects bugs** via LLM-powered code review- π **Measures cyclomatic complexity** using Radon- π **Explains functions** in plain English- π **Generates module docs and READMEs** automatically- π οΈ **Proposes & creates new files** using AI, saved to your chosen directory- π **Lists 44 GitHub MCP tools** via the GitHub Copilot MCP APIThe assistant searches the relevant parts of the codebase and generates an answer with source references.
**LLM Providers supported:**| Provider | Model | Notes ||---|---|---|| Groq | `llama-3.3-70b-versatile` | Free tier, recommended || Gemini | Configurable | Paid, stricter quota |---
**Embedding:** Google Gemini Embedding API (`models/gemini-embedding-001`) **Vector Store:** ChromaDB (local persistent)### Bug Detection
---Analyze a source file and identify potential issues using an LLM-powered code review.
## 2. Repository StructureExample:
```text[HIGH] Line 34SQL query uses string concatenation
Recommendation:Use parameterized queries to prevent SQL injection.```Codebase Assistant/ββββ cli.py # β Main entry point (interactive CLI)βββ app.py # β FastAPI REST server (optional)βββ config.py # β All settings via pydantic-settings + .envβββ llm.py # β LLM abstraction (Gemini / Groq) + prompt templatesβββ mcp_client.py # β GitHub MCP async context-manager clientβββ requirements.txt # β All Python dependenciesβββ .env # β API keys and configuration (not committed)ββββ rag/ # ββ RAG Pipeline βββββββββββββββββββββββββββββββ βββ repository_loader.py # Walk directory, read files β CodeDocumentβ βββ splitter.py # Split CodeDocuments into chunks with metadataβ βββ embedding.py # Embed chunks/queries via Gemini Embeddingsβ βββ retriever.py # ChromaDB vector store: build / load / queryβ βββ rag_chain.py # Orchestrate retrieve β build context β LLMββββ services/ # ββ Feature Services βββββββββββββββββββββββββββ βββ code_analysis.py # Bug detection, complexity, function explainerβ βββ documentation.py # Module docs, README generatorβ βββ file_creator.py # AI file proposal + local disk writeββββ api/ # ββ REST API (FastAPI) βββββββββββββββββββββββββ βββ routes.py # All HTTP endpoints (mirrors CLI features)ββββ vector_db/ # ββ ChromaDB Storage (auto-created) βββββββββββ βββ chroma.sqlite3 # Persisted vector embeddings```
The system returns the issue severity, location, and recommendation.
---
## 3. Architecture & Flow
### 3.1 Full System Architecture
```mermaidgraph TB subgraph USER["User Interface"] CLI["cli.py\n(Interactive CLI)"] API["app.py\n(FastAPI REST API)"] end
subgraph RAG["RAG Pipeline"] RL["repository_loader.py\nWalk & read files"] SP["splitter.py\nChunk by language"] EM["embedding.py\nGemini Embeddings"] RT["retriever.py\nChromaDB"] RC["rag_chain.py\nOrchestrator"] end
subgraph SERVICES["Feature Services"] CA["code_analysis.py\nBugs Β· Complexity Β· Explain"] DOC["documentation.py\nModule Docs Β· README"] FC["file_creator.py\nAI File Creator"] end
subgraph EXTERNAL["External APIs"] GROQ["Groq API\nllama-3.3-70b"] GEM["Gemini API\nEmbeddings"] MCP["GitHub MCP\n44 tools"] end
LLM["llm.py\nLLM Abstraction Layer"] CFG["config.py\n.env Settings"] DB[("vector_db/\nChromaDB")]
CLI --> RAG CLI --> SERVICES API --> RAG API --> SERVICES
RL --> SP --> EM --> RT RT --> DB RC --> RT RC --> LLM
CA --> LLM DOC --> LLM FC --> LLM
LLM --> GROQ LLM --> GEM EM --> GEM CLI --> MCP
CFG -.->|settings| RAG CFG -.->|settings| LLM CFG -.->|settings| SERVICES```### Cyclomatic Complexity Analysis
### 3.2 Ingest Flow (Step-by-step)
```mermaidflowchart LR A["User provides\nrepo path"] --> B["repository_loader.py\nwalk directories\nskip: .git venv __pycache__"] B --> C["Filter by\nallowed extensions\n.py .js .ts .java .go .md"] C --> D["Read each file\nβ CodeDocument\n(content, path, language, size)"] D --> E["splitter.py\nLanguage-aware chunking\nRecursiveCharacterTextSplitter"] E --> F["Each chunk gets\nmetadata: file_path\nlanguage Β· start_line Β· end_line"] F --> G["embedding.py\nGemini embed_documents\nβ float vectors"] G --> H["retriever.py\nDelete old collection\nCreate fresh ChromaDB\ncollection.add(...)"] H --> I["β Vector store ready"]```Analyze the complexity of Python functions using **Radon**.
### 3.3 RAG Query FlowExample:
```mermaidflowchart LR Q["User question"] --> E["embed_query\n(Gemini)"] E --> S["ChromaDB\ncollection.query\ntop-k chunks"] S --> C["build_context\nformat chunks\nwith file/line headers"] C --> P["build_prompt\nqa template\ncontext + question"] P --> L["LLM\n(Groq / Gemini)"] L --> A["Answer + Sources\n(file_path, line range)"]```text[A] process_order complexity = 2[B] validate_cart complexity = 5[C] apply_discounts complexity = 8[F] handle_edge_cases complexity = 18```
### 3.4 CLI Menu Flow
```mermaidflowchart TD START([Start cli.py]) --> REPO["βΆ Enter repo path"] REPO --> INGEST["Ingest Repository\nload β split β embed β store"] INGEST --> MENU["Show Menu\nOptions 1β9"]
MENU --> O1["1 Ask a question\nβ RAG Query"] MENU --> O2["2 Detect bugs\nβ LLM code review"] MENU --> O3["3 Cyclomatic complexity\nβ Radon"] MENU --> O4["4 Explain function\nβ AST + LLM"] MENU --> O5["5 Module docs\nβ LLM"] MENU --> O6["6 Generate README\nβ LLM"] MENU --> O7["7 Propose & create file\nβ LLM + local write"] MENU --> O8["8 List GitHub MCP tools\nβ GitHub Copilot MCP"] MENU --> O9["9 Re-ingest repo\nβ new repo path"] MENU --> O0["0 Exit"]
O1 & O2 & O3 & O4 & O5 & O6 & O7 & O8 & O9 --> MENU O0 --> END([Goodbye!])```This helps identify functions that may be difficult to maintain or test.
---
## 4. Component Deep-Dive
### 4.1 `config.py` β Settings### Function Explanation
All configuration lives in one `pydantic-settings` class loaded from `.env`:Select a function and get a plain-English explanation of what it does.
| Setting | Default | Description ||---|---|---|| `llm_provider` | `"groq"` | `"groq"` or `"gemini"` || `groq_api_key` | `""` | From `.env` || `groq_model` | `"llama-3.3-70b-versatile"` | Free Groq model || `gemini_api_key` | `""` | From `.env` || `embedding_model` | `"models/gemini-embedding-001"` | Always Gemini for embeddings || `vector_db_path` | `"./vector_db"` | ChromaDB storage directory || `chunk_size` | `1200` | Characters per chunk || `chunk_overlap` | `100` | Overlap between chunks || `allowed_extensions` | `[.py .js .ts .go .java .md]` | File types to load || `max_file_size_kb` | `1042` | Skip files larger than this || `github_mcp_url` | GitHub Copilot MCP endpoint | For option 8 || `github_mcp_token` | `""` | GitHub PAT from `.env` |
### 4.2 `rag/repository_loader.py` β File IngestionFor Python code, the project uses the `ast` module to extract the function and provides relevant repository context to the LLM.
```load_repository(root_path) βββ os.walk(root_path) βββ Skip: .git, node_modules, __pycache__, venv, .venv, dist, build βββ should_include(fpath) β checks extension + file size βββ read_file_with_metadata(fpath) β CodeDocument(content, file_path, language, size_bytes)```---
**Supported languages detected by extension:**### Documentation Generation
| Extension | Language ||---|---|| `.py` | python || `.js` | javascript || `.ts` | typescript || `.java` | java || `.go` | go || `.md` | markdown |Generate documentation automatically for your codebase.
### 4.3 `rag/splitter.py` β ChunkingThe assistant can generate:
Uses **LangChain's `RecursiveCharacterTextSplitter`** with language-aware splitting:- For Python/JS/TS/Java/Go β uses syntax-aware boundaries (functions, classes)- For Markdown/unknown β falls back to generic character splitting- Each chunk carries: `content`, `file_path`, `language`, `chunk_index`, `start_line`, `end_line`- Module documentation- Function explanations- Docstrings- Repository README files
### 4.4 `rag/embedding.py` β Embeddings---
- Uses `GoogleGenerativeAIEmbeddings` (`models/gemini-embedding-001`)- `embed_document(chunks)` β batch embeds all chunks, mutates dicts in-place- `embed_query(query)` β single query vector for similarity search### AI File Generation
### 4.5 `rag/retriever.py` β Vector StoreDescribe the file you want to create and let the AI generate it.
> **Critical fix applied:** collection is deleted and recreated on every ingest to prevent stale data from previous repos bleeding through.Example:
```pythonbuild_vector_store(chunks) # delete β create β add (fresh each ingest)load_vector_store() # get_or_create for readingretrieve_relevant_chunks(q, k) # embed query β cosine similarity β top-k```textCreate a Rectangle class in JavaScriptthat calculates area and perimeter.```
### 4.6 `rag/rag_chain.py` β Orchestration
```pythonrun_rag_query(query, k=5) 1. retrieve_relevant_chunks(query, k) 2. build_context(chunks) # format with file/line headers 3. build_prompt(query, context) # fill qa template 4. llm.generate(prompt) 5. return { answer, sources }```The generated file is shown before it is written to the repository, allowing the user to approve it first.
### 4.7 `llm.py` β LLM Abstraction---
Abstract `BaseLLM` with two concrete providers:### GitHub MCP Integration
| Class | Provider | API ||---|---|---|| `GeminiLLM` | Google Gemini | `google-genai` SDK || `GroqLLM` | Groq | `groq` SDK, chat completions |The project integrates with the **GitHub Copilot MCP API**.
**Prompt templates (`build_prompt`):**It currently supports access to **44 GitHub MCP tools**, including:
| `task_type` | Used by ||---|---|| `"qa"` | RAG query, function explain, module docs, README || `"bug_finding"` | Bug detection (returns JSON) || `"docstring"` | Docstring generation || `"file_creation"` | AI file proposal |- `search_code`- `search_repositories`- `get_file_contents`- `list_issues`- `create_branch`- `create_pull_request`- `push_files`- `fork_repository`
### 4.8 `mcp_client.py` β GitHub MCP Client---
Async context-manager pattern using `AsyncExitStack` to keep all `anyio` cancel scopes in the **same task**:## RAG-Based Code Search
```pythonasync with get_github_mcp_client() as client: tools = await client.list_tools() result = await client.call_tool("create_branch", {...})```The project uses **Retrieval-Augmented Generation (RAG)** to work with repository-level code.
Available GitHub MCP tools (44 total) include: `search_code`, `list_issues`, `create_pull_request`, `get_file_contents`, `push_files`, `create_branch`, `fork_repository`, `search_repositories`, and many more.Repository files are:
### 4.9 `services/code_analysis.py`1. Loaded and filtered2. Split into smaller chunks3. Converted into embeddings4. Stored in ChromaDB5. Retrieved based on semantic similarity when a question is asked
| Function | How it works ||---|---|| `explain_function(file, name)` | Python `ast` extracts the function source β RAG context β LLM || `detect_bugs(file)` | Read file β `bug_finding` prompt β LLM returns JSON list || `analyze_complexity(file)` | `radon.cc_visit` β cyclomatic complexity + rank AβF |
### 4.10 `services/file_creator.py`The retrieved code is then provided to the LLM as context.
```propose_new_file(description, context_query) βββ RAG retrieve relevant context βββ build_prompt(description, context, "file_creation") βββ LLM generates complete file content βββ infer_file_path(description) β LLM suggests relative path
apply_approved_file(proposal, confirmed, base_dir) βββ Strip leading / or \ from LLM path βββ os.path.join(base_dir, relative_path) βββ os.makedirs(parent_dirs, exist_ok=True) βββ open(abs_path, "w").write(content)```Source metadata such as file path and line range is preserved during this process.
---
## 5. Setup & Installation## Supported Languages
### PrerequisitesThe repository ingestion system currently supports:
| Requirement | Version || Extension | Language ||---|---|| Python | 3.11+ || pip | Latest || Internet | For API calls || `.py` | Python || `.js` | JavaScript || `.ts` | TypeScript || `.java` | Java || `.go` | Go || `.md` | Markdown |
### Step 1 β Clone / Download the project---
```bashgit clone <your-repo-url>cd "Codebase Assistant"```## Tech Stack
### Step 2 β Create a virtual environment### AI / LLM
```bash# Windows (PowerShell)python -m venv .venv.venv\Scripts\Activate.ps1- Groq- Llama 3.3 70B- Google Gemini
# macOS / Linuxpython3 -m venv .venvsource .venv/bin/activate```### RAG
### Step 3 β Install dependencies- LangChain- Google Gemini Embeddings- ChromaDB
```bashpip install -r requirements.txt```### Backend
> [!TIP]> If you hit permission issues on Windows, use:> `pip install -r requirements.txt --user`- Python- FastAPI- Pydantic Settings
### Step 4 β Create your `.env` file### Code Analysis
Create a file named `.env` in the project root:- Python AST- Radon- LLM-based code analysis
```env# Choose your LLM provider: "groq" (free) or "gemini"LLM_PROVIDER=groq### Integration
# Groq β free at https://console.groq.comGROQ_API_KEY=gsk_your_key_here- GitHub MCP- GitHub Copilot MCP API
# Gemini β get at https://aistudio.google.comGEMINI_API_KEY=your_gemini_key_here---
# GitHub PAT for MCP tools β create at https://github.com/settings/tokens# Required scopes: repo, read:orgGITHUB_MCP_TOKEN=github_pat_your_token_here```## LLM Providers
> [!IMPORTANT]> `GEMINI_API_KEY` is **always required** regardless of LLM provider, because embeddings always use Gemini.| Provider | Model | Usage ||---|---|---|| Groq | `llama-3.3-70b-versatile` | LLM generation || Gemini | Configurable | LLM generation || Gemini Embeddings | `models/gemini-embedding-001` | Code embeddings |
### Step 5 β Run the CLIThe project supports switching between Groq and Gemini for LLM generation.
```bash.venv\Scripts\python.exe cli.py # Windowspython cli.py # macOS / Linux```Gemini Embeddings are used for semantic retrieval.
---
## 6. Configuration (.env)
```env# βββ LLM Provider ββββββββββββββββββββββββββββββββββββββββLLM_PROVIDER=groq # "groq" | "gemini"
# βββ Groq (recommended β free tier) βββββββββββββββββββββGROQ_API_KEY=gsk_...GROQ_MODEL=llama-3.3-70b-versatile
# βββ Gemini ββββββββββββββββββββββββββββββββββββββββββββββGEMINI_API_KEY=...LLM_MODEL=gemini-1.5-flash # only used if LLM_PROVIDER=geminiEMBEDDING_MODEL=models/gemini-embedding-001
# βββ RAG / Vector DB βββββββββββββββββββββββββββββββββββββVECTOR_DB_PATH=./vector_dbCHUNK_SIZE=1200CHUNK_OVERLAP=100# Installation
# βββ File loader βββββββββββββββββββββββββββββββββββββββββ# comma-separated extensionsALLOWED_EXTENSIONS=[".py",".js",".ts",".go",".java",".md"]MAX_FILE_SIZE_KB=1042## 1. Clone the Repository
# βββ GitHub MCP ββββββββββββββββββββββββββββββββββββββββββGITHUB_MCP_URL=https://api.githubcopilot.com/mcp/GITHUB_MCP_TOKEN=github_pat_...```bashgit clone <your-repository-url>cd "Codebase Assistant"```
---## 2. Create a Virtual Environment
## 7. Running the CLI### Windows
```bashpython -m venv .venv.venv\Scripts\Activate.ps1```βββββββββββββββββββββββββββββββββββββββββββββ AI Codebase Assistant CLI βββββββββββββββββββββββββββββββββββββββββββββ
βΆ Enter the path to the repository you want to analyse: D:\MyProject
ββ Ingesting Repository ββββββββββββββββββββββ Loading files from: D:\MyProject β Loaded 12 files β Split into 47 chunks Embedding chunks (this may take a moment)... β Embedded 47 chunks β Vector store ready (ChromaDB)
ββ What would you like to do? ββββββββββββββββ 1 Ask a question about the codebase 2 Detect bugs in a file 3 Cyclomatic complexity analysis 4 Explain a function 5 Generate module documentation 6 Generate README for a repository 7 Propose & create a new file (AI) 8 List GitHub MCP tools 9 Re-ingest a repository 0 Exit
βΆ Choose an option [0β9]:```
---
## 8. CLI Features β All 9 Options
### Option 1 β Ask a Question (RAG Query)### Linux / macOS
```bashpython3 -m venv .venvsource .venv/bin/activate```βΆ Your question: How does the authentication work?βΆ Number of source chunks to retrieve? [default: 5] 3
ββ Answer ββββββββββββββββββββββββββββββββββββThe authentication uses JWT tokens ...## 3. Install Dependencies
ββ Sources βββββββββββββββββββββββββββββββββββ β’ src/auth/middleware.py lines 12β45 β’ src/auth/tokens.py lines 1β30```bashpip install -r requirements.txt```
**Pipeline:** Embed question β ChromaDB similarity search β Build context β LLM β Answer + cited sources
---## ποΈ Architecture
### Option 2 β Detect Bugs
```βΆ File path to analyse: src/payment.pyThe system combines a RAG pipeline, LLM providers, code analysis services,FastAPI, and GitHub MCP integration to provide repository-level AI assistance.
ββ Found 2 issue(s) ββββββββββββββββββββββββββ [HIGH] Line 34: SQL query uses string concatenation β Use parameterized queries to prevent SQL injection
[MEDIUM] Line 67: Exception swallowed silently β Log or re-raise the exception```# Configuration
**Pipeline:** Read file β `bug_finding` prompt β LLM returns JSON β parsed and displayedCreate a `.env` file in the project root.
---
### Option 3 β Cyclomatic Complexity
```βΆ File path to analyse: src/processor.py
ββ 4 function(s) βββββββββββββββββββββββββββββ [A] process_order complexity=2 ββ [B] validate_cart complexity=5 βββββ [C] apply_discounts complexity=8 ββββββββ [F] handle_edge_cases complexity=18 ββββββββββββββββββ```
**Rank scale:** A (1β5, simple) β F (26+, untestable)```envLLM_PROVIDER=groq
---GROQ_API_KEY=your_groq_api_keyGROQ_MODEL=llama-3.3-70b-versatile
### Option 4 β Explain a FunctionGEMINI_API_KEY=your_gemini_api_keyEMBEDDING_MODEL=models/gemini-embedding-001
```βΆ File path: src/utils.pyβΆ Function name: parse_date_rangeVECTOR_DB_PATH=./vector_db
ββ Explanation βββββββββββββββββββββββββββββββparse_date_range takes a string like "2024-01-01:2024-12-31"and returns a tuple of (start_date, end_date) as datetime objects ...GITHUB_MCP_TOKEN=your_github_token```
**Pipeline:** Python `ast` module extracts exact function source β RAG retrieves usages β LLM explains### Required API Keys
---**Groq**
### Option 5 β Generate Module DocumentationUsed for LLM generation when:
```envLLM_PROVIDER=groq```βΆ File path: src/database.py
ββ Documentation βββββββββββββββββββββββββββββ## database.py**Gemini**
### OverviewThis module provides the database connection layer ...Required for embeddings because the project uses Gemini Embeddings for repository indexing.
### Functions- `connect(url)` β Establishes a connection ...- `execute(query, params)` β Runs a parameterized query ...```
---**GitHub Token**
### Option 6 β Generate READMERequired for GitHub MCP functionality.
```βΆ Repository root path: D:\MyProject---
ββ README Preview ββββββββββββββββββββββββββββ# MyProject# Running the CLI
## OverviewA FastAPI application that ...Start the interactive CLI:
βΆ Save to README.md in that directory? [y/N] y β Saved to D:\MyProject\README.md```bashpython cli.py```
---
### Option 7 β Propose & Create a New FileThe application will ask for the repository you want to analyze.
```textβΆ Enter the path to the repository you want to analyse:```βΆ Describe the file you want to create: Rectangle area calculator in JavaScriptβΆ Optional context query (or press Enter to skip):
ββ Proposed File βββββββββββββββββββββββββββββ Path: /src/geometry/rectangle.jsAfter the repository is indexed, you can choose from:
class Rectangle { ...full generated code... }
βΆ Write this file to disk? [y/N] yβΆ Save under which directory? [default: D:\MyProject]
β File written: D:\MyProject\src\geometry\rectangle.js```text1 Ask a question about the codebase2 Detect bugs in a file3 Cyclomatic complexity analysis4 Explain a function5 Generate module documentation6 Generate README7 Propose & create a new file8 List GitHub MCP tools9 Re-ingest repository0 Exit```
**Pipeline:** RAG context (optional) β `file_creation` prompt β LLM generates code β user confirms β write to `base_dir/relative_path`
---
### Option 8 β List GitHub MCP Tools# REST API
```ββ List GitHub MCP Tools βββββββββββββββββββββ 44 tools available: β’ create_branch Create a new branch in a GitHub repository β’ create_pull_request Create a new pull request ... β’ search_code Fast and precise code search ... β’ list_issues List issues in a GitHub repository ... ...```
**Connection:** Uses `streamable_http_client` β `ClientSession` β GitHub Copilot MCP endpointThe project also provides a FastAPI REST API.
---Start the server:
### Option 9 β Re-ingest a Repository
```βΆ New repository path to ingest: D:\AnotherProjectββ Ingesting Repository ββββββββββββββββββββββ β Loaded 8 files ...```bashpython -m uvicorn app:app --reload --port 8000```
Wipes the ChromaDB collection and ingests the new repo fresh. All subsequent queries answer from the new repo only.
---
## 9. REST API
Start the FastAPI server:Open the interactive API documentation:
```bash.venv\Scripts\python.exe -m uvicorn app:app --reload --port 8000```texthttp://localhost:8000/docs```
Open docs at: `http://localhost:8000/docs`
### Endpoints## API Endpoints
| Method | Path | Description || Method | Endpoint | Description ||---|---|---|| `GET` | `/health` | Health check || `POST` | `/api/query` | RAG question answering || `POST` | `/api/analyze/bugs?file_path=...` | Bug detection || `POST` | `/api/analyze/complexity?file_path=...` | Cyclomatic complexity || `POST` | `/api/query` | Ask questions about the codebase || `POST` | `/api/analyze/bugs` | Detect potential bugs || `POST` | `/api/analyze/complexity` | Analyze cyclomatic complexity || `POST` | `/api/analyze/explain` | Explain a function || `POST` | `/api/docs/module?file_path=...` | Module documentation || `POST` | `/api/docs/readme?root_path=...` | README generation || `POST` | `/api/files/propose` | Propose a new file || `POST` | `/api/files/approve` | Write approved file to disk || `POST` | `/api/docs/module` | Generate module documentation || `POST` | `/api/docs/readme` | Generate README || `POST` | `/api/files/propose` | Generate a file proposal || `POST` | `/api/files/approve` | Write an approved file |
### Example β Query---
## Example API Request
```bashcurl -X POST http://localhost:8000/api/query \1 unmodified line -d '{"query": "How does authentication work?", "k": 5}'```
Example response:
```json{ "answer": "Authentication is handled by ...", "sources": [ {"file_path": "src/auth.py", "start_line": 10, "end_line": 45} { "file_path": "src/auth.py", "start_line": 10, "end_line": 45 } ]}```
---
## 10. Key Design Decisions & Bug Fixes
### Bug Fix 1 β Collection Isolation (retriever.py)
**Problem:** ChromaDB used `upsert` on a shared `"codebase"` collection β stale chunks from previously ingested repos leaked into new queries.
**Fix:** On every ingest, `delete_collection` + `create_collection` ensures a clean slate:
```python# Before (bug)collection = client.get_or_create_collection("codebase")collection.upsert(...)# π Project Structure
# After (fix)client.delete_collection("codebase") # wipe old repocollection = client.create_collection("codebase")collection.add(...)```textCodebase Assistant/ββββ cli.pyβββ app.pyβββ config.pyβββ llm.pyβββ mcp_client.pyβββ requirements.txtββββ rag/β βββ repository_loader.pyβ βββ splitter.pyβ βββ embedding.pyβ βββ retriever.pyβ βββ rag_chain.pyββββ services/β βββ code_analysis.pyβ βββ documentation.pyβ βββ file_creator.pyββββ api/β βββ routes.pyββββ vector_db/ βββ chroma.sqlite3```
---
### Bug Fix 2 β GitHub MCP Cancel Scope (mcp_client.py)
**Problem:** Manually calling `__aenter__`/`__aexit__` on `anyio`-backed context managers across tasks causes `RuntimeError: Attempted to exit cancel scope in a different task`.# Configuration Options
**Fix:** Use `AsyncExitStack` to nest all context managers inside a single `async with`:
```pythonasync with get_github_mcp_client() as client: tools = await client.list_tools()```| Setting | Default | Description ||---|---|---|| `LLM_PROVIDER` | `groq` | LLM provider || `GROQ_MODEL` | `llama-3.3-70b-versatile` | Groq model || `EMBEDDING_MODEL` | `models/gemini-embedding-001` | Embedding model || `VECTOR_DB_PATH` | `./vector_db` | ChromaDB storage || `CHUNK_SIZE` | `1200` | Chunk size || `CHUNK_OVERLAP` | `100` | Chunk overlap || `MAX_FILE_SIZE_KB` | `1042` | Maximum file size || `ALLOWED_EXTENSIONS` | `.py,.js,.ts,.go,.java,.md` | Supported files |
---
### Bug Fix 3 β Wrong Unpack Count (mcp_client.py)
**Problem:** `streamable_http_client` yields 2 values, not 3. Unpacking 3 caused `ValueError: not enough values to unpack`.# Limitations
```python# Before (bug)read, write, _ = await ctx.__aenter__()
# After (fix)read, write = await stack.enter_async_context(streamable_http_client(...))```- Repository ingestion currently runs locally.- External API keys are required for LLM and embedding services.- Gemini embedding quotas may limit large repositories.- Only the currently supported file types are indexed.- LLM-generated code and bug reports should be reviewed before use.- The vector database currently focuses on the actively ingested repository.
---
### Bug Fix 4 β File Save Path (file_creator.py)# Future Improvements
**Problem:** Generated files saved to the current working directory regardless of user input.Planned or possible improvements include:
**Fix:** - Strip leading `/\` from LLM path to make it always relative- Accept `base_dir` defaulting to `_current_repo` (the ingested repo path)- Create all parent directories automatically- More programming language support- Incremental repository indexing- GitHub repository ingestion- AST-based code chunking- Hybrid keyword + vector search- Retrieval reranking- Dependency graph analysis- Automated test generation- Automated pull request review- Multi-repository search- Web-based developer interface
---
## 11. Extending the Project# Project Goal
### Add a new LLM providerThe goal of this project is to build an AI developer assistant that can understand and interact with an entire codebase rather than only individual code snippets.
1. Add a new class in `llm.py` extending `BaseLLM`2. Add the provider name to `get_llm_client()` factory3. Add matching settings in `config.py`It combines:
### Add support for new file types**RAG + LLMs + Vector Search + Code Analysis + FastAPI + MCP**
1. Add extension β language in `LANGUAGE_BY_EXT` in `repository_loader.py`2. Add extension to `allowed_extensions` in `config.py`3. If LangChain has a `Language` enum for it, add to `LANGUAGE_MAP` in `splitter.py`into a single developer-focused tool.
### Use a GitHub MCP tool in a feature---
```pythonasync with get_github_mcp_client() as client: result = await client.call_tool("create_branch", { "owner": "myuser", "repo": "myrepo", "branch": "feature/new-branch", "from_branch": "main" })```
### Add a new CLI option# Author
1. Write a `feature_xxx()` function in `cli.py`2. Add `("Label", feature_xxx)` to the `MENU` list3. Add a matching FastAPI endpoint in `api/routes.py`**Armaan Alam**
---AI Engineer & Software Developer
Interested in:
- Generative AI- RAG Systems- Backend Engineering- LLM Applications- AI Developer Tools- Machine LearningREADME.md+277-561