Skip to main content
Glama
git-mcp-server

git-mcp-server

by cyanheads

Servidor Git MCP

Mecanografiado Protocolo de contexto modelo Versión Licencia Estado GitHub

Un servidor MCP (Protocolo de Contexto de Modelo) que proporciona herramientas para interactuar con repositorios Git. Permite a los LLM y agentes de IA realizar operaciones Git como clonar, confirmar, enviar, extraer, ramificar, comparar, registrar, establecer estado y más mediante el estándar MCP.

Construido sobre la cyanheads/mcp-ts-template , este servidor sigue una arquitectura modular:

Nota para el desarrollador : este repositorio incluye un archivo .clinerules que sirve como hoja de trucos para desarrolladores para su agente de codificación LLM con referencia rápida para los patrones de base de código, ubicaciones de archivos y fragmentos de código.

Tabla de contenido

| Descripción general | Características | Instalación |

| Configuración | Estructura del proyecto |

| Herramientas | Recursos | Desarrollo | Licencia |

Related MCP server: GIT MCP Server

Descripción general

¡Potencie a sus agentes de IA y herramientas de desarrollo con una integración perfecta de Git!

El servidor Git MCP actúa como un puente que permite que las aplicaciones (clientes MCP) que entienden el Protocolo de contexto de modelo (MCP), como los asistentes de IA avanzados (LLM), las extensiones IDE o los scripts personalizados, interactúen de forma directa y segura con los repositorios Git locales.

En lugar de scripts complejos o CLI manual, sus herramientas pueden aprovechar este servidor para:

  • Automatice los flujos de trabajo de Git : clone repositorios, cree ramas, prepare cambios, confirme trabajos, envíe actualizaciones y administre etiquetas mediante programación.

  • Obtenga información sobre el repositorio : verifique el estado, vea registros, compare cambios e inspeccione objetos Git sin salir de la aplicación host.

  • Integre Git en el desarrollo impulsado por IA : permita que los LLM administren el control de versiones como parte de sus tareas de codificación o refactorización.

Basado en la robusta mcp-ts-template , este servidor proporciona una forma estandarizada, segura y eficiente de exponer la funcionalidad de Git mediante el estándar MCP. Esto se logra mediante la ejecución segura de la herramienta de línea de comandos git estándar instalada en el sistema mediante el módulo child_process de Node.js, lo que garantiza la compatibilidad y aprovecha al máximo la potencia de Git.

Características

Utilidades principales (desde plantilla)

Aprovecha las robustas utilidades proporcionadas por la mcp-ts-template :

  • Registro : registro estructurado y configurable (rotación de archivos, consola, notificaciones MCP) con redacción de datos confidenciales.

  • Manejo de errores : procesamiento de errores centralizado, tipos de errores estandarizados ( McpError ) y registro automático.

  • Configuración : Carga de variable de entorno ( dotenv ).

  • Validación/saneamiento de entrada : utiliza zod para la validación del esquema y la lógica de saneamiento personalizada (crucial para las rutas).

  • Contexto de solicitud : seguimiento y correlación de operaciones a través de identificadores de solicitud únicos.

  • Seguridad de tipos : tipado fuerte impuesto por los esquemas TypeScript y Zod.

  • Opción de transporte HTTP : servidor Express integrado con SSE, administración de sesiones y compatibilidad con CORS.

