A Model Context Protocol server that provides Git operations to Large Language Models. This tool enables LLMs to interact with Git repositories through a robust and flexible API.
- Overview
- Features
- Installation
- Configuration
- Tools
- Performance
- Error Handling
- Best Practices
- Development
- Contributing
- License
Git MCP Server implements the Model Context Protocol (MCP), enabling standardized communication between LLMs and Git repositories through:
- Clients (Claude Desktop, IDEs) that maintain server connections
- Servers that provide tools and resources (Like our Git MCP Server)
- LLMs that interact with servers through client applications
- GitOperations: Core Git command execution with error handling
- RepositoryValidator: Comprehensive repository validation
- PathValidator: Path validation and security checks
- CommandExecutor: Secure command execution
- PerformanceMonitor: Performance tracking and optimization
- RepositoryCache: Caching system for Git operations
- ErrorHandler: Structured error handling with recovery
- Repository initialization and cloning
- File staging and committing
- Branch management
- Tag operations
- Remote repository handling
- Stash management
- Bulk operations support
- Repository state caching
- Command result caching
- Performance monitoring:
- Operation timing
- Memory usage tracking
- Resource utilization
- Cache hit rates
- Automatic cache invalidation
- Memory pressure monitoring
Error severity levels:
- CRITICAL: System-level failures
- HIGH: Operation-blocking errors
- MEDIUM: Non-blocking issues
- LOW: Minor problems
Error categories:
- SYSTEM: System-level errors
- VALIDATION: Input validation errors
- OPERATION: Git operation errors
- REPOSITORY: Repository state errors
- NETWORK: Network-related errors
- CONFIGURATION: Configuration errors
- SECURITY: Security-related errors
Error context tracking:
- Operation details
- Timestamps
- Stack traces
- Recovery steps
- Technical context
- Path validation and sanitization
- Command injection prevention
- Repository access control
- Secure credential handling
- Input validation
- Error message sanitization
- Install the package:
npm install git-mcp-server
- Add to your MCP client settings:
{
"mcpServers": {
"git": {
"command": "node",
"args": ["/path/to/git-mcp-server/build/index.js"],
"env": {
"GIT_DEFAULT_PATH": "/path/to/default/repo/directory",
"GIT_MAX_MEMORY": "1024", // Optional, in MB
"GIT_CACHE_TTL": "300", // Optional, in seconds
"GIT_LOG_LEVEL": "info" // Optional: debug, info, warn, error
}
}
}
}
GIT_DEFAULT_PATH
: Default repository directoryGIT_MAX_MEMORY
: Maximum memory usage (MB)GIT_CACHE_TTL
: Cache time-to-live (seconds)GIT_LOG_LEVEL
: Logging levelGIT_PERFORMANCE_MONITOR
: Enable performance monitoringGIT_ERROR_DETAILS
: Include detailed error information
Cache configuration:
{
"repository": {
"ttl": 300,
"maxSize": 100
},
"command": {
"ttl": 60,
"maxSize": 500
}
}
Resource thresholds:
{
"memory": {
"warning": 1024,
"critical": 2048
},
"operations": {
"warning": 100,
"critical": 200
}
}
Initialize a new Git repository:
{
"path": "/path/to/repo" // Optional if GIT_DEFAULT_PATH is set
}
Clone a repository:
{
"url": "https://github.com/user/repo.git",
"path": "/path/to/destination" // Optional
}
Get repository status:
{
"path": "/path/to/repo" // Optional
}
Stage files:
{
"path": "/path/to/repo", // Optional
"files": ["/path/to/file1", "/path/to/file2"]
}
Create a commit:
{
"path": "/path/to/repo", // Optional
"message": "Commit message"
}
Push commits to remote:
{
"path": "/path/to/repo", // Optional
"remote": "origin", // Optional, defaults to "origin"
"branch": "main"
}
Execute multiple operations atomically. This is the preferred method for executing multiple Git operations as it:
- Ensures operations are executed in the correct order
- Provides atomic execution (all succeed or all fail)
- Optimizes performance through reduced command overhead
- Maintains consistent repository state
- Automatically handles cache invalidation
Example usage:
{
"path": "/path/to/repo", // Optional
"actions": [
{
"type": "stage",
"files": ["file1", "file2"] // Optional - if omitted, stages all changes
},
{
"type": "commit",
"message": "Commit message"
},
{
"type": "push",
"branch": "main",
"remote": "origin" // Optional - defaults to "origin"
}
]
}
The bulk_action tool supports three types of operations:
stage
: Stage files for commitfiles
: Optional array of files to stage. If omitted, stages all changes
commit
: Create a new commitmessage
: Required commit message
push
: Push changes to remotebranch
: Required branch nameremote
: Optional remote name (defaults to "origin")
The server implements a robust caching system built on top of simple-git, providing two-level caching:
-
Repository State Cache:
- Branch information
- Status
- Tags
- Remotes
- Stash entries
-
Command Result Cache:
- Common command outputs
- Validation results
- Repository metadata
Cache invalidation:
- Automatic on state-changing operations (commit, push, etc.)
- TTL-based expiration (configurable via GIT_CACHE_TTL)
- Memory pressure-based eviction (monitored via GIT_MAX_MEMORY)
- LRU eviction policy for optimal cache utilization
- Smart invalidation based on operation dependencies
- Partial cache updates for efficiency
Implementation details:
- Uses simple-git for reliable Git operations
- Implements optimistic locking for cache updates
- Maintains cache coherency across operations
- Provides cache warming for frequently accessed data
- Supports concurrent cache access with proper synchronization
Metrics collected:
- Operation timing
- Memory usage
- Cache hit rates
- Resource utilization
- Command execution stats
Monitoring tools:
// Get performance statistics
const stats = await performanceMonitor.getStatistics();
// Get cache statistics
const cacheStats = await repositoryCache.getStats();
// Get operation metrics
const metrics = await performanceMonitor.getMetrics(
MetricType.OPERATION_DURATION,
startTime,
endTime
);
// System errors
throw new SystemError('Disk space exhausted', {
operation: 'clone',
path: '/path/to/repo'
});
// Validation errors
throw new ValidationError('Invalid branch name', {
operation: 'branch_create',
details: { name: 'invalid/name' }
});
// Operation errors
throw new OperationError('Push failed', {
operation: 'push',
command: 'git push origin main'
});
Each error includes recovery steps:
try {
await gitOps.push(options);
} catch (error) {
if (error instanceof GitMcpError) {
console.log('Recovery steps:', error.getRecoverySteps());
}
}
Errors include detailed context:
{
"name": "OperationError",
"message": "Push failed: remote connection error",
"code": "INTERNAL_ERROR",
"severity": "HIGH",
"category": "NETWORK",
"context": {
"operation": "push",
"path": "/path/to/repo",
"command": "git push origin main",
"timestamp": 1234567890,
"recoverySteps": [
"Check network connection",
"Verify remote URL",
"Check credentials"
]
}
}
- Use bulk operations for multiple changes:
await gitOps.executeBulkActions({
actions: [
{ type: 'stage', files: ['file1', 'file2'] },
{ type: 'commit', message: 'Update files' },
{ type: 'push', branch: 'main' }
]
});
- Validate paths and inputs:
PathValidator.validatePath(path, {
mustExist: true,
allowDirectory: true
});
- Handle embedded repositories:
const { path, hasEmbeddedRepo } = PathValidator.validateGitRepo(path);
if (hasEmbeddedRepo) {
// Handle embedded .git directories
}
- Use caching appropriately:
const result = await repositoryCache.getState(
repoPath,
RepoStateType.BRANCH,
'branch -a',
() => executeGitCommand('branch -a')
);
- Monitor resource usage:
performanceMonitor.recordMemoryUsage();
performanceMonitor.recordResourceUsage('cpu', cpuUsage);
- Handle cache invalidation:
repositoryCache.invalidateState(repoPath, RepoStateType.STATUS);
repositoryCache.invalidateCommand(repoPath, 'status');
- Use appropriate error types:
if (!isValidBranch(name)) {
throw new ValidationError(`Invalid branch name: ${name}`, {
operation: 'branch_create',
details: { name }
});
}
- Include recovery steps:
throw new NetworkError('Remote unreachable', {
operation: 'push',
recoverySteps: [
'Check network connection',
'Verify remote URL'
]
});
- Log errors appropriately:
logger.error(
operation,
'Operation failed',
path,
error,
{ command, context }
);
- Clone the repository:
git clone https://github.com/your-org/git-mcp-server.git
cd git-mcp-server
- Install dependencies:
npm install
- Build the project:
npm run build
- Run tests:
npm test
- Fork the repository
- Create a feature branch
- Commit your changes
- Push to the branch
- Create a Pull Request
For bugs and feature requests, please create an issue.
Apache License 2.0