# Git Commit Implementation Plan
## Adding Actual Commit Functionality with User Approval
### Overview
This document outlines the implementation plan for adding actual git commit functionality to the Commitizen MCP Connector, leveraging unused capabilities in the `commitizen>=3.0.0` dependency.
### Current State Analysis
#### What's Already Implemented
- ✅ Commit message generation and validation
- ✅ Plugin adapter system for different Commitizen plugins
- ✅ MCP tools for interactive commit message creation
- ✅ Configuration and schema access
- ✅ Health monitoring and configuration refresh
#### Unused Commitizen Functionality
The `commitizen>=3.0.0` package includes significant git integration capabilities that are currently unused:
1. **Direct Git Integration**
- `commitizen.git` module for git operations
- `commitizen.commands.commit` module for actual git commits
- Git repository detection and validation
- Repository state management
2. **Commit Execution Features**
- Execute `git commit` commands with generated messages
- Handle git commit options (signing, staging, etc.)
- Manage git hooks and pre-commit validation
- Support for `--dry-run` mode to preview commits
3. **Repository Context Management**
- Detect git repository context
- Validate repository state before committing
- Handle staging of files before commit
- Support various git commit flags (`--signoff`, `--amend`, etc.)
### Implementation Plan
#### Phase 1: Core Git Integration
##### 1.1 Add Git Service Layer
Create `src/commitizen_mcp_connector/git_service.py`:
```python
"""
Git Service
Service class that wraps Commitizen's git functionality for actual commit operations.
"""
import logging
from typing import Dict, List, Any, Optional
from pathlib import Path
import subprocess
from commitizen.git import GitCommit
from commitizen.exceptions import CommitizenException
logger = logging.getLogger(__name__)
class GitService:
"""Service class for git operations with safety checks."""
def __init__(self, repo_path: Optional[str] = None):
"""Initialize git service with repository path."""
self.repo_path = Path(repo_path) if repo_path else Path.cwd()
self.git_commit = GitCommit()
def validate_repository(self) -> Dict[str, Any]:
"""Validate git repository state."""
# Implementation details
def get_staged_files(self) -> List[str]:
"""Get list of staged files."""
# Implementation details
def get_repository_status(self) -> Dict[str, Any]:
"""Get comprehensive repository status."""
# Implementation details
def execute_commit(
self,
message: str,
stage_all: bool = False,
sign_off: bool = False,
dry_run: bool = True,
additional_args: Optional[List[str]] = None
) -> Dict[str, Any]:
"""Execute git commit with safety checks."""
# Implementation details
```
##### 1.2 Extend CommitzenService
Add git integration methods to existing `CommitzenService`:
```python
# Add to src/commitizen_mcp_connector/commitizen_service.py
from .git_service import GitService
class CommitzenService:
def __init__(self):
# Existing initialization
self.git_service = GitService()
def prepare_commit(
self,
message: str,
stage_all: bool = False
) -> Dict[str, Any]:
"""Prepare commit with validation and preview."""
# Implementation details
def execute_commit_with_approval(
self,
message: str,
**kwargs
) -> Dict[str, Any]:
"""Execute commit after user approval."""
# Implementation details
```
#### Phase 2: New MCP Tools for Git Operations
##### 2.1 Repository Status Tools
Add to `src/commitizen_mcp_connector/commitizen_server.py`:
```python
@mcp.tool()
def get_repository_status() -> Dict[str, Any]:
"""
Get current git repository status including staged files and changes.
Returns:
Dict containing repository status, staged files, and validation info
"""
# Implementation details
@mcp.tool()
def get_staged_files() -> Dict[str, Any]:
"""
Get list of currently staged files ready for commit.
Returns:
Dict containing staged files and their status
"""
# Implementation details
```
##### 2.2 Commit Preview Tools
```python
@mcp.tool()
def preview_commit(
message: str,
stage_all: bool = False,
sign_off: bool = False,
additional_args: Optional[List[str]] = None
) -> Dict[str, Any]:
"""
Preview a git commit without executing it (dry-run mode).
Args:
message: The commit message to use
stage_all: Whether to stage all changes before commit
sign_off: Whether to add sign-off to the commit
additional_args: Additional git commit arguments
Returns:
Dict containing commit preview, affected files, and validation status
"""
# Implementation details
```
##### 2.3 Commit Execution Tools
```python
@mcp.tool()
def execute_commit(
message: str,
stage_all: bool = False,
sign_off: bool = False,
force_execute: bool = False,
additional_args: Optional[List[str]] = None
) -> Dict[str, Any]:
"""
Execute actual git commit with safety checks and user approval.
Args:
message: The commit message to use
stage_all: Whether to stage all changes before commit
sign_off: Whether to add sign-off to the commit
force_execute: Override safety checks (use with caution)
additional_args: Additional git commit arguments
Returns:
Dict containing commit result, hash, and status
"""
# Implementation details
@mcp.tool()
def stage_and_commit(
type: str,
subject: str,
body: Optional[str] = None,
scope: Optional[str] = None,
breaking: Optional[bool] = False,
footer: Optional[str] = None,
stage_all: bool = True,
sign_off: bool = False,
dry_run: bool = True
) -> Dict[str, Any]:
"""
Generate commit message and execute commit in one step.
Combines message generation with commit execution for streamlined workflow.
"""
# Implementation details
```
#### Phase 3: Safety and Approval Mechanisms
##### 3.1 Safety Checks
Implement comprehensive safety checks:
```python
class CommitSafetyValidator:
"""Validates repository state before commits."""
def validate_pre_commit(self) -> Dict[str, Any]:
"""Run pre-commit validation checks."""
checks = {
"repository_exists": self._check_git_repo(),
"has_staged_changes": self._check_staged_changes(),
"no_merge_conflicts": self._check_merge_conflicts(),
"branch_is_clean": self._check_working_directory(),
"hooks_will_pass": self._validate_hooks()
}
return checks
def get_commit_impact(self, stage_all: bool = False) -> Dict[str, Any]:
"""Analyze the impact of the proposed commit."""
# Implementation details
```
##### 3.2 User Approval Workflow
Design approval workflow through MCP:
1. **Generate/Validate Message** → Use existing tools
2. **Preview Commit** → New `preview_commit` tool shows:
- Generated commit message
- Files to be committed
- Repository status
- Safety check results
3. **Request Approval** → AI assistant presents preview to user
4. **Execute Commit** → Only after explicit user approval
##### 3.3 Configuration Options
Add git-related configuration to `pyproject.toml`:
```toml
[tool.commitizen.git]
# Git integration settings
enable_git_operations = true
default_dry_run = true
require_staged_files = true
auto_stage_all = false
default_sign_off = false
safety_checks_enabled = true
```
#### Phase 4: Enhanced Workflow Integration
##### 4.1 Workflow Tools
```python
@mcp.tool()
def commit_workflow(
type: str,
subject: str,
body: Optional[str] = None,
scope: Optional[str] = None,
breaking: Optional[bool] = False,
footer: Optional[str] = None,
workflow_step: str = "preview" # "preview", "approve", "execute"
) -> Dict[str, Any]:
"""
Guided commit workflow with multiple steps.
Args:
workflow_step: "preview" | "approve" | "execute"
... (other commit parameters)
Returns:
Dict containing workflow status and next steps
"""
# Implementation details
```
##### 4.2 Batch Operations
```python
@mcp.tool()
def batch_commit_files(
files: List[str],
message_template: Dict[str, Any],
dry_run: bool = True
) -> Dict[str, Any]:
"""
Stage specific files and commit with generated message.
Useful for selective commits of specific files.
"""
# Implementation details
```
### Implementation Details
#### Dependencies and Imports
The implementation will leverage existing Commitizen functionality:
```python
# Core Commitizen imports for git operations
from commitizen.git import GitCommit, GitTag
from commitizen.commands.commit import Commit
from commitizen.exceptions import (
CommitizenException,
GitCommandError,
NoStagedFilesError
)
# Additional git utilities
import subprocess
from pathlib import Path
import os
```
#### Error Handling Strategy
Comprehensive error handling for git operations:
```python
class GitOperationError(Exception):
"""Custom exception for git operation failures."""
pass
class CommitValidationError(Exception):
"""Custom exception for commit validation failures."""
pass
# Error handling patterns
try:
result = git_service.execute_commit(message, **kwargs)
return {"success": True, "result": result}
except GitOperationError as e:
logger.error(f"Git operation failed: {e}")
return {"error": str(e), "success": False, "type": "git_error"}
except CommitValidationError as e:
logger.error(f"Commit validation failed: {e}")
return {"error": str(e), "success": False, "type": "validation_error"}
```
#### Testing Strategy
Comprehensive testing approach:
1. **Unit Tests**
- Test git service methods in isolation
- Mock git operations for safety
- Test error handling scenarios
2. **Integration Tests**
- Test MCP tool integration
- Test workflow scenarios
- Test safety mechanisms
3. **Safety Tests**
- Test dry-run functionality
- Test approval mechanisms
- Test repository validation
#### Security Considerations
1. **Default Safety**
- All commit operations default to `dry_run=True`
- Require explicit approval for actual commits
- Validate repository state before operations
2. **Input Validation**
- Sanitize commit messages
- Validate file paths
- Check git command arguments
3. **Permission Checks**
- Verify write permissions to repository
- Check git configuration
- Validate user identity
### Migration Path
#### Phase 1: Foundation (Week 1)
- [ ] Implement `GitService` class
- [ ] Add repository validation methods
- [ ] Create safety check framework
- [ ] Add basic unit tests
#### Phase 2: MCP Integration (Week 2)
- [ ] Add repository status tools
- [ ] Implement commit preview functionality
- [ ] Create commit execution tools
- [ ] Add comprehensive error handling
#### Phase 3: Workflow Enhancement (Week 3)
- [ ] Implement guided workflow tools
- [ ] Add batch operation support
- [ ] Create configuration options
- [ ] Add integration tests
#### Phase 4: Polish and Documentation (Week 4)
- [ ] Complete test coverage
- [ ] Update documentation
- [ ] Add usage examples
- [ ] Performance optimization
### Usage Examples
#### Basic Commit Workflow
```python
# 1. Generate commit message
message_result = generate_commit_message(
type="feat",
subject="add git commit functionality",
body="Implements actual git commits with user approval"
)
# 2. Preview commit
preview_result = preview_commit(
message=message_result["message"],
stage_all=True
)
# 3. Execute after user approval
if user_approves:
commit_result = execute_commit(
message=message_result["message"],
stage_all=True,
force_execute=True
)
```
#### AI Assistant Integration
The AI assistant workflow would be:
1. **Generate Message**: Use existing MCP tools
2. **Show Preview**: Call `preview_commit` and present results
3. **Request Approval**: Ask user "Do you want to execute this commit?"
4. **Execute**: Call `execute_commit` only after approval
### Benefits
1. **Enhanced Functionality**: Leverages unused Commitizen capabilities
2. **Safety First**: Multiple safety checks and approval mechanisms
3. **Seamless Integration**: Works with existing MCP tools and workflow
4. **User Control**: Explicit approval required for all git operations
5. **Comprehensive**: Supports full git commit workflow with staging, signing, etc.
### Risks and Mitigations
#### Risks
1. **Accidental Commits**: User might approve unintended commits
2. **Repository Corruption**: Git operations could fail unexpectedly
3. **Permission Issues**: Insufficient git permissions
#### Mitigations
1. **Default Dry-Run**: All operations default to preview mode
2. **Comprehensive Validation**: Multiple safety checks before execution
3. **Clear Previews**: Detailed commit previews before approval
4. **Error Recovery**: Robust error handling and recovery mechanisms
5. **Audit Trail**: Log all git operations for debugging
This implementation plan provides a comprehensive approach to adding git commit functionality while maintaining safety and user control through the MCP protocol.