Skip to content

Commit 98845dc

Browse files
cliffhallclaude
andcommitted
feat(git): add git_merge tool
Merges a branch, tag or commit into the current branch. Fast-forward only by default; fast_forward_only=false allows a merge commit. Refuses a detached HEAD, a dirty working tree and a merge already in progress, and aborts a merge that stops on conflicts (naming the files) or fails to commit, so a failed call leaves the repository as it was. Keeps the flag-injection guard and repository confinement of the other tools. Closes modelcontextprotocol#659 Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent 446be48 commit 98845dc

5 files changed

Lines changed: 453 additions & 3 deletions

File tree

‎src/git/README.md‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -84,14 +84,22 @@ Please note that mcp-server-git is currently in early development. The functiona
8484
- `repo_path` (string): Path to Git repository
8585
- `branch_name` (string): Name of branch to checkout
8686
- Returns: Confirmation of branch switch, or `HEAD is now detached at <short sha>` when `branch_name` is not a branch (a sha, tag or other revision)
87-
11. `git_show`
87+
11. `git_merge`
88+
- Merges a branch into the current branch, or changes nothing
89+
- Inputs:
90+
- `repo_path` (string): Path to Git repository
91+
- `source_branch` (string): Branch, tag or commit to merge into the current branch (check out the branch to merge into first with `git_checkout`)
92+
- `fast_forward_only` (boolean, optional): Only fast-forward, failing if the branches have diverged (default `true`). `false` lets Git create a merge commit when they have
93+
- Returns: `Fast-forwarded`, `Merged ... with merge commit <short sha>`, or `Already up to date`
94+
- Refuses a detached HEAD, a working tree with uncommitted changes, and a merge already in progress. A merge that stops on conflicts is aborted (`git merge --abort`) and the error names the conflicting files, so the repository is left as it was
95+
12. `git_show`
8896
- Shows the contents of a commit, or of a file or directory at a revision
8997
- Inputs:
9098
- `repo_path` (string): Path to Git repository
9199
- `revision` (string): The revision (commit hash, branch name, tag) or object spec (`HEAD:path/to/file`) to show
92100
- Returns: Contents of the specified commit, file content, or directory listing
93101

94-
12. `git_branch`
102+
13. `git_branch`
95103
- List Git branches
96104
- Inputs:
97105
- `repo_path` (string): Path to the Git repository.
@@ -135,7 +143,7 @@ python -m mcp_server_git
135143
## Configuration
136144

137145
> [!IMPORTANT]
138-
> **Without `--repository`, the server reads and writes any Git repository the server process can reach.** Each tool call names its own `repo_path`, and that holds for the tools that change a repository too (`git_add`, `git_commit`, `git_reset`, `git_create_branch`, `git_checkout`). `--repository` is the only confinement the server offers: it never asks the client for Roots, in either protocol era. Set `--repository` whenever the server is used with prompts or content that are not fully trusted. It admits the whole enclosing repository, not only the directory you name, as the next paragraph describes.
146+
> **Without `--repository`, the server reads and writes any Git repository the server process can reach.** Each tool call names its own `repo_path`, and that holds for the tools that change a repository too (`git_add`, `git_commit`, `git_reset`, `git_create_branch`, `git_checkout`, `git_merge`). `--repository` is the only confinement the server offers: it never asks the client for Roots, in either protocol era. Set `--repository` whenever the server is used with prompts or content that are not fully trusted. It admits the whole enclosing repository, not only the directory you name, as the next paragraph describes.
139147
140148
`--repository` (`-r`) accepts any path inside a Git working tree. At startup the server walks up to the enclosing repository root, the way `git rev-parse --show-toplevel` does, so `--repository .` works when a shared config is launched from any subdirectory of the repository. A path inside the repository therefore allows tool calls anywhere in that repository, not only under the subdirectory given. A path that does not exist, or is not inside a Git repository, is logged as a one-line error at startup.
141149

‎src/git/src/mcp_server_git/server.py‎

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ class GitTools(str, Enum):
6969
LOG = "git_log"
7070
CREATE_BRANCH = "git_create_branch"
7171
CHECKOUT = "git_checkout"
72+
MERGE = "git_merge"
7273
SHOW = "git_show"
7374

