Skip to content

Commit c998563

Browse files
cliffhallclaude
andcommitted
fix(git): report unknown tools and flag-injection rejections as written
call_tool read arguments["repo_path"] before dispatching on the tool name, so an unknown tool called without repo_path failed with the KeyError repr "'repo_path'". It now rejects an unknown name first, with "Unknown tool: <name>" (modelcontextprotocol#4994). The flag-injection guards raised BadName, whose __str__ wraps its argument as a ref name, so the guard's message reached the client as "Ref '<message>' did not resolve to an object". They now raise FlagInjectionError, a BadName subclass that reports its message as written; the rejection itself, and the BadName type test_server.py asserts, are unchanged (modelcontextprotocol#4999). The pinning tests in test_protocol.py now assert the correct messages, and their KNOWN BUG markers are gone. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent 571e2b3 commit c998563

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
@@ -17,6 +17,18 @@
1717
DEFAULT_CONTEXT_LINES = 3
1818

1919

20+
class FlagInjectionError(BadName):
21+
"""A flag-injection guard's rejection of a value starting with '-'.
22+
23+
Still a BadName, but BadName's __str__ wraps its argument as a ref name
24+
("Ref '...' did not resolve to an object"), which garbles the guard's own
25+
message. The message is already complete, so report it as written.
26+
"""
27+
28+
def __str__(self) -> str:
29+
return str(self.args[0])
30+
31+
2032
class GitStatus(BaseModel):
2133
repo_path: str
2234

@@ -135,7 +147,7 @@ def git_diff(
135147
# Defense in depth: reject targets starting with '-' to prevent flag injection,
136148
# even if a malicious ref with that name exists (e.g. via filesystem manipulation)
137149
if target.startswith("-"):
138-
raise BadName(f"Invalid target: '{target}' - cannot start with '-'")
150+
raise FlagInjectionError(f"Invalid target: '{target}' - cannot start with '-'")
139151
repo.rev_parse(target) # Validates target is a real git ref, throws BadName if not
140152
return repo.git.diff(f"--unified={context_lines}", target)
141153

@@ -211,9 +223,13 @@ def git_create_branch(
211223
) -> str:
212224
# Defense in depth: reject names starting with '-' to prevent flag injection
213225
if branch_name.startswith("-"):
214-
raise BadName(f"Invalid branch name: '{branch_name}' - cannot start with '-'")
226+
raise FlagInjectionError(
227+
f"Invalid branch name: '{branch_name}' - cannot start with '-'"
228+
)
215229
if base_branch and base_branch.startswith("-"):
216-
raise BadName(f"Invalid base branch: '{base_branch}' - cannot start with '-'")
230+
raise FlagInjectionError(
231+
f"Invalid base branch: '{base_branch}' - cannot start with '-'"
232+
)
217233
if base_branch:
218234
base = repo.references[base_branch]
219235
else:
@@ -227,7 +243,9 @@ def git_checkout(repo: git.Repo, branch_name: str) -> str:
227243
# Defense in depth: reject branch names starting with '-' to prevent flag injection,
228244
# even if a malicious ref with that name exists (e.g. via filesystem manipulation)
229245
if branch_name.startswith("-"):
230-
raise BadName(f"Invalid branch name: '{branch_name}' - cannot start with '-'")
246+
raise FlagInjectionError(
247+
f"Invalid branch name: '{branch_name}' - cannot start with '-'"
248+
)
231249
repo.rev_parse(
232250
branch_name
233251
) # Validates branch_name is a real git ref, throws BadName if not
@@ -239,7 +257,9 @@ def git_show(repo: git.Repo, revision: str) -> str:
239257
# Defense in depth: reject revisions starting with '-' to prevent flag injection,
240258
# even if a malicious ref with that name exists (e.g. via filesystem manipulation)
241259
if revision.startswith("-"):
242-
raise BadName(f"Invalid revision: '{revision}' - cannot start with '-'")
260+
raise FlagInjectionError(
261+
f"Invalid revision: '{revision}' - cannot start with '-'"
262+
)
243263
commit = repo.commit(revision)
244264
output = [
245265
f"Commit: {commit.hexsha!r}\n"
@@ -292,9 +312,11 @@ def git_branch(
292312
) -> str:
293313
# Defense in depth: reject values starting with '-' to prevent flag injection
294314
if contains and contains.startswith("-"):
295-
raise BadName(f"Invalid contains value: '{contains}' - cannot start with '-'")
315+
raise FlagInjectionError(
316+
f"Invalid contains value: '{contains}' - cannot start with '-'"
317+
)
296318
if not_contains and not_contains.startswith("-"):
297-
raise BadName(
319+
raise FlagInjectionError(
298320
f"Invalid not_contains value: '{not_contains}' - cannot start with '-'"
299321
)
300322

@@ -478,6 +500,11 @@ async def list_tools() -> list[Tool]:
478500

479501
@server.call_tool()
480502
async def call_tool(name: str, arguments: dict) -> list[TextContent]:
503+
# Reject an unknown tool before reading its arguments, so a call
504+
# without repo_path still reports "Unknown tool" (#4994).
505+
if name not in {tool.value for tool in GitTools}:
506+
raise ValueError(f"Unknown tool: {name}")
507+
481508
repo_path = Path(arguments["repo_path"])
482509

483510
# Validate repo_path is within allowed repository
@@ -562,7 +589,8 @@ async def call_tool(name: str, arguments: dict) -> list[TextContent]:
562589
)
563590
return [TextContent(type="text", text=result)]
564591

565-
case _:
592+
# Unreachable: unknown names are rejected before the repo is opened.
593+
case _: # pragma: no cover
566594
raise ValueError(f"Unknown tool: {name}")
567595

568596
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]:
@@ -115,11 +110,12 @@ async def test_unknown_tool_is_error(repo: git.Repo):
115110
) == text_result("Unknown tool: git_nope", is_error=True)
116111

117112

118-
# 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.
119-
async def test_unknown_tool_without_repo_path_reports_the_key_error():
120-
# An unlisted tool skips schema validation, so call_tool's
121-
# `arguments["repo_path"]` raises KeyError and its repr is the message.
122-
assert await call(None, "git_nope", {}) == text_result("'repo_path'", is_error=True)
113+
async def test_unknown_tool_without_repo_path_is_unknown_tool():
114+
# An unlisted tool skips schema validation; the name is checked before
115+
# any argument is read, so a missing repo_path does not mask it.
116+
assert await call(None, "git_nope", {}) == text_result(
117+
"Unknown tool: git_nope", is_error=True
118+
)
123119

124120

125121
async def test_nonexistent_repo_path_error_is_the_bare_path(tmp_path: Path):
@@ -270,7 +266,6 @@ async def test_git_diff_unknown_target_is_error(repo: git.Repo):
270266
) == text_result("Ref 'nope' did not resolve to an object", is_error=True)
271267

