Skip to main content
Glama
git-mcp-server

git-mcp-server

by cyanheads

Git MCP 服务器

TypeScript 模型上下文协议 版本 执照 地位 GitHub

MCP(模型上下文协议)服务器,提供与 Git 存储库交互的工具。使 LLM 和 AI 代理能够通过 MCP 标准执行 Git 操作,例如克隆、提交、推送、拉取、分支、差异、日志、状态等。

该服务器基于cyanheads/mcp-ts-template构建,遵循模块化架构:

开发人员注意事项:此存储库包含一个.clinerules文件,该文件可作为您的 LLM 编码代理的开发人员备忘单,并提供代码库模式、文件位置和代码片段的快速参考。

目录

|概述|特点|安装|

|配置|项目结构|

|工具|资源|开发|许可证|

Related MCP server: GIT MCP Server

概述

通过无缝 Git 集成增强您的 AI 代理和开发工具!

Git MCP 服务器充当桥梁,允许理解模型上下文协议 (MCP) 的应用程序(MCP 客户端) - 如高级 AI 助手 (LLM)、IDE 扩展或自定义脚本 - 直接安全地与本地 Git 存储库进行交互。

您的工具可以利用此服务器来执行以下操作,而无需使用复杂的脚本或手动 CLI:

  • 自动化 Git 工作流程:克隆存储库、创建分支、暂存更改、提交工作、推送更新以及以编程方式管理标签。

  • 获得存储库洞察:无需离开主机应用程序即可检查状态、查看日志、差异更改和检查 Git 对象。

  • 将 Git 集成到 AI 驱动的开发中:使 LLM 能够将版本控制作为其编码或重构任务的一部分进行管理。

该服务器基于强大的mcp-ts-template构建,提供了一种通过 MCP 标准公开 Git 功能的标准化、安全且高效的方式。它通过使用 Node.js 的child_process模块安全地执行系统上安装的标准git命令行工具来实现这一点,从而确保兼容性并充分利用 Git 的全部功能。

特征

核心实用程序(来自模板)

利用mcp-ts-template提供的强大实用程序:

  • 日志记录:结构化、可配置的日志记录(文件轮换、控制台、MCP 通知),并带有敏感数据编辑。

  • 错误处理:集中错误处理、标准化错误类型( McpError )和自动日志记录。

  • 配置:环境变量加载( dotenv )。

  • 输入验证/清理:使用zod进行模式验证和自定义清理逻辑(对于路径至关重要)。

  • 请求上下文:通过唯一的请求 ID 来跟踪和关联操作。

  • 类型安全:由 TypeScript 和 Zod 模式强制执行的强类型。

  • HTTP 传输选项:内置 Express 服务器,支持 SSE、会话管理和 CORS。

Git 操作

  • 直接 Git CLI 执行:通过 Node.js child_process安全地执行标准git命令行工具与 Git 交互,确保完全兼容并可访问 Git 的功能。

  • 全面的命令覆盖:将各种 Git 命令作为 MCP 工具公开(参见工具部分)。

  • 存储库交互:支持状态检查、分支、暂存、提交、获取、拉取、推送、差异、日志记录、重置、标记等。

  • 工作目录管理:允许设置和清除特定于会话的工作目录,以便在多个 Git 操作中保持上下文持久性。

  • 安全功能:包括检查并要求对潜在破坏性操作(如git clean和git reset --hard进行明确确认。

  • 提交签名:支持使用 GPG 或 SSH 签名已验证的提交,通过GIT_SIGN_COMMITS环境变量和服务器端 Git 配置进行控制。包含一个可选工具参数,用于在签名失败时回退到未签名的提交。

安装

先决条件

通过 npm 安装

  1. 全局安装包:

    npm install @cyanheads/git-mcp-server

从源安装

  1. 克隆存储库:

    git clone https://github.com/cyanheads/git-mcp-server.git
    cd git-mcp-server
  2. 安装依赖项:

    npm install
  3. 构建项目:

    npm run build (or `npm run rebuild`)

    这会将dist/目录中的 TypeScript 代码编译为 JavaScript,并使入口点可执行。

配置

环境变量

使用环境变量配置服务器。在项目根目录下创建一个.env文件(从.env.example复制),或者在你的环境中设置它们。

多变的

描述

默认

MCP_TRANSPORT_TYPE

传输机制: stdio或http 。

stdio

MCP_HTTP_PORT

HTTP 服务器的端口(如果MCP_TRANSPORT_TYPE=http )。如果端口繁忙,则重试下一个端口。

3010

MCP_HTTP_HOST

HTTP 服务器的主机地址(如果MCP_TRANSPORT_TYPE=http )。

127.0.0.1

MCP_ALLOWED_ORIGINS

以逗号分隔的 CORS 允许来源列表(如果MCP_TRANSPORT_TYPE=http )。

(没有任何)

MCP_LOG_LEVEL

日志级别( debug 、 info 、 notice 、 warning 、 error 、 crit 、 alert 、 emerg )。继承自模板。

info

GIT_SIGN_COMMITS

设置为"true"即可启用对git_commit工具所作提交的签名尝试。需要服务器端 Git/key 设置(见下文)。

false

MCP_AUTH_SECRET_KEY

用于签署/验证身份验证令牌的密钥(如果将来启用身份验证则需要)。

''

MCP 客户端设置

添加到您的 MCP 客户端设置(例如, 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
    }
  }
}

