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}`;
        }
      }
    }

Schema Changelog

Changes observed during successful MCP inspections.

  1. Addedv1.0.0

TDQS

A3.7/5.0
Behavior3/5

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

With no annotations provided, the description carries the burden of behavioral disclosure. It explicitly states the read-only, safe nature, which is a key behavioral trait, but it does not disclose what happens if an unsafe command is attempted, error behavior, or output format. This is adequate but not rich.

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?

The description is a single sentence that immediately conveys the tool's purpose and key restriction. Every word is purposeful, with no redundancy or filler, making it highly efficient.

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

Completeness3/5

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

The tool is relatively simple (two string params, no output schema), and the description communicates the core read-only constraint. However, it omits any mention of return values, command whitelist specifics, or error handling, which would be useful given the lack of annotations. It is minimally complete but could be more thorough.

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?

The input schema fully documents both parameters with descriptions and examples (e.g., 'log -10', 'diff HEAD~1'). The description adds no extra semantic detail beyond reasserting read-only constraints, so it does not compensate beyond the schema's 100% coverage.

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 tool's function: 'Execute a read-only git command on a ShadowGit repository.' This specifies a concrete action (execute) and resource (git command on a repository), and the read-only distinction sets it apart from siblings like list_repos or session management tools.

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

Usage Guidelines3/5

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

The description notes that only 'safe, read-only commands are allowed,' implying it should be used for non-mutating operations. However, it does not explicitly provide when-to-use guidance or contrast with alternative tools, leaving the usage context somewhat implicit.

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