272268

273-
# 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.
274269
async def test_git_diff_rejects_flag_injection(repo: git.Repo):
275270
assert await call(
276271
None,
@@ -632,7 +627,6 @@ async def test_git_create_branch_existing_name_at_other_commit_is_error(
632627
assert "already exist" in result["content"][0]["text"]
633628

634629

635-
# 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.
636630
async def test_git_create_branch_rejects_flag_injection(repo: git.Repo):
637631
root = str(root_of(repo))
638632
assert await call(
@@ -692,7 +686,6 @@ async def test_git_checkout_unknown_branch_is_error(repo: git.Repo):
692686
assert repo.active_branch.name == "main"
693687

694688

695-
# 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.
696689
async def test_git_checkout_rejects_flag_injection(repo: git.Repo):
697690
assert await call(
698691
None,
@@ -826,7 +819,6 @@ async def test_git_show_unknown_revision_is_error(repo: git.Repo):
826819
) == text_result("Ref 'nope' did not resolve to an object", is_error=True)
827820

828821

829-
# 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.
830822
async def test_git_show_rejects_flag_injection(repo: git.Repo):
831823
assert await call(
832824
None, "git_show", {"repo_path": str(root_of(repo)), "revision": "--format=x"}
@@ -895,7 +887,6 @@ async def test_git_branch_unknown_type_is_not_an_error(repo: git.Repo):
895887
) == text_result("Invalid branch type: bogus")
896888

897889

898-
# 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.
899890
async def test_git_branch_rejects_flag_injection(repo: git.Repo):
900891
root = str(root_of(repo))
901892
assert await call(

0 commit comments

Comments
 (0)