Operaciones de Git

  • Ejecución directa de Git CLI : interactúa con Git ejecutando de forma segura la herramienta de línea de comandos git estándar a través de child_process de Node.js, lo que garantiza la compatibilidad total y el acceso a las funciones de Git.

  • Cobertura integral de comandos : expone una amplia gama de comandos Git como herramientas MCP (consulte la sección Herramientas ).

  • Interacción del repositorio : admite verificación de estado, ramificación, preparación, confirmación, búsqueda, extracción, envío, comparación, registro, restablecimiento, etiquetado y más.

  • Administración del directorio de trabajo : permite configurar y borrar un directorio de trabajo específico de la sesión para la persistencia del contexto en múltiples operaciones de Git.

  • Características de seguridad : incluye controles y requiere confirmación explícita para operaciones potencialmente destructivas como git clean y git reset --hard .

  • Firma de confirmaciones : Admite la firma GPG o SSH para confirmaciones verificadas, controlada mediante la variable de entorno GIT_SIGN_COMMITS y la configuración de Git del servidor. Incluye un parámetro de herramienta opcional para recurrir a confirmaciones sin firmar en caso de fallo de firma.

Instalación

Prerrequisitos

Instalar mediante npm

  1. Instalar el paquete globalmente:

    npm install @cyanheads/git-mcp-server

Instalar desde la fuente

  1. Clonar el repositorio:

    git clone https://github.com/cyanheads/git-mcp-server.git
    cd git-mcp-server
  2. Instalar dependencias:

    npm install
  3. Construir el proyecto:

    npm run build (or `npm run rebuild`)

    Esto compila el código TypeScript a JavaScript en el directorio dist/ y hace que el punto de entrada sea ejecutable.

Configuración

Variables de entorno

Configure el servidor mediante variables de entorno. Cree un archivo .env en la raíz del proyecto (cópielo de .env.example ) o configúrelo en su entorno.

Variable

Descripción

Por defecto

MCP_TRANSPORT_TYPE

Mecanismo de transporte: stdio o http .

stdio

MCP_HTTP_PORT

Puerto del servidor HTTP (si MCP_TRANSPORT_TYPE=http ). Reintentar el siguiente puerto si está ocupado.

3010

MCP_HTTP_HOST

Dirección de host del servidor HTTP (si MCP_TRANSPORT_TYPE=http ).

127.0.0.1

MCP_ALLOWED_ORIGINS

Lista separada por comas de orígenes permitidos para CORS (si MCP_TRANSPORT_TYPE=http ).

(ninguno)

MCP_LOG_LEVEL

Nivel de registro ( debug , info , notice , warning , error , crit , alert , emerg ). Heredado de la plantilla.

info

GIT_SIGN_COMMITS

Configurar como "true" para habilitar los intentos de firma de las confirmaciones realizadas con la herramienta git_commit . Requiere la configuración de Git/clave del servidor (ver más abajo).

false

MCP_AUTH_SECRET_KEY

Clave secreta para firmar/verificar tokens de autenticación (requerida si la autenticación se habilita en el futuro).

''

Configuración del cliente MCP

Agregue a la configuración de su cliente MCP (por ejemplo, cline_mcp_settings.json ):

{
  "mcpServers": {
    "git-mcp-server": {
      // Use a descriptive name
      "command": "node", // Use node to run the script
      "args": ["/path/to/your/git-mcp-server/dist/index.js"], // Absolute path to the built entry point
      "env": {
        // "MCP_TRANSPORT_TYPE": "http", // Optional: if using http
        // "MCP_HTTP_PORT": "3010",     // Optional: if using http and non-default port
        // "GIT_SIGN_COMMITS": "true"   // Optional: Enable commit signing attempts if server is configured
      },
      "disabled": false,
      "autoApprove": [] // Configure auto-approval rules if desired
    }
  }
}

Estructura del proyecto

La base del código sigue una estructura modular dentro del directorio src/ :

src/
├── index.ts           # Entry point: Initializes and starts the server
├── config/            # Configuration loading (env vars, package info)
│   └── index.ts
├── mcp-server/        # Core MCP server logic and capability registration
│   ├── server.ts      # Server setup, capability registration
│   ├── transports/    # Transport handling (stdio, http)
│   ├── resources/     # MCP Resource implementations (currently none)
│   └── tools/         # MCP Tool implementations (subdirs per tool)
├── types-global/      # Shared TypeScript type definitions
└── utils/             # Common utility functions (logger, error handler, etc.)

