Skip to content

Commit 0e729d3

Browse files
authored
Merge pull request #5007 from modelcontextprotocol/v2/fix/4762-git-commit-add-nothing-staged
fix(git): refuse empty commits and report no-op git_add (#4762, #4763)
2 parents a837007 + d3b2af9 commit 0e729d3

5 files changed

Lines changed: 218 additions & 25 deletions

File tree

‎src/git/README.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -47,14 +47,14 @@ Please note that mcp-server-git is currently in early development. The functiona
4747
- Inputs:
4848
- `repo_path` (string): Path to Git repository
4949
- `message` (string): Commit message
50-
- Returns: Confirmation with new commit hash
50+
- Returns: Confirmation with new commit hash; an error if nothing is staged (as `git commit` without `--allow-empty`), except while a merge is in progress (`MERGE_HEAD` present), where git also allows an empty commit. While a merge is in progress the commit concludes it: its parents are `HEAD` and every `MERGE_HEAD` commit, and the merge state is cleared
5151

5252
6. `git_add`
5353
- Adds file contents to the staging area
5454
- Inputs:
5555
- `repo_path` (string): Path to Git repository
56-
- `files` (string[]): Array of file paths to stage
57-
- Returns: Confirmation of staged files
56+
- `files` (string[]): Non-empty array of file paths to stage; `["."]` stages everything
57+
- Returns: Confirmation of staged files, or a message saying nothing was staged when the call left the index unchanged
5858

5959
7. `git_reset`
6060
- Unstages all staged changes

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

Lines changed: 57 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ class GitCommit(BaseModel):
5050

5151
class GitAdd(BaseModel):
5252
repo_path: str
53-
files: list[str]
53+
files: list[str] = Field(..., min_length=1)
5454

5555

5656
class GitReset(BaseModel):
@@ -146,13 +146,60 @@ def git_diff(
146146
return repo.git.diff(f"--unified={context_lines}", target)
147147

148148

149+
def _has_staged_changes(repo: git.Repo) -> bool:
150+
"""Whether the index holds anything git would record as a commit.
151+
152+
Mirrors `git commit`, which refuses to create an empty commit unless
153+
--allow-empty is given, but permits one while a merge is in progress.
154+
"""
155+
if (Path(repo.git_dir) / "MERGE_HEAD").exists():
156+
return True
157+
if not repo.head.is_valid():
158+
# Unborn branch: the first commit, so anything in the index counts.
159+
return bool(repo.index.entries)
160+
return bool(repo.index.diff(repo.head.commit))
161+
162+
149163
def git_commit(repo: git.Repo, message: str) -> str:
150-
commit = repo.index.commit(message)
164+
# repo.index.commit() writes a tree unconditionally, so without this check
165+
# a caller that forgot to stage gets a hash back for an empty commit and no
166+
# way to tell it apart from a real one.
167+
if not _has_staged_changes(repo):
168+
raise ValueError(
169+
"No changes staged for commit. Use git_add to stage changes first; "
170+
"git_status shows what is currently staged."
171+
)
172+
git_dir = Path(repo.git_dir)
173+
merge_head = git_dir / "MERGE_HEAD"
174+
if merge_head.exists():
175+
# Conclude the merge as `git commit` does: HEAD plus every MERGE_HEAD
176+
# commit as parents, then clear the merge state. index.commit() alone
177+
# records only HEAD and leaves the repository mid-merge.
178+
parents = [repo.head.commit] + [
179+
repo.commit(sha) for sha in merge_head.read_text().split()
180+
]
181+
commit = repo.index.commit(message, parent_commits=parents)
182+
for name in ("MERGE_HEAD", "MERGE_MSG", "MERGE_MODE", "AUTO_MERGE"):
183+
(git_dir / name).unlink(missing_ok=True)
184+
else:
185+
commit = repo.index.commit(message)
151186
return f"Changes committed successfully with hash {commit.hexsha}"
152187

153188

189+
def _index_entries(repo: git.Repo, files: list[str]) -> str:
190+
"""Mode, blob and stage of the index entries matching the pathspecs."""
191+
return repo.git.ls_files("--stage", "--", *files)
192+
193+
154194
def git_add(repo: git.Repo, files: list[str]) -> str:
195+
if not files:
196+
# `git add --` with no pathspec is a no-op that exits 0.
197+
raise ValueError(
198+
"No files provided to stage. Pass one or more paths, "
199+
"or ['.'] to stage everything."
200+
)
155201
if files == ["."]:
202+
before = _index_entries(repo, files)
156203
repo.git.add(".")
157204
else:
158205
# Defense in depth: validate each path resolves within the repository
@@ -168,8 +215,16 @@ def git_add(repo: git.Repo, files: list[str]) -> str:
168215
resolved.relative_to(repo_root)
169216
except ValueError:
170217
raise ValueError(f"Path '{f}' is outside the repository '{repo_root}'")
218+
before = _index_entries(repo, files)
171219
# Use '--' to prevent files starting with '-' from being interpreted as options
172220
repo.git.add("--", *files)
221+
# `git add` exits 0 when it stages nothing (e.g. '.' on a clean tree), so
222+
# read the outcome back from the index rather than the exit status.
223+
if _index_entries(repo, files) == before:
224+
return (
225+
"No changes were staged: the given paths had nothing new to stage. "
226+
"git_status shows what is modified or untracked."
227+
)
173228
return "Files staged successfully"
174229

175230

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,7 @@
153153
"items": {
154154
"type": "string"
155155
},
156+
"minItems": 1,
156157
"title": "Files",
157158
"type": "array"
158159
}

‎src/git/tests/test_protocol.py‎

Lines changed: 19 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -313,23 +313,21 @@ async def test_git_commit_records_staged_changes(repo: git.Repo):
313313
assert "new.txt" in head.stats.files
314314

315315

316-
# KNOWN BUG #4762: pins current (wrong) behavior; the fix changes this assertion.
317-
async def test_git_commit_with_nothing_staged_creates_empty_commit(repo: git.Repo):
318-
# Pins #4762: with nothing staged, git_commit still writes a commit (whose
319-
# tree equals its parent's) and reports success. `git commit` would refuse
320-
# with "no changes added to commit". Fixing #4762 changes this test.
316+
async def test_git_commit_with_nothing_staged_is_refused(repo: git.Repo):
317+
# #4762: with nothing staged, git_commit refuses, as `git commit` does
318+
# without --allow-empty, instead of writing an empty commit.
321319
root = root_of(repo)
322320
(root / "test.txt").write_text("edited but not staged\n", newline="\n")
323321
before = repo.head.commit
324322
result = await call(
325323
None, "git_commit", {"repo_path": str(root), "message": "claims a fix"}
326324
)
327-
after = repo.head.commit
328325
assert result == text_result(
329-
f"Changes committed successfully with hash {after.hexsha}"
326+
"No changes staged for commit. Use git_add to stage changes first; "
327+
"git_status shows what is currently staged.",
328+
is_error=True,
330329
)
331-
assert after.parents == (before,)
332-
assert after.tree.hexsha == before.tree.hexsha
330+
assert repo.head.commit == before
333331
assert repo.is_dirty()
334332

335333

@@ -386,26 +384,27 @@ async def test_git_add_file_starting_with_dash_is_a_path(repo: git.Repo):
386384
assert staged_paths(repo) == {"-n"}
387385

388386

389-
# KNOWN BUG #4763: pins current (wrong) behavior; the fix changes this assertion.
390-
async def test_git_add_empty_list_reports_success_but_stages_nothing(
391-
repo: git.Repo,
392-
):
393-
# Pins #4763: `files: []` runs `git add --`, a no-op, and still reports
394-
# success. Fixing #4763 changes this test.
387+
async def test_git_add_empty_list_is_rejected(repo: git.Repo):
388+
# #4763: `files: []` would run `git add --`, a no-op. The schema's
389+
# minItems makes the SDK reject it before the tool runs.
395390
root = root_of(repo)
396391
(root / "test.txt").write_text("edited\n", newline="\n")
397392
result = await call(None, "git_add", {"repo_path": str(root), "files": []})
398-
assert result == text_result("Files staged successfully")
393+
assert result == text_result(
394+
"Input validation error: [] should be non-empty", is_error=True
395+
)
399396
assert staged_paths(repo) == set()
400397

401398

402-
# KNOWN BUG #4763: pins current (wrong) behavior; the fix changes this assertion.
403-
async def test_git_add_dot_on_clean_tree_reports_success(repo: git.Repo):
404-
# Pins #4763: nothing to stage, success reported anyway.
399+
async def test_git_add_dot_on_clean_tree_reports_nothing_staged(repo: git.Repo):
400+
# #4763: nothing to stage, and the result says so.
405401
result = await call(
406402
None, "git_add", {"repo_path": str(root_of(repo)), "files": ["."]}
407403
)
408-
assert result == text_result("Files staged successfully")
404+
assert result == text_result(
405+
"No changes were staged: the given paths had nothing new to stage. "
406+
"git_status shows what is modified or untracked."
407+
)
409408
assert staged_paths(repo) == set()
410409

411410

‎src/git/tests/test_server.py‎

Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,35 @@ def test_git_add_specific_files(test_repository):
110110
assert result == "Files staged successfully"
111111

112112

113+
def test_git_add_rejects_an_empty_file_list(test_repository):
114+
# #4763: `git add --` with no pathspec is a no-op that exits 0.
115+
with pytest.raises(ValueError, match="No files provided to stage"):
116+
git_add(test_repository, [])
117+
118+
119+
def test_git_add_clean_tree_reports_nothing_staged(test_repository):
120+
result = git_add(test_repository, ["."])
121+
122+
assert result.startswith("No changes were staged")
123+
assert not test_repository.index.diff(test_repository.head.commit)
124+
125+
126+
def test_git_add_already_staged_file_reports_nothing_staged(test_repository):
127+
# A change staged earlier must not make a no-op call read as a success.
128+
Path(test_repository.working_dir, "staged.txt").write_text("staged")
129+
test_repository.index.add(["staged.txt"])
130+
131+
assert git_add(test_repository, ["staged.txt"]).startswith("No changes were staged")
132+
assert git_add(test_repository, ["."]).startswith("No changes were staged")
133+
134+
135+
def test_git_add_reports_a_staged_deletion(test_repository):
136+
Path(test_repository.working_dir, "test.txt").unlink()
137+
138+
assert git_add(test_repository, ["test.txt"]) == "Files staged successfully"
139+
assert "test.txt" not in [path for path, _stage in test_repository.index.entries]
140+
141+
113142
def test_git_add_rejects_path_traversal(test_repository):
114143
# Security invariant (CVE-2026-27735): a relative path escaping the
115144
# repository must never be staged. Accept rejection from either the
@@ -206,6 +235,115 @@ def test_git_commit(test_repository):
206235
assert latest_commit.message.strip() == "test commit message"
207236

208237

238+
def test_git_commit_refuses_when_nothing_is_staged(test_repository):
239+
# #4762: repo.index.commit() writes a tree unconditionally, so each of
240+
# these used to come back as a hash for an empty commit.
241+
head_before = test_repository.head.commit.hexsha
242+
working_file = Path(test_repository.working_dir) / "test.txt"
243+
244+
# A clean tree.
245+
with pytest.raises(ValueError, match="No changes staged for commit"):
246+
git_commit(test_repository, "nothing to record")
247+
248+
# An untracked file, which git_add was never called for.
249+
Path(test_repository.working_dir, "untracked.txt").write_text("never added")
250+
with pytest.raises(ValueError, match="No changes staged for commit"):
251+
git_commit(test_repository, "nothing to record")
252+
253+
# A tracked file edited but not staged.
254+
working_file.write_text("edited but never staged")
255+
with pytest.raises(ValueError, match="No changes staged for commit"):
256+
git_commit(test_repository, "nothing to record")
257+
258+
assert test_repository.head.commit.hexsha == head_before
259+
assert working_file.read_text() == "edited but never staged"
260+
261+
262+
def test_git_commit_records_a_staged_deletion(test_repository):
263+
# A deletion leaves no file behind, so it must not read as an empty index.
264+
test_repository.git.rm("test.txt")
265+
266+
result = git_commit(test_repository, "remove test.txt")
267+
268+
assert "Changes committed successfully with hash" in result
269+
assert "test.txt" not in test_repository.head.commit.tree
270+
271+
272+
def test_git_commit_allows_the_first_commit_on_an_unborn_branch(tmp_path: Path):
273+
repo = git.Repo.init(tmp_path / "unborn")
274+
Path(repo.working_dir, "first.txt").write_text("first")
275+
repo.index.add(["first.txt"])
276+
277+
result = git_commit(repo, "initial commit")
278+
279+
assert "Changes committed successfully with hash" in result
280+
assert repo.head.commit.message.strip() == "initial commit"
281+
repo.close()
282+
283+
284+
def test_git_commit_refuses_an_empty_unborn_branch(tmp_path: Path):
285+
repo = git.Repo.init(tmp_path / "unborn")
286+
287+
with pytest.raises(ValueError, match="No changes staged for commit"):
288+
git_commit(repo, "initial commit")
289+
290+
assert not repo.head.is_valid()
291+
repo.close()
292+
293+
294+
def test_git_commit_allows_an_empty_merge_commit(repo):
295+
# git permits an empty commit while a merge is in progress, so a merge
296+
# whose result matches HEAD must still be committable. --no-commit sets
297+
# MERGE_HEAD deterministically, without provoking a conflict.
298+
starting_branch = repo.active_branch.name
299+
repo.git.checkout("-b", "side")
300+
Path(repo.working_dir, "side.txt").write_text("side only")
301+
repo.git.add("side.txt")
302+
side_sha = repo.index.commit("side change").hexsha
303+
304+
repo.git.checkout(starting_branch)
305+
head_before = repo.head.commit.hexsha
306+
repo.git.merge("side", "--no-commit", "--no-ff")
307+
assert (Path(repo.git_dir) / "MERGE_HEAD").exists()
308+
309+
# Roll the index back to HEAD's own content: the pending merge commit
310+
# records no change at all, which git allows.
311+
repo.git.rm("side.txt", "--cached")
312+
Path(repo.working_dir, "side.txt").unlink()
313+
assert not repo.index.diff(repo.head.commit)
314+
315+
result = git_commit(repo, "merge side")
316+
317+
assert "Changes committed successfully with hash" in result
318+
assert [p.hexsha for p in repo.head.commit.parents] == [head_before, side_sha]
319+
assert not (Path(repo.git_dir) / "MERGE_HEAD").exists()
320+
321+
322+
def test_git_commit_concludes_a_merge_with_both_parents(repo):
323+
# #5012: a merge commit records HEAD and MERGE_HEAD as parents and clears
324+
# the merge state, as `git commit` does.
325+
starting_branch = repo.active_branch.name
326+
repo.git.checkout("-b", "side")
327+
Path(repo.working_dir, "side.txt").write_text("side only")
328+
repo.git.add("side.txt")
329+
side_sha = repo.index.commit("side change").hexsha
330+
331+
repo.git.checkout(starting_branch)
332+
head_before = repo.head.commit.hexsha
333+
repo.git.merge("side", "--no-commit", "--no-ff")
334+
335+
result = git_commit(repo, "merge side")
336+
337+
commit = repo.head.commit
338+
assert commit.hexsha in result
339+
assert [p.hexsha for p in commit.parents] == [head_before, side_sha]
340+
assert "side.txt" in commit.tree
341+
git_dir = Path(repo.git_dir)
342+
for name in ("MERGE_HEAD", "MERGE_MSG", "MERGE_MODE"):
343+
assert not (git_dir / name).exists()
344+
assert repo.active_branch.name == starting_branch
345+
346+
209347
def test_git_reset(test_repository):
210348
file_path = Path(test_repository.working_dir) / "reset_test.txt"
211349
file_path.write_text("content to reset")

0 commit comments

Comments
 (0)