Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/git/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ Please note that mcp-server-git is currently in early development. The functiona

### Tools

Every tool's `repo_path` is taken literally: neither a leading `~` nor `$NAME` or `${NAME}` is expanded, and a relative path is relative to the server's working directory.

1. `git_status`
- Shows the working tree status
- Input:
Expand Down
35 changes: 32 additions & 3 deletions src/git/src/mcp_server_git/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -1017,7 +1017,7 @@ def outside(used: Path) -> ValueError:
p for p in git_dirs + common_dirs if not p.resolve().is_relative_to(allowed)
]
if escaped:
with git.Repo(allowed) as allowed_repo:
with git.Repo(allowed, expand_vars=False) as allowed_repo:
own_git_dir = Path(allowed_repo.git_dir).resolve()
own_common_dir = Path(allowed_repo.common_dir).resolve()
is_own = (
Expand Down Expand Up @@ -1513,6 +1513,30 @@ def reported_as_invalid_params() -> Iterator[None]:
raise MCPError(code=INVALID_PARAMS, message=str(e)) from e


class _LiteralGit(git.Git):
"""A `git.Git` whose working directory is taken literally.

`git.Git` runs `os.path.expandvars` on a `str` working directory, and
`git.Repo` hands it one, whatever `expand_vars` the repository was opened
with. A `Path` is only resolved, so a `$NAME` in it stays as written.
"""

def __init__(self, working_dir: str | os.PathLike[str] | None = None) -> None:
super().__init__(None if working_dir is None else Path(working_dir))


class _LiteralRepo(git.Repo):
"""A `git.Repo` whose git commands run in the directory it was opened at.

Opened with `expand_vars=False` and an absolute path, a repository path is
taken literally: neither a `$NAME` nor a leading `~` in it becomes the
value of the server's environment, in the directory opened, in where its
commands run, or in an error.
"""

GitCommandWrapperType = _LiteralGit


def create_server(repository: Path | None) -> MCPServer:
"""The git server, confined to `repository` when one is given."""

Expand Down Expand Up @@ -1545,7 +1569,10 @@ async def reject_unknown_tools(
def open_repo(repo_path: str) -> git.Repo:
path = Path(repo_path)
validate_repo_path(path, repository)
repo = git.Repo(path)
# Opened at exactly the path checked above. GitPython expands a leading
# `~` in a relative path whatever `expand_vars` says, so it is made
# absolute first, which leaves nothing for it to expand.
repo = _LiteralRepo(path.absolute(), expand_vars=False)
try:
# First, so that no git command run for the repository, the
# confinement checks' included, runs a program it names.
Expand Down Expand Up @@ -1866,7 +1893,9 @@ async def serve(repository: Path | None, transport: str = "stdio") -> None:
# 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).working_dir
git.Repo(
repository, search_parent_directories=True, expand_vars=False
).working_dir
)
except git.NoSuchPathError:
logger.error(f"{repository} does not exist")
Expand Down
109 changes: 109 additions & 0 deletions src/git/tests/test_expand_vars.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
"""A tool's `repo_path` is taken literally: no `$NAME` or `~` in it is expanded.

GitPython's `Repo()` expands environment variables in the path it is given
unless it is passed `expand_vars=False`, and expands a leading `~` (from
`HOME`) in any relative path. A `$NAME`, `${NAME}` or `~` in `repo_path` must
name a file whose name holds those characters, so the result of a tool call
(its errors included) never holds the value of `HOME` or of a variable the
path names. A `$NAME` in `--repository` is taken literally too. These tests
set a variable, name it in a path, and assert on what a client receives over
the wire.
"""

from pathlib import Path

import git
import pytest
from conftest import connect, make_repo, wire

VALUE = "value-of-the-variable"
NAME = "MCP_GIT_TEST_VARIABLE"


@pytest.fixture(autouse=True)
def variable(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv(NAME, VALUE)


async def status(repository: Path | None, repo_path: str) -> dict[str, object]:
async with connect(repository) as session:
return wire(await session.call_tool("git_status", {"repo_path": repo_path}))


def text_of(result: dict[str, object]) -> str:
content = result["content"]
assert isinstance(content, list)
return "".join(block["text"] for block in content)


@pytest.mark.parametrize("reference", [f"${NAME}", f"${{{NAME}}}"])
async def test_relative_repo_path_is_not_expanded(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, reference: str
):
monkeypatch.chdir(tmp_path)
result = await status(None, reference)
assert result["isError"] is True
assert VALUE not in text_of(result)
assert reference in text_of(result)


@pytest.mark.parametrize("reference", [f"${NAME}", f"${{{NAME}}}"])
async def test_repo_path_under_repository_is_not_expanded(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, reference: str
):
root = tmp_path / "repo"
make_repo(root).close()
# With the working directory inside the allowed repository, a relative
# path passes the --repository check before the repository is opened.
monkeypatch.chdir(root)
for repo_path in (reference, str(root / reference)):
result = await status(root, repo_path)
assert result["isError"] is True
assert VALUE not in text_of(result)


@pytest.mark.parametrize("reference", ["~", "~/repo"])
async def test_tilde_in_repo_path_is_not_expanded(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, reference: str
):
home = tmp_path / VALUE
make_repo(home / "repo").close()
monkeypatch.setenv("HOME", str(home))
monkeypatch.setenv("USERPROFILE", str(home))
monkeypatch.chdir(tmp_path)
result = await status(None, reference)
assert result["isError"] is True
assert VALUE not in text_of(result)
assert str(tmp_path / reference) in text_of(result)


async def test_repository_named_with_a_dollar_sign_opens(tmp_path: Path):
# Made under a plain name and renamed, since `make_repo` would expand it.
root = tmp_path / f"${NAME}"
make_repo(tmp_path / "plain").close()
(tmp_path / "plain").rename(root)
for repository in (None, root):
result = await status(repository, str(root))
assert result["isError"] is False, result
assert "On branch main" in text_of(result)
# Reading a commit goes through the object database's own git.
async with connect(repository) as session:
log = wire(await session.call_tool("git_log", {"repo_path": str(root)}))
assert log["isError"] is False, log
assert "initial commit" in text_of(log)


async def test_repository_with_separate_git_dir_named_with_a_dollar_sign(
tmp_path: Path,
):
# A git dir outside the working tree makes the --repository check compare
# it with the allowed root's own. Its `core.worktree` names the root back,
# as a submodule's git dir does, so the root is one the check accepts.
root = tmp_path / f"${NAME}"
root.mkdir()
git_dir = tmp_path / "gitdir"
git.Git(root).init(f"--separate-git-dir={git_dir}")
git.Git(root).config("core.worktree", str(root))
result = await status(root, str(root))
assert result["isError"] is False, result
assert "No commits yet" in text_of(result)