Skip to content

Commit d148379

Browse files
cliffhallclaude
andcommitted
feat(git): add a read-only git_remote tool that lists remotes
Lists each remote's fetch and push URLs, like `git remote -v`. A credential embedded in a URL is never returned: the userinfo of a URL is replaced by <redacted>, except an SSH username, which names an account and authenticates nothing. Closes modelcontextprotocol#1611 Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent 446be48 commit d148379

5 files changed

Lines changed: 239 additions & 0 deletions

File tree

‎src/git/README.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,13 @@ Please note that mcp-server-git is currently in early development. The functiona
100100
- `not_contains` (string, optional): The commit sha that branch should NOT contain. Do not pass anything to this param if no commit sha is specified
101101
- Returns: List of branches
102102

103+
14. `git_remote`
104+
- Lists the repository's remotes with their fetch and push URLs, like `git remote -v`
105+
- Inputs:
106+
- `repo_path` (string): Path to the Git repository.
107+
- Returns: One line per remote and direction, `<name>\t<url> (fetch)` or `(push)`, or `No remotes configured`
108+
- A credential embedded in a URL is never returned: the whole userinfo of a URL such as `https://user:token@host/...` or `https://token@host/...` is shown as `<redacted>`. An SSH username (`ssh://git@host/...`) is kept, since it names an account rather than authenticating one; a password after it is redacted. scp-style addresses (`git@host:path`) and local paths are shown as configured.
109+
103110
### Protocol versions
104111

105112
The server speaks both eras of the Model Context Protocol over stdio, with nothing to configure: a **2026-07-28** client (discovered with `server/discover`, no session) and a **2025-11-25** client (the `initialize` handshake). The client's first request decides which. Tools behave the same in both.

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

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
# logging), so nothing differs between them.
1919

2020
import logging
21+
import re
2122
import threading
2223
from collections.abc import Callable, Iterator
2324
from contextlib import contextmanager
@@ -72,6 +73,7 @@ class GitTools(str, Enum):
7273
SHOW = "git_show"
7374

7475
BRANCH = "git_branch"
76+
REMOTE = "git_remote"
7577

7678

