Skip to content

Commit 6ec4e48

Browse files
cliffhallclaude
andcommitted
chore(python): per-file coverage gate in CI and local:gate
Add `npm run coverage:py` (scripts/coverage-py.mjs): for each Python server, a locked sync, then `uv run --frozen pytest --cov --cov-report=term-missing --cov-report=json`, then a per-file check of coverage.json (scripts/lib/py-coverage.mjs) that fails any file below 90% on lines or on branches. coverage.py's fail_under is global, hence the script. Discovery, server selection and the carry-on-after-a-failure shape are shared with validate-py.mjs. Wire it in as a parallel `coverage` matrix job in python.yml and as a stage of local:gate:stages after validate:py, and document it in docs/quality-gate.md, AGENTS.md (the Python half of the coverage rule), CONTRIBUTING.md and the pre-push-gate and testing skills. Signed-off-by: cliffhall <cliff@futurescale.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent cb88e8f commit 6ec4e48

12 files changed

Lines changed: 1033 additions & 67 deletions

File tree

‎.claude/skills/pre-push-gate/SKILL.md‎

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,8 @@ unquoted `#` or `:` in a `description`.
7575
`verify:skills:cli` is the authoritative validator. It fetches the pinned
7676
Claude Code CLI with `npx` when the installed one is a different version, so it
7777
**fails offline**. (`validate:py`'s `sync` step is the other stage that can:
78-
`uv sync --locked` downloads when a server's environment is missing or stale.)
78+
`uv sync --locked` downloads when a server's environment is missing or stale.
79+
`coverage:py` opens with the same sync, a no-op once `validate:py` has run.)
7980

8081
### `verify:typecheck-coverage`
8182

@@ -171,6 +172,38 @@ the last `[validate:py] <server>: <step>` line above it. Re-run one server with
171172

172173
`uv: command not found` means `uv` is not installed. Never substitute `pip`.
173174

