Spaces:
Sleeping
Sleeping
File size: 16,485 Bytes
32dc112 |
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 |
# ๐๏ธ System Architecture
MissionControlMCP system design and architecture documentation.
---
## ๐ High-Level Architecture
```
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Client Layer โ
โ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ โ
โ โ Claude โ โ Custom โ โ Other MCP โ โ
โ โ Desktop โ โ Client โ โ Clients โ โ
โ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ MCP Protocol (stdio)
โโโโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ MCP Server Layer โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ mcp_server.py โ โ
โ โ โข Tool Registration โ โ
โ โ โข Request Routing โ โ
โ โ โข Response Formatting โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Business Logic Layer โ
โ โโโโโโโโโโโโฌโโโโโโโโโโโฌโโโโโโโโโโโฌโโโโโโโโโโโ โ
โ โ PDF โ Text โ Web โ RAG โ โ
โ โ Reader โ Extract โ Fetcher โ Search โ โ
โ โโโโโโโโโโโโผโโโโโโโโโโโผโโโโโโโโโโโผโโโโโโโโโโโค โ
โ โ Data โ File โ Email โ KPI โ โ
โ โ Visual โ Convert โ Classify โ Generate โ โ
โ โโโโโโโโโโโโดโโโโโโโโโโโดโโโโโโโโโโโดโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Utility Layer โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ โข helpers.py - Text processing utilities โ โ
โ โ โข rag_utils.py - Vector search & FAISS โ โ
โ โ โข schemas.py - Pydantic models โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
```
---
## ๐งฉ Component Architecture
### 1. MCP Server (`mcp_server.py`)
**Responsibilities:**
- Register all 8 tools with MCP SDK
- Handle incoming tool requests
- Route requests to appropriate tool functions
- Format and return responses
- Error handling and logging
**Flow:**
```
Client Request โ MCP Protocol โ Server โ Tool โ Response โ Client
```
**Code Structure:**
```python
# Tool Registration
server.register_tool(name, description, input_schema)
# Request Handler
async def call_tool(name, arguments):
if name == "pdf_reader":
return await pdf_reader.read_pdf(**arguments)
elif name == "text_extractor":
return await text_extractor.extract_text(**arguments)
# ... other tools
# Server Startup
async with stdio_server() as (read_stream, write_stream):
await server.run(read_stream, write_stream)
```
---
### 2. Tool Layer (`tools/`)
Each tool is independent and follows this pattern:
**Tool Structure:**
```python
"""
Tool Name - Description
"""
import logging
from typing import Dict, Any
logger = logging.getLogger(__name__)
def tool_function(param: str) -> Dict[str, Any]:
"""
Tool description.
Args:
param: Parameter description
Returns:
Standardized result dictionary
"""
try:
# Validation
if not param:
raise ValueError("Invalid input")
# Processing
result = process_data(param)
# Return standardized format
return {
"success": True,
"data": result,
"metadata": {}
}
except Exception as e:
logger.error(f"Error: {e}")
raise
```
**Tool Independence:**
- Each tool is self-contained
- No dependencies between tools
- Can be tested individually
- Easy to add/remove tools
---
### 3. Utility Layer (`utils/`)
**helpers.py - Text Processing:**
```python
โข clean_text() - Remove extra whitespace
โข extract_keywords() - NLP keyword extraction
โข chunk_text() - Text splitting with overlap
โข validate_url() - URL validation
```
**rag_utils.py - Vector Search:**
```python
โข SimpleRAGStore - FAISS-based vector database
โข semantic_search() - Sentence transformer embeddings
โข create_rag_store() - Initialize vector store
```
**Models (models/schemas.py):**
```python
โข Pydantic models for type validation
โข Input/output schemas
โข Data validation
```
---
## ๐ Data Flow
### Request Flow
```
1. Client sends MCP request
โ
2. mcp_server.py receives request
โ
3. Server validates input schema
โ
4. Server routes to tool function
โ
5. Tool processes data
โ
6. Tool returns result dict
โ
7. Server formats MCP response
โ
8. Client receives response
```
### Example: PDF Reading Flow
```
Client: "Read this PDF"
โ
MCP Server: Receives pdf_reader request
โ
pdf_reader.py: read_pdf(file_path)
โ
PyPDF2: Extract text from pages
โ
Return: {text, pages, metadata}
โ
MCP Server: Format response
โ
Client: Receives extracted text
```
---
## ๐๏ธ Project Structure
```
mission_control_mcp/
โ
โโโ mcp_server.py # MCP server entry point
โ
โโโ tools/ # 8 independent tools
โ โโโ pdf_reader.py # PDF text extraction
โ โโโ text_extractor.py # Text processing (4 ops)
โ โโโ web_fetcher.py # Web scraping
โ โโโ rag_search.py # Semantic search
โ โโโ data_visualizer.py # Chart generation
โ โโโ file_converter.py # File format conversion
โ โโโ email_intent_classifier.py # Email classification
โ โโโ kpi_generator.py # Business metrics
โ
โโโ utils/ # Shared utilities
โ โโโ helpers.py # Text processing helpers
โ โโโ rag_utils.py # Vector search utilities
โ
โโโ models/ # Data models
โ โโโ schemas.py # Pydantic schemas
โ
โโโ examples/ # Sample test data
โ โโโ sample_report.txt # Business report
โ โโโ business_data.csv # Financial data
โ โโโ sample_email_*.txt # Email samples
โ โโโ sample_documents.txt # RAG search docs
โ
โโโ app.py # Gradio web interface
โโโ demo.py # Demo & test suite
โ
โโโ docs/ # Documentation
โ โโโ README.md # Main documentation
โ โโโ API.md # API reference
โ โโโ EXAMPLES.md # Use cases
โ โโโ TESTING.md # Testing guide
โ โโโ ARCHITECTURE.md # This file
โ โโโ CONTRIBUTING.md # Contribution guide
โ
โโโ requirements.txt # Python dependencies
โโโ .gitignore # Git ignore rules
โโโ LICENSE # MIT License
```
---
## ๐ Integration Points
### MCP Protocol Integration
```python
from mcp.server import Server
from mcp.types import Tool, TextContent
# Create server
server = Server("mission-control")
# Register tool
@server.tool()
async def pdf_reader(file_path: str) -> str:
result = read_pdf(file_path)
return json.dumps(result)
# Run server
await server.run(stdin, stdout)
```
### Claude Desktop Integration
**Configuration:**
```json
{
"mcpServers": {
"mission-control": {
"command": "python",
"args": ["path/to/mcp_server.py"]
}
}
}
```
**Communication:**
```
Claude Desktop โโ MCP Protocol โโ mcp_server.py โโ Tools
```
---
## ๐ Scalability Design
### Horizontal Scaling
**Current:** Single-process server
**Future:** Multi-process with load balancing
```
Load Balancer
โ
โโโโโโโโโโโโผโโโโโโโโโโโ
โ โ โ
Server 1 Server 2 Server 3
โ โ โ
โโโโโโโโโโโโดโโโโโโโโโโโ
Tools
```
### Caching Strategy
**Implemented:**
- RAG model caching (sentence transformers)
- NLTK data caching
**Future Improvements:**
- Redis for result caching
- Database for document storage
- CDN for static assets
---
## ๐ Security Architecture
### Input Validation
```python
# Pydantic schemas
from pydantic import BaseModel, validator
class PDFReaderInput(BaseModel):
file_path: str
@validator('file_path')
def validate_path(cls, v):
if not Path(v).exists():
raise ValueError("File not found")
return v
```
### Error Handling
```python
try:
result = tool_function(input)
except FileNotFoundError:
return {"error": "File not found", "code": 404}
except ValueError:
return {"error": "Invalid input", "code": 400}
except Exception:
return {"error": "Internal error", "code": 500}
```
### Authentication
**Current:** None (local tool execution)
**Production Considerations:**
- API key authentication
- Rate limiting
- Request logging
- User permissions
---
## ๐ Performance Characteristics
### Tool Performance
| Tool | Avg Time | Memory | Notes |
|------|----------|--------|-------|
| PDF Reader | 1s | 50MB | Depends on PDF size |
| Text Extractor | 0.5s | 10MB | Fast text processing |
| Web Fetcher | 2-3s | 20MB | Network dependent |
| RAG Search | 2.5s* | 200MB | *First run (model load) |
| RAG Search | 0.5s | 200MB | Subsequent runs |
| Data Visualizer | 1.2s | 30MB | Chart generation |
| File Converter | 1-2s | 50MB | File size dependent |
| Email Classifier | 0.1s | 5MB | Very fast |
| KPI Generator | 0.3s | 10MB | Quick calculations |
### Bottlenecks
1. **RAG Search** - Initial model loading (~2s)
- Solution: Keep model in memory
2. **Web Fetcher** - Network latency
- Solution: Async requests, caching
3. **PDF Reader** - Large files
- Solution: Stream processing
---
## ๐ State Management
### Stateless Design
Each tool request is independent:
- No session state
- No user context
- Pure function design
**Benefits:**
- Easy scaling
- No state synchronization
- Simple debugging
- High availability
### RAG Store State
Exception: RAG search maintains in-memory vector store:
```python
class SimpleRAGStore:
def __init__(self):
self.documents = []
self.index = None # FAISS index
```
**Lifecycle:**
- Created on first search
- Persists during server lifetime
- Cleared on server restart
---
## ๐งช Testing Architecture
### Test Pyramid
```
โโโโโโโโโโโโโโโ
โ E2E Tests โ (MCP integration)
โโโโโโโโโโโโโโโค
โ Integration โ (Tool combinations)
โโโโโโโโโโโโโโโค
โ Unit Tests โ (Individual functions)
โโโโโโโโโโโโโโโ
```
### Test Coverage
- **Unit Tests:** Test each function independently
- **Integration Tests:** Test tool interactions
- **MCP Tests:** Test server communication
- **Sample Tests:** Test with real data
---
## ๐ฆ Dependency Management
### Core Dependencies
```
MCP SDK (>=1.0.0)
โโโ stdio communication
โโโ Tool registration
Processing Libraries
โโโ PyPDF2 (PDF reading)
โโโ BeautifulSoup4 (HTML parsing)
โโโ Pandas (Data processing)
โโโ Matplotlib (Visualization)
ML/NLP Libraries
โโโ scikit-learn (Text processing)
โโโ NLTK (Keyword extraction)
โโโ sentence-transformers (Embeddings)
โโโ FAISS (Vector search)
```
### Optional Dependencies
- faiss-cpu: Can use faiss-gpu on GPU systems
- reportlab: Optional for PDF generation
---
## ๐ฎ Future Architecture Improvements
### Planned Enhancements
1. **Database Integration**
```
PostgreSQL for persistent storage
Redis for caching
```
2. **Async Processing**
```python
async def process_pdf(file_path: str):
# Async PDF processing
return await asyncio.to_thread(read_pdf, file_path)
```
3. **Microservices**
```
Each tool as separate service
API gateway for routing
Service mesh for communication
```
4. **Monitoring**
```
Prometheus metrics
Grafana dashboards
Error tracking (Sentry)
```
---
## ๐ Design Principles
### SOLID Principles
- **Single Responsibility:** Each tool does one thing
- **Open/Closed:** Easy to add new tools
- **Liskov Substitution:** Tools are interchangeable
- **Interface Segregation:** Minimal tool interfaces
- **Dependency Inversion:** Tools depend on abstractions
### Clean Architecture
- **Independent of Frameworks:** Core logic separate from MCP
- **Testable:** Can test without MCP server
- **Independent of UI:** Works with any MCP client
- **Independent of Database:** No database coupling
---
## ๐ฏ Architectural Goals
โ
**Achieved:**
- Modular design
- Easy to extend
- Well-documented
- Testable
- Production-ready
๐ **In Progress:**
- Performance optimization
- Enhanced caching
- Better error handling
๐ฏ **Future:**
- Multi-tenancy
- Distributed processing
- Advanced monitoring
- Auto-scaling
---
**MissionControlMCP Architecture Documentation v1.0** ๐๏ธ
|