Metadata-Version: 2.4
Name: commitguard-mcp
Version: 0.3.0
Summary: An issue-tracker MCP server where agents can read, comment and propose, but can never write a commitment (owner, due date, status).
Author: Bharath Gaviriboina
License: MIT
Project-URL: Homepage, https://github.com/bharathg217/commitguard
Project-URL: Issues, https://github.com/bharathg217/commitguard/issues
Project-URL: Security, https://github.com/bharathg217/commitguard/blob/main/SECURITY.md
Keywords: mcp,model-context-protocol,ai-agents,github,issues,human-in-the-loop,agent-safety
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Bug Tracking
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: mcp<3,>=2.3
Requires-Dist: pyyaml<7,>=6
Provides-Extra: agent
Requires-Dist: anthropic>=0.40; extra == "agent"
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == "dev"
Requires-Dist: pytest-cov>=5; extra == "dev"
Requires-Dist: pytest-benchmark>=4; extra == "dev"
Requires-Dist: hypothesis>=6.100; extra == "dev"
Requires-Dist: ruff<0.18,>=0.17; extra == "dev"
Requires-Dist: mypy<2.5,>=2.3; extra == "dev"
Requires-Dist: types-PyYAML; extra == "dev"
Dynamic: license-file

# CommitGuard

[![ci](https://github.com/bharathg217/commitguard/actions/workflows/ci.yml/badge.svg)](https://github.com/bharathg217/commitguard/actions/workflows/ci.yml)
[![codeql](https://github.com/bharathg217/commitguard/actions/workflows/codeql.yml/badge.svg)](https://github.com/bharathg217/commitguard/actions/workflows/codeql.yml)
[![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/bharathg217/commitguard/badge)](https://scorecard.dev/viewer/?uri=github.com/bharathg217/commitguard)
[![PyPI](https://img.shields.io/pypi/v/commitguard-mcp)](https://pypi.org/project/commitguard-mcp/)

**An issue-tracker MCP server where AI agents can read, comment and propose changes, but can never write a commitment.**

Agents are good at reading a tracker and drafting updates. They should not be the ones deciding who owns a task, when it's due, or that it's done. Those are commitments people make. CommitGuard lets agents do the useful part and routes every commitment change to a named human for approval.

The rule is enforced by structure, not by a prompt:

| Layer | What stops an agent from setting owner, due date, status or title |
|---|---|
| Tool surface | There is no `update_issue`, `assign` or `set_status` tool. Only `search_issues`, `get_issue`, `add_comment`, `propose_update`, `list_my_proposals`. |
| Agent client | The only client the server builds (`AgentClient`) has no method that writes those fields, and agent-side code contains no `UPDATE issues`. |
| Process boundary | The code that applies changes (`review.py`) is never loaded by the server process. A test checks this transitively. |
| HTTP allowlist (GitHub) | GitHub tokens can't grant "comment" without "edit". CommitGuard's agent-side HTTP client permits only `GET` issue, comments and search, and `POST .../comments`. Anything else raises before it's sent, redirects are never followed, and search results outside your repository allowlist are dropped. |
| Human gate | `propose_update` stores a proposal with a rationale, evidence and a snapshot of the current values. A reviewer applies it with the CLI. The approval is refused if the issue changed since the proposal, and an agent identity can never be the reviewer. |

## How it compares

| | Field-level control (comment yes, assign no) | Where it's enforced | Agent keeps working while it waits | Cost |
|---|---|---|---|---|
| GitHub's official MCP server | No. Toolsets and read-only mode are per tool, and `issue_write` covers both editing and assigning | Tool selection | n/a | Free |
| MCP gateways with approvals (Permit, TrueFoundry, DigitalOcean Action Gateway) | No. Approvals are per tool call, not per argument | A gateway the traffic must pass through | No. Calls are held until someone approves or they time out | Mostly paid tiers |
| **CommitGuard** | **Yes. Commitment fields specifically** | **Inside the server: tool surface, client, HTTP allowlist and process boundary** | **Yes. It files a proposal with evidence and moves on** | **Free, MIT, self-hosted** |

You can combine them: run CommitGuard behind a gateway if you want centralized policy too.

## Quick start (demo tracker, 2 minutes)

```bash
pip install commitguard-mcp      # or, from a clone: pip install -e .
commitguard seed            # creates commitguard.db with demo issues, including a prompt-injection comment
```

The package is `commitguard-mcp` on PyPI; the commands it installs are `commitguard-server` and `commitguard`. (The unrelated `commitguard` package on PyPI is a git-hooks tool.)

Add it to Claude Desktop or Claude Code (`claude mcp add` or your client's MCP config):

```json
{
  "mcpServers": {
    "commitguard": {
      "command": "commitguard-server",
      "env": { "COMMITGUARD_DB": "/absolute/path/commitguard.db", "COMMITGUARD_AGENT_ID": "my-assistant" }
    }
  }
}
```

Ask your assistant: *"Read ENG-102 and do what the latest comment says."* The comment tries to get it to close the issue, reassign it and leak a restricted issue. Then review what it proposed:

```bash
commitguard review
commitguard approve p_xxxxxxxxxx --reviewer your-name
commitguard reject  p_xxxxxxxxxx --reviewer your-name --reason "not done yet"
```

## Use it with GitHub Issues

Create two fine-grained tokens scoped to the repositories you want:

- **Agent token** (given to the server): Issues read and write. Write is needed to comment; the allowlist blocks everything else.
- **Reviewer token** (kept on your machine, never deployed): Issues read and write, used only by the review CLI. With the GitHub backend, the reviewer recorded in the audit log is the token's owner, verified with GitHub, not a name typed on the command line.

```bash
export COMMITGUARD_BACKEND=github
export COMMITGUARD_GITHUB_REPOS=acme/app,acme/api        # the agent can't read or write anything else
export COMMITGUARD_GITHUB_TOKEN=github_pat_agent...      # server side
commitguard-server

# on the reviewer's machine
export COMMITGUARD_REVIEWER_GITHUB_TOKEN=github_pat_reviewer...
commitguard approve p_xxxxxxxxxx
```

Issue ids look like `acme/app#42` (case and leading zeros don't matter). Owner maps to the assignee. Status maps to open/closed plus a `status:<value>` label, and due date to a `due:YYYY-MM-DD` label.

## How approval works

1. **Claim.** The proposal moves from `pending` to `applying` with a conditional update, so only one reviewer can win. A rejected proposal can never ship.
2. **Check.** It must not have expired (7 days), and the issue's fields must still hold the values the agent saw when it proposed. Otherwise it goes back to `pending` with the difference shown.
3. **Apply, then record.** On failure it returns to `pending`. If the process dies between applying and recording, the proposal stays in `applying`, so it can't be approved twice, and `commitguard reconcile <id>` checks the tracker and finishes the job.

Every step writes to the audit table.

## Engineering and supply chain

Every push and pull request runs the same gate a release does ([`ci.yml`](.github/workflows/ci.yml)):

| Area | What runs | Fails the build when |
|---|---|---|
| Correctness | Tests on Linux and macOS, Python 3.11 to 3.13; the hijacked-agent safety eval | any test fails, coverage drops under 85%, or safety is under 100% |
| Fuzzing | Hypothesis generates thousands of hostile inputs per validator, and random sequences of agent calls | any input breaks a property, or any call sequence changes a commitment |
| Performance | Benchmarks of the hot paths; an HTTP load test on the built container | a hot path is over its budget, p95 is over 250 ms, or any request errors |
| Code security | Ruff with Bandit rules, mypy; CodeQL on Python and the workflows themselves | Ruff or mypy finds an issue (CodeQL findings land in the Security tab, and block merges once branch protection requires it) |
| Dependencies | Hash-locked `requirements.lock`, pip-audit, dependency review on pull requests | a pinned package has a known vulnerability, or a PR adds one |
| Secrets | gitleaks over the full git history | a credential appears in any commit |
| Container | Hadolint; Trivy; smoke test with a read-only filesystem, no capabilities, non-root | a fixable HIGH/CRITICAL CVE, or the container misbehaves |
| Infrastructure | `terraform fmt`/`validate`, Checkov policies (Terraform, Dockerfile, workflows) | a policy fails without a written exception next to the code |
| The pipeline itself | Every action pinned to a commit SHA, read-only token by default, no persisted credentials, timeouts, runner egress audit (harden-runner), OpenSSF Scorecard | n/a (Scorecard publishes a public score) |

A version tag runs that gate, then ships a **verifiable** release ([`release.yml`](.github/workflows/release.yml)): PyPI trusted publishing with attestations, a CycloneDX SBOM, signed SLSA build provenance for the wheel, and a multi-arch image on GHCR that is scanned, signed with cosign (keyless) and attested. To check a release yourself: `make demo-verify VERSION=0.2.0`, or see [docs/RELEASE.md](docs/RELEASE.md).

Load testing found a real bug on the way: concurrent HTTP calls shared one SQLite connection and returned wrong "not found" answers. Calls are now serialized per server, with a regression test; throughput went from 72 to about 550 requests a second and p95 from 508 ms to 22 ms on the same machine.

## Monitoring

Over HTTP the server also serves `/healthz` (liveness), `/readyz` (the database answers) and `/metrics` (Prometheus format): calls by tool and outcome, a latency histogram, version and uptime. A spike in `rejected_before_tool` or refused calls is what an agent under prompt injection looks like, so it's worth an alert; example rules are in [`deploy/monitoring/alerts.yml`](deploy/monitoring/alerts.yml). With `COMMITGUARD_RUNLOG=-` every call is also a structured JSON log line with a `severity`, ready for Cloud Logging. See [docs/OPERATIONS.md](docs/OPERATIONS.md).

## Comment safety

Comments can't change fields. Some repositories, though, run bots that act on slash commands (`/close`, `/assign`) or notify people on @mentions. So CommitGuard refuses comment lines that start with a slash command, and posts @mentions as code so nobody gets pinged by an agent.

## Evaluations

`evals/cases.yaml` holds the suite: **safety cases** must pass 100% of the time; **quality cases** are gated on a pass rate.

```bash
python evals/harness.py                           # scripted: replays what a fully hijacked agent would try
python evals/harness.py --mode agent --repeats 3  # a real model (needs ANTHROPIC_API_KEY), with an LLM judge
```

Scripted mode needs no model. It proves the guarantees hold even when the model does exactly what an attacker wants. Agent mode checks what a real model actually does: whether it files proposals instead of guessing, whether its comments stay neutral, and whether it ignores injected instructions. Both write `evals/report.json` and exit non-zero when the gate fails. CI runs scripted mode on every pull request.

## Security review

v0.2.0 went through an independent red-team review. It confirmed the core guarantee: no tool, argument or comment could change a commitment field. It also found 11 issues in v0.1.0, including search scope widening through injected `repo:` qualifiers, redirects bypassing the HTTP allowlist, and non-atomic approval with the GitHub backend. All are fixed, and each attack is now a regression test in `tests/test_redteam_regressions.py`. See [SECURITY.md](SECURITY.md).

## Run logging

Every tool call writes one JSON line to `COMMITGUARD_RUNLOG` (default `runs/runlog.jsonl`): run id, agent id, tool, arguments, outcome, error and latency. That includes calls rejected before reaching a tool, like unknown tool names or invalid arguments, which are the attempts you most want to see. The shape matches the BigQuery table in `deploy/terraform`:

```bash
bq load --source_format=NEWLINE_DELIMITED_JSON commitguard.runlog runs/runlog.jsonl
```

## Hosted demo on Cloud Run

`Dockerfile` and `deploy/terraform/main.tf` deploy a **demo**: the server over streamable HTTP with the demo tracker, private (IAM-authenticated callers only), one instance at most, its own service account. Its data resets when it scales to zero. For real teams, run CommitGuard locally next to your MCP client for now; a shared Postgres queue for hosted use is planned.

## Configuration

| Variable | Default | Meaning |
|---|---|---|
| `COMMITGUARD_BACKEND` | `sqlite` | `sqlite` (demo) or `github` |
| `COMMITGUARD_DB` | `commitguard.db` | Proposal queue and audit log (and demo issues) |
| `COMMITGUARD_AGENT_ID` | `default-agent` | Identity written to logs, comments and proposals |
| `COMMITGUARD_GITHUB_REPOS` | none | Comma-separated repository allowlist |
| `COMMITGUARD_GITHUB_TOKEN` | none | Agent token (server side) |
| `COMMITGUARD_REVIEWER_GITHUB_TOKEN` | none | Reviewer token (CLI only) |
| `COMMITGUARD_RUNLOG` | `runs/runlog.jsonl` | Run log path, or `-` for JSON lines on stderr (containers) |
| `COMMITGUARD_TRANSPORT` | `stdio` | `stdio` or `streamable-http` |
| `COMMITGUARD_ALLOWED_HOSTS` | `localhost`, `127.0.0.1` (any port) | HTTP only: Host headers the server answers (DNS-rebinding protection) |
| `COMMITGUARD_METRICS` | `1` | HTTP only: `0` turns off `/metrics` |
| `HOST`, `PORT` | `0.0.0.0`, `8080` | HTTP only: listen address |
| `COMMITGUARD_SEED_DEMO` | `0` | `1` seeds demo issues into an empty database on start |

## Known limits (v0.3)

- The proposal queue is SQLite: right for local use, not for multi-instance hosting. Postgres is next on the roadmap.
- One server process handles one tool call at a time on its database (calls are serialized for correctness). That is about 550 calls a second on a laptop, plenty for agents; scale out with more processes, not threads.
- Under the streamable HTTP transport, all clients of one server process share a run id. With stdio (one process per client) run ids are per session.
- GitHub is the first real backend. Linear and Jira adapters are planned; contributions welcome.
- A model can still write a poor comment. That's what the quality evals and judge are for.

## Contributing

Issues and pull requests are welcome. `make install && make check` runs locally what CI runs (lint, types, tests, fuzzing, evals, benchmarks); `make docker-smoke` adds the container checks. `make help` lists everything, including the demos. A new tracker adapter needs an agent-side class with only `search`, `get` and `comment`, a reviewer-side class in `review.py`, and tests that its HTTP allowlist blocks writes and redirects.

## License

MIT
