diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..c3ecb73 --- /dev/null +++ b/.env.example @@ -0,0 +1,13 @@ +TV_IP= +TV_MAC= +WOL_BROADCAST=255.255.255.255 +CLIENT_KEY_PATH=.client_key.json +SSH_KEY_PATH= +WEBOS_SSH_PASSPHRASE= +SSH_KNOWN_HOSTS_PATH= +HOST=127.0.0.1 +PORT=8765 +ALLOWED_HOSTS= +MCP_BEARER_TOKEN= +MAX_VOLUME=40 +ENABLE_RAW_SSAP=false diff --git a/.gitea/workflows/ci.yaml b/.gitea/workflows/ci.yaml new file mode 100644 index 0000000..6f4c2af --- /dev/null +++ b/.gitea/workflows/ci.yaml @@ -0,0 +1,27 @@ +name: Core Architecture & Invariant CI + +on: + push: + branches: [ main ] + pull_request: + branches: [ main ] + +jobs: + validate: + runs-on: ubuntu-latest + container: + image: nixery.dev/shell/coreutils/git/nix/nodejs:latest + steps: + - name: Check out repository + uses: actions/checkout@v4 + + - name: Configure Git Safe Directory & Nix Flakes + run: | + git config --global --add safe.directory "$GITHUB_WORKSPACE" + mkdir -p ~/.config/nix + echo "experimental-features = nix-command flakes" >> ~/.config/nix/nix.conf + echo "build-users-group =" >> ~/.config/nix/nix.conf + + - name: Run Architecture & Security Invariant Checks + run: | + nix flake check diff --git a/.githooks/pre-commit b/.githooks/pre-commit new file mode 100755 index 0000000..df299d5 --- /dev/null +++ b/.githooks/pre-commit @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +set -euo pipefail + +if command -v ruff >/dev/null 2>&1 && command -v pyright >/dev/null 2>&1 && command -v pytest >/dev/null 2>&1; then + ruff check . + ruff format --check . + pyright + pytest +else + nix develop --command bash -c "ruff check . && ruff format --check . && pyright && pytest" +fi diff --git a/.gitignore b/.gitignore index 8bc840d..7a5359b 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,9 @@ __pycache__/ .tv_state.json *.jpg .internal/ +webos_rsa +.webos_rsa +*.pem +*.key +id_rsa* +id_ed25519* diff --git a/AGENTS.md b/AGENTS.md index 9839527..2550ac9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -29,6 +29,11 @@ The working tree represents the user's active work. - **Contracts Without Code Duplication:** Avoid pasting Python class or dataclass blocks into architecture/design docs. Model relationships with a Mermaid `classDiagram` (or `erDiagram`), summarize exact signatures in a concise table, and link directly to the authoritative source file (label as *(planned)* if not yet created). - **Policy vs. Mechanism in Diagrams:** Keep flowcharts at the domain-policy level (e.g., *"Is the TV in standby (`1008`)?"*) rather than mirroring low-level library syntax. Capture mandatory mechanism invariants in prose or the detailed implementation manifest. +### 3.2 Validation, Error Boundaries & Dependency Hygiene +- **Boundary Validation vs. Internal State:** Any class representing external/operator input or wire schemas (e.g., `TvConfig`, MCP tool inputs) must use Pydantic v2 `BaseModel` (`ConfigDict(frozen=True, extra="forbid")`) with validators on the class itself so invalid state cannot be constructed by bypassing a factory function. Pure internal state containers (such as `TvState`) may use stdlib `@dataclass`. Never decorate `Exception` subclasses with `@dataclass`—always write an explicit `__init__` calling `super().__init__(...)` so `Exception.args` and `str(err)` remain intact. +- **Error Domain Separation (`ConfigError` vs. `TvError`):** Raise `ConfigError` for startup, environment, and operator configuration failures (caught by the CLI entrypoint to exit cleanly; never returned as an MCP tool payload). Raise `TvError(ErrorCode, message)` exclusively for runtime TV, SSAP, pointer, WoL, or Dev Mode SSH failures during tool execution so the MCP server can surface actionable recovery hints to the calling agent. +- **Single-Source & Explicit Dependencies:** Keep `runtimeDeps` and `testDeps` single-sourced in `flake.nix` (`pythonEnv = runtimeDeps ++ testDeps`, `packages.default.dependencies = runtimeDeps`). Never rely on implicit transitive dependencies: if any module under `src/` imports a third-party package directly, declare it explicitly in both `pyproject.toml` (`dependencies`) and `flake.nix` (`runtimeDeps`). + --- ## 4. Operational & Protocol Invariants @@ -42,9 +47,12 @@ The working tree represents the user's active work. --- -## 5. Verification & Completion +## 5. Verification, Hooks & CI Expectations -Every task must be verified inside `nix develop` before declaring completion: -1. Run linters, formatters, and type checks: `nix develop --command ruff check .` and `nix develop --command pyright`. -2. Run test suites when tests are present: `nix develop --command pytest`. -3. Report: (1) What changed, (2) Files modified/created, (3) Verification performed, (4) Unverified areas/risks. +Every task and commit must pass automated verification inside `nix develop`: +1. **Local Pre-Commit Hook (`.githooks/pre-commit`):** Configured automatically by `flake.nix` `shellHook` (`git config core.hooksPath .githooks`). Runs `ruff check .`, `ruff format --check .`, `pyright`, and `pytest` before every commit. Never bypass hooks with `--no-verify`. +2. **TDD Red-Phase Commits (`@pytest.mark.xfail`):** When committing Red-phase tests before the feature implementation exists, provide typed symbol stubs (`raise NotImplementedError`) so `pyright` passes, and decorate unimplemented tests with `@pytest.mark.xfail(strict=True, reason="Red phase: ...")` so `pytest` and `.githooks/pre-commit` exit `0` while still failing if a Red test passes tautologically. Remove `xfail` in the Green-phase commit. +3. **Behavior-Driven Test Naming:** Name all test functions using the consistent `test__` convention (e.g., `test_load_config_rejects_invalid_env_values_with_config_error` rather than broad names like `test_load_config_defaults`) so `pytest -v` output reads as a clear specification of expected behavior. +4. **Python 3.14 & Strict Typing:** Target Python `>=3.14` (PEP 649 lazy annotations are native—never add `from __future__ import annotations`, enforced by Ruff `TID251`). All code in `src/` and `tests/` must pass `pyright` in `strict` mode without untyped parameters or implicit `Any`. +5. **Server-Side Gitea Actions CI (`.gitea/workflows/ci.yaml`):** Runs `nix flake check` on every push and pull request targeting `main`, executing `ruff check .`, `ruff format --check .`, `pyright`, `pytestCheckHook`, and `buildPythonApplication` inside the isolated Nix sandbox. Verify `nix flake check` locally before opening or updating a pull request. +6. **Completion Reporting:** Report: (1) What changed, (2) Files modified/created, (3) Verification performed, (4) Unverified areas/risks. diff --git a/flake.nix b/flake.nix index dda63e4..56f4e30 100644 --- a/flake.nix +++ b/flake.nix @@ -9,17 +9,56 @@ let system = "x86_64-linux"; pkgs = import nixpkgs { inherit system; }; - pythonEnv = pkgs.python3.withPackages (ps: [ + ps = pkgs.python3Packages; + + runtimeDeps = [ ps.websockets - ]); + ps.mcp + ps.pydantic + ps.asyncssh + ps.uvicorn + ]; + + testDeps = [ + ps.httpx + ps.pytest + ps.pytest-asyncio + ]; + + pythonEnv = pkgs.python3.withPackages (_: runtimeDeps ++ testDeps); in { + packages.${system}.default = ps.buildPythonApplication { + pname = "lg-smtv-mcp"; + version = "0.1.0"; + src = ./.; + pyproject = true; + build-system = [ ps.setuptools ]; + dependencies = runtimeDeps; + nativeCheckInputs = [ + ps.pytestCheckHook + pkgs.ruff + pkgs.pyright + ] ++ testDeps; + preCheck = '' + ruff check . + ruff format --check . + pyright + ''; + }; + devShells.${system}.default = pkgs.mkShell { packages = [ pythonEnv pkgs.pyright pkgs.ruff ]; + shellHook = '' + export PYTHONPATH="$PWD/src:${PYTHONPATH:-}" + if [ -d .git ] && [ -d .githooks ]; then + git config core.hooksPath .githooks + fi + ''; }; }; } diff --git a/pyproject.toml b/pyproject.toml index 2b8a771..0450ecd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,10 +1,47 @@ +[build-system] +requires = ["setuptools"] +build-backend = "setuptools.build_meta" + +[project] +name = "lg-smtv-mcp" +version = "0.1.0" +description = "MCP server for controlling an LG webOS Smart TV over the local network" +requires-python = ">=3.14" +dependencies = [ + "websockets", + "mcp", + "pydantic", + "asyncssh", + "uvicorn", +] + +[project.scripts] +lg-smtv-mcp = "lg_smtv_mcp.cli:main" + +[tool.setuptools.packages.find] +where = ["src"] + +[tool.pytest.ini_options] +asyncio_mode = "auto" +pythonpath = ["src"] + [tool.ruff] line-length = 100 target-version = "py314" [tool.ruff.lint] -select = ["E", "F", "I", "UP", "B"] +select = ["E", "F", "I", "UP", "B", "TID"] + +[tool.ruff.lint.per-file-ignores] +"docs/poc/*" = ["TID251"] + +[tool.ruff.lint.flake8-tidy-imports.banned-api] +"__future__.annotations".msg = "Python 3.14 evaluates annotations lazily by default (PEP 649); omit from __future__ import annotations." + +[tool.ruff.format] +exclude = ["docs/poc/**"] [tool.pyright] -typeCheckingMode = "standard" +include = ["src", "tests"] +typeCheckingMode = "strict" pythonVersion = "3.14" diff --git a/src/lg_smtv_mcp/__init__.py b/src/lg_smtv_mcp/__init__.py new file mode 100644 index 0000000..391b8ec --- /dev/null +++ b/src/lg_smtv_mcp/__init__.py @@ -0,0 +1,5 @@ +"""LG webOS Smart TV MCP server package.""" + +__all__ = ["__version__"] + +__version__ = "0.1.0" diff --git a/src/lg_smtv_mcp/__main__.py b/src/lg_smtv_mcp/__main__.py new file mode 100644 index 0000000..70f44e5 --- /dev/null +++ b/src/lg_smtv_mcp/__main__.py @@ -0,0 +1,6 @@ +"""Module entrypoint for `python -m lg_smtv_mcp`.""" + +from lg_smtv_mcp.cli import main + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/lg_smtv_mcp/cli.py b/src/lg_smtv_mcp/cli.py new file mode 100644 index 0000000..fd29e47 --- /dev/null +++ b/src/lg_smtv_mcp/cli.py @@ -0,0 +1,9 @@ +"""CLI entrypoint stub for lg-smtv-mcp (expanded in Issue #3).""" + +from collections.abc import Sequence + + +def main(argv: Sequence[str] | None = None) -> int: + """CLI entrypoint stub.""" + _ = argv + return 0 diff --git a/src/lg_smtv_mcp/config.py b/src/lg_smtv_mcp/config.py new file mode 100644 index 0000000..e89da69 --- /dev/null +++ b/src/lg_smtv_mcp/config.py @@ -0,0 +1,195 @@ +"""Runtime configuration loader, Pydantic v2 validation model, and stdlib .env parser.""" + +import ipaddress +import os +from pathlib import Path +from typing import Any + +from pydantic import BaseModel, ConfigDict, ValidationError, field_validator +from pydantic_core import PydanticCustomError + +from lg_smtv_mcp.errors import ConfigError + + +def _parse_ipv4(env_name: str, value: Any) -> str: + if not isinstance(value, str) or not value.strip(): + raise PydanticCustomError( + "invalid_ipv4", + "{name} is required and must be a valid IPv4 address", + {"name": env_name}, + ) + cleaned = value.strip() + try: + ipaddress.IPv4Address(cleaned) + except ValueError as exc: + raise PydanticCustomError( + "invalid_ipv4", + "{name} must be a valid IPv4 address, got {ip!r}", + {"name": env_name, "ip": cleaned}, + ) from exc + return cleaned + + +def _parse_bounded_int(env_name: str, value: Any, *, min_val: int, max_val: int) -> int: + if isinstance(value, bool) or not isinstance(value, (int, str)): + raise PydanticCustomError( + "invalid_int", + "{name} must be an integer between {min_val} and {max_val}, got {val!r}", + {"name": env_name, "min_val": min_val, "max_val": max_val, "val": value}, + ) + try: + parsed = int(value.strip()) if isinstance(value, str) else value + except ValueError as exc: + raise PydanticCustomError( + "invalid_int", + "{name} must be an integer between {min_val} and {max_val}, got {val!r}", + {"name": env_name, "min_val": min_val, "max_val": max_val, "val": value}, + ) from exc + if not (min_val <= parsed <= max_val): + raise PydanticCustomError( + "int_out_of_range", + "{name} must be between {min_val} and {max_val}, got {val}", + {"name": env_name, "min_val": min_val, "max_val": max_val, "val": parsed}, + ) + return parsed + + +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" + client_key_path: Path = Path(".client_key.json") + ssh_key_path: Path | None = None + webos_ssh_passphrase: str | None = None + ssh_known_hosts_path: Path | None = None + host: str = "127.0.0.1" + port: int = 8765 + allowed_hosts: tuple[str, ...] = () + mcp_bearer_token: str | None = None + 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: + return _parse_ipv4("TV_IP", value) + + @field_validator("wol_broadcast", mode="before") + @classmethod + def _validate_wol_broadcast(cls, value: Any) -> str: + return _parse_ipv4("WOL_BROADCAST", value) + + @field_validator("port", mode="before") + @classmethod + def _validate_port(cls, value: Any) -> int: + return _parse_bounded_int("PORT", value, min_val=1, max_val=65535) + + @field_validator("max_volume", mode="before") + @classmethod + def _validate_max_volume(cls, value: Any) -> int: + return _parse_bounded_int("MAX_VOLUME", value, min_val=0, max_val=100) + + +def _load_dotenv(env_path: Path) -> None: + """Populate unset os.environ keys from a .env file using stdlib only.""" + if not env_path.is_file(): + return + + for raw_line in env_path.read_text(encoding="utf-8").splitlines(): + line = raw_line.strip() + if not line or line.startswith("#"): + continue + if line.startswith("export "): + line = line[len("export ") :].strip() + if "=" not in line: + continue + + key, value = line.split("=", 1) + key = key.strip() + if not key: + continue + + value = value.strip() + if len(value) >= 2 and value[0] == value[-1] and value[0] in {"'", '"'}: + value = value[1:-1] + + # Never overwrite variables already present in the process environment. + os.environ.setdefault(key, value) + + +def _optional_str(name: str) -> str | None: + raw = os.environ.get(name) + if raw is None: + return None + stripped = raw.strip() + return stripped or None + + +def _optional_path(name: str) -> Path | None: + val = _optional_str(name) + return Path(val) if val is not None else None + + +def load_config(env_path: Path | None = Path(".env")) -> TvConfig: + """Load and validate TvConfig from environment variables with optional .env fallback.""" + if env_path is not None: + _load_dotenv(env_path) + + 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" + client_key_path = _optional_path("CLIENT_KEY_PATH") or Path(".client_key.json") + + allowed_raw = os.environ.get("ALLOWED_HOSTS", "") + allowed_hosts = tuple(part.strip() for part in allowed_raw.split(",") if part.strip()) + + enable_raw_raw = (os.environ.get("ENABLE_RAW_SSAP") or "").strip().lower() + enable_raw_ssap = enable_raw_raw in {"1", "true", "yes", "on"} + + 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 ConfigError.""" + if config.mcp_bearer_token is None or not config.mcp_bearer_token.strip(): + 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 ConfigError.""" + if config.tv_mac is None or not config.tv_mac.strip(): + 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 new file mode 100644 index 0000000..9249ff2 --- /dev/null +++ b/src/lg_smtv_mcp/errors.py @@ -0,0 +1,32 @@ +"""Typed domain error taxonomy for lg-smtv-mcp.""" + +from enum import StrEnum + + +class ErrorCode(StrEnum): + """Canonical error codes mapped to MCP tool errors.""" + + TV_OFFLINE_STANDBY = "TV_OFFLINE_STANDBY" + PAIRING_REQUIRED = "PAIRING_REQUIRED" + SCREENSHOT_UNAVAILABLE = "SCREENSHOT_UNAVAILABLE" + LOCK_TIMEOUT = "LOCK_TIMEOUT" + WAKE_TIMEOUT = "WAKE_TIMEOUT" + COMMAND_FAILED = "COMMAND_FAILED" + INVALID_ARGUMENT = "INVALID_ARGUMENT" + + +class TvError(Exception): + """Domain error carrying a structured ErrorCode and message.""" + + def __init__(self, code: ErrorCode, message: str) -> None: + 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 new file mode 100644 index 0000000..dc2f2bb --- /dev/null +++ b/tests/test_config.py @@ -0,0 +1,212 @@ +from enum import StrEnum +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 ConfigError, ErrorCode, TvError + + +def _clear_tv_env(monkeypatch: pytest.MonkeyPatch) -> None: + for key in ( + "TV_IP", + "TV_MAC", + "WOL_BROADCAST", + "CLIENT_KEY_PATH", + "SSH_KEY_PATH", + "WEBOS_SSH_PASSPHRASE", + "SSH_KNOWN_HOSTS_PATH", + "HOST", + "PORT", + "ALLOWED_HOSTS", + "MCP_BEARER_TOKEN", + "MAX_VOLUME", + "ENABLE_RAW_SSAP", + ): + monkeypatch.delenv(key, raising=False) + + +def test_error_taxonomy_defines_codes_and_decouples_config_error() -> None: + expected = { + "TV_OFFLINE_STANDBY", + "PAIRING_REQUIRED", + "SCREENSHOT_UNAVAILABLE", + "LOCK_TIMEOUT", + "WAKE_TIMEOUT", + "COMMAND_FAILED", + "INVALID_ARGUMENT", + } + assert issubclass(ErrorCode, StrEnum) + assert {member.value for member in ErrorCode} == expected + + err = TvError(ErrorCode.INVALID_ARGUMENT, "bad input") + assert isinstance(err, Exception) + assert err.code is ErrorCode.INVALID_ARGUMENT + 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_uses_expected_defaults_when_optional_vars_unset( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + _clear_tv_env(monkeypatch) + monkeypatch.setenv("TV_IP", "192.0.2.10") + + cfg = load_config(env_path=tmp_path / "missing.env") + + assert isinstance(cfg, TvConfig) + assert cfg.tv_ip == "192.0.2.10" + assert cfg.host == "127.0.0.1" + assert cfg.port == 8765 + assert cfg.max_volume == 40 + assert cfg.wol_broadcast == "255.255.255.255" + assert cfg.client_key_path == Path(".client_key.json") + assert cfg.enable_raw_ssap is False + assert cfg.ssh_key_path is None + assert cfg.webos_ssh_passphrase is None + assert cfg.ssh_known_hosts_path is None + assert cfg.allowed_hosts == () + assert cfg.tv_mac is None + assert cfg.mcp_bearer_token is None + + +def test_dotenv_fallback_does_not_overwrite_existing_env( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + _clear_tv_env(monkeypatch) + env_file = tmp_path / ".env" + env_file.write_text( + "# comment line\nTV_IP=192.0.2.20\nPORT='9000'\nHOST=\"0.0.0.0\"\nENABLE_RAW_SSAP=true\n", + encoding="utf-8", + ) + monkeypatch.setenv("TV_IP", "192.0.2.99") + + cfg = load_config(env_path=env_file) + + assert cfg.tv_ip == "192.0.2.99" + assert cfg.port == 9000 + assert cfg.host == "0.0.0.0" + assert cfg.enable_raw_ssap is True + + +@pytest.mark.parametrize( + ("env_overrides", "expected_substr"), + [ + ({}, "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"), + ({"TV_IP": "192.0.2.10", "PORT": "0"}, "PORT"), + ({"TV_IP": "192.0.2.10", "PORT": "65536"}, "PORT"), + ({"TV_IP": "192.0.2.10", "PORT": "abc"}, "PORT"), + ], +) +def test_load_config_rejects_invalid_env_values_with_config_error( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + env_overrides: dict[str, str], + expected_substr: str, +) -> None: + _clear_tv_env(monkeypatch) + for k, v in env_overrides.items(): + monkeypatch.setenv(k, v) + + with pytest.raises(ConfigError) as exc_info: + load_config(env_path=tmp_path / "missing.env") + + 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", "port": 8000.5}, "PORT"), + ({"tv_ip": "192.0.2.10", "max_volume": 150}, "MAX_VOLUME"), + ({"tv_ip": "192.0.2.10", "max_volume": 12.5}, "MAX_VOLUME"), + ({"tv_ip": "192.0.2.10", "wol_broadcast": "bad-ip"}, "WOL_BROADCAST"), + ], +) +def test_tv_config_rejects_invalid_direct_arguments_with_config_error( + 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 + + +def test_load_config_parses_comma_separated_allowed_hosts( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + _clear_tv_env(monkeypatch) + monkeypatch.setenv("TV_IP", "192.0.2.10") + monkeypatch.setenv("ALLOWED_HOSTS", "tv.local, 192.0.2.5:8765 , , localhost") + + cfg = load_config(env_path=tmp_path / "missing.env") + + assert cfg.allowed_hosts == ("tv.local", "192.0.2.5:8765", "localhost") + + +@pytest.mark.parametrize("token", [None, "", " "]) +def test_require_bearer_token_rejects_missing_or_blank( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, token: str | None +) -> None: + _clear_tv_env(monkeypatch) + monkeypatch.setenv("TV_IP", "192.0.2.10") + if token is not None: + monkeypatch.setenv("MCP_BEARER_TOKEN", token) + + cfg = load_config(env_path=tmp_path / "missing.env") + with pytest.raises(ConfigError) as exc_info: + require_bearer_token(cfg) + + assert "MCP_BEARER_TOKEN" in exc_info.value.message + + +def test_require_bearer_token_returns_trimmed_value( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + _clear_tv_env(monkeypatch) + monkeypatch.setenv("TV_IP", "192.0.2.10") + monkeypatch.setenv("MCP_BEARER_TOKEN", " secret-token ") + + cfg = load_config(env_path=tmp_path / "missing.env") + assert require_bearer_token(cfg) == "secret-token" + + +@pytest.mark.parametrize("mac", [None, "", " "]) +def test_require_mac_rejects_missing_or_blank( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, mac: str | None +) -> None: + _clear_tv_env(monkeypatch) + monkeypatch.setenv("TV_IP", "192.0.2.10") + if mac is not None: + monkeypatch.setenv("TV_MAC", mac) + + cfg = load_config(env_path=tmp_path / "missing.env") + with pytest.raises(ConfigError) as exc_info: + require_mac(cfg) + + assert "TV_MAC" in exc_info.value.message + + +def test_require_mac_returns_trimmed_value(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + _clear_tv_env(monkeypatch) + monkeypatch.setenv("TV_IP", "192.0.2.10") + monkeypatch.setenv("TV_MAC", " AA:BB:CC:DD:EE:FF ") + + cfg = load_config(env_path=tmp_path / "missing.env") + assert require_mac(cfg) == "AA:BB:CC:DD:EE:FF"