Package Exports
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (nerdcode-gitlab-server) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
GitLab MCP Server
A production-ready Model Context Protocol (MCP) server that provides seamless integration with GitLab repositories. This server offers two powerful tools for repository interaction: scanning complete repository file structures and reading specific file contents through GitLab's REST API.
Overview
The GitLab MCP Server is designed to work with self-hosted GitLab instances and provides robust, error-resilient tools for repository analysis and file access. Built with TypeScript and featuring comprehensive error handling, retry mechanisms, and production-ready architecture, this server enables AI assistants and other MCP clients to efficiently interact with GitLab repositories.
Key Features
- Complete Repository Scanning: Recursively scan entire GitLab repositories to retrieve comprehensive file structure listings
- Individual File Reading: Access and read the contents of specific files within GitLab repositories
- Robust Error Handling: Comprehensive error handling for network issues, authentication problems, and API limitations
- Retry Mechanisms: Built-in exponential backoff retry logic for handling transient failures and rate limiting
- Production Ready: Thoroughly tested, documented, and designed for production environments
- Self-Hosted GitLab Support: Optimized for self-hosted GitLab instances with flexible URL handling
Installation
Prerequisites
- Node.js 18.0 or higher
- npm or yarn package manager
- Access to a GitLab instance (self-hosted or GitLab.com)
Setup Instructions
Clone or download the server files
# Ensure you have the following files: # - gitlab-mcp-server.ts # - package.json # - tsconfig.json # - test-server.js
Install dependencies
npm install
Build the TypeScript code
npm run build
Validate the installation
npm test
Start the server
npm start
Tools Reference
Tool 1: gitlab-repo-scanner
The gitlab-repo-scanner
tool provides comprehensive repository analysis by scanning the entire file structure of a GitLab repository and returning a complete list of all files contained within it.
Purpose
This tool is designed to give users and AI assistants a complete overview of a repository's structure, enabling them to understand the codebase organization, identify key files, and make informed decisions about which files to examine in detail.
Parameters
Parameter | Type | Required | Description | Example |
---|---|---|---|---|
repo_url |
string | Yes | The root URL of the GitLab repository to scan | "http://localhost/root/momentum" |
Usage Example
{
"tool": "gitlab-repo-scanner",
"parameters": {
"repo_url": "http://localhost/root/momentum"
}
}
Expected Output
The tool returns a structured response containing:
- Total number of files found in the repository
- Complete list of file paths, sorted alphabetically
- Repository URL for reference
Example output format:
Found 247 files in repository: http://localhost/root/momentum
File paths:
.gitignore
README.md
LH_BatchEJB/pom.xml
LH_BatchEJB/src/main/java/momentum/wealth/batch/BatchJobManagerBean.java
LH_BatchEJB/src/main/java/momentum/wealth/batch/processors/DataProcessor.java
...
Error Handling
The tool handles various error scenarios gracefully:
- Invalid URL Format: Returns clear error message for malformed URLs
- Project Not Found: Specific error when the repository doesn't exist
- Authentication Required: Clear indication when access requires authentication
- Network Issues: Automatic retry with exponential backoff for transient failures
- Rate Limiting: Handles GitLab API rate limits with appropriate retry delays
Tool 2: gitlab-file-reader
The gitlab-file-reader
tool enables reading the complete contents of specific files within GitLab repositories, providing direct access to source code, configuration files, documentation, and other repository assets.
Purpose
This tool allows detailed examination of individual files within a repository, enabling code analysis, configuration review, and content extraction for AI assistants and other automated processes.
Parameters
Parameter | Type | Required | Description | Example |
---|---|---|---|---|
repo_url |
string | Yes | The root URL of the GitLab repository containing the file | "http://localhost/root/momentum" |
path |
string | Yes | The relative path to the file within the repository | "LH_BatchEJB/src/main/java/momentum/wealth/batch/BatchJobManagerBean.java" |
Usage Example
{
"tool": "gitlab-file-reader",
"parameters": {
"repo_url": "http://localhost/root/momentum",
"path": "LH_BatchEJB/src/main/java/momentum/wealth/batch/BatchJobManagerBean.java"
}
}
Expected Output
The tool returns a structured response containing:
- File path for reference
- Repository URL for context
- Complete file contents as raw text
Example output format:
File: LH_BatchEJB/src/main/java/momentum/wealth/batch/BatchJobManagerBean.java
Repository: http://localhost/root/momentum
Content:
package momentum.wealth.batch;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
...
Error Handling
The tool provides comprehensive error handling for various scenarios:
- File Not Found: Clear error when the specified file doesn't exist
- Invalid Path: Handles malformed or inaccessible file paths
- Authentication Issues: Specific errors for access permission problems
- Network Failures: Automatic retry mechanisms for connection issues
- Rate Limiting: Intelligent handling of API rate limits
Architecture and Implementation Details
Core Components
The GitLab MCP Server is built using several key components that work together to provide reliable and efficient repository interaction:
MCP Server Framework
The server utilizes the official Model Context Protocol SDK, specifically the @modelcontextprotocol/sdk
package, which provides the foundational framework for creating MCP-compliant servers. This ensures compatibility with MCP clients and adherence to protocol standards.
GitLab API Integration
The server integrates with GitLab's REST API v4, utilizing two primary endpoints:
Repository Tree Endpoint:
GET /api/v4/projects/:id/repository/tree?recursive=true
- Used by the
gitlab-repo-scanner
tool - Retrieves complete repository file structure
- Supports recursive traversal of directories
- Used by the
Repository Files Endpoint:
GET /api/v4/projects/:id/repository/files/:file_path/raw
- Used by the
gitlab-file-reader
tool - Retrieves raw file contents
- Handles various file types and encodings
- Used by the
Error Handling Architecture
The server implements a multi-layered error handling approach:
Retry Mechanism: The retryWithBackoff
function implements exponential backoff retry logic with configurable parameters:
- Maximum retry attempts: 3 (for network errors)
- Base delay: 1000ms
- Exponential multiplier: 2x per attempt
- Smart error classification to avoid retrying non-transient errors
Error Classification: Errors are categorized and handled appropriately:
- Transient Errors: Network timeouts, connection failures (retried)
- Client Errors: Invalid URLs, malformed requests (not retried)
- Authentication Errors: 401/403 responses (not retried, clear error message)
- Rate Limiting: 429 responses (retried with longer delays)
URL Processing and Project Resolution
The server includes sophisticated URL processing capabilities to handle various GitLab URL formats and extract project information:
URL Parsing
The extractProjectPath
function processes GitLab repository URLs to extract the project path:
- Handles both HTTP and HTTPS protocols
- Supports custom ports and subdomains
- Extracts namespace and project name from URL path
Project ID Resolution
The getProjectId
function resolves project paths to GitLab project IDs:
- Makes API calls to GitLab's projects endpoint
- Handles URL encoding for special characters in project names
- Provides specific error messages for various failure scenarios
Security Considerations
The server is designed with security best practices in mind:
Input Validation
All input parameters are validated using Zod schemas:
- URL format validation
- Path sanitization
- Parameter type checking
Error Information Disclosure
Error messages are carefully crafted to provide useful information without exposing sensitive system details:
- Generic error messages for internal failures
- Specific guidance for user-correctable issues
- No exposure of internal API endpoints or system paths
Configuration and Customization
Environment Variables
While the server works out-of-the-box for most use cases, several aspects can be customized through environment variables:
# Optional: Set custom timeout for API requests (default: 30 seconds)
GITLAB_API_TIMEOUT=30000
# Optional: Set custom retry attempts (default: 3)
GITLAB_MAX_RETRIES=3
# Optional: Set custom base delay for retries (default: 1000ms)
GITLAB_RETRY_BASE_DELAY=1000
Authentication Configuration
For private repositories or GitLab instances requiring authentication, you can extend the server to include authentication headers:
// Example authentication header addition
const headers = {
'Private-Token': process.env.GITLAB_TOKEN,
'Content-Type': 'application/json'
};
Troubleshooting Guide
Common Issues and Solutions
Connection Refused Errors
Symptom: Error scanning repository: connect ECONNREFUSED
Causes and Solutions:
- GitLab instance is not running: Verify GitLab service status
- Incorrect URL: Double-check the repository URL format
- Network connectivity: Test network access to GitLab instance
- Firewall restrictions: Ensure required ports are accessible
Authentication Errors
Symptom: Authentication required for project: root/momentum
Causes and Solutions:
- Private repository: Configure authentication tokens
- Insufficient permissions: Verify user access to repository
- Token expiration: Refresh or regenerate access tokens
Rate Limiting Issues
Symptom: Rate limit exceeded. Please try again later.
Causes and Solutions:
- High API usage: Implement request throttling in client applications
- Concurrent requests: Reduce parallel request volume
- GitLab configuration: Adjust rate limiting settings if self-hosted
File Not Found Errors
Symptom: File not found: path/to/file.java
Causes and Solutions:
- Incorrect file path: Verify file exists in repository
- Case sensitivity: Ensure correct case for file and directory names
- Branch specification: File may exist on different branch (future enhancement)
Debugging and Logging
For development and debugging purposes, you can enable verbose logging by modifying the server code:
// Add debug logging
console.log(`Making API request to: ${apiUrl}`);
console.log(`Response status: ${response.status}`);
Performance Considerations
API Rate Limiting
GitLab instances typically implement rate limiting to prevent API abuse. The server handles this through:
- Exponential Backoff: Automatic retry with increasing delays
- Request Throttling: Built-in delays between requests
- Error Handling: Graceful degradation when limits are reached
Memory Usage
The server is designed to be memory-efficient:
- Streaming Responses: Large files are handled without loading entirely into memory
- Garbage Collection: Proper cleanup of HTTP connections and response objects
- Resource Management: Automatic cleanup of failed requests
Network Optimization
Several optimizations improve network performance:
- Connection Reuse: HTTP keep-alive for multiple requests
- Compression: Automatic handling of compressed responses
- Timeout Management: Appropriate timeouts to prevent hanging connections
Future Enhancements
Planned Features
- Branch Support: Ability to specify Git branches for file operations
- Authentication Integration: Built-in support for GitLab tokens and OAuth
- Caching Layer: Local caching of repository metadata for improved performance
- Batch Operations: Support for multiple file operations in single requests
- Webhook Integration: Real-time repository change notifications
Extension Points
The server architecture supports easy extension for additional functionality:
- Custom Tools: Add new MCP tools for specific GitLab operations
- Middleware: Implement request/response middleware for logging or transformation
- Plugin System: Modular architecture for optional features
Contributing and Support
Development Setup
For developers wanting to contribute or customize the server:
- Fork the repository and create a development branch
- Install development dependencies:
npm install
- Run tests:
npm test
- Build and test changes:
npm run build && npm start
- Submit pull requests with comprehensive test coverage
Code Style and Standards
The project follows TypeScript best practices:
- Strict TypeScript: All code uses strict type checking
- ESLint Configuration: Consistent code formatting and style
- Documentation: Comprehensive JSDoc comments for all functions
- Error Handling: Explicit error handling for all operations
Support and Community
For support, bug reports, and feature requests:
- GitHub Issues: Primary channel for bug reports and feature requests
- Documentation: Comprehensive documentation and examples
- Community: Active community of users and contributors
License and Legal
This GitLab MCP Server is released under the MIT License, providing maximum flexibility for both commercial and non-commercial use. The server is designed to work with GitLab's public APIs and respects all GitLab terms of service and API usage guidelines.
Third-Party Dependencies
The server relies on several high-quality open-source packages:
- @modelcontextprotocol/sdk: Official MCP SDK for protocol compliance
- node-fetch: HTTP client for GitLab API interactions
- zod: Runtime type validation and schema definition
- TypeScript: Type-safe JavaScript development
All dependencies are regularly updated and security-audited to ensure production readiness and security compliance.
Author: Manus AI
Version: 1.0.0
Last Updated: January 2025