commitguard-mcp 0.2.0__tar.gz → 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. {commitguard_mcp-0.2.0/src/commitguard_mcp.egg-info → commitguard_mcp-0.3.0}/PKG-INFO +43 -4
  2. {commitguard_mcp-0.2.0 → commitguard_mcp-0.3.0}/README.md +36 -3
  3. {commitguard_mcp-0.2.0 → commitguard_mcp-0.3.0}/pyproject.toml +42 -2
  4. {commitguard_mcp-0.2.0 → commitguard_mcp-0.3.0}/src/commitguard/__init__.py +1 -1
  5. {commitguard_mcp-0.2.0 → commitguard_mcp-0.3.0}/src/commitguard/cli.py +2 -1
  6. commitguard_mcp-0.3.0/src/commitguard/metrics.py +100 -0
  7. {commitguard_mcp-0.2.0 → commitguard_mcp-0.3.0}/src/commitguard/review.py +2 -1
  8. {commitguard_mcp-0.2.0 → commitguard_mcp-0.3.0}/src/commitguard/runlog.py +24 -5
  9. {commitguard_mcp-0.2.0 → commitguard_mcp-0.3.0}/src/commitguard/server.py +76 -4
  10. {commitguard_mcp-0.2.0 → commitguard_mcp-0.3.0}/src/commitguard/store.py +11 -4
  11. {commitguard_mcp-0.2.0 → commitguard_mcp-0.3.0}/src/commitguard/trackers.py +8 -3
  12. {commitguard_mcp-0.2.0 → commitguard_mcp-0.3.0/src/commitguard_mcp.egg-info}/PKG-INFO +43 -4
  13. {commitguard_mcp-0.2.0 → commitguard_mcp-0.3.0}/src/commitguard_mcp.egg-info/SOURCES.txt +5 -0
  14. commitguard_mcp-0.3.0/src/commitguard_mcp.egg-info/requires.txt +14 -0
  15. commitguard_mcp-0.3.0/tests/test_cli_and_review.py +107 -0
  16. commitguard_mcp-0.3.0/tests/test_fuzz.py +140 -0
  17. {commitguard_mcp-0.2.0 → commitguard_mcp-0.3.0}/tests/test_github_backend.py +12 -0
  18. {commitguard_mcp-0.2.0 → commitguard_mcp-0.3.0}/tests/test_guarantees.py +2 -1
  19. commitguard_mcp-0.3.0/tests/test_http_and_metrics.py +175 -0
  20. commitguard_mcp-0.3.0/tests/test_perf.py +83 -0
  21. commitguard_mcp-0.2.0/src/commitguard_mcp.egg-info/requires.txt +0 -8
  22. {commitguard_mcp-0.2.0 → commitguard_mcp-0.3.0}/LICENSE +0 -0
  23. {commitguard_mcp-0.2.0 → commitguard_mcp-0.3.0}/setup.cfg +0 -0
  24. {commitguard_mcp-0.2.0 → commitguard_mcp-0.3.0}/src/commitguard/demo.py +0 -0
  25. {commitguard_mcp-0.2.0 → commitguard_mcp-0.3.0}/src/commitguard_mcp.egg-info/dependency_links.txt +0 -0
  26. {commitguard_mcp-0.2.0 → commitguard_mcp-0.3.0}/src/commitguard_mcp.egg-info/entry_points.txt +0 -0
  27. {commitguard_mcp-0.2.0 → commitguard_mcp-0.3.0}/src/commitguard_mcp.egg-info/top_level.txt +0 -0
  28. {commitguard_mcp-0.2.0 → commitguard_mcp-0.3.0}/tests/test_redteam_regressions.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: commitguard-mcp
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: An issue-tracker MCP server where agents can read, comment and propose, but can never write a commitment (owner, due date, status).
5
5
  Author: Bharath Gaviriboina
6
6
  License: MIT
@@ -26,10 +26,21 @@ Provides-Extra: agent
26
26
  Requires-Dist: anthropic>=0.40; extra == "agent"
27
27
  Provides-Extra: dev
28
28
  Requires-Dist: pytest>=8; extra == "dev"
29
+ Requires-Dist: pytest-cov>=5; extra == "dev"
30
+ Requires-Dist: pytest-benchmark>=4; extra == "dev"
31
+ Requires-Dist: hypothesis>=6.100; extra == "dev"
32
+ Requires-Dist: ruff<0.18,>=0.17; extra == "dev"
33
+ Requires-Dist: mypy<2.5,>=2.3; extra == "dev"
34
+ Requires-Dist: types-PyYAML; extra == "dev"
29
35
  Dynamic: license-file
