feat(mcp): Implement Git Operations MCP Server #58

Open
opened 2026-01-03 01:25:46 +00:00 by cardosofelipe · 1 comment

Summary

Implement the Git Operations MCP server that provides version control capabilities for agents. This enables agents to clone repositories, create branches, commit changes, and manage pull requests across multiple Git providers.

Sub-Tasks

1. Project Setup

  • Initialize FastMCP project in mcp-servers/git-ops/
  • Create pyproject.toml with dependencies
  • Add fastmcp>=0.4.0, gitpython>=3.1.0, httpx>=0.25.0
  • Add pygithub>=2.0.0, python-gitlab>=4.0.0
  • Create Docker configuration (Dockerfile, .dockerignore)
  • Add to docker-compose.dev.yml
  • Create README.md with setup instructions

2. Workspace Management (workspace.py)

  • Create WorkspaceManager class
  • Define workspace base path (/var/syndarix/workspaces/)
  • Create workspace directory structure per project
  • Implement get_workspace(project_id) method
  • Implement create_workspace(project_id) method
  • Implement delete_workspace(project_id) method
  • Add workspace cleanup for stale workspaces (>7 days unused)
  • Implement workspace locking to prevent concurrent access
  • Handle disk space monitoring and alerts
  • Add workspace size limits per project

3. Credential Management (credentials.py)

  • Create CredentialStore class
  • Store Git credentials securely (encrypted at rest)
  • Support multiple credential types (SSH key, token, username/password)
  • Implement per-project credential isolation
  • Add credential rotation support
  • Integrate with backend secrets management
  • Create temporary credential files for Git operations
  • Clean up credentials after use

4. Git Wrapper (git_wrapper.py)

  • Create GitWrapper class using gitpython
  • Implement clone(repo_url, workspace, branch) method
  • Implement checkout(branch) method
  • Implement create_branch(branch_name, base) method
  • Implement delete_branch(branch_name) method
  • Implement list_branches() method
  • Implement status() method (modified, staged, untracked)
  • Implement add(files) method
  • Implement commit(message, author) method
  • Implement push(branch, force) method
  • Implement pull(branch) method
  • Implement fetch() method
  • Implement diff(base, target) method
  • Implement log(limit) method
  • Implement reset(commit, mode) method
  • Add proper error handling for all operations
  • Handle large file detection (.gitattributes, LFS)

5. Gitea Provider (providers/gitea.py)

  • Create GiteaProvider class
  • Implement API client with authentication
  • Implement create_pull_request() method
  • Implement list_pull_requests() method
  • Implement get_pull_request() method
  • Implement merge_pull_request() method
  • Implement close_pull_request() method
  • Implement add_pr_comment() method
  • Implement add_pr_reviewer() method
  • Implement get_pr_diff() method
  • Implement list_branches() method (remote)
  • Implement create_branch() method (remote)
  • Implement delete_branch() method (remote)
  • Handle API rate limiting
  • Add pagination support

