Skip to main content
Glama

Commit Helper MCP

by jolfr
  • Apple
configure_cline.py16 kB
#!/usr/bin/env python3 """ Global configuration script to set up Commit Helper MCP with Cline. This script configures the MCP server globally, making it available to all projects. """ import json import os import sys from pathlib import Path import shutil def get_cline_config_path(): """Get the path to Cline's configuration file.""" home = Path.home() # Cline stores its MCP settings in VS Code's global storage cline_config_path = ( home / "Library" / "Application Support" / "Code" / "User" / "globalStorage" / "saoudrizwan.claude-dev" / "settings" / "cline_mcp_settings.json" ) return cline_config_path def get_global_clinerules_path(): """Get the path to global Cline rules directory.""" home = Path.home() return home / "Documents" / "Cline" / "Rules" def get_mcp_server_absolute_path(): """Get the absolute path to the MCP server directory.""" # Get the directory where this script is located script_dir = Path(__file__).parent.absolute() return str(script_dir) def load_existing_config(config_path): """Load existing Cline configuration or create empty one.""" if config_path.exists(): try: with open(config_path, "r") as f: return json.load(f) except (json.JSONDecodeError, FileNotFoundError): print(f"Warning: Could not read existing config at {config_path}") return {} else: return {} def save_config(config_path, config): """Save configuration to file.""" # Ensure directory exists config_path.parent.mkdir(parents=True, exist_ok=True) with open(config_path, "w") as f: json.dump(config, f, indent=2) def configure_global_mcp_server(): """Configure the Commit Helper MCP globally with Cline.""" print("🔧 Configuring Commit Helper MCP globally with Cline...") # Get absolute path to MCP server (project-agnostic) server_path = get_mcp_server_absolute_path() print(f"📁 MCP Server location: {server_path}") # Get Cline config path config_path = get_cline_config_path() print(f"📄 Cline config path: {config_path}") # Load existing configuration config = load_existing_config(config_path) # Ensure mcpServers section exists if "mcpServers" not in config: config["mcpServers"] = {} # Add our MCP server configuration with absolute paths and auto-approval for safe tools server_config = { "command": "uv", "args": ["run", "python", "main.py"], "cwd": server_path, "autoApprove": [ "health_check", "get_commit_types", "get_commit_questions", "validate_commit_message", "generate_commit_message", "create_commit_message", "get_git_status", "validate_commit_readiness", "preview_git_commit", "refresh_configuration", ], } config["mcpServers"]["commit-helper-mcp"] = server_config # Configure auto-approval settings for optimal MCP tool usage if "autoApprove" not in config: config["autoApprove"] = {} # Enable auto-approval for MCP servers and read operations auto_approve_config = { "useMcpServers": True, "readProjectFiles": True, "executeSafeCommands": True, "maxRequests": 20, } # Merge with existing auto-approve settings (preserve user preferences) for key, value in auto_approve_config.items(): if key not in config["autoApprove"]: config["autoApprove"][key] = value # Save the configuration try: save_config(config_path, config) print("✅ Global MCP server configuration saved successfully!") print("\n📋 Global MCP Server Configuration:") print(f" Name: commit-helper-mcp") print(f" Command: uv run python main.py") print(f" Working Directory: {server_path}") print(f" Scope: Available to ALL projects") print("\n🔧 Auto-Approval Configuration:") print( f" Use MCP Servers: {config['autoApprove'].get('useMcpServers', False)}" ) print( f" Read Project Files: {config['autoApprove'].get('readProjectFiles', False)}" ) print( f" Execute Safe Commands: {config['autoApprove'].get('executeSafeCommands', False)}" ) print(f" Max Requests: {config['autoApprove'].get('maxRequests', 0)}") print(f"\n💾 Configuration file: {config_path}") return True except Exception as e: print(f"❌ Error saving global configuration: {e}") return False def create_global_clinerules(): """Create global Cline rules for commit workflows.""" print("\n🔧 Creating global Cline rules for commit workflows...") rules_dir = get_global_clinerules_path() rules_file = rules_dir / "commitizen-workflow.md" # Ensure rules directory exists rules_dir.mkdir(parents=True, exist_ok=True) rules_content = """# Commit Helper MCP - Global Commit Workflow Rules ## Overview These rules establish standardized commit practices using the Commit Helper MCP across all projects. ## Commit Workflow Standards ### 1. Always Preview Before Commit Before executing any commit, ALWAYS use the preview tools first: ``` Use preview_git_commit tool to show what will be committed before executing ``` ### 2. Validate Repository Readiness Check repository status before committing: ``` Use validate_commit_readiness tool to ensure repository is ready for commit Use get_git_status tool to see staged files and repository state ``` ### 3. Generate Conventional Commit Messages Always use conventional commit format: ``` Use generate_commit_message tool with appropriate type, subject, and optional body/scope Available types: feat, fix, docs, style, refactor, test, chore, ci, build, perf ``` ### 4. Safety-First Approach - All git operations default to preview mode - Actual commits require explicit confirmation - Use force_execute=True only after preview and validation ## Tool Usage Guidelines ### Core Workflow Tools - **get_git_status**: Check repository status and staged files - **validate_commit_readiness**: Comprehensive readiness validation - **generate_commit_message**: Create conventional commit messages - **preview_git_commit**: Safe preview of commit operation - **execute_git_commit**: Execute commit with force_execute=True ### Advanced Workflow Tools - **generate_and_commit**: Complete workflow in one step (preview_only=True by default) - **stage_files_and_commit**: Selective file commits - **commit_workflow_step**: Multi-step workflow with approval gates ### Validation Tools - **validate_commit_message**: Check existing messages against project rules - **get_commit_types**: See available commit types for current project - **health_check**: Verify MCP server and Commitizen configuration ## Safety Mechanisms ### Built-in Safety Features 1. **Preview Mode Default**: All operations show what will happen first 2. **Explicit Confirmation**: Destructive operations require force flags 3. **Repository Validation**: Prevents operations in invalid git repositories 4. **Message Validation**: Ensures commit messages follow project conventions ### Best Practices 1. **Always Preview**: Use preview tools before any git operation 2. **Validate First**: Check repository readiness and message format 3. **Explicit Confirmation**: Only use force_execute after careful review 4. **Conventional Format**: Always use conventional commit message format ## Project Detection The MCP server automatically detects: - Git repository status - Commitizen configuration (pyproject.toml, .cz.toml, etc.) - Available commit types and validation rules - Project-specific commit message patterns ## Fallback Instructions If MCP server is unavailable: 1. Use standard git commands with manual conventional commit format 2. Follow pattern: `type(scope): subject` (e.g., `feat(auth): add JWT authentication`) 3. Include body and footer as needed 4. Validate manually against project's commit conventions ## Error Handling Common issues and solutions: - **Server not connected**: Restart Cline or check MCP configuration - **Invalid repository**: Ensure you're in a git repository with staged changes - **Validation errors**: Check commit message format and project configuration - **Permission errors**: Ensure proper git repository permissions ## Integration with Development Workflow ### Before Committing 1. Stage your changes: `git add .` or stage specific files 2. Use `get_git_status` to verify staged files 3. Use `validate_commit_readiness` to check repository state 4. Generate commit message with `generate_commit_message` 5. Preview with `preview_git_commit` 6. Execute with `execute_git_commit` and `force_execute=True` ### For Complex Workflows - Use `generate_and_commit` for complete workflow - Use `stage_files_and_commit` for selective commits - Use `commit_workflow_step` for multi-step approval processes This workflow ensures consistent, safe, and conventional commits across all projects. """ try: with open(rules_file, "w") as f: f.write(rules_content) print(f"✅ Global Cline rules created: {rules_file}") print(" Rules will apply to ALL projects automatically") return True except Exception as e: print(f"❌ Error creating global rules: {e}") return False def check_dependencies(): """Check that required dependencies are available.""" print("\n🔍 Checking dependencies...") # Check uv is available if not shutil.which("uv"): print("❌ uv package manager not found. Please install uv first.") print(" Install with: curl -LsSf https://astral.sh/uv/install.sh | sh") return False print("✅ uv package manager found") # Check Python version python_version = sys.version_info if python_version < (3, 8): print( f"❌ Python {python_version.major}.{python_version.minor} found, but Python 3.8+ required" ) return False print(f"✅ Python {python_version.major}.{python_version.minor} found") return True def verify_global_setup(): """Verify the global setup is working correctly.""" print("\n🔍 Verifying global setup...") # Check MCP server configuration config_path = get_cline_config_path() if not config_path.exists(): print("❌ Cline configuration file not found") return False try: config = load_existing_config(config_path) if "commit-helper-mcp" not in config.get("mcpServers", {}): print("❌ MCP server not found in Cline configuration") return False print("✅ MCP server configured in Cline") # Check global rules rules_dir = get_global_clinerules_path() rules_file = rules_dir / "commitizen-workflow.md" if rules_file.exists(): print("✅ Global Cline rules created") else: print("⚠️ Global Cline rules not found") return True except Exception as e: print(f"❌ Error verifying setup: {e}") return False def test_server(): """Test that the MCP server can start.""" print("\n🧪 Testing MCP server startup...") try: # Test server using uv run to ensure proper environment import subprocess result = subprocess.run( [ "uv", "run", "python", "-c", "from src.commit_helper_mcp.server.workflow_tools import health_check; print('Health check imported successfully')", ], capture_output=True, text=True, timeout=30, ) if result.returncode == 0: print("✅ MCP server is working correctly!") print(f" Output: {result.stdout.strip()}") return True else: print(f"❌ MCP server test failed:") print(f" Return code: {result.returncode}") print(f" Error: {result.stderr}") return False except subprocess.TimeoutExpired: print("❌ MCP server test timed out") return False except Exception as e: print(f"❌ Error testing MCP server: {e}") return False def main(): """Main global configuration function.""" print("🚀 Commit Helper MCP - Global Cline Configuration") print("=" * 65) print("This script configures the MCP server globally for ALL projects") print("=" * 65) # Check dependencies first if not check_dependencies(): print("\n❌ Dependency check failed. Please install required dependencies.") sys.exit(1) # Test server functionality if not test_server(): print("\n❌ MCP server test failed. Please check the installation.") sys.exit(1) # Configure global MCP server if not configure_global_mcp_server(): print("\n❌ Global MCP server configuration failed.") sys.exit(1) # Create global Cline rules if not create_global_clinerules(): print("\n❌ Global Cline rules creation failed.") sys.exit(1) # Verify the complete setup if not verify_global_setup(): print( "\n⚠️ Setup verification had issues, but basic configuration is complete." ) print("\n🎉 Global Configuration Complete!") print("\n✨ The Commit Helper MCP is now available to ALL projects!") print("\n🔄 Next Steps:") print("1. Restart Cline (close and reopen the panel)") print("2. Navigate to any git repository") print("3. Test the connection by asking Cline:") print( " 'Use the health_check tool to verify the Commit Helper MCP server is working'" ) print("\n📚 Available Tools (in ALL projects):") tools = [ "generate_commit_message - Create conventional commit messages", "validate_commit_message - Check message format", "get_git_status - Check repository status and staged files", "preview_git_commit - Preview commits safely (dry-run)", "execute_git_commit - Execute commits with force_execute confirmation", "validate_commit_readiness - Comprehensive readiness validation", "generate_and_commit - Complete workflow in one step", "stage_files_and_commit - Selective file commits", "commit_workflow_step - Multi-step workflow with approval", "get_commit_types - See available commit types", "health_check - Verify server and configuration status", "refresh_configuration - Reload Commitizen configuration", ] for tool in tools: print(f" • {tool}") print(f"\n📋 Global Configuration Details:") server_path = get_mcp_server_absolute_path() rules_path = get_global_clinerules_path() config_path = get_cline_config_path() print(f" • MCP Server: {server_path}") print(f" • Global Rules: {rules_path}/commitizen-workflow.md") print(f" • Cline Config: {config_path}") print(f"\n📖 Documentation:") print(f" • QUICK_START.md - Quick setup guide") print(f" • CLINE_SETUP.md - Detailed setup and troubleshooting") print(f" • Global Rules: {rules_path}/commitizen-workflow.md") print(f" • tests/test_mcp_tools.py - Test script") print(f"\n🌟 Benefits of Global Setup:") print(" • Works in ANY git repository automatically") print(" • Consistent commit practices across all projects") print(" • Safety-first approach with preview and validation") print(" • No per-project configuration needed") print(" • Automatic Commitizen configuration detection") if __name__ == "__main__": main()

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