Skip to main content
Glama
Semantic Codebase Search MCP Server

Semantic Codebase Search MCP Server

by ogghst
README.md
# Semantic Codebase Search MCP Server

<div align="center">

**Intelligent code search using semantic understanding and vector embeddings**

[![Python Version](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
[![Code style: ruff](https://img.shields.io/badge/code%20style-ruff-000000.svg)](https://github.com/astral-sh/ruff)

[Features](#-features) •
[Installation](#-installation) •
[Quick Start](#-quick-start) •
[Documentation](#-documentation) •
[Contributing](#-contributing)

</div>

---

## ✨ Features

### 🧠 Semantic Search
- Find code by **meaning**, not just keywords
- Understands natural language queries
- Returns semantically similar code even when keywords don't match

### 🌐 Multi-Language Support
- **Python**, **JavaScript**, **TypeScript**, **Go**, **Rust**, and more
- Uses Tree-sitter for robust, language-agnostic parsing
- Easily extensible to new languages

### 🚀 High Performance
- **Incremental indexing** with Merkle trees (only reindex changed files)
- **Local-first** design with optional cloud embeddings
- **Sub-200ms** search latency with caching
- **Parallel processing** for batch operations

### 🔌 Pluggable Architecture
- **Multiple embedding providers**: OpenAI, C2LLM, Sentence Transformers
- **Vector store backends**: ChromaDB, FAISS, Qdrant, and more
- Easy to extend with custom implementations

### 🔒 Privacy & Security
- Local-first: code never leaves your machine (with local embeddings)
- No telemetry or analytics by default
- Input validation and sanitization
- Secure API key management

---

## 📦 Installation

### From PyPI (when published)

```bash
pip install semantic-code-search
```

### From Source

```bash
git clone https://github.com/yourusername/semantic-mcp-search.git
cd semantic-mcp-search
pip install -e .
```

### With Optional Dependencies

```bash
# With OpenAI support
pip install -e ".[openai]"

# With development tools
pip install -e ".[dev]"

# With everything
pip install -e ".[openai,dev]"
```

---

## 🚀 Quick Start

### 1. Configuration

Create a `.env` file:

```bash
# MCP Server
MCP_HOST=localhost
MCP_PORT=8000
MCP_TRANSPORT=stdio

# Vector Store
VECTORSTORE_TYPE=chroma
VECTORSTORE_PATH=./data/vectorstore

# Embeddings (choose one)
# Option 1: OpenAI (recommended for best quality)
EMBEDDINGS_PROVIDER=openai
EMBEDDINGS_MODEL=text-embedding-3-small
EMBEDDINGS_API_KEY=sk-your-key-here

# Option 2: C2LLM (local, free, code-specific)
EMBEDDINGS_PROVIDER=c2llm
EMBEDDINGS_MODEL=codefuse-ai/C2LLM-0.5B

# Option 3: Sentence Transformers (local, free)
EMBEDDINGS_PROVIDER=sentence-transformers
EMBEDDINGS_MODEL=all-MiniLM-L6-v2

# Codebase
PATHS_CODEBASE_PATH=./codebase
```

### 2. Start the Server

```bash
# Start MCP server
semantic-search start

# Or with custom port
semantic-search start --port 9000

# Or with HTTP transport
semantic-search start --transport http
```

### 3. Perform Your First Search

The server exposes MCP tools that you can call:

```json
{
  "tool": "semantic_search",
  "arguments": {
    "query": "how is authentication handled?"
  }
}
```

**Response**:
```json
[
  {
    "filepath": "src/auth/middleware.py",
    "snippet": "def authenticate(request):\n    token = request.headers.get('Authorization')",
    "score": 0.92,
    "line_numbers": [42, 43]
  }
]
```

---

## 📚 Documentation

| Document | Description |
|----------|-------------|
| **[User Guide](./docs/user-guide.md)** | Installation, configuration, and usage examples |
| **[API Reference](./docs/api.md)** | Complete API documentation for all classes and methods |
| **[OpenAPI Spec](./docs/openapi.yaml)** | HTTP API specification (if HTTP transport enabled) |
| **[Architecture](./ARCHITECTURE.md)** | System design, components, and data flow |
| **[Contributing](./CONTRIBUTING.md)** | Development setup and contribution guidelines |

### Usage Examples

#### Python API

```python
from semantic_search import SearchPipeline, get_settings
from semantic_search.storage import ChromaDBVectorStore
from semantic_search.embeddings import OpenAIEmbeddingGenerator

# Initialize
settings = get_settings()
embedder = OpenAIEmbeddingGenerator(api_key=settings.embeddings.api_key)
vector_store = ChromaDBVectorStore(path=settings.vectorstore.path)
pipeline = SearchPipeline(embedder, vector_store)

# Search
results = await pipeline.search("authentication middleware", top_k=5)

for result in results:
    print(f"{result.chunk.file_path}:{result.chunk.start_line}")
    print(f"Score: {result.score:.2f}")
    print(f"Code:\n{result.chunk.content}\n")
```

#### Command Line Interface

```bash
# Index a directory
semantic-search index ./src

# Search for code
semantic-search search "authentication middleware"

# Search with filters
semantic-search search "database connection" --language python --path "src/db/*"

# Check indexing status
semantic-search status --watch
```

#### MCP Client Integration

Add to your Claude Desktop MCP config:

```json
{
  "mcpServers": {
    "semantic-search": {
      "command": "semantic-search",
      "args": ["start"],
      "env": {
        "EMBEDDINGS_PROVIDER": "openai",
        "EMBEDDINGS_API_KEY": "sk-your-key",
        "PATHS_CODEBASE_PATH": "/path/to/your/code"
      }
    }
  }
}
```

---

## 🏗️ Architecture

The system follows a modular pipeline architecture:

```
MCP Client
    ↓
MCP Server (stdio/HTTP)
    ↓
┌─────────────────────────────────────┐
│  Search Pipeline (cached, expanded) │
├─────────────────────────────────────┤
│  Embedding Service (pluggable)      │
│  ├─ OpenAI                           │
│  ├─ C2LLM (local)                    │
│  └─ Sentence Transformers (local)   │
├─────────────────────────────────────┤
│  Vector Store (abstraction layer)   │
│  ├─ ChromaDB (default)               │
│  ├─ FAISS                            │
│  └─ Qdrant                           │
├─────────────────────────────────────┤
│  Indexing Engine (incremental)      │
│  ├─ Merkle Tree (change detection)  │
│  ├─ Tree-sitter (AST parsing)       │
│  └─ File Watcher                    │
└─────────────────────────────────────┘
```

**Key Design Decisions**:
- **Merkle Trees**: Efficient incremental indexing (only process changed files)
- **Tree-sitter**: Robust, multi-language AST parsing
- **Strategy Pattern**: Pluggable embeddings and vector stores
- **Local-First**: Privacy by default with optional cloud embeddings

See [ARCHITECTURE.md](./ARCHITECTURE.md) for detailed system design, component diagrams, performance characteristics, and security architecture.

---

## 🧪 Development

### Setup

```bash
# Clone repository
git clone https://github.com/yourusername/semantic-mcp-search.git
cd semantic-mcp-search

# Create virtual environment
python -m venv .venv
source .venv/bin/activate  # Windows: .venv\Scripts\activate

# Install with dev dependencies
pip install -e ".[dev]"

# Install pre-commit hooks
pre-commit install
```

### Testing

```bash
# Run all tests
pytest

# Run with coverage
pytest --cov=src/semantic_code_search --cov-report=html

# Run only unit tests
pytest -m unit

# Skip slow tests
pytest -m "not slow"

# Run specific test
pytest tests/test_searcher.py::test_search_returns_results
```

### Code Quality

```bash
# Format code
ruff format src/ tests/

# Lint code
ruff check src/ tests/

# Type checking
mypy src/

# Security scan
bandit -r src/

# Pre-commit hooks (run all checks)
pre-commit run --all-files
```

### Project Structure

```
semantic-mcp-search/
├── src/semantic_search/
│   ├── __init__.py
│   ├── config.py              # Configuration management
│   ├── main.py                # Entry point
│   ├── cli.py                 # CLI interface
│   ├── server/
│   │   └── tools.py           # MCP tool implementations
│   ├── searcher.py            # Search pipeline
│   ├── indexer/               # Indexing engine
│   │   ├── merkle.py          # Merkle tree
│   │   ├── watcher.py         # File watcher
│   │   └── scheduler.py       # Task scheduler
│   ├── processing/
│   │   ├── chunker.py         # Tree-sitter chunker
│   │   └── ast_parser.py      # AST parser
│   ├── embeddings/            # Embedding providers
│   │   ├── base.py            # Abstract interface
│   │   ├── openai.py          # OpenAI provider
│   │   ├── c2llm.py           # C2LLM provider
│   │   └── huggingface.py     # HuggingFace provider
│   └── storage/               # Vector stores
│       ├── base.py            # Abstract interface
│       ├── chromadb_store.py  # ChromaDB implementation
│       └── factory.py         # Backend selection
├── tests/
│   ├── unit/                  # Unit tests
│   ├── integration/           # Integration tests
│   └── conftest.py            # Test fixtures
├── docs/
│   ├── api.md                 # API reference
│   ├── user-guide.md          # User guide
│   └── openapi.yaml           # OpenAPI specification
├── ARCHITECTURE.md            # System architecture
├── CONTRIBUTING.md            # Contribution guidelines
├── README.md
└── pyproject.toml
```

---

## 🤝 Contributing

We welcome contributions! Please see [CONTRIBUTING.md](./CONTRIBUTING.md) for guidelines.

### Ways to Contribute

- 🐛 Report bugs
- 💡 Suggest new features
- 📝 Improve documentation
- 🔧 Submit pull requests
- 🧪 Write tests
- 👀 Review pull requests

### Development Guidelines

- Write tests for all new features (>80% coverage required)
- Follow PEP 8 style guide (enforced by ruff)
- Add type hints to all functions (enforced by mypy)
- Update documentation for API changes
- Keep PRs focused and atomic

---

## 📊 Performance

| Metric | Target | Notes |
|--------|--------|-------|
| **Search Latency** | <200ms | Uncached, full pipeline |
| **Cached Search** | <10ms | LRU cache hit |
| **Indexing** | <100ms | Small file, incremental |
| **Memory Usage** | ~1GB | With C2LLM model |
| **Storage** | ~90MB | Per 10K files |

See [ARCHITECTURE.md](./ARCHITECTURE.md#-performance-characteristics) for detailed performance analysis.

---

## 🔐 Security

- **Input Validation**: All inputs validated with Pydantic
- **Path Traversal Protection**: Restricted to configured codebase path
- **API Key Security**: Environment variables, .gitignore
- **Local-First**: Code never leaves machine (with local embeddings)
- **No Telemetry**: No analytics or tracking by default

See [ARCHITECTURE.md](./ARCHITECTURE.md#-security-architecture) for threat model and security measures.

---

## 🗺️ Roadmap

### v0.2 (Next Release)
- [ ] Hybrid search (semantic + keyword)
- [ ] Query suggestions/autocomplete
- [ ] Multi-file context search
- [ ] Search result ranking feedback

### v0.3
- [ ] Cross-encoder reranking
- [ ] Code diff search
- [ ] Repository-level search
- [ ] Search analytics dashboard

### v1.0
- [ ] Multi-user support
- [ ] Team collaboration features
- [ ] IDE integrations (VS Code, JetBrains)
- [ ] Advanced filtering (author, time, branch)

---

## 📄 License

MIT License - see [LICENSE](./LICENSE) for details.

---

## 🙏 Acknowledgments

Built with amazing open-source tools:

- [Model Context Protocol](https://modelcontextprotocol.io/) - AI agent communication
- [Tree-sitter](https://tree-sitter.github.io/tree-sitter/) - AST parsing
- [ChromaDB](https://www.trychroma.com/) - Vector database
- [C2LLM](https://github.com/codefuse-ai/C2LLM) - Code embeddings
- [FastAPI](https://fastapi.tiangolo.com/) - Web framework
- [Pydantic](https://docs.pydantic.dev/) - Data validation

---

## 📞 Support

- **Issues**: [GitHub Issues](https://github.com/yourusername/semantic-mcp-search/issues)
- **Discussions**: [GitHub Discussions](https://github.com/yourusername/semantic-mcp-search/discussions)
- **Documentation**: [docs/](./docs/)

---

<div align="center">

**⭐ Star us on GitHub** — it helps!

Made with ❤️ by the Semantic MCP Search community

</div>