6. GitHub Provider (providers/github.py)

  • Create GitHubProvider class using PyGithub
  • Implement API client with token authentication
  • Implement create_pull_request() method
  • Implement list_pull_requests() method
  • Implement get_pull_request() method
  • Implement merge_pull_request() method
  • Implement close_pull_request() method
  • Implement add_pr_comment() method
  • Implement add_pr_reviewer() method
  • Implement get_pr_diff() method
  • Implement list_branches() method
  • Implement create_branch() method
  • Implement delete_branch() method
  • Handle API rate limiting (GitHub's limits)
  • Add pagination support
  • Support GitHub Enterprise

7. GitLab Provider (providers/gitlab.py)

  • Create GitLabProvider class using python-gitlab
  • Implement API client with token authentication
  • Implement create_merge_request() method
  • Implement list_merge_requests() method
  • Implement get_merge_request() method
  • Implement merge_merge_request() method
  • Implement close_merge_request() method
  • Implement add_mr_comment() method
  • Implement add_mr_reviewer() method
  • Implement get_mr_diff() method
  • Implement list_branches() method
  • Implement create_branch() method
  • Implement delete_branch() method
  • Handle API rate limiting
  • Add pagination support
  • Support GitLab self-hosted

8. Provider Factory (providers/factory.py)

  • Create ProviderFactory class
  • Auto-detect provider from repo URL
  • Support provider override in configuration
  • Cache provider instances per repository
  • Handle provider-specific URL formats

9. MCP Tools Implementation (server.py)

  • Implement clone_repo tool
    • Accept project_id, repo_url, branch
    • Store credentials securely
    • Return workspace path
  • Implement create_branch tool
    • Accept project_id, branch_name, base_branch
    • Validate branch naming conventions
    • Return branch info
  • Implement list_branches tool
    • Accept project_id
    • Return local and remote branches
  • Implement checkout_branch tool
    • Accept project_id, branch
    • Handle uncommitted changes
  • Implement commit_changes tool
    • Accept project_id, message, files (optional)
    • Auto-stage if no files specified
    • Validate commit message format
    • Return commit hash
  • Implement push_branch tool
    • Accept project_id, branch, force flag
    • Handle push rejection
    • Return push result
  • Implement pull_changes tool
    • Accept project_id, branch
    • Handle merge conflicts
    • Return updated files
  • Implement get_diff tool
    • Accept project_id, base, target
    • Return unified diff format
    • Include file statistics
  • Implement get_status tool
    • Accept project_id
    • Return modified, staged, untracked files
  • Implement create_pull_request tool
    • Accept project_id, title, description, source, target
    • Accept labels, reviewers
    • Return PR URL and number
  • Implement list_pull_requests tool
    • Accept project_id, state filter
    • Return PR list with metadata
  • Implement merge_pull_request tool
    • Accept project_id, pr_number, strategy
    • Support merge, squash, rebase strategies
    • Delete source branch option
    • Return merge result
  • Implement add_pr_comment tool
    • Accept project_id, pr_number, body
    • Support inline comments (file, line)

10. Branch Naming Conventions

  • Define naming patterns (feature/, bugfix/, hotfix/, etc.)
  • Implement validation function
  • Add auto-correction suggestions
  • Support custom patterns via configuration

11. Conflict Detection

  • Detect merge conflicts before operations
  • Report conflicting files
  • Provide conflict markers in output
  • Suggest resolution strategies

12. Error Handling

  • Create GitError base exception
  • Create CloneError for clone failures
  • Create PushError for push failures
  • Create MergeConflictError for conflicts
  • Create AuthenticationError for auth issues
  • Create ProviderError for API failures
  • Map provider-specific errors to standard errors

13. Docker & Deployment

  • Create optimized Dockerfile
  • Install Git CLI in container
  • Configure SSH for Git operations
  • Add health check endpoint
  • Mount workspace volume
  • Configure resource limits

14. Testing

  • Create unit tests for git_wrapper.py
  • Create unit tests for each provider
  • Create integration tests with test repositories
  • Test workspace management
  • Test credential handling
  • Test conflict detection
  • Achieve >90% code coverage

15. Documentation

  • Document all MCP tools with examples
  • Create provider setup guides (Gitea, GitHub, GitLab)
  • Document branch naming conventions
  • Add troubleshooting guide
  • Document workspace management

Technical Specifications

MCP Tools

@mcp.tool()
async def clone_repo(
    project_id: str,
    repo_url: str,
    branch: str = "main",
    credentials: dict = None,
) -> CloneResult:
    """Clone a repository for a project."""

@mcp.tool()
async def create_branch(
    project_id: str,
    branch_name: str,
    base_branch: str = "main",
) -> BranchResult:
    """Create a new branch."""

@mcp.tool()
async def commit_changes(
    project_id: str,
    message: str,
    files: list[str] = None,
    author_name: str = None,
    author_email: str = None,
) -> CommitResult:
    """Commit staged changes."""

@mcp.tool()
async def push_branch(
    project_id: str,
    branch: str = None,
    force: bool = False,
) -> PushResult:
    """Push branch to remote."""

@mcp.tool()
async def create_pull_request(
    project_id: str,
    title: str,
    description: str,
    source_branch: str,
    target_branch: str = "main",
    labels: list[str] = None,
    reviewers: list[str] = None,
) -> PRResult:
    """Create a pull request."""

@mcp.tool()
async def merge_pull_request(
    project_id: str,
    pr_number: int,
    merge_strategy: str = "squash",
    delete_source_branch: bool = True,
) -> MergeResult:
    """Merge a pull request."""

@mcp.tool()
async def get_diff(
    project_id: str,
    base: str = "HEAD~1",
    target: str = "HEAD",
) -> DiffResult:
    """Get diff between commits/branches."""

@mcp.tool()
async def get_status(
    project_id: str,
) -> StatusResult:
    """Get repository status."""

Acceptance Criteria

  • Clone repositories with authentication working
  • Branch operations (create, list, delete) working
  • Commit and push operations working
  • Pull and fetch operations working
  • Diff generation working
  • Gitea PR operations complete
  • GitHub PR operations complete
  • GitLab MR operations complete
  • Merge with all strategies (merge, squash, rebase)
  • Workspace isolation per project enforced
  • Credential management secure
  • Conflict detection working
  • All MCP tools documented and working
  • Unit tests >90% coverage
  • Integration tests with real Git
  • Docker container builds and runs
  • Documentation complete

Dependencies

  • Depends on: #55 (MCP Client Infrastructure)
  • Blocks: Phase 3 Agent Orchestration (code changes)

Assignable To

backend-engineer agent

## Summary Implement the Git Operations MCP server that provides version control capabilities for agents. This enables agents to clone repositories, create branches, commit changes, and manage pull requests across multiple Git providers. ## Sub-Tasks ### 1. Project Setup - [ ] Initialize FastMCP project in `mcp-servers/git-ops/` - [ ] Create `pyproject.toml` with dependencies - [ ] Add `fastmcp>=0.4.0`, `gitpython>=3.1.0`, `httpx>=0.25.0` - [ ] Add `pygithub>=2.0.0`, `python-gitlab>=4.0.0` - [ ] Create Docker configuration (`Dockerfile`, `.dockerignore`) - [ ] Add to `docker-compose.dev.yml` - [ ] Create `README.md` with setup instructions ### 2. Workspace Management (`workspace.py`) - [ ] Create `WorkspaceManager` class - [ ] Define workspace base path (`/var/syndarix/workspaces/`) - [ ] Create workspace directory structure per project - [ ] Implement `get_workspace(project_id)` method - [ ] Implement `create_workspace(project_id)` method - [ ] Implement `delete_workspace(project_id)` method - [ ] Add workspace cleanup for stale workspaces (>7 days unused) - [ ] Implement workspace locking to prevent concurrent access - [ ] Handle disk space monitoring and alerts - [ ] Add workspace size limits per project ### 3. Credential Management (`credentials.py`) - [ ] Create `CredentialStore` class - [ ] Store Git credentials securely (encrypted at rest) - [ ] Support multiple credential types (SSH key, token, username/password) - [ ] Implement per-project credential isolation - [ ] Add credential rotation support - [ ] Integrate with backend secrets management - [ ] Create temporary credential files for Git operations - [ ] Clean up credentials after use ### 4. Git Wrapper (`git_wrapper.py`) - [ ] Create `GitWrapper` class using gitpython - [ ] Implement `clone(repo_url, workspace, branch)` method - [ ] Implement `checkout(branch)` method - [ ] Implement `create_branch(branch_name, base)` method - [ ] Implement `delete_branch(branch_name)` method - [ ] Implement `list_branches()` method - [ ] Implement `status()` method (modified, staged, untracked) - [ ] Implement `add(files)` method - [ ] Implement `commit(message, author)` method - [ ] Implement `push(branch, force)` method - [ ] Implement `pull(branch)` method - [ ] Implement `fetch()` method - [ ] Implement `diff(base, target)` method - [ ] Implement `log(limit)` method - [ ] Implement `reset(commit, mode)` method - [ ] Add proper error handling for all operations - [ ] Handle large file detection (.gitattributes, LFS) ### 5. Gitea Provider (`providers/gitea.py`) - [ ] Create `GiteaProvider` class - [ ] Implement API client with authentication - [ ] Implement `create_pull_request()` method - [ ] Implement `list_pull_requests()` method - [ ] Implement `get_pull_request()` method - [ ] Implement `merge_pull_request()` method - [ ] Implement `close_pull_request()` method - [ ] Implement `add_pr_comment()` method - [ ] Implement `add_pr_reviewer()` method - [ ] Implement `get_pr_diff()` method - [ ] Implement `list_branches()` method (remote) - [ ] Implement `create_branch()` method (remote) - [ ] Implement `delete_branch()` method (remote) - [ ] Handle API rate limiting - [ ] Add pagination support ### 6. GitHub Provider (`providers/github.py`) - [ ] Create `GitHubProvider` class using PyGithub - [ ] Implement API client with token authentication - [ ] Implement `create_pull_request()` method - [ ] Implement `list_pull_requests()` method - [ ] Implement `get_pull_request()` method - [ ] Implement `merge_pull_request()` method - [ ] Implement `close_pull_request()` method - [ ] Implement `add_pr_comment()` method - [ ] Implement `add_pr_reviewer()` method - [ ] Implement `get_pr_diff()` method - [ ] Implement `list_branches()` method - [ ] Implement `create_branch()` method - [ ] Implement `delete_branch()` method - [ ] Handle API rate limiting (GitHub's limits) - [ ] Add pagination support - [ ] Support GitHub Enterprise ### 7. GitLab Provider (`providers/gitlab.py`) - [ ] Create `GitLabProvider` class using python-gitlab - [ ] Implement API client with token authentication - [ ] Implement `create_merge_request()` method - [ ] Implement `list_merge_requests()` method - [ ] Implement `get_merge_request()` method - [ ] Implement `merge_merge_request()` method - [ ] Implement `close_merge_request()` method - [ ] Implement `add_mr_comment()` method - [ ] Implement `add_mr_reviewer()` method - [ ] Implement `get_mr_diff()` method - [ ] Implement `list_branches()` method - [ ] Implement `create_branch()` method - [ ] Implement `delete_branch()` method - [ ] Handle API rate limiting - [ ] Add pagination support - [ ] Support GitLab self-hosted ### 8. Provider Factory (`providers/factory.py`) - [ ] Create `ProviderFactory` class - [ ] Auto-detect provider from repo URL - [ ] Support provider override in configuration - [ ] Cache provider instances per repository - [ ] Handle provider-specific URL formats ### 9. MCP Tools Implementation (`server.py`) - [ ] Implement `clone_repo` tool - [ ] Accept project_id, repo_url, branch - [ ] Store credentials securely - [ ] Return workspace path - [ ] Implement `create_branch` tool - [ ] Accept project_id, branch_name, base_branch - [ ] Validate branch naming conventions - [ ] Return branch info - [ ] Implement `list_branches` tool - [ ] Accept project_id - [ ] Return local and remote branches - [ ] Implement `checkout_branch` tool - [ ] Accept project_id, branch - [ ] Handle uncommitted changes - [ ] Implement `commit_changes` tool - [ ] Accept project_id, message, files (optional) - [ ] Auto-stage if no files specified - [ ] Validate commit message format - [ ] Return commit hash - [ ] Implement `push_branch` tool - [ ] Accept project_id, branch, force flag - [ ] Handle push rejection - [ ] Return push result - [ ] Implement `pull_changes` tool - [ ] Accept project_id, branch - [ ] Handle merge conflicts - [ ] Return updated files - [ ] Implement `get_diff` tool - [ ] Accept project_id, base, target - [ ] Return unified diff format - [ ] Include file statistics - [ ] Implement `get_status` tool - [ ] Accept project_id - [ ] Return modified, staged, untracked files - [ ] Implement `create_pull_request` tool - [ ] Accept project_id, title, description, source, target - [ ] Accept labels, reviewers - [ ] Return PR URL and number - [ ] Implement `list_pull_requests` tool - [ ] Accept project_id, state filter - [ ] Return PR list with metadata - [ ] Implement `merge_pull_request` tool - [ ] Accept project_id, pr_number, strategy - [ ] Support merge, squash, rebase strategies - [ ] Delete source branch option - [ ] Return merge result - [ ] Implement `add_pr_comment` tool - [ ] Accept project_id, pr_number, body - [ ] Support inline comments (file, line) ### 10. Branch Naming Conventions - [ ] Define naming patterns (feature/, bugfix/, hotfix/, etc.) - [ ] Implement validation function - [ ] Add auto-correction suggestions - [ ] Support custom patterns via configuration ### 11. Conflict Detection - [ ] Detect merge conflicts before operations - [ ] Report conflicting files - [ ] Provide conflict markers in output - [ ] Suggest resolution strategies ### 12. Error Handling - [ ] Create `GitError` base exception - [ ] Create `CloneError` for clone failures - [ ] Create `PushError` for push failures - [ ] Create `MergeConflictError` for conflicts - [ ] Create `AuthenticationError` for auth issues - [ ] Create `ProviderError` for API failures - [ ] Map provider-specific errors to standard errors ### 13. Docker & Deployment - [ ] Create optimized `Dockerfile` - [ ] Install Git CLI in container - [ ] Configure SSH for Git operations - [ ] Add health check endpoint - [ ] Mount workspace volume - [ ] Configure resource limits ### 14. Testing - [ ] Create unit tests for `git_wrapper.py` - [ ] Create unit tests for each provider - [ ] Create integration tests with test repositories - [ ] Test workspace management - [ ] Test credential handling - [ ] Test conflict detection - [ ] Achieve >90% code coverage ### 15. Documentation - [ ] Document all MCP tools with examples - [ ] Create provider setup guides (Gitea, GitHub, GitLab) - [ ] Document branch naming conventions - [ ] Add troubleshooting guide - [ ] Document workspace management ## Technical Specifications ### MCP Tools ```python @mcp.tool() async def clone_repo( project_id: str, repo_url: str, branch: str = "main", credentials: dict = None, ) -> CloneResult: """Clone a repository for a project.""" @mcp.tool() async def create_branch( project_id: str, branch_name: str, base_branch: str = "main", ) -> BranchResult: """Create a new branch.""" @mcp.tool() async def commit_changes( project_id: str, message: str, files: list[str] = None, author_name: str = None, author_email: str = None, ) -> CommitResult: """Commit staged changes.""" @mcp.tool() async def push_branch( project_id: str, branch: str = None, force: bool = False, ) -> PushResult: """Push branch to remote.""" @mcp.tool() async def create_pull_request( project_id: str, title: str, description: str, source_branch: str, target_branch: str = "main", labels: list[str] = None, reviewers: list[str] = None, ) -> PRResult: """Create a pull request.""" @mcp.tool() async def merge_pull_request( project_id: str, pr_number: int, merge_strategy: str = "squash", delete_source_branch: bool = True, ) -> MergeResult: """Merge a pull request.""" @mcp.tool() async def get_diff( project_id: str, base: str = "HEAD~1", target: str = "HEAD", ) -> DiffResult: """Get diff between commits/branches.""" @mcp.tool() async def get_status( project_id: str, ) -> StatusResult: """Get repository status.""" ``` ## Acceptance Criteria - [ ] Clone repositories with authentication working - [ ] Branch operations (create, list, delete) working - [ ] Commit and push operations working - [ ] Pull and fetch operations working - [ ] Diff generation working - [ ] Gitea PR operations complete - [ ] GitHub PR operations complete - [ ] GitLab MR operations complete - [ ] Merge with all strategies (merge, squash, rebase) - [ ] Workspace isolation per project enforced - [ ] Credential management secure - [ ] Conflict detection working - [ ] All MCP tools documented and working - [ ] Unit tests >90% coverage - [ ] Integration tests with real Git - [ ] Docker container builds and runs - [ ] Documentation complete ## Dependencies - Depends on: #55 (MCP Client Infrastructure) - Blocks: Phase 3 Agent Orchestration (code changes) ## Assignable To backend-engineer agent
cardosofelipe added the mcpphase-2 labels 2026-01-03 01:26:16 +00:00
Author
Owner

Sub-Issues Created

This issue has been broken down into the following sub-issues for manageable implementation:

# Issue Description Status
1 #105 Foundation & Core Setup In Progress
2 #106 Git Wrapper Implementation 📋 Pending
3 #107 Workspace Management 📋 Pending
4 #108 Gitea Provider 📋 Pending
5 #109 MCP Tools Integration 📋 Pending
6 #110 GitHub Provider (Optional) 📋 Pending

Implementation Order:

  1. Foundation (#105) - Core models, exceptions, project structure
  2. Git Wrapper (#106) + Workspace (#107) - Can be done in parallel
  3. Gitea Provider (#108) - Remote API operations
  4. MCP Tools (#109) - Integrate everything
  5. GitHub Provider (#110) - If time permits and patterns are clean

Branch: feature/58-git-operations-mcp

## Sub-Issues Created This issue has been broken down into the following sub-issues for manageable implementation: | # | Issue | Description | Status | |---|-------|-------------|--------| | 1 | #105 | Foundation & Core Setup | ⏳ In Progress | | 2 | #106 | Git Wrapper Implementation | 📋 Pending | | 3 | #107 | Workspace Management | 📋 Pending | | 4 | #108 | Gitea Provider | 📋 Pending | | 5 | #109 | MCP Tools Integration | 📋 Pending | | 6 | #110 | GitHub Provider (Optional) | 📋 Pending | **Implementation Order:** 1. Foundation (#105) - Core models, exceptions, project structure 2. Git Wrapper (#106) + Workspace (#107) - Can be done in parallel 3. Gitea Provider (#108) - Remote API operations 4. MCP Tools (#109) - Integrate everything 5. GitHub Provider (#110) - If time permits and patterns are clean **Branch:** `feature/58-git-operations-mcp`
Sign in to join this conversation.