项目结构

代码库遵循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.)

有关详细的文件树,请运行npm run tree或查看docs/tree.md 。

工具

Git MCP 服务器提供了一套用于与 Git 存储库交互的工具,可通过模型上下文协议调用。

工具名称

描述

关键论点

git_add

暂存指定的文件或模式。

path? 、 files?

git_branch

管理分支(列出、创建、删除、重命名、显示当前)。

path? 、 mode 、 branchName? 、 newBranchName? 、 startPoint? 、 force? 、 all? 、 remote?

git_checkout

切换分支或恢复工作树文件。

path? 、 branchOrPath 、 newBranch? force?

git_cherry_pick

应用现有提交引入的更改。

path? 、 commitRef 、 mainline? 、 strategy? 、 noCommit? signoff?

git_clean

删除未跟踪的文件。需要force: true 。

path? 、 force 、 dryRun? directories? 、 ignored?

git_clear_working_dir

清除会话特定的工作目录。

(没有任何)

git_clone

将存储库克隆到指定的绝对路径。

repositoryUrl 、 targetPath 、 branch? 、 depth? 、 quiet?

git_commit

提交阶段性变更。支持作者覆盖和签名控制。

path? 、 message 、 author? 、 allowEmpty? 、 amend? 、 forceUnsignedOnFailure?

git_diff

显示提交、工作树等之间的变化。

path? 、 commit1? commit2? ?、 staged? 、 file?

git_fetch

从其他存储库下载对象和引用。

path? 、 remote? 、 prune? 、 tags? 、 all?

git_init

在指定的绝对路径下初始化一个新的 Git 仓库。初始分支默认为“main”。

path 、 initialBranch? bare? 、 quiet?

git_log

显示提交日志。

path? 、 maxCount? 、 author? 、 since? 、 until? 、 branchOrFile?

git_merge

将指定分支合并到当前分支。

path? 、 branch 、 commitMessage? 、 noFf? 、 squash? 、 abort?

git_pull

从另一个存储库或本地分支获取并集成。

path? 、 remote? 、 branch? 、 rebase? 、 ffOnly?

git_push

使用本地引用更新远程引用。

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

git_rebase

在另一个基本提示之上重新应用提交。

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

git_remote

管理远程存储库(列出、添加、删除、显示)。

path? 、 mode 、 name? 、 url?

git_reset

将当前 HEAD 重置为指定状态。支持软、混合、硬三种模式。请谨慎使用“hard” 。

path? 、 mode? 、 commit?

git_set_working_dir

设置默认工作目录。如果不存在,可以选择初始化 repo。需要绝对路径。

path 、 validateGitRepo? 、 initializeIfNotPresent?

git_show

显示有关 Git 对象(提交、标签等)的信息。

path? , ref , filePath?

git_stash

管理存储的更改(列出、应用、弹出、删除、保存)。

path? 、 mode 、 stashRef? message?

git_status

获取存储库状态(分支、暂存、修改、未跟踪的文件)。

path?

git_tag

管理标签(列表、创建注释/轻量级、删除)。

path? 、 mode 、 tagName? 、 message? 、 commitRef? annotate?

git_worktree

管理 Git 工作树(列出、添加、删除、移动、修剪)。

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

注意:如果通过git_set_working_dir设置,大多数工具的path参数默认为会话的工作目录。

资源

此版本(v2.0.12)中未实现 MCP 资源。

此版本重点关注基于最新mcp-ts-template和 MCP SDK v1.12.0 重构的 Git 工具实现。此前可用的资源功能在本次重大更新中被暂时移除。

如果您需要 MCP 资源访问(例如,直接通过服务器读取文件内容),请使用稳定的**v1.2.4 版本**。

未来的开发可能会在后续版本中重新引入资源功能。

**注意:**此版本 (v2.0.0) 重点基于最新的 MCP SDK 重构和更新了核心 Git 工具。MCP 资源功能尚未在此版本中实现。如需访问资源,请使用v1.2.4 版本。

发展

构建和测试

# 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

执照

该项目根据 Apache License 2.0 获得许可 - 有关详细信息,请参阅LICENSE文件。


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

    ActivityNo data
    ResponsivenessOutdated data

    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
      91,952
      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
      147 npm
      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