mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 18:41:07 +08:00
## Description Removes private CLI helpers that no product code calls any more. Each one lost its last caller in an earlier rewrite, so only its own unit tests still called it. The tests that pinned the dead code go with it. Refs #4136 ## Type of Change - [ ] 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 - [x] Code refactoring (no functional changes) ## Changes Made - `headroom/cli/wrap.py`: removed six dead helpers and constants. - `_wrap_marker_proxy_is_dead`: the self-heal path now calls `_wrap_proxy_alive` inline. - `_agent_savings_config_mismatches` and `_AGENT_SAVINGS_TARGET_AGENTS`: the live restart check only compares `savings_profile`. - The `_normalize_openclaw_gateway_provider_ids` forwarder and its import alias. - A dead copy of `_opencode_home_dir`; the real one lives in `providers/opencode/config.py`. - The unused `_CONTEXT_1M_SUFFIX` and `_OPENCLAUDE_INSTRUCTIONS_FILE` constants. - `headroom/cli/proxy.py`: removed `_get_env_float_optional`, which had no callers. - `headroom/cli/mcp.py`: removed `get_headroom_command`, `load_mcp_config`, `save_mcp_config`, `find_headroom_registration` and the `CLAUDE_CONFIG_DIR` / `MCP_CONFIG_PATH` / `CLAUDE_JSON_PATH` constants. - `mcp install`, `mcp status` and `mcp uninstall` all go through `headroom.mcp_registry` registrars now. - `load_mcp_config` returned `{}` on corrupt JSON, and `save_mcp_config` would then overwrite the file. That data-loss path goes away with them. - Tests removed, because they only exercised the deleted code: - `tests/test_cli/test_mcp_status.py`, all of which tested `find_headroom_registration`; - `TestMCPConfigFunctions` and its path fixtures in `tests/test_cli/test_mcp.py`; - 3 `_wrap_marker_proxy_is_dead` tests; - 5 `_agent_savings_config_mismatches` tests; - 1 forwarder test. - The remaining `mcp uninstall` / `mcp status` tests already patch the registrars. They no longer take the path fixture. Evidence: `rg -n -w '<name>' headroom crates plugins sdk examples benchmarks scripts e2e docs wiki .github pyproject.toml tests <consumer repos>` for each name finds only the definition and the removed tests. Live behaviour stays covered: - `test_wrap_dead_marker_selfheal.py`: `test_dead_port_*`, `test_live_port_is_never_cleared` and the `_wrap_proxy_alive` tests; - `tests/test_provider_openclaw_wrap.py`; - `test_mcp.py::TestMCPStatusCommand` / `TestMCPUninstallCommand`. ## Testing - [x] Unit tests pass (`pytest`) - [x] Linting passes (`ruff check .`) - [x] Type checking passes (`mypy headroom`) - [ ] New tests added for new functionality - [ ] Manual testing performed ### Test Output ```text $ pytest -q -p no:cacheprovider tests/test_cli/test_wrap_dead_marker_selfheal.py tests/test_agent_savings.py tests/test_cli/test_wrap_openclaw.py tests/test_cli/test_wrap_opencode.py tests/test_cli/test_mcp.py tests/test_cli/test_wrap_helpers.py tests/test_provider_openclaw_wrap.py tests/test_cli/test_main_help_version.py 253 passed in 33.08s $ uvx ruff@0.16.8 check headroom/cli tests/test_cli tests/test_agent_savings.py All checks passed! $ mypy headroom/cli/wrap.py headroom/cli/mcp.py headroom/cli/proxy.py --ignore-missing-imports Success: no issues found in 3 source files ``` ## Real Behavior Proof - Environment: macOS, Python 3.12, repo `.venv`, branch cut from `origin/main` ata9815bbb. - Exact command / steps: ran the pytest files above, which cover `wrap`, `unwrap`, `mcp status` and `mcp uninstall` via CliRunner, plus `headroom --help` / `--version`. - Observed result: all 253 passed; ruff and mypy are clean. - Smoke harness (real proxy started from this checkout against a local fake upstream; temp HOME and workspace, offline): ```text branch: cleanup/cli-integrations-dead-cli-helpers @5f450556health: 200 POST /v1/messages -> HTTP200 smoke-ok POST /v1/chat/completions -> HTTP200 smoke-ok stats: requests=2 failed=0 tokens_saved=13574 savings_percent=99.82 proxy.log WARNING/ERROR lines (<tmp>/ws/logs/proxy-63492.log): 2 headroom.proxy - WARNING - event=proxy_offline_mode air-gap active — every connection Headroom initiates is refused (telemetry, update check, license reporter, model/tokenizer/binary/dataset downloads, remote Kompress, OTLP/Langfuse export, Copilot auth, subscription polling, OpenAI embedders, Headroom Cloud compression). Still allowed on purpose: forwarding your requests to the upstream you configured, operator-configured local endpoints, loopback health probes. 4 headroom.transforms.kompress_compressor - WARNING - Kompress: artifact prefetch found no usable file for chopratejas/kompress-v2-base 4 headroom.transforms.kompress_compressor - WARNING - Kompress: artifact prefetch refused for chopratejas/kompress-v2-base (HEADROOM_OFFLINE is set): HEADROOM_OFFLINE is set: refusing outbound network access for HuggingFace download of chopratejas/kompress-v2-base/onnx/kompress-int8-wo.onnx to huggingface.co. Unset HEADROOM_OFFLINE, or turn off the feature that needs this connection. (smoke dir: <tmp>) ``` - Direct runtime command on this PR's own path (temp HOME, HEADROOM_WORKSPACE_DIR and CODEX_HOME): ```text $ HOME=<tmp>/home HEADROOM_WORKSPACE_DIR=<tmp>/ws CODEX_HOME=<tmp>/codex headroom mcp install --agent claude exit=0 --- stdout Installing Headroom MCP server... claude: registered (restart the agent if it was already running) Next steps: 1. Start the Headroom proxy (if not running): headroom proxy 2. Start your agent (e.g.) ANTHROPIC_BASE_URL=http://127.0.0.1:8787 claude 3. Restart any agent that was already running so it picks up the new MCP server. --- stderr $ HOME=<tmp>/home HEADROOM_WORKSPACE_DIR=<tmp>/ws CODEX_HOME=<tmp>/codex headroom mcp status exit=0 --- stdout Headroom MCP Status ======================================== MCP SDK: ✓ Installed Agent Config: Antigravity IDE: ✗ Not detected Claude Code: ✓ Configured $ HOME=<tmp>/home HEADROOM_WORKSPACE_DIR=<tmp>/ws CODEX_HOME=<tmp>/codex headroom mcp uninstall exit=0 --- stdout ✓ Claude Code: removed headroom MCP server(s) --- stderr ``` - Not tested: a live `headroom wrap` session against a real agent binary. Only unreferenced private code was deleted, so no runtime path changes. ## Runtime Rollout Safety - Rollout-managed feature(s): None. - Minimum rollout channel: N/A, no rollout-managed behaviour. - Stable/default behavior changed: No. Only code with no callers is removed. - Kill switch / disable path: N/A. - Unsafe override required: No. - Qualification impact: None. - Rollback path: Revert this commit. ## 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 - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [x] My changes generate no new warnings - [ ] 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` — it is generated by release-please from my Conventional Commit PR title (a CI guard enforces this) ## Screenshots (if applicable) N/A ## Additional Notes - Part of maintainer-requested cleanup #4136 (dead code, duplication, debuggability), split into small PRs for review. - No new tests or docs are needed, because this is a pure removal and none of the removed names were documented. - `_DEFAULT_1M_MODEL` stays, because `tests/test_cli/test_wrap_helpers.py` pins it. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- devin-review-badge-begin --> --- <a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4118" target="_blank"><picture><source media="(prefers-color-scheme: dark)" srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4" alt="Devin Review"></picture></a> <!-- devin-review-badge-end --> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
314 lines
11 KiB
Python
314 lines
11 KiB
Python
"""Integration tests for MCP CLI commands.
|
|
|
|
These are real tests that:
|
|
- Actually write/read config files
|
|
- Test actual CLI behavior
|
|
- Test MCP server initialization (when MCP SDK is available)
|
|
"""
|
|
|
|
import sys
|
|
from unittest.mock import AsyncMock, MagicMock, patch
|
|
|
|
import pytest
|
|
from click.testing import CliRunner
|
|
|
|
from headroom.cli.main import main
|
|
from headroom.mcp_registry.base import ServerSpec
|
|
|
|
# Check if MCP SDK is available
|
|
try:
|
|
import mcp # noqa: F401
|
|
|
|
MCP_AVAILABLE = True
|
|
except ImportError:
|
|
MCP_AVAILABLE = False
|
|
|
|
|
|
@pytest.fixture
|
|
def mock_mcp_available():
|
|
"""Mock MCP SDK as available for testing install/uninstall commands."""
|
|
mock_mcp = MagicMock()
|
|
with patch.dict(sys.modules, {"mcp": mock_mcp}):
|
|
yield mock_mcp
|
|
|
|
|
|
class FakeRegistrar:
|
|
name = "fake"
|
|
display_name = "Fake Agent"
|
|
|
|
def __init__(self, *, configured: bool = True) -> None:
|
|
self.configured = configured
|
|
self.removed: list[str] = []
|
|
|
|
def detect(self) -> bool:
|
|
return True
|
|
|
|
def get_server(self, server_name: str) -> ServerSpec | None:
|
|
if self.configured and server_name == "headroom":
|
|
return ServerSpec(name="headroom", command="headroom", args=("mcp", "serve"))
|
|
return None
|
|
|
|
def unregister_server(self, server_name: str) -> bool:
|
|
if self.configured and server_name == "headroom":
|
|
self.configured = False
|
|
self.removed.append(server_name)
|
|
return True
|
|
return False
|
|
|
|
|
|
#
|
|
# Note: Tests for the 'mcp install' command's writes/idempotency/CLI-vs-file
|
|
# fallback used to live here, but they were tightly coupled to private
|
|
# module globals (config paths, shutil.which) and exercised the same surface
|
|
# already covered by:
|
|
# - tests/test_mcp_registry/test_claude_registrar.py (file/CLI behavior
|
|
# with proper constructor injection — no patches)
|
|
# - tests/test_mcp_registry/test_install.py (orchestrator semantics with
|
|
# fake registrars)
|
|
# Removing the duplicates leaves the CLI as glue: argument parsing +
|
|
# output formatting, which is straightforward and not worth its own test
|
|
# layer.
|
|
|
|
|
|
class TestMCPUninstallCommand:
|
|
"""Test 'headroom mcp uninstall' command."""
|
|
|
|
def test_uninstall_removes_headroom(self, mock_mcp_available):
|
|
"""Uninstall removes headroom through detected registrars."""
|
|
registrar = FakeRegistrar()
|
|
|
|
runner = CliRunner()
|
|
with patch("headroom.mcp_registry.get_all_registrars", return_value=[registrar]):
|
|
result = runner.invoke(main, ["mcp", "uninstall"])
|
|
|
|
assert result.exit_code == 0
|
|
assert "removed" in result.output.lower()
|
|
assert registrar.removed == ["headroom"]
|
|
|
|
def test_uninstall_checks_only_headroom_servers(self):
|
|
"""Uninstall only asks registrars to remove Headroom-owned servers."""
|
|
registrar = FakeRegistrar()
|
|
|
|
runner = CliRunner()
|
|
with patch("headroom.mcp_registry.get_all_registrars", return_value=[registrar]):
|
|
result = runner.invoke(main, ["mcp", "uninstall"])
|
|
|
|
assert result.exit_code == 0
|
|
assert registrar.removed == ["headroom"]
|
|
|
|
def test_uninstall_no_config_file(self):
|
|
"""Uninstall with no config file exits cleanly."""
|
|
runner = CliRunner()
|
|
with patch("headroom.mcp_registry.get_all_registrars", return_value=[]):
|
|
result = runner.invoke(main, ["mcp", "uninstall"])
|
|
|
|
assert result.exit_code == 0
|
|
assert "nothing to uninstall" in result.output.lower()
|
|
|
|
def test_uninstall_not_configured(self):
|
|
"""Uninstall when headroom not in config exits cleanly."""
|
|
registrar = FakeRegistrar(configured=False)
|
|
|
|
runner = CliRunner()
|
|
with patch("headroom.mcp_registry.get_all_registrars", return_value=[registrar]):
|
|
result = runner.invoke(main, ["mcp", "uninstall"])
|
|
|
|
assert result.exit_code == 0
|
|
assert "not configured" in result.output.lower()
|
|
|
|
def test_uninstall_agent_filter_restricts_registrars(self):
|
|
"""--agent limits uninstallation to the named registrars."""
|
|
antigravity = FakeRegistrar()
|
|
antigravity.name = "antigravity"
|
|
claude = FakeRegistrar()
|
|
claude.name = "claude"
|
|
|
|
runner = CliRunner()
|
|
with patch(
|
|
"headroom.mcp_registry.get_all_registrars",
|
|
return_value=[antigravity, claude],
|
|
):
|
|
result = runner.invoke(main, ["mcp", "uninstall", "--agent", "antigravity"])
|
|
|
|
assert result.exit_code == 0
|
|
assert antigravity.removed == ["headroom"]
|
|
assert claude.removed == []
|
|
|
|
def test_uninstall_agent_filter_no_match_exits_nonzero(self):
|
|
"""--agent with no matching registrar exits non-zero."""
|
|
runner = CliRunner()
|
|
with patch("headroom.mcp_registry.get_all_registrars", return_value=[FakeRegistrar()]):
|
|
result = runner.invoke(main, ["mcp", "uninstall", "--agent", "bogus"])
|
|
|
|
assert result.exit_code == 1
|
|
assert "no agents matched" in result.output.lower()
|
|
|
|
|
|
class TestMCPStatusCommand:
|
|
"""Test 'headroom mcp status' command."""
|
|
|
|
def test_status_not_configured(self):
|
|
"""Status shows not configured when no config."""
|
|
runner = CliRunner()
|
|
registrar = FakeRegistrar(configured=False)
|
|
with patch("headroom.mcp_registry.get_all_registrars", return_value=[registrar]):
|
|
result = runner.invoke(main, ["mcp", "status"])
|
|
|
|
assert result.exit_code == 0
|
|
assert "MCP SDK" in result.output
|
|
# Should show not configured
|
|
assert (
|
|
"✗" in result.output
|
|
or "Not configured" in result.output.lower()
|
|
or "No config" in result.output
|
|
)
|
|
|
|
def test_status_configured(self, mock_mcp_available):
|
|
"""Status reports configured when a registrar has headroom."""
|
|
registrar = FakeRegistrar(configured=True)
|
|
|
|
runner = CliRunner()
|
|
with patch("headroom.mcp_registry.get_all_registrars", return_value=[registrar]):
|
|
result = runner.invoke(main, ["mcp", "status"])
|
|
|
|
assert result.exit_code == 0
|
|
assert "✓ Configured" in result.output
|
|
|
|
|
|
class TestMCPServeCommand:
|
|
"""Test 'headroom mcp serve' command."""
|
|
|
|
def test_serve_help(self):
|
|
"""Serve command shows help."""
|
|
runner = CliRunner()
|
|
result = runner.invoke(main, ["mcp", "serve", "--help"])
|
|
|
|
assert result.exit_code == 0
|
|
assert "transport" in result.output
|
|
assert "host" in result.output
|
|
assert "port" in result.output
|
|
assert "path" in result.output
|
|
assert "proxy-url" in result.output
|
|
assert "debug" in result.output
|
|
|
|
def test_serve_defaults_to_stdio(self):
|
|
"""Serve command defaults to stdio transport."""
|
|
fake_server = MagicMock()
|
|
fake_server.run_stdio = AsyncMock()
|
|
fake_server.run_streamable_http = AsyncMock()
|
|
fake_server.cleanup = AsyncMock()
|
|
|
|
runner = CliRunner()
|
|
with patch("headroom.ccr.mcp_server.create_ccr_mcp_server", return_value=fake_server):
|
|
result = runner.invoke(main, ["mcp", "serve"])
|
|
|
|
assert result.exit_code == 0
|
|
fake_server.run_stdio.assert_awaited_once()
|
|
fake_server.run_streamable_http.assert_not_awaited()
|
|
fake_server.cleanup.assert_awaited_once()
|
|
|
|
def test_serve_http_transport_uses_http_settings(self):
|
|
"""Serve command uses HTTP transport when requested with mixed-case input."""
|
|
fake_server = MagicMock()
|
|
fake_server.run_stdio = AsyncMock()
|
|
fake_server.run_streamable_http = AsyncMock()
|
|
fake_server.cleanup = AsyncMock()
|
|
|
|
runner = CliRunner()
|
|
with patch("headroom.ccr.mcp_server.create_ccr_mcp_server", return_value=fake_server):
|
|
result = runner.invoke(
|
|
main,
|
|
[
|
|
"mcp",
|
|
"serve",
|
|
"--transport",
|
|
"HTTP",
|
|
"--host",
|
|
"0.0.0.0",
|
|
"--port",
|
|
"9191",
|
|
"--path",
|
|
"/mcp",
|
|
],
|
|
)
|
|
|
|
assert result.exit_code == 0
|
|
fake_server.run_stdio.assert_not_awaited()
|
|
fake_server.run_streamable_http.assert_awaited_once_with(
|
|
host="0.0.0.0",
|
|
port=9191,
|
|
path="/mcp",
|
|
debug=False,
|
|
)
|
|
fake_server.cleanup.assert_awaited_once()
|
|
|
|
|
|
@pytest.mark.skipif(not MCP_AVAILABLE, reason="MCP SDK not installed")
|
|
class TestMCPServerInitialization:
|
|
"""Test actual MCP server creation.
|
|
|
|
These tests require the MCP SDK to be installed.
|
|
"""
|
|
|
|
def test_mcp_server_can_be_created(self):
|
|
"""MCP server can be instantiated."""
|
|
from headroom.ccr.mcp_server import create_ccr_mcp_server
|
|
|
|
server = create_ccr_mcp_server()
|
|
assert server is not None
|
|
assert server.proxy_url == "http://127.0.0.1:8787"
|
|
|
|
def test_mcp_server_with_custom_url(self):
|
|
"""MCP server accepts custom proxy URL."""
|
|
from headroom.ccr.mcp_server import create_ccr_mcp_server
|
|
|
|
server = create_ccr_mcp_server(proxy_url="http://custom:9000")
|
|
assert server.proxy_url == "http://custom:9000"
|
|
|
|
def test_mcp_server_has_correct_tool_name(self):
|
|
"""MCP server is configured for headroom_retrieve tool."""
|
|
from headroom.ccr.mcp_server import create_ccr_mcp_server
|
|
from headroom.ccr.tool_injection import CCR_TOOL_NAME
|
|
|
|
server = create_ccr_mcp_server()
|
|
|
|
# Verify the server was created with correct configuration
|
|
assert server.server is not None
|
|
assert server.server.name == "headroom"
|
|
# The tool name should be headroom_retrieve
|
|
assert CCR_TOOL_NAME == "headroom_retrieve"
|
|
|
|
|
|
#
|
|
# Tests for "install via claude CLI" used to live here, exercising
|
|
# subprocess.run patches against the old direct CLI invocation. Equivalent
|
|
# coverage now lives in tests/test_mcp_registry/test_claude_registrar.py
|
|
# using constructor injection (`claude_cli="/path/to/fake"`) and bounded
|
|
# subprocess.run mocks at the registrar boundary — no module-level patches.
|
|
|
|
|
|
class TestMCPUninstallWithRegistrars:
|
|
"""Test mcp_uninstall delegates to registrars."""
|
|
|
|
def test_uninstall_reports_removed_registrar_server(self):
|
|
registrar = FakeRegistrar(configured=True)
|
|
|
|
runner = CliRunner()
|
|
with patch("headroom.mcp_registry.get_all_registrars", return_value=[registrar]):
|
|
result = runner.invoke(main, ["mcp", "uninstall"])
|
|
|
|
assert result.exit_code == 0
|
|
assert "Fake Agent" in result.output
|
|
assert registrar.removed == ["headroom"]
|
|
|
|
def test_uninstall_skips_unconfigured_registrar(self):
|
|
registrar = FakeRegistrar(configured=False)
|
|
|
|
runner = CliRunner()
|
|
with patch("headroom.mcp_registry.get_all_registrars", return_value=[registrar]):
|
|
result = runner.invoke(main, ["mcp", "uninstall"])
|
|
|
|
assert result.exit_code == 0
|
|
assert "nothing to uninstall" in result.output.lower()
|
|
assert registrar.removed == []
|