Skip to main content
Glama
aflsolutions

ShadowGit MCP Server

by aflsolutions

git_command

Execute safe, read-only git commands on a ShadowGit repository to inspect commit history and code changes for debugging and analysis.

Instructions

Execute a read-only git command on a ShadowGit repository. Only safe, read-only commands are allowed.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
repoYesRepository name (use list_repos to see available repositories)
commandYesGit command to execute (e.g., "log -10", "diff HEAD~1", "status")

Implementation Reference

  • GitHandler class with the handle() method that executes git_command tool logic. Validates args via isGitCommandArgs(), resolves repo path, delegates execution to GitExecutor, and optionally appends workflow hints.
    /**
     * Handler for git_command tool
     */
    
    import { RepositoryManager } from '../core/repository-manager';
    import { GitExecutor } from '../core/git-executor';
    import { createErrorResponse, createTextResponse, createRepoNotFoundResponse } from '../utils/response-utils';
    import type { MCPToolResponse, GitCommandArgs } from '../types';
    
    export class GitHandler {
      constructor(
        private repositoryManager: RepositoryManager,
        private gitExecutor: GitExecutor
      ) {}
    
      /**
       * Validate git command arguments
       */
      private isGitCommandArgs(args: unknown): args is GitCommandArgs {
        return (
          typeof args === 'object' &&
          args !== null &&
          'repo' in args &&
          'command' in args &&
          typeof (args as GitCommandArgs).repo === 'string' &&
          typeof (args as GitCommandArgs).command === 'string'
        );
      }
    
      /**
       * Handle git_command tool execution
       */
      async handle(args: unknown): Promise<MCPToolResponse> {
        if (!this.isGitCommandArgs(args)) {
          return createErrorResponse(
            "Error: Both 'repo' and 'command' parameters are required.",
            `Example usage:
      git_command({repo: "my-project", command: "log --oneline -10"})
      git_command({repo: "my-project", command: "diff HEAD~1"})
      
    Use list_repos() to see available repositories.`
          );
        }
    
        const repoPath = this.repositoryManager.resolveRepoPath(args.repo);
        
        if (!repoPath) {
          const repos = this.repositoryManager.getRepositories();
          return createRepoNotFoundResponse(args.repo, repos);
        }
    
        const output = await this.gitExecutor.execute(args.command, repoPath);
        
        // Add workflow reminder for common commands that suggest changes are being planned
        // Show workflow hints unless disabled
        const showHints = process.env.SHADOWGIT_HINTS !== '0';
        const reminderCommands = ['diff', 'status', 'log', 'blame'];
        const needsReminder = showHints && reminderCommands.some(cmd => args.command.toLowerCase().includes(cmd));
        
        if (needsReminder) {
          return createTextResponse(
            `${output}
    
    ${'='.repeat(50)}
    📝 **Planning to Make Changes?**
    ${'='.repeat(50)}
    
    **Required Workflow:**
    1️⃣ \`start_session({repo: "${args.repo}", description: "your task"})\`
    2️⃣ Make your changes
    3️⃣ \`checkpoint({repo: "${args.repo}", title: "commit message"})\`
    4️⃣ \`end_session({sessionId: "...", commitHash: "..."})\`
    
    💡 **NEXT STEP:** Call \`start_session()\` before editing any files!`
          );
        }
        
        return createTextResponse(output);
      }
    }
  • Tool registration for 'git_command' in the ListToolsRequestSchema handler, defining name, description, and inputSchema (requires repo and command strings).
    {
      name: 'git_command',
      description: 'Execute a read-only git command on a ShadowGit repository. Only safe, read-only commands are allowed.',
      inputSchema: {
        type: 'object',
        properties: {
          repo: {
            type: 'string',
            description: 'Repository name (use list_repos to see available repositories)',
          },
          command: {
            type: 'string',
            description: 'Git command to execute (e.g., "log -10", "diff HEAD~1", "status")',
          },
        },
        required: ['repo', 'command'],
      },
    },
  • Tool dispatch in CallToolRequestSchema: routes 'git_command' to this.gitHandler.handle(args).
    case 'git_command':
      return await this.gitHandler.handle(args);
  • GitCommandArgs interface defining the input shape: { repo: string; command: string }.
    export interface GitCommandArgs {
      repo: string;
      command: string;
    }
  • GitExecutor.execute() runs the actual git command with security checks: command whitelist (SAFE_COMMANDS), dangerous arg blocking, control character sanitization, and execution against .shadowgit.git directory.
    export class GitExecutor {
    
      /**
       * Execute a git command with security checks
       * @param command - Either a string command or array of arguments
       */
      async execute(
        command: string | string[], 
        repoPath: string, 
        isInternal = false,
        additionalEnv?: NodeJS.ProcessEnv
      ): Promise<string> {
        // Parse command into arguments
        let args: string[];
        
        if (Array.isArray(command)) {
          // Array-based command (safer for internal use)
          args = command;
        } else {
          // String command - check length only for external calls
          if (!isInternal && command.length > MAX_COMMAND_LENGTH) {
            return `Error: Command too long (max ${MAX_COMMAND_LENGTH} characters).`;
          }
        
          // Remove control characters
          const sanitizedCommand = command.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, '');
          
          // Simple argument parsing that handles quotes and all whitespace
          args = [];
          let current = '';
          let inQuotes = false;
          let quoteChar = '';
          
          for (let i = 0; i < sanitizedCommand.length; i++) {
            const char = sanitizedCommand[i];
            const nextChar = sanitizedCommand[i + 1];
            
            if (!inQuotes && (char === '"' || char === "'")) {
              inQuotes = true;
              quoteChar = char;
            } else if (inQuotes && char === '\\' && nextChar === quoteChar) {
              // Handle escaped quote
              current += quoteChar;
              i++; // Skip the quote
            } else if (inQuotes && char === quoteChar) {
              inQuotes = false;
              quoteChar = '';
            } else if (!inQuotes && /\s/.test(char)) {
              // Split on any whitespace (space, tab, etc.)
              if (current) {
                args.push(current);
                current = '';
              }
            } else {
              current += char;
            }
          }
          if (current) {
            args.push(current);
          }
        }
        
        if (args.length === 0) {
          return 'Error: No command provided.';
        }
        
        const gitCommand = args[0];
        
        // Safety check 1: ALWAYS block dangerous arguments
        for (const arg of args) {
          if (isDangerousArg(arg)) {
            return 'Error: Command contains potentially dangerous arguments.';
          }
        }
        
        // Safety check 2: Only check command whitelist for external calls
        if (!isInternal && !SAFE_COMMANDS.has(gitCommand)) {
          return `Error: Command '${gitCommand}' is not allowed. Only read-only commands are permitted.
    
    Allowed commands: ${Array.from(SAFE_COMMANDS).join(', ')}`;
        }
        
        // Safety check 3: Ensure we're operating on a .shadowgit.git repository
        const gitDir = path.join(repoPath, SHADOWGIT_DIR);
        
        if (!fs.existsSync(gitDir)) {
          return `Error: Not a ShadowGit repository. The .shadowgit.git directory was not found at ${gitDir}`;
        }
        
        log('debug', `Executing git ${gitCommand} in ${repoPath}`);
        
        try {
          const output = execFileSync('git', [
            `--git-dir=${gitDir}`,
            `--work-tree=${repoPath}`,
            ...args
          ], {
            cwd: repoPath,
            encoding: 'utf-8',
            timeout: TIMEOUT_MS,
            maxBuffer: MAX_BUFFER_SIZE,
            env: {
              ...process.env,
              GIT_TERMINAL_PROMPT: '0', // Disable interactive prompts
              GIT_SSH_COMMAND: 'ssh -o BatchMode=yes', // Disable SSH prompts
              GIT_PAGER: 'cat', // Disable pager
              PAGER: 'cat', // Fallback pager disable
              ...additionalEnv
            }
          });
          
          return output || '(empty output)';
        } catch (error: unknown) {
          if (error && typeof error === 'object') {
            const execError = error as any;
            
            // Check for timeout
            if (execError.code === 'ETIMEDOUT' || execError.signal === 'SIGTERM') {
              return `Error: Command timed out after ${TIMEOUT_MS}ms.`;
            }
            
            // Check for detailed error info (has stderr/stdout or status code)
            if ('stderr' in execError || 'stdout' in execError || 'status' in execError) {
              const stderr = execError.stderr?.toString() || '';
              const stdout = execError.stdout?.toString() || '';
              const message = execError.message || 'Unknown error';
              
              return `Error executing git command:
    ${message}
    ${stderr ? `\nError output:\n${stderr}` : ''}
    ${stdout ? `\nPartial output:\n${stdout}` : ''}`;
            }
          }
          
          return `Error: ${error}`;
        }
      }
    }
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations provided, so the description must disclose behavior. It states the tool is read-only and safe, which is the key behavioral trait. However, it lacks details on error handling, auth requirements, or output format.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Two concise sentences, front-loaded with action and constraint. Every word earns its place.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the simplicity of the tool and no output schema, the description is fairly complete. It covers the main purpose and constraint, though it could mention output or error behavior.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 100% with good descriptions for both parameters. The description does not add additional meaning beyond what is in the schema, so a baseline score of 3 is appropriate.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the verb 'Execute', the resource 'git command on a ShadowGit repository', and specifies the scope 'read-only' and 'safe'. This distinguishes it from sibling tools like checkpoint or start_session.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description explicitly limits usage to read-only commands, which helps the agent decide when to use it. However, it does not explicitly mention when not to use it or provide alternatives among siblings.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/aflsolutions/shadowgit-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server