175+
### `coverage:py`
176+
177+
The Python per-file coverage gate: every file each server measures must reach
178+
**90% on lines and 90% on branches**. The summary names the server, the step,
179+
and for a shortfall each file and dimension below 90:
180+
181+
```
182+
FAIL time — per-file check (2 below 90%)
183+
src/time/src/mcp_server_time/server.py: lines 84.2% (75/89) is below 90%
184+
src/time/src/mcp_server_time/server.py: branches 78.5% (11/14) is below 90%
185+
```
186+
187+
Re-run one server with `npm run coverage:py -- <server>`. The per-file table
188+
above the summary gives both figures for every file, and coverage.py's own
189+
report above that (`term-missing`) lists the uncovered lines and partial
190+
branches (`120->124` is the jump from line 120 to 124 never taken).
191+
192+
| Step | Fix |
193+
| --- | --- |
194+
| `sync` | As for `validate:py`: run `uv lock` in that server and commit the lockfile |
195+
| `pytest --cov` | A test failed, so no verdict was reached; fix it as for `validate:py`'s `pytest`. `unrecognized arguments: --cov` means `pytest-cov` is missing from the server's dev dependencies |
196+
| `per-file check`, "below 90%" | Write tests for the lines and branches the report lists. Drive the server in-process through a `ClientSession` where you can (`/testing`) |
197+
| `per-file check`, "was not written" or "measured no files" | The run produced no usable `coverage.json`: check the server's `[tool.coverage.run]` (`branch = true`, `source` naming its package) |
198+
| `per-file check`, "no covered_branches/num_branches" | `branch = true` is missing from `[tool.coverage.run]` |
199+
200+
**Never lower the gate**, and never drop a file from `source` to clear it.
201+
Code that genuinely cannot run (a guard the types already rule out, a branch
202+
the SDK's input validation makes unreachable) is marked at the source with
203+
`# pragma: no cover # <reason>`; every pragma carries its reason
204+
(`AGENTS.md` **Always test new or modified code**). A pragma on a line that is
205+
merely awkward to test is not justified; write the test.
206+
174207
### `smoke`
175208

176209
`smoke — FAIL <server> over <transport>` followed by the reason and the tail
@@ -221,8 +254,9 @@ The details of the lease are in
221254

222255
## Not part of the gate
223256

224-
`npm run skills:eval` (real model calls), `npm run coverage` (a report; no
225-
threshold is enforced yet) and `npm run pack:verify` (installs each package's
257+
`npm run skills:eval` (real model calls), `npm run coverage` (the TypeScript
258+
servers' report; no threshold is enforced on them yet; the Python servers' gate
259+
is the `coverage:py` stage above) and `npm run pack:verify` (installs each package's
226260
publish artifact and boots it; needs the network, and belongs to the release
227261
flow) are separate commands. Run the eval suite when you
228262
add a skill or change a description.

‎.claude/skills/testing/SKILL.md‎

Lines changed: 91 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -15,18 +15,19 @@ and which command runs what.
1515
Driving a running server by hand, with the Inspector or an LLM client, is
1616
`/client-smoke`. It is evidence for a PR, not a substitute for a test.
1717

18-
⚠️ **The harnesses are uneven, and this page describes them as they are.** Only
19-
`everything` and `time` can be driven in-process today. A shared in-process
20-
harness for every server, and an enforced per-file coverage threshold, are the
21-
work of #4854 (TypeScript) and #4855 (Python); neither is complete yet, and
22-
this skill changes when they land. Do not write a test that assumes them.
18+
⚠️ **The harnesses are uneven, and this page describes them as they are.** The
19+
three Python servers are driven in-process through a `ClientSession` and held
20+
to a per-file coverage gate (#4855). Of the TypeScript servers only
21+
`everything` can be driven in-process today, and none has a coverage
22+
threshold yet; both are the work of #4854, and the TypeScript half of this
23+
skill changes when it lands. Do not write a TypeScript test that assumes them.
2324

2425
## Where a test goes
2526

2627
| Server | Directory | File name | Runner |
2728
| --- | --- | --- | --- |
2829
| `everything`, `filesystem`, `memory`, `sequentialthinking` | `src/<server>/__tests__/` | `<subject>.test.ts` | vitest, `globals: true` |
29-
| `fetch`, `git`, `time` | `src/<server>/tests/` | `test_<subject>.py` | pytest |
30+
| `fetch`, `git`, `time` | `src/<server>/tests/` | `test_<subject>.py` | pytest, with `pytest-asyncio` (`asyncio_mode = "auto"`) |
3031
| Root tooling | `scripts/`, beside the script | `<name>.test.mjs` | `node --test` |
3132

3233
Each vitest config includes only `**/__tests__/**/*.test.ts`, so a test file
@@ -42,10 +43,9 @@ helpers go in `__tests__/` without the `.test` suffix, as
4243
| `filesystem` | Unit tests of `lib.ts` and the path helpers, plus an SDK `Client` over `StdioClientTransport` that spawns the built `dist/index.js` |
4344
| `sequentialthinking` | Unit tests of `lib.ts`, plus an SDK `Client` over stdio against `dist/index.js` |
4445
| `memory` | Direct calls on the exported `KnowledgeGraphManager` and `register…` functions, with a mocked server |
45-
| `fetch`, `git` | Direct calls on the functions in `server.py`, with `unittest.mock` |
46-
| `time` | A `ClientSession` against `serve()` in-process, over in-memory streams (`tests/test_protocol.py`); direct calls on the helpers in `server.py` (`tests/test_server.py`) |
46+
| `fetch`, `git`, `time` | A `ClientSession` linked in-process to the real `serve()` over in-memory streams (below), plus direct calls on the pure functions in `server.py` |
4747

48-
Of the Python servers, only `time` opens a `ClientSession` in its tests.
48+
No TypeScript test uses an in-memory transport yet.
4949

5050
## Choosing a harness for a new test
5151

@@ -167,47 +167,71 @@ the wire. The `filesystem` stdio tests and `memory`'s dist-layout test have no
167167
such guard and **fail**. A skipped test in this repo usually means "not
168168
built".
169169

170-
### Python: `ClientSession` over stdio
170+
### Python: `ClientSession` over in-memory streams, in-process
171171

172-
Each Python server constructs its `Server` inside `serve()`, so it cannot be
173-
handed to an in-memory session directly. `time` drives it in-process anyway, by
174-
patching `stdio_server` to yield the server side of
175-
`create_client_server_memory_streams()`; see the `serving()` helper in
176-
`src/time/tests/test_protocol.py`. The other route spawns the module and talks
177-
to it through the SDK's stdio client:
172+
Each Python server builds its `Server` inside `serve()` and serves it over the
173+
`stdio_server()` it imports into `server.py`. A test replaces that one name
174+
with a context manager that yields the server side of a pair of in-memory
175+
streams, runs the real `serve()` in a task group, and opens a `ClientSession`
176+
on the client side. No process, no build, and the SDK's input validation and
177+
error mapping run exactly as they do for a real client:
178178

179179
```python
180-
import sys
180+
from contextlib import asynccontextmanager
181+
from typing import Any, AsyncIterator
181182

182183
import anyio
183-
from mcp import ClientSession, StdioServerParameters
184-
from mcp.client.stdio import stdio_client
185-
186-
187-
def test_get_current_time_over_stdio() -> None:
188-
async def _run() -> None:
189-
params = StdioServerParameters(
190-
command=sys.executable, args=["-m", "mcp_server_time"]
191-
)
192-
async with stdio_client(params) as (read, write):
193-
async with ClientSession(read, write) as session:
194-
await session.initialize()
195-
result = await session.call_tool(
196-
"get_current_time", {"timezone": "UTC"}
197-
)
198-
assert result.isError is False
199-
200-
anyio.run(_run)
201-
```
184+
import pytest
185+
from mcp import ClientSession
186+
from mcp.shared.memory import create_client_server_memory_streams
187+
188+
import mcp_server_time.server as server_module
189+
190+
191+
@asynccontextmanager
192+
async def connect(**serve_kwargs: Any) -> AsyncIterator[ClientSession]:
193+
async with create_client_server_memory_streams() as (client, server):
202194

203-
`sys.executable` is the server's own virtual environment under `uv run pytest`,
204-
and the install there is editable, so this runs your edit with no build step.
195+
@asynccontextmanager
196+
async def fake_stdio_server() -> AsyncIterator[Any]:
197+
yield server
205198

206-
How an async test is written differs by server, because the dev dependencies
207-
do: `fetch` and `time` have `pytest-asyncio` with `asyncio_mode = "auto"`,
208-
so an `async def test_…` just works. `git` does not have it; wrap the
209-
coroutine in `anyio.run(...)` as above (`git`'s `serve()` test does), rather
210-
than adding a dependency for one test.
199+
with pytest.MonkeyPatch.context() as mp:
200+
mp.setattr(server_module, "stdio_server", fake_stdio_server)
201+
async with anyio.create_task_group() as tg:
202+
tg.start_soon(lambda: server_module.serve(**serve_kwargs))
203+
async with ClientSession(*client) as session:
204+
await session.initialize()
205+
yield session
206+
tg.cancel_scope.cancel()
207+
208+
209+
async def test_get_current_time() -> None:
210+
async with connect() as session:
211+
result = await session.call_tool("get_current_time", {"timezone": "UTC"})
212+
assert result.isError is False
213+
```
214+
215+
- **Patch the name `server.py` looks up** (`mcp_server_<name>.server.stdio_server`),
216+
not `mcp.server.stdio.stdio_server`: `server.py` imported the function, so
217+
the module attribute is what `serve()` calls.
218+
- **Cancel the task group after the session closes.** `serve()` runs until its
219+
streams end, so without the cancel the test never returns.
220+
- **Assert on the wire shape where you can**, for example
221+
`result.model_dump(by_alias=True, mode="json")`, rather than on Python
222+
attribute names: the SDK v2 port (#4851) renames them, and a wire-level
223+
assertion survives it.
224+
- **No network in a test.** `fetch` replaces `httpx.AsyncClient` with one on an
225+
`httpx.MockTransport`; `git` works against a temporary repository its
226+
fixture creates and closes before removing.
227+
228+
`pytest-asyncio` with `asyncio_mode = "auto"` is a dev dependency of all three,
229+
so an `async def test_…` runs as it stands.
230+
231+
A subprocess test over stdio (`StdioServerParameters(command=sys.executable,
232+
args=["-m", "mcp_server_<name>"])` with `mcp.client.stdio.stdio_client`) is
233+
kept to a thin smoke of the entry point. coverage.py does not measure a child
234+
process, so code reached only that way reads as uncovered.
211235

212236
## Running them
213237

@@ -220,6 +244,8 @@ than adding a dependency for one test.
220244
| One Python server | `uv run pytest` in `src/<server>` |
221245
| One Python test | `uv run pytest <path to the test file>::<name>` in `src/<server>` (for example `tests/test_server.py::test_git_checkout_existing_branch`) |
222246
| One Python server's whole chain | `npm run validate:py -- <server>` |
247+
| One Python server's coverage gate | `npm run coverage:py -- <server>` at the root |
248+
| Every Python server's coverage gate | `npm run coverage:py` at the root |
223249
| Root tooling | `npm run test:scripts` |
224250

225251
`npm run typecheck -w src/<server>` is the only step that typechecks the test
@@ -237,13 +263,30 @@ npm run coverage -w src/<server> # one server
237263
npm run coverage # all four
238264
```
239265

240-
Today the report is **informational**. No vitest config sets a threshold, so
241-
`coverage` fails only when a test fails, and neither `validate` nor CI runs it.
242-
Of the Python servers, only `time` has coverage tooling so far: its README's
243-
**Development** section gives the command, which writes `coverage.json`.
244-
Nothing enforces a threshold on it yet. Read the report to find what a change left
266+
For the TypeScript servers the report is **informational** today. No vitest
267+
config sets a threshold, so `coverage` fails only when a test fails, and
268+
neither `validate` nor CI runs it. Read the report to find what a change left
245269
untested; do not describe it as a gate.
246270

271+
**The Python servers' coverage is a gate.** `npm run coverage:py -- <server>`
272+
runs, in `src/<server>`:
273+
274+
```sh
275+
uv run --frozen pytest --cov --cov-report=term-missing --cov-report=json
276+
```
277+
278+
which prints coverage.py's report (the missing lines and partial branches)
279+
and writes `coverage.json` (ignored by git). `scripts/lib/py-coverage.mjs` then
280+
checks **every file** in it: at least 90% of its lines and 90% of its branches,
281+
each file on its own. What is measured is the server's `[tool.coverage.run]`
282+
(`branch = true`, `source` set to its package). `local:gate` and CI's
283+
**Coverage \<server\>** job both run it. It is kept out of the plain
284+
`uv run pytest` loop, which stays fast and uninstrumented.
285+
286+
A line or branch that genuinely cannot run is marked
287+
`# pragma: no cover # <reason>`, with the reason on the same line; never
288+
lower the gate. Diagnosing a red run is `/pre-push-gate`.
289+
247290
⚠️ **A spawned server is invisible to the report.** v8 coverage measures the
248291
vitest process, not a child it starts, so code reached only through a stdio
249292
test reads as uncovered: `sequentialthinking`'s `index.ts` reports 0% while its

‎.github/workflows/python.yml‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ jobs:
3838
node-version: 22
3939

4040
- name: Run node --test
41-
run: node --test scripts/validate-py.test.mjs
41+
run: node --test scripts/validate-py.test.mjs scripts/coverage-py.test.mjs scripts/lib/py-coverage.test.mjs
4242

4343
test:
4444
timeout-minutes: 15
@@ -68,6 +68,37 @@ jobs:
6868
- name: Validate
6969
run: node scripts/validate-py.mjs ${{ matrix.package }}
7070

71+
# The per-file coverage gate (#4855), in parallel with `test`: every file of
72+
# each server at >= 90% on lines and on branches. The same script
73+
# `npm run coverage:py` runs locally, one server per leg. fail-fast is off so
74+
# one server's shortfall does not cancel the other legs' verdicts.
75+
coverage:
76+
timeout-minutes: 15
77+
needs: [detect-packages]
78+
strategy:
79+
fail-fast: false
80+
matrix:
81+
package: ${{ fromJson(needs.detect-packages.outputs.packages) }}
82+
name: Coverage ${{ matrix.package }}
83+
runs-on: ubuntu-latest
84+
steps:
85+
- uses: actions/checkout@v6
86+
87+
- name: Install uv
88+
uses: astral-sh/setup-uv@v7
89+
90+
- name: Set up Python
91+
uses: actions/setup-python@v7
92+
with:
93+
python-version-file: "src/${{ matrix.package }}/.python-version"
94+
95+
- uses: actions/setup-node@v7
96+
with:
97+
node-version: 22
98+
99+
- name: Coverage
100+
run: npm run coverage:py -- ${{ matrix.package }}
101+
71102
build:
72103
timeout-minutes: 10
73104
needs: [detect-packages, test]

‎AGENTS.md‎

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ servers/
5252
│ └── time/ Py mcp-server-time PyPI Time and timezone conversion
5353
├── .claude/skills/ On-demand procedures (see the Skills index above)
5454
├── .changeset/ Pending changesets for the TypeScript servers, and the changesets config
55-
├── scripts/ The pre-push gate (gate-lease, smoke-servers, validate-py), its guards (verify-*),
55+
├── scripts/ The pre-push gate (gate-lease, smoke-servers, validate-py, coverage-py), its guards (verify-*),
5656
│ the skills tooling, and release tooling (npm-publish-guard, prepare-python-release,
5757
│ pack-and-verify, release-manifest)
5858
├── docs/ Design documents; quality-gate.md is the gate's reference (stages, CI vs local, the lease);
@@ -109,6 +109,7 @@ uv run pytest
109109
uv run --frozen pyright
110110
uv run ruff check .
111111
uv build
112+
npm run coverage:py -- <server> # at the root: the per-file coverage gate
112113

113114
# Both languages: the pre-push gate (see Before pushing)
114115
npm run local:gate
@@ -121,7 +122,8 @@ It runs every check CI runs, for both languages, in one command:
121122
`verify:install-fresh`, the root `validate` (the guards, then each TypeScript
122123
workspace's format check, lint, typecheck, build and tests), `validate:py`
123124
(each Python server's locked sync, `ruff check`, `ruff format --check`,
124-
pyright, pytest and build), `verify:skills:cli`, and `smoke` (every server
125+
pyright, pytest and build), `coverage:py` (each Python server's per-file
126+
coverage gate), `verify:skills:cli`, and `smoke` (every server
125127
booted over each transport it implements). The stage-by-stage reference, and
126128
what CI runs where, is [`docs/quality-gate.md`](./docs/quality-gate.md);
127129
diagnosing a red stage is the `pre-push-gate` skill.
@@ -450,9 +452,18 @@ here.
450452

451453
- **New or changed behavior comes with tests.** TypeScript servers use
452454
**vitest** (with `@vitest/coverage-v8`), with tests in the server's
453-
`__tests__/` directory. Python servers use **pytest** (`pytest-asyncio` where
454-
the server is async), with tests in the server's `tests/` directory (`test/` in
455-
`time`).
455+
`__tests__/` directory. Python servers use **pytest** (with `pytest-asyncio`),
456+
with tests in the server's `tests/` directory.
457+
- **Python: every file clears ≥ 90 per file on lines and on branches**, the
458+
two dimensions coverage.py measures (it has no native function dimension).
459+
Coverage is its own command, `npm run coverage:py` (`-- <server>` for one),
460+
separate from the fast `uv run pytest` loop, and **CI enforces it** in a
461+
parallel job, as `local:gate` does: a change that drops any Python file
462+
below 90 on either dimension fails both.
463+
- **Genuinely unreachable Python code is marked at the source, never waved
464+
through by lowering the gate**: `# pragma: no cover # <reason>`, and every
465+
pragma carries its reason. Reach for it only when the line or branch cannot
466+
be exercised, not because a test is hard to write.
456467
- **Test at the protocol level where you can**: drive the server through an MCP
457468
client over an in-memory transport and assert on what comes back, rather than
458469
only calling internal functions.

‎CONTRIBUTING.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -152,8 +152,8 @@ pushing, run `npm run format` at the repository root and then
152152
**`npm run local:gate`**, which runs every check CI runs for both languages:
153153
the repo-wide guards, each TypeScript server's `validate` (format check, lint
154154
where a warning fails like an error, typecheck, build, tests), each Python
155-
server's `validate:py` chain, the skills validator, and a boot smoke of every
156-
server. [`docs/quality-gate.md`](./docs/quality-gate.md) describes each stage.
155+
server's `validate:py` chain and per-file coverage gate (`coverage:py`), the
156+
skills validator, and a boot smoke of every server. [`docs/quality-gate.md`](./docs/quality-gate.md) describes each stage.
157157
While iterating, `npm run validate -w src/<server>` checks a single TypeScript
158158
server and `npm run validate:py -- <server>` a single Python one; neither
159159
replaces the gate.

0 commit comments

Comments
 (0)