Skip to content

Latest commit

 

History

History
671 lines (492 loc) · 17.4 KB

File metadata and controls

671 lines (492 loc) · 17.4 KB

GitLab MCP Server Integration

Table of Contents


Overview

The GitLab MCP (Model Context Protocol) Server enables Claude Code to interact directly with your GitLab repositories. This integration allows you to perform code reviews, manage branches, push code, and execute other GitLab operations directly from your conversation with Claude.

Key capabilities:

  • Review merge requests and provide feedback
  • Create and manage branches
  • Push code changes to remote repositories
  • Query repository information
  • Manage issues and merge requests
  • Interact with GitLab CI/CD pipelines

Prerequisites

Before installing the GitLab MCP server, ensure you have:

  1. Node.js and npm (version 14 or higher)

    node --version  # Should be v14.0.0 or higher
    npm --version   # Should be 6.0.0 or higher
  2. GitLab Account with access to the repositories you want to work with

  3. GitLab Personal Access Token with appropriate scopes:

    • api - Full API access
    • read_repository - Read repository data
    • write_repository - Write repository data
    • read_user - Read user information
  4. Claude Code CLI installed and configured


Installation

The GitLab MCP server is installed automatically when Claude Code starts, using npx to run the latest version. No manual installation is required.

How it works

The configuration in .mcp.json tells Claude Code to:

  1. Use npx to download and run the latest version of @luiscusihuaman/gitlab-mcp-server
  2. Pass environment variables for authentication
  3. Establish a connection between Claude and your GitLab instance

Verification

To verify the server is working, you can ask Claude:

"List my GitLab projects"

If configured correctly, Claude will return a list of your accessible GitLab repositories.


Configuration

Step 1: Create a GitLab Personal Access Token

  1. Log in to your GitLab instance
  2. Navigate to User Settings > Access Tokens
  3. Click Add new token
  4. Configure the token:
    • Token name: Claude Code MCP
    • Expiration date: Set according to your security policy
    • Scopes: Select the following:
      • api
      • read_repository
      • write_repository
      • read_user
  5. Click Create personal access token
  6. Important: Copy the token immediately - you won't be able to see it again

Step 2: Configure Environment Variables

Create or update your .env file in the workspace root:

# GitLab Configuration
GITLAB_URL=https://gitlab.com
GITLAB_PERSONAL_ACCESS_TOKEN=your-personal-access-token-here

For self-hosted GitLab instances, replace the URL:

GITLAB_URL=https://gitlab.yourcompany.com
GITLAB_PERSONAL_ACCESS_TOKEN=your-personal-access-token-here

Step 3: Verify MCP Configuration

The .mcp.json file should contain the following configuration:

{
  "mcpServers": {
    "gitlab": {
      "command": "npx",
      "args": ["-y", "@luiscusihuaman/gitlab-mcp-server"],
      "env": {
        "GITLAB_URL": "${GITLAB_URL}",
        "GITLAB_PERSONAL_ACCESS_TOKEN": "${GITLAB_PERSONAL_ACCESS_TOKEN}"
      }
    }
  }
}

Configuration breakdown:

  • command: Uses npx to run the package without global installation
  • args:
    • -y: Automatically accepts prompts
    • @luiscusihuaman/gitlab-mcp-server: The npm package to run
  • env: Environment variables passed to the server
    • ${GITLAB_URL}: Replaced with value from your .env file
    • ${GITLAB_PERSONAL_ACCESS_TOKEN}: Replaced with your token from .env

Step 4: Restart Claude Code

After configuration, restart Claude Code to load the new environment variables:

# Exit current session and restart
claude

Usage with Claude Code

Once configured, Claude can interact with GitLab through natural language commands. The MCP server translates your requests into GitLab API calls.

Basic Interaction Pattern

  1. Ask Claude to perform a GitLab operation
  2. Claude analyzes your request and determines the appropriate GitLab API calls
  3. Claude executes the operation via the MCP server
  4. Claude reports the results back to you

Example Interactions

You: "Show me all open merge requests in the project 'myapp'"

You: "Create a new branch called 'feature/user-authentication' from main"

You: "Review the merge request #42 in the 'backend-api' project"

You: "Push my local changes to the remote branch 'feature/payment-integration'"

Common Workflows

Code Review

Code review is one of the most powerful use cases for the GitLab MCP integration. Claude can analyze merge requests, provide feedback, and suggest improvements.

Workflow 1: Review a Specific Merge Request

You: "Review merge request #23 in the 'frontend-app' project"

What Claude does:

  1. Fetches the merge request details
  2. Retrieves the diff/changes
  3. Analyzes the code for:
    • Code quality issues
    • Potential bugs
    • Security vulnerabilities
    • Best practice violations
    • Documentation needs
  4. Provides structured feedback

Example output:

I've reviewed merge request #23 "Add user authentication". Here's my analysis:

Strengths:
- Well-structured authentication flow
- Good error handling in login component
- Comprehensive test coverage

Concerns:
1. Security: Password stored in plain text in component state (line 45)
   Recommendation: Use a secure state management solution

