From e8d2597ca8aae34985f1b6057daccccd3cb99590 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Fri, 4 Dec 2026 22:21:24 -0500 Subject: [PATCH] fix(git): harden repository argument checks Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- src/git/README.md | 2 +- src/git/src/mcp_server_git/server.py | 27 ++++++-- src/git/tests/test_entrypoints.py | 94 +++++++++++++++++++++++++++- 3 files changed, 116 insertions(+), 7 deletions(-) diff --git a/src/git/README.md b/src/git/README.md index 818ccf731a..dfedceb2f7 100644 --- a/src/git/README.md +++ b/src/git/README.md @@ -174,7 +174,7 @@ python -m mcp_server_git > [!IMPORTANT] > **Without `--repository`, the server reads and writes any Git repository the server process can reach.** Each tool call names its own `repo_path`, and that holds for the tools that change a repository too (`git_add`, `git_commit`, `git_reset`, `git_create_branch`, `git_checkout`, `git_merge`). `--repository` is the only confinement the server offers: it never asks the client for Roots, in either protocol era. Set `--repository` whenever the server is used with prompts or content that are not fully trusted. It admits the whole enclosing repository, not only the directory you name, as the next paragraph describes. -`--repository` (`-r`) accepts any path inside a Git working tree. At startup the server walks up to the enclosing repository root, the way `git rev-parse --show-toplevel` does, so `--repository .` works when a shared config is launched from any subdirectory of the repository. A path inside the repository therefore allows tool calls anywhere in that repository, not only under the subdirectory given. A path that does not exist, or is not inside a Git repository, is logged as a one-line error at startup. +`--repository` (`-r`) accepts any path inside a Git working tree. At startup the server walks up to the enclosing repository root, the way `git rev-parse --show-toplevel` does, so `--repository .` works when a shared config is launched from any subdirectory of the repository. A path inside the repository therefore allows tool calls anywhere in that repository, not only under the subdirectory given. A path that does not exist, or is not inside a Git repository, is logged as a one-line error at startup. So is a path inside a Git directory (a repository's `.git`, or a directory laid out as one, which a repository can track), since Git would take that directory's `core.worktree` as the root, which can be any directory, `/` included: the server refuses to start rather than serve that root. The root the server serves is always the path given or one of its ancestors. A bare repository is accepted at its own path, which is its root. With `--repository` set, the server's `instructions` (in the `initialize` result for a 2025-11-25 client, and the `server/discover` result for a 2026-07-28 client) name that repository root, with symbolic links resolved, and tell the model to pass exactly that path as `repo_path`: for example, `This server is confined to the Git repository at /home/me/project. Pass exactly that path as repo_path to every tool and prompt: a path outside that repository is refused.` A client that gives the server's instructions to its model therefore needs no path in the user's prompt. `repo_path` is still required on every tool and prompt. Without `--repository` the server sends no instructions. diff --git a/src/git/src/mcp_server_git/server.py b/src/git/src/mcp_server_git/server.py index f3cf2dc201..fefdeea0fa 100644 --- a/src/git/src/mcp_server_git/server.py +++ b/src/git/src/mcp_server_git/server.py @@ -2574,17 +2574,34 @@ async def serve(repository: Path | None, transport: str = "stdio") -> None: try: # Walk up to the enclosing working tree, like `git rev-parse # --show-toplevel`, so `--repository .` works from a subdirectory. - root = Path( - git.Repo( - repository, search_parent_directories=True, expand_vars=False - ).working_dir - ) + with git.Repo( + repository, search_parent_directories=True, expand_vars=False + ) as found: + root = Path(found.working_dir) + git_dir = Path(found.git_dir).resolve() + bare = found.working_tree_dir is None except git.NoSuchPathError: logger.error(f"{repository} does not exist") raise SystemExit(1) except git.InvalidGitRepositoryError: logger.error(f"{repository} is not a valid Git repository") return + # The root must be the path given or one of its ancestors. A path + # inside a git directory (a repository's `.git`, or a directory laid + # out as one, which a repository can track) makes that directory the + # repository, and its `core.worktree` the root: any directory, `/` + # included. A bare repository has no working tree, so its git + # directory is its root. + given = repository.resolve() + if not bare and given.is_relative_to(git_dir): + logger.error( + f"{repository} is inside the Git directory {git_dir}, " + "not a working tree" + ) + return + if not given.is_relative_to(root.resolve()): + logger.error(f"{repository} is outside the working tree {root}") + return if root != repository: logger.info(f"Resolved --repository {repository} to repository root {root}") repository = root diff --git a/src/git/tests/test_entrypoints.py b/src/git/tests/test_entrypoints.py index f4c5dcdfe7..d77c96a47a 100644 --- a/src/git/tests/test_entrypoints.py +++ b/src/git/tests/test_entrypoints.py @@ -15,7 +15,7 @@ import git import pytest from click.testing import CliRunner -from conftest import connect +from conftest import connect, make_repo import mcp_server_git from mcp_server_git import main @@ -102,6 +102,98 @@ async def test_serve_exits_for_nonexistent_repository( assert f"{missing} does not exist" in caplog.text +def _fake_git_dir(fake: Path, worktree: Path) -> Path: + """`fake` laid out as a git directory whose `core.worktree` is `worktree`, + as a cloned repository can track one.""" + (fake / "objects").mkdir(parents=True) + (fake / "refs").mkdir() + (fake / "HEAD").write_text("ref: refs/heads/main\n") + (fake / "config").write_text( + "[core]\n\trepositoryformatversion = 0\n\tbare = false\n" + f"\tworktree = {worktree.as_posix()}\n" + ) + return fake + + +async def _refused_at_startup( + repository: Path, caplog: pytest.LogCaptureFixture +) -> None: + stdio = mock.MagicMock() + with ( + mock.patch("mcp.server.mcpserver.server.stdio_server", stdio), + caplog.at_level(logging.INFO, logger="mcp_server_git.server"), + ): + assert await serve(repository) is None + stdio.assert_not_called() + assert "Using repository at" not in caplog.text + + +@pytest.mark.parametrize("target", ["filesystem root", "other repository"]) +async def test_serve_refuses_repository_inside_a_git_directory( + repo: git.Repo, tmp_path: Path, caplog: pytest.LogCaptureFixture, target: str +): + # A `--repository` inside a directory laid out as a git directory makes + # that directory the repository, and its `core.worktree` the root: the + # filesystem root, or another repository. The server refuses to start + # rather than serve that root. + assert repo.working_dir is not None + if target == "filesystem root": + worktree = Path(tmp_path.resolve().anchor) + else: + other = make_repo(tmp_path / "other") + assert other.working_dir is not None + worktree = Path(other.working_dir) + other.close() + fake = _fake_git_dir(Path(repo.working_dir) / "sub", worktree) + await _refused_at_startup(fake, caplog) + assert f"{fake} is inside the Git directory" in caplog.text + + +async def test_serve_refuses_the_repository_git_directory( + repo: git.Repo, caplog: pytest.LogCaptureFixture +): + assert repo.working_dir is not None + git_dir = Path(repo.working_dir) / ".git" + await _refused_at_startup(git_dir, caplog) + assert f"{git_dir} is inside the Git directory" in caplog.text + + +async def test_serve_refuses_a_root_that_does_not_contain_the_repository( + repo: git.Repo, tmp_path: Path, caplog: pytest.LogCaptureFixture +): + # Whatever leads GitPython to it, a root that is not the given path or + # one of its ancestors is refused. No layout on disk reaches this past the + # git-directory check above (GitPython applies `core.worktree` only to a + # path it opens as a git directory), so GitPython's answer is stood in. + assert repo.working_dir is not None + given = Path(repo.working_dir) + other = tmp_path / "other" + other.mkdir() + found = mock.MagicMock() + found.__enter__.return_value = found + found.working_dir = str(other) + found.git_dir = str(other / ".git") + found.working_tree_dir = str(other) + with mock.patch("mcp_server_git.server.git.Repo", return_value=found): + await _refused_at_startup(given, caplog) + assert f"{given} is outside the working tree {other}" in caplog.text + + +async def test_serve_accepts_a_bare_repository( + tmp_path: Path, caplog: pytest.LogCaptureFixture +): + # A bare repository has no working tree: its git directory is its root. + bare = tmp_path / "bare.git" + git.Repo.init(bare, bare=True).close() + with caplog.at_level(logging.INFO, logger="mcp_server_git.server"): + async with connect(bare) as session: + result = await session.call_tool( + "git_branch", {"repo_path": str(bare), "branch_type": "local"} + ) + assert not result.is_error + assert f"Using repository at {bare}" in caplog.text + + # -------------------------------------------------------------------------- # main() # --------------------------------------------------------------------------