Para obtener un árbol de archivos detallado, ejecute npm run tree o consulte docs/tree.md .

Herramientas

El servidor Git MCP proporciona un conjunto de herramientas para interactuar con repositorios Git, a las que se puede llamar a través del Protocolo de contexto de modelo.

Nombre de la herramienta

Descripción

Argumentos clave

git_add

Etapas de archivos o patrones específicos.

path? files?

git_branch

Administra las ramas (enumerar, crear, eliminar, renombrar, mostrar las actuales).

path? mode , ¿ branchName? ¿ newBranchName? ¿ startPoint? ¿ force? ¿ all? ¿ remote?

git_checkout

Cambia de rama o restaura archivos del árbol de trabajo.

path? branchOrPath , newBranch? ¿ force?

git_cherry_pick

Aplica los cambios introducidos por confirmaciones existentes.

path? commitRef , mainline? ¿ strategy? ¿ noCommit? ¿ signoff?

git_clean

Elimina archivos no rastreados. Requiere force: true .

path? force ?, dryRun? ¿ directories? ¿ ignored?

git_clear_working_dir

Borra el directorio de trabajo específico de la sesión.

(ninguno)

git_clone

Clona un repositorio en una ruta absoluta especificada.

repositoryUrl , targetPath , ¿ branch? ¿ depth? ¿ quiet?

git_commit

Confirma cambios programados. Admite la anulación por parte del autor y el control de firma.

path? message , author? ¿ allowEmpty? ¿ amend? ¿ forceUnsignedOnFailure?

git_diff

Muestra cambios entre confirmaciones, árbol de trabajo, etc.

path? commit1? ¿ commit2? ¿ staged? ¿ file?

git_fetch

Descarga objetos y referencias de otros repositorios.

path? remote? prune? ¿ tags? all?

git_init

Inicializa un nuevo repositorio Git en la ruta absoluta especificada. El valor predeterminado es 'main' para la rama inicial.

path , ¿ initialBranch? ¿ bare? ¿ quiet?

git_log

Muestra registros de confirmación.

path? ¿ maxCount? ¿ author? ¿ since? ¿ until? ¿ branchOrFile?

git_merge

Fusiona la rama especificada en la rama actual.

path? branch ?, commitMessage? ¿ noFf? ¿ squash? ¿ abort?

git_pull

Obtiene y se integra con otro repositorio o rama local.

path? ¿ remote? branch? ¿ rebase? ¿ ffOnly?

git_push

Actualiza referencias remotas utilizando referencias locales.

path? remote? ¿ branch? ¿ remoteBranch? ¿ force? ¿ forceWithLease? ¿ setUpstream? ¿ tags? delete?

git_rebase

Vuelve a aplicar confirmaciones sobre otra punta base.

path? mode? upstream? ¿ branch? ¿ interactive? ¿ strategy? ¿ strategyOption? onto?

git_remote

Administra repositorios remotos (enumerar, agregar, eliminar, mostrar).

path? mode , name? url?

git_reset

Restablece el HEAD actual a un estado especificado. Admite los modos suave, mixto y duro. USE "duro" CON PRECAUCIÓN .

path? mode? ¿ commit?

git_set_working_dir

Establece el directorio de trabajo predeterminado. Opcionalmente, se puede inicializar el repositorio si no está presente. Requiere una ruta absoluta.

path , validateGitRepo? initializeIfNotPresent?

git_show

Muestra información sobre los objetos Git (confirmaciones, etiquetas, etc.).

path? ref , ¿ filePath?

git_stash

Administra los cambios almacenados (enumerar, aplicar, extraer, soltar, guardar).

path? mode , ¿ stashRef? ¿ message?

git_status

Obtiene el estado del repositorio (rama, preparado, modificado, archivos no rastreados).

path?

git_tag

Administra etiquetas (lista, crear anotadas/ligeras, eliminar).

