DEV Community

Lycore Development
Lycore Development

Posted on

mcp-server-git Leaked Env Vars Through Its Errors. Test Your MCP Tools

On November 27 the maintainers of the official Model Context Protocol servers published an advisory for mcp-server-git, the reference Git server a lot of people wire into Claude Code, Cursor and other agent clients. The bug is small and a bit embarrassing in the way the best lessons are: if a tool call passed $NAME as the repository path, the error message came back with the value of that environment variable in it.

It is rated Moderate, the repository confinement held, and the fix (2026.11.27) is out. I still think it is one of the more useful MCP bugs of the year, because nothing about it is specific to Git. It is three ordinary habits lined up in a row, and I'd bet a lot of home-grown MCP servers have at least two of them.

So I reproduced it, read the patch, and then wrote a small canary check you can point at your own tool functions. Everything below was run on Python 3.13.5 with mcp-server-git 2026.11.18 (vulnerable), 2026.11.27 (fixed) and GitPython 3.2.1.

What the advisory says

The full write-up is in the GHSA-f33v-89w7-f9vc advisory on the modelcontextprotocol/servers repository. The short version:

  • Every tool that takes repo_path opened the repository with git.Repo(Path(repo_path)).
  • GitPython's Repo.__init__ has expand_vars=True by default, so it runs os.path.expandvars on the path. It warns that this is deprecated "for security reasons", and then does it anyway.
  • When the expanded path doesn't exist, GitPython raises NoSuchPathError with the expanded path in the message.
  • The server returned that message to the client.

So a repo_path of $DEMO_SECRET or ${DEMO_SECRET} returned the value of DEMO_SECRET from the server process. Who controls repo_path? The model. And who can steer the model? Anyone who can get text in front of it: a README, an issue, a web page it was asked to summarise.

The advisory notes that the bug was found by an MCP fuzzer called mcp-wallfacer, which plants a random canary in the server's environment and flags any response that contains it. That idea is the most reusable part of this whole story, and I come back to it below.

Reproducing it in about 40 lines

First, plain GitPython, no MCP involved:

import os, warnings
import git

os.environ["DEMO_SECRET"] = "demo-secret-value-123"
warnings.simplefilter("always")

for p in ["$DEMO_SECRET", "${DEMO_SECRET}", "%DEMO_SECRET%"]:
    try:
        git.Repo(p)
    except Exception as e:
        print(f"{p!r:18} -> {type(e).__name__}: {e}")

try:
    git.Repo("$DEMO_SECRET", expand_vars=False)
except Exception as e:
    print(f"expand_vars=False  -> {type(e).__name__}: {e}")
Enter fullscreen mode Exit fullscreen mode

Output (paths shortened, and the warning is printed once per call):

UserWarning: The use of environment variables in paths is deprecated
for security reasons and may be removed in the future!!
'$DEMO_SECRET'     -> NoSuchPathError: ~/demo/demo-secret-value-123
'${DEMO_SECRET}'   -> NoSuchPathError: ~/demo/demo-secret-value-123
'%DEMO_SECRET%'    -> NoSuchPathError: ~/demo/%DEMO_SECRET%
expand_vars=False  -> NoSuchPathError: ~/demo/$DEMO_SECRET
Enter fullscreen mode Exit fullscreen mode

On Linux %NAME% stays literal, because posixpath.expandvars only understands $ forms. On Windows, ntpath.expandvars handles %NAME% too, so a Windows-hosted server has one more spelling to worry about.

Then the real server. This script speaks MCP over stdio: initialize, then three git_status calls.

import json, os, subprocess, sys

repo = os.path.abspath("repo")             # an empty `git init` repo
env = dict(os.environ, DEMO_SECRET="demo-secret-value-123")
p = subprocess.Popen(
    [sys.executable, "-m", "mcp_server_git", "--repository", repo],
    cwd=repo, env=env, text=True,
    stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
)

def send(msg):
    p.stdin.write(json.dumps(msg) + "\n"); p.stdin.flush()

def recv():
    return json.loads(p.stdout.readline())

send({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {
    "protocolVersion": "2025-06-18", "capabilities": {},
    "clientInfo": {"name": "probe", "version": "0"}}})
recv()
send({"jsonrpc": "2.0", "method": "notifications/initialized"})

