Skip to main content
Glama
RepoPatch
by kitepon
README.md
# RepoPatch (`repopatch-mcp`)

[![CI](https://github.com/kitepon/repopatch-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/kitepon/repopatch-mcp/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
[![Node.js >= 20](https://img.shields.io/badge/node-%3E%3D20-brightgreen.svg)](package.json)
[![Release](https://img.shields.io/github/v/release/kitepon/repopatch-mcp)](https://github.com/kitepon/repopatch-mcp/releases)
[![Glama](https://glama.ai/mcp/servers/kitepon/repopatch-mcp/badge)](https://glama.ai/mcp/servers/kitepon/repopatch-mcp)

**Least-privilege write-scoped GitHub MCP server (5 tools) for targeted diff commits on feature branches and draft PRs — no full-file rewrites.**

> **Part of the [kitepon](https://kitepon.dev) GitHub MCP pair:**
> **[RepoPeek](https://github.com/kitepon/repopeek-mcp)** (read-only, 5 tools) + **RepoPatch** (write-scoped diff commits & draft PRs, 5 tools — this repo).
> Split read and write into two small, auditable servers so AI agents get read access everywhere and write access only when editing.

---

## Why RepoPatch?

1. **Large-file reliability (no output truncation):** Official GitHub MCP tools (`push_files`, `create_or_update_file`) require the LLM to emit the **entire file** on every edit — hitting model output caps on large files or forcing multiple fragmented pushes. RepoPatch accepts targeted `old_text -> new_text` diffs, verifies each edit matches **uniquely (exactly once)** on the server, and commits multiple edits, creations, and deletions atomically in **one** Git Data API commit.
2. **Blast-radius isolation:** RepoPatch hard-refuses direct pushes to `main`, `master`, and the repository's live `default_branch`, hard-codes `force: false`, blocks secret paths, caps per-commit file count and size, and opens pull requests as **draft by default**.

### Official GitHub MCP vs. RepoPeek + RepoPatch

| Capability | Official GitHub MCP | RepoPeek + RepoPatch |
|---|---|---|
| Tool surface | ~50+ tools in one server | **5 read** (RepoPeek) + **5 write** (RepoPatch) |
| Read / write token split | Shared token | **Strictly separated** (read-only PAT vs. write-scoped PAT) |
| Large-file edits | Full-file `push_files` / `create_or_update_file` (truncates on LLM output limits) | **Server-side diff patching** (`old_text -> new_text`, atomic 1-commit push) |
| Default-branch & force-push safety | Relies on prompt discipline / repo rules | **Hard-refused in server** (`main`/`master`/`default_branch`, `force: false`, secret-path blocks) |
| Plain-text web connectors (Gemini, etc.) | Mixed `resource` / JSON blocks | **100% plain `type: "text"`** results |

### How the pair fits together

```mermaid
flowchart LR
  Client["AI Client (Gemini, Claude, Cursor, Codex)"]
  Peek["RepoPeek (5 read tools)<br/>bare git · plain text"]
  Patch["RepoPatch (5 write tools)<br/>branch · atomic diff · draft PR"]
  GH["GitHub (repos / Git Data API)"]

  Client -- "list / read / grep" --> Peek
  Peek -- "read-only PAT or public clone" --> GH
  Client -- "create_branch / patch_files / PR" --> Patch
  Patch -- "write-scoped PAT (non-default only)" --> GH
```

---

## Tools (5 write-scoped)

| Tool | Purpose |
|---|---|
| `list_repos` | List repositories allowed by `ALLOWED_REPOS` |
| `create_branch` | Create a new non-default branch from a ref (default: repository `default_branch`) |
| `patch_files` | Atomically edit (`old_text -> new_text`, unique-match verified), create, or delete multiple files in **one** commit (`force: false`) |
| `create_pull_request` | Open a pull request (`draft: true` by default) |
| `update_pull_request` | Update an existing pull request's title, body, or base branch |

### Example tool call (`patch_files`)

```json
{
  "name": "patch_files",
  "arguments": {
    "repo": "myorg/myrepo",
    "branch": "feat/fix-timeout",
    "message": "Increase request timeout and add test",
    "changes": [
      {
        "path": "src/client.ts",
        "action": "edit",
        "edits": [
          {
            "old_text": "const TIMEOUT_MS = 5000;",
            "new_text": "const TIMEOUT_MS = 15000;"
          }
        ]
      },
      {
        "path": "src/client.test.ts",
        "action": "create",
        "content": "import assert from 'node:assert/strict';\nassert.ok(true);\n"
      }
    ]
  }
}
```

```text
Committed 2 files to myorg/myrepo@feat/fix-timeout
Commit: 4a106befc15fa50fbedb840ba6f3e179573a44a0
Message: Increase request timeout and add test
Changes:
- M src/client.ts (+1/-1 lines, 1 edit)
- A src/client.test.ts (+2 lines)
Compare: https://github.com/myorg/myrepo/compare/main...feat%2Ffix-timeout
```

Full specs: [tool contract](docs/tools.md) · [architecture & data flow](docs/architecture.md).

---

## Quick start (Docker Compose)

```sh
git clone https://github.com/kitepon/repopatch-mcp.git && cd repopatch-mcp

TOKEN=$(openssl rand -base64 32)          # Bearer token; save in your password manager
cat > docker-compose.override.yml <<EOF
services:
  repopatch-mcp:
    environment:
      - ALLOWED_REPOS=myorg/myrepo
      - GITHUB_TOKEN=github_pat_...       # Fine-grained PAT: Contents (R/W) + Pull requests (R/W)
      - REPOPATCH_TOKEN_SHA256=$(printf %s "$TOKEN" | sha256sum | cut -d' ' -f1)
      - REPOPATCH_STORE_KEY=$(openssl rand -base64 32)
EOF

docker compose up -d --build
curl -s http://127.0.0.1:39231/health     # {"status":"ok","service":"repopatch-mcp"}
```

The server listens on `127.0.0.1:39231` and refuses to start without `REPOPATCH_TOKEN_SHA256`. Only the token's SHA-256 goes into config; clients send `Authorization: Bearer $TOKEN`. See [docker-compose.override.yml.example](docker-compose.override.yml.example) for all options.

### Without Docker (Node.js 20+)

```sh
npm ci && npm run build
export ALLOWED_REPOS=myorg/myrepo
export GITHUB_TOKEN=github_pat_...
export REPOPATCH_TOKEN_SHA256=$(printf %s "$TOKEN" | sha256sum | cut -d' ' -f1)
export REPOPATCH_STORE_KEY=$(openssl rand -base64 32)
npm start   # http://0.0.0.0:39231/mcp
```

---

## Connect an MCP client

### Static Bearer header (Cursor, Claude Code, Codex, generic Streamable HTTP clients)

```json
{
  "mcpServers": {
    "repopatch": {
      "url": "https://repopatch.example.com/mcp",
      "headers": {
        "Authorization": "Bearer YOUR_MCP_TOKEN"
      }
    }
  }
}
```

### Web connectors with OAuth 2.1 (Gemini, etc.)

1. Deploy RepoPatch behind HTTPS and set `REPOPATCH_PUBLIC_URL=https://<your-host>`.
2. Add a custom MCP connector with URL `https://<your-host>/mcp`.
3. The client registers via DCR + PKCE S256 and opens `/authorize` (protected by Cloudflare Access when configured, or by the Bearer token form).
4. RepoPatch advertises server-level MCP `instructions` and tool descriptions guiding clients to prefer `patch_files` over GitHub MCP's `push_files` / `create_or_update_file` for repositories in `ALLOWED_REPOS`.

---

## Configuration

| Variable | Default | Meaning |
|---|---|---|
| `REPOPATCH_TOKEN_SHA256` | required | SHA-256 hex of the shared Bearer token (exits without it) |
| `ALLOWED_REPOS` | empty (refuse all) | Comma-separated `owner/name` or `owner/*` (case-insensitive) |
| `GITHUB_TOKEN` | unset | Direct-mode fine-grained PAT (*Contents: R/W*, *Pull requests: R/W*) |
| `GITHUB_API_BASE` | `https://api.github.com` | GitHub REST API origin |
| `REPOPATCH_PUBLIC_URL` | `http://localhost:<PORT>` | Public origin advertised in OAuth metadata |
| `PORT` | `39231` | HTTP port |
| `REPOPATCH_DATA_DIR` | `./data` (`/data` in Docker) | Encrypted OAuth store (`oauth.enc`) and optional wrapped key blob |
| `REPOPATCH_STORE_KEY` | unset | Base64 of 32 bytes; encrypts the OAuth store when no auth module is used |
| `REPOPATCH_SECRET_PATTERNS` | empty | Extra comma-separated secret-file globs (`*`, `?`) |
| `REPOPATCH_MAX_FILES_PER_COMMIT` | `20` | Max files per `patch_files` call |
| `REPOPATCH_MAX_FILE_BYTES` | `524288` | Max single-file size in bytes (512 KiB) |
| `REPOPATCH_MAX_TOTAL_BYTES` | `2097152` | Max total commit payload in bytes (2 MiB) |
| `REPOPATCH_ACCESS_TEAM_DOMAIN` | unset | Cloudflare Access team domain (set together with `REPOPATCH_ACCESS_AUD`) |
| `REPOPATCH_ACCESS_AUD` | unset | Cloudflare Access application AUD |
| `REPOPATCH_ACCESS_EMAILS` | empty | Optional comma-separated e-mail allow-list |
| `REPOPATCH_AUTH_SOCKET` | unset | Optional auth-mediation caller socket (zero-PAT container mode + wrapped store key) |
| `REPOPATCH_WRAP_KEY_NAME` | unset | Auth-mediation wrap key name |
| `REPOPATCH_MODULE_ITEMS` | empty | Comma-separated `owner=item` for auth-mediation module mode |

## Security model

- **No default-branch writes:** `patch_files` hard-refuses `main`, `master`, and the repository's live `default_branch`; `updateRef` hard-codes `force: false`.
- **Atomic batch validation:** every file is fetched, validated, and patched in memory before any write API call; any mismatch or violation aborts with zero writes.
- **Allowlist:** empty `ALLOWED_REPOS` refuses all repositories.
- **Secret-path protection:** `.env`, `.env.*`, `*.pem`, `*.key`, `*secret*`, `id_rsa*`, `id_ed25519*`, `*.p12`, `*.pfx`, `credentials.json`, plus `REPOPATCH_SECRET_PATTERNS` are refused for `create`, `edit`, and `delete`.
- **Authentication:** `/mcp` requires `Authorization: Bearer` (only SHA-256 stored); OAuth 2.1 tokens live in an AES-256-GCM encrypted store; `/authorize` supports Cloudflare Access JWT (fail closed).

See [SECURITY.md](SECURITY.md) to report vulnerabilities.

## Development

```sh
npm ci
npm run lint
npm run typecheck
npm run build
npm test
```

See [CONTRIBUTING.md](CONTRIBUTING.md) before opening a pull request.

## Directory listings

- [Glama MCP Directory](https://glama.ai/mcp/servers/kitepon/repopatch-mcp)

## License

[MIT](LICENSE) — built by [kitepon.dev](https://kitepon.dev).