Skip to content

Commit 0e51df4

Browse files
authored
Merge pull request #5038 from modelcontextprotocol/v2/fix/4999-git-error-messages
fix(git): report unknown tools and flag-injection rejections as written
2 parents 608a365 + 74c0c6f commit 0e51df4

2 files changed

Lines changed: 44 additions & 25 deletions

File tree

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

Lines changed: 36 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,18 @@
2323
DEFAULT_CONTEXT_LINES = 3
2424

2525

26+
class FlagInjectionError(BadName):
27+
"""A flag-injection guard's rejection of a value starting with '-'.
28+
29+
Still a BadName, but BadName's __str__ wraps its argument as a ref name
30+
("Ref '...' did not resolve to an object"), which garbles the guard's own
31+
message. The message is already complete, so report it as written.
32+
"""
33+
34+
def __str__(self) -> str:
35+
return str(self.args[0])
36+
37+
2638
class GitStatus(BaseModel):
2739
repo_path: str
2840

@@ -141,7 +153,7 @@ def git_diff(
141153
# Defense in depth: reject targets starting with '-' to prevent flag injection,
142154
# even if a malicious ref with that name exists (e.g. via filesystem manipulation)
143155
if target.startswith("-"):
144-
raise BadName(f"Invalid target: '{target}' - cannot start with '-'")
156+
raise FlagInjectionError(f"Invalid target: '{target}' - cannot start with '-'")
145157
repo.rev_parse(target) # Validates target is a real git ref, throws BadName if not
146158
return repo.git.diff(f"--unified={context_lines}", target)
147159

@@ -272,9 +284,13 @@ def git_create_branch(
272284
) -> str:
273285
# Defense in depth: reject names starting with '-' to prevent flag injection
274286
if branch_name.startswith("-"):
275-
raise BadName(f"Invalid branch name: '{branch_name}' - cannot start with '-'")
287+
raise FlagInjectionError(
288+
f"Invalid branch name: '{branch_name}' - cannot start with '-'"
289+
)
276290
if base_branch and base_branch.startswith("-"):
277-
raise BadName(f"Invalid base branch: '{base_branch}' - cannot start with '-'")
291+
raise FlagInjectionError(
292+
f"Invalid base branch: '{base_branch}' - cannot start with '-'"
293+
)
278294
if base_branch:
279295
base = repo.references[base_branch]
280296
else:
@@ -296,7 +312,9 @@ def git_checkout(repo: git.Repo, branch_name: str) -> str:
296312
# Defense in depth: reject branch names starting with '-' to prevent flag injection,
297313
# even if a malicious ref with that name exists (e.g. via filesystem manipulation)
298314
if branch_name.startswith("-"):
299-
raise BadName(f"Invalid branch name: '{branch_name}' - cannot start with '-'")
315+
raise FlagInjectionError(
316+
f"Invalid branch name: '{branch_name}' - cannot start with '-'"
317+
)
300318
repo.rev_parse(
301319
branch_name
302320
) # Validates branch_name is a real git ref, throws BadName if not
@@ -313,7 +331,9 @@ def git_show(repo: git.Repo, revision: str) -> str:
313331
# Defense in depth: reject revisions starting with '-' to prevent flag injection,
314332
# even if a malicious ref with that name exists (e.g. via filesystem manipulation)
315333
if revision.startswith("-"):
316-
raise BadName(f"Invalid revision: '{revision}' - cannot start with '-'")
334+
raise FlagInjectionError(
335+
f"Invalid revision: '{revision}' - cannot start with '-'"
336+
)
317337
obj = repo.rev_parse(revision)
318338
if isinstance(obj, git.Blob):
319339
return obj.data_stream.read().decode("utf-8", errors="replace")
@@ -383,9 +403,11 @@ def git_branch(
383403
) -> str:
384404
# Defense in depth: reject values starting with '-' to prevent flag injection
385405
if contains and contains.startswith("-"):
386-
raise BadName(f"Invalid contains value: '{contains}' - cannot start with '-'")
406+
raise FlagInjectionError(
407+
f"Invalid contains value: '{contains}' - cannot start with '-'"
408+
)
387409
if not_contains and not_contains.startswith("-"):
388-
raise BadName(
410+
raise FlagInjectionError(
389411
f"Invalid not_contains value: '{not_contains}' - cannot start with '-'"
390412
)
391413

@@ -579,6 +601,11 @@ async def list_tools() -> list[Tool]:
579601

580602
@server.call_tool()
581603
async def call_tool(name: str, arguments: dict) -> list[TextContent]:
604+
# Reject an unknown tool before reading its arguments, so a call
605+
# without repo_path still reports "Unknown tool" (#4994).
606+
if name not in {tool.value for tool in GitTools}:
607+
raise ValueError(f"Unknown tool: {name}")
608+
582609
repo_path = Path(arguments["repo_path"])
583610

584611
# Validate repo_path is within allowed repository
@@ -663,7 +690,8 @@ async def call_tool(name: str, arguments: dict) -> list[TextContent]:
663690
)
664691
return [TextContent(type="text", text=result)]
665692

666-
case _:
693+
# Unreachable: unknown names are rejected before the repo is opened.
694+
case _: # pragma: no cover
667695
raise ValueError(f"Unknown tool: {name}")
668696

669697
options = server.create_initialization_options()

‎src/git/tests/test_protocol.py‎

Lines changed: 8 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -40,13 +40,8 @@ async def call(
4040

4141

4242
def rejected(message: str) -> dict[str, Any]:
43-
"""The error a flag-injection guard returns over the wire.
44-
45-
The guards raise `BadName(message)`, and BadName's `__str__` wraps its
46-
argument as a ref name, so the client sees the guard's message nested
47-
inside "Ref '...' did not resolve to an object". Characterized as is.
48-
"""
49-
return text_result(f"Ref '{message}' did not resolve to an object", is_error=True)
43+
"""The error a flag-injection guard returns: its message, as written."""
44+
return text_result(message, is_error=True)
5045

5146

5247
def staged_paths(repo: git.Repo) -> set[str]:
@@ -117,11 +112,12 @@ async def test_unknown_tool_is_error(repo: git.Repo):
117112
) == text_result("Unknown tool: git_nope", is_error=True)
118113

119114

120-
# KNOWN BUG #4994: an unknown tool called without repo_path reports the KeyError repr "'repo_path'" instead of "Unknown tool"; the fix changes this assertion.
121-
async def test_unknown_tool_without_repo_path_reports_the_key_error():
122-
# An unlisted tool skips schema validation, so call_tool's
123-
# `arguments["repo_path"]` raises KeyError and its repr is the message.
124-
assert await call(None, "git_nope", {}) == text_result("'repo_path'", is_error=True)
115+
async def test_unknown_tool_without_repo_path_is_unknown_tool():
116+
# An unlisted tool skips schema validation; the name is checked before
117+
# any argument is read, so a missing repo_path does not mask it.
118+
assert await call(None, "git_nope", {}) == text_result(
119+
"Unknown tool: git_nope", is_error=True
120+
)
125121

126122

127123
async def test_nonexistent_repo_path_error_is_the_bare_path(tmp_path: Path):
@@ -284,7 +280,6 @@ async def test_git_diff_unknown_target_is_error(repo: git.Repo):
284280
) == text_result("Ref 'nope' did not resolve to an object", is_error=True)
285281