path? mode ?, tagName? ¿ message? ¿ commitRef? ¿ annotate?

git_worktree

Administra árboles de trabajo de Git (enumerar, agregar, eliminar, mover, podar).

path? ?, mode , worktreePath? ¿ commitish? newBranch? ¿ force? ¿ detach? ¿ newPath? verbose? ¿ dryRun? expire?

Nota: El parámetro path para la mayoría de las herramientas tiene como valor predeterminado el directorio de trabajo de la sesión si se configura mediante git_set_working_dir .

Recursos

Los recursos de MCP no están implementados en esta versión (v2.0.12).

Esta versión se centra en la implementación refactorizada de las herramientas Git, basada en la última mcp-ts-template y el SDK de MCP v1.12.0. Las funciones de recursos, previamente disponibles, se han eliminado temporalmente durante esta importante actualización.

Si necesita acceso a recursos MCP (por ejemplo, para leer el contenido del archivo directamente a través del servidor), utilice la versión estable v1.2.4 .

Es posible que el desarrollo futuro vuelva a introducir capacidades de recursos en una versión posterior.

Nota: Esta versión (v2.0.0) se centra en la refactorización y actualización de las herramientas principales de Git basadas en el último SDK de MCP. Las funciones de recursos de MCP no están implementadas en esta versión. Para acceder a los recursos, utilice la versión v1.2.4 .

Desarrollo

Construir y probar

# Build the project (compile TS to JS in dist/ and make executable)
npm run build

# Test the server locally using the MCP inspector tool (stdio transport)
npm run inspector

# Test the server locally using the MCP inspector tool (http transport)
npm run inspector:http

# Clean build artifacts (runs scripts/clean.ts)
npm run clean

# Generate a file tree representation for documentation (runs scripts/tree.ts)
npm run tree

# Clean build artifacts and then rebuild the project
npm run rebuild

# Start the server using stdio (default)
npm start
# Or explicitly:
npm run start:stdio

# Start the server using HTTP transport
npm run start:http

Licencia

Este proyecto está licenciado bajo la Licencia Apache 2.0: consulte el archivo de LICENCIA para obtener más detalles.


Available Tools

28 tools
git_addGit AddA

Stage files for commit. Add file contents to the staging area (index) to prepare for the next commit.

Inputs: path, files, update, all, +1 more. Returns: success, stagedFiles, totalFiles, status

git_blameGit BlameA
Read-only

Show line-by-line authorship information for a file, displaying who last modified each line and when. For large files, use startLine/endLine to limit output.

Inputs: file (required), path, startLine, endLine, +1 more. Returns: success, file, lines, totalLines

git_branchGit BranchA

Manage branches: list all branches, show current branch, create a new branch, delete a branch, or rename a branch.

Inputs: path, operation, name, newName, +6 more. Returns: success, operation, branches, currentBranch, +1 more

git_changelog_analyzeGit Changelog AnalyzeA
Read-only

Gather git history context (commits, tags) and structured review instructions to support LLM-driven changelog analysis. Changelog file should be read separately; this tool provides the supporting git data and analysis framework. Pass one or more review types to control what kind of analysis to perform.

Inputs: reviewTypes (required), path, maxCommits, sinceTag, +1 more. Returns: success, reviewTypes, gitContext, reviewInstructions

git_checkoutGit CheckoutA

Switch branches or restore working tree files. Can checkout an existing branch, create a new branch, or restore specific files.

Inputs: target (required), path, createBranch, force, +2 more. Returns: success, target, branchCreated, filesModified

git_cherry_pickGit Cherry-PickA

Cherry-pick commits from other branches. Apply specific commits to the current branch without merging entire branches.

Inputs: commits (required), path, noCommit, continueOperation, +4 more. Returns: success, pickedCommits, conflicts, conflictedFiles

git_cleanGit CleanA

Remove untracked files from the working directory. Requires force flag for safety. Use dry-run to preview files that would be removed.