2. Performance: Multiple unnecessary re-renders in AuthContext
   Recommendation: Memoize the context value

3. Code Quality: Magic numbers in token expiration (line 78)
   Recommendation: Extract to configuration constant

Would you like me to provide code snippets for these fixes?

Workflow 2: Review All Open Merge Requests

You: "Review all open merge requests in my current project and prioritize them by importance"

What Claude does:

  1. Lists all open merge requests
  2. Analyzes each for complexity and impact
  3. Provides a prioritized summary

Workflow 3: Comment on Merge Request

You: "Add a comment to merge request #23 suggesting that we extract the authentication logic into a custom hook"

What Claude does:

  1. Locates the merge request
  2. Posts your comment with proper formatting
  3. Confirms the action

Branch Management

Workflow 1: Create a New Branch

You: "Create a new branch called 'feature/dark-mode' from the main branch in project 'frontend-app'"

What Claude does:

  1. Verifies the source branch exists
  2. Creates the new branch
  3. Confirms creation with branch details

Best practice example:

You: "I'm about to work on adding a dark mode feature. Create an appropriate branch following our naming conventions"

Claude will:

  1. Analyze your repository's branching patterns
  2. Suggest a branch name following your conventions (e.g., feature/dark-mode)
  3. Create the branch from the appropriate base
  4. Provide next steps for local checkout

Workflow 2: List Branches

You: "Show me all branches in the 'backend-api' project"

Example output:

Active branches in 'backend-api':

Main branches:
- main (protected)
- develop (protected)

Feature branches:
- feature/payment-gateway (last updated 2 days ago)
- feature/user-roles (last updated 1 week ago)

Bugfix branches:
- bugfix/memory-leak (last updated 3 days ago)

Stale branches (no updates in 30+ days):
- feature/old-experiment (90 days ago)

Would you like me to suggest branches for cleanup?

Workflow 3: Delete a Branch

You: "Delete the branch 'feature/old-experiment' as it's no longer needed"

What Claude does:

  1. Checks if the branch has been merged
  2. Warns if the branch hasn't been merged
  3. Deletes the branch after confirmation
  4. Confirms deletion

Code Pushing

Workflow 1: Push Current Changes

You: "Push my current branch to GitLab"

What Claude does:

  1. Detects your current branch name
  2. Checks for uncommitted changes
  3. Pushes to the remote repository
  4. Provides the branch URL for creating a merge request

Important note: Claude needs to work with your local Git repository. Ensure your current working directory is a Git repository.

Workflow 2: Push with Merge Request Creation

You: "Push my changes to GitLab and create a merge request to main"

What Claude does:

  1. Pushes the current branch
  2. Creates a merge request with:
    • Appropriate title (based on branch name or recent commits)
    • Description (summarizing changes)
    • Target branch set to main
    • Proper labels and assignees (if configured)
  3. Provides the merge request URL

Example interaction:

You: "I've finished implementing the dark mode feature. Push the code and create a merge request."

Claude: "I'll help you push your changes and create a merge request. Let me analyze your commits first."

[Claude analyzes commits]

Claude: "I found 8 commits related to dark mode implementation:
- Add dark mode toggle component
- Implement theme context
- Update color scheme variables
- Add dark mode styles to main components
- Add tests for theme switching
- Update documentation
- Fix contrast issues
- Add user preference persistence

Pushing to remote branch 'feature/dark-mode'...
✓ Branch pushed successfully

Creating merge request...
✓ Merge request #45 created: 'Add dark mode feature'

Title: Add dark mode feature
Target: main
URL: https://gitlab.com/yourorg/frontend-app/-/merge_requests/45

I've included:
- Summary of all 8 commits
- Screenshots from your recent work
- Testing checklist
- Closes #123 (dark mode issue)

Would you like me to assign reviewers?"

Workflow 3: Force Push (Use with Caution)

You: "I rebased my feature branch on main. Force push to update the remote branch."

What Claude does:

  1. Warns about force pushing and its implications
  2. Confirms this is what you want to do
  3. Executes force push with lease (safer than regular force push)
  4. Confirms completion

Claude's warning:

⚠️  Force pushing will overwrite remote history. This affects:
- Any team members working on this branch
- Open merge requests pointing to this branch

I recommend force push with lease (--force-with-lease) which is safer.

Proceed? (yes/no)

Advanced Examples

Example 1: Comprehensive Pre-Merge Review

You: "Before merging MR #42, perform a comprehensive review including code quality, security, performance, and test coverage"

What Claude does:

  1. Fetches the complete merge request
  2. Analyzes code changes across multiple dimensions:
    • Security: Scans for vulnerabilities, injection risks, authentication issues
    • Performance: Identifies inefficient patterns, N+1 queries, memory leaks
    • Code Quality: Checks formatting, naming conventions, code complexity
    • Test Coverage: Analyzes test files and coverage
    • Documentation: Verifies comments, README updates, API docs
  3. Provides a detailed report with severity levels
  4. Suggests specific improvements with code examples

Example 2: Automated Branch Cleanup

You: "Identify all stale branches (no updates in 60+ days) that have been merged and create a cleanup plan"

