Skip to content

Commit 2afe47e

Browse files
authored
Merge pull request #5029 from modelcontextprotocol/v2/fix/4998-git-show-output
fix(git): git_show prints git's format, decodes non-UTF-8 patches and shows <rev>:<path>
2 parents b39888c + 8602098 commit 2afe47e

5 files changed

Lines changed: 130 additions & 52 deletions

File tree

‎src/git/README.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -85,11 +85,11 @@ Please note that mcp-server-git is currently in early development. The functiona
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)
8787
11. `git_show`
88-
- Shows the contents of a commit
88+
- Shows the contents of a commit, or of a file or directory at a revision
8989
- Inputs:
9090
- `repo_path` (string): Path to Git repository
91-
- `revision` (string): The revision (commit hash, branch name, tag) to show
92-
- Returns: Contents of the specified commit
91+
- `revision` (string): The revision (commit hash, branch name, tag) or object spec (`HEAD:path/to/file`) to show
92+
- Returns: Contents of the specified commit, file content, or directory listing
9393

9494
12. `git_branch`
9595
- List Git branches

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

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -314,24 +314,41 @@ def git_show(repo: git.Repo, revision: str) -> str:
314314
# even if a malicious ref with that name exists (e.g. via filesystem manipulation)
315315
if revision.startswith("-"):
316316
raise BadName(f"Invalid revision: '{revision}' - cannot start with '-'")
317+
obj = repo.rev_parse(revision)
318+
if isinstance(obj, git.Blob):
319+
return obj.data_stream.read().decode("utf-8", errors="replace")
320+
if isinstance(obj, git.Tree):
321+
return "\n".join(
322+
f"{item.name}/" if isinstance(item, git.Tree) else item.name for item in obj
323+
)
317324
commit = repo.commit(revision)
325+
message = commit.message
326+
if isinstance(message, bytes): # pragma: no cover
327+
# GitPython already decodes the message, falling back to errors="replace".
328+
message = message.decode("utf-8", errors="replace")
329+
# The header follows `git show --date=iso`: the sha, `Name <email>`, an
330+
# ISO date, and the message indented by four spaces.
318331
output = [
319-
f"Commit: {commit.hexsha!r}\n"
320-
f"Author: {commit.author!r}\n"
321-
f"Date: {commit.authored_datetime!r}\n"
322-
f"Message: {commit.message!r}\n"
332+
f"commit {commit.hexsha}\n"
333+
f"Author: {commit.author.name} <{commit.author.email}>\n"
334+
f"Date: {commit.authored_datetime.strftime('%Y-%m-%d %H:%M:%S %z')}\n"
335+
"\n" + "".join(f" {line}\n" for line in message.rstrip("\n").split("\n"))
323336
]
324337
if commit.parents:
325338
parent = commit.parents[0]
326339
diff = parent.diff(commit, create_patch=True)
327340
else:
328341
diff = commit.diff(git.NULL_TREE, create_patch=True)
329342
for d in diff:
330-
output.append(f"\n--- {d.a_path}\n+++ {d.b_path}\n")
343+
# git prints /dev/null for the missing side of an added or deleted file.
344+
a_path = "/dev/null" if d.new_file or d.a_path is None else d.a_path
345+
b_path = "/dev/null" if d.deleted_file or d.b_path is None else d.b_path
346+
output.append(f"\n--- {a_path}\n+++ {b_path}\n")
331347
if d.diff is None:
332348
continue # pragma: no cover # with create_patch=True GitPython always assigns the patch as bytes
333349
if isinstance(d.diff, bytes):
334-
output.append(d.diff.decode("utf-8"))
350+
# A non-UTF-8 file (Latin-1, say) must not fail the whole call.
351+
output.append(d.diff.decode("utf-8", errors="replace"))
335352
else: # pragma: no cover # with create_patch=True GitPython always assigns the patch as bytes
336353
output.append(d.diff)
337354
return "".join(output)
@@ -528,7 +545,7 @@ async def list_tools() -> list[Tool]:
528545
),
529546
Tool(
530547
name=GitTools.SHOW,
531-
description="Shows the contents of a commit",
548+
description="Shows the contents of a commit, or of a file or directory given as <revision>:<path>",
532549
inputSchema=GitShow.model_json_schema(),
533550
annotations=ToolAnnotations(
534551
readOnlyHint=True,

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -319,7 +319,7 @@
319319
},
320320
{
321321
"name": "git_show",
322-
"description": "Shows the contents of a commit",
322+
"description": "Shows the contents of a commit, or of a file or directory given as <revision>:<path>",
323323
"inputSchema": {
324324
"properties": {
325325
"repo_path": {

‎src/git/tests/test_protocol.py‎

Lines changed: 76 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -730,29 +730,23 @@ async def test_git_checkout_rejects_flag_injection(repo: git.Repo):
730730
# --------------------------------------------------------------------------
731731

732732

733-
def without_addresses(text: str) -> str:
734-
"""Mask CPython object addresses (`object at 0x...`)."""
735-
return re.sub(r" at 0x[0-9a-fA-F]+", " at 0x?", text)
736-
737-
738733
def show_text(result: dict[str, Any]) -> str:
739734
assert result["isError"] is False
740-
return without_addresses(result["content"][0]["text"])
735+
return result["content"][0]["text"]
741736

742737

743738
def show_header(commit: git.Commit) -> str:
744-
# git_show formats its header with !r, so the reply carries Python reprs:
745-
# a quoted sha, `<git.Actor ...>`, and a `datetime.datetime(...)` whose
746-
# tzinfo repr includes a memory address. Compared with addresses masked.
747-
return without_addresses(
748-
f"Commit: {commit.hexsha!r}\n"
749-
f"Author: {commit.author!r}\n"
750-
f"Date: {commit.authored_datetime!r}\n"
751-
f"Message: {commit.message!r}\n"
739+
# git_show's header follows `git show --date=iso`.
740+
date = commit.authored_datetime.strftime("%Y-%m-%d %H:%M:%S %z")
741+
lines = str(commit.message).rstrip("\n").split("\n")
742+
return (
743+
f"commit {commit.hexsha}\n"
744+
"Author: Test User <test@example.com>\n"
745+
f"Date: {date}\n"
746+
"\n" + "".join(f" {line}\n" for line in lines)
752747
)
753748

754749

755-
# KNOWN BUG #4998: git_show prints Python reprs (quoted sha, <git.Actor>, datetime with a memory address) instead of git's format; the fix changes this assertion.
756750
async def test_git_show_commit_with_parent(repo: git.Repo):
757751
root = root_of(repo)
758752
(root / "test.txt").write_text(
@@ -769,29 +763,52 @@ async def test_git_show_commit_with_parent(repo: git.Repo):
769763
+ "@@ -1,5 +1,5 @@\n line 1\n line 2\n-line 3\n+SHOWN\n line 4\n line 5\n"
770764
)
771765
text = show_text(result)
772-
assert f"Commit: '{commit.hexsha}'\n" in text
773-
assert 'Author: <git.Actor "Test User <test@example.com>">\n' in text
774-
assert "Date: datetime.datetime(" in text
775-
assert "Message: 'show me'\n" in text
766+
assert text.startswith(
767+
f"commit {commit.hexsha}\nAuthor: Test User <test@example.com>\n"
768+
)
769+
assert re.search(
770+
r"\nDate: \d{4}-\d\d-\d\d \d\d:\d\d:\d\d [+-]\d{4}\n\n show me\n", text
771+
)
772+
773+
774+
async def test_git_show_multiline_message_is_indented(repo: git.Repo):
775+
root = root_of(repo)
776+
(root / "test.txt").write_text("changed\n")
777+
repo.index.add(["test.txt"])
778+
commit = repo.index.commit("subject\n\nbody line\n")
779+
result = await call(None, "git_show", {"repo_path": str(root), "revision": "HEAD"})
780+
text = show_text(result)
781+
assert text.startswith(show_header(commit))
782+
assert "\n\n subject\n \n body line\n\n--- test.txt\n" in text
776783

777784

778-
# KNOWN BUG #4998: git_show prints Python reprs (with a memory address) and "--- None" where git prints /dev/null; the fix changes this assertion.
779785
async def test_git_show_initial_commit_diffs_against_empty_tree(repo: git.Repo):
780786
# With no parent the commit is diffed against NULL_TREE. An added file has
781-
# no a_path, so the header prints Python's `None` where git prints
782-
# `/dev/null`.
787+
# no a_path, so the header prints /dev/null, as git does.
783788
initial = repo.head.commit
784789
result = await call(
785790
None, "git_show", {"repo_path": str(root_of(repo)), "revision": "HEAD"}
786791
)
787792
assert show_text(result) == (
788793
show_header(initial)
789-
+ "\n--- None\n+++ test.txt\n"
794+
+ "\n--- /dev/null\n+++ test.txt\n"
790795
+ "@@ -0,0 +1,5 @@\n+line 1\n+line 2\n+line 3\n+line 4\n+line 5\n"
791796
)
792797

793798

794-
# KNOWN BUG #4998: git_show prints Python reprs (quoted sha, <git.Actor>, datetime with a memory address) instead of git's format; the fix changes this assertion.
799+
async def test_git_show_deleted_file_diffs_to_dev_null(repo: git.Repo):
800+
repo.index.remove(["test.txt"], working_tree=True)
801+
commit = repo.index.commit("delete")
802+
result = await call(
803+
None, "git_show", {"repo_path": str(root_of(repo)), "revision": "HEAD"}
804+
)
805+
assert show_text(result) == (
806+
show_header(commit)
807+
+ "\n--- test.txt\n+++ /dev/null\n"
808+
+ "@@ -1,5 +0,0 @@\n-line 1\n-line 2\n-line 3\n-line 4\n-line 5\n"
809+
)
810+
811+
795812
async def test_git_show_rename_only_commit_has_header_and_no_patch(repo: git.Repo):
796813
# A pure rename yields a diff entry whose patch is empty bytes.
797814
repo.index.move(["test.txt", "renamed.txt"])
@@ -804,7 +821,6 @@ async def test_git_show_rename_only_commit_has_header_and_no_patch(repo: git.Rep
804821
)
805822

806823

807-
# KNOWN BUG #4998: git_show prints Python reprs (quoted sha, <git.Actor>, datetime with a memory address) instead of git's format; the fix changes this assertion.
808824
async def test_git_show_binary_commit(repo: git.Repo):
809825
root = root_of(repo)
810826
(root / "blob.bin").write_bytes(bytes(range(256)))
@@ -813,36 +829,57 @@ async def test_git_show_binary_commit(repo: git.Repo):
813829
result = await call(None, "git_show", {"repo_path": str(root), "revision": "HEAD"})
814830
assert show_text(result) == (
815831
show_header(commit)
816-
+ "\n--- blob.bin\n+++ blob.bin\n"
832+
+ "\n--- /dev/null\n+++ blob.bin\n"
817833
+ "Binary files /dev/null and b/blob.bin differ\n"
818834
)
819835

820836

821-
# KNOWN BUG #4997: git_show decodes the patch as strict UTF-8, so a Latin-1 file fails the whole call; the fix changes this assertion.
822-
async def test_git_show_non_utf8_patch_is_decode_error(repo: git.Repo):
823-
# Characterization: the patch bytes are decoded as strict UTF-8, so a
824-
# Latin-1 text file makes the whole call fail.
837+
async def test_git_show_non_utf8_patch_is_decoded_with_replacement(repo: git.Repo):
838+
# A Latin-1 text file's patch is not valid UTF-8; the undecodable byte
839+
# becomes U+FFFD and the rest of the commit is still shown.
825840
root = root_of(repo)
826841
(root / "latin.txt").write_bytes("caf\xe9\n".encode("latin-1"))
827842
repo.index.add(["latin.txt"])
828-
repo.index.commit("latin-1")
843+
commit = repo.index.commit("latin-1")
829844
result = await call(None, "git_show", {"repo_path": str(root), "revision": "HEAD"})
830-
assert result["isError"] is True
831-
assert "codec can't decode byte 0xe9" in result["content"][0]["text"]
845+
assert show_text(result) == (
846+
show_header(commit)
847+
+ "\n--- /dev/null\n+++ latin.txt\n"
848+
+ "@@ -0,0 +1 @@\n+caf\ufffd\n"
849+
)
832850

833851

834-
# KNOWN BUG #1682: pins current (wrong) behavior; the fix changes this assertion.
835-
async def test_git_show_revision_path_syntax_is_error(repo: git.Repo):
836-
# Pins #1682's current error: `<rev>:<path>` names a blob, not a commit,
837-
# and repo.commit() appends `^0`, so the call fails with this message
838-
# rather than crashing the server.
852+
async def test_git_show_revision_path_shows_the_file(repo: git.Repo):
853+
# `<rev>:<path>` names a blob; git_show returns its content (#1682).
839854
result = await call(
840855
None,
841856
"git_show",
842857
{"repo_path": str(root_of(repo)), "revision": "HEAD:test.txt"},
843858
)
859+
# Compared with the raw bytes: the fixture writes text, so CRLF on Windows.
860+
expected = (root_of(repo) / "test.txt").read_bytes().decode()
861+
assert result == text_result(expected)
862+
863+
864+
async def test_git_show_revision_path_to_a_directory_lists_it(repo: git.Repo):
865+
# `<rev>:<dir>` names a tree; git_show lists it, subdirectories with `/`.
866+
root = root_of(repo)
867+
(root / "logic").mkdir()
868+
(root / "logic" / "infos.py").write_text("print('infos')\n")
869+
repo.index.add(["logic/infos.py"])
870+
repo.index.commit("add infos")
871+
result = await call(None, "git_show", {"repo_path": str(root), "revision": "HEAD:"})
872+
assert result == text_result("logic/\ntest.txt")
873+
874+
875+
async def test_git_show_revision_path_not_found_is_error(repo: git.Repo):
876+
result = await call(
877+
None,
878+
"git_show",
879+
{"repo_path": str(root_of(repo)), "revision": "HEAD:nope.txt"},
880+
)
844881
assert result == text_result(
845-
"\"Blob or Tree named 'test.txt^0' not found\"", is_error=True
882+
"\"Blob or Tree named 'nope.txt' not found\"", is_error=True
846883
)
847884

848885

‎src/git/tests/test_server.py‎

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -461,7 +461,7 @@ def test_git_show(test_repository):
461461

462462
result = git_show(test_repository, commit_sha)
463463

464-
assert "Commit:" in result
464+
assert result.startswith("commit ")
465465
assert "Author:" in result
466466
assert "show test commit" in result
467467
assert "show_test.txt" in result
@@ -472,11 +472,35 @@ def test_git_show_initial_commit(test_repository):
472472

473473
result = git_show(test_repository, initial_commit.hexsha)
474474

475-
assert "Commit:" in result
475+
assert result.startswith("commit ")
476476
assert "initial commit" in result
477477
assert "test.txt" in result
478478

479479

480+
def test_git_show_blob_object_spec(test_repository):
481+
file_path = Path(test_repository.working_dir) / "logic" / "infos.py"
482+
file_path.parent.mkdir()
483+
file_path.write_bytes(b"print('infos')\n")
484+
test_repository.index.add(["logic/infos.py"])
485+
test_repository.index.commit("add infos")
486+
487+
result = git_show(test_repository, "HEAD:logic/infos.py")
488+
489+
assert result == "print('infos')\n"
490+
491+
492+
def test_git_show_tree_object_spec(test_repository):
493+
file_path = Path(test_repository.working_dir) / "logic" / "infos.py"
494+
file_path.parent.mkdir()
495+
file_path.write_text("print('infos')\n")
496+
test_repository.index.add(["logic/infos.py"])
497+
test_repository.index.commit("add infos")
498+
499+
result = git_show(test_repository, "HEAD:")
500+
501+
assert result == "logic/\ntest.txt"
502+
503+
480504
# Tests for validate_repo_path (repository scoping security fix)
481505

482506

0 commit comments

Comments
 (0)