|
| 1 | +# Context Engine Architecture |
| 2 | + |
| 3 | +## Overview |
| 4 | + |
| 5 | +Context Engine is a production-ready MCP (Model Context Protocol) retrieval stack that unifies code indexing, hybrid search, and optional LLM decoding. It enables teams to ship context-aware AI agents by providing sophisticated semantic and lexical search capabilities with dual-transport compatibility. |
| 6 | + |
| 7 | +## Core Principles |
| 8 | + |
| 9 | +- **Research-Grade Retrieval**: Implements ReFRAG-inspired micro-chunking and span budgeting |
| 10 | +- **Dual-Transport Support**: Supports both SSE (legacy) and HTTP RMCP (modern) protocols |
| 11 | +- **Performance-First**: Intelligent caching, connection pooling, and async I/O patterns |
| 12 | +- **Production-Ready**: Comprehensive health checks, monitoring, and operational tooling |
| 13 | + |
| 14 | +## System Architecture |
| 15 | + |
| 16 | +### Component Diagram |
| 17 | + |
| 18 | +``` |
| 19 | +┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ |
| 20 | +│ Client Apps │◄──►│ MCP Servers │◄──►│ Qdrant DB │ |
| 21 | +│ (IDE, CLI, Web) │ │ (SSE + HTTP) │ │ (Vector Store) │ |
| 22 | +└─────────────────┘ └─────────────────┘ └─────────────────┘ |
| 23 | + │ |
| 24 | + ▼ |
| 25 | + ┌─────────────────┐ |
| 26 | + │ LLM Decoder │ |
| 27 | + │ (llama.cpp) │ |
| 28 | + │ (Optional) │ |
| 29 | + └─────────────────┘ |
| 30 | +``` |
| 31 | + |
| 32 | +## Core Components |
| 33 | + |
| 34 | +### 1. MCP Servers |
| 35 | + |
| 36 | +#### Memory Server (`scripts/mcp_memory_server.py`) |
| 37 | +- **Purpose**: Knowledge base storage and retrieval |
| 38 | +- **Transport**: SSE (port 8000) + HTTP RMCP (port 8002) |
| 39 | +- **Key Features**: |
| 40 | + - Structured memory storage with rich metadata |
| 41 | + - Hybrid search (dense + lexical) |
| 42 | + - Dual vector support for embedding and lexical hashes |
| 43 | + - Automatic collection management |
| 44 | + |
| 45 | +#### Indexer Server (`scripts/mcp_indexer_server.py`) |
| 46 | +- **Purpose**: Code search, indexing, and management |
| 47 | +- **Transport**: SSE (port 8001) + HTTP RMCP (port 8003) |
| 48 | +- **Key Features**: |
| 49 | + - Hybrid code search with multiple filtering options |
| 50 | + - ReFRAG-inspired micro-chunking (16-token windows) |
| 51 | + - Context-aware Q&A with local LLM integration |
| 52 | + - Workspace and collection management |
| 53 | + - Live indexing and pruning capabilities |
| 54 | + |
| 55 | +### 2. Search Pipeline |
| 56 | + |
| 57 | +#### Hybrid Search Engine (`scripts/hybrid_search.py`) |
| 58 | +- **Multi-Vector Architecture**: |
| 59 | + - **Dense Vectors**: Semantic embeddings (BAAI/bge-base-en-v1.5) |
| 60 | + - **Lexical Vectors**: BM25-style hashing (4096 dimensions) |
| 61 | + - **Mini Vectors**: ReFRAG gating (64 dimensions, optional) |
| 62 | + |
| 63 | +- **Retrieval Process**: |
| 64 | + 1. **Query Expansion**: Generate multiple query variations |
| 65 | + 2. **Parallel Search**: Dense + lexical search with RRF fusion |
| 66 | + 3. **Optional Reranking**: Cross-encoder neural reranking |
| 67 | + 4. **Result Assembly**: Format with citations and metadata |
| 68 | + |
| 69 | +- **Advanced Features**: |
| 70 | + - Request deduplication |
| 71 | + - Intelligent caching (multi-policy: LRU, LFU, TTL, FIFO) |
| 72 | + - Connection pooling to Qdrant |
| 73 | + - Batch processing support |
| 74 | + |
| 75 | +#### ReFRAG Implementation |
| 76 | +- **Micro-chunking**: Token-level windows (16 tokens, 8 stride) |
| 77 | +- **Span Budgeting**: Global token budget management |
| 78 | +- **Gate-First Filtering**: Mini-vector pre-filtering for efficiency |
| 79 | + |
| 80 | +### 3. Storage Layer |
| 81 | + |
| 82 | +#### Qdrant Vector Database |
| 83 | +- **Primary Storage**: Embeddings and metadata |
| 84 | +- **Collection Management**: Automatic creation and configuration |
| 85 | +- **Named Vectors**: Separate storage for different embedding types |
| 86 | +- **Performance**: HNSW indexing for fast approximate nearest neighbor search |
| 87 | + |
| 88 | +#### Unified Cache System (`scripts/cache_manager.py`) |
| 89 | +- **Eviction Policies**: LRU, LFU, TTL, FIFO |
| 90 | +- **Memory Management**: Configurable size limits and monitoring |
| 91 | +- **Thread Safety**: Proper locking for concurrent access |
| 92 | +- **Statistics Tracking**: Hit rates, memory usage, eviction counts |
| 93 | + |
| 94 | +### 4. Supporting Infrastructure |
| 95 | + |
| 96 | +#### Async Subprocess Manager (`scripts/async_subprocess_manager.py`) |
| 97 | +- **Process Management**: Async subprocess execution with resource cleanup |
| 98 | +- **Connection Pooling**: Reused HTTP connections |
| 99 | +- **Timeout Handling**: Configurable timeouts with graceful degradation |
| 100 | +- **Resource Tracking**: Active process monitoring and statistics |
| 101 | + |
| 102 | +#### Deduplication System (`scripts/deduplication.py`) |
| 103 | +- **Request Deduplication**: Prevent redundant processing |
| 104 | +- **Cache Integration**: Works with unified cache system |
| 105 | +- **Performance Impact**: Significant reduction in duplicate work |
| 106 | + |
| 107 | +#### Semantic Expansion (`scripts/semantic_expansion.py`) |
| 108 | +- **Query Enhancement**: LLM-assisted query variation generation |
| 109 | +- **Local LLM Integration**: llama.cpp for offline expansion |
| 110 | +- **Caching**: Expanded query results cached for reuse |
| 111 | + |
| 112 | +## Data Flow Architecture |
| 113 | + |
| 114 | +### Search Request Flow |
| 115 | +``` |
| 116 | +1. Client Query → MCP Server |
| 117 | +2. Query Expansion (optional) → Multiple Query Variations |
| 118 | +3. Parallel Execution → Dense Search + Lexical Search |
| 119 | +4. RRF Fusion → Combined Results |
| 120 | +5. Reranking (optional) → Enhanced Relevance |
| 121 | +6. Result Formatting → Structured Response with Citations |
| 122 | +7. Return to Client → MCP Protocol Response |
| 123 | +``` |
| 124 | + |
| 125 | +### Indexing Flow |
| 126 | +``` |
| 127 | +1. File Change Detection → File System Watcher |
| 128 | +2. Content Processing → Tokenization + Chunking |
| 129 | +3. Embedding Generation → Model Inference |
| 130 | +4. Vector Creation → Dense + Lexical + Mini |
| 131 | +5. Metadata Assembly → Path, symbols, language, etc. |
| 132 | +6. Batch Upsert → Qdrant Storage |
| 133 | +7. Cache Updates → Local Cache Refresh |
| 134 | +``` |
| 135 | + |
| 136 | +## Configuration Architecture |
| 137 | + |
| 138 | +### Environment-Based Configuration |
| 139 | +- **Docker-Native**: All configuration via environment variables |
| 140 | +- **Development Support**: Local .env file configuration |
| 141 | +- **Production Ready**: External secret management integration |
| 142 | + |
| 143 | +### Key Configuration Areas |
| 144 | +- **Service Configuration**: Ports, hosts, transport protocols |
| 145 | +- **Model Configuration**: Embedding models, reranker settings |
| 146 | +- **Performance Tuning**: Cache sizes, batch sizes, timeouts |
| 147 | +- **Feature Flags**: Experimental features, debug modes |
| 148 | + |
| 149 | +## Transport Layer Architecture |
| 150 | + |
| 151 | +### Dual-Transport Design |
| 152 | +- **SSE (Server-Sent Events)**: Legacy client compatibility |
| 153 | +- **HTTP RMCP**: Modern JSON-RPC over HTTP |
| 154 | +- **Simultaneous Operation**: Both protocols can run together |
| 155 | +- **Automatic Fallback**: Graceful degradation when transport fails |
| 156 | + |
| 157 | +### MCP Protocol Implementation |
| 158 | +- **FastMCP Framework**: Modern MCP server implementation |
| 159 | +- **Tool Registry**: Automatic tool discovery and registration |
| 160 | +- **Health Endpoints**: `/readyz` and `/tools` endpoints |
| 161 | +- **Error Handling**: Structured error responses and logging |
| 162 | + |
| 163 | +## Performance Architecture |
| 164 | + |
| 165 | +### Caching Strategy |
| 166 | +- **Multi-Level Caching**: Embedding cache, search cache, expansion cache |
| 167 | +- **Intelligent Invalidation**: TTL-based and LRU eviction |
| 168 | +- **Memory Management**: Configurable limits and monitoring |
| 169 | +- **Performance Monitoring**: Hit rates, response times, memory usage |
| 170 | + |
| 171 | +### Concurrency Model |
| 172 | +- **Async I/O**: Non-blocking operations throughout |
| 173 | +- **Connection Pooling**: Reused connections to external services |
| 174 | +- **Batch Processing**: Efficient bulk operations |
| 175 | +- **Resource Management**: Proper cleanup and resource limits |
| 176 | + |
| 177 | +## Security Architecture |
| 178 | + |
| 179 | +### Isolation and Safety |
| 180 | +- **Container-Based**: Docker isolation for all services |
| 181 | +- **Network Segmentation**: Internal service communication |
| 182 | +- **Input Validation**: Comprehensive parameter validation |
| 183 | +- **Resource Limits**: Configurable timeouts and memory limits |
| 184 | + |
| 185 | +### Data Protection |
| 186 | +- **No Hardcoded Secrets**: Environment-based configuration |
| 187 | +- **API Key Management**: External secret manager integration |
| 188 | +- **Audit Logging**: Structured logging for security events |
| 189 | + |
| 190 | +## Operational Architecture |
| 191 | + |
| 192 | +### Health Monitoring |
| 193 | +- **Service Health**: `/readyz` endpoints for all services |
| 194 | +- **Tool Availability**: Dynamic tool listing and status |
| 195 | +- **Performance Metrics**: Response times, cache statistics |
| 196 | +- **Error Tracking**: Structured error logging and alerting |
| 197 | + |
| 198 | +### Deployment Patterns |
| 199 | +- **Docker Compose**: Multi-service orchestration |
| 200 | +- **Environment Parity**: Development ↔ Production consistency |
| 201 | +- **Graceful Shutdown**: Proper resource cleanup on termination |
| 202 | +- **Rolling Updates**: Zero-downtime deployment support |
| 203 | + |
| 204 | +## Extensibility Architecture |
| 205 | + |
| 206 | +### Plugin System |
| 207 | +- **MCP Tool Extension**: Easy addition of new tools |
| 208 | +- **Transport Flexibility**: Support for future MCP transports |
| 209 | +- **Model Pluggability**: Support for different embedding models |
| 210 | +- **Storage Abstraction**: Potential for alternative vector stores |
| 211 | + |
| 212 | +### Configuration Extension |
| 213 | +- **Environment-Driven**: Easy configuration via environment variables |
| 214 | +- **Feature Flags**: Experimental feature toggling |
| 215 | +- **A/B Testing**: Multiple configuration variants support |
| 216 | + |
| 217 | +This architecture enables Context Engine to serve as a production-ready, scalable context layer for AI applications while maintaining the flexibility to evolve with changing requirements and technologies. |
0 commit comments