What Claude does:

  1. Lists all branches with last commit dates
  2. Filters for branches older than 60 days
  3. Checks merge status for each branch
  4. Provides a categorized list:
    • Safe to delete (merged)
    • Review needed (not merged but old)
    • Keep (protected or recent activity)
  5. Offers to delete safe branches after confirmation

Example 3: Merge Request Template Application

You: "Create a merge request for my current branch using our standard template with all sections filled out based on my commits"

What Claude does:

  1. Analyzes your commits and code changes
  2. Loads your merge request template
  3. Intelligently fills in:
    • Title from branch name or primary commit
    • Description summarizing changes
    • Type of change (feature/bugfix/refactor)
    • Breaking changes (if any)
    • Testing checklist
    • Related issues
    • Screenshots (if UI changes detected)
  4. Creates the merge request with complete information

Example 4: CI/CD Pipeline Analysis

You: "Check the pipeline status for merge request #38 and explain any failures"

What Claude does:

  1. Fetches pipeline information for the merge request
  2. Analyzes job statuses
  3. For failed jobs:
    • Retrieves error logs
    • Explains the failure in plain language
    • Suggests fixes
  4. Provides a summary with actionable next steps

Troubleshooting

Issue 1: "GitLab MCP server not responding"

Symptoms:

  • Claude says it can't connect to GitLab
  • GitLab commands time out

Solutions:

  1. Verify environment variables:

    # Check if variables are set
    echo $GITLAB_URL
    echo $GITLAB_PERSONAL_ACCESS_TOKEN
  2. Restart Claude Code:

    # Exit and restart
    exit
    claude
  3. Test token validity:

    # Test with curl
    curl --header "PRIVATE-TOKEN: your-token" "https://gitlab.com/api/v4/projects"
  4. Check network connectivity:

    # Ping GitLab instance
    ping gitlab.com

Issue 2: "Permission denied" errors

Symptoms:

  • Claude reports insufficient permissions
  • Operations fail with 403 errors

Solutions:

  1. Verify token scopes:

    • Go to GitLab → User Settings → Access Tokens
    • Ensure the token has all required scopes:
      • api
      • read_repository
      • write_repository
      • read_user
  2. Check project access:

    • Verify you have the appropriate role in the project (Developer or Maintainer)
    • For protected branches, ensure you have permission to push
  3. Regenerate token:

    • Create a new token with correct scopes
    • Update .env file with new token
    • Restart Claude Code

Issue 3: "Project not found"

Symptoms:

  • Claude can't find your project
  • Project list is empty

Solutions:

  1. Use full project path:

    Instead of: "Review MR #42"
    Use: "Review MR #42 in project 'myorg/myapp'"
    
  2. Verify project visibility:

    • Check if the project is private and you have access
    • Ensure your token has access to the project's group
  3. Use project ID instead of name:

    You: "Show me merge requests in project ID 12345"
    

Issue 4: Rate limiting

Symptoms:

  • Operations slow down after many requests
  • "Rate limit exceeded" errors

Solutions:

  1. Wait and retry:

    • GitLab API has rate limits (typically 600 requests per minute)
    • Wait a minute before retrying
  2. Batch operations:

    Instead of: Multiple separate requests
    Use: "Review all open merge requests in one analysis"
    
  3. For self-hosted GitLab:

    • Contact your administrator to adjust rate limits if needed

Security Best Practices

1. Token Management

DO:

  • Store tokens in .env files that are in .gitignore
  • Use tokens with minimal required scopes
  • Set expiration dates on tokens
  • Rotate tokens regularly (every 90 days recommended)
  • Use different tokens for different purposes

DON'T:

  • Commit tokens to version control
  • Share tokens between team members
  • Use tokens with sudo scope unless absolutely necessary
  • Store tokens in configuration files that are tracked by Git

2. Access Control

Principle of Least Privilege:

For read-only operations: Use a token with only `read_repository` scope
For code reviews: Add `read_api` scope
For pushing code: Add `write_repository` scope only when needed

3. Environment Isolation

Development vs. Production:

Development .env:

GITLAB_URL=https://gitlab.dev.company.com
GITLAB_PERSONAL_ACCESS_TOKEN=dev-token-here

Production .env:

GITLAB_URL=https://gitlab.company.com
GITLAB_PERSONAL_ACCESS_TOKEN=prod-token-here

Keep these files separate and never use production tokens in development.

4. Audit and Monitoring

Regularly review:

  • Active tokens in GitLab settings
  • Recent API activity in audit logs
  • Unusual access patterns

5. Incident Response

If a token is compromised:

  1. Immediately revoke the token in GitLab
  2. Review recent activity for unauthorized access
  3. Generate a new token with appropriate scopes
  4. Update the .env file
  5. Restart Claude Code
  6. Document the incident

Additional Resources


Support and Feedback

If you encounter issues not covered in this documentation:

  1. Check the GitLab MCP Server GitHub Issues
  2. Review GitLab API status page for service interruptions
  3. Consult your organization's internal documentation for self-hosted instances

Last Updated: January 2025 Version: 1.0 Maintainer: Documentation Team