for i, arg in enumerate(["$DEMO_SECRET", "${DEMO_SECRET}", repo], start=2):
    send({"jsonrpc": "2.0", "id": i, "method": "tools/call",
          "params": {"name": "git_status", "arguments": {"repo_path": arg}}})
    r = recv()["result"]
    text = r["content"][0]["text"].replace(repo, "<repo>").splitlines()[0]
    print(f"{arg.replace(repo, '<repo>'):16} isError={r.get('isError')}  {text}")
p.terminate()
Enter fullscreen mode Exit fullscreen mode

On 2026.11.18:

$DEMO_SECRET     isError=True  Error executing tool git_status: <repo>/demo-secret-value-123
${DEMO_SECRET}   isError=True  Error executing tool git_status: <repo>/demo-secret-value-123
<repo>           isError=False  Repository status:
Enter fullscreen mode Exit fullscreen mode

On 2026.11.27, same script:

$DEMO_SECRET     isError=True  Error executing tool git_status: <repo>/$DEMO_SECRET
${DEMO_SECRET}   isError=True  Error executing tool git_status: <repo>/${DEMO_SECRET}
<repo>           isError=False  Repository status:
Enter fullscreen mode Exit fullscreen mode

Notice that --repository didn't help on the old version. As the advisory explains, the server's path check looked at the literal <cwd>/$DEMO_SECRET, which is inside the allowed root, and only then did GitPython expand it. Validate one string, use a different one: that's the classic parser differential, and it's the same family as the Kyverno ? URL bug we wrote about in November.

The patch is more interesting than the bug

The suggested fix in the advisory is one line: git.Repo(path, expand_vars=False). The shipped fix goes further, and the comments in server.py explain why. Two details I didn't know:

  1. GitPython expands a leading ~ in a relative path whatever expand_vars says. The fixed server makes the path absolute first, so there is nothing left to expand.
  2. git.Git, the command wrapper, runs os.path.expandvars on a working directory given as a str, and git.Repo hands it one regardless of how the repo was opened. A pathlib.Path is taken as written. So the fix wraps git.Git in a subclass that converts to Path.

I checked the second one myself, because it sounded too odd to repeat without seeing it:

import os, git
os.environ["DEMO_SECRET"] = "demo-secret-value-123"
g = git.Git("$DEMO_SECRET")
print(g.working_dir)
# ~/demo/demo-secret-value-123
Enter fullscreen mode Exit fullscreen mode

So expand_vars=False alone would have closed the reported path and left a second one sitting underneath it. That's the part I'd remember. When a library has a "helpful" expansion feature, there's often more than one place it applies, and the flag you found only turns off one of them.

Three habits that line up into this bug

Strip out Git and MCP and you get three things that are each fine on their own:

1. Something between your tool argument and the filesystem expands it. GitPython is one example. os.path.expandvars and os.path.expanduser sprinkled in "to be nice to users" is another. And the oldest one is the shell:

repo_path = "$DEMO_SECRET"   # from a tool argument
subprocess.run(f"git -C {repo_path} status", shell=True, capture_output=True, text=True)
# fatal: cannot change to 'demo-secret-value-123': No such file or directory

subprocess.run(["git", "-C", repo_path, "status"], capture_output=True, text=True)
# fatal: cannot change to '$DEMO_SECRET': No such file or directory
Enter fullscreen mode Exit fullscreen mode

Both lines are real output from my run. shell=True with an f-string is a command injection problem first, of course, but even if you "only" wanted to run Git, the shell happily turns a variable reference into a secret and Git prints it back.

2. Your error message echoes the input after processing. Echoing the resolved path is great for a human debugging locally. In an MCP server, the error goes to the model, and from there into a transcript, a log, or a tool call that sends it somewhere else.

3. The server process holds secrets in its environment. It usually does, because that's how MCP client configs pass credentials: an env block per server. One small reassurance I found while reading code: the official Python SDK's stdio client (mcp 2.3.0) doesn't pass your whole shell environment to servers it starts. It inherits only HOME, LOGNAME, PATH, SHELL, TERM and USER on POSIX, plus whatever the server's env sets. Other clients, Docker -e flags, systemd units and your own subprocess.Popen calls may pass everything. Check how yours does it, and don't put a key in a server's environment that the server doesn't need.

Break any one of the three and the bug disappears. The fixed server breaks the first. I'd break all three.

What I checked: a canary test for your own tools

This is the wallfacer idea shrunk to something you can drop into a test suite. Plant a random value in the environment, call every tool function with references to it, and fail if the value shows up in a return value or in an exception message (which is what most servers send back on error).

import os, secrets, warnings
warnings.simplefilter("ignore")

PAYLOADS = ["$CANARY_X", "${CANARY_X}", "%CANARY_X%", "~/$CANARY_X", "logs/${CANARY_X}.txt"]

