"""Characterization tests for mcp-server-git, driven through the protocol. Each test runs the real `serve()` in-process (see `conftest.connect`) and asserts on what a client receives: the wire JSON of the tool list and of each tool result. They pin the server's *current* behavior on `mcp` 1.x, bugs included, as the regression net for the SDK v2 port (#4851). A test that pins a known bug says so and cites the issue (or says "no issue"); fixing the bug means changing that test. """ import json import re import shutil import threading import time from collections.abc import AsyncIterator from contextlib import asynccontextmanager from importlib.metadata import version from pathlib import Path from typing import Any from unittest import mock from unittest.mock import patch import anyio import git import pytest from conftest import connect, make_repo, rmtree, text_result, tool_error, wire from mcp.client.session import ClientRequestContext from mcp.shared.exceptions import MCPError from mcp.shared.memory import create_client_server_memory_streams from mcp.shared.message import SessionMessage from mcp.types import INVALID_PARAMS, JSONRPCRequest, ListRootsResult, Root from pydantic import FileUrl from mcp_server_git.server import serve SNAPSHOTS = Path(__file__).parent / "snapshots" # What the server advertises in either era. MCPServer serves prompt and # resource lists (the git prompts, #5195; no resources), so both appear; # nothing ever changes, so no listChanged. CAPABILITIES = { "prompts": {"listChanged": False}, "resources": {"listChanged": False, "subscribe": False}, "tools": {"listChanged": False}, } def root_of(repo: git.Repo) -> Path: assert repo.working_dir is not None return Path(repo.working_dir) async def call( repository: Path | None, name: str, arguments: dict[str, Any] ) -> dict[str, Any]: """One tool call against a fresh server, as wire JSON.""" async with connect(repository) as session: return wire(await session.call_tool(name, arguments)) def staged_paths(repo: git.Repo) -> set[str]: return set(repo.git.diff("--cached", "--name-only").splitlines()) # -------------------------------------------------------------------------- # Initialization and the tool list # -------------------------------------------------------------------------- async def test_initialize_reports_package_version_as_server_version(repo: git.Repo): # #360: serverInfo.version is this package's version (from pyproject.toml # via the installed metadata), not the `mcp` SDK's. async with connect(root_of(repo), initialize=False) as session: init = wire(await session.initialize()) assert init["serverInfo"] == { "name": "mcp-git", "version": version("mcp-server-git"), } assert version("mcp") != version("mcp-server-git") # MCPServer (#5174) always serves prompts/list and resources/list (the # resource list is empty here), so it advertises both beside tools. assert init["capabilities"] == CAPABILITIES async def test_list_tools_matches_wire_snapshot(): expected = json.loads((SNAPSHOTS / "list_tools.json").read_text()) async with connect(None) as session: tools = wire(await session.list_tools()) assert tools == expected async def test_list_tools_names_in_order(): async with connect(None) as session: tools = wire(await session.list_tools())["tools"] assert [t["name"] for t in tools] == [ "git_status", "git_diff_unstaged", "git_diff_staged", "git_diff", "git_commit", "git_add", "git_reset", "git_log", "git_create_branch", "git_checkout", "git_merge", "git_show", "git_branch", "git_remote", ] # -------------------------------------------------------------------------- # Protocol-level errors common to every tool # -------------------------------------------------------------------------- async def test_missing_required_argument_is_input_validation_error(repo: git.Repo): # #5174: MCPServer validates arguments against the signature-derived # schema and reports pydantic's message, prefixed with the tool name. result = await call(None, "git_status", {}) assert result["isError"] is True text = result["content"][0]["text"] assert text.startswith( "Error executing tool git_status: 1 validation error for statusArguments\n" "repo_path\n Field required" ) async def test_unknown_tool_is_a_json_rpc_invalid_params_error(repo: git.Repo): # #5174: an unknown tool is a protocol error, JSON-RPC -32602, as the spec # requires (server/tools, "Error Handling"), not an isError result. async with connect(None) as session: with pytest.raises(MCPError) as exc: await session.call_tool("git_nope", {"repo_path": str(root_of(repo))}) assert exc.value.error.code == INVALID_PARAMS assert exc.value.error.message == "Unknown tool: git_nope" async def test_unknown_tool_without_repo_path_is_unknown_tool(): # The name is checked before any argument is read, so a missing repo_path # does not mask it (#4994). async with connect(None) as session: with pytest.raises(MCPError) as exc: await session.call_tool("git_nope", {}) assert exc.value.error.code == INVALID_PARAMS assert exc.value.error.message == "Unknown tool: git_nope" async def test_nonexistent_repo_path_error_is_the_bare_path(tmp_path: Path): # NoSuchPathError's message is just the path. missing = tmp_path / "missing" assert await call(None, "git_status", {"repo_path": str(missing)}) == ( tool_error("git_status", str(missing)) ) async def test_non_repository_repo_path_error_is_the_bare_path(tmp_path: Path): # InvalidGitRepositoryError's message is just the path. plain = tmp_path / "plain" plain.mkdir() assert await call(None, "git_status", {"repo_path": str(plain)}) == ( tool_error("git_status", str(plain)) ) async def test_repo_path_subdirectory_is_not_a_repository(repo: git.Repo): # git.Repo() is opened without search_parent_directories, so a directory # inside a working tree is rejected even though git itself accepts it. sub = root_of(repo) / "sub" sub.mkdir() assert await call(None, "git_status", {"repo_path": str(sub)}) == tool_error( "git_status", str(sub) ) # -------------------------------------------------------------------------- # git_status # -------------------------------------------------------------------------- async def test_git_status_clean(repo: git.Repo): assert await call(None, "git_status", {"repo_path": str(root_of(repo))}) == ( text_result( "Repository status:\nOn branch main\nnothing to commit, working tree clean" ) ) async def test_git_status_reports_untracked_and_modified(repo: git.Repo): root = root_of(repo) (root / "test.txt").write_text("changed\n", newline="\n") (root / "new.txt").write_text("new\n", newline="\n") result = await call(None, "git_status", {"repo_path": str(root)}) assert result == text_result(f"Repository status:\n{repo.git.status()}") text = result["content"][0]["text"] assert "modified: test.txt" in text assert "new.txt" in text # -------------------------------------------------------------------------- # git_diff_unstaged / git_diff_staged # -------------------------------------------------------------------------- async def test_git_diff_unstaged(repo: git.Repo): root = root_of(repo) (root / "test.txt").write_text( "line 1\nline 2\nCHANGED\nline 4\nline 5\n", newline="\n" ) result = await call(None, "git_diff_unstaged", {"repo_path": str(root)}) assert result == text_result("Unstaged changes:\n" + repo.git.diff("--unified=3")) assert "-line 3\n+CHANGED" in result["content"][0]["text"] assert " line 1\n" in result["content"][0]["text"] async def test_git_diff_unstaged_honors_context_lines(repo: git.Repo): root = root_of(repo) (root / "test.txt").write_text( "line 1\nline 2\nCHANGED\nline 4\nline 5\n", newline="\n" ) result = await call( None, "git_diff_unstaged", {"repo_path": str(root), "context_lines": 0} ) text = result["content"][0]["text"] assert "@@ -3 +3 @@" in text assert "\n line 1\n" not in text async def test_git_diff_unstaged_empty(repo: git.Repo): assert await call( None, "git_diff_unstaged", {"repo_path": str(root_of(repo))} ) == text_result("Unstaged changes:\n") async def test_git_diff_staged(repo: git.Repo): root = root_of(repo) (root / "test.txt").write_text( "line 1\nline 2\nCHANGED\nline 4\nline 5\n", newline="\n" ) repo.index.add(["test.txt"]) result = await call(None, "git_diff_staged", {"repo_path": str(root)}) assert result == text_result( "Staged changes:\n" + repo.git.diff("--unified=3", "--cached") ) assert "-line 3\n+CHANGED" in result["content"][0]["text"] async def test_git_diff_staged_honors_context_lines(repo: git.Repo): root = root_of(repo) (root / "test.txt").write_text( "line 1\nline 2\nCHANGED\nline 4\nline 5\n", newline="\n" ) repo.index.add(["test.txt"]) result = await call( None, "git_diff_staged", {"repo_path": str(root), "context_lines": 0} ) text = result["content"][0]["text"] assert "@@ -3 +3 @@" in text assert "\n line 2\n" not in text async def test_git_diff_staged_empty(repo: git.Repo): assert await call( None, "git_diff_staged", {"repo_path": str(root_of(repo))} ) == text_result("Staged changes:\n") # -------------------------------------------------------------------------- # git_diff # -------------------------------------------------------------------------- async def test_git_diff_against_branch(repo: git.Repo): root = root_of(repo) repo.git.checkout("-b", "feature") (root / "test.txt").write_text( "line 1\nline 2\nFEATURE\nline 4\nline 5\n", newline="\n" ) repo.index.add(["test.txt"]) repo.index.commit("feature commit") result = await call(None, "git_diff", {"repo_path": str(root), "target": "main"}) assert result == text_result( "Diff with main:\n" + repo.git.diff("--unified=3", "main") ) assert "+FEATURE" in result["content"][0]["text"] async def test_git_diff_honors_context_lines(repo: git.Repo): root = root_of(repo) (root / "test.txt").write_text( "line 1\nline 2\nCHANGED\nline 4\nline 5\n", newline="\n" ) result = await call( None, "git_diff", {"repo_path": str(root), "target": "HEAD", "context_lines": 0}, ) assert result == text_result( "Diff with HEAD:\n" + repo.git.diff("--unified=0", "HEAD") ) async def test_git_diff_unknown_target_is_error(repo: git.Repo): assert await call( None, "git_diff", {"repo_path": str(root_of(repo)), "target": "nope"} ) == tool_error("git_diff", "Ref 'nope' did not resolve to an object") async def test_git_diff_rejects_flag_injection(repo: git.Repo): assert await call( None, "git_diff", {"repo_path": str(root_of(repo)), "target": "--output=/tmp/evil"}, ) == tool_error( "git_diff", "Invalid target: '--output=/tmp/evil' - cannot start with '-'" ) def _diverge(repo: git.Repo) -> None: """Give `main` and a new `feature` branch one commit each past their base.""" root = root_of(repo) repo.git.checkout("-b", "feature") (root / "feature.txt").write_text("FEATURE\n", newline="\n") repo.index.add(["feature.txt"]) repo.index.commit("feature commit") repo.git.checkout("main") (root / "main.txt").write_text("MAIN\n", newline="\n") repo.index.add(["main.txt"]) repo.index.commit("main commit") @pytest.mark.parametrize("target", ["main..feature", "main...feature"]) async def test_git_diff_accepts_revision_range(repo: git.Repo, target: str): """A range reaches `git diff` as given (#5194); rev_parse refuses it whole.""" _diverge(repo) result = await call( None, "git_diff", {"repo_path": str(root_of(repo)), "target": target} ) assert result == text_result( f"Diff with {target}:\n" + repo.git.diff("--unified=3", target) ) text = result["content"][0]["text"] assert "+FEATURE" in text # Two dots compare the tips, so main's own commit shows as removed; three # dots start from the merge base, so it does not appear at all. assert ("-MAIN" in text) is (target == "main..feature") @pytest.mark.parametrize( ("target", "message"), [ ("main..nope", "Ref 'nope' did not resolve to an object"), ("nope...main", "Ref 'nope' did not resolve to an object"), ( "main..-output=/tmp/evil", ( "Invalid target: 'main..-output=/tmp/evil' - range endpoint " "'-output=/tmp/evil' cannot start with '-'" ), ), ("..", "Ref '..' did not resolve to an object"), ], ) async def test_git_diff_range_endpoints_are_validated( repo: git.Repo, target: str, message: str ): """Each endpoint gets the single-target checks: it resolves, no leading '-'.""" assert await call( None, "git_diff", {"repo_path": str(root_of(repo)), "target": target} ) == tool_error("git_diff", message) async def test_git_diff_of_non_utf8_content_is_a_normal_result(repo: git.Repo): """A Latin-1 file's diff reaches the client with U+FFFD in place of the undecodable bytes, as git_show's does, and serializes as UTF-8 (#5193).""" root = root_of(repo) (root / "latin1.txt").write_bytes(b"caf\xe9\n") repo.index.add(["latin1.txt"]) repo.index.commit("add Latin-1 file") (root / "latin1.txt").write_bytes(b"caf\xe9 na\xefve\n") result = await call(None, "git_diff_unstaged", {"repo_path": str(root)}) assert result["isError"] is False text = result["content"][0]["text"] assert text.startswith("Unstaged changes:\ndiff --git a/latin1.txt b/latin1.txt") assert "-caf�\n+caf� na�ve" in text json.dumps(result, ensure_ascii=False).encode("utf-8") # no lone surrogates async def test_git_status_non_ascii_path_round_trips_through_git_add( repo: git.Repo, ): """Under git's default core.quotepath=true the name still comes back as written, so a client can pass it straight to git_add (#5129).""" root = root_of(repo) with repo.config_writer() as config: config.set_value("core", "quotepath", "true") (root / "日本語.txt").write_text("new\n", newline="\n") status = await call(None, "git_status", {"repo_path": str(root)}) assert "\t日本語.txt\n" in status["content"][0]["text"] added = await call( None, "git_add", {"repo_path": str(root), "files": ["日本語.txt"]} ) assert added["isError"] is False # Read the index directly: `staged_paths` lists through git, which would # octal-escape the name under the pinned core.quotepath. assert "日本語.txt" in {path for path, _stage in repo.index.entries} # -------------------------------------------------------------------------- # git_commit # -------------------------------------------------------------------------- async def test_git_commit_records_staged_changes(repo: git.Repo): root = root_of(repo) (root / "new.txt").write_text("new\n", newline="\n") repo.index.add(["new.txt"]) result = await call( None, "git_commit", {"repo_path": str(root), "message": "add new"} ) head = repo.head.commit assert result == text_result( f"Changes committed successfully with hash {head.hexsha}" ) assert head.message == "add new" assert "new.txt" in head.stats.files async def test_git_commit_with_nothing_staged_is_refused(repo: git.Repo): # #4762: with nothing staged, git_commit refuses, as `git commit` does # without --allow-empty, instead of writing an empty commit. root = root_of(repo) (root / "test.txt").write_text("edited but not staged\n", newline="\n") before = repo.head.commit result = await call( None, "git_commit", {"repo_path": str(root), "message": "claims a fix"} ) assert result == tool_error( "git_commit", "No changes staged for commit. Use git_add to stage changes first; " "git_status shows what is currently staged.", ) assert repo.head.commit == before assert repo.is_dirty() # -------------------------------------------------------------------------- # git_add # -------------------------------------------------------------------------- async def test_git_add_specific_files(repo: git.Repo): root = root_of(repo) (root / "a.txt").write_text("a\n", newline="\n") (root / "b.txt").write_text("b\n", newline="\n") result = await call(None, "git_add", {"repo_path": str(root), "files": ["a.txt"]}) assert result == text_result("Files staged successfully") assert staged_paths(repo) == {"a.txt"} async def test_git_add_dot_stages_everything(repo: git.Repo): root = root_of(repo) (root / "a.txt").write_text("a\n", newline="\n") (root / "b.txt").write_text("b\n", newline="\n") result = await call(None, "git_add", {"repo_path": str(root), "files": ["."]}) assert result == text_result("Files staged successfully") assert staged_paths(repo) == {"a.txt", "b.txt"} async def test_git_add_dot_never_stages_git_dir(repo: git.Repo): # Regression guard for #628: `git add .` must not stage `.git` itself. root = root_of(repo) (root / "a.txt").write_text("a\n", newline="\n") await call(None, "git_add", {"repo_path": str(root), "files": ["."]}) entries = [str(path) for path, _stage in repo.index.entries] assert not any(p == ".git" or p.startswith(".git/") for p in entries) assert "a.txt" in entries async def test_git_add_absolute_path_inside_repository(repo: git.Repo): root = root_of(repo) (root / "a.txt").write_text("a\n", newline="\n") result = await call( None, "git_add", {"repo_path": str(root), "files": [str(root / "a.txt")]} ) assert result == text_result("Files staged successfully") assert staged_paths(repo) == {"a.txt"} async def test_git_add_file_starting_with_dash_is_a_path(repo: git.Repo): # `--` separates the pathspec, so a dash-named file is staged, not parsed # as an option. root = root_of(repo) (root / "-n").write_text("dash\n", newline="\n") result = await call(None, "git_add", {"repo_path": str(root), "files": ["-n"]}) assert result == text_result("Files staged successfully") assert staged_paths(repo) == {"-n"} async def test_git_add_empty_list_is_rejected(repo: git.Repo): # #4763: `files: []` would run `git add --`, a no-op. The schema's # minItems makes MCPServer reject it before the tool runs. root = root_of(repo) (root / "test.txt").write_text("edited\n", newline="\n") result = await call(None, "git_add", {"repo_path": str(root), "files": []}) assert result["isError"] is True assert result["content"][0]["text"].startswith( "Error executing tool git_add: 1 validation error for addArguments\n" "files\n List should have at least 1 item after validation, not 0" ) assert staged_paths(repo) == set() async def test_git_add_dot_on_clean_tree_reports_nothing_staged(repo: git.Repo): # #4763: nothing to stage, and the result says so. result = await call( None, "git_add", {"repo_path": str(root_of(repo)), "files": ["."]} ) assert result == text_result( "No changes were staged: the given paths had nothing new to stage. " "git_status shows what is modified or untracked." ) assert staged_paths(repo) == set() async def test_git_add_nonexistent_file_is_git_error(repo: git.Repo): result = await call( None, "git_add", {"repo_path": str(root_of(repo)), "files": ["nope.txt"]} ) assert result["isError"] is True text = result["content"][0]["text"] assert "cmdline: git add -- nope.txt" in text assert "pathspec 'nope.txt' did not match any files" in text async def test_git_add_rejects_relative_traversal(repo: git.Repo): # CVE-2026-27735: a path escaping the working tree is refused before git # runs. root = root_of(repo) (root.parent / "outside.txt").write_text("secret\n", newline="\n") result = await call( None, "git_add", {"repo_path": str(root), "files": ["../outside.txt"]} ) assert result == tool_error( "git_add", f"Path '../outside.txt' is outside the repository '{root.resolve()}'" ) assert staged_paths(repo) == set() async def test_git_add_rejects_absolute_path_outside(repo: git.Repo): root = root_of(repo) outside = root.parent / "outside.txt" outside.write_text("secret\n", newline="\n") result = await call( None, "git_add", {"repo_path": str(root), "files": [str(outside)]} ) assert result == tool_error( "git_add", f"Path '{outside}' is outside the repository '{root.resolve()}'" ) async def test_git_add_rejects_symlink_out_of_repository(repo: git.Repo): root = root_of(repo) outside = root.parent / "outside.txt" outside.write_text("secret\n", newline="\n") (root / "link.txt").symlink_to(outside) result = await call( None, "git_add", {"repo_path": str(root), "files": ["link.txt"]} ) assert result == tool_error( "git_add", f"Path 'link.txt' is outside the repository '{root.resolve()}'" ) async def test_git_add_unresolvable_path_is_invalid_path(repo: git.Repo): # Path.resolve() raising (a symlink loop on some Pythons, an OS error) # becomes "Invalid path". Simulated so the test does not depend on which # Python versions raise for a loop. root = root_of(repo) real_resolve = Path.resolve def resolve(self: Path, strict: bool = False) -> Path: if self.name == "unresolvable": raise OSError("simulated") return real_resolve(self, strict) with mock.patch.object(Path, "resolve", resolve): result = await call( None, "git_add", {"repo_path": str(root), "files": ["unresolvable"]} ) assert result == tool_error("git_add", "Invalid path: 'unresolvable'") # -------------------------------------------------------------------------- # git_reset # -------------------------------------------------------------------------- async def test_git_reset_unstages_everything(repo: git.Repo): root = root_of(repo) (root / "a.txt").write_text("a\n", newline="\n") (root / "test.txt").write_text("edited\n", newline="\n") repo.index.add(["a.txt", "test.txt"]) assert staged_paths(repo) == {"a.txt", "test.txt"} result = await call(None, "git_reset", {"repo_path": str(root)}) assert result == text_result("All staged changes reset") assert staged_paths(repo) == set() # The working tree is untouched. assert (root / "test.txt").read_text() == "edited\n" # -------------------------------------------------------------------------- # git_log # -------------------------------------------------------------------------- def log_entry(commit: git.Commit) -> str: return ( f"Commit: {commit.hexsha}\n" f"Author: {commit.author}\n" f"Date: {commit.authored_datetime}\n" f"Message: {commit.message}\n" ) def add_commits(repo: git.Repo, n: int) -> list[git.Commit]: root = root_of(repo) commits = [] for i in range(n): (root / f"f{i}.txt").write_text(f"{i}\n", newline="\n") repo.index.add([f"f{i}.txt"]) commits.append(repo.index.commit(f"commit {i}\n\nbody {i}")) return commits async def test_git_log_default(repo: git.Repo): commits = add_commits(repo, 2) initial = repo.head.commit.parents[0].parents[0] result = await call(None, "git_log", {"repo_path": str(root_of(repo))}) assert result == text_result( "Commit history:\n" + "\n".join(log_entry(c) for c in [commits[1], commits[0], initial]) ) text = result["content"][0]["text"] assert "Author: Test User\n" in text assert "Message: commit 1\n\nbody 1\n" in text async def test_git_log_max_count(repo: git.Repo): commits = add_commits(repo, 3) result = await call( None, "git_log", {"repo_path": str(root_of(repo)), "max_count": 1} ) assert result == text_result("Commit history:\n" + log_entry(commits[2])) @pytest.mark.parametrize("max_count", [-1, 0]) async def test_git_log_rejects_non_positive_max_count(repo: git.Repo, max_count: int): # #5214: git reads a negative -n as "no limit" and 0 as nothing, so either # used to succeed with the wrong commits. The schema's minimum makes # MCPServer reject them before the tool runs. add_commits(repo, 3) result = await call( None, "git_log", {"repo_path": str(root_of(repo)), "max_count": max_count} ) assert result["isError"] is True assert result["content"][0]["text"].startswith( "Error executing tool git_log: 1 validation error for logArguments\n" "max_count\n Input should be greater than or equal to 1" ) async def test_git_log_max_count_beyond_history_returns_all(repo: git.Repo): # #5214: the bound is a minimum only; a count above the history's length # still returns every commit rather than an error. commits = add_commits(repo, 2) initial = repo.head.commit.parents[0].parents[0] result = await call( None, "git_log", {"repo_path": str(root_of(repo)), "max_count": 100} ) assert result == text_result( "Commit history:\n" + "\n".join(log_entry(c) for c in [commits[1], commits[0], initial]) ) async def test_git_log_timestamps_filter(repo: git.Repo): root = str(root_of(repo)) future = await call( None, "git_log", {"repo_path": root, "start_timestamp": "2099-01-01"} ) assert future == text_result("Commit history:\n") past = await call( None, "git_log", {"repo_path": root, "end_timestamp": "2000-01-01"} ) assert past == text_result("Commit history:\n") both = await call( None, "git_log", { "repo_path": root, "start_timestamp": "2000-01-01", "end_timestamp": "2099-01-01", }, ) assert both == text_result("Commit history:\n" + log_entry(repo.head.commit)) async def test_git_log_rejects_timestamp_flag_injection(repo: git.Repo): root = str(root_of(repo)) assert await call( None, "git_log", {"repo_path": root, "start_timestamp": "--all"} ) == tool_error( "git_log", "Invalid start_timestamp: '--all' - cannot start with '-'" ) assert await call( None, "git_log", {"repo_path": root, "end_timestamp": "--all"} ) == tool_error("git_log", "Invalid end_timestamp: '--all' - cannot start with '-'") # -------------------------------------------------------------------------- # git_create_branch # -------------------------------------------------------------------------- async def test_git_create_branch_from_active_branch(repo: git.Repo): root = root_of(repo) result = await call( None, "git_create_branch", {"repo_path": str(root), "branch_name": "feat"} ) assert result == text_result("Created branch 'feat' from 'main'") assert repo.heads["feat"].commit == repo.heads["main"].commit # Creating a branch does not switch to it. assert repo.active_branch.name == "main" async def test_git_create_branch_from_base_branch(repo: git.Repo): root = root_of(repo) repo.git.checkout("-b", "base") add_commits(repo, 1) repo.git.checkout("main") result = await call( None, "git_create_branch", {"repo_path": str(root), "branch_name": "derived", "base_branch": "base"}, ) assert result == text_result("Created branch 'derived' from 'base'") assert repo.heads["derived"].commit == repo.heads["base"].commit async def test_git_create_branch_unknown_base_is_error(repo: git.Repo): assert await call( None, "git_create_branch", {"repo_path": str(root_of(repo)), "branch_name": "x", "base_branch": "nope"}, ) == tool_error("git_create_branch", "Unknown base branch or commit: 'nope'") async def test_git_create_branch_existing_name_at_same_commit_is_error( repo: git.Repo, ): # GitPython's create_head accepts an existing branch that already points # at the base commit; the server rejects it rather than report a creation. assert await call( None, "git_create_branch", {"repo_path": str(root_of(repo)), "branch_name": "main"}, ) == tool_error( "git_create_branch", "Cannot create branch 'main': refs/heads/main already exists", ) async def test_git_create_branch_name_matching_list_attribute(repo: git.Repo): # The existence check compares head names, so a new branch named like an # attribute of GitPython's IterableList ("append") is still created. assert await call( None, "git_create_branch", {"repo_path": str(root_of(repo)), "branch_name": "append"}, ) == text_result("Created branch 'append' from 'main'") assert repo.commit("refs/heads/append") == repo.heads["main"].commit async def test_git_create_branch_existing_name_at_other_commit_is_error( repo: git.Repo, ): repo.git.branch("old") add_commits(repo, 1) result = await call( None, "git_create_branch", {"repo_path": str(root_of(repo)), "branch_name": "old"}, ) assert result["isError"] is True assert "refs/heads/old" in result["content"][0]["text"] assert "already exist" in result["content"][0]["text"] async def test_git_create_branch_on_detached_head_uses_current_commit( repo: git.Repo, ): # With no base_branch the base is the active branch, which a detached HEAD # does not have (GitPython would raise TypeError, a crash under MCPServer). # #5192: the tool branches from the current commit and names it. head = repo.head.commit repo.git.checkout("--detach") result = await call( None, "git_create_branch", {"repo_path": str(root_of(repo)), "branch_name": "x"}, ) assert result == text_result(f"Created branch 'x' from commit {head.hexsha[:7]}") assert repo.heads["x"].commit == head assert repo.head.is_detached async def test_git_create_branch_from_commit_sha(repo: git.Repo): first = repo.head.commit add_commits(repo, 1) result = await call( None, "git_create_branch", { "repo_path": str(root_of(repo)), "branch_name": "x", "base_branch": first.hexsha, }, ) assert result == text_result(f"Created branch 'x' from commit {first.hexsha[:7]}") assert repo.heads["x"].commit == first async def test_an_unanticipated_exception_is_reported_generically(repo: git.Repo): # #5174: only the failures listed in ANTICIPATED_ERRORS reach the model # with their message. Anything else is a crash: MCPServer withholds its # text and logs the traceback. with mock.patch( "mcp_server_git.server.git_status", side_effect=RuntimeError("internal") ): result = await call(None, "git_status", {"repo_path": str(root_of(repo))}) assert result == text_result("Error executing tool git_status", is_error=True) async def test_overlapping_tool_calls_run_one_at_a_time(repo: git.Repo): # #5175 review: MCPServer runs a synchronous tool in a worker thread, so # two calls can overlap, and a git operation is a check and then a change # on a shared index. The server runs one tool call at a time. active = 0 peak = 0 guard = threading.Lock() def slow_status(_repo: git.Repo) -> str: nonlocal active, peak with guard: active += 1 peak = max(peak, active) time.sleep(0.2) with guard: active -= 1 return "clean" root = str(root_of(repo)) with mock.patch("mcp_server_git.server.git_status", side_effect=slow_status): async with connect(None) as session, anyio.create_task_group() as tg: for _ in range(3): tg.start_soon(session.call_tool, "git_status", {"repo_path": root}) assert peak == 1 async def test_git_create_branch_rejects_flag_injection(repo: git.Repo): root = str(root_of(repo)) assert await call( None, "git_create_branch", {"repo_path": root, "branch_name": "-f"} ) == tool_error( "git_create_branch", "Invalid branch name: '-f' - cannot start with '-'" ) assert await call( None, "git_create_branch", {"repo_path": root, "branch_name": "x", "base_branch": "--track"}, ) == tool_error( "git_create_branch", "Invalid base branch: '--track' - cannot start with '-'" ) # -------------------------------------------------------------------------- # git_checkout # -------------------------------------------------------------------------- async def test_git_checkout_branch(repo: git.Repo): repo.git.branch("feature") result = await call( None, "git_checkout", {"repo_path": str(root_of(repo)), "branch_name": "feature"}, ) assert result == text_result("Switched to branch 'feature'") assert repo.active_branch.name == "feature" @pytest.mark.parametrize("revision", ["sha", "tag", "HEAD~1", "refs/heads/feature"]) async def test_git_checkout_non_branch_reports_detached_head( repo: git.Repo, revision: str ): # #4804: any revision rev_parse accepts is checked out, detaching HEAD, and # the reply says so with the short sha instead of claiming a branch switch. add_commits(repo, 1) repo.git.branch("feature") repo.create_tag("v1", ref="HEAD~1") name = { "sha": repo.head.commit.hexsha[:7], "tag": "v1", }.get(revision, revision) target = repo.commit(name).hexsha result = await call( None, "git_checkout", {"repo_path": str(root_of(repo)), "branch_name": name} ) assert repo.head.is_detached assert repo.head.commit.hexsha == target assert result == text_result(f"HEAD is now detached at {target[:7]}") async def test_git_checkout_unknown_branch_is_error(repo: git.Repo): assert await call( None, "git_checkout", {"repo_path": str(root_of(repo)), "branch_name": "nope"}, ) == tool_error("git_checkout", "Ref 'nope' did not resolve to an object") assert repo.active_branch.name == "main" async def test_git_checkout_rejects_flag_injection(repo: git.Repo): assert await call( None, "git_checkout", {"repo_path": str(root_of(repo)), "branch_name": "--orphan=evil"}, ) == tool_error( "git_checkout", "Invalid branch name: '--orphan=evil' - cannot start with '-'" ) # -------------------------------------------------------------------------- # git_show # -------------------------------------------------------------------------- def show_text(result: dict[str, Any]) -> str: assert result["isError"] is False return result["content"][0]["text"] def show_header(commit: git.Commit) -> str: # git_show's header follows `git show --date=iso`. date = commit.authored_datetime.strftime("%Y-%m-%d %H:%M:%S %z") lines = str(commit.message).rstrip("\n").split("\n") return ( f"commit {commit.hexsha}\n" "Author: Test User \n" f"Date: {date}\n" "\n" + "".join(f" {line}\n" for line in lines) ) async def test_git_show_commit_with_parent(repo: git.Repo): root = root_of(repo) (root / "test.txt").write_text( "line 1\nline 2\nSHOWN\nline 4\nline 5\n", newline="\n" ) repo.index.add(["test.txt"]) commit = repo.index.commit("show me") result = await call( None, "git_show", {"repo_path": str(root), "revision": commit.hexsha} ) assert show_text(result) == ( show_header(commit) + "\n--- a/test.txt\n+++ b/test.txt\n" + "@@ -1,5 +1,5 @@\n line 1\n line 2\n-line 3\n+SHOWN\n line 4\n line 5\n" ) text = show_text(result) assert text.startswith( f"commit {commit.hexsha}\nAuthor: Test User \n" ) assert re.search( r"\nDate: \d{4}-\d\d-\d\d \d\d:\d\d:\d\d [+-]\d{4}\n\n show me\n", text ) async def test_git_show_multiline_message_is_indented(repo: git.Repo): root = root_of(repo) (root / "test.txt").write_text("changed\n") repo.index.add(["test.txt"]) commit = repo.index.commit("subject\n\nbody line\n") result = await call(None, "git_show", {"repo_path": str(root), "revision": "HEAD"}) text = show_text(result) assert text.startswith(show_header(commit)) assert "\n\n subject\n \n body line\n\n--- a/test.txt\n" in text async def test_git_show_initial_commit_diffs_against_empty_tree(repo: git.Repo): # With no parent the commit is diffed against NULL_TREE. An added file has # no a_path, so the header prints /dev/null, as git does. initial = repo.head.commit result = await call( None, "git_show", {"repo_path": str(root_of(repo)), "revision": "HEAD"} ) assert show_text(result) == ( show_header(initial) + "\n--- /dev/null\n+++ b/test.txt\n" + "@@ -0,0 +1,5 @@\n+line 1\n+line 2\n+line 3\n+line 4\n+line 5\n" ) async def test_git_show_deleted_file_diffs_to_dev_null(repo: git.Repo): repo.index.remove(["test.txt"], working_tree=True) commit = repo.index.commit("delete") result = await call( None, "git_show", {"repo_path": str(root_of(repo)), "revision": "HEAD"} ) assert show_text(result) == ( show_header(commit) + "\n--- a/test.txt\n+++ /dev/null\n" + "@@ -1,5 +0,0 @@\n-line 1\n-line 2\n-line 3\n-line 4\n-line 5\n" ) async def test_git_show_patch_applies_with_git_apply(repo: git.Repo): # The a/ and b/ prefixes make the output a patch `git apply` accepts as # is: without them its default -p1 strips `logic/` from a nested path # (#5107). Reverse-applying the commit's own patch must check clean. root = root_of(repo) (root / "logic").mkdir() (root / "logic" / "a.py").write_bytes(b"x = 1\n") repo.index.add(["logic/a.py"]) repo.index.commit("add logic/a.py") (root / "logic" / "a.py").write_bytes(b"x = 2\n") repo.index.add(["logic/a.py"]) commit = repo.index.commit("change logic/a.py") result = await call(None, "git_show", {"repo_path": str(root), "revision": "HEAD"}) text = show_text(result) assert text == ( show_header(commit) + "\n--- a/logic/a.py\n+++ b/logic/a.py\n" + "@@ -1 +1 @@\n-x = 1\n+x = 2\n" ) patch_file = root.parent / "show.patch" patch_file.write_bytes(text.encode()) repo.git.apply("-R", "--check", str(patch_file)) async def test_git_show_rename_only_commit_has_header_and_no_patch(repo: git.Repo): # A pure rename yields a diff entry whose patch is empty bytes. repo.index.move(["test.txt", "renamed.txt"]) commit = repo.index.commit("rename only") result = await call( None, "git_show", {"repo_path": str(root_of(repo)), "revision": "HEAD"} ) assert show_text(result) == ( show_header(commit) + "\n--- a/test.txt\n+++ b/renamed.txt\n" ) async def test_git_show_binary_commit(repo: git.Repo): root = root_of(repo) (root / "blob.bin").write_bytes(bytes(range(256))) repo.index.add(["blob.bin"]) commit = repo.index.commit("binary") result = await call(None, "git_show", {"repo_path": str(root), "revision": "HEAD"}) assert show_text(result) == ( show_header(commit) + "\n--- /dev/null\n+++ b/blob.bin\n" + "Binary files /dev/null and b/blob.bin differ\n" ) async def test_git_show_non_utf8_patch_is_decoded_with_replacement(repo: git.Repo): # A Latin-1 text file's patch is not valid UTF-8; the undecodable byte # becomes U+FFFD and the rest of the commit is still shown. root = root_of(repo) (root / "latin.txt").write_bytes("caf\xe9\n".encode("latin-1")) repo.index.add(["latin.txt"]) commit = repo.index.commit("latin-1") result = await call(None, "git_show", {"repo_path": str(root), "revision": "HEAD"}) assert show_text(result) == ( show_header(commit) + "\n--- /dev/null\n+++ b/latin.txt\n" + "@@ -0,0 +1 @@\n+caf\ufffd\n" ) async def test_git_show_revision_path_shows_the_file(repo: git.Repo): # `:` names a blob; git_show returns its content (#1682). result = await call( None, "git_show", {"repo_path": str(root_of(repo)), "revision": "HEAD:test.txt"}, ) # Compared with the raw bytes: the fixture writes text, so CRLF on Windows. expected = (root_of(repo) / "test.txt").read_bytes().decode() assert result == text_result(expected) async def test_git_show_revision_path_to_a_directory_lists_it(repo: git.Repo): # `:` names a tree; git_show lists it, subdirectories with `/`. root = root_of(repo) (root / "logic").mkdir() (root / "logic" / "infos.py").write_text("print('infos')\n") repo.index.add(["logic/infos.py"]) repo.index.commit("add infos") result = await call(None, "git_show", {"repo_path": str(root), "revision": "HEAD:"}) assert result == text_result("logic/\ntest.txt") async def test_git_show_revision_path_not_found_is_error(repo: git.Repo): result = await call( None, "git_show", {"repo_path": str(root_of(repo)), "revision": "HEAD:nope.txt"}, ) assert result == tool_error( "git_show", "\"Blob or Tree named 'nope.txt' not found\"" ) async def test_git_show_unknown_revision_is_error(repo: git.Repo): assert await call( None, "git_show", {"repo_path": str(root_of(repo)), "revision": "nope"} ) == tool_error("git_show", "Ref 'nope' did not resolve to an object") async def test_git_show_rejects_flag_injection(repo: git.Repo): assert await call( None, "git_show", {"repo_path": str(root_of(repo)), "revision": "--format=x"} ) == tool_error( "git_show", "Invalid revision: '--format=x' - cannot start with '-'" ) # -------------------------------------------------------------------------- # git_branch # -------------------------------------------------------------------------- async def test_git_branch_local(repo: git.Repo): repo.git.branch("feature") assert await call( None, "git_branch", {"repo_path": str(root_of(repo)), "branch_type": "local"} ) == text_result(" feature\n* main") async def test_git_branch_remote_and_all(tmp_path: Path, repo: git.Repo): clone = repo.clone(str(tmp_path / "clone")) try: clone.git.branch("local-only") clone_root = root_of(clone) remote = await call( None, "git_branch", {"repo_path": str(clone_root), "branch_type": "remote"} ) assert remote == text_result(clone.git.branch("-r")) assert "origin/main" in remote["content"][0]["text"] assert "local-only" not in remote["content"][0]["text"] everything = await call( None, "git_branch", {"repo_path": str(clone_root), "branch_type": "all"} ) text = everything["content"][0]["text"] assert "local-only" in text assert "remotes/origin/main" in text finally: clone.close() async def test_git_branch_contains_and_not_contains(repo: git.Repo): root = str(root_of(repo)) repo.git.checkout("-b", "feature") commit = add_commits(repo, 1)[0] repo.git.checkout("main") contains = await call( None, "git_branch", {"repo_path": root, "branch_type": "local", "contains": commit.hexsha}, ) assert contains == text_result(" feature") not_contains = await call( None, "git_branch", {"repo_path": root, "branch_type": "local", "not_contains": commit.hexsha}, ) assert not_contains == text_result("* main") async def test_git_branch_unknown_type_is_error(repo: git.Repo): assert await call( None, "git_branch", {"repo_path": str(root_of(repo)), "branch_type": "bogus"} ) == tool_error("git_branch", "Invalid branch type: bogus") async def test_git_branch_rejects_flag_injection(repo: git.Repo): root = str(root_of(repo)) assert await call( None, "git_branch", {"repo_path": root, "branch_type": "local", "contains": "--x"}, ) == tool_error( "git_branch", "Invalid contains value: '--x' - cannot start with '-'" ) assert await call( None, "git_branch", {"repo_path": root, "branch_type": "local", "not_contains": "--x"}, ) == tool_error( "git_branch", "Invalid not_contains value: '--x' - cannot start with '-'" ) # -------------------------------------------------------------------------- # Repository restriction (--repository) and the #4550 concerns # -------------------------------------------------------------------------- def outside_error(repo_path: Path | str, allowed: Path) -> dict[str, Any]: return tool_error( "git_status", f"Repository path '{repo_path}' is outside the allowed repository '{allowed}'", ) async def test_without_repository_any_repository_is_reachable(tmp_path: Path): # Pins #4550: with no --repository, validate_repo_path is a no-op and every # tool reaches any repository on the filesystem. Restricting this changes # this test. first = make_repo(tmp_path / "first") second = make_repo(tmp_path / "second") try: async with connect(None) as session: for r in (first, second): result = wire( await session.call_tool( "git_status", {"repo_path": str(root_of(r))} ) ) assert result["isError"] is False finally: first.close() second.close() async def test_restricted_server_serves_its_repository(repo: git.Repo): root = root_of(repo) assert (await call(root, "git_status", {"repo_path": str(root)}))[ "isError" ] is False async def test_restricted_server_rejects_other_repository( tmp_path: Path, repo: git.Repo ): root = root_of(repo) other = make_repo(tmp_path / "other") try: assert await call( root, "git_status", {"repo_path": str(root_of(other))} ) == outside_error(root_of(other), root) finally: other.close() async def test_restricted_server_rejects_sibling_with_shared_prefix( tmp_path: Path, repo: git.Repo ): # `/x/repo-evil` starts with the string `/x/repo` but is not inside it; the # check compares path components, not string prefixes. root = root_of(repo) evil = make_repo(tmp_path / "repo-evil") try: assert await call( root, "git_status", {"repo_path": str(root_of(evil))} ) == outside_error(root_of(evil), root) finally: evil.close() async def test_restricted_server_rejects_dotdot_traversal( tmp_path: Path, repo: git.Repo ): root = root_of(repo) other = make_repo(tmp_path / "other") try: sneaky = f"{root}/../other" # The server echoes the path as `Path(repo_path)` renders it: unchanged # on POSIX, with backslash separators on Windows. assert await call(root, "git_status", {"repo_path": sneaky}) == outside_error( Path(sneaky), root ) finally: other.close() async def test_restricted_server_rejects_symlink_escape(tmp_path: Path, repo: git.Repo): root = root_of(repo) other = make_repo(tmp_path / "other") link = root / "escape" link.symlink_to(root_of(other)) try: assert await call( root, "git_status", {"repo_path": str(link)} ) == outside_error(link, root) finally: other.close() def uses_outside(result: dict[str, Any], used: Path, allowed: Path) -> bool: """The result is the error for a repository git opened outside `allowed`.""" text = result["content"][0]["text"] return ( result["isError"] is True and f"uses '{used}'" in text and f"which is outside the allowed repository '{allowed}'" in text ) async def test_restricted_server_rejects_gitdir_file_pointing_outside( tmp_path: Path, repo: git.Repo ): # A `.git` file inside the allowed repository passes the path check, but # git follows its `gitdir:` line to the repository it names. Neither a read # nor a write may reach that repository. root = root_of(repo) other = make_repo(tmp_path / "other") nested = root / "nested" nested.mkdir() (nested / ".git").write_text(f"gitdir: {other.git_dir}\n") try: shown = await call( root, "git_show", {"repo_path": str(nested), "revision": "HEAD"} ) assert uses_outside(shown, Path(other.git_dir), root) branched = await call( root, "git_create_branch", {"repo_path": str(nested), "branch_name": "escaped"}, ) assert uses_outside(branched, Path(other.git_dir), root) assert "escaped" not in {head.name for head in other.heads} finally: other.close() async def test_restricted_server_rejects_commondir_pointing_outside( tmp_path: Path, repo: git.Repo ): # A worktree-style git directory inside the allowed repository whose # `commondir` names another repository's `.git` reads that repository's # objects and refs. root = root_of(repo) other = make_repo(tmp_path / "other") other.git.worktree("add", str(tmp_path / "other-wt")) admin = root / "admin" shutil.copytree( Path(other.git_dir) / "worktrees" / "other-wt", admin, ignore=shutil.ignore_patterns("*.ipc"), # git's fsmonitor socket ) (admin / "commondir").write_text(f"{other.git_dir}\n") nested = root / "nested" nested.mkdir() (nested / ".git").write_text(f"gitdir: {admin}\n") try: result = await call(root, "git_log", {"repo_path": str(nested)}) assert uses_outside(result, Path(other.git_dir), root) finally: other.close() async def test_restricted_server_rejects_worktree_config_pointing_outside( tmp_path: Path, repo: git.Repo ): # `core.worktree` in a nested repository moves its working tree, and every # checkout or add with it, to wherever the setting names. root = root_of(repo) elsewhere = tmp_path / "elsewhere" elsewhere.mkdir() nested = make_repo(root / "nested") with nested.config_writer() as config: config.set_value("core", "worktree", str(elsewhere)) nested.close() result = await call(root, "git_status", {"repo_path": str(root / "nested")}) assert uses_outside(result, elsewhere, root) async def test_restricted_server_serves_a_linked_worktree(tmp_path: Path): # A linked worktree's git directory lives under the main repository's # `.git`, outside the worktree, and is still the allowed repository's own. main = make_repo(tmp_path / "main") worktree = tmp_path / "worktree" main.git.worktree("add", str(worktree)) try: result = await call(worktree, "git_status", {"repo_path": str(worktree)}) assert result["isError"] is False finally: main.close() @pytest.mark.parametrize("name", ["alternates", "http-alternates"]) async def test_restricted_server_rejects_alternate_object_stores( tmp_path: Path, repo: git.Repo, name: str ): # `objects/info/alternates` names more object stores git reads as the # repository's own: a nested repository naming an outside one would show # that repository's commits and files by id. root = root_of(repo) other = make_repo(tmp_path / "other") secret = other.head.commit.hexsha nested = make_repo(root / "nested") alternates = Path(nested.git_dir) / "objects" / "info" / name alternates.parent.mkdir(parents=True, exist_ok=True) alternates.write_text(f"# a comment\n\n{Path(other.git_dir) / 'objects'}\n") nested.close() try: shown = await call( root, "git_show", {"repo_path": str(root / "nested"), "revision": secret} ) assert shown["isError"] is True text = shown["content"][0]["text"] assert f"uses '{alternates}'" in text assert "alternate object stores are not allowed with --repository" in text assert "line 1" not in text finally: other.close() async def test_restricted_server_accepts_empty_alternates(repo: git.Repo): # An alternates file holding only comments and blank lines names nothing. root = root_of(repo) alternates = Path(repo.git_dir) / "objects" / "info" / "alternates" alternates.parent.mkdir(parents=True, exist_ok=True) alternates.write_text("# no alternates\n\n") result = await call(root, "git_status", {"repo_path": str(root)}) assert result["isError"] is False @pytest.mark.parametrize("entry", ["objects", "refs", "index", "packed-refs"]) async def test_restricted_server_rejects_git_dir_symlink_pointing_outside( tmp_path: Path, repo: git.Repo, entry: str ): # A symbolic link inside a nested repository's `.git` is followed by git, # for reading (objects, refs) and for writing (a linked index takes # git_add's writes to the repository it names). root = root_of(repo) other = make_repo(tmp_path / "other") other.git.pack_refs("--all") nested = make_repo(root / "nested") nested_git = Path(nested.git_dir) nested.close() link = nested_git / entry if link.is_dir(): rmtree(link) else: link.unlink(missing_ok=True) link.symlink_to( Path(other.git_dir) / entry, target_is_directory=link.name in ("objects", "refs"), ) index_before = (Path(other.git_dir) / "index").read_bytes() (root / "nested" / "new.txt").write_text("new\n") try: for tool, arguments in ( ("git_show", {"revision": other.head.commit.hexsha}), ("git_branch", {"branch_type": "local"}), ("git_add", {"files": ["new.txt"]}), ): result = await call( root, tool, {"repo_path": str(root / "nested"), **arguments} ) assert uses_outside( result, (Path(other.git_dir) / entry).resolve(), root ), (tool, result) assert (Path(other.git_dir) / "index").read_bytes() == index_before finally: other.close() async def test_restricted_server_follows_an_allowed_git_dir_symlink( tmp_path: Path, repo: git.Repo ): # A link that stays inside the allowed repository is followed by git, so # what it leads to is checked too: here `.git/objects` names an object # store in the working tree holding a link outside. root = root_of(repo) other = make_repo(tmp_path / "other") nested = make_repo(root / "nested") nested_git = Path(nested.git_dir) nested.close() store = root / "store" shutil.copytree(nested_git / "objects", store, symlinks=True) rmtree(nested_git / "objects") (nested_git / "objects").symlink_to(store, target_is_directory=True) escape = Path(other.git_dir) / "objects" (store / "elsewhere").symlink_to(escape, target_is_directory=True) # A cycle of allowed links ends rather than being walked forever. (store / "loop").symlink_to(store, target_is_directory=True) try: result = await call(root, "git_status", {"repo_path": str(root / "nested")}) assert uses_outside(result, escape.resolve(), root), result finally: other.close() async def test_restricted_server_accepts_git_dir_symlinks_that_stay_inside( tmp_path: Path, repo: git.Repo ): # A link within the git directory, or to elsewhere in the allowed # repository, leads nowhere new; nor does a hooks directory linked to a # shared one outside, since no hook runs. root = root_of(repo) git_dir = Path(repo.git_dir) (git_dir / "head-link").symlink_to(git_dir / "HEAD") (git_dir / "readme-link").symlink_to(root / "test.txt") shared_hooks = tmp_path / "shared-hooks" shared_hooks.mkdir() hooks = git_dir / "hooks" if hooks.exists(): rmtree(hooks) hooks.symlink_to(shared_hooks, target_is_directory=True) result = await call(root, "git_status", {"repo_path": str(root)}) assert result["isError"] is False async def test_restricted_server_rejects_nested_gitdir_naming_main_of_worktree( tmp_path: Path, ): # With a linked worktree as the allowed repository, the main repository's # git directory is the worktree's common directory, outside it. A `.git` # file nested in the worktree naming that directory must not reach the # main repository's index, HEAD or branches. main = make_repo(tmp_path / "main") worktree = tmp_path / "worktree" main.git.worktree("add", str(worktree)) (tmp_path / "main" / "test.txt").write_text("staged in main\n") main.git.add("test.txt") staged_before = main.git.diff("--cached", "--name-only") main_head = main.head.commit.hexsha nested = worktree / "nested" nested.mkdir() (nested / ".git").write_text(f"gitdir: {main.git_dir}\n") try: for tool, arguments in ( ("git_reset", {}), ("git_log", {}), ("git_commit", {"message": "escaped"}), ): result = await call(worktree, tool, {"repo_path": str(nested), **arguments}) assert uses_outside(result, Path(main.git_dir), worktree), (tool, result) assert main.git.diff("--cached", "--name-only") == staged_before assert main.head.commit.hexsha == main_head finally: main.close() async def test_restricted_server_rejects_nested_gitdir_naming_worktree_git_dir( tmp_path: Path, ): # The linked worktree's own git directory, named from a repository nested # in it, is the allowed repository's, but not opened from the allowed # repository: refused too. main = make_repo(tmp_path / "main") worktree = tmp_path / "worktree" main.git.worktree("add", str(worktree)) worktree_git_dir = Path(main.git_dir) / "worktrees" / "worktree" nested = worktree / "nested" nested.mkdir() (nested / ".git").write_text(f"gitdir: {worktree_git_dir}\n") try: result = await call(worktree, "git_status", {"repo_path": str(nested)}) assert uses_outside(result, worktree_git_dir, worktree), result finally: main.close() async def test_restricted_server_accepts_nested_bare_repository(repo: git.Repo): # A bare repository has no working tree; its git directory is inside. root = root_of(repo) bare = git.Repo.init(root / "bare.git", bare=True) bare.close() result = await call( root, "git_branch", {"repo_path": str(root / "bare.git"), "branch_type": "local"}, ) assert result["isError"] is False async def test_restricted_server_accepts_nested_repository(repo: git.Repo): # Characterization: the restriction is a path containment check, so a # separate repository nested inside the allowed one is served. root = root_of(repo) nested = make_repo(root / "vendor" / "nested") try: result = await call(root, "git_status", {"repo_path": str(root_of(nested))}) assert result["isError"] is False finally: nested.close() async def test_restricted_server_subdirectory_passes_check_but_is_not_a_repo( repo: git.Repo, ): root = root_of(repo) sub = root / "sub" sub.mkdir() assert await call(root, "git_status", {"repo_path": str(sub)}) == tool_error( "git_status", str(sub) ) async def test_restricted_server_resolves_relative_repo_path_against_cwd( repo: git.Repo, monkeypatch: pytest.MonkeyPatch ): root = root_of(repo) monkeypatch.chdir(root) assert (await call(root, "git_status", {"repo_path": "."}))["isError"] is False monkeypatch.chdir(root.parent) assert await call(root, "git_status", {"repo_path": "."}) == outside_error( ".", root ) async def test_restricted_server_unresolvable_repo_path_is_invalid_path( repo: git.Repo, ): root = root_of(repo) real_resolve = Path.resolve def resolve(self: Path, strict: bool = False) -> Path: if self.name == "unresolvable": raise RuntimeError("simulated symlink loop") return real_resolve(self, strict) target = root / "unresolvable" with mock.patch.object(Path, "resolve", resolve): result = await call(root, "git_status", {"repo_path": str(target)}) assert result == tool_error("git_status", f"Invalid path: {target}") # -------------------------------------------------------------------------- # Roots # -------------------------------------------------------------------------- # The client side of this test offers Roots, which SDK v2 deprecates as of # 2026-07-28 (SEP-2577); the warning is about the test's client, not the server. @pytest.mark.filterwarnings("ignore::mcp.shared.exceptions.MCPDeprecationWarning") async def test_server_never_requests_roots(tmp_path: Path, repo: git.Repo): # The server ignores Roots entirely: it never sends roots/list, not even # after notifications/roots/list_changed, and a repository outside every # root the client offers is still served. (The unreachable `list_repos` # helper that read roots was removed as dead code in #4855.) elsewhere = tmp_path / "elsewhere" elsewhere.mkdir() calls: list[object] = [] async def list_roots(context: ClientRequestContext) -> ListRootsResult: calls.append(context) return ListRootsResult(roots=[Root(uri=FileUrl(elsewhere.as_uri()))]) async with connect(None, list_roots_callback=list_roots) as session: await session.send_roots_list_changed() result = wire( await session.call_tool("git_status", {"repo_path": str(root_of(repo))}) ) assert result["isError"] is False # A request after the notification proves it was processed. await session.send_ping() assert calls == [] async def test_server_without_client_roots_behaves_the_same(repo: git.Repo): async with connect(None) as session: result = wire( await session.call_tool("git_status", {"repo_path": str(root_of(repo))}) ) assert result["isError"] is False # --------------------------------------------------------------------------- # Protocol era # --------------------------------------------------------------------------- async def test_server_discover_answers_the_2026_07_28_era() -> None: # #4853: serve() serves the 2026-07-28 era beside the 2025-11-25 handshake. # A `server/discover` carrying the per-request `_meta` envelope opens it. # Asserted on the raw JSON-RPC response, so the fields the 2026-07-28 # spec requires on a result (resultType, ttlMs, cacheScope) are pinned as # the server sends them, not as a client model would default them. Era by # era behavior through a real client is in test_eras.py. # # Replaces #4851's test_modern_era_is_not_served, which pinned this request # being refused with -32601 "Method not found" until this issue landed. discover = JSONRPCRequest( jsonrpc="2.0", id=1, method="server/discover", params={ "_meta": { "io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientInfo": {"name": "test", "version": "0"}, "io.modelcontextprotocol/clientCapabilities": {}, } }, ) response: SessionMessage | Exception | None = None async with create_client_server_memory_streams() as ( (client_read, client_write), server_streams, ): @asynccontextmanager async def fake_stdio_server() -> AsyncIterator[Any]: yield server_streams with patch("mcp.server.mcpserver.server.stdio_server", fake_stdio_server): async with anyio.create_task_group() as tg: tg.start_soon(serve, None) await client_write.send(SessionMessage(discover)) with anyio.fail_after(5): response = await client_read.receive() tg.cancel_scope.cancel() assert isinstance(response, SessionMessage) assert response.message.model_dump(by_alias=True, exclude_none=True) == { "jsonrpc": "2.0", "id": 1, "result": { "capabilities": CAPABILITIES, "supportedVersions": ["2026-07-28"], "resultType": "complete", "ttlMs": 0, "cacheScope": "private", "_meta": { "io.modelcontextprotocol/serverInfo": { "name": "mcp-git", "version": version("mcp-server-git"), } }, }, }