Inputs: path, force, dryRun, directories, +1 more. Returns: success, filesRemoved, directoriesRemoved, dryRun

git_clear_working_dirGit Clear Working DirectoryA

Clear the session working directory setting. This resets the context without restarting the server. Subsequent git operations will require an explicit path parameter unless git_set_working_dir is called again.

Inputs: confirm (required). Returns: success, message, previousPath

git_cloneGit CloneA

Clone a repository from a remote URL to a local path. Supports HTTP/HTTPS and SSH URLs, with optional shallow cloning.

Inputs: url (required), localPath (required), branch, depth, +2 more. Returns: success, remoteUrl, localPath, branch, +1 more

git_commitGit CommitA

Create a new commit with staged changes in the repository. Records a snapshot of the staging area with a commit message.

Commit Message Format: Pass commit messages as JSON string parameters. Multi-line messages are supported using standard JSON string escaping.

Examples:

  • Single line: { "message": "feat: add user authentication" }

  • Multi-line: { "message": "feat: add user authentication\n\nImplemented OAuth2 flow with JWT tokens.\nAdded tests for login and logout." }

Note: Do not use bash heredoc syntax. Literal escape sequences (\n, \t) in the message string are automatically normalized to their actual characters.

Inputs: message (required), path, author, amend, +5 more. Returns: success, commitHash, message, author, +6 more

git_diffGit DiffB
Read-only

View differences between commits, branches, or working tree. Shows changes in unified diff format.

Inputs: path, target, source, paths, +6 more. Returns: success, diff, filesChanged, insertions, +2 more

git_fetchGit FetchA

Fetch updates from a remote repository. Downloads objects and refs without merging them.

Inputs: path, remote, prune, tags, +1 more. Returns: success, remote, fetchedRefs, prunedRefs

git_initGit InitA

Initialize a new Git repository at the specified path. Creates a .git directory and sets up the initial branch.

Inputs: path, initialBranch, bare. Returns: success, path, initialBranch, isBare

git_logGit LogA
Read-only

View commit history with optional filtering by author, date range, file path, or commit message pattern.

Inputs: path, maxCount, skip, since, +9 more. Returns: success, commits, totalCount

git_mergeGit MergeB

Merge branches together. Integrates changes from another branch into the current branch with optional merge strategies.

Inputs: branch (required), path, strategy, noFastForward, +3 more. Returns: success, strategy, fastForward, conflicts, +3 more

git_pullGit PullA

Pull changes from a remote repository. Fetches and integrates changes into the current branch.

Inputs: path, remote, branch, rebase, +1 more. Returns: success, remote, branch, strategy, +2 more

git_pushGit PushC

Push changes to a remote repository. Uploads local commits to the remote branch.

Inputs: path, remote, branch, force, +7 more. Returns: success, remote, branch, upstreamSet, +2 more

git_rebaseGit RebaseB

Rebase commits onto another branch. Reapplies commits on top of another base tip for a cleaner history.

Inputs: path, mode, upstream, branch, +3 more. Returns: success, conflicts, conflictedFiles, rebasedCommits, +1 more

git_reflogGit ReflogA
Read-only

View the reference logs (reflog) to track when branch tips and other references were updated. Useful for recovering lost commits.

Inputs: path, ref, maxCount. Returns: success, ref, entries, totalEntries

git_remoteGit RemoteA

Manage remote repositories: list remotes, add new remotes, remove remotes, rename remotes, or get/set remote URLs.

Inputs: path, mode, name, url, +2 more. Returns: success, mode, remotes, url, +3 more

git_resetGit ResetA

Reset current HEAD to specified state. Can be used to unstage files (soft), discard commits (mixed), or discard all changes (hard).

Inputs: path, mode, target, paths, +1 more. Returns: success, mode, target, filesReset

git_set_working_dirGit Set Working DirectoryA

Set the session working directory for all git operations. This allows subsequent git commands to omit the path parameter and use this directory as the default.

