Skip to main content
Glama
README.md
# mcp-repo-context

A small, zero-runtime-dependency [Model Context Protocol](https://modelcontextprotocol.io/) server that gives a coding agent **read-only, bounded context from a local Git repository**.

It is intentionally narrower than a shell:

- paths are confined to one `--root`
- secret-like and binary files are skipped
- every result has a size/entry/line limit
- git is invoked without a shell
- the server exposes **5 focused tools**, not arbitrary command execution

This is useful when an MCP client needs to understand a repository without being handed the whole filesystem.

## What it is not

This is **not** a sandbox, a code executor, or a replacement for Git. It reads files with the permissions of the user who starts it. Run it under an account with the least privilege you can afford, and keep real credentials out of the repository.

It deliberately does **not** support write operations, shell commands, URL fetching, package installation, or arbitrary binary reads.

## Tools

| Tool | What it returns | Important limits |
|---|---|---|
| `repo_tree` | Sorted, filtered repository tree with file sizes | depth 1-6, up to 2,000 entries |
| `search_text` | Literal text matches with optional context lines | up to 100 configured results; 500 chars/line |
| `read_file` | UTF-8 text with line numbers, byte range, and redaction | 2 MB/file ceiling; 500 chars/line |
| `git_diff` | Unified diff against a validated revision | no shell; 500 lines; 20 paths |
| `project_summary` | File count, extensions, largest files, detected README/tests/CI signals | read-only metadata |

All tools are exposed through MCP `tools/list` and `tools/call`.

## Security model

The server applies several independent checks:

1. **Root confinement** — absolute paths, drive-letter paths, and `..` components are rejected before resolution. The resolved path must remain under `--root`.
2. **Symlink refusal** — symlinked files and directories are not followed or read.
3. **Secret filtering** — `.env` files (except `.env.example`/`.sample`/`.template`), private-key files, `.ssh`, `.aws`, `.gnupg`, `.docker`, common credential files, and key/keystore suffixes are skipped.
4. **Redaction** — output is best-effort redacted for private keys, GitHub tokens, AWS access keys, bearer tokens, URL credentials, and common `password=`, `token:`, and `api_key=` assignments.
5. **Bounded output** — file bytes, line lengths, result counts, tree depth, tree entries, diff lines, and total output characters have hard caps.
6. **No shell** — `git_diff` uses an argument list and validates the revision string. It checks that the revision resolves to a commit before running the diff.

Redaction is defense in depth, not a guarantee. A secret that does not match a known pattern can still be returned. Use repository permissions and secret-management tools as the primary control.

## Requirements

- Python **3.8+**
- Git on `PATH` only if you use `git_diff`
- No third-party runtime packages

## Quick start

From this checkout:

```powershell
python -m mcp_repo_context --root C:\path\to\your\repo
```

Or install the console script:

```powershell
python -m pip install -e . --no-build-isolation
mcp-repo-context --root C:\path\to\your\repo
```

`--no-build-isolation` keeps the install working on older Python 3.8/pip setups that do not fetch a newer `setuptools` into a temporary build environment.

The process speaks newline-delimited JSON-RPC over stdin/stdout. Logs go to stderr so stdout stays protocol-clean.

### Try it without an MCP client

On Windows PowerShell:

```powershell
Get-Content .\examples\session.jsonl | python -m mcp_repo_context --root .
```

On macOS/Linux:

```bash
python -m mcp_repo_context --root . < examples/session.jsonl
```

The session initializes, lists tools, and calls `project_summary`.

### Claude Desktop configuration

Add this to `claude_desktop_config.json` (Windows: `%APPDATA%\Claude\claude_desktop_config.json`):

```json
{
  "mcpServers": {
    "repo-context": {
      "command": "python",
      "args": [
        "-m",
        "mcp_repo_context",
        "--root",
        "C:\\path\\to\\your\\repo"
      ],
      "env": {
        "PYTHONIOENCODING": "utf-8"
      }
    }
  }
}
```

Use the absolute path to the Python interpreter that has this package installed if `python` is ambiguous. The exact configuration file location varies by client and operating system; check your MCP client's documentation.

Any MCP client that supports stdio servers can use the same command and arguments.

## Example protocol exchange

Request:

```json
{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{}}}
```

Response (abridged):

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "protocolVersion": "2025-06-18",
    "capabilities": {"tools": {"listChanged": false}},
    "serverInfo": {"name": "mcp-repo-context", "version": "0.1.0"}
  }
}
```

Call a tool:

```json
{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"read_file","arguments":{"path":"src/app.py","start_line":1,"end_line":20}}}
```

The result is a normal MCP text content block. Tool-level failures (`unknown tool`, invalid path, binary file, missing Git) set `isError` to `true` and return a short readable message. Parse/validation failures use JSON-RPC error codes (`-32700`, `-32600`, `-32601`, `-32602`).

## Configuration

| Flag | Default | Notes |
|---|---|---|
| `--root` | `.` | Repository boundary; must exist |
| `--max-file-bytes` | `200000` | 1 KB to 2 MB |
| `--max-output-chars` | `24000` | 4,000 to 200,000 |
| `--max-search-results` | `100` | 1 to 200 |
| `--git-executable` | `git` | Useful when Git is not on `PATH` |
| `--log-level` | `WARNING` | `DEBUG`, `INFO`, `WARNING`, or `ERROR` |

## Project layout

```text
mcp_repo_context/
  config.py       settings and bounds
  errors.py       ToolError
  paths.py        root confinement, ignore and secret rules, text reads
  redact.py       best-effort credential redaction
  service.py      the five tools and their JSON schemas
  server.py       MCP stdio loop and JSON-RPC dispatch
  __main__.py     python -m entry point
