Skip to main content
Glama
bhasinagam

CodeContext

by bhasinagam
README.md
<div align="center">

# 🧠 CodeContext

**AI Coding Context Layer β€” Make AI assistants understand your team's codebase patterns**

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.0-blue.svg)](https://www.typescriptlang.org/)
[![Next.js](https://img.shields.io/badge/Next.js-14-black.svg)](https://nextjs.org/)
[![MCP Compatible](https://img.shields.io/badge/MCP-Compatible-green.svg)](https://modelcontextprotocol.io/)

[Features](#features) β€’ [Quick Start](#quick-start) β€’ [Architecture](#architecture) β€’ [API Reference](#api-reference) β€’ [Contributing](#contributing)

</div>

---

## 🎯 The Problem

AI coding assistants like Cursor and Copilot are powerful, but they don't understand your team's **unique patterns**:
- Your error handling conventions
- Your import style preferences
- Your validation approach
- Your authentication patterns

Every suggestion requires mental translation to match your codebase.

## ✨ The Solution

**CodeContext** automatically detects your codebase patterns and injects them as context into AI assistants via the [Model Context Protocol (MCP)](https://modelcontextprotocol.io/). Now every AI suggestion follows your team's conventions out of the box.

---

## πŸš€ Features

### 8 Pattern Types Detected

| Category | Pattern Types | Detection Method |
|----------|--------------|------------------|
| **Code Style** | Error Handling, Imports, Naming, Structure | Rules-based (instant) |
| **Frameworks** | API Format, Validation, Database, Auth | Hybrid (rules + LLM fallback) |

### Key Capabilities

- **πŸ” AST-Powered Analysis** β€” Deep code parsing with Babel for accurate pattern detection
- **πŸ€– Hybrid Detection** β€” Rules-based first, LLM (Groq) fallback for complex patterns
- **⚑ Real-time Indexing** β€” Background processing with Redis queue
- **πŸ”— MCP Protocol** β€” Native integration with Cursor, Copilot, and more
- **πŸ” GitHub OAuth** β€” Seamless onboarding and repository access
- **πŸ“Š Dashboard** β€” View detected patterns, confidence scores, and usage analytics

---

## πŸ—οΈ Architecture

```mermaid
flowchart TB
    subgraph Input["πŸ“₯ Input"]
        GH[GitHub Repository]
    end
    
    subgraph Core["🧠 CodeContext Engine"]
        IDX[Indexing Queue<br/>Redis/Upstash]
        AST[AST Parser<br/>Babel]
        DET[Pattern Detectors<br/>8 Types]
        LLM[LLM Fallback<br/>Groq]
        CTX[Context Generator]
    end
    
    subgraph Storage["πŸ’Ύ Storage"]
        DB[(PostgreSQL<br/>Supabase)]
    end
    
    subgraph Output["πŸ“€ Output"]
        MCP[MCP Server]
        DASH[Dashboard]
    end
    
    subgraph Clients["πŸ€– AI Clients"]
        CUR[Cursor]
        COP[Copilot]
        OTHER[Other MCP Clients]
    end
    
    GH --> IDX
    IDX --> AST
    AST --> DET
    DET --> LLM
    DET --> DB
    LLM --> DB
    DB --> CTX
    CTX --> MCP
    DB --> DASH
    MCP --> CUR
    MCP --> COP
    MCP --> OTHER
```

---

## πŸ“¦ Tech Stack

| Layer | Technology |
|-------|------------|
| **Frontend** | Next.js 14 (App Router), TypeScript, Tailwind CSS |
| **Backend** | Next.js API Routes, NextAuth.js |
| **Database** | PostgreSQL (Supabase) |
| **Queue** | Redis (Upstash) |
| **AST Parsing** | @babel/parser, @babel/traverse |
| **LLM** | Groq (llama-3.3-70b-versatile) |
| **MCP** | @modelcontextprotocol/sdk |

---

## πŸš€ Quick Start

### Prerequisites

- Node.js 18+
- PostgreSQL database (we recommend [Supabase](https://supabase.com))
- Redis instance (we recommend [Upstash](https://upstash.com))
- GitHub OAuth App
- Groq API key (free tier: 14,400 req/day)

### 1. Clone & Install

```bash
git clone https://github.com/bhasinagam/ContextBridge.git
cd ContextBridge
npm install
```

### 2. Configure Environment

```bash
cp .env.example .env.local
```

Edit `.env.local` with your credentials:

| Variable | Description | Where to Get |
|----------|-------------|--------------|
| `DATABASE_URL` | PostgreSQL connection string | [Supabase](https://supabase.com/dashboard) β†’ Settings β†’ Database |
| `UPSTASH_REDIS_REST_URL` | Redis REST URL | [Upstash](https://console.upstash.com) β†’ Redis β†’ REST API |
| `UPSTASH_REDIS_REST_TOKEN` | Redis REST token | Same as above |
| `NEXTAUTH_SECRET` | Random 32-byte secret | Run: `openssl rand -base64 32` |
| `GITHUB_CLIENT_ID` | OAuth App client ID | [GitHub](https://github.com/settings/developers) β†’ OAuth Apps |
| `GITHUB_CLIENT_SECRET` | OAuth App secret | Same as above |
| `GROQ_API_KEY` | Groq API key | [Groq Console](https://console.groq.com/keys) |

### 3. Set Up Database

Run the schema in your Supabase SQL editor:

```sql
-- Contents of src/lib/db/schema.sql
```

Or use the Supabase dashboard to import `src/lib/db/schema.sql`.

### 4. Run Development Server

```bash
npm run dev
```

Open [http://localhost:3000](http://localhost:3000) to access the dashboard.

---

## πŸ”Œ MCP Integration

### Using with Cursor

Add to `~/.cursor/mcp.json`:

```json
{
  "mcpServers": {
    "codecontext": {
      "url": "http://localhost:3000/api/mcp/context",
      "headers": {
        "X-API-Key": "your-api-key"
      },
      "defaultParams": {
        "repo_id": "your-repo-id"
      }
    }
  }
}
```

### API Usage

```bash
curl -X POST http://localhost:3000/api/mcp/context \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your-api-key" \
  -d '{
    "query": "add an API endpoint",
    "repo_id": "your-repo-id"
  }'
```

---

## πŸ“ Project Structure

```
src/
β”œβ”€β”€ app/                      # Next.js App Router
β”‚   β”œβ”€β”€ api/                  # API Routes
β”‚   β”‚   β”œβ”€β”€ auth/             # NextAuth endpoints
β”‚   β”‚   β”œβ”€β”€ github/           # GitHub API proxy
β”‚   β”‚   β”œβ”€β”€ mcp/              # MCP context & health
β”‚   β”‚   β”œβ”€β”€ patterns/         # Pattern queries
β”‚   β”‚   β”œβ”€β”€ repos/            # Repository CRUD
β”‚   β”‚   └── webhooks/         # GitHub webhooks
β”‚   β”œβ”€β”€ dashboard/            # Dashboard pages
β”‚   └── onboarding/           # Onboarding flow
β”œβ”€β”€ components/               # React components
β”‚   β”œβ”€β”€ ui/                   # shadcn/ui components
β”‚   └── dashboard/            # Dashboard-specific
└── lib/                      # Core libraries
    β”œβ”€β”€ db/                   # Database client & schema
    β”œβ”€β”€ github/               # GitHub API client
    β”œβ”€β”€ indexing/             # AST parser & queue
    β”œβ”€β”€ mcp/                  # MCP server & context generator
    β”œβ”€β”€ patterns/             # 8 pattern detectors
    └── utils/                # Types, helpers, Groq client
```

---

## πŸ” Pattern Types

### Rules-Based (No API Calls)

| Pattern | What It Detects |
|---------|-----------------|
| **Error Handling** | try-catch blocks, wrapper functions (handleError, etc.) |
| **Import Style** | Relative (./path), Absolute (@/, ~/), Barrel exports |
| **Naming Convention** | camelCase, snake_case, PascalCase |
| **File Structure** | App Router, Pages Router, Components directory |

### Hybrid (Rules + LLM Fallback)

| Pattern | What It Detects |
|---------|-----------------|
| **API Format** | Next.js API Routes, response structure patterns |
| **Validation** | Zod, Yup, Joi, Valibot, custom validation |
| **Database** | Prisma, Drizzle, TypeORM, Mongoose, Supabase, Kysely |
| **Authentication** | NextAuth, Clerk, Auth0, Supabase Auth, Firebase |

---

## πŸ”§ Troubleshooting

<details>
<summary><strong>Database connection failed</strong></summary>

- Ensure your Supabase project is active
- Check if the password contains special characters (URL-encode them)
- Use port `5432` for direct connection, `6543` for pooled

</details>

<details>
<summary><strong>GitHub OAuth redirect error</strong></summary>

- Verify callback URL is set to `http://localhost:3000/api/auth/callback/github`
- Ensure `NEXTAUTH_URL` matches your app URL

</details>

<details>
<summary><strong>Pattern detection returns empty</strong></summary>

- Check if repository indexing is complete (status: "completed")
- Verify there are TypeScript/JavaScript files in the repo
- Check Redis queue for pending jobs

</details>

<details>
<summary><strong>MCP not connecting to Cursor</strong></summary>

- Restart Cursor after updating `mcp.json`
- Check API key is valid and not expired
- Verify the repo_id matches a indexed repository

</details>

---

## πŸ—ΊοΈ Roadmap

- [ ] **Multi-language support** β€” Python, Go, Rust
- [ ] **Custom pattern definitions** β€” User-defined pattern rules
- [ ] **Team collaboration** β€” Shared pattern configs
- [ ] **VS Code extension** β€” Native VS Code integration
- [ ] **Pattern analytics** β€” Usage trends and insights

---

## 🀝 Contributing

We welcome contributions! See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

---

## πŸ“„ License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

---

<div align="center">

**Built with ❀️ for the AI-assisted coding community**

[⭐ Star this repo](https://github.com/bhasinagam/ContextBridge) if you find it useful!

</div>