@andrebuzeli/git-mcp 6.0.1 → 6.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,6 +8,7 @@ export declare class GitBranchesTool implements Tool {
8
8
  branches?: undefined;
9
9
  current?: undefined;
10
10
  deleted?: undefined;
11
+ currentBranch?: undefined;
11
12
  result?: undefined;
12
13
  baseBranch?: undefined;
13
14
  compareBranch?: undefined;
@@ -19,6 +20,7 @@ export declare class GitBranchesTool implements Tool {
19
20
  success?: undefined;
20
21
  branch?: undefined;
21
22
  deleted?: undefined;
23
+ currentBranch?: undefined;
22
24
  result?: undefined;
23
25
  baseBranch?: undefined;
24
26
  compareBranch?: undefined;
@@ -30,6 +32,7 @@ export declare class GitBranchesTool implements Tool {
30
32
  current: boolean;
31
33
  branches?: undefined;
32
34
  deleted?: undefined;
35
+ currentBranch?: undefined;
33
36
  result?: undefined;
34
37
  baseBranch?: undefined;
35
38
  compareBranch?: undefined;
@@ -38,6 +41,7 @@ export declare class GitBranchesTool implements Tool {
38
41
  } | {
39
42
  success: boolean;
40
43
  deleted: any;
44
+ currentBranch: string;
41
45
  branch?: undefined;
42
46
  branches?: undefined;
43
47
  current?: undefined;
@@ -53,6 +57,7 @@ export declare class GitBranchesTool implements Tool {
53
57
  branches?: undefined;
54
58
  current?: undefined;
55
59
  deleted?: undefined;
60
+ currentBranch?: undefined;
56
61
  baseBranch?: undefined;
57
62
  compareBranch?: undefined;
58
63
  commits?: undefined;
@@ -67,6 +72,7 @@ export declare class GitBranchesTool implements Tool {
67
72
  branches?: undefined;
68
73
  current?: undefined;
69
74
  deleted?: undefined;
75
+ currentBranch?: undefined;
70
76
  result?: undefined;
71
77
  }>;
72
78
  }
@@ -7,6 +7,7 @@ exports.GitBranchesTool = void 0;
7
7
  const simple_git_1 = __importDefault(require("simple-git"));
8
8
  const errors_1 = require("../utils/errors");
9
9
  const safetyController_1 = require("../utils/safetyController");
10
+ const repoHelpers_1 = require("../utils/repoHelpers");
10
11
  class GitBranchesTool {
11
12
  constructor() {
12
13
  this.name = 'git-branches';
@@ -60,8 +61,17 @@ class GitBranchesTool {
60
61
  const branchName = params.branchName;
61
62
  if (!branchName)
62
63
  throw new errors_1.MCPError('VALIDATION_ERROR', 'branchName is required');
64
+ // Safety check: prevent deleting the current active branch
65
+ const currentBranch = (0, repoHelpers_1.getCurrentBranch)(projectPath);
66
+ if (currentBranch && currentBranch === branchName) {
67
+ throw new errors_1.MCPError('SAFETY_ERROR', `Cannot delete the currently active branch '${branchName}'.`, [
68
+ 'Switch to another branch first using git checkout',
69
+ 'Example: git checkout master',
70
+ 'Then retry the delete operation',
71
+ ]);
72
+ }
63
73
  await git.deleteLocalBranch(branchName, params.force);
64
- return { success: true, deleted: branchName };
74
+ return { success: true, deleted: branchName, currentBranch };
65
75
  }
66
76
  case 'merge': {
67
77
  const branchName = params.branchName;
@@ -43,7 +43,17 @@ class GitIssuesTool {
43
43
  results.providers.github = { success: true, issue: result.data };
44
44
  }
45
45
  catch (err) {
46
- results.providers.github = { success: false, error: err.message };
46
+ const mcpError = (0, errors_1.handleApiError)(err, {
47
+ provider: 'github',
48
+ operation: 'create issue',
49
+ resource: `${githubOwner}/${repo}`,
50
+ });
51
+ results.providers.github = {
52
+ success: false,
53
+ error: mcpError.message,
54
+ code: mcpError.code,
55
+ suggestions: mcpError.suggestions,
56
+ };
47
57
  }
48
58
  }
49
59
  // Gitea
@@ -84,7 +94,17 @@ class GitIssuesTool {
84
94
  results.providers.github = { success: true, issues: result.data };
85
95
  }
86
96
  catch (err) {
87
- results.providers.github = { success: false, error: err.message };
97
+ const mcpError = (0, errors_1.handleApiError)(err, {
98
+ provider: 'github',
99
+ operation: 'list issues',
100
+ resource: `${githubOwner}/${repo}`,
101
+ });
102
+ results.providers.github = {
103
+ success: false,
104
+ error: mcpError.message,
105
+ code: mcpError.code,
106
+ suggestions: mcpError.suggestions,
107
+ };
88
108
  }
89
109
  }
90
110
  // Gitea
@@ -6,6 +6,7 @@ export declare class GitSyncTool implements Tool {
6
6
  success: boolean;
7
7
  remote: any;
8
8
  branch: any;
9
+ automated: boolean;
9
10
  message: string;
10
11
  status?: undefined;
11
12
  remotes?: undefined;
@@ -20,6 +21,7 @@ export declare class GitSyncTool implements Tool {
20
21
  remotes: import("simple-git").RemoteWithRefs[];
21
22
  remote?: undefined;
22
23
  branch?: undefined;
24
+ automated?: undefined;
23
25
  message?: undefined;
24
26
  }>;
25
27
  }
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.GitSyncTool = void 0;
7
7
  const simple_git_1 = __importDefault(require("simple-git"));
8
8
  const errors_1 = require("../utils/errors");
9
+ const repoHelpers_1 = require("../utils/repoHelpers");
9
10
  class GitSyncTool {
10
11
  constructor() {
11
12
  this.name = 'git-sync';
@@ -21,13 +22,20 @@ class GitSyncTool {
21
22
  switch (action) {
22
23
  case 'sync': {
23
24
  const remote = params.remote || 'origin';
24
- const branch = params.branch;
25
+ // Auto-detect current branch if not provided
26
+ let branch = params.branch;
27
+ if (!branch) {
28
+ branch = (0, repoHelpers_1.getCurrentBranch)(projectPath);
29
+ if (!branch) {
30
+ throw new errors_1.MCPError('VALIDATION_ERROR', 'Could not detect current branch. Please provide branch parameter.');
31
+ }
32
+ }
25
33
  if (branch) {
26
34
  await git.checkout(branch);
27
35
  }
28
36
  await git.fetch(remote);
29
37
  await git.pull(remote, branch);
30
- return { success: true, remote, branch, message: 'Repository synced' };
38
+ return { success: true, remote, branch, automated: !params.branch, message: 'Repository synced' };
31
39
  }
32
40
  case 'status': {
33
41
  const status = await git.status();
@@ -60,7 +60,14 @@ class GitUploadTool {
60
60
  const repoName = params.repoName || (0, repoHelpers_1.getRepoNameFromPath)(projectPath);
61
61
  const description = params.description || `Project uploaded via git-upload at ${new Date().toISOString()}`;
62
62
  const isPrivate = params.private !== undefined ? params.private : true;
63
- const branch = params.branch || 'master';
63
+ // Auto-detect current branch if not provided
64
+ let branch = params.branch;
65
+ if (!branch) {
66
+ branch = (0, repoHelpers_1.getCurrentBranch)(projectPath);
67
+ if (!branch) {
68
+ branch = 'master'; // Ultimate fallback
69
+ }
70
+ }
64
71
  const git = (0, simple_git_1.default)({ baseDir: projectPath });
65
72
  // Resultado com rastreabilidade completa
66
73
  const results = {
@@ -11,3 +11,45 @@ export declare class MCPError extends Error {
11
11
  suggestions?: string[];
12
12
  constructor(code: string, message: string, suggestions?: string[]);
13
13
  }
14
+ /**
15
+ * Transform GitHub/Gitea API errors into user-friendly messages
16
+ */
17
+ export declare function handleApiError(error: any, context: {
18
+ provider: 'github' | 'gitea';
19
+ operation: string;
20
+ resource?: string;
21
+ }): MCPError;
22
+ /**
23
+ * Handle Git command errors with helpful context
24
+ */
25
+ export declare function handleGitError(error: any, context: {
26
+ operation: string;
27
+ path: string;
28
+ }): MCPError;
29
+ /**
30
+ * Wrap API calls with error handling
31
+ */
32
+ export declare function withApiErrorHandling<T>(fn: () => Promise<T>, context: {
33
+ provider: 'github' | 'gitea';
34
+ operation: string;
35
+ resource?: string;
36
+ }): Promise<{
37
+ success: true;
38
+ data: T;
39
+ } | {
40
+ success: false;
41
+ error: MCPError;
42
+ }>;
43
+ /**
44
+ * Wrap Git commands with error handling
45
+ */
46
+ export declare function withGitErrorHandling<T>(fn: () => Promise<T>, context: {
47
+ operation: string;
48
+ path: string;
49
+ }): Promise<{
50
+ success: true;
51
+ data: T;
52
+ } | {
53
+ success: false;
54
+ error: MCPError;
55
+ }>;
@@ -2,6 +2,10 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MCPError = void 0;
4
4
  exports.createErrorResponse = createErrorResponse;
5
+ exports.handleApiError = handleApiError;
6
+ exports.handleGitError = handleGitError;
7
+ exports.withApiErrorHandling = withApiErrorHandling;
8
+ exports.withGitErrorHandling = withGitErrorHandling;
5
9
  function createErrorResponse(code, message, suggestions) {
6
10
  return {
7
11
  success: false,
@@ -20,3 +24,199 @@ class MCPError extends Error {
20
24
  }
21
25
  }
22
26
  exports.MCPError = MCPError;
27
+ /**
28
+ * Transform GitHub/Gitea API errors into user-friendly messages
29
+ */
30
+ function handleApiError(error, context) {
31
+ const { provider, operation, resource } = context;
32
+ // Extract status code and message
33
+ const status = error.status || error.response?.status;
34
+ const message = error.message || error.response?.data?.message || 'Unknown error';
35
+ // Handle common HTTP errors with context-specific messages
36
+ switch (status) {
37
+ case 401:
38
+ return new MCPError('AUTHENTICATION_ERROR', `❌ Authentication failed for ${provider.toUpperCase()}`, [
39
+ `Check if ${provider === 'github' ? 'GITHUB_TOKEN' : 'GITEA_TOKEN'} is set correctly`,
40
+ 'Verify token has not expired',
41
+ `Generate a new token at: ${provider === 'github' ? 'https://github.com/settings/tokens' : 'your Gitea instance settings'}`,
42
+ 'Ensure token has required permissions',
43
+ ]);
44
+ case 403:
45
+ const rateLimitRemaining = error.response?.headers?.['x-ratelimit-remaining'];
46
+ if (rateLimitRemaining === '0') {
47
+ const resetTime = error.response?.headers?.['x-ratelimit-reset'];
48
+ const resetDate = resetTime ? new Date(parseInt(resetTime) * 1000).toLocaleString() : 'soon';
49
+ return new MCPError('RATE_LIMIT_EXCEEDED', `⏱️ ${provider.toUpperCase()} API rate limit exceeded`, [
50
+ `Rate limit will reset at: ${resetDate}`,
51
+ 'Wait for the rate limit to reset',
52
+ `Consider using a different ${provider === 'github' ? 'GitHub' : 'Gitea'} account or token`,
53
+ 'For GitHub: Upgrade to GitHub Pro for higher limits',
54
+ ]);
55
+ }
56
+ return new MCPError('PERMISSION_DENIED', `🔒 Insufficient permissions for ${operation} on ${provider.toUpperCase()}`, [
57
+ `Token does not have permission to ${operation}`,
58
+ resource ? `Verify you have access to ${resource}` : 'Verify repository access',
59
+ 'Check if repository is private and token has appropriate scopes',
60
+ `Required scopes: ${getRequiredScopes(operation, provider)}`,
61
+ ]);
62
+ case 404:
63
+ return new MCPError('RESOURCE_NOT_FOUND', `🔍 ${resource || 'Resource'} not found on ${provider.toUpperCase()}`, [
64
+ resource ? `"${resource}" does not exist` : 'The requested resource does not exist',
65
+ 'Check if the repository/issue/PR name is correct',
66
+ 'Verify you have access to this resource',
67
+ provider === 'github' ? 'Check if owner (GITHUB_USERNAME) is correct' : 'Check if owner (GITEA_USERNAME) is correct',
68
+ 'For private resources, ensure your token has access',
69
+ ]);
70
+ case 409:
71
+ return new MCPError('CONFLICT_ERROR', `⚠️ Conflict during ${operation} on ${provider.toUpperCase()}`, [
72
+ 'Resource already exists or is in conflicting state',
73
+ operation.includes('create') ? 'Try a different name or delete the existing resource' : 'Resolve conflicts first',
74
+ 'Check if there are merge conflicts',
75
+ 'Pull latest changes before pushing',
76
+ ]);
77
+ case 422:
78
+ return new MCPError('VALIDATION_ERROR', `📋 Invalid data for ${operation} on ${provider.toUpperCase()}: ${message}`, [
79
+ 'Check if all required fields are provided',
80
+ 'Verify field formats (branch names, tags, etc.)',
81
+ 'Branch names cannot contain spaces or special characters',
82
+ 'Issue/PR titles must not be empty',
83
+ ]);
84
+ case 500:
85
+ case 502:
86
+ case 503:
87
+ return new MCPError('SERVER_ERROR', `🔥 ${provider.toUpperCase()} server error during ${operation}`, [
88
+ `${provider === 'github' ? 'GitHub' : 'Gitea'} is experiencing issues`,
89
+ 'Check service status: ' + (provider === 'github' ? 'https://www.githubstatus.com/' : 'your Gitea instance status'),
90
+ 'Wait a few minutes and try again',
91
+ 'If issue persists, the problem is on the server side',
92
+ ]);
93
+ default:
94
+ return new MCPError('API_ERROR', `❌ ${provider.toUpperCase()} API error during ${operation}: ${message}`, [
95
+ `HTTP ${status || 'unknown'}: ${message}`,
96
+ 'Check your internet connection',
97
+ `Verify ${provider === 'github' ? 'GITHUB_TOKEN' : 'GITEA_TOKEN'} is valid`,
98
+ 'Check API endpoint availability',
99
+ ]);
100
+ }
101
+ }
102
+ /**
103
+ * Get required token scopes for an operation
104
+ */
105
+ function getRequiredScopes(operation, provider) {
106
+ if (provider === 'gitea') {
107
+ return 'write:repository, write:issue, write:user';
108
+ }
109
+ // GitHub scopes
110
+ if (operation.includes('delete') || operation.includes('update')) {
111
+ return 'repo (full control)';
112
+ }
113
+ if (operation.includes('create')) {
114
+ return 'repo, user';
115
+ }
116
+ if (operation.includes('read') || operation.includes('list') || operation.includes('get')) {
117
+ return 'repo (or public_repo for public repos)';
118
+ }
119
+ return 'repo';
120
+ }
121
+ /**
122
+ * Handle Git command errors with helpful context
123
+ */
124
+ function handleGitError(error, context) {
125
+ const message = error.message || String(error);
126
+ const { operation, path } = context;
127
+ // Not a git repository
128
+ if (message.includes('not a git repository') || message.includes('not found')) {
129
+ return new MCPError('NOT_A_GIT_REPOSITORY', `📁 "${path}" is not a Git repository`, [
130
+ 'Initialize a git repository first: git init',
131
+ 'Or provide a valid repository path',
132
+ 'Check if .git directory exists',
133
+ 'Verify you have permissions to access the directory',
134
+ ]);
135
+ }
136
+ // Authentication/permission errors
137
+ if (message.includes('Permission denied') || message.includes('authentication failed')) {
138
+ return new MCPError('GIT_AUTH_ERROR', `🔐 Git authentication failed during ${operation}`, [
139
+ 'Check if SSH keys are configured correctly',
140
+ 'For HTTPS: verify credentials are correct',
141
+ 'For SSH: ensure ssh-agent is running',
142
+ 'Test connection: git ls-remote <remote-url>',
143
+ ]);
144
+ }
145
+ // Remote errors
146
+ if (message.includes('remote') || message.includes('fetch') || message.includes('push')) {
147
+ if (message.includes('does not appear to be a git repository')) {
148
+ return new MCPError('INVALID_REMOTE', `🌐 Remote repository URL is invalid or inaccessible`, [
149
+ 'Check if remote URL is correct',
150
+ 'Verify repository exists on remote',
151
+ 'For private repos: ensure authentication is configured',
152
+ 'List remotes: git remote -v',
153
+ ]);
154
+ }
155
+ if (message.includes('rejected') || message.includes('non-fast-forward')) {
156
+ return new MCPError('PUSH_REJECTED', `⚠️ Push rejected - remote has changes you don't have`, [
157
+ 'Pull latest changes first: git pull',
158
+ 'Resolve any merge conflicts',
159
+ 'Then try pushing again',
160
+ 'Or force push (dangerous): use with caution',
161
+ ]);
162
+ }
163
+ }
164
+ // Merge conflicts
165
+ if (message.includes('conflict') || message.includes('CONFLICT')) {
166
+ return new MCPError('MERGE_CONFLICT', `⚔️ Merge conflict detected during ${operation}`, [
167
+ 'Resolve conflicts in affected files',
168
+ 'Stage resolved files: git add <file>',
169
+ 'Complete merge: git commit',
170
+ 'Or abort: git merge --abort',
171
+ ]);
172
+ }
173
+ // Nothing to commit
174
+ if (message.includes('nothing to commit') || message.includes('no changes')) {
175
+ return new MCPError('NOTHING_TO_COMMIT', `✅ No changes to commit - working tree is clean`, [
176
+ 'All changes are already committed',
177
+ 'Check status: git status',
178
+ 'Make changes before committing',
179
+ 'Or use --allow-empty to create empty commit',
180
+ ]);
181
+ }
182
+ // Branch errors
183
+ if (message.includes('branch') && (message.includes('not found') || message.includes('does not exist'))) {
184
+ return new MCPError('BRANCH_NOT_FOUND', `🌿 Branch not found during ${operation}`, [
185
+ 'List available branches: git branch -a',
186
+ 'Create the branch first if needed',
187
+ 'Check for typos in branch name',
188
+ 'Fetch from remote: git fetch',
189
+ ]);
190
+ }
191
+ // Generic git error
192
+ return new MCPError('GIT_ERROR', `❌ Git error during ${operation}: ${message}`, [
193
+ 'Check git command output for details',
194
+ 'Verify repository state is clean',
195
+ 'Try: git status',
196
+ 'For more info: git --help',
197
+ ]);
198
+ }
199
+ /**
200
+ * Wrap API calls with error handling
201
+ */
202
+ async function withApiErrorHandling(fn, context) {
203
+ try {
204
+ const data = await fn();
205
+ return { success: true, data };
206
+ }
207
+ catch (error) {
208
+ return { success: false, error: handleApiError(error, context) };
209
+ }
210
+ }
211
+ /**
212
+ * Wrap Git commands with error handling
213
+ */
214
+ async function withGitErrorHandling(fn, context) {
215
+ try {
216
+ const data = await fn();
217
+ return { success: true, data };
218
+ }
219
+ catch (error) {
220
+ return { success: false, error: handleGitError(error, context) };
221
+ }
222
+ }
@@ -6,6 +6,16 @@
6
6
  * Normalizes: spaces to hyphens, lowercase, keeps alphanumeric and hyphens/underscores
7
7
  */
8
8
  export declare function getRepoNameFromPath(projectPath: string): string;
9
+ /**
10
+ * Get current Git branch from project path
11
+ * Returns empty string if not in a Git repository
12
+ */
13
+ export declare function getCurrentBranch(projectPath: string): string;
14
+ /**
15
+ * Get default branch from Git repository (usually 'main' or 'master')
16
+ * Falls back to 'master' if unable to determine
17
+ */
18
+ export declare function getDefaultBranch(projectPath: string): string;
9
19
  /**
10
20
  * Get GitHub owner from environment
11
21
  */
@@ -4,6 +4,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.getRepoNameFromPath = getRepoNameFromPath;
7
+ exports.getCurrentBranch = getCurrentBranch;
8
+ exports.getDefaultBranch = getDefaultBranch;
7
9
  exports.getGitHubOwner = getGitHubOwner;
8
10
  exports.getGiteaOwner = getGiteaOwner;
9
11
  exports.getGiteaUrl = getGiteaUrl;
@@ -11,6 +13,7 @@ exports.buildGitHubUrl = buildGitHubUrl;
11
13
  exports.buildGiteaUrl = buildGiteaUrl;
12
14
  exports.getRepoInfo = getRepoInfo;
13
15
  const path_1 = __importDefault(require("path"));
16
+ const child_process_1 = require("child_process");
14
17
  /**
15
18
  * Helper functions to extract repository information automatically
16
19
  */
@@ -24,6 +27,55 @@ function getRepoNameFromPath(projectPath) {
24
27
  .replace(/\s+/g, '-')
25
28
  .replace(/[^a-z0-9-_]/g, '');
26
29
  }
30
+ /**
31
+ * Get current Git branch from project path
32
+ * Returns empty string if not in a Git repository
33
+ */
34
+ function getCurrentBranch(projectPath) {
35
+ try {
36
+ const branchName = (0, child_process_1.execSync)('git rev-parse --abbrev-ref HEAD', {
37
+ cwd: projectPath,
38
+ encoding: 'utf8',
39
+ stdio: ['pipe', 'pipe', 'ignore'], // Suppress stderr
40
+ });
41
+ return branchName.trim();
42
+ }
43
+ catch (error) {
44
+ return '';
45
+ }
46
+ }
47
+ /**
48
+ * Get default branch from Git repository (usually 'main' or 'master')
49
+ * Falls back to 'master' if unable to determine
50
+ */
51
+ function getDefaultBranch(projectPath) {
52
+ try {
53
+ // Try to get default branch from remote
54
+ const defaultBranch = (0, child_process_1.execSync)('git symbolic-ref refs/remotes/origin/HEAD', {
55
+ cwd: projectPath,
56
+ encoding: 'utf8',
57
+ stdio: ['pipe', 'pipe', 'ignore'],
58
+ });
59
+ return defaultBranch.trim().replace('refs/remotes/origin/', '');
60
+ }
61
+ catch (error) {
62
+ // If that fails, try to detect main or master
63
+ try {
64
+ const branches = (0, child_process_1.execSync)('git branch -r', {
65
+ cwd: projectPath,
66
+ encoding: 'utf8',
67
+ stdio: ['pipe', 'pipe', 'ignore'],
68
+ });
69
+ if (branches.includes('origin/main'))
70
+ return 'main';
71
+ if (branches.includes('origin/master'))
72
+ return 'master';
73
+ }
74
+ catch { }
75
+ // Ultimate fallback
76
+ return 'master';
77
+ }
78
+ }
27
79
  /**
28
80
  * Get GitHub owner from environment
29
81
  */
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@andrebuzeli/git-mcp",
3
- "version": "6.0.1",
4
- "description": "Professional MCP server for Git operations - FULLY AUTONOMOUS: each provider uses own username from env, repo name auto-normalized from projectPath (spaces→hyphens, lowercase, keeps underscores), zero redundant parameters, automatic dual-provider execution (GitHub + Gitea)",
3
+ "version": "6.2.0",
4
+ "description": "Professional MCP server for Git operations - FULLY AUTONOMOUS with INTELLIGENT ERROR HANDLING: auto-detects branches, owner, repo. User-friendly error messages with actionable suggestions. Zero cryptic codes. Dual-provider execution (GitHub + Gitea)",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
7
  "bin": {