Skip to main content
Glama
jolfr

Commit Helper MCP

by jolfr

smart_commit_suggestion

Analyzes staged Git changes to generate commit message suggestions, including type, scope, and subject based on file patterns and affected modules.

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

TableJSON Schema
NameRequiredDescriptionDefault
repo_pathYes
analyze_changesNo
suggest_typeNo
suggest_scopeNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The core handler function for the 'smart_commit_suggestion' MCP tool. Decorated with @mcp.tool() for registration. Analyzes staged Git changes, detects file patterns to suggest conventional commit types (feat, fix, docs, test, etc.), scopes from directories, and subject lines. Uses CommitzenService for repo access and returns ranked suggestions with confidence scores and analysis.
    @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
            )
  • Import statement in the main MCP server file that brings the smart_commit_suggestion tool into the server's namespace, making it available for MCP protocol exposure.
    from .server.enhanced_tools import (
        analyze_repository_health,
        get_detailed_diff_analysis,
        get_branch_analysis,
        smart_commit_suggestion,
        batch_commit_analysis,
    )
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries full burden. It mentions using GitPython and analyzing staged changes, but doesn't disclose critical behavioral traits: whether this is a read-only operation, if it modifies the repository, what permissions are needed, or any rate limits. The description is functional but lacks transparency about the tool's operational characteristics.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately sized and well-structured. It starts with a clear purpose statement, then details what the tool analyzes, lists parameters with brief explanations, and specifies the return type. Each sentence adds value without redundancy. The front-loaded purpose statement makes the tool's function immediately clear.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's moderate complexity (4 parameters, no annotations, but has output schema), the description is partially complete. It covers the basic purpose and parameters but lacks behavioral transparency and usage guidelines. The presence of an output schema means the description doesn't need to explain return values, but it should address when to use this tool versus siblings and disclose operational characteristics.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

With 0% schema description coverage, the description must compensate for the schema's lack of parameter documentation. It successfully adds meaning by listing all four parameters ('repo_path', 'analyze_changes', 'suggest_type', 'suggest_scope') and briefly explaining their purposes in the context of commit suggestions. This provides essential semantic context beyond the bare schema.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Intelligent commit message suggestions based on repository changes.' It specifies the verb ('suggest') and resource ('commit message'), and mentions using GitPython to analyze staged changes. However, it doesn't explicitly differentiate from sibling tools like 'create_commit_message' or 'generate_commit_message', which appear to have similar functions.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. With many sibling tools related to commits (e.g., 'create_commit_message', 'generate_commit_message', 'execute_git_commit'), there's no indication of when this 'intelligent' suggestion tool is preferred over others. It mentions analyzing staged changes but doesn't specify prerequisites or exclusions.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/jolfr/commit-helper-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server