Skip to content

Commit 5a91588

Browse files
cliffhallclaude
andcommitted
fix(git): create a branch on a detached HEAD, and from a commit-ish base
git_create_branch refused a detached HEAD when no base_branch was given, and looked base_branch up only among references, so a commit SHA raised a raw IndexError. On a detached HEAD with no base it now branches from the current commit and names its short SHA in the reply; a base that is not a reference is resolved as a commit-ish; an unknown base gives a clear error. The leading '-' guard and the existing-branch check are unchanged. Closes #5192 Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent 0c8c564 commit 5a91588

5 files changed

Lines changed: 114 additions & 18 deletions

File tree

‎src/git/README.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -76,8 +76,8 @@ Please note that mcp-server-git is currently in early development. The functiona
7676
- Inputs:
7777
- `repo_path` (string): Path to Git repository
7878
- `branch_name` (string): Name of the new branch
79-
- `base_branch` (string, optional): Base branch to create from (defaults to current branch)
80-
- Returns: Confirmation of branch creation
79+
- `base_branch` (string, optional): Branch, tag or commit SHA to create from (defaults to the current branch, or to the current commit when HEAD is detached)
80+
- Returns: Confirmation of branch creation, naming the base branch, or the short SHA when the base is a commit
8181
10. `git_checkout`
8282
- Switches branches
8383
- Inputs:

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

Lines changed: 36 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -257,16 +257,32 @@ def git_create_branch(
257257
raise FlagInjectionError(
258258
f"Invalid base branch: '{base_branch}' - cannot start with '-'"
259259
)
260+
# The base is a reference (a branch, tag or remote-tracking ref) when one
261+
# has that name, otherwise any commit-ish (a SHA, `HEAD~2`). With no base,
262+
# it is the current branch, or the current commit on a detached HEAD, where
263+
# GitPython's `active_branch` would raise TypeError. The reply names the
264+
# base the branch was created from.
265+
base: git.SymbolicReference | str
260266
if base_branch:
261-
base = repo.references[base_branch]
267+
try:
268+
base = repo.references[base_branch]
269+
base_label = f"'{base.name}'"
270+
except IndexError:
271+
try:
272+
base = repo.commit(base_branch).hexsha
273+
except (ODBError, ValueError) as e:
274+
# BadName for an unknown name, ValueError for an object that
275+
# is not a commit (a tree, say).
276+
raise ValueError(
277+
f"Unknown base branch or commit: '{base_branch}'"
278+
) from e
279+
base_label = f"commit {base[:7]}"
262280
elif repo.head.is_detached:
263-
# GitPython's `active_branch` raises TypeError on a detached HEAD.
264-
raise ValueError(
265-
"HEAD is detached, so there is no current branch to branch from; "
266-
"pass base_branch"
267-
)
281+
base = repo.head.commit.hexsha
282+
base_label = f"commit {base[:7]}"
268283
else:
269284
base = repo.active_branch
285+
base_label = f"'{base.name}'"
270286

271287
# GitPython's create_head accepts a name that already points at the base
272288
# commit, so check first rather than report a branch that was not created.
@@ -277,7 +293,7 @@ def git_create_branch(
277293
f"Cannot create branch '{branch_name}': refs/heads/{branch_name} already exists"
278294
)
279295
repo.create_head(branch_name, base)
280-
return f"Created branch '{branch_name}' from '{base.name}'"
296+
return f"Created branch '{branch_name}' from {base_label}"
281297

282298

283299
def git_checkout(repo: git.Repo, branch_name: str) -> str:
@@ -633,13 +649,24 @@ def log(
633649

634650
@server.tool(
635651
name=GitTools.CREATE_BRANCH.value,
636-
description="Creates a new branch from an optional base branch",
652+
description="Creates a new branch from an optional base branch or commit",
637653
annotations=writes(destructive=False, idempotent=False),
638654
structured_output=False,
639655
)
640656
@reports_failures
641657
def create_branch(
642-
repo_path: str, branch_name: str, base_branch: str | None = None
658+
repo_path: str,
659+
branch_name: str,
660+
base_branch: Annotated[
661+
str | None,
662+
Field(
663+
description=(
664+
"Branch, tag or commit SHA to create the branch from. "
665+
"Defaults to the current branch, or to the current commit "
666+
"when HEAD is detached"
667+
)
668+
),
669+
] = None,
643670
) -> str:
644671
return git_create_branch(open_repo(repo_path), branch_name, base_branch)
645672

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -251,7 +251,7 @@
251251
},
252252
{
253253
"name": "git_create_branch",
254-
"description": "Creates a new branch from an optional base branch",
254+
"description": "Creates a new branch from an optional base branch or commit",
255255
"inputSchema": {
256256
"properties": {
257257
"repo_path": {
@@ -272,6 +272,7 @@
272272
}
273273
],
274274
"default": null,
275+
"description": "Branch, tag or commit SHA to create the branch from. Defaults to the current branch, or to the current commit when HEAD is detached",
275276
"title": "Base Branch"
276277
}
277278
},

‎src/git/tests/test_protocol.py‎

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -632,7 +632,7 @@ async def test_git_create_branch_unknown_base_is_error(repo: git.Repo):
632632
None,
633633
"git_create_branch",
634634
{"repo_path": str(root_of(repo)), "branch_name": "x", "base_branch": "nope"},
635-
) == tool_error("git_create_branch", "No item found with id nope")
635+
) == tool_error("git_create_branch", "Unknown base branch or commit: 'nope'")
636636