Inputs: path (required), validateGitRepo, initializeIfNotPresent, includeMetadata. Returns: success, path, message, repositoryContext

git_showGit ShowA
Read-only

Show details of a git object (commit, tree, blob, or tag). Displays commit information and the diff of changes introduced.

Inputs: object (required), path, format, stat, +1 more. Returns: success, object, type, content, +1 more

git_stashGit StashA

Manage stashes: list stashes, save current changes (push), restore changes (pop/apply), or remove stashes (drop/clear).

Inputs: path, mode, message, stashRef, +2 more. Returns: success, mode, stashes, created, +3 more

git_statusGit StatusA
Read-only

Show the working tree status including staged, unstaged, and untracked files.

Inputs: path, includeUntracked. Returns: success, currentBranch, isClean, stagedChanges, +3 more

git_tagGit TagA

Manage tags: list all tags, create a new tag, or delete a tag. Tags are used to mark specific points in history (releases, milestones).

Inputs: path, mode, tagName, commit, +5 more. Returns: success, mode, tags, created, +1 more

git_worktreeGit WorktreeB

Manage multiple working trees: list worktrees, add new worktrees for parallel work, remove worktrees, or move worktrees to new locations.

Inputs: path, mode, worktreePath, branch, +6 more. Returns: success, mode, worktrees, added, +3 more

git_wrapup_instructionsGit Wrap-up InstructionsA
Read-only

Provides the user's desired Git wrap-up workflow and instructions. Returns custom workflow steps (if configured) or default best practices for reviewing, documenting, and committing changes. Includes current repository status to guide next actions.

Inputs: acknowledgement (required), updateAgentMetaFiles, createTag. Returns: instructions, gitStatus, gitStatusError

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.7/5.0

    Scored across 28 tools

    Disambiguation5/5

    Every tool has a clearly distinct purpose with no ambiguity. Each tool corresponds to a specific Git command or operation, such as git_add for staging files, git_commit for creating commits, and git_merge for merging branches. The descriptions reinforce these distinctions, making it easy for an agent to select the correct tool without confusion.

    Naming Consistency5/5

    The tool names follow a highly consistent verb_noun pattern throughout, all prefixed with 'git_' and using snake_case uniformly. Examples include git_clone, git_pull, and git_status, with no deviations in style or structure. This predictability enhances readability and usability for agents.

    Tool Count3/5

    With 28 tools, the count feels heavy for a Git server, as many tools cover niche or advanced operations like git_changelog_analyze and git_wrapup_instructions. While comprehensive, it may overwhelm agents with less common commands, suggesting a borderline scope that could benefit from consolidation or simplification.

    Completeness5/5

    The tool set provides complete coverage of Git operations, including core commands (e.g., clone, commit, push), branch management, history viewing, and advanced features like stashing and worktrees. There are no obvious gaps; agents can perform full CRUD/lifecycle tasks for repository management without dead ends.

    Maintenance

    ActivityInactive
    ResponsivenessMostly unanswered

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      B
      quality
      B
      maintenance
      A Model Context Protocol server for Git repository interaction and automation. This server provides tools to read, search, and manipulate Git repositories via Large Language Models.
      14
      115,976 PyPI
      92,301
      MIT
    • A
      license
      C
      quality
      C
      maintenance
      Node.js server implementing Model Context Protocol for git operations, enabling AI assistants to manage git repositories through natural language commands.
      11
      MIT
    • A
      license
      B
      quality
      D
      maintenance
      A Model Context Protocol server that enables LLMs to interact with Git repositories, providing tools to read, search, and manipulate Git repositories through commands like status, diff, commit, and branch management.
      12
      MIT
    • A
      license
      C
      quality
      B
      maintenance
      A Model Context Protocol server that enables LLMs to interact with Git repositories, providing tools to read, search, and manipulate Git repositories through commands like status, diff, commit, and branch operations.
      22
      4
      MIT