7779
def _git_text(repo: git.Repo, command: str, *args: str) -> str:
@@ -517,6 +519,65 @@ def git_branch(
517519
return branch_info
518520

519521

522+
# A URL with an authority part: `scheme://[userinfo@]host...`. The userinfo is
523+
# everything up to the last '@' before the first '/', which is where git itself
524+
# stops reading it.
525+
_URL_USERINFO = re.compile(
526+
r"^(?P<scheme>[A-Za-z][A-Za-z0-9+.-]*)://(?P<userinfo>[^/]*)@"
527+
)
528+
529+
# Schemes whose username is an account name rather than a secret, so it is kept
530+
# (`ssh://git@host/...`) and only a password after it is redacted.
531+
_SSH_SCHEMES = frozenset({"ssh", "git+ssh", "ssh+git"})
532+
533+
REDACTED = "<redacted>"
534+
535+
536+
def redact_url(url: str) -> str:
537+
"""`url` with any credential in its userinfo replaced by `<redacted>` (#1611).
538+
539+
A remote URL can carry a credential (`https://user:token@host/...`), and
540+
the tool's output goes to the model, so it must not echo one. Over HTTP(S)
541+
and every other scheme a token is as often the username as the password
542+
(`https://<token>@github.com/...`), so the whole userinfo is redacted. An
543+
SSH username names the account and authenticates nothing, so it stays,
544+
with only a password after it redacted. An scp-like address
545+
(`git@host:path`) or a local path has no userinfo to carry a password and
546+
is returned as is.
547+
"""
548+
match = _URL_USERINFO.match(url)
549+
if match is None:
550+
return url
551+
scheme, userinfo = match["scheme"], match["userinfo"]
552+
if scheme.lower() in _SSH_SCHEMES:
553+
user, has_password, _ = userinfo.partition(":")
554+
kept = f"{user}:{REDACTED}" if has_password else user
555+
else:
556+
kept = REDACTED
557+
return f"{scheme}://{kept}@{url[match.end() :]}"
558+
559+
560+
def git_remote(repo: git.Repo) -> str:
561+
"""The repository's remotes with their fetch and push URLs, as `git remote -v`.
562+
563+
Each line is `<name>\t<url> (fetch|push)`; the URL goes through
564+
`redact_url` so no credential reaches the client.
565+
"""
566+
lines = []
567+
for line in _git_text(repo, "remote", "-v").splitlines():
568+
name, tab, rest = line.partition("\t")
569+
url, space, direction = rest.rpartition(" ")
570+
if not tab or not space:
571+
# Not the `<name>\t<url> (<direction>)` shape `git remote -v`
572+
# prints; redact it whole rather than pass a URL through unread.
573+
lines.append(redact_url(line))
574+
continue
575+
lines.append(f"{name}\t{redact_url(url)} {direction}")
576+
if not lines:
577+
return "No remotes configured"
578+
return "\n".join(lines)
579+
580+
520581
# The failures a tool reports to the model as a `ToolError`, each with the
521582
# message it was raised with: the guards' `ValueError`s and
522583
# `FlagInjectionError`s, git and GitPython errors (`GitError`: a failed
@@ -814,6 +875,22 @@ def branch(
814875
) -> str:
815876
return git_branch(open_repo(repo_path), branch_type, contains, not_contains)
816877

878+
@server.tool(
879+
name=GitTools.REMOTE.value,
880+
description=(
881+
"Lists the repository's remotes with their fetch and push URLs, "
882+
"like `git remote -v`. Credentials embedded in a URL are shown as "
883+
"<redacted>"
884+
),
885+
annotations=READ_ONLY,
886+
structured_output=False,
887+
)
888+
@reports_failures
889+
def remote(
890+
repo_path: Annotated[str, Field(description="The path to the Git repository.")],
891+
) -> str:
892+
return git_remote(open_repo(repo_path))
893+
817894
return server
818895

819896

‎src/git/tests/snapshots/list_tools.json‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -401,6 +401,30 @@
401401
"idempotentHint": true,
402402
"openWorldHint": false
403403
}
404+
},
405+
{
406+
"name": "git_remote",
407+
"description": "Lists the repository's remotes with their fetch and push URLs, like `git remote -v`. Credentials embedded in a URL are shown as <redacted>",
408+
"inputSchema": {
409+
"properties": {
410+
"repo_path": {
411+
"description": "The path to the Git repository.",
412+
"title": "Repo Path",
413+
"type": "string"
414+
}
415+
},
416+
"required": [
417+
"repo_path"
418+
],
419+
"type": "object",
420+
"title": "remoteArguments"
421+
},
422+
"annotations": {
423+
"readOnlyHint": true,
424+
"destructiveHint": false,
425+
"idempotentHint": true,
426+
"openWorldHint": false
427+
}
404428
}
405429
]
406430
}

‎src/git/tests/test_protocol.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ async def test_list_tools_names_in_order():
106106
"git_checkout",
107107
"git_show",
108108
"git_branch",
109+
"git_remote",
109110
]
110111

111112

