diff --git a/flake.nix b/flake.nix index 345258b..56f4e30 100644 --- a/flake.nix +++ b/flake.nix @@ -14,6 +14,7 @@ runtimeDeps = [ ps.websockets ps.mcp + ps.pydantic ps.asyncssh ps.uvicorn ]; diff --git a/pyproject.toml b/pyproject.toml index 6a374e3..62ab42a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -10,6 +10,7 @@ requires-python = ">=3.14" dependencies = [ "websockets", "mcp", + "pydantic", "asyncssh", "uvicorn", ] diff --git a/src/lg_smtv_mcp/config.py b/src/lg_smtv_mcp/config.py index b055de4..3d48520 100644 --- a/src/lg_smtv_mcp/config.py +++ b/src/lg_smtv_mcp/config.py @@ -1,16 +1,21 @@ -"""Runtime configuration loader and stdlib .env parser.""" +"""Runtime configuration loader, Pydantic v2 validation model, and stdlib .env parser.""" +import ipaddress import os -from dataclasses import dataclass from pathlib import Path +from typing import Any -from lg_smtv_mcp.errors import ErrorCode, TvError +from pydantic import BaseModel, ConfigDict, ValidationError, field_validator +from pydantic_core import PydanticCustomError + +from lg_smtv_mcp.errors import ConfigError -@dataclass(frozen=True) -class TvConfig: +class TvConfig(BaseModel): """Validated runtime configuration for lg-smtv-mcp.""" + model_config = ConfigDict(frozen=True, extra="forbid") + tv_ip: str tv_mac: str | None = None wol_broadcast: str = "255.255.255.255" @@ -25,6 +30,101 @@ class TvConfig: max_volume: int = 40 enable_raw_ssap: bool = False + def __init__(self, **data: Any) -> None: + try: + super().__init__(**data) + except ValidationError as exc: + messages = "; ".join(err["msg"] for err in exc.errors()) + raise ConfigError(messages) from exc + + @field_validator("tv_ip", mode="before") + @classmethod + def _validate_tv_ip(cls, value: Any) -> str: + if not isinstance(value, str) or not value.strip(): + raise PydanticCustomError( + "missing_tv_ip", + "TV_IP is required and must be a non-empty IPv4 address", + ) + cleaned = value.strip() + try: + ipaddress.IPv4Address(cleaned) + except ValueError as exc: + raise PydanticCustomError( + "invalid_tv_ip", + "TV_IP must be a valid IPv4 address, got {tv_ip!r}", + {"tv_ip": cleaned}, + ) from exc + return cleaned + + @field_validator("wol_broadcast", mode="before") + @classmethod + def _validate_wol_broadcast(cls, value: Any) -> str: + if not isinstance(value, str) or not value.strip(): + raise PydanticCustomError( + "invalid_wol_broadcast", + "WOL_BROADCAST must be a valid IPv4 address", + ) + cleaned = value.strip() + try: + ipaddress.IPv4Address(cleaned) + except ValueError as exc: + raise PydanticCustomError( + "invalid_wol_broadcast", + "WOL_BROADCAST must be a valid IPv4 address, got {ip!r}", + {"ip": cleaned}, + ) from exc + return cleaned + + @field_validator("port", mode="before") + @classmethod + def _validate_port(cls, value: Any) -> int: + if isinstance(value, bool): + raise PydanticCustomError( + "invalid_port", + "PORT must be an integer between 1 and 65535, got {val!r}", + {"val": value}, + ) + try: + parsed = int(value.strip()) if isinstance(value, str) else int(value) + except (ValueError, TypeError) as exc: + raise PydanticCustomError( + "invalid_port", + "PORT must be an integer between 1 and 65535, got {val!r}", + {"val": value}, + ) from exc + if not (1 <= parsed <= 65535): + raise PydanticCustomError( + "invalid_port_range", + "PORT must be between 1 and 65535, got {val}", + {"val": parsed}, + ) + return parsed + + @field_validator("max_volume", mode="before") + @classmethod + def _validate_max_volume(cls, value: Any) -> int: + if isinstance(value, bool): + raise PydanticCustomError( + "invalid_max_volume", + "MAX_VOLUME must be an integer between 0 and 100, got {val!r}", + {"val": value}, + ) + try: + parsed = int(value.strip()) if isinstance(value, str) else int(value) + except (ValueError, TypeError) as exc: + raise PydanticCustomError( + "invalid_max_volume", + "MAX_VOLUME must be an integer between 0 and 100, got {val!r}", + {"val": value}, + ) from exc + if not (0 <= parsed <= 100): + raise PydanticCustomError( + "invalid_max_volume_range", + "MAX_VOLUME must be between 0 and 100, got {val}", + {"val": parsed}, + ) + return parsed + def _load_dotenv(env_path: Path) -> None: """Populate unset os.environ keys from a .env file using stdlib only.""" @@ -53,24 +153,6 @@ def _load_dotenv(env_path: Path) -> None: os.environ.setdefault(key, value) -def _parse_int_range(name: str, raw: str | None, default: int, min_val: int, max_val: int) -> int: - if raw is None or not raw.strip(): - return default - try: - parsed = int(raw.strip()) - except ValueError as exc: - raise TvError( - ErrorCode.INVALID_ARGUMENT, - f"{name} must be an integer between {min_val} and {max_val}, got {raw!r}", - ) from exc - if not (min_val <= parsed <= max_val): - raise TvError( - ErrorCode.INVALID_ARGUMENT, - f"{name} must be between {min_val} and {max_val}, got {parsed}", - ) - return parsed - - def _optional_str(name: str) -> str | None: raw = os.environ.get(name) if raw is None: @@ -89,14 +171,9 @@ def load_config(env_path: Path | None = Path(".env")) -> TvConfig: if env_path is not None: _load_dotenv(env_path) - tv_ip = _optional_str("TV_IP") - if tv_ip is None: - raise TvError(ErrorCode.INVALID_ARGUMENT, "TV_IP is required and must be non-empty") - - port = _parse_int_range("PORT", os.environ.get("PORT"), default=8765, min_val=1, max_val=65535) - max_volume = _parse_int_range( - "MAX_VOLUME", os.environ.get("MAX_VOLUME"), default=40, min_val=0, max_val=100 - ) + tv_ip = _optional_str("TV_IP") or "" + port_raw = _optional_str("PORT") + max_volume_raw = _optional_str("MAX_VOLUME") host = _optional_str("HOST") or "127.0.0.1" wol_broadcast = _optional_str("WOL_BROADCAST") or "255.255.255.255" @@ -108,38 +185,36 @@ def load_config(env_path: Path | None = Path(".env")) -> TvConfig: enable_raw_raw = (os.environ.get("ENABLE_RAW_SSAP") or "").strip().lower() enable_raw_ssap = enable_raw_raw in {"1", "true", "yes", "on"} - return TvConfig( - tv_ip=tv_ip, - tv_mac=_optional_str("TV_MAC"), - wol_broadcast=wol_broadcast, - client_key_path=client_key_path, - ssh_key_path=_optional_path("SSH_KEY_PATH"), - webos_ssh_passphrase=os.environ.get("WEBOS_SSH_PASSPHRASE") or None, - ssh_known_hosts_path=_optional_path("SSH_KNOWN_HOSTS_PATH"), - host=host, - port=port, - allowed_hosts=allowed_hosts, - mcp_bearer_token=_optional_str("MCP_BEARER_TOKEN"), - max_volume=max_volume, - enable_raw_ssap=enable_raw_ssap, - ) + kwargs: dict[str, Any] = { + "tv_ip": tv_ip, + "tv_mac": _optional_str("TV_MAC"), + "wol_broadcast": wol_broadcast, + "client_key_path": client_key_path, + "ssh_key_path": _optional_path("SSH_KEY_PATH"), + "webos_ssh_passphrase": os.environ.get("WEBOS_SSH_PASSPHRASE") or None, + "ssh_known_hosts_path": _optional_path("SSH_KNOWN_HOSTS_PATH"), + "host": host, + "allowed_hosts": allowed_hosts, + "mcp_bearer_token": _optional_str("MCP_BEARER_TOKEN"), + "enable_raw_ssap": enable_raw_ssap, + } + if port_raw is not None: + kwargs["port"] = port_raw + if max_volume_raw is not None: + kwargs["max_volume"] = max_volume_raw + + return TvConfig(**kwargs) def require_bearer_token(config: TvConfig) -> str: - """Return a non-empty MCP_BEARER_TOKEN or raise INVALID_ARGUMENT.""" + """Return a non-empty MCP_BEARER_TOKEN or raise ConfigError.""" if config.mcp_bearer_token is None or not config.mcp_bearer_token.strip(): - raise TvError( - ErrorCode.INVALID_ARGUMENT, - "MCP_BEARER_TOKEN is required when running streamable-http transport", - ) + raise ConfigError("MCP_BEARER_TOKEN is required when running streamable-http transport") return config.mcp_bearer_token.strip() def require_mac(config: TvConfig) -> str: - """Return a non-empty TV_MAC or raise INVALID_ARGUMENT.""" + """Return a non-empty TV_MAC or raise ConfigError.""" if config.tv_mac is None or not config.tv_mac.strip(): - raise TvError( - ErrorCode.INVALID_ARGUMENT, - "TV_MAC is required for Wake-on-LAN (tv_wake)", - ) + raise ConfigError("TV_MAC is required for Wake-on-LAN (tv_wake)") return config.tv_mac.strip() diff --git a/src/lg_smtv_mcp/errors.py b/src/lg_smtv_mcp/errors.py index 0479fc7..9249ff2 100644 --- a/src/lg_smtv_mcp/errors.py +++ b/src/lg_smtv_mcp/errors.py @@ -22,3 +22,11 @@ class TvError(Exception): super().__init__(f"{code.value}: {message}") self.code = code self.message = message + + +class ConfigError(Exception): + """Raised when runtime configuration is missing or fails validation.""" + + def __init__(self, message: str) -> None: + super().__init__(message) + self.message = message diff --git a/tests/test_config.py b/tests/test_config.py index ab617b8..07913bf 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -4,7 +4,7 @@ from pathlib import Path import pytest from lg_smtv_mcp.config import TvConfig, load_config, require_bearer_token, require_mac -from lg_smtv_mcp.errors import ErrorCode, TvError +from lg_smtv_mcp.errors import ConfigError, ErrorCode, TvError def _clear_tv_env(monkeypatch: pytest.MonkeyPatch) -> None: @@ -45,6 +45,12 @@ def test_error_code_and_tv_error() -> None: assert err.message == "bad input" assert "bad input" in str(err) + cfg_err = ConfigError("invalid TV_IP") + assert isinstance(cfg_err, Exception) + assert not isinstance(cfg_err, TvError) + assert cfg_err.message == "invalid TV_IP" + assert str(cfg_err) == "invalid TV_IP" + def test_load_config_defaults(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: _clear_tv_env(monkeypatch) @@ -92,6 +98,8 @@ def test_dotenv_fallback_does_not_overwrite_existing_env( [ ({}, "TV_IP"), ({"TV_IP": " "}, "TV_IP"), + ({"TV_IP": "999.999.999.999"}, "TV_IP"), + ({"TV_IP": "192.0.2.10", "WOL_BROADCAST": "not-an-ip"}, "WOL_BROADCAST"), ({"TV_IP": "192.0.2.10", "MAX_VOLUME": "-1"}, "MAX_VOLUME"), ({"TV_IP": "192.0.2.10", "MAX_VOLUME": "101"}, "MAX_VOLUME"), ({"TV_IP": "192.0.2.10", "MAX_VOLUME": "loud"}, "MAX_VOLUME"), @@ -110,10 +118,29 @@ def test_load_config_validation_errors( for k, v in env_overrides.items(): monkeypatch.setenv(k, v) - with pytest.raises(TvError) as exc_info: + with pytest.raises(ConfigError) as exc_info: load_config(env_path=tmp_path / "missing.env") - assert exc_info.value.code is ErrorCode.INVALID_ARGUMENT + assert expected_substr in exc_info.value.message + + +@pytest.mark.parametrize( + ("kwargs", "expected_substr"), + [ + ({"tv_ip": ""}, "TV_IP"), + ({"tv_ip": "not-an-ip"}, "TV_IP"), + ({"tv_ip": "192.0.2.10", "port": 70000}, "PORT"), + ({"tv_ip": "192.0.2.10", "max_volume": 150}, "MAX_VOLUME"), + ({"tv_ip": "192.0.2.10", "wol_broadcast": "bad-ip"}, "WOL_BROADCAST"), + ], +) +def test_tv_config_direct_instantiation_enforces_pydantic_validation( + kwargs: dict[str, object], + expected_substr: str, +) -> None: + with pytest.raises(ConfigError) as exc_info: + TvConfig(**kwargs) # type: ignore[arg-type] + assert expected_substr in exc_info.value.message @@ -137,10 +164,10 @@ def test_require_bearer_token_rejects_missing_or_blank( monkeypatch.setenv("MCP_BEARER_TOKEN", token) cfg = load_config(env_path=tmp_path / "missing.env") - with pytest.raises(TvError) as exc_info: + with pytest.raises(ConfigError) as exc_info: require_bearer_token(cfg) - assert exc_info.value.code is ErrorCode.INVALID_ARGUMENT + assert "MCP_BEARER_TOKEN" in exc_info.value.message def test_require_bearer_token_returns_trimmed_value( @@ -164,10 +191,10 @@ def test_require_mac_rejects_missing_or_blank( monkeypatch.setenv("TV_MAC", mac) cfg = load_config(env_path=tmp_path / "missing.env") - with pytest.raises(TvError) as exc_info: + with pytest.raises(ConfigError) as exc_info: require_mac(cfg) - assert exc_info.value.code is ErrorCode.INVALID_ARGUMENT + assert "TV_MAC" in exc_info.value.message def test_require_mac_returns_trimmed_value(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: