generate_and_commit
Generate conventional commit messages and optionally execute git commits in one step to streamline version control workflows.
Instructions
Generate commit message and optionally execute commit in one step.
Combines message generation with git operations for streamlined workflow.
Args: type: Commit type (feat, fix, docs, etc.) subject: Commit subject/description repo_path: Path to git repository body: Optional detailed description scope: Optional scope of changes breaking: Whether this is a breaking change footer: Optional footer (e.g., issue references) stage_all: Whether to stage all changes (not implemented yet) sign_off: Whether to add sign-off to commit (default: True) preview_only: If True, only preview (default for safety)
Returns: Dict containing: - message: Generated commit message - is_valid: Whether message is valid - git_preview: Preview of git operation (if preview_only=True) - commit_result: Commit execution result (if preview_only=False)
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| type | Yes | ||
| subject | Yes | ||
| repo_path | Yes | ||
| body | No | ||
| scope | No | ||
| breaking | No | ||
| footer | No | ||
| stage_all | No | ||
| sign_off | No | ||
| preview_only | No |
Implementation Reference
- The main @mcp.tool()-decorated handler function that implements the generate_and_commit tool logic. It generates the commit message, validates it, and then either previews or executes the git commit.@mcp.tool() def generate_and_commit( type: str, subject: str, repo_path: str, body: Optional[str] = None, scope: Optional[str] = None, breaking: Optional[bool] = False, footer: Optional[str] = None, stage_all: bool = True, sign_off: bool = True, preview_only: bool = True, ) -> Dict[str, Any]: """ Generate commit message and optionally execute commit in one step. Combines message generation with git operations for streamlined workflow. Args: type: Commit type (feat, fix, docs, etc.) subject: Commit subject/description repo_path: Path to git repository body: Optional detailed description scope: Optional scope of changes breaking: Whether this is a breaking change footer: Optional footer (e.g., issue references) stage_all: Whether to stage all changes (not implemented yet) sign_off: Whether to add sign-off to commit (default: True) preview_only: If True, only preview (default for safety) Returns: Dict containing: - message: Generated commit message - is_valid: Whether message is valid - git_preview: Preview of git operation (if preview_only=True) - commit_result: Commit execution result (if preview_only=False) """ try: # Import message generation function from .message_tools import generate_commit_message # First generate the commit message message_result = generate_commit_message( type=type, subject=subject, body=body, scope=scope, breaking=breaking, footer=footer, ) if "error" in message_result: return { "error": f"Message generation failed: {message_result['error']}", "message": None, "is_valid": False, "preview_only": preview_only, } generated_message = message_result["message"] is_valid = message_result["is_valid"] if not is_valid: return { "error": "Generated message failed validation", "message": generated_message, "is_valid": False, "preview_only": preview_only, } # Now handle git operations using the provided repo_path if preview_only: # Get git preview using provided repository path git_preview = preview_git_commit(generated_message, repo_path) return { "message": generated_message, "is_valid": is_valid, "git_enabled": git_preview.get("git_enabled", False), "git_preview": git_preview, "preview_only": True, "repository_path": repo_path, } else: # Execute the commit using provided repository path commit_result = execute_git_commit( message=generated_message, repo_path=repo_path, sign_off=sign_off, force_execute=True, # Since user explicitly set preview_only=False ) return { "message": generated_message, "is_valid": is_valid, "git_enabled": commit_result.get("git_enabled", False), "commit_result": commit_result, "preview_only": False, "repository_path": repo_path, } except Exception as e: logger.error(f"Failed to generate and commit: {e}") return { "error": str(e), "message": None, "is_valid": False, "git_enabled": service.git_enabled, "preview_only": preview_only, }
- src/commit_helper_mcp/mcp_server.py:34-43 (registration)Import statement in the main MCP server module that brings the generate_and_commit tool into scope, effectively registering it with the MCP server.from .server.git_tools import ( get_git_implementation_info, get_enhanced_git_status, get_git_status, preview_git_commit, execute_git_commit, generate_and_commit, validate_commit_readiness, stage_files_and_commit, )
- Supporting helper function generate_commit_message called by the main handler to generate and validate the commit message from input parameters.@mcp.tool() @handle_errors(log_errors=True) def generate_commit_message( type: str, subject: str, body: Optional[str] = None, scope: Optional[str] = None, breaking: Optional[bool] = False, footer: Optional[str] = None, include_git_preview: bool = False, ) -> Dict[str, Any]: """ Generate a commit message with validation using provided parameters. Args: type: The commit type (e.g., 'feat', 'fix', 'docs') subject: The commit subject/description body: Optional commit body with detailed description scope: Optional scope of the change breaking: Whether this is a breaking change footer: Optional footer (e.g., issue references) include_git_preview: Whether to include git preview in response Returns: Dict containing the generated message and validation status """ # Build answers dictionary with all fields (adapter will handle mapping) answers = { "type": type, "prefix": type, # Some plugins expect 'prefix' "subject": subject, "body": body or "", "scope": scope or "", "breaking": breaking or False, "is_breaking_change": breaking or False, # Some plugins expect this name "footer": footer or "", } # Generate the message message = service.generate_message(answers) # Validate the generated message is_valid = service.validate_message(message) if not is_valid: raise create_validation_error( "Invalid commit message format", validation_type="commit_message", invalid_value=f"{type}: {subject}", ) result = { "message": message, "is_valid": is_valid, "parameters": { "type": type, "subject": subject, "body": body, "scope": scope, "breaking": breaking, "footer": footer, }, } # Add git preview if requested and available if include_git_preview and service.git_enabled: try: # Import preview function from git_tools from .git_tools import preview_git_commit # Use the current service's repository path for preview repo_path = ( str(service.git_service.repo_path) if service.git_service else None ) if repo_path: git_preview = preview_git_commit(message, repo_path) result["git_preview"] = git_preview else: result["git_preview_error"] = ( "No repository path available for git preview" ) except Exception as e: logger.warning(f"Failed to include git preview: {e}") result["git_preview_error"] = str(e) elif include_git_preview and not service.git_enabled: result["git_preview_error"] = ( "Git operations not available - not in a git repository" ) return create_success_response(result)
- Helper tool used by generate_and_commit for preview mode (preview_only=True).@mcp.tool() @handle_errors(log_errors=True) def preview_git_commit( message: str, repo_path: str, stage_all: bool = False, sign_off: bool = True ) -> Dict[str, Any]: """ Preview git commit operation without executing (dry-run mode). Args: message: Commit message to preview repo_path: Path to git repository stage_all: Whether to stage all changes before commit (not implemented yet) sign_off: Whether to add sign-off to commit (default: True) Returns: Dict containing: - message: The commit message - is_valid: Whether message passes validation - files_to_commit: List of files that would be committed - dry_run: Always True for this tool - repository_status: Current repository state """ # For backward compatibility with tests expecting git_enabled field try: # Initialize service for the specified repository try: target_service = CommitzenService(repo_path=repo_path) except Exception as e: return { "git_enabled": False, "error": f"Failed to initialize service for repository '{repo_path}': {e}", "message": message, "dry_run": True, "repository_path": repo_path, } if not target_service.git_enabled: return { "git_enabled": False, "error": "Git operations not available - not in a git repository", "message": message, "dry_run": True, "repository_path": repo_path, } # Get preview from service preview_result = target_service.preview_commit_operation( message, sign_off=sign_off ) if "error" in preview_result: return { "git_enabled": True, "error": preview_result["error"], "message": message, "dry_run": True, "repository_path": repo_path, } git_preview = preview_result.get("git_preview", {}) return { "git_enabled": True, "message": message, "is_valid": preview_result.get("is_valid", False), "files_to_commit": git_preview.get("staged_files", []), "staged_files_count": git_preview.get("staged_files_count", 0), "would_execute": git_preview.get("would_execute", False), "dry_run": True, "repository_status": git_preview, "repository_path": git_preview.get("repository_path"), "success": True, } except Exception as e: logger.error(f"Failed to preview git commit: {e}") return { "git_enabled": False, "error": str(e), "message": message, "dry_run": True, "repository_path": repo_path, "success": False, }
- Helper tool used by generate_and_commit for execution mode (preview_only=False).@mcp.tool() def execute_git_commit( message: str, repo_path: str, stage_all: bool = False, sign_off: bool = True, force_execute: bool = False, ) -> Dict[str, Any]: """ Execute actual git commit with safety checks and user approval. SAFETY: Requires force_execute=True to perform actual commit. Args: message: Commit message to use repo_path: Path to git repository stage_all: Whether to stage all changes before commit (not implemented yet) sign_off: Whether to add sign-off to commit (default: True) force_execute: Must be True to execute actual commit (safety flag) Returns: Dict containing: - success: Whether commit was successful - message: The commit message used - executed: Whether commit was actually executed - error: Error message (if failed) - dry_run: False if actually executed, True if preview only """ try: # Initialize service for the specified repository try: target_service = CommitzenService(repo_path=repo_path) except Exception as e: return { "git_enabled": False, "error": f"Failed to initialize service for repository '{repo_path}': {e}", "success": False, "executed": False, "message": message, "repository_path": repo_path, } if not target_service.git_enabled: return { "git_enabled": False, "error": "Git operations not available - not in a git repository", "success": False, "executed": False, "message": message, "repository_path": repo_path, } # Execute commit with safety checks result = target_service.execute_commit_operation( message=message, force_execute=force_execute, sign_off=sign_off ) # Add dry_run flag based on execution result["dry_run"] = not result.get("executed", False) result["git_enabled"] = True result["repository_path"] = repo_path return result except Exception as e: logger.error(f"Failed to execute git commit: {e}") return { "git_enabled": False, "error": str(e), "success": False, "executed": False, "message": message, "dry_run": True, "repository_path": repo_path, }