# Professional Modular Architecture
## ๐ Project Structure
```
Expense Tracker/
โโโ main_new.py # Entry point (NEW modular version)
โโโ main.py # Old monolithic version (backup)
โโโ requirements.txt # Python dependencies
โโโ .env # Environment variables
โโโ README.md # Documentation
โ
โโโ data/ # Database files
โ โโโ company.db # SQLite database
โ โโโ .gitkeep
โ
โโโ config/ # Configuration files
โ โโโ departments.json # Department definitions
โ
โโโ src/ # Source code (NEW)
โ โโโ __init__.py
โ โโโ config.py # Centralized configuration
โ โ
โ โโโ database/ # Database layer
โ โ โโโ __init__.py
โ โ โโโ connection.py # Database connections
โ โ โโโ schema.py # Schema initialization
โ โ โโโ queries.py # Helper queries
โ โ
โ โโโ models/ # Data models
โ โ โโโ __init__.py
โ โ โโโ employee.py # Employee model
โ โ โโโ department.py # Department model
โ โ โโโ expense.py # Expense model
โ โ โโโ performance.py # Performance model
โ โ
โ โโโ services/ # Business logic
โ โ โโโ __init__.py
โ โ โโโ employee_service.py # Employee operations
โ โ โโโ department_service.py # Department operations
โ โ โโโ expense_service.py # Expense operations
โ โ โโโ performance_service.py # Performance operations
โ โ โโโ ai_service.py # AI analysis
โ โ
โ โโโ tools/ # MCP tool wrappers
โ โ โโโ __init__.py
โ โ โโโ employee_tools.py # Employee MCP tools
โ โ โโโ department_tools.py # Department MCP tools
โ โ โโโ expense_tools.py # Expense MCP tools
โ โ โโโ performance_tools.py # Performance MCP tools
โ โ โโโ ai_tools.py # AI MCP tools
โ โ
โ โโโ utils/ # Utility functions
โ โโโ __init__.py
โ โโโ validators.py # Input validation
โ โโโ formatters.py # Output formatting
โ
โโโ scripts/ # Utility scripts
โ โโโ populate_data.py # Database population
โ โโโ db_viewer.py # Database viewer
โ
โโโ docs/ # Documentation
โโโ ARCHITECTURE.md # This file
โโโ QUICK_REFERENCE.md
โโโ GETTING_STARTED.md
```
## ๐๏ธ Architecture Layers
### 1. **Entry Point Layer** (`main_new.py`)
- Server initialization
- Tool registration
- Startup configuration
### 2. **Tool Layer** (`src/tools/`)
- MCP tool wrappers
- Input/output formatting
- Tool descriptions for Claude
### 3. **Service Layer** (`src/services/`)
- Business logic
- Data validation
- Transaction management
- Error handling
### 4. **Database Layer** (`src/database/`)
- Database connections
- Schema management
- Query helpers
- Data access
### 5. **Model Layer** (`src/models/`)
- Data structures
- Type definitions
- Model validation
### 6. **Utils Layer** (`src/utils/`)
- Validation functions
- Formatters
- Helper utilities
## ๐ Request Flow
```
Claude Desktop
โ
MCP Tool (src/tools/)
โ
Service Layer (src/services/)
โ
Database Layer (src/database/)
โ
SQLite Database (data/company.db)
```
## โจ Benefits of This Structure
### 1. **Separation of Concerns**
- Each module has a single responsibility
- Easy to locate and fix bugs
- Clear boundaries between layers
### 2. **Maintainability**
- Small, focused files (100-300 lines each)
- Easy to understand and modify
- No code duplication
### 3. **Testability**
- Each component can be tested independently
- Mock dependencies easily
- Unit test each service
### 4. **Scalability**
- Add new features without touching existing code
- Easy to add new tools or services
- Modular imports
### 5. **Debugging**
- Clear error paths
- Isolated components
- Easy to trace issues
## ๐ Module Responsibilities
| Module | Responsibility | Size |
|--------|---------------|------|
| `config.py` | Configuration management | ~40 lines |
| `database/connection.py` | DB connections | ~20 lines |
| `database/schema.py` | Schema initialization | ~80 lines |
| `database/queries.py` | Helper queries | ~60 lines |
| `services/employee_service.py` | Employee business logic | ~250 lines |
| `services/department_service.py` | Department business logic | ~200 lines |
| `services/expense_service.py` | Expense business logic | ~180 lines |
| `services/performance_service.py` | Performance business logic | ~80 lines |
| `services/ai_service.py` | AI analysis logic | ~150 lines |
| `tools/*.py` | MCP tool wrappers | ~50-100 lines each |
## ๐ง How to Extend
### Adding a New Feature
1. **Add Model** (if needed)
```python
# src/models/new_feature.py
@dataclass
class NewFeature:
field1: str
field2: int
```
2. **Add Service**
```python
# src/services/new_feature_service.py
class NewFeatureService:
@staticmethod
async def create_feature(...):
# Business logic here
```
3. **Add Tool Wrapper**
```python
# src/tools/new_feature_tools.py
def register_new_feature_tools(mcp):
@mcp.tool(name="new_tool")
async def new_tool(...):
result = await NewFeatureService.create_feature(...)
return json.dumps(result)
```
4. **Register in main_new.py**
```python
from src.tools import register_new_feature_tools
register_new_feature_tools(mcp)
```
## ๐ Usage
### Running the New Modular Server
```bash
# Activate virtual environment
.\.venv\Scripts\Activate.ps1
# Run the new modular server
python main_new.py
```
### Claude Desktop Configuration
Update `claude_desktop_config.json`:
```json
{
"mcpServers": {
"expense-tracker": {
"command": "python",
"args": [
"C:\\Users\\VH0000812\\Desktop\\Expense Tracker\\main_new.py"
],
"cwd": "C:\\Users\\VH0000812\\Desktop\\Expense Tracker"
}
}
}
```
## ๐ Debugging Guide
### Finding Issues
1. **Tool not working?**
โ Check `src/tools/` for tool wrapper
โ Verify registration in `main_new.py`
2. **Business logic error?**
โ Check `src/services/` for the relevant service
โ Add logging to trace the issue
3. **Database error?**
โ Check `src/database/queries.py`
โ Verify connection in `connection.py`
4. **Configuration issue?**
โ Check `src/config.py`
โ Verify `.env` file
### Adding Debug Logging
```python
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
# In any service
logger.debug(f"Processing request: {data}")
```
## ๐ Comparison: Old vs New
| Aspect | Old (main.py) | New (Modular) |
|--------|--------------|---------------|
| **File Count** | 1 file (1088 lines) | 25+ files (~100-250 lines each) |
| **Debugging** | Scroll through 1000 lines | Jump to specific module |
| **Adding Features** | Edit monolith | Add new module |
| **Testing** | Test entire file | Test individual modules |
| **Team Work** | Merge conflicts | Parallel development |
| **Code Reuse** | Copy-paste | Import module |
## ๐ฏ Best Practices
1. **Keep services focused** - One service per entity type
2. **Use type hints** - Better IDE support and documentation
3. **Handle errors gracefully** - Return status dicts, don't crash
4. **Document functions** - Docstrings for all public methods
5. **Validate inputs** - Check data before database operations
6. **Log important events** - Debug issues in production
## ๐ฎ Future Improvements
1. **Add Logging** - Structured logging with levels
2. **Add Tests** - Unit tests for each service
3. **Add Caching** - Cache frequent queries
4. **Add Migrations** - Database schema versioning
5. **Add API Layer** - REST API alongside MCP
6. **Add Monitoring** - Performance metrics and alerts