Skip to content

Commit 9b46a58

Browse files
cliffhallclaude
andcommitted
fix(git): accept revision ranges in git_diff
git_diff validated target with rev_parse, which resolves one revision, so main..feature and main...feature were refused although git diff accepts them. A target that does not resolve whole is now split at its first '..' or '...', and each endpoint gets the single-target checks: no leading '-', and it must resolve. An empty endpoint means HEAD. Closes #5194 Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent 446be48 commit 9b46a58

5 files changed

Lines changed: 122 additions & 6 deletions

File tree

‎src/git/README.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,12 +35,12 @@ Please note that mcp-server-git is currently in early development. The functiona
3535
- Returns: Diff output of staged changes
3636

3737
4. `git_diff`
38-
- Shows differences between branches or commits
38+
- Shows differences between branches or commits, or across a revision range
3939
- Inputs:
4040
- `repo_path` (string): Path to Git repository
41-
- `target` (string): Target branch or commit to compare with
41+
- `target` (string): Target branch or commit to compare with, or a revision range: `a..b` (from `a` to `b`) or `a...b` (from the merge base of `a` and `b` to `b`). An omitted endpoint means `HEAD`; each endpoint must resolve and cannot start with `-`
4242
- `context_lines` (number, optional): Number of context lines to show (default: 3)
43-
- Returns: Diff output comparing current state with target
43+
- Returns: Diff output comparing the working tree with target, or the two endpoints of a range with each other
4444

4545
5. `git_commit`
4646
- Records changes to the repository

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

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -117,14 +117,46 @@ def git_diff_staged(repo: git.Repo, context_lines: int = DEFAULT_CONTEXT_LINES)
117117
return _git_text(repo, "diff", f"--unified={context_lines}", "--cached")
118118

119119

120+
def _validate_diff_target(repo: git.Repo, target: str) -> None:
121+
"""Check that git_diff's target is one revision, or a range of two (#5194).
122+
123+
`rev_parse` resolves a single revision, so it rejects `main..feature` and
124+
`main...feature` as a whole although `git diff` accepts them. The target is
125+
tried whole first, because one revision may itself contain `..` (the
126+
commit-message search `:/fix..bug`). Only when that fails is it split at
127+
its first `..` or `...`, and each endpoint is held to the single-revision
128+
rules: no leading '-', and it must resolve. An empty endpoint means HEAD,
129+
as in git; both empty (`..`) is not a range.
130+
"""
131+
try:
132+
repo.rev_parse(target)
133+
return
134+
except (ODBError, ValueError, KeyError):
135+
# BadName (an ODBError) for an unknown name; ValueError and KeyError
136+
# for a spec GitPython cannot apply. Re-raise unless it is a range.
137+
start = target.find("..")
138+
if start == -1 or target in ("..", "..."):
139+
raise
140+
end = start + 3 if target.startswith("...", start) else start + 2
141+
for endpoint in (target[:start], target[end:]):
142+
# The same flag-injection guard the whole target gets in git_diff.
143+
if endpoint.startswith("-"):
144+
raise FlagInjectionError(
145+
f"Invalid target: '{target}' - range endpoint '{endpoint}' "
146+
"cannot start with '-'"
147+
)
148+
repo.rev_parse(endpoint or "HEAD") # BadName names the bad endpoint
149+
150+
120151
def git_diff(
121152
repo: git.Repo, target: str, context_lines: int = DEFAULT_CONTEXT_LINES
122153
) -> str:
123154
# Defense in depth: reject targets starting with '-' to prevent flag injection,
124155
# even if a malicious ref with that name exists (e.g. via filesystem manipulation)
125156
if target.startswith("-"):
126157
raise FlagInjectionError(f"Invalid target: '{target}' - cannot start with '-'")
127-
repo.rev_parse(target) # Validates target is a real git ref, throws BadName if not
158+
# Validates target is a real revision or range, throws BadName if not
159+
_validate_diff_target(repo, target)
128160
return _git_text(repo, "diff", f"--unified={context_lines}", target)
129161

130162

@@ -672,7 +704,7 @@ def diff_staged(repo_path: str, context_lines: int = DEFAULT_CONTEXT_LINES) -> s
672704