‎src/git/tests/test_remote.py‎

Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
"""Tests for git_remote (#1611): listing remotes without leaking credentials.
2+
3+
The tool's output goes to the model, and a remote URL can carry a credential
4+
(`https://user:token@host/...`), so most of these pin `redact_url`'s rule: the
5+
whole userinfo is redacted except an SSH username, which names an account and
6+
authenticates nothing. The protocol tests drive the real server through
7+
`conftest.connect`; the unit tests cover URL shapes git would not let a test
8+
configure as easily.
9+
"""
10+
11+
from pathlib import Path
12+
from typing import Any
13+
from unittest import mock
14+
15+
import git
16+
import pytest
17+
18+
from mcp_server_git import server
19+
from mcp_server_git.server import git_remote, redact_url
20+
21+
from conftest import connect, make_repo, text_result, tool_error, wire
22+
23+
24+
async def call_remote(repository: Path | None, repo: git.Repo) -> dict[str, Any]:
25+
assert repo.working_dir is not None
26+
async with connect(repository) as session:
27+
return wire(
28+
await session.call_tool("git_remote", {"repo_path": repo.working_dir})
29+
)
30+
31+
32+
async def test_no_remotes(repo: git.Repo):
33+
assert await call_remote(None, repo) == text_result("No remotes configured")
34+
35+
36+
async def test_lists_fetch_and_push_urls(repo: git.Repo):
37+
repo.create_remote("origin", "https://example.com/org/repo.git")
38+
repo.create_remote("upstream", "[email protected]:org/repo.git")
39+
repo.git.remote("set-url", "--push", "upstream", "/srv/mirror.git")
40+
assert await call_remote(None, repo) == text_result(
41+
"origin\thttps://example.com/org/repo.git (fetch)\n"
42+
"origin\thttps://example.com/org/repo.git (push)\n"
43+
"upstream\t[email protected]:org/repo.git (fetch)\n"
44+
"upstream\t/srv/mirror.git (push)"
45+
)
46+
47+
48+
async def test_credentials_are_redacted_over_the_wire(repo: git.Repo):
49+
repo.create_remote("origin", "https://user:[email protected]/org/repo.git")
50+
repo.create_remote("fork", "https://[email protected]/me/repo.git")
51+
repo.git.remote("set-url", "--push", "fork", "ssh://git:[email protected]/r")
52+
result = await call_remote(None, repo)
53+
assert result == text_result(
54+
"fork\thttps://<redacted>@github.com/me/repo.git (fetch)\n"
55+
"fork\tssh://git:<redacted>@example.com/r (push)\n"
56+
"origin\thttps://<redacted>@example.com/org/repo.git (fetch)\n"
57+
"origin\thttps://<redacted>@example.com/org/repo.git (push)"
58+
)
59+
text = result["content"][0]["text"]
60+
for secret in ("s3cret-token", "ghp_abc123", "hunter2"):
61+
assert secret not in text
62+
63+
64+
async def test_respects_repository_confinement(tmp_path: Path, repo: git.Repo):
65+
# --repository must name a real repository, or serve() exits before the
66+
# client connects.
67+
allowed_repo = make_repo(tmp_path / "allowed")
68+
allowed_repo.close()
69+
allowed = (tmp_path / "allowed").resolve()
70+
assert await call_remote(allowed, repo) == tool_error(
71+
"git_remote",
72+
f"Repository path '{repo.working_dir}' is outside the allowed repository "
73+
f"'{allowed}'",
74+
)
75+
76+
77+
async def test_not_a_repository(tmp_path: Path):
78+
plain = tmp_path / "plain"
79+
plain.mkdir()
80+
async with connect(None) as session:
81+
result = wire(await session.call_tool("git_remote", {"repo_path": str(plain)}))
82+
assert result == tool_error("git_remote", str(plain))
83+
84+
85+
@pytest.mark.parametrize(
86+
("url", "expected"),
87+
[
88+
# HTTP(S): a token is as often the username as the password.
89+
(
90+
"https://user:[email protected]/r.git",
91+
"https://<redacted>@example.com/r.git",
92+
),
93+
("https://[email protected]/r.git", "https://<redacted>@example.com/r.git"),
94+
("http://u:[email protected]:8080/r", "http://<redacted>@example.com:8080/r"),
95+
("HTTPS://u:[email protected]/r", "HTTPS://<redacted>@example.com/r"),
96+
# Any other scheme with userinfo is treated the same way.
97+
("ftps://u:[email protected]/r", "ftps://<redacted>@example.com/r"),
98+
# A password holding an unescaped '@': the userinfo runs to the last
99+
# '@' before the first '/', so none of it survives.
100+
("https://u:p@[email protected]/r", "https://<redacted>@example.com/r"),
101+
# No path at all.
102+
("https://u:[email protected]", "https://<redacted>@example.com"),
103+
# SSH: the username stays, a password does not.
104+
("ssh://[email protected]/r.git", "ssh://[email protected]/r.git"),
105+
("ssh://git:[email protected]/r.git", "ssh://git:<redacted>@example.com/r.git"),
106+
("git+ssh://me:[email protected]/r", "git+ssh://me:<redacted>@example.com/r"),
107+
("SSH+GIT://[email protected]/r", "SSH+GIT://[email protected]/r"),
108+
# No userinfo: unchanged.
109+
("https://example.com/r.git", "https://example.com/r.git"),
110+
("https://example.com/path@x/r.git", "https://example.com/path@x/r.git"),
111+
("[email protected]:org/r.git", "[email protected]:org/r.git"),
112+
("/srv/repos/r.git", "/srv/repos/r.git"),
113+
("file:///srv/repos/r.git", "file:///srv/repos/r.git"),
114+
],
115+
)
116+
def test_redact_url(url: str, expected: str):
117+
assert redact_url(url) == expected
118+
119+
120+
def test_unrecognized_line_is_redacted_whole(repo: git.Repo):
121+
# `git remote -v` always prints `<name>\t<url> (<direction>)`; a line in any
122+
# other shape is still redacted rather than passed through.
123+
with mock.patch.object(
124+
server,
125+
"_git_text",
126+
return_value="https://u:[email protected]/r\norigin\tno-direction\n",
127+
):
128+
assert git_remote(repo) == (
129+
"https://<redacted>@example.com/r\norigin\tno-direction"
130+
)

0 commit comments

Comments
 (0)