def check(tools: dict) -> int:
    canary = "cnry-" + secrets.token_hex(6)
    os.environ["CANARY_X"] = canary
    leaks = 0
    for name, fn in tools.items():
        for p in PAYLOADS:
            try:
                out = str(fn(p))
            except Exception as e:          # what your server would send back
                out = f"{type(e).__name__}: {e}"
            if canary in out:
                leaks += 1
                print(f"LEAK  {name:14} {p!r}")
    print(f"{leaks} leaking call(s) across {len(tools)} tool(s)")
    return leaks
Enter fullscreen mode Exit fullscreen mode

I ran it against four small tool functions: two written the way I'd have written them without thinking about this, and two hardened versions.

import os
from pathlib import Path
import git

ROOT = Path("repo").resolve()

def status_naive(repo_path):                     # the pre-2026.11.27 pattern
    return git.Repo(repo_path).git.status()

def read_log_naive(rel):                         # "helpful" expansion
    return (ROOT / os.path.expandvars(os.path.expanduser(rel))).read_text()

class ToolError(Exception):
    pass

def safe_path(arg: str) -> Path:
    if "$" in arg or "%" in arg or arg.startswith("~"):
        raise ToolError("path must be a plain relative path")
    p = (ROOT / arg).resolve()
    if not p.is_relative_to(ROOT):
        raise ToolError("path is outside the allowed root")
    return p

def status_safe(repo_path):
    p = safe_path(repo_path)
    try:
        return git.Repo(p, expand_vars=False).git.status()
    except Exception:
        raise ToolError("not a git repository")  # no path echoed back

def read_log_safe(rel):
    try:
        return safe_path(rel).read_text()
    except FileNotFoundError:
        raise ToolError("file not found")
Enter fullscreen mode Exit fullscreen mode

Result:

LEAK  status_naive   '$CANARY_X'
LEAK  status_naive   '${CANARY_X}'
LEAK  status_naive   '~/$CANARY_X'
LEAK  status_naive   'logs/${CANARY_X}.txt'
LEAK  read_log_naive '$CANARY_X'
LEAK  read_log_naive '${CANARY_X}'
LEAK  read_log_naive '~/$CANARY_X'
LEAK  read_log_naive 'logs/${CANARY_X}.txt'
8 leaking call(s) across 4 tool(s)
Enter fullscreen mode Exit fullscreen mode

Both naive tools leak on every $ form, including one buried in the middle of a path. Both safe tools leak nothing, and status_safe(".") still returns On branch master, so the hardening doesn't break the normal case. %CANARY_X% didn't leak anywhere because I ran this on Linux; on a Windows box I'd expect the naive tools to leak on that one too.

A few notes on the safe version, since it's deliberately blunt:

  • Rejecting $, % and a leading ~ will annoy someone with a directory literally named $tmp. I'm fine with that trade for a tool an LLM drives. If you need those characters, at least make sure nothing downstream expands them, and add them to your canary payloads.
  • The check and the use operate on the same Path object. That's the real fix for the "validated one string, used another" problem.
  • The error messages are fixed strings. Log the detail server-side if you need it; don't hand it to the model.

The canary test is cheap enough to run in CI on every MCP server you write, and it catches more than this one bug. It would flag a tool that dumps os.environ in a debug response, a tool that renders a template with the environment in its context, or a tool that includes request headers in an error.

What to do this week

  1. If you run mcp-server-git, upgrade to 2026.11.27 or later. If you launch it with uvx or a pinned config, check which version actually runs.
  2. Grep your own MCP servers for expandvars, expanduser, shell=True and git.Repo( without expand_vars=False. Each hit is a place where a tool argument can turn into something else.
  3. Look at what your error handler returns. If it's str(exception), you're returning whatever the deepest library decided to put in it.
  4. Trim the environment. Give each MCP server only the credentials it needs, and scope them down: a read-only token for a read-only tool.
  5. Add the canary test. Twenty lines, no dependencies, and it encodes the attacker's move as a regression test.

The broader point is the same one that keeps coming up with agent tooling: once a model is choosing the arguments, every convenience feature in your stack is reachable by whoever can write text the model reads. If you're building your own server and want the basics of tool design first, our guide on how to build an MCP server covers the structure (in TypeScript); the canary idea above ports to any language.

So, for your MCP tools: would you rather reject anything that looks like a variable reference up front, or keep accepting it and make sure nothing downstream ever expands it?

Top comments (0)