637637

638638
async def test_git_create_branch_existing_name_at_same_commit_is_error(
@@ -676,23 +676,38 @@ async def test_git_create_branch_existing_name_at_other_commit_is_error(
676676
assert "already exist" in result["content"][0]["text"]
677677

678678

679-
async def test_git_create_branch_on_detached_head_asks_for_a_base(
679+
async def test_git_create_branch_on_detached_head_uses_current_commit(
680680
repo: git.Repo,
681681
):
682682
# With no base_branch the base is the active branch, which a detached HEAD
683683
# does not have (GitPython would raise TypeError, a crash under MCPServer).
684-
# #5174: the tool says so instead, as an anticipated failure.
684+
# #5192: the tool branches from the current commit and names it.
685+
head = repo.head.commit
685686
repo.git.checkout("--detach")
686687
result = await call(
687688
None,
688689
"git_create_branch",
689690
{"repo_path": str(root_of(repo)), "branch_name": "x"},
690691
)
691-
assert result == tool_error(
692+
assert result == text_result(f"Created branch 'x' from commit {head.hexsha[:7]}")
693+
assert repo.heads["x"].commit == head
694+
assert repo.head.is_detached
695+
696+
697+
async def test_git_create_branch_from_commit_sha(repo: git.Repo):
698+
first = repo.head.commit
699+
add_commits(repo, 1)
700+
result = await call(
701+
None,
692702
"git_create_branch",
693-
"HEAD is detached, so there is no current branch to branch from; "
694-
"pass base_branch",
703+
{
704+
"repo_path": str(root_of(repo)),
705+
"branch_name": "x",
706+
"base_branch": first.hexsha,
707+
},
695708
)
709+
assert result == text_result(f"Created branch 'x' from commit {first.hexsha[:7]}")
710+
assert repo.heads["x"].commit == first
696711

697712

698713
async def test_an_unanticipated_exception_is_reported_generically(repo: git.Repo):

‎src/git/tests/test_server.py‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -505,6 +505,59 @@ def test_git_create_branch_from_base(test_repository):
505505
assert "Created branch 'derived-branch' from 'base-branch'" in result
506506

507507

508+
def test_git_create_branch_on_detached_head_uses_current_commit(test_repository):
509+
# #5192: with no base_branch, a detached HEAD branches from its commit.
510+
head = test_repository.head.commit
511+
test_repository.git.checkout("--detach")
512+
513+
result = git_create_branch(test_repository, "keep")
514+
515+
assert result == f"Created branch 'keep' from commit {head.hexsha[:7]}"
516+
assert test_repository.heads["keep"].commit == head
517+
# Creating the branch does not attach HEAD to it.
518+
assert test_repository.head.is_detached
519+
520+
521+
def test_git_create_branch_from_commit_sha(test_repository):
522+
# #5192: a base that is not a reference is resolved as a commit-ish.
523+
first = test_repository.head.commit
524+
file_path = Path(test_repository.working_dir) / "later.txt"
525+
file_path.write_text("later")
526+
test_repository.index.add(["later.txt"])
527+
test_repository.index.commit("later commit")
528+
529+
result = git_create_branch(test_repository, "from-sha", first.hexsha)
530+
531+
assert result == f"Created branch 'from-sha' from commit {first.hexsha[:7]}"
532+
assert test_repository.heads["from-sha"].commit == first
533+
534+
535+
def test_git_create_branch_from_relative_revision(test_repository):
536+
first = test_repository.head.commit
537+
test_repository.index.commit("second commit")
538+
539+
git_create_branch(test_repository, "from-parent", "HEAD~1")
540+
541+
assert test_repository.heads["from-parent"].commit == first
542+
543+
544+
@pytest.mark.parametrize("base", ["nope", "HEAD^{tree}"])
545+
def test_git_create_branch_unknown_base(test_repository, base):
546+
# An unknown name (BadName) and an object that is not a commit (ValueError)
547+
# both get the same clear message, not GitPython's raw lookup error.
548+
with pytest.raises(ValueError, match="Unknown base branch or commit"):
549+
git_create_branch(test_repository, "x", base)
550+
assert not any(head.name == "x" for head in test_repository.heads)
551+
552+
553+
def test_git_create_branch_from_sha_keeps_existing_branch_check(test_repository):
554+
sha = test_repository.head.commit.hexsha
555+
test_repository.git.branch("taken")
556+
557+
with pytest.raises(ValueError, match="refs/heads/taken already exists"):
558+
git_create_branch(test_repository, "taken", sha)
559+
560+
508561
def test_git_show(test_repository):
509562
file_path = Path(test_repository.working_dir) / "show_test.txt"
510563
file_path.write_text("show content")

0 commit comments

Comments
 (0)