tests/
  support.py      temporary-repository helpers
  test_paths.py   path, ignore, binary, and secret rules
  test_redact.py  redaction patterns
  test_service.py tool behavior and limits
  test_protocol.py JSON-RPC methods and errors
  test_stdio.py   real subprocess handshake
  test_cli.py     argument parsing
examples/
  mcp_config.json client configuration example
  session.jsonl   raw stdio handshake
setup.py          Python 3.8-compatible packaging shim
pyproject.toml    PEP 517 build configuration
Dockerfile        optional stdio container
SECURITY.md       vulnerability-reporting policy
```

## Tests

```bash
python -m unittest discover -v
```

Current suite: **40 tests** (39 pass + 1 skipped on this Windows machine). The skipped test creates a symlink pointing outside the repository; Windows refused the symlink without Developer Mode/administrator privileges. On Linux/macOS the same test runs.

The end-to-end suite launches the real process, sends a JSON-RPC handshake over stdin, and checks that stdout contains only protocol messages.

CI runs the suite on Python 3.8, 3.9, 3.10, 3.11, and 3.12 via `.github/workflows/tests.yml`.

## Design notes

- **SQLite/vector search was intentionally not added.** This project is about bounded context and MCP behavior; a local text search is enough for the stated surface.
- **No third-party SDK.** Implementing the JSON-RPC framing directly keeps the server easy to audit and run in restricted environments.
- **Secret filtering happens in the file iterator, not only at the tool boundary.** `repo_tree`, `search_text`, and `project_summary` therefore do not enumerate secret files, while `read_file` and `git_diff` still reject them explicitly.
- **Fail closed for paths, fail readable for tools.** Invalid input is an error; a missing optional Git executable is a tool error, not a crash.

## Known limitations

- Text search is literal and line-oriented, not regex, glob, or semantic search.
- There is no authentication, TLS, or remote transport; this is a local stdio process.
- The secret denylist is not exhaustive. A repository can still contain sensitive text in a normal `.md` or `.py` file.
- The symlink test is skipped on Windows when symlink creation is unavailable.
- The server was tested with its own subprocess harness, not against every third-party MCP client.
- A single process serves one client. Multi-client deployment is out of scope.

## License

MIT. See [LICENSE](LICENSE).