Skip to content

Commit a4a43ac

Browse files
cliffhallclaude
andcommitted
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: cliffhall <cliff@futurescale.com>
1 parent b71b3da commit a4a43ac

5 files changed

Lines changed: 863 additions & 49 deletions

File tree

‎src/git/README.md‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,22 @@ python -m mcp_server_git
173173
174174
`--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.
175175

176-
A tool call's `repo_path` must be inside that repository, and so must the directories Git then uses for it: a repository nested inside whose `.git` file, `commondir` or `core.worktree` points outside is refused. A linked worktree can still be the `--repository`, though its Git directory lives under the main repository's `.git`.
176+
A tool call's `repo_path` must be inside that repository, and so must the directories Git then uses for it: a repository nested inside whose `.git` file, `commondir` or `core.worktree` points outside is refused. A linked worktree can still be the `--repository`, though its Git directory lives under the main repository's `.git`; only the worktree itself may use that directory, so a repository nested in the worktree whose `.git` names it, or the main repository's `.git`, is refused. With `--repository` set, the server also refuses a repository whose Git directory:
177+
178+
- names alternate object stores (`objects/info/alternates` or `objects/info/http-alternates` with any entry), wherever they are. A clone made with `--reference` or `--shared` therefore cannot be used under `--repository`; `git repack -a -d` and then deleting `objects/info/alternates` makes it self-contained.
179+
- holds a symbolic link (at `objects`, `refs`, `index`, `HEAD` or anywhere else in it) that resolves outside both the allowed repository and that Git directory. A `hooks` directory linked elsewhere is allowed, since no hook runs.
180+
181+
### A repository's own programs
182+
183+
A repository's configuration and hooks travel with it (an unpacked archive, a shared folder, a vendored tree), so the server never runs a program they name, with or without `--repository`. Every Git command it runs overrides, through `GIT_CONFIG_COUNT`, the settings that would start one:
184+
185+
- `core.fsmonitor` is `false`, and `core.hooksPath` points at the null device, so no hook runs; `git_commit` also skips the hooks GitPython would run itself (`pre-commit`, `commit-msg`, `post-commit`).
186+
- Diffs pass `--no-ext-diff` and `--no-textconv`, so `diff.external`, `diff.<driver>.command` and `diff.<driver>.textconv` are ignored.
187+
- Each filter driver (`filter.<name>.clean`, `smudge`, `process`) and merge driver (`merge.<name>.driver`) that the repository's own configuration defines is emptied: files are staged and checked out unfiltered, and a file a merge driver would have merged is a conflict, which `git_merge` aborts. Drivers from your global or system configuration, such as Git LFS's, keep working.
188+
- `commit.gpgSign` and `merge.verifySignatures` are `false`, `submodule.recurse` and `merge.autoStash` are `false`, and `core.pager` is `cat`.
189+
- `git_status`, `git_diff_unstaged` and `git_diff` pass `--ignore-submodules=dirty`, because looking for changes inside a submodule runs Git under the submodule's own configuration. A submodule whose checked-out commit moved is still reported; changes inside one are not, so run the tool on the submodule's path to see them.
190+
191+
This needs Git 2.31 or later; with an older Git every tool call fails with an error saying so, rather than run unprotected.
177192

178193
### Commit identity
179194

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

Lines changed: 227 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
# The git MCP server: tools that read and change a Git repository through
22
# GitPython, and prompts that embed a repository's changes in a message for the
33
# model (#5195). Repository confinement (`--repository`, `validate_repo_path` on
4-
# the path given, `validate_opened_repo` on the directories git then uses) and
5-
# the flag-injection guards live beside the handlers because every tool call and
6-
# prompt must pass them before any git command runs.
4+
# the path given, `validate_opened_repo` on the directories git then uses), the
5+
# overrides that keep a repository's own configuration from running programs
6+
# (`harden_repo`), and the flag-injection guards live beside the handlers
7+
# because every tool call and prompt must pass them before any git command runs.
78
#
89
# Built on the MCP Python SDK's high-level `MCPServer` (#5174), the API these
910
# reference servers are meant to teach: each tool is a typed function, and the
@@ -19,6 +20,7 @@
1920
# logging), so nothing differs between them.
2021

2122
import logging
23+
import os
2224
import re
2325
import threading
2426
from collections.abc import Callable, Iterator
@@ -107,18 +109,135 @@ def _git_text(repo: git.Repo, command: str, *args: str) -> str:
107109
return output.decode("utf-8", errors="replace")
108110

109111

112+
# Configuration that names a program git would run, overridden for every git
113+
# command the server runs in a repository it opens (`harden_repo`). A
114+
# repository's own `.git/config` is not trusted: it travels with the
115+
# repository (an unpacked archive, a shared folder, a vendored tree), so
116+
# honoring it would let the repository run code as the server's user on a
117+
# read-only call such as git_status. The overrides go in through
118+
# GIT_CONFIG_COUNT (git 2.31+), which outranks every config file and is
119+
# inherited by the git processes git itself starts, submodules included.
120+
#
121+
# - `core.fsmonitor` is run on every index refresh (status, diff, add).
122+
# - `core.hooksPath` pointing at the null device leaves no hook to find, so
123+
# no hook runs (post-checkout, pre-merge-commit, reference-transaction, ...).
124+
# GitPython's `index.commit` runs hooks itself; git_commit skips them.
125+
# - `core.pager` is never started without a terminal; pinned all the same.
126+
# - `commit.gpgSign` and `merge.verifySignatures` would run `gpg.program` on
127+
# a merge commit or a merge.
128+
# - `submodule.recurse` would carry checkout and merge into submodules, whose
129+
# own configuration this override cannot neutralize (see `_LISTED_KEYS`).
130+
# - `merge.autoStash` keeps git_merge from stashing behind the tool's back.
131+
#
132+
# External diff programs and textconv filters are turned off per command
133+
# (`_DIFF_FLAGS`), and filter and merge drivers per repository (`_LISTED_KEYS`).
134+
HARDENED_CONFIG: tuple[tuple[str, str], ...] = (
135+
("core.fsmonitor", "false"),
136+
("core.hooksPath", os.devnull),
137+
("core.pager", "cat"),
138+
("commit.gpgSign", "false"),
139+
("merge.verifySignatures", "false"),
140+
("submodule.recurse", "false"),
141+
("status.submoduleSummary", "false"),
142+
("merge.autoStash", "false"),
143+
)
144+
145+
# A filter driver (`filter.<name>.clean`/`smudge`/`process`, applied by
146+
# `.gitattributes` on add, checkout and status) or merge driver
147+
# (`merge.<name>.driver`) is a command too, under a name the repository
148+
# chooses, so each one the repository's own configuration defines is
149+
# overridden with an empty command, which git skips (a filter) or reports as
150+
# a conflict (a merge driver). Drivers from the user's global or system
151+
# configuration (git-lfs, say) are the user's own and keep working.
152+
# `harden_repo` lists these keys, and `core.hooksPath`, whose command-scope
153+
# value shows that git applied the overrides.
154+
_LISTED_KEYS = (
155+
r"^(core\.hookspath|filter\..+\.(clean|smudge|process)|merge\..+\.driver)$"
156+
)
157+
158+
# Scopes whose configuration the user wrote rather than the repository.
159+
_TRUSTED_SCOPES = frozenset({"system", "global", "command"})
160+
161+
# For every diff whose output is the patch: `--no-ext-diff` turns off
162+
# `diff.external` and `diff.<driver>.command`, `--no-textconv` the
163+
# `diff.<driver>.textconv` filters git diff applies by default.
164+
_DIFF_FLAGS = ("--no-ext-diff", "--no-textconv")
165+
166+
# A command that compares the working tree looks inside each submodule by
167+
# running `git status` there, under the submodule's own configuration, whose
168+
# filter drivers `harden_repo` never sees. `dirty` still reports a submodule
169+
# whose checked-out commit moved, without that look inside. The flag outranks
170+
# `submodule.<name>.ignore`, which the repository could set to `none`.
171+
_NO_SUBMODULE_STATUS = "--ignore-submodules=dirty"
172+
173+
174+
def _config_env(entries: list[tuple[str, str]]) -> dict[str, str]:
175+
"""GIT_CONFIG_COUNT variables for `entries`, after any the user set."""
176+
base = int(os.environ.get("GIT_CONFIG_COUNT", "0"))
177+
env = {"GIT_CONFIG_COUNT": str(base + len(entries))}
178+
for i, (key, value) in enumerate(entries, start=base):
179+
env[f"GIT_CONFIG_KEY_{i}"] = key
180+
env[f"GIT_CONFIG_VALUE_{i}"] = value
181+
return env
182+
183+
184+
def harden_repo(repo: git.Repo) -> None:
185+
"""Keep every git command run for `repo` from running a program it names.
186+
187+
Sets `HARDENED_CONFIG` on the repository's git, then reads which filter
188+
and merge drivers the repository's own configuration (its `.git/config`,
189+
a worktree's `config.worktree`, and files they include) defines, and
190+
overrides each with an empty command. The same read checks that git
191+
applied the overrides: git older than 2.31 ignores GIT_CONFIG_COUNT, and
192+
is refused rather than run unprotected.
193+
"""
194+
entries = list(HARDENED_CONFIG)
195+
repo.git.update_environment(**_config_env(entries))
196+
try:
197+
listed = repo.git.config("--show-scope", "-z", "--get-regexp", _LISTED_KEYS)
198+
except git.GitCommandError as e:
199+
# Exit 1 is "nothing matched", which a git that applied the
200+
# overrides never reports, since core.hooksPath always matches.
201+
if e.status != 1:
202+
raise
203+
listed = ""
204+
applied = False
205+
drivers: set[str] = set()
206+
# -z prints `<scope>\0<key>\n<value>\0` for each entry.
207+
fields = listed.split("\0")
208+
for scope, entry in zip(fields[0::2], fields[1::2]):
209+
key, _, value = entry.partition("\n")
210+
if key == "core.hookspath":
211+
applied = applied or (scope == "command" and value == os.devnull)
212+
elif scope not in _TRUSTED_SCOPES:
213+
drivers.add(key)
214+
if not applied:
215+
raise git.GitError(
216+
"Git 2.31 or later is required: this git ignores the configuration "
217+
"overrides that keep a repository's own configuration from running "
218+
"programs"
219+
)
220+
if drivers:
221+
entries += [(key, "") for key in sorted(drivers)]
222+
repo.git.update_environment(**_config_env(entries))
223+
224+
110225
def git_status(repo: git.Repo) -> str:
111-
return _git_text(repo, "status")
226+
return _git_text(repo, "status", _NO_SUBMODULE_STATUS)
112227

113228

114229
def git_diff_unstaged(
115230
repo: git.Repo, context_lines: int = DEFAULT_CONTEXT_LINES
116231
) -> str:
117-
return _git_text(repo, "diff", f"--unified={context_lines}")
232+
return _git_text(
233+
repo, "diff", *_DIFF_FLAGS, _NO_SUBMODULE_STATUS, f"--unified={context_lines}"
234+
)
118235

119236

120237
def git_diff_staged(repo: git.Repo, context_lines: int = DEFAULT_CONTEXT_LINES) -> str:
121-
return _git_text(repo, "diff", f"--unified={context_lines}", "--cached")
238+
return _git_text(
239+
repo, "diff", *_DIFF_FLAGS, f"--unified={context_lines}", "--cached"
240+
)
122241

123242

124243
def _validate_diff_target(repo: git.Repo, target: str) -> None:
@@ -161,7 +280,14 @@ def git_diff(
161280
raise FlagInjectionError(f"Invalid target: '{target}' - cannot start with '-'")
162281
# Validates target is a real revision or range, throws BadName if not
163282
_validate_diff_target(repo, target)
164-
return _git_text(repo, "diff", f"--unified={context_lines}", target)
283+
return _git_text(
284+
repo,
285+
"diff",
286+
*_DIFF_FLAGS,
287+
_NO_SUBMODULE_STATUS,
288+
f"--unified={context_lines}",
289+
target,
290+
)
165291

166292

167293
def _has_staged_changes(repo: git.Repo) -> bool:
@@ -196,12 +322,14 @@ def git_commit(repo: git.Repo, message: str) -> str:
196322
parents = [repo.head.commit] + [
197323
repo.commit(sha) for sha in merge_head.read_text().split()
198324
]
199-
commit = repo.index.commit(message, parent_commits=parents)
325+
commit = repo.index.commit(message, parent_commits=parents, skip_hooks=True)
200326
for name in ("MERGE_HEAD", "MERGE_MSG", "MERGE_MODE", "AUTO_MERGE"):
201327
(git_dir / name).unlink(missing_ok=True)
202328
autostash_note = _apply_merge_autostash(repo)
203329
else:
204-
commit = repo.index.commit(message)
330+
# skip_hooks: GitPython runs the repository's hooks itself, ignoring
331+
# the core.hooksPath override (`harden_repo`).
332+
commit = repo.index.commit(message, skip_hooks=True)
205333
autostash_note = ""
206334
return f"Changes committed successfully with hash {commit.hexsha}{autostash_note}"
207335

@@ -410,7 +538,9 @@ def _merge_failure(repo: git.Repo, error: git.GitCommandError, what: str) -> str
410538
return f"{what} failed. {unchanged} Git reported:\n{_git_stderr(error)}"
411539
# Through _git_text, so a non-ASCII name prints as written, not as
412540
# core.quotepath's octal escapes.
413-
conflicts = _git_text(repo, "diff", "--name-only", "--diff-filter=U").splitlines()
541+
conflicts = _git_text(
542+
repo, "diff", _NO_SUBMODULE_STATUS, "--name-only", "--diff-filter=U"
543+
).splitlines()
414544
repo.git.merge("--abort")
415545
if conflicts:
416546
return (
@@ -449,7 +579,9 @@ def git_merge(
449579
raise ValueError(
450580
"A merge is already in progress; conclude it with git_commit first"
451581
)
452-
if repo.is_dirty():
582+
# Not `repo.is_dirty()`, whose `git diff` looks inside submodules
583+
# (_NO_SUBMODULE_STATUS); a merge never touches a submodule's working tree.
584+
if repo.git.status("--porcelain", "--untracked-files=no", _NO_SUBMODULE_STATUS):
453585
raise ValueError(
454586
f"Cannot merge into '{target}': the working tree has uncommitted "
455587
"changes. Commit or discard them first, so a failed merge can be "
@@ -589,13 +721,19 @@ def validate_opened_repo(
589721
follow a `.git` file (`gitdir:`), a `commondir` file or `core.worktree` to
590722
a directory anywhere else, so the working tree, git directory and common
591723
directory git actually uses are checked too. The working tree must lie
592-
inside the allowed repository. The two git directories must lie inside it
593-
or be the allowed repository's own: a linked worktree's git directory
594-
lives under the main repository's `.git`, outside the worktree it serves.
724+
inside the allowed repository. The two git directories must lie inside it,
725+
or be the allowed repository's own as a pair, opened from the allowed
726+
repository itself: a linked worktree's git directory lives under the main
727+
repository's `.git`, outside the worktree it serves, and only that
728+
worktree may use it. A repository nested inside a linked worktree whose
729+
`.git` names the main repository's git directory is refused.
595730
596731
Both git's answer (`rev-parse`, which the tools' git commands follow) and
597732
GitPython's (which some tools read directly) are checked: GitPython does
598733
not apply `core.worktree`, so the two can differ.
734+
735+
Git also reaches past those directories from inside them, so
736+
`_check_git_dir_contents` holds what they contain to the same boundary.
599737
"""
600738
if allowed_repository is None:
601739
return
@@ -621,21 +759,79 @@ def outside(used: Path) -> ValueError:
621759
if not working_tree.resolve().is_relative_to(allowed):
622760
raise outside(working_tree)
623761

762+
git_dirs = [Path(git_dir), Path(repo.git_dir)]
763+
common_dirs = [Path(common_dir), Path(repo.common_dir)]
624764
escaped = [
625-
p
626-
for p in map(Path, (git_dir, common_dir, repo.git_dir, repo.common_dir))
627-
if not p.resolve().is_relative_to(allowed)
765+
p for p in git_dirs + common_dirs if not p.resolve().is_relative_to(allowed)
628766
]
629-
if not escaped:
630-
return
631-
with git.Repo(allowed) as allowed_repo:
632-
own = {
633-
Path(allowed_repo.git_dir).resolve(),
634-
Path(allowed_repo.common_dir).resolve(),
635-
}
636-
for p in escaped:
637-
if p.resolve() not in own:
638-
raise outside(p)
767+
if escaped:
768+
with git.Repo(allowed) as allowed_repo:
769+
own_git_dir = Path(allowed_repo.git_dir).resolve()
770+
own_common_dir = Path(allowed_repo.common_dir).resolve()
771+
is_own = (
772+
bool(working_trees)
773+
and all(Path(w).resolve() == allowed for w in working_trees)
774+
and all(p.resolve() == own_git_dir for p in git_dirs)
775+
and all(p.resolve() == own_common_dir for p in common_dirs)
776+
)
777+
if not is_own:
778+
raise outside(escaped[0])
779+
780+
for directory in {p.resolve() for p in git_dirs + common_dirs}:
781+
_check_git_dir_contents(repo_path, directory, allowed, outside)
782+
783+
784+
# Files in a git directory that name more object stores for git to read: an
785+
# alternate's objects are read as the repository's own, from wherever it is.
786+
_ALTERNATES = ("alternates", "http-alternates")
787+
788+
789+
def _check_git_dir_contents(
790+
repo_path: Path,
791+
directory: Path,
792+
allowed: Path,
793+
outside: Callable[[Path], ValueError],
794+
) -> None:
795+
"""Refuse what in a git directory leads git outside the allowed repository.
796+
797+
- An alternate object store (`objects/info/alternates`, and
798+
`http-alternates`), of any kind: under `--repository`, a repository
799+
reads only its own objects.
800+
- A symbolic link that resolves outside both the allowed repository and
801+
`directory` itself: a link at `objects`, `refs`, `index`, `HEAD` or
802+
anything else in a git directory is followed by git, for reading and
803+
for writing (a linked `index` takes git_add's writes elsewhere).
804+
805+
`hooks` is not walked: no hook runs (`HARDENED_CONFIG`), so a hooks
806+
directory linked to a shared one elsewhere is harmless.
807+
"""
808+
for name in _ALTERNATES:
809+
alternates = directory / "objects" / "info" / name
810+
if alternates.is_file():
811+
lines = alternates.read_text(encoding="utf-8", errors="replace")
812+
if any(
813+
line.strip() and not line.startswith("#") for line in lines.split("\n")
814+
):
815+
raise ValueError(
816+
f"Repository path '{repo_path}' uses '{alternates}': "
817+
"alternate object stores are not allowed with --repository"
818+
)
819+
pending = [directory]
820+
while pending:
821+
current = pending.pop()
822+
with os.scandir(current) as entries:
823+
for entry in entries:
824+
if current == directory and entry.name == "hooks":
825+
continue
826+
if entry.is_symlink():
827+
target = Path(entry.path).resolve()
828+
if not (
829+
target.is_relative_to(allowed)
830+
or target.is_relative_to(directory)
831+
):
832+
raise outside(target)
833+
elif entry.is_dir():
834+
pending.append(Path(entry.path))
639835

640836

641837
def git_branch(
@@ -932,7 +1128,7 @@ def summarize_changes_prompt(repo: git.Repo, target: str | None = None) -> str:
9321128
parts.append(f"Unstaged changes:\n{_fenced(unstaged)}")
9331129
# The porcelain status is empty only on a clean tree; an untracked file
9341130
# alone leaves both diffs empty but is still a change to summarize.
935-
clean = not repo.git.status("--porcelain").strip()
1131+
clean = not repo.git.status("--porcelain", _NO_SUBMODULE_STATUS).strip()
9361132
changes = "" if clean else "\n\n".join(parts)
9371133
if not changes:
9381134
return f"There are no changes {scope} to summarize. Tell the user so."
@@ -994,6 +1190,9 @@ def open_repo(repo_path: str) -> git.Repo:
9941190
validate_repo_path(path, repository)
9951191
repo = git.Repo(path)
9961192
try:
1193+
# First, so that no git command run for the repository, the
1194+
# confinement checks' included, runs a program it names.
1195+
harden_repo(repo)
9971196
validate_opened_repo(repo, path, repository)
9981197
except Exception:
9991198
repo.close()

0 commit comments

Comments
 (0)