286282

287-
# KNOWN BUG #4999: the flag-injection guard's message reaches the client wrapped as "Ref '...' did not resolve to an object"; the fix changes this assertion.
288283
async def test_git_diff_rejects_flag_injection(repo: git.Repo):
289284
assert await call(
290285
None,
@@ -656,7 +651,6 @@ async def test_git_create_branch_existing_name_at_other_commit_is_error(
656651
assert "already exist" in result["content"][0]["text"]
657652

658653

659-
# KNOWN BUG #4999: the flag-injection guard's message reaches the client wrapped as "Ref '...' did not resolve to an object"; the fix changes this assertion.
660654
async def test_git_create_branch_rejects_flag_injection(repo: git.Repo):
661655
root = str(root_of(repo))
662656
assert await call(
@@ -716,7 +710,6 @@ async def test_git_checkout_unknown_branch_is_error(repo: git.Repo):
716710
assert repo.active_branch.name == "main"
717711

718712

719-
# KNOWN BUG #4999: the flag-injection guard's message reaches the client wrapped as "Ref '...' did not resolve to an object"; the fix changes this assertion.
720713
async def test_git_checkout_rejects_flag_injection(repo: git.Repo):
721714
assert await call(
722715
None,
@@ -889,7 +882,6 @@ async def test_git_show_unknown_revision_is_error(repo: git.Repo):
889882
) == text_result("Ref 'nope' did not resolve to an object", is_error=True)
890883

891884

892-
# KNOWN BUG #4999: the flag-injection guard's message reaches the client wrapped as "Ref '...' did not resolve to an object"; the fix changes this assertion.
893885
async def test_git_show_rejects_flag_injection(repo: git.Repo):
894886
assert await call(
895887
None, "git_show", {"repo_path": str(root_of(repo)), "revision": "--format=x"}
@@ -954,7 +946,6 @@ async def test_git_branch_unknown_type_is_error(repo: git.Repo):
954946
) == text_result("Invalid branch type: bogus", is_error=True)
955947

956948

957-
# KNOWN BUG #4999: the flag-injection guard's message reaches the client wrapped as "Ref '...' did not resolve to an object"; the fix changes this assertion.
958949
async def test_git_branch_rejects_flag_injection(repo: git.Repo):
959950
root = str(root_of(repo))
960951
assert await call(

0 commit comments

Comments
 (0)