673705
@server.tool(
674706
name=GitTools.DIFF.value,
675-
description="Shows differences between branches or commits",
707+
description="Shows differences between branches or commits, or across a revision range (main..feature, main...feature)",
676708
annotations=READ_ONLY,
677709
structured_output=False,
678710
)

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@
8181
},
8282
{
8383
"name": "git_diff",
84-
"description": "Shows differences between branches or commits",
84+
"description": "Shows differences between branches or commits, or across a revision range (main..feature, main...feature)",
8585
"inputSchema": {
8686
"properties": {
8787
"repo_path": {

‎src/git/tests/test_protocol.py‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -316,6 +316,58 @@ async def test_git_diff_rejects_flag_injection(repo: git.Repo):
316316
)
317317

318318

319+
def _diverge(repo: git.Repo) -> None:
320+
"""Give `main` and a new `feature` branch one commit each past their base."""
321+
root = root_of(repo)
322+
repo.git.checkout("-b", "feature")
323+
(root / "feature.txt").write_text("FEATURE\n", newline="\n")
324+
repo.index.add(["feature.txt"])
325+
repo.index.commit("feature commit")
326+
repo.git.checkout("main")
327+
(root / "main.txt").write_text("MAIN\n", newline="\n")
328+
repo.index.add(["main.txt"])
329+
repo.index.commit("main commit")
330+
331+
332+
@pytest.mark.parametrize("target", ["main..feature", "main...feature"])
333+
async def test_git_diff_accepts_revision_range(repo: git.Repo, target: str):
334+
"""A range reaches `git diff` as given (#5194); rev_parse refuses it whole."""
335+
_diverge(repo)
336+
result = await call(
337+
None, "git_diff", {"repo_path": str(root_of(repo)), "target": target}
338+
)
339+
assert result == text_result(
340+
f"Diff with {target}:\n" + repo.git.diff("--unified=3", target)
341+
)
342+
text = result["content"][0]["text"]
343+
assert "+FEATURE" in text
344+
# Two dots compare the tips, so main's own commit shows as removed; three
345+
# dots start from the merge base, so it does not appear at all.
346+
assert ("-MAIN" in text) is (target == "main..feature")
347+
348+
349+
@pytest.mark.parametrize(
350+
("target", "message"),
351+
[
352+
("main..nope", "Ref 'nope' did not resolve to an object"),
353+
("nope...main", "Ref 'nope' did not resolve to an object"),
354+
(
355+
"main..-output=/tmp/evil",
356+
"Invalid target: 'main..-output=/tmp/evil' - range endpoint "
357+
"'-output=/tmp/evil' cannot start with '-'",
358+
),
359+
("..", "Ref '..' did not resolve to an object"),
360+
],
361+
)
362+
async def test_git_diff_range_endpoints_are_validated(
363+
repo: git.Repo, target: str, message: str
364+
):
365+
"""Each endpoint gets the single-target checks: it resolves, no leading '-'."""
366+
assert await call(
367+
None, "git_diff", {"repo_path": str(root_of(repo)), "target": target}
368+
) == tool_error("git_diff", message)
369+
370+
319371
async def test_git_diff_of_non_utf8_content_is_a_normal_result(repo: git.Repo):
320372
"""A Latin-1 file's diff reaches the client with U+FFFD in place of the
321373
undecodable bytes, as git_show's does, and serializes as UTF-8 (#5193)."""

‎src/git/tests/test_server.py‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,38 @@ def test_git_diff(test_repository):
268268
assert "feature changes" in result
269269

270270

271+
def test_git_diff_range_with_omitted_endpoint_means_head(test_repository):
272+
"""`a..` and `..b` default the missing endpoint to HEAD, as git does."""
273+
default_branch = test_repository.active_branch.name
274+
test_repository.git.checkout("-b", "feature-range")
275+
file_path = Path(test_repository.working_dir) / "test.txt"
276+
file_path.write_text("range changes")
277+
test_repository.index.add(["test.txt"])
278+
test_repository.index.commit("range commit")
279+
280+
assert git_diff(test_repository, f"{default_branch}..") == git_diff(
281+
test_repository, f"{default_branch}..HEAD"
282+
)
283+
assert "range changes" in git_diff(test_repository, f"{default_branch}..")
284+
assert git_diff(test_repository, "..HEAD") == ""
285+
286+
287+
def test_git_diff_single_revision_containing_dots_is_not_split(test_repository):
288+
"""A revision that resolves whole is used whole, even with '..' inside it."""
289+
test_repository.index.commit("fix..bug")
290+
291+
# ':/fix..bug' names the commit whose message matches, not a range.
292+
assert git_diff(test_repository, ":/fix..bug") == ""
293+
294+
295+
@pytest.mark.parametrize("target", ["HEAD..feature..x", "...."])
296+
def test_git_diff_rejects_malformed_ranges(test_repository, target):
297+
"""Only the first '..' or '...' splits; anything left must still resolve."""
298+
test_repository.git.branch("feature")
299+
with pytest.raises(BadName):
300+
git_diff(test_repository, target)
301+
302+
271303
# A non-ASCII name, and the octal escape git prints for its first character
272304
# under its default core.quotepath=true (#5129).
273305
NON_ASCII_FILENAME = "日本語.txt"

0 commit comments

Comments
 (0)