30
36
 
31
37
  # CommitGuard
32
38
 
39
+ [![ci](https://github.com/bharathg217/commitguard/actions/workflows/ci.yml/badge.svg)](https://github.com/bharathg217/commitguard/actions/workflows/ci.yml)
40
+ [![codeql](https://github.com/bharathg217/commitguard/actions/workflows/codeql.yml/badge.svg)](https://github.com/bharathg217/commitguard/actions/workflows/codeql.yml)
41
+ [![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/bharathg217/commitguard/badge)](https://scorecard.dev/viewer/?uri=github.com/bharathg217/commitguard)
42
+ [![PyPI](https://img.shields.io/pypi/v/commitguard-mcp)](https://pypi.org/project/commitguard-mcp/)
43
+
33
44
  **An issue-tracker MCP server where AI agents can read, comment and propose changes, but can never write a commitment.**
34
45
 
35
46
  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.
@@ -112,6 +123,30 @@ Issue ids look like `acme/app#42` (case and leading zeros don't matter). Owner m
112
123
 
113
124
  Every step writes to the audit table.
114
125
 
126
+ ## Engineering and supply chain
127
+
128
+ Every push and pull request runs the same gate a release does ([`ci.yml`](.github/workflows/ci.yml)):
129
+
130
+ | Area | What runs | Fails the build when |
131
+ |---|---|---|
132
+ | 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% |
133
+ | 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 |
134
+ | 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 |
135
+ | 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) |
136
+ | Dependencies | Hash-locked `requirements.lock`, pip-audit, dependency review on pull requests | a pinned package has a known vulnerability, or a PR adds one |
137
+ | Secrets | gitleaks over the full git history | a credential appears in any commit |
138
+ | Container | Hadolint; Trivy; smoke test with a read-only filesystem, no capabilities, non-root | a fixable HIGH/CRITICAL CVE, or the container misbehaves |
139
+ | Infrastructure | `terraform fmt`/`validate`, Checkov policies (Terraform, Dockerfile, workflows) | a policy fails without a written exception next to the code |
140
+ | 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) |
141
+
142
+ 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).
143
+
144
+ 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.
145
+
146
+ ## Monitoring
147
+
148
+ 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).
149
+
115
150
  ## Comment safety
116
151
 
117
152
  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.
@@ -153,20 +188,24 @@ bq load --source_format=NEWLINE_DELIMITED_JSON commitguard.runlog runs/runlog.js
153
188
  | `COMMITGUARD_GITHUB_REPOS` | none | Comma-separated repository allowlist |
154
189
  | `COMMITGUARD_GITHUB_TOKEN` | none | Agent token (server side) |
155
190
  | `COMMITGUARD_REVIEWER_GITHUB_TOKEN` | none | Reviewer token (CLI only) |
156
- | `COMMITGUARD_RUNLOG` | `runs/runlog.jsonl` | Run log path |
191
+ | `COMMITGUARD_RUNLOG` | `runs/runlog.jsonl` | Run log path, or `-` for JSON lines on stderr (containers) |
157
192
  | `COMMITGUARD_TRANSPORT` | `stdio` | `stdio` or `streamable-http` |
193
+ | `COMMITGUARD_ALLOWED_HOSTS` | `localhost`, `127.0.0.1` (any port) | HTTP only: Host headers the server answers (DNS-rebinding protection) |
194
+ | `COMMITGUARD_METRICS` | `1` | HTTP only: `0` turns off `/metrics` |
195
+ | `HOST`, `PORT` | `0.0.0.0`, `8080` | HTTP only: listen address |
158
196
  | `COMMITGUARD_SEED_DEMO` | `0` | `1` seeds demo issues into an empty database on start |
159
197
 
160
- ## Known limits (v0.2)
198
+ ## Known limits (v0.3)
161
199
 
162
200
  - The proposal queue is SQLite: right for local use, not for multi-instance hosting. Postgres is next on the roadmap.
201
+ - 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.
163
202
  - 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.
164
203
  - GitHub is the first real backend. Linear and Jira adapters are planned; contributions welcome.
165
204
  - A model can still write a poor comment. That's what the quality evals and judge are for.
166
205
 
167
206
  ## Contributing
168
207
 
169
- Issues and pull requests are welcome. Every change runs the guarantee tests, the red-team regressions and the eval gate. 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.
208
+ 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.
170
209
 
171
210
  ## License
172
211
 
@@ -1,5 +1,10 @@
1
1
  # CommitGuard
2
2
 
3
+ [![ci](https://github.com/bharathg217/commitguard/actions/workflows/ci.yml/badge.svg)](https://github.com/bharathg217/commitguard/actions/workflows/ci.yml)
4
+ [![codeql](https://github.com/bharathg217/commitguard/actions/workflows/codeql.yml/badge.svg)](https://github.com/bharathg217/commitguard/actions/workflows/codeql.yml)
5
+ [![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/bharathg217/commitguard/badge)](https://scorecard.dev/viewer/?uri=github.com/bharathg217/commitguard)
6
+ [![PyPI](https://img.shields.io/pypi/v/commitguard-mcp)](https://pypi.org/project/commitguard-mcp/)
7
+
3
8
  **An issue-tracker MCP server where AI agents can read, comment and propose changes, but can never write a commitment.**
4
9
 
5
10
  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.
@@ -82,6 +87,30 @@ Issue ids look like `acme/app#42` (case and leading zeros don't matter). Owner m
82
87
 
83
88
  Every step writes to the audit table.
84
89
 
90
+ ## Engineering and supply chain
91
+
92
+ Every push and pull request runs the same gate a release does ([`ci.yml`](.github/workflows/ci.yml)):
93
+
94
+ | Area | What runs | Fails the build when |
95
+ |---|---|---|
96
+ | 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% |
97
+ | 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 |
98
+ | 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 |
99
+ | 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) |
100
+ | Dependencies | Hash-locked `requirements.lock`, pip-audit, dependency review on pull requests | a pinned package has a known vulnerability, or a PR adds one |
101
+ | Secrets | gitleaks over the full git history | a credential appears in any commit |
102
+ | Container | Hadolint; Trivy; smoke test with a read-only filesystem, no capabilities, non-root | a fixable HIGH/CRITICAL CVE, or the container misbehaves |
103
+ | Infrastructure | `terraform fmt`/`validate`, Checkov policies (Terraform, Dockerfile, workflows) | a policy fails without a written exception next to the code |
104
+ | 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) |
105
+
106
+ 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).
107
+
108
+ 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.
109
+
110
+ ## Monitoring
111
+
112
+ 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).
113
+
85
114
  ## Comment safety
86
115
 
87
116
  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.
@@ -123,20 +152,24 @@ bq load --source_format=NEWLINE_DELIMITED_JSON commitguard.runlog runs/runlog.js
123
152
  | `COMMITGUARD_GITHUB_REPOS` | none | Comma-separated repository allowlist |
124
153
  | `COMMITGUARD_GITHUB_TOKEN` | none | Agent token (server side) |
125
154
  | `COMMITGUARD_REVIEWER_GITHUB_TOKEN` | none | Reviewer token (CLI only) |
126
- | `COMMITGUARD_RUNLOG` | `runs/runlog.jsonl` | Run log path |
155
+ | `COMMITGUARD_RUNLOG` | `runs/runlog.jsonl` | Run log path, or `-` for JSON lines on stderr (containers) |
127
156
  | `COMMITGUARD_TRANSPORT` | `stdio` | `stdio` or `streamable-http` |
157
+ | `COMMITGUARD_ALLOWED_HOSTS` | `localhost`, `127.0.0.1` (any port) | HTTP only: Host headers the server answers (DNS-rebinding protection) |
158
+ | `COMMITGUARD_METRICS` | `1` | HTTP only: `0` turns off `/metrics` |
159
+ | `HOST`, `PORT` | `0.0.0.0`, `8080` | HTTP only: listen address |
128
160
  | `COMMITGUARD_SEED_DEMO` | `0` | `1` seeds demo issues into an empty database on start |
129
161
 
130
- ## Known limits (v0.2)
162
+ ## Known limits (v0.3)
131
163
 
132
164
  - The proposal queue is SQLite: right for local use, not for multi-instance hosting. Postgres is next on the roadmap.
165
+ - 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.
133
166
  - 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.
134
167
  - GitHub is the first real backend. Linear and Jira adapters are planned; contributions welcome.
135
168
  - A model can still write a poor comment. That's what the quality evals and judge are for.
136
169
 
137
170
  ## Contributing
138
171
 
139
- Issues and pull requests are welcome. Every change runs the guarantee tests, the red-team regressions and the eval gate. 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.
172
+ 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.
140
173
 
141
174
  ## License
142
175
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "commitguard-mcp"
3
- version = "0.2.0"
3
+ version = "0.3.0"
4
4
  description = "An issue-tracker MCP server where agents can read, comment and propose, but can never write a commitment (owner, due date, status)."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -27,7 +27,15 @@ Security = "https://github.com/bharathg217/commitguard/blob/main/SECURITY.md"
27
27
 
28
28
  [project.optional-dependencies]
29
29
  agent = ["anthropic>=0.40"]
30
- dev = ["pytest>=8"]
30
+ dev = [
31
+ "pytest>=8",
32
+ "pytest-cov>=5",
33
+ "pytest-benchmark>=4",
34
+ "hypothesis>=6.100",
35
+ "ruff>=0.17,<0.18",
36
+ "mypy>=2.3,<2.5",
37
+ "types-PyYAML",
38
+ ]
31
39
 
32
40
  [project.scripts]
33
41
  commitguard-server = "commitguard.server:main"
@@ -43,3 +51,35 @@ where = ["src"]
43
51
  [tool.pytest.ini_options]
44
52
  testpaths = ["tests"]
45
53
  pythonpath = ["src"]
54
+ addopts = "--benchmark-disable"
55
+
56
+ [tool.coverage.run]
57
+ source = ["commitguard"]
58
+ branch = true
59
+
60
+ [tool.coverage.report]
61
+ fail_under = 85
62
+ show_missing = true
63
+ skip_covered = true
64
+
65
+ [tool.ruff]
66
+ line-length = 120
67
+ target-version = "py311"
68
+ src = ["src", "tests"]
69
+
70
+ [tool.ruff.lint]
71
+ # E/F/W: correctness, I: imports, B: bugbear, S: Bandit security rules (flake8-bandit), UP: modern syntax
72
+ select = ["E", "F", "W", "I", "B", "S", "UP"]
73
+ ignore = ["S101", "E741"]
74
+
75
+ [tool.ruff.lint.per-file-ignores]
76
+ "tests/**" = ["S", "B"]
77
+ "evals/**" = ["S"]
78
+ "src/commitguard/demo.py" = ["E501"]
79
+
80
+ [tool.mypy]
81
+ python_version = "3.11"
82
+ files = ["src/commitguard"]
83
+ ignore_missing_imports = true
84
+ check_untyped_defs = true
85
+ warn_unused_ignores = true
@@ -1,6 +1,6 @@
1
1
  """CommitGuard: an issue-tracker MCP server with structurally blocked commitment writes."""
2
2
 
3
- __version__ = "0.2.0"
3
+ __version__ = "0.3.0"
4
4
 
5
5
  # Fields that represent a commitment someone made. An agent may propose a change
6
6
  # to these, but no agent-facing code path can write them.
@@ -16,10 +16,11 @@ import argparse
16
16
  import json
17
17
  import os
18
18
 
19
- from .review import GitHubReviewerTracker, ReviewerClient, SqliteReviewerTracker
20
19
  from .demo import DEMO_ISSUES, seed
20
+ from .review import GitHubReviewerTracker, ReviewerClient, SqliteReviewerTracker
21
21
  from .store import connect
22
22
 
23
+
23
24
  def main() -> None:
24
25
  p = argparse.ArgumentParser(prog="commitguard")
25
26
  p.add_argument("--db", default=os.environ.get("COMMITGUARD_DB", "commitguard.db"))
@@ -0,0 +1,100 @@
1
+ """In-process metrics in Prometheus text format, with no extra dependency.
2
+
3
+ Every tool call recorded by RunLog is also counted here, so /metrics shows:
4
+ commitguard_tool_calls_total{tool, outcome} calls by result (ok / error / rejected_before_tool)
5
+ commitguard_tool_latency_seconds{tool} (histogram) how long each tool took
6
+ commitguard_up, commitguard_build_info{version} liveness and the running version
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import threading
12
+ import time
13
+ from collections import defaultdict
14
+ from typing import Any
15
+
16
+ # Seconds. Covers a local SQLite call (~1 ms) up to a slow GitHub API round trip.
17
+ BUCKETS = (0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0)
18
+ _MAX_LABEL = 64
19
+
20
+
21
+ def _label(value: Any) -> str:
22
+ """Label values come from tool names, which a client controls: keep them short and safe."""
23
+ s = str(value)[:_MAX_LABEL]
24
+ return s.replace("\\", "\\\\").replace('"', '\\"').replace("\n", " ")
25
+
26
+
27
+ class Metrics:
28
+ # Unknown tool names are client-chosen; cap distinct label sets so they cannot grow memory forever.
29
+ MAX_SERIES = 200
30
+
31
+ def __init__(self, known_tools: set[str] | None = None) -> None:
32
+ self._lock = threading.Lock()
33
+ # The server's real tool names. Any other name (clients choose it freely) is counted as
34
+ # "_unknown", so an agent spraying made-up tool names can't crowd the real tools out.
35
+ self.known_tools = set(known_tools or ())
36
+ self._clear()
37
+
38
+ def _clear(self) -> None:
39
+ self.started = time.time()
40
+ self.calls: dict[tuple[str, str], int] = defaultdict(int)
41
+ self.buckets: dict[str, list[int]] = {}
42
+ self.sums: dict[str, float] = defaultdict(float)
43
+ self.counts: dict[str, int] = defaultdict(int)
44
+
45
+ def reset(self) -> None:
46
+ with self._lock:
47
+ self._clear()
48
+
49
+ def observe(self, record: dict[str, Any]) -> None:
50
+ tool = _label(record.get("tool", "unknown"))
51
+ outcome = _label(record.get("outcome", "unknown"))
52
+ if self.known_tools and tool not in self.known_tools:
53
+ tool = "_unknown"
54
+ latency_ms = record.get("latency_ms")
55
+ with self._lock:
56
+ if (tool, outcome) not in self.calls and len(self.calls) >= self.MAX_SERIES:
57
+ tool = "_other"
58
+ self.calls[(tool, outcome)] += 1
59
+ if latency_ms is None:
60
+ return
61
+ if tool not in self.buckets and len(self.buckets) >= self.MAX_SERIES:
62
+ tool = "_other"
63
+ seconds = float(latency_ms) / 1000
64
+ counts = self.buckets.setdefault(tool, [0] * len(BUCKETS))
65
+ for i, edge in enumerate(BUCKETS):
66
+ if seconds <= edge:
67
+ counts[i] += 1
68
+ self.sums[tool] += seconds
69
+ self.counts[tool] += 1
70
+
71
+ def render(self, version: str) -> str:
72
+ with self._lock:
73
+ out = [
74
+ "# HELP commitguard_up 1 while the server is running.",
75
+ "# TYPE commitguard_up gauge",
76
+ "commitguard_up 1",
77
+ "# HELP commitguard_build_info Running version.",
78
+ "# TYPE commitguard_build_info gauge",
79
+ f'commitguard_build_info{{version="{_label(version)}"}} 1',
80
+ "# HELP commitguard_uptime_seconds Seconds since the process started.",
81
+ "# TYPE commitguard_uptime_seconds gauge",
82
+ f"commitguard_uptime_seconds {time.time() - self.started:.0f}",
83
+ "# HELP commitguard_tool_calls_total Tool calls by tool and outcome.",
84
+ "# TYPE commitguard_tool_calls_total counter",
85
+ ]
86
+ for (tool, outcome), n in sorted(self.calls.items()):
87
+ out.append(f'commitguard_tool_calls_total{{tool="{tool}",outcome="{outcome}"}} {n}')
88
+ out += ["# HELP commitguard_tool_latency_seconds Tool call latency.",
89
+ "# TYPE commitguard_tool_latency_seconds histogram"]
90
+ for tool in sorted(self.buckets):
91
+ for edge, n in zip(BUCKETS, self.buckets[tool], strict=True):
92
+ out.append(f'commitguard_tool_latency_seconds_bucket{{tool="{tool}",le="{edge}"}} {n}')
93
+ out.append(f'commitguard_tool_latency_seconds_bucket{{tool="{tool}",le="+Inf"}} {self.counts[tool]}')
94
+ out.append(f'commitguard_tool_latency_seconds_sum{{tool="{tool}"}} {self.sums[tool]:.6f}')
95
+ out.append(f'commitguard_tool_latency_seconds_count{{tool="{tool}"}} {self.counts[tool]}')
96
+ return "\n".join(out) + "\n"
97
+
98
+
99
+ TOOLS = {"search_issues", "get_issue", "add_comment", "propose_update", "list_my_proposals"}
100
+ METRICS = Metrics(TOOLS)
@@ -32,7 +32,8 @@ class SqliteReviewerTracker(SqliteAgentTracker):
32
32
  if not cols:
33
33
  return
34
34
  sets = ", ".join(f"{self._COLUMNS[c]} = ?" for c in cols)
35
- self._conn.execute(f"UPDATE issues SET {sets}, updated_at = ? WHERE id = ?",
35
+ # Column names come from the fixed _COLUMNS map above, never from input; values are bound.
36
+ self._conn.execute(f"UPDATE issues SET {sets}, updated_at = ? WHERE id = ?", # noqa: S608
36
37
  [changes[c] for c in cols] + [_now(), issue_id])
37
38
 
38
39
 
@@ -2,31 +2,50 @@
2
2
 
3
3
  Lines are shaped to load straight into a warehouse table (BigQuery, Postgres):
4
4
  run_id, agent_id, tool, arguments, outcome, error, latency_ms, at.
5
+
6
+ Set COMMITGUARD_RUNLOG=- to write the lines to stderr instead (containers, Cloud Logging). stderr, not
7
+ stdout, because the stdio transport uses stdout for the MCP protocol itself.
8
+ Every record is also counted in commitguard.metrics, whether or not it is written anywhere.
5
9
  """
6
10
 
7
11
  from __future__ import annotations
8
12
 
9
13
  import json
10
14
  import os
15
+ import sys
16
+ import threading
11
17
  import time
18
+ from collections.abc import Iterator
12
19
  from contextlib import contextmanager
13
20
  from pathlib import Path
14
- from typing import Any, Iterator
21
+ from typing import Any
15
22
 
23
+ from .metrics import METRICS
16
24
  from .store import now
17
25
 
18
26
 
19
27
  class RunLog:
20
28
  def __init__(self, path: str | Path | None):
21
- self.path = Path(path) if path else None
29
+ self.stdout = path == "-"
30
+ self.path = Path(path) if path and not self.stdout else None
31
+ self._lock = threading.Lock()
22
32
  if self.path:
23
33
  self.path.parent.mkdir(parents=True, exist_ok=True)
24
34
 
25
35
  def write(self, record: dict[str, Any]) -> None:
26
- if not self.path:
36
+ METRICS.observe(record)
37
+ if not (self.path or self.stdout):
27
38
  return
28
- with self.path.open("a", encoding="utf-8") as f:
29
- f.write(json.dumps(record, sort_keys=True, default=str) + "\n")
39
+ if self.stdout: # Cloud Logging reads "severity" from JSON lines
40
+ record = {"severity": "INFO" if record.get("outcome") == "ok" else "WARNING", **record}
41
+ line = json.dumps(record, sort_keys=True, default=str) + "\n"
42
+ with self._lock:
43
+ if self.stdout:
44
+ sys.stderr.write(line)
45
+ sys.stderr.flush()
46
+ elif self.path is not None:
47
+ with self.path.open("a", encoding="utf-8") as f:
48
+ f.write(line)
30
49
 
31
50
  @contextmanager
32
51
  def call(self, run_id: str, agent_id: str, tool: str, arguments: dict[str, Any]) -> Iterator[dict]:
@@ -11,13 +11,17 @@ from __future__ import annotations
11
11
 
12
12
  import contextvars
13
13
  import os
14
+ import threading
14
15
  import uuid
16
+ from collections.abc import Iterator
15
17
  from contextlib import contextmanager
16
- from typing import Any, Iterator
18
+ from typing import Any
17
19
 
18
20
  from mcp.server.mcpserver import MCPServer
19
21
  from mcp.server.mcpserver.exceptions import ToolError
20
22
 
23
+ from . import __version__
24
+ from .metrics import METRICS
21
25
  from .runlog import RunLog, default_log
22
26
  from .store import AgentClient, connect, now
23
27
  from .trackers import AgentTracker, GitHubAgentTracker, SqliteAgentTracker
@@ -46,9 +50,13 @@ def build_server(db_path: str, agent_id: str, runlog: RunLog | None = None,
46
50
  client = AgentClient(conn, tracker or agent_tracker_from_env(conn), agent_id)
47
51
  log = runlog or default_log()
48
52
  session_run_id = run_id or f"run_{uuid.uuid4().hex[:12]}"
49
- mcp = MCPServer(name="commitguard", instructions=INSTRUCTIONS, version="0.2.0")
53
+ mcp = MCPServer(name="commitguard", instructions=INSTRUCTIONS, version=__version__)
50
54
 
51
55
  reached_tool: contextvars.ContextVar[dict] = contextvars.ContextVar("reached_tool")
56
+ # The MCP SDK runs tool functions in worker threads, and HTTP clients call concurrently.
57
+ # A sqlite3 connection is not safe for concurrent use (found by scripts/loadtest.py: wrong
58
+ # "not found" answers and InterfaceErrors), so calls on this server's connection are serialized.
59
+ db_lock = threading.Lock()
52
60
 
53
61
  @contextmanager
54
62
  def logged(tool: str, args: dict[str, Any]) -> Iterator[None]:
@@ -57,7 +65,7 @@ def build_server(db_path: str, agent_id: str, runlog: RunLog | None = None,
57
65
  if marker is not None:
58
66
  marker["reached"] = True # shared object: visible even from the worker thread
59
67
  try:
60
- with log.call(session_run_id, agent_id, tool, args):
68
+ with log.call(session_run_id, agent_id, tool, args), db_lock:
61
69
  yield
62
70
  except (LookupError, ValueError, PermissionError, TypeError) as exc:
63
71
  raise ToolError(str(exc)) from None
@@ -146,6 +154,63 @@ def build_server(db_path: str, agent_id: str, runlog: RunLog | None = None,
146
154
  return mcp
147
155
 
148
156
 
157
+ DEFAULT_ALLOWED_HOSTS = "localhost,localhost:*,127.0.0.1,127.0.0.1:*"
158
+ MAX_BODY_BYTES = 256 * 1024
159
+ _HEADERS = [(b"cache-control", b"no-store"), (b"x-content-type-options", b"nosniff")]
160
+
161
+
162
+ def http_app(server: MCPServer, db_path: str, allowed_hosts: list[str] | None = None,
163
+ metrics: bool = True):
164
+ """The MCP endpoint at /mcp plus operational endpoints for load balancers and monitoring.
165
+
166
+ /healthz liveness: the process is serving requests.
167
+ /readyz readiness: the issue database answers a query.
168
+ /metrics Prometheus text format (see commitguard.metrics). Off with metrics=False.
169
+
170
+ Host headers are checked (DNS-rebinding protection) and request bodies are capped.
171
+ """
172
+ import sqlite3
173
+ from contextlib import closing
174
+ from pathlib import Path
175
+
176
+ from mcp.server.transport_security import TransportSecuritySettings
177
+
178
+ hosts = allowed_hosts or DEFAULT_ALLOWED_HOSTS.split(",")
179
+ mcp_app = server.streamable_http_app(
180
+ json_response=True, max_request_body_size=MAX_BODY_BYTES,
181
+ transport_security=TransportSecuritySettings(enable_dns_rebinding_protection=True,
182
+ allowed_hosts=hosts, allowed_origins=[]))
183
+
184
+ def ready() -> bool:
185
+ try:
186
+ uri = Path(db_path).resolve().as_uri() + "?mode=ro" # percent-encodes '#', '?', spaces
187
+ with closing(sqlite3.connect(uri, uri=True, timeout=1)) as c:
188
+ c.execute("SELECT 1 FROM issues LIMIT 1").fetchall()
189
+ return True
190
+ except sqlite3.Error:
191
+ return False
192
+
193
+ async def respond(send, status: int, body: bytes, ctype: bytes = b"text/plain; charset=utf-8"):
194
+ await send({"type": "http.response.start", "status": status,
195
+ "headers": [(b"content-type", ctype), (b"content-length", str(len(body)).encode())] + _HEADERS})
196
+ await send({"type": "http.response.body", "body": body})
197
+
198
+ async def app(scope, receive, send):
199
+ if scope["type"] == "http" and scope.get("method") in ("GET", "HEAD"):
200
+ path = scope.get("path")
201
+ if path == "/healthz":
202
+ return await respond(send, 200, b"ok\n")
203
+ if path == "/readyz":
204
+ ok = ready()
205
+ return await respond(send, 200 if ok else 503, b"ready\n" if ok else b"database unavailable\n")
206
+ if path == "/metrics" and metrics:
207
+ return await respond(send, 200, METRICS.render(__version__).encode(),
208
+ b"text/plain; version=0.0.4; charset=utf-8")
209
+ await mcp_app(scope, receive, send)
210
+
211
+ return app
212
+
213
+
149
214
  def main() -> None:
150
215
  db = os.environ.get("COMMITGUARD_DB", "commitguard.db")
151
216
  agent_id = os.environ.get("COMMITGUARD_AGENT_ID", "default-agent")
@@ -157,7 +222,14 @@ def main() -> None:
157
222
  seed(conn)
158
223
  server = build_server(db, agent_id)
159
224
  if transport == "streamable-http":
160
- server.run("streamable-http", host="0.0.0.0", port=int(os.environ.get("PORT", "8080")))
225
+ import uvicorn
226
+
227
+ hosts = [h.strip() for h in os.environ.get("COMMITGUARD_ALLOWED_HOSTS", DEFAULT_ALLOWED_HOSTS).split(",")
228
+ if h.strip()]
229
+ app = http_app(server, db, hosts, metrics=os.environ.get("COMMITGUARD_METRICS", "1") != "0")
230
+ uvicorn.run(app, host=os.environ.get("HOST", "0.0.0.0"), # noqa: S104 - containers listen on all interfaces
231
+ port=int(os.environ.get("PORT", "8080")), access_log=False, proxy_headers=True,
232
+ timeout_graceful_shutdown=10)
161
233
  else:
162
234
  server.run("stdio")
163
235
 
@@ -18,7 +18,7 @@ import json
18
18
  import re
19
19
  import sqlite3
20
20
  import uuid
21
- from datetime import date, datetime, timedelta, timezone
21
+ from datetime import UTC, date, datetime, timedelta
22
22
  from pathlib import Path
23
23
  from typing import Any
24
24
 
@@ -73,12 +73,19 @@ PROPOSAL_TTL_DAYS = 7
73
73
 
74
74
 
75
75
  def now() -> str:
76
- return datetime.now(timezone.utc).isoformat(timespec="seconds")
76
+ return datetime.now(UTC).isoformat(timespec="seconds")
77
77
 
78
78
 
79
79
  def connect(path: str | Path) -> sqlite3.Connection:
80
- conn = sqlite3.connect(str(path), check_same_thread=False)
80
+ """Open the database. One connection must not be used by two threads at once: the server
81
+ serializes tool calls on it (see server.build_server). Other processes (the review CLI)
82
+ get their own connection; WAL mode and a busy timeout let them work alongside the server."""
83
+ conn = sqlite3.connect(str(path), check_same_thread=False, timeout=10)
81
84
  conn.row_factory = sqlite3.Row
85
+ conn.execute("PRAGMA busy_timeout = 10000")
86
+ if str(path) != ":memory:":
87
+ conn.execute("PRAGMA journal_mode = WAL")
88
+ conn.execute("PRAGMA foreign_keys = ON")
82
89
  conn.executescript(SCHEMA)
83
90
  return conn
84
91
 
@@ -200,7 +207,7 @@ class AgentClient:
200
207
  " created_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
201
208
  (pid, key, self.agent_id, run_id, json.dumps(changes, sort_keys=True),
202
209
  json.dumps(before, sort_keys=True), rationale, json.dumps(evidence), now(),
203
- (datetime.now(timezone.utc) + timedelta(days=PROPOSAL_TTL_DAYS)).isoformat(timespec="seconds")),
210
+ (datetime.now(UTC) + timedelta(days=PROPOSAL_TTL_DAYS)).isoformat(timespec="seconds")),
204
211
  )
205
212
  audit(self._conn, f"agent:{self.agent_id}", "propose",
206
213
  {"issue": key, "proposal": pid, "run": run_id, "changes": changes})
@@ -19,7 +19,7 @@ import urllib.error
19
19
  import urllib.parse
20
20
  import urllib.request
21
21
  import uuid
22
- from datetime import datetime, timezone
22
+ from datetime import UTC, datetime
23
23
  from typing import Any, Protocol
24
24
 
25
25
  STATUSES = ("open", "in_progress", "blocked", "done", "closed")
@@ -32,7 +32,7 @@ class AgentTracker(Protocol):
32
32
 
33
33
 
34
34
  def _now() -> str:
35
- return datetime.now(timezone.utc).isoformat(timespec="seconds")
35
+ return datetime.now(UTC).isoformat(timespec="seconds")
36
36
 
37
37
 
38
38
  # --------------------------------------------------------------------------- sqlite
@@ -119,6 +119,10 @@ class GitHubHTTP:
119
119
  raise ValueError("a GitHub token is required")
120
120
  self._token = token
121
121
  self._allow = allow
122
+ parsed = urllib.parse.urlsplit(base)
123
+ loopback = parsed.hostname in ("127.0.0.1", "localhost", "::1")
124
+ if parsed.scheme != "https" and not (parsed.scheme == "http" and loopback):
125
+ raise ValueError("the GitHub API base must be https (plain http only for a local test server)")
122
126
  self._base = base.rstrip("/")
123
127
 
124
128
  def _allowed(self, method: str, path: str) -> bool:
@@ -130,7 +134,8 @@ class GitHubHTTP:
130
134
  raise PermissionError(f"CommitGuard blocks {method} {bare} for this client")
131
135
  data = json.dumps(body).encode() if body is not None else None
132
136
  for attempt in range(2):
133
- req = urllib.request.Request(self._base + path, data=data, method=method, headers={
137
+ req = urllib.request.Request(self._base + path, # noqa: S310 - scheme checked in __init__
138
+ data=data, method=method, headers={
134
139
  "Authorization": f"Bearer {self._token}",
135
140
  "Accept": "application/vnd.github+json",
136
141
  "X-GitHub-Api-Version": "2022-11-28",