# Task 1: MCP Server Decomposition
## Overview
**Priority**: High
**Goal**: Break down the monolithic 1000+ line `commitizen_server.py` into 6 focused modules
**Target**: No file over 300 lines, each module ~150-200 lines
**Status**: ✅ COMPLETE
## Current Problem
The `src/commit_helper_mcp/commitizen_server.py` file contains:
- 1000+ lines of code
- 19 MCP tools mixed together
- 3 MCP resources
- Global service initialization
- Mixed concerns and responsibilities
This makes the code:
- Hard to navigate and understand
- Difficult to test individual components
- Challenging for multiple developers to work on
- Prone to merge conflicts
## Target Structure
```
src/commit_helper_mcp/server/
├── __init__.py
├── base_server.py # FastMCP setup and common utilities
├── message_tools.py # 4 message-related MCP tools
├── git_tools.py # 7 git operation MCP tools
├── workflow_tools.py # 3 workflow MCP tools
├── enhanced_tools.py # 5 enhanced analysis MCP tools
└── resources.py # 3 MCP resources
```
## Implementation Steps
### Step 1: Create Base Server Module
**File**: `src/commit_helper_mcp/server/base_server.py`
**Responsibilities**:
- FastMCP server initialization
- Global service instance management
- Common utilities and decorators
- Shared imports and logging setup
**Content**:
```python
"""
Base MCP Server Setup
Common utilities and FastMCP initialization for the Commitizen MCP Connector.
"""
import logging
from mcp.server.fastmcp import FastMCP
from ..commitizen_service import CommitzenService
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Initialize FastMCP server
mcp = FastMCP("Commitizen MCP Connector")
# Initialize global service instance with environment variable support
try:
service = CommitzenService() # Will check COMMITIZEN_REPO_PATH automatically
logger.info("CommitzenService initialized successfully")
except Exception as e:
logger.error(f"Failed to initialize CommitzenService: {e}")
raise
# Common utilities and decorators can be added here
```
### Step 2: Extract Message Tools
**File**: `src/commit_helper_mcp/server/message_tools.py`
**Tools to Extract** (4 tools):
- `generate_commit_message`
- `create_commit_message`
- `validate_commit_message`
- `get_commit_types`
**Dependencies**:
- Import `mcp` and `service` from `base_server`
- Import necessary types and exceptions
### Step 3: Extract Git Tools
**File**: `src/commit_helper_mcp/server/git_tools.py`
**Tools to Extract** (7 tools):
- `get_git_status`
- `preview_git_commit`
- `execute_git_commit`
- `generate_and_commit`
- `validate_commit_readiness`
- `stage_files_and_commit`
- `get_git_implementation_info`
### Step 4: Extract Workflow Tools
**File**: `src/commit_helper_mcp/server/workflow_tools.py`
**Tools to Extract** (3 tools):
- `commit_workflow_step`
- `get_commit_questions`
- `health_check`
- `refresh_configuration`
### Step 5: Extract Enhanced Tools
**File**: `src/commit_helper_mcp/server/enhanced_tools.py`
**Tools to Extract** (5 tools):
- `analyze_repository_health`
- `get_detailed_diff_analysis`
- `get_branch_analysis`
- `smart_commit_suggestion`
- `batch_commit_analysis`
### Step 6: Extract Resources
**File**: `src/commit_helper_mcp/server/resources.py`
**Resources to Extract** (3 resources):
- `commitizen://config`
- `commitizen://schema`
- `commitizen://example`
### Step 7: Update Main Server File
**File**: `src/commit_helper_mcp/commitizen_server.py`
Transform into a simple aggregator:
```python
"""
Commitizen MCP Server
FastMCP server that exposes Commitizen functionality through MCP tools and resources.
"""
# Import all tools and resources from modules
from .server.base_server import mcp
from .server import message_tools
from .server import git_tools
from .server import workflow_tools
from .server import enhanced_tools
from .server import resources
# Export the server for main.py
__all__ = ['mcp']
if __name__ == "__main__":
# This allows the server to be run directly for testing
import asyncio
async def main():
logger.info("Starting Commitizen MCP Server...")
logger.info("Server initialized successfully")
# List available tools and resources
try:
tools = getattr(mcp, '_tools', {})
resources = getattr(mcp, '_resources', {})
logger.info(f"Server has {len(tools)} tools and {len(resources)} resources")
if tools:
logger.info("Available tools:")
for tool_name in tools.keys():
logger.info(f" - {tool_name}")
if resources:
logger.info("Available resources:")
for resource_pattern in resources.keys():
logger.info(f" - {resource_pattern}")
except Exception as e:
logger.info(f"Could not list tools/resources: {e}")
asyncio.run(main())
```
## Implementation Guidelines
### Code Organization
1. **Consistent Imports**: All modules import from `base_server`
2. **Error Handling**: Maintain existing error handling patterns
3. **Documentation**: Each tool keeps its existing docstring
4. **Type Hints**: Preserve all type annotations
### Testing Strategy
1. **Incremental Testing**: Test after each module extraction
2. **Import Testing**: Ensure all imports work correctly
3. **Tool Registration**: Verify all tools are still registered
4. **Functionality Testing**: Run existing test suite after each step
### Migration Steps
1. Create `server/` directory
2. Create `base_server.py` with shared setup
3. Extract tools one module at a time
4. Update imports in main server file
5. Test after each extraction
6. Update `main.py` if needed
## Validation Criteria
### Success Metrics
- [ ] All 19 tools still function correctly
- [ ] All 3 resources still accessible
- [ ] No file over 300 lines
- [ ] Each module has clear, single responsibility
- [ ] All existing tests pass
- [ ] Import structure is clean and logical
### File Size Targets
- `base_server.py`: ~50-100 lines
- `message_tools.py`: ~150-200 lines
- `git_tools.py`: ~200-250 lines (largest module)
- `workflow_tools.py`: ~100-150 lines
- `enhanced_tools.py`: ~200-250 lines
- `resources.py`: ~50-100 lines
## Potential Issues and Solutions
### Issue 1: Circular Imports
**Problem**: Modules might have circular dependencies
**Solution**: Keep all shared code in `base_server.py`
### Issue 2: Tool Registration Order
**Problem**: FastMCP might be sensitive to registration order
**Solution**: Import modules in a specific order, test thoroughly
### Issue 3: Global State Management
**Problem**: Service instance needs to be shared across modules
**Solution**: Export service from `base_server.py`
## Testing Plan
### Unit Tests
- Test each module can be imported independently
- Verify tool registration works correctly
- Check that service instance is properly shared
### Integration Tests
- Run full test suite after decomposition
- Verify MCP protocol still works correctly
- Test all tools and resources function as expected
### Performance Tests
- Measure startup time before and after
- Ensure no performance regression
- Verify memory usage is similar
## Dependencies
### Prerequisites
- Current codebase is stable and all tests pass
- Understanding of FastMCP tool registration
- Familiarity with Python module structure
### Affected Files
- `src/commit_helper_mcp/commitizen_server.py` (major changes)
- `main.py` (potential minor changes)
- All test files (potential import updates)
## Estimated Effort
**Time Estimate**: 15 minutes
**Complexity**: Medium
**Risk Level**: Low (no functional changes, only reorganization)
## Next Steps
After completing this task:
1. Proceed to Task 2: Service Layer Refactoring
2. Update documentation to reflect new structure
3. Consider updating development setup instructions