mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 13:29:19 +08:00
fix(mcp): accept an empty install ledger instead of failing mutations as malformed (#3235)
## Description
`validate_ledger_for_mutation` (the preflight run before a config write
in `headroom mcp adopt`) rejects a legitimately **empty** ledger as
malformed:
```python
for section in ("agents",):
section_data = data.get(section)
if not isinstance(section_data, dict) or any(...): # None -> not a dict -> raises
raise LedgerMutationError(f"MCP install ledger section {section!r} is malformed")
```
An empty ledger has no `agents` key at all — `clear_install` **pops**
the section once its last entry is removed (`if not agents:
data.pop("agents", None)`), so a fully-unwrapped ledger is exactly `{}`,
and `record_install` likewise treats a missing `agents` as empty. But
`data.get("agents")` on `{}` returns `None`, which fails the
`isinstance(..., dict)` check and raises.
Impact: after a user unwraps their last MCP install (ledger becomes
`{}`), the next `headroom mcp ... --adopt` fails at the preflight
(`cli/mcp.py:245`) with a bogus `MCP install ledger section 'agents' is
malformed` `ClickException`, even though the ledger is perfectly valid.
Reproduction:
```python
record_install("claude", spec, path=lf)
clear_install("claude", "serena", path=lf) # ledger is now "{}"
validate_ledger_for_mutation(lf) # -> LedgerMutationError: ... 'agents' is malformed
```
## Type of Change
- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)
## Changes Made
- `headroom/mcp_registry/ledger.py`: in `_read_ledger`'s mutation
preflight, skip a section that is **absent** (`section not in data`) as
a valid empty ledger. A section that is *present* but not a dict (e.g.
`{"agents": null}`) is still rejected as malformed — the distinction is
key-absence, not a `None` value, so the existing unsafe-shape rejections
are unchanged.
- `tests/test_mcp_registry/test_ledger.py`: added
`test_mutation_preflight_accepts_empty_ledger` (`{}` and `{"agents":
{}}`) and
`test_mutation_preflight_accepts_ledger_after_clearing_last_install`
(install -> clear -> validate).
## Testing
- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
### Test Output
```text
tests/test_mcp_registry/test_ledger.py -> 18 passed in 0.98s
uvx ruff@0.16.2 check headroom/mcp_registry/ledger.py tests/test_mcp_registry/test_ledger.py -> All checks passed!
uvx mypy@1.20.2 headroom/mcp_registry/ledger.py -> Success: no issues found in 1 source file
```
## Real Behavior Proof
- Environment: Windows 11, Python 3.12.11, project venv, pytest 9.1.1,
ruff 0.16.2 and mypy 1.20.2 via uvx.
- Exact command / steps: before the fix, `record_install` then
`clear_install` leaves `{}`, and `validate_ledger_for_mutation` raised
`LedgerMutationError: ... 'agents' is malformed`. After the fix, that
validates cleanly, while `{"agents": null}`, `{"agents": []}`, and
`{"agents": {"claude": null}}` are still rejected and a populated ledger
still validates.
- Observed result: empty ledgers (absent or empty `agents`) accepted;
all previously-rejected malformed shapes still rejected.
- Not tested: no live `headroom mcp adopt` end-to-end run; the ledger
preflight is exercised directly (it is the function the command calls).
## Runtime Rollout Safety
- Rollout-managed feature(s): none. This is the MCP install-ledger
preflight in the CLI, not a rollout-channel-gated runtime feature.
- Minimum rollout channel: N/A.
- Stable/default behavior changed: no, except that a valid empty ledger
is no longer misreported as malformed. Malformed-shape rejection is
unchanged.
- Kill switch / disable path: N/A.
- Unsafe override required: no.
- Qualification impact: none.
- Rollback path: revert this PR.
## Review Readiness
- [x] I have performed a self-review
- [x] This PR is ready for human review
## Checklist
- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation (N/A:
internal behavior)
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md`
This commit is contained in:
@@ -127,6 +127,16 @@ def _read_ledger(path: Path, *, for_mutation: bool = False) -> dict[str, Any]:
|
||||
return {}
|
||||
if for_mutation:
|
||||
for section in ("agents",):
|
||||
# An *absent* section is a valid empty ledger, not a malformed one.
|
||||
# ``clear_install`` pops ``agents`` once its last entry is removed, so
|
||||
# a fully-unwrapped ledger is exactly ``{}`` — and ``record_install``
|
||||
# likewise treats a missing ``agents`` as empty. Rejecting it here made
|
||||
# the very next mutation (e.g. ``headroom mcp adopt``) fail with a
|
||||
# bogus "malformed" error after an ordinary unwrap. A section that is
|
||||
# *present* but not a dict (e.g. ``{"agents": null}``) is still
|
||||
# malformed — so key-absence, not a ``None`` value, is what is skipped.
|
||||
if section not in data:
|
||||
continue
|
||||
section_data = data.get(section)
|
||||
if not isinstance(section_data, dict) or any(
|
||||
not isinstance(agent_entry, dict)
|
||||
|
||||
@@ -55,6 +55,28 @@ def test_mutation_preflight_rejects_unsafe_shapes(tmp_path, value):
|
||||
validate_ledger_for_mutation(ledger)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("contents", ["{}", '{"agents": {}}'])
|
||||
def test_mutation_preflight_accepts_empty_ledger(tmp_path, contents):
|
||||
"""An empty ledger must not be rejected as malformed.
|
||||
|
||||
``clear_install`` pops the ``agents`` section once its last entry is removed,
|
||||
so a fully-unwrapped ledger is exactly ``{}``. Rejecting it made the next
|
||||
mutation (``headroom mcp adopt``) fail with a bogus "malformed" error.
|
||||
"""
|
||||
ledger = tmp_path / "mcp_installs.json"
|
||||
ledger.write_text(contents)
|
||||
validate_ledger_for_mutation(ledger) # must not raise
|
||||
|
||||
|
||||
def test_mutation_preflight_accepts_ledger_after_clearing_last_install(tmp_path):
|
||||
ledger = tmp_path / "mcp_installs.json"
|
||||
spec = _spec()
|
||||
record_install("claude", spec, path=ledger)
|
||||
clear_install("claude", "serena", path=ledger)
|
||||
assert ledger.read_text().strip() == "{}"
|
||||
validate_ledger_for_mutation(ledger) # must not raise
|
||||
|
||||
|
||||
def test_mutation_preflight_rejects_unreadable_ledger(monkeypatch, tmp_path):
|
||||
ledger = tmp_path / "mcp_installs.json"
|
||||
ledger.write_text('{"agents": {}}')
|
||||
|
||||
Reference in New Issue
Block a user