smart_commit_suggestion
Automatically generate structured commit message suggestions by analyzing staged changes in a repository. Provides commit type, scope, and subject line based on file patterns and affected directories.
Instructions
Intelligent commit message suggestions based on repository changes.
Uses GitPython to analyze staged changes and suggest:
Appropriate commit type based on file patterns
Scope based on affected directories/modules
Subject line based on change patterns
Args: repo_path: Path to git repository analyze_changes: Whether to analyze file changes for suggestions suggest_type: Whether to suggest commit type suggest_scope: Whether to suggest scope
Returns: Dict containing intelligent commit suggestions
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| analyze_changes | No | ||
| repo_path | Yes | ||
| suggest_scope | No | ||
| suggest_type | No |
Implementation Reference
- The primary MCP tool handler for 'smart_commit_suggestion'. Decorated with @mcp.tool(), it initializes CommitzenService, checks staged files, performs pattern-based analysis on file paths to suggest commit types (feat, fix, docs, etc.), scopes (directories), and subjects. Returns structured suggestions with confidence scores. Handles errors with custom exceptions.@mcp.tool() @handle_errors(log_errors=True) def smart_commit_suggestion( repo_path: str, analyze_changes: bool = True, suggest_type: bool = True, suggest_scope: bool = True ) -> Dict[str, Any]: """ Intelligent commit message suggestions based on repository changes. Uses GitPython to analyze staged changes and suggest: - Appropriate commit type based on file patterns - Scope based on affected directories/modules - Subject line based on change patterns Args: repo_path: Path to git repository analyze_changes: Whether to analyze file changes for suggestions suggest_type: Whether to suggest commit type suggest_scope: Whether to suggest scope Returns: Dict containing intelligent commit suggestions """ # Initialize service for the specified repository try: target_service = CommitzenService(repo_path=repo_path) except Exception as e: raise RepositoryError( f"Failed to initialize service for repository '{repo_path}'", repo_path=repo_path, cause=e ) try: # Get current staged files status = target_service.get_repository_status() if "error" in status: raise GitOperationError( status["error"], repo_path=repo_path ) if status["staging_clean"]: # For backward compatibility with tests return { "success": False, "error": "No staged changes to analyze", "repository_path": repo_path } suggestions = { "types": [], "scopes": [], "subjects": [], "analysis": {} } if analyze_changes and target_service.git_enabled: # Analyze file patterns for intelligent suggestions staged_files = status["staged_files"] # Analyze file types and patterns file_patterns = { "docs": [".md", ".rst", ".txt", "README", "CHANGELOG"], "tests": ["test_", "_test", ".test.", "/tests/", "/test/"], "config": [".json", ".yaml", ".yml", ".toml", ".ini", ".cfg"], "frontend": [".js", ".ts", ".jsx", ".tsx", ".vue", ".css", ".scss"], "backend": [".py", ".java", ".go", ".rs", ".cpp", ".c"], "build": ["Makefile", "setup.py", "pyproject.toml", "package.json", "Dockerfile"], "ci": [".github/", ".gitlab-ci", "Jenkinsfile", ".travis"] } detected_patterns = set() affected_dirs = set() for file_path in staged_files: # Detect file patterns for pattern_type, patterns in file_patterns.items(): if any(pattern in file_path for pattern in patterns): detected_patterns.add(pattern_type) # Extract directory for scope suggestion if "/" in file_path: dir_parts = file_path.split("/") if len(dir_parts) > 1: affected_dirs.add(dir_parts[0]) # Suggest commit types based on patterns if suggest_type: if "docs" in detected_patterns: suggestions["types"].append({"type": "docs", "confidence": 0.9, "reason": "Documentation files modified"}) if "tests" in detected_patterns: suggestions["types"].append({"type": "test", "confidence": 0.8, "reason": "Test files modified"}) if "config" in detected_patterns: suggestions["types"].append({"type": "chore", "confidence": 0.7, "reason": "Configuration files modified"}) if "build" in detected_patterns or "ci" in detected_patterns: suggestions["types"].append({"type": "ci", "confidence": 0.8, "reason": "Build/CI files modified"}) if "frontend" in detected_patterns or "backend" in detected_patterns: suggestions["types"].append({"type": "feat", "confidence": 0.6, "reason": "Code files modified (likely feature)"}) suggestions["types"].append({"type": "fix", "confidence": 0.5, "reason": "Code files modified (possibly fix)"}) # Suggest scopes based on affected directories if suggest_scope: for dir_name in affected_dirs: suggestions["scopes"].append({ "scope": dir_name, "confidence": 0.7, "reason": f"Files in {dir_name}/ directory modified" }) # Generate subject suggestions if len(staged_files) == 1: file_name = staged_files[0].split("/")[-1] suggestions["subjects"].append({ "subject": f"update {file_name}", "confidence": 0.6, "reason": "Single file modification" }) elif "docs" in detected_patterns: suggestions["subjects"].append({ "subject": "update documentation", "confidence": 0.8, "reason": "Documentation files modified" }) elif "tests" in detected_patterns: suggestions["subjects"].append({ "subject": "add/update tests", "confidence": 0.7, "reason": "Test files modified" }) suggestions["analysis"] = { "staged_files_count": len(staged_files), "detected_patterns": list(detected_patterns), "affected_directories": list(affected_dirs), "file_types": list(set(f.split(".")[-1] for f in staged_files if "." in f)) } # Sort suggestions by confidence suggestions["types"].sort(key=lambda x: x["confidence"], reverse=True) suggestions["scopes"].sort(key=lambda x: x["confidence"], reverse=True) suggestions["subjects"].sort(key=lambda x: x["confidence"], reverse=True) return create_success_response({ "repository_path": repo_path, "implementation": target_service.git_implementation, "enhanced_features_used": target_service.git_enabled, "suggestions": suggestions, "staged_files": status["staged_files"] }) except Exception as e: logger.error(f"Failed to generate smart commit suggestions: {e}") raise ServiceError( f"Failed to generate smart commit suggestions: {e}", service_name="smart_commit_suggestion", cause=e )
- src/commit_helper_mcp/mcp_server.py:54-60 (registration)Explicit import of the smart_commit_suggestion handler function from enhanced_tools.py into the main MCP server module, exporting it via __all__ for availability in the server.from .server.enhanced_tools import ( analyze_repository_health, get_detailed_diff_analysis, get_branch_analysis, smart_commit_suggestion, batch_commit_analysis, )