7475
BRANCH = "git_branch"
@@ -345,6 +346,103 @@ def git_checkout(repo: git.Repo, branch_name: str) -> str:
345346
return f"Switched to branch '{repo.active_branch.name}'"
346347

347348

349+
def _git_stderr(error: git.GitCommandError) -> str:
350+
"""Git's own message from a failed command, without GitPython's framing.
351+
352+
GitPython formats `stderr` as `\n stderr: '<message>'`.
353+
"""
354+
message = str(error.stderr).strip().removeprefix("stderr: '").removesuffix("'")
355+
return message or str(error)
356+
357+
358+
def _merge_failure(repo: git.Repo, error: git.GitCommandError, what: str) -> str:
359+
"""Why `git merge` failed, after undoing whatever it left behind.
360+
361+
A merge that stops on conflicts, or fails to write its merge commit,
362+
leaves MERGE_HEAD and a half-merged index and working tree. The tool
363+
required a clean tree before merging, so `git merge --abort` restores
364+
exactly the state the call started from. `what` names the merge, as
365+
"Merge of '<source>' into '<target>'".
366+
"""
367+
unchanged = "The merge was aborted and the repository is unchanged."
368+
if not (Path(repo.git_dir) / "MERGE_HEAD").exists():
369+
# Git refused before changing anything.
370+
return f"{what} failed. {unchanged} Git reported:\n{_git_stderr(error)}"
371+
conflicts = repo.git.diff("--name-only", "--diff-filter=U").splitlines()
372+
repo.git.merge("--abort")
373+
if conflicts:
374+
return (
375+
f"{what} stopped on conflicts in: {', '.join(conflicts)}. {unchanged} "
376+
"Resolve the conflicts by hand."
377+
)
378+
return f"{what} failed. {unchanged} Git reported:\n{_git_stderr(error)}"
379+
380+
381+
def git_merge(
382+
repo: git.Repo, source_branch: str, fast_forward_only: bool = True
383+
) -> str:
384+
"""Merge `source_branch` into the current branch, or change nothing.
385+
386+
Conservative by design (#659): the merge goes into the branch HEAD is on,
387+
never another, and it starts only from a clean working tree, so a merge
388+
that stops on conflicts is aborted and the repository is left as it was.
389+
The conflicts are reported for the caller to resolve by hand. By default
390+
only a fast-forward is allowed; `fast_forward_only=False` lets git create
391+
a merge commit when the branches have diverged.
392+
"""
393+
# Defense in depth: reject sources starting with '-' to prevent flag
394+
# injection, even if a malicious ref with that name exists.
395+
if source_branch.startswith("-"):
396+
raise FlagInjectionError(
397+
f"Invalid source branch: '{source_branch}' - cannot start with '-'"
398+
)
399+
if repo.head.is_detached:
400+
raise ValueError(
401+
"HEAD is detached; check out the branch to merge into first (git_checkout)"
402+
)
403+
target = repo.active_branch.name
404+
if not repo.head.is_valid():
405+
raise ValueError(f"Branch '{target}' has no commits yet; nothing to merge into")
406+
if (Path(repo.git_dir) / "MERGE_HEAD").exists():
407+
raise ValueError(
408+
"A merge is already in progress; conclude it with git_commit first"
409+
)
410+
if repo.is_dirty():
411+
raise ValueError(
412+
f"Cannot merge into '{target}': the working tree has uncommitted "
413+
"changes. Commit or discard them first, so a failed merge can be "
414+
"undone cleanly."
415+
)
416+
# Resolves the revision (BadName if unknown) and requires a commit.
417+
source = repo.commit(source_branch)
418+
head = repo.head.commit
419+
if repo.is_ancestor(source, head):
420+
return f"Already up to date: '{target}' already contains '{source_branch}'"
421+
fast_forward = repo.is_ancestor(head, source)
422+
if fast_forward_only and not fast_forward:
423+
raise ValueError(
424+
f"Cannot fast-forward '{target}' to '{source_branch}': the branches "
425+
"have diverged. Nothing was changed. Pass fast_forward_only=false "
426+
"to create a merge commit."
427+
)
428+
# --ff overrides a merge.ff setting in the user's config, so the outcome
429+
# is the one this tool describes; --no-edit keeps git from opening an
430+
# editor for the merge commit message.
431+
mode = "--ff-only" if fast_forward_only else "--ff"
432+
try:
433+
repo.git.merge(mode, "--no-edit", source_branch)
434+
except git.GitCommandError as e:
435+
what = f"Merge of '{source_branch}' into '{target}'"
436+
raise ValueError(_merge_failure(repo, e, what)) from e
437+
merged = repo.head.commit
438+
if fast_forward:
439+
return f"Fast-forwarded '{target}' to '{source_branch}' ({merged.hexsha[:7]})"
440+
return (
441+
f"Merged '{source_branch}' into '{target}' with merge commit "
442+
f"{merged.hexsha[:7]}"
443+
)
444+
445+
348446
def git_show(repo: git.Repo, revision: str) -> str:
349447
# Defense in depth: reject revisions starting with '-' to prevent flag injection,
350448
# even if a malicious ref with that name exists (e.g. via filesystem manipulation)
@@ -774,6 +872,37 @@ def create_branch(
774872
def checkout(repo_path: str, branch_name: str) -> str:
775873
return git_checkout(open_repo(repo_path), branch_name)
776874

875+
@server.tool(
876+
name=GitTools.MERGE.value,
877+
description=(
878+
"Merges a branch into the current branch. Fast-forward only unless "
879+
"fast_forward_only is false; refuses a dirty working tree, and "
880+
"aborts a merge that conflicts, leaving the repository unchanged"
881+
),
882+
annotations=writes(destructive=False, idempotent=True),
883+
structured_output=False,
884+
)
885+
@reports_failures
886+
def merge(
887+
repo_path: str,
888+
source_branch: Annotated[
889+
str,
890+
Field(
891+
description=("Branch, tag or commit to merge into the current branch")
892+
),
893+
],
894+
fast_forward_only: Annotated[
895+
bool,
896+
Field(
897+
description=(
898+
"Only fast-forward, failing if the branches have diverged. "
899+
"False allows a merge commit"
900+
)
901+
),
902+
] = True,
903+
) -> str:
904+
return git_merge(open_repo(repo_path), source_branch, fast_forward_only)
905+
777906
@server.tool(
778907
name=GitTools.SHOW.value,
779908
description="Shows the contents of a commit, or of a file or directory given as <revision>:<path>",

‎src/git/tests/snapshots/list_tools.json‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -318,6 +318,41 @@
318318
"openWorldHint": false
319319
}
320320
},
321+
{
322+
"name": "git_merge",
323+
"description": "Merges a branch into the current branch. Fast-forward only unless fast_forward_only is false; refuses a dirty working tree, and aborts a merge that conflicts, leaving the repository unchanged",
324+
"inputSchema": {
325+
"properties": {
326+
"repo_path": {
327+
"title": "Repo Path",
328+
"type": "string"
329+
},
330+
"source_branch": {
331+
"description": "Branch, tag or commit to merge into the current branch",
332+
"title": "Source Branch",
333+
"type": "string"
334+
},
335+
"fast_forward_only": {
336+
"default": true,
337+
"description": "Only fast-forward, failing if the branches have diverged. False allows a merge commit",
338+
"title": "Fast Forward Only",
339+
"type": "boolean"
340+
}
341+
},
342+
"required": [
343+
"repo_path",
344+
"source_branch"
345+
],
346+
"type": "object",
347+
"title": "mergeArguments"
348+
},
349+
"annotations": {
350+
"readOnlyHint": false,
351+
"destructiveHint": false,
352+
"idempotentHint": true,
353+
"openWorldHint": false
354+
}
355+
},
321356
{
322357
"name": "git_show",
323358
"description": "Shows the contents of a commit, or of a file or directory given as <revision>:<path>",

0 commit comments

Comments
 (0)