# 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