Spaces:
Build error
Build error
File size: 21,199 Bytes
bc5c41c d45db57 bc5c41c d45db57 bc5c41c d45db57 bc5c41c 4d381a9 bc5c41c 4d381a9 bc5c41c 4d381a9 bc5c41c d45db57 bc5c41c d45db57 bc5c41c d45db57 bc5c41c d45db57 bc5c41c d45db57 bc5c41c d45db57 bc5c41c d45db57 bc5c41c d45db57 bc5c41c d45db57 bc5c41c d45db57 bc5c41c d45db57 bc5c41c d45db57 bc5c41c d45db57 bc5c41c d45db57 bc5c41c d45db57 bc5c41c d45db57 bc5c41c d45db57 bc5c41c facf3b5 bc5c41c d45db57 bc5c41c d45db57 bc5c41c 514dae4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 | """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 json
import sys
from unittest.mock import MagicMock, patch
import pytest
from click.testing import CliRunner
from headroom.cli.main import main
from headroom.cli.mcp import (
get_headroom_command,
load_mcp_config,
save_mcp_config,
)
# Check if MCP SDK is available
try:
import mcp # noqa: F401
MCP_AVAILABLE = True
except ImportError:
MCP_AVAILABLE = False
@pytest.fixture
def temp_claude_dir(tmp_path):
"""Create a temporary .claude directory for testing."""
claude_dir = tmp_path / ".claude"
claude_dir.mkdir()
return claude_dir
@pytest.fixture
def mock_claude_config_path(temp_claude_dir):
"""Patch the MCP config path to use temp directory.
Also mocks the claude CLI as absent so tests exercise the mcp.json
fallback path rather than the `claude mcp add` path.
"""
import shutil as _shutil
config_path = temp_claude_dir / "mcp.json"
# Capture the original function reference before patching so we don't recurse.
_real_which = _shutil.which
def which_no_claude(cmd):
if cmd == "claude":
return None
return _real_which(cmd)
with patch("headroom.cli.mcp.MCP_CONFIG_PATH", config_path):
with patch("headroom.cli.mcp.CLAUDE_CONFIG_DIR", temp_claude_dir):
with patch("headroom.cli.mcp.shutil.which", side_effect=which_no_claude):
yield config_path
@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 TestMCPConfigFunctions:
"""Test config file handling functions."""
def test_get_headroom_command_returns_list(self):
"""Command should be a list suitable for subprocess."""
cmd = get_headroom_command()
assert isinstance(cmd, list)
assert len(cmd) >= 1
# Should end with mcp serve args
assert "mcp" in cmd or "-m" in cmd
def test_load_mcp_config_empty_when_no_file(self, mock_claude_config_path):
"""Loading non-existent config returns empty structure."""
config = load_mcp_config()
assert config == {"mcpServers": {}}
def test_save_and_load_config(self, mock_claude_config_path):
"""Config can be saved and loaded back."""
test_config = {
"mcpServers": {
"headroom": {
"command": "headroom",
"args": ["mcp", "serve"],
}
}
}
save_mcp_config(test_config)
# File should exist
assert mock_claude_config_path.exists()
# Load it back
loaded = load_mcp_config()
assert loaded == test_config
def test_save_config_creates_directory(self, tmp_path):
"""save_mcp_config creates parent directory if needed."""
claude_dir = tmp_path / "new_dir" / ".claude"
config_path = claude_dir / "mcp.json"
with patch("headroom.cli.mcp.MCP_CONFIG_PATH", config_path):
with patch("headroom.cli.mcp.CLAUDE_CONFIG_DIR", claude_dir):
save_mcp_config({"mcpServers": {}})
assert config_path.exists()
def test_load_config_preserves_other_servers(self, mock_claude_config_path):
"""Loading preserves other MCP servers in config."""
# Write config with another server
existing_config = {
"mcpServers": {
"other-server": {"command": "other", "args": []},
}
}
mock_claude_config_path.write_text(json.dumps(existing_config))
loaded = load_mcp_config()
assert "other-server" in loaded["mcpServers"]
class TestMCPInstallCommand:
"""Test 'headroom mcp install' command."""
def test_install_creates_config(self, mock_claude_config_path, mock_mcp_available):
"""Install creates MCP config file."""
runner = CliRunner()
result = runner.invoke(main, ["mcp", "install"])
assert result.exit_code == 0, f"Failed with output: {result.output}"
assert "installed" in result.output.lower()
assert mock_claude_config_path.exists()
# Verify config content
config = json.loads(mock_claude_config_path.read_text())
assert "headroom" in config["mcpServers"]
assert config["mcpServers"]["headroom"]["command"] == "headroom"
assert "mcp" in config["mcpServers"]["headroom"]["args"]
assert "serve" in config["mcpServers"]["headroom"]["args"]
def test_install_preserves_other_servers(self, mock_claude_config_path, mock_mcp_available):
"""Install preserves existing MCP servers."""
# Create config with another server
existing_config = {
"mcpServers": {
"github": {"command": "github-mcp", "args": []},
}
}
mock_claude_config_path.write_text(json.dumps(existing_config))
runner = CliRunner()
result = runner.invoke(main, ["mcp", "install"])
assert result.exit_code == 0, f"Failed with output: {result.output}"
# Both servers should exist
config = json.loads(mock_claude_config_path.read_text())
assert "github" in config["mcpServers"]
assert "headroom" in config["mcpServers"]
def test_install_with_custom_proxy_url(self, mock_claude_config_path, mock_mcp_available):
"""Install with custom proxy URL sets env var."""
runner = CliRunner()
result = runner.invoke(main, ["mcp", "install", "--proxy-url", "http://localhost:9000"])
assert result.exit_code == 0, f"Failed with output: {result.output}"
config = json.loads(mock_claude_config_path.read_text())
assert (
config["mcpServers"]["headroom"]["env"]["HEADROOM_PROXY_URL"] == "http://localhost:9000"
)
def test_install_default_proxy_url_no_env(self, mock_claude_config_path, mock_mcp_available):
"""Install with default proxy URL doesn't set env var."""
runner = CliRunner()
result = runner.invoke(main, ["mcp", "install"])
assert result.exit_code == 0, f"Failed with output: {result.output}"
config = json.loads(mock_claude_config_path.read_text())
# No env section for default URL
assert "env" not in config["mcpServers"]["headroom"]
def test_install_already_configured_no_force(self, mock_claude_config_path, mock_mcp_available):
"""Install without --force when already configured exits cleanly."""
# First install
runner = CliRunner()
runner.invoke(main, ["mcp", "install"])
# Second install without force
result = runner.invoke(main, ["mcp", "install"])
assert result.exit_code == 0
assert "already configured" in result.output.lower()
def test_install_force_overwrites(self, mock_claude_config_path, mock_mcp_available):
"""Install with --force overwrites existing config."""
runner = CliRunner()
runner.invoke(main, ["mcp", "install", "--proxy-url", "http://old:8787"])
# Force install with new URL
result = runner.invoke(
main, ["mcp", "install", "--force", "--proxy-url", "http://new:9000"]
)
assert result.exit_code == 0, f"Failed with output: {result.output}"
assert "installed" in result.output.lower()
config = json.loads(mock_claude_config_path.read_text())
assert config["mcpServers"]["headroom"]["env"]["HEADROOM_PROXY_URL"] == "http://new:9000"
@pytest.mark.skipif(MCP_AVAILABLE, reason="Test only runs when MCP SDK is NOT installed")
def test_install_without_mcp_sdk_fails(self, mock_claude_config_path):
"""Install fails gracefully when MCP SDK is not installed."""
runner = CliRunner()
result = runner.invoke(main, ["mcp", "install"])
# Should fail with helpful message
assert result.exit_code == 1
assert "mcp" in result.output.lower() or "not installed" in result.output.lower()
class TestMCPUninstallCommand:
"""Test 'headroom mcp uninstall' command."""
def test_uninstall_removes_headroom(self, mock_claude_config_path, mock_mcp_available):
"""Uninstall removes headroom from config."""
# First install
runner = CliRunner()
runner.invoke(main, ["mcp", "install"])
# Then uninstall
result = runner.invoke(main, ["mcp", "uninstall"])
assert result.exit_code == 0
assert "removed" in result.output.lower()
config = json.loads(mock_claude_config_path.read_text())
assert "headroom" not in config["mcpServers"]
def test_uninstall_preserves_other_servers(self, mock_claude_config_path):
"""Uninstall preserves other MCP servers."""
# Create config with headroom and another server
config = {
"mcpServers": {
"headroom": {"command": "headroom", "args": ["mcp", "serve"]},
"github": {"command": "github-mcp", "args": []},
}
}
mock_claude_config_path.write_text(json.dumps(config))
runner = CliRunner()
result = runner.invoke(main, ["mcp", "uninstall"])
assert result.exit_code == 0
config = json.loads(mock_claude_config_path.read_text())
assert "headroom" not in config["mcpServers"]
assert "github" in config["mcpServers"]
def test_uninstall_no_config_file(self, mock_claude_config_path):
"""Uninstall with no config file exits cleanly."""
runner = CliRunner()
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, mock_claude_config_path):
"""Uninstall when headroom not in config exits cleanly."""
# Create config without headroom
config = {"mcpServers": {"other": {"command": "other"}}}
mock_claude_config_path.write_text(json.dumps(config))
runner = CliRunner()
result = runner.invoke(main, ["mcp", "uninstall"])
assert result.exit_code == 0
assert "not configured" in result.output.lower()
class TestMCPStatusCommand:
"""Test 'headroom mcp status' command."""
def test_status_not_configured(self, mock_claude_config_path):
"""Status shows not configured when no config."""
runner = CliRunner()
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_claude_config_path, mock_mcp_available):
"""Status shows configured when installed."""
runner = CliRunner()
runner.invoke(main, ["mcp", "install"])
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 "proxy-url" in result.output
assert "debug" in result.output
@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"
class TestEndToEndFlow:
"""Test complete install -> status -> uninstall flow."""
def test_full_lifecycle(self, mock_claude_config_path, mock_mcp_available):
"""Test complete lifecycle of MCP configuration."""
runner = CliRunner()
# Initially not configured
result = runner.invoke(main, ["mcp", "status"])
assert "No config" in result.output or "Not configured" in result.output.lower()
# Install
result = runner.invoke(main, ["mcp", "install"])
assert result.exit_code == 0, f"Install failed: {result.output}"
assert "installed" in result.output.lower()
# Status shows configured
result = runner.invoke(main, ["mcp", "status"])
assert "✓ Configured" in result.output
# Config file has correct content
config = json.loads(mock_claude_config_path.read_text())
assert config["mcpServers"]["headroom"]["command"] == "headroom"
# Uninstall
result = runner.invoke(main, ["mcp", "uninstall"])
assert result.exit_code == 0
assert "removed" in result.output.lower()
# Status shows not configured
result = runner.invoke(main, ["mcp", "status"])
assert "headroom" not in result.output.lower() or "not configured" in result.output.lower()
class TestMCPInstallWithClaudeCLI:
"""Test mcp_install when the claude CLI is available."""
def _make_run(self, get_rc=1, add_rc=0, remove_rc=0):
"""Return a subprocess.run mock with configurable return codes."""
def run(cmd, **kwargs):
if "get" in cmd:
return MagicMock(returncode=get_rc, stderr="")
if "remove" in cmd:
return MagicMock(returncode=remove_rc, stderr="")
if "add" in cmd:
return MagicMock(returncode=add_rc, stderr="")
return MagicMock(returncode=0, stderr="")
return run
def test_install_uses_claude_mcp_add(self, mock_mcp_available):
"""When claude CLI is available, install calls claude mcp add."""
runner = CliRunner()
with patch("headroom.cli.mcp.shutil.which", return_value="/usr/bin/claude"):
with patch("headroom.cli.mcp.subprocess.run", side_effect=self._make_run()) as mock_run:
result = runner.invoke(main, ["mcp", "install"])
assert result.exit_code == 0, f"Failed: {result.output}"
assert "installed" in result.output.lower()
assert "claude mcp add" in result.output
# Verify claude mcp add was called
add_calls = [c for c in mock_run.call_args_list if "add" in c.args[0]]
assert len(add_calls) == 1
add_cmd = add_calls[0].args[0]
assert "headroom" in add_cmd
assert "-s" in add_cmd
assert "user" in add_cmd
def test_install_already_registered_no_force(self, mock_mcp_available):
"""Install without --force exits cleanly when already registered via claude CLI."""
runner = CliRunner()
with patch("headroom.cli.mcp.shutil.which", return_value="/usr/bin/claude"):
# get returns 0 → already registered
with patch("headroom.cli.mcp.subprocess.run", side_effect=self._make_run(get_rc=0)):
result = runner.invoke(main, ["mcp", "install"])
assert result.exit_code == 0
assert "already configured" in result.output.lower()
def test_install_force_calls_remove_then_add(self, mock_mcp_available):
"""--force calls claude mcp remove before claude mcp add."""
runner = CliRunner()
calls = []
def capturing_run(cmd, **kwargs):
calls.append(cmd)
return MagicMock(returncode=0, stderr="")
with patch("headroom.cli.mcp.shutil.which", return_value="/usr/bin/claude"):
with patch("headroom.cli.mcp.subprocess.run", side_effect=capturing_run):
result = runner.invoke(main, ["mcp", "install", "--force"])
assert result.exit_code == 0, f"Failed: {result.output}"
subcommands = [c[2] for c in calls] # third element is the subcommand
assert "remove" in subcommands
assert "add" in subcommands
assert subcommands.index("remove") < subcommands.index("add")
def test_install_fallback_on_claude_mcp_add_failure(self, temp_claude_dir, mock_mcp_available):
"""If claude mcp add fails, falls back to writing mcp.json."""
config_path = temp_claude_dir / "mcp.json"
with patch("headroom.cli.mcp.MCP_CONFIG_PATH", config_path):
with patch("headroom.cli.mcp.CLAUDE_CONFIG_DIR", temp_claude_dir):
with patch("headroom.cli.mcp.shutil.which", return_value="/usr/bin/claude"):
with patch(
"headroom.cli.mcp.subprocess.run",
side_effect=self._make_run(add_rc=1),
):
runner = CliRunner()
result = runner.invoke(main, ["mcp", "install"])
assert result.exit_code == 0, f"Failed: {result.output}"
assert config_path.exists()
config = json.loads(config_path.read_text())
assert "headroom" in config["mcpServers"]
def test_install_with_custom_proxy_url_passes_e_flag(self, mock_mcp_available):
"""Custom proxy URL is passed as -e KEY=VALUE to claude mcp add."""
calls = []
def capturing_run(cmd, **kwargs):
calls.append(list(cmd))
# Return rc=1 for "get" so headroom is treated as not yet registered
if "get" in cmd:
return MagicMock(returncode=1, stderr="")
return MagicMock(returncode=0, stderr="")
runner = CliRunner()
with patch("headroom.cli.mcp.shutil.which", return_value="/usr/bin/claude"):
with patch("headroom.cli.mcp.subprocess.run", side_effect=capturing_run):
result = runner.invoke(
main, ["mcp", "install", "--proxy-url", "http://custom:9000"]
)
assert result.exit_code == 0, f"Failed: {result.output}"
add_calls = [c for c in calls if "add" in c]
assert len(add_calls) == 1
add_cmd = add_calls[0]
assert "-e" in add_cmd
env_idx = add_cmd.index("-e")
assert add_cmd[env_idx + 1] == "HEADROOM_PROXY_URL=http://custom:9000"
class TestMCPUninstallWithClaudeCLI:
"""Test mcp_uninstall when the claude CLI is available."""
def test_uninstall_calls_claude_mcp_remove(self):
"""Uninstall calls claude mcp remove when headroom is registered."""
calls = []
def capturing_run(cmd, **kwargs):
calls.append(list(cmd))
return MagicMock(returncode=0, stderr="")
runner = CliRunner()
with patch("headroom.cli.mcp.shutil.which", return_value="/usr/bin/claude"):
with patch("headroom.cli.mcp.subprocess.run", side_effect=capturing_run):
result = runner.invoke(main, ["mcp", "uninstall"])
assert result.exit_code == 0
assert "removed" in result.output.lower()
subcommands = [c[2] for c in calls]
assert "remove" in subcommands
def test_uninstall_skips_remove_when_not_registered(self):
"""Uninstall does not call remove when headroom is not registered via claude CLI."""
calls = []
def capturing_run(cmd, **kwargs):
calls.append(list(cmd))
# mcp get returns non-zero → not registered
if "get" in cmd:
return MagicMock(returncode=1, stderr="")
return MagicMock(returncode=0, stderr="")
runner = CliRunner()
with patch("headroom.cli.mcp.shutil.which", return_value="/usr/bin/claude"):
with patch("headroom.cli.mcp.subprocess.run", side_effect=capturing_run):
result = runner.invoke(main, ["mcp", "uninstall"])
assert result.exit_code == 0
subcommands = [c[2] for c in calls]
assert "remove" not in subcommands
|