From 35a66bd456561a5f76c827150fe5b7948f35770c Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sun, 15 Nov 2026 10:14:31 -0500 Subject: [PATCH 01/12] test(config): add Nix packaging, pyproject, and Red-phase config/error tests - flake.nix: expose packages.default (buildPythonApplication) and expand devShell with mcp, asyncssh, uvicorn, httpx, pytest, pytest-asyncio, and PYTHONPATH shellHook - pyproject.toml: configure setuptools build-system, project metadata/dependencies, lg-smtv-mcp script entrypoint, pytest asyncio/pythonpath, and pyright include paths - tests/test_config.py: add Red-phase unit tests for ErrorCode, TvError, load_config(), .env fallback, validation, ALLOWED_HOSTS, require_bearer_token(), and require_mac() --- flake.nix | 23 ++++++ pyproject.toml | 27 ++++++ tests/test_config.py | 191 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 241 insertions(+) create mode 100644 tests/test_config.py diff --git a/flake.nix b/flake.nix index dda63e4..a4a2566 100644 --- a/flake.nix +++ b/flake.nix @@ -11,15 +11,38 @@ pkgs = import nixpkgs { inherit system; }; pythonEnv = pkgs.python3.withPackages (ps: [ ps.websockets + ps.mcp + ps.asyncssh + ps.uvicorn + ps.httpx + ps.pytest + ps.pytest-asyncio ]); in { + packages.${system}.default = pkgs.python3Packages.buildPythonApplication { + pname = "lg-smtv-mcp"; + version = "0.1.0"; + src = ./.; + pyproject = true; + build-system = [ pkgs.python3Packages.setuptools ]; + dependencies = with pkgs.python3Packages; [ + websockets + mcp + asyncssh + uvicorn + ]; + }; + devShells.${system}.default = pkgs.mkShell { packages = [ pythonEnv pkgs.pyright pkgs.ruff ]; + shellHook = '' + export PYTHONPATH="$PWD/src:${PYTHONPATH:-}" + ''; }; }; } diff --git a/pyproject.toml b/pyproject.toml index 2b8a771..200fa7f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,3 +1,29 @@ +[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.11" +dependencies = [ + "websockets", + "mcp", + "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" @@ -6,5 +32,6 @@ target-version = "py314" select = ["E", "F", "I", "UP", "B"] [tool.pyright] +include = ["src", "tests"] typeCheckingMode = "standard" pythonVersion = "3.14" diff --git a/tests/test_config.py b/tests/test_config.py new file mode 100644 index 0000000..541ae97 --- /dev/null +++ b/tests/test_config.py @@ -0,0 +1,191 @@ +from __future__ import annotations + +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 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_code_and_tv_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) + + +def test_load_config_defaults( + 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\n" + "TV_IP=192.0.2.20\n" + "PORT='9000'\n" + 'HOST="0.0.0.0"\n' + "ENABLE_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": "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_validation_errors( + 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(TvError) 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 + + +def test_allowed_hosts_comma_separated( + 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(TvError) as exc_info: + require_bearer_token(cfg) + + assert exc_info.value.code is ErrorCode.INVALID_ARGUMENT + + +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(TvError) as exc_info: + require_mac(cfg) + + assert exc_info.value.code is ErrorCode.INVALID_ARGUMENT + + +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" From c549c83e2ca4e717129bfeff215f5d0021ae7aab Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sun, 15 Nov 2026 10:16:26 -0500 Subject: [PATCH 02/12] feat(config): implement ErrorCode, TvConfig, load_config, CLI stub, and secret hygiene - src/lg_smtv_mcp/errors.py: define ErrorCode(StrEnum) and TvError(code, message) domain error taxonomy - src/lg_smtv_mcp/config.py: add frozen TvConfig, stdlib .env fallback in load_config(), range/required validations, ALLOWED_HOSTS parsing, require_bearer_token(), and require_mac() - src/lg_smtv_mcp/{__init__,__main__,cli}.py: add package root, module entrypoint, and minimal main() CLI stub - .gitignore & .env.example: exclude SSH key artifacts and provide placeholder runtime config template --- .env.example | 13 ++++ .gitignore | 6 ++ src/lg_smtv_mcp/__init__.py | 5 ++ src/lg_smtv_mcp/__main__.py | 8 ++ src/lg_smtv_mcp/cli.py | 11 +++ src/lg_smtv_mcp/config.py | 147 ++++++++++++++++++++++++++++++++++++ src/lg_smtv_mcp/errors.py | 26 +++++++ 7 files changed, 216 insertions(+) create mode 100644 .env.example create mode 100644 src/lg_smtv_mcp/__init__.py create mode 100644 src/lg_smtv_mcp/__main__.py create mode 100644 src/lg_smtv_mcp/cli.py create mode 100644 src/lg_smtv_mcp/config.py create mode 100644 src/lg_smtv_mcp/errors.py 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/.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/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..415eb38 --- /dev/null +++ b/src/lg_smtv_mcp/__main__.py @@ -0,0 +1,8 @@ +"""Module entrypoint for `python -m lg_smtv_mcp`.""" + +from __future__ import annotations + +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..41fa10b --- /dev/null +++ b/src/lg_smtv_mcp/cli.py @@ -0,0 +1,11 @@ +"""CLI entrypoint stub for lg-smtv-mcp (expanded in Issue #3).""" + +from __future__ import annotations + +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..a46728f --- /dev/null +++ b/src/lg_smtv_mcp/config.py @@ -0,0 +1,147 @@ +"""Runtime configuration loader and stdlib .env parser.""" + +from __future__ import annotations + +import os +from dataclasses import dataclass +from pathlib import Path + +from lg_smtv_mcp.errors import ErrorCode, TvError + + +@dataclass(frozen=True) +class TvConfig: + """Validated runtime configuration for lg-smtv-mcp.""" + + 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 _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 _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: + 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") + 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 + ) + + 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"} + + 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, + ) + + +def require_bearer_token(config: TvConfig) -> str: + """Return a non-empty MCP_BEARER_TOKEN or raise INVALID_ARGUMENT.""" + 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", + ) + return config.mcp_bearer_token.strip() + + +def require_mac(config: TvConfig) -> str: + """Return a non-empty TV_MAC or raise INVALID_ARGUMENT.""" + 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)", + ) + 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..ac7bdee --- /dev/null +++ b/src/lg_smtv_mcp/errors.py @@ -0,0 +1,26 @@ +"""Typed domain error taxonomy for lg-smtv-mcp.""" + +from __future__ import annotations + +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 From 98ffc65cb1576cbbe61fae1139752c3a42ba74be Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sun, 15 Nov 2026 12:11:53 -0500 Subject: [PATCH 03/12] build(nix): deduplicate runtime/test deps and add pre-commit check hook - flake.nix: extract shared runtimeDeps and testDeps lists for packages.default (with pytestCheckHook) and devShells.default, and configure git core.hooksPath in shellHook - .githooks/pre-commit: run ruff check, pyright, pytest, and nix flake check before each commit --- .githooks/pre-commit | 12 ++++++++++++ flake.nix | 26 ++++++++++++++++---------- 2 files changed, 28 insertions(+), 10 deletions(-) create mode 100755 .githooks/pre-commit diff --git a/.githooks/pre-commit b/.githooks/pre-commit new file mode 100755 index 0000000..0d5b515 --- /dev/null +++ b/.githooks/pre-commit @@ -0,0 +1,12 @@ +#!/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 . + pyright + pytest +else + nix develop --command bash -c "ruff check . && pyright && pytest" +fi + +nix flake check diff --git a/flake.nix b/flake.nix index a4a2566..23f12c2 100644 --- a/flake.nix +++ b/flake.nix @@ -9,29 +9,32 @@ let system = "x86_64-linux"; pkgs = import nixpkgs { inherit system; }; - pythonEnv = pkgs.python3.withPackages (ps: [ + ps = pkgs.python3Packages; + + runtimeDeps = [ ps.websockets ps.mcp ps.asyncssh ps.uvicorn + ]; + + testDeps = [ ps.httpx ps.pytest ps.pytest-asyncio - ]); + ]; + + pythonEnv = pkgs.python3.withPackages (_: runtimeDeps ++ testDeps); in { - packages.${system}.default = pkgs.python3Packages.buildPythonApplication { + packages.${system}.default = ps.buildPythonApplication { pname = "lg-smtv-mcp"; version = "0.1.0"; src = ./.; pyproject = true; - build-system = [ pkgs.python3Packages.setuptools ]; - dependencies = with pkgs.python3Packages; [ - websockets - mcp - asyncssh - uvicorn - ]; + build-system = [ ps.setuptools ]; + dependencies = runtimeDeps; + nativeCheckInputs = [ ps.pytestCheckHook ] ++ testDeps; }; devShells.${system}.default = pkgs.mkShell { @@ -42,6 +45,9 @@ ]; shellHook = '' export PYTHONPATH="$PWD/src:${PYTHONPATH:-}" + if [ -d .git ] && [ -d .githooks ]; then + git config core.hooksPath .githooks + fi ''; }; }; From 7ea45c3d3b61cf45fddfddf89795bf93cd8e0d84 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sun, 15 Nov 2026 12:21:01 -0500 Subject: [PATCH 04/12] ci(nix): wire ruff and pyright into flake check and add Gitea Actions workflow - flake.nix: add ruff and pyright to packages.default nativeCheckInputs and preCheck so nix build / nix flake check enforce lint, types, and pytest in the Nix sandbox - .githooks/pre-commit: keep local pre-commit hook fast (<0.5s) running ruff, pyright, and pytest - .gitea/workflows/ci.yaml: run nix flake check on push and pull_request to main - AGENTS.md: document .githooks/pre-commit, @pytest.mark.xfail(strict=True) Red-phase rule, and .gitea/workflows/ci.yaml expectations --- .gitea/workflows/ci.yaml | 27 +++++++++++++++++++++++++++ .githooks/pre-commit | 2 -- AGENTS.md | 11 ++++++----- flake.nix | 10 +++++++++- 4 files changed, 42 insertions(+), 8 deletions(-) create mode 100644 .gitea/workflows/ci.yaml 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 index 0d5b515..5d03393 100755 --- a/.githooks/pre-commit +++ b/.githooks/pre-commit @@ -8,5 +8,3 @@ if command -v ruff >/dev/null 2>&1 && command -v pyright >/dev/null 2>&1 && comm else nix develop --command bash -c "ruff check . && pyright && pytest" fi - -nix flake check diff --git a/AGENTS.md b/AGENTS.md index 9839527..0731395 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -42,9 +42,10 @@ 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 .`, `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. **Server-Side Gitea Actions CI (`.gitea/workflows/ci.yaml`):** Runs `nix flake check` on every push and pull request targeting `main`, executing `ruff check .`, `pyright`, `pytestCheckHook`, and `buildPythonApplication` inside the isolated Nix sandbox. Verify `nix flake check` locally before opening or updating a pull request. +4. **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 23f12c2..c612763 100644 --- a/flake.nix +++ b/flake.nix @@ -34,7 +34,15 @@ pyproject = true; build-system = [ ps.setuptools ]; dependencies = runtimeDeps; - nativeCheckInputs = [ ps.pytestCheckHook ] ++ testDeps; + nativeCheckInputs = [ + ps.pytestCheckHook + pkgs.ruff + pkgs.pyright + ] ++ testDeps; + preCheck = '' + ruff check . + pyright + ''; }; devShells.${system}.default = pkgs.mkShell { From 165a6c28dac2cdd4d356871c9f059e3083954e0e Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sun, 15 Nov 2026 12:36:36 -0500 Subject: [PATCH 05/12] style(lint): apply automated ruff formatting --- docs/poc/tv_test.py | 4 +--- tests/test_config.py | 18 ++++-------------- 2 files changed, 5 insertions(+), 17 deletions(-) diff --git a/docs/poc/tv_test.py b/docs/poc/tv_test.py index 3b60288..619f5c2 100644 --- a/docs/poc/tv_test.py +++ b/docs/poc/tv_test.py @@ -205,9 +205,7 @@ async def verify_subscriptions(ip: str, port: int, key_file: Path) -> dict[str, ) ) await ws.send( - json.dumps( - {"id": "req_info", "type": "request", "uri": "ssap://system/getSystemInfo"} - ) + json.dumps({"id": "req_info", "type": "request", "uri": "ssap://system/getSystemInfo"}) ) frames: list[dict[str, Any]] = [] diff --git a/tests/test_config.py b/tests/test_config.py index 541ae97..fe71c9b 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -48,9 +48,7 @@ def test_error_code_and_tv_error() -> None: assert "bad input" in str(err) -def test_load_config_defaults( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path -) -> None: +def test_load_config_defaults(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: _clear_tv_env(monkeypatch) monkeypatch.setenv("TV_IP", "192.0.2.10") @@ -78,11 +76,7 @@ def test_dotenv_fallback_does_not_overwrite_existing_env( _clear_tv_env(monkeypatch) env_file = tmp_path / ".env" env_file.write_text( - "# comment line\n" - "TV_IP=192.0.2.20\n" - "PORT='9000'\n" - 'HOST="0.0.0.0"\n' - "ENABLE_RAW_SSAP=true\n", + "# 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") @@ -125,9 +119,7 @@ def test_load_config_validation_errors( assert expected_substr in exc_info.value.message -def test_allowed_hosts_comma_separated( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path -) -> None: +def test_allowed_hosts_comma_separated(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") @@ -180,9 +172,7 @@ def test_require_mac_rejects_missing_or_blank( assert exc_info.value.code is ErrorCode.INVALID_ARGUMENT -def test_require_mac_returns_trimmed_value( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path -) -> None: +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 ") From a5d69eb37d5a6c1d787b2bab39e572e75ad75c44 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sun, 15 Nov 2026 12:43:57 -0500 Subject: [PATCH 06/12] ci(lint): enforce ruff format --check in pre-commit hook and flake check - .githooks/pre-commit: add ruff format --check . alongside ruff check, pyright, and pytest - flake.nix: add ruff format --check . to packages.default preCheck - AGENTS.md: update Section 5 verification rules to include ruff format --check --- .githooks/pre-commit | 3 ++- AGENTS.md | 4 ++-- flake.nix | 1 + 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/.githooks/pre-commit b/.githooks/pre-commit index 5d03393..df299d5 100755 --- a/.githooks/pre-commit +++ b/.githooks/pre-commit @@ -3,8 +3,9 @@ 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 . && pyright && pytest" + nix develop --command bash -c "ruff check . && ruff format --check . && pyright && pytest" fi diff --git a/AGENTS.md b/AGENTS.md index 0731395..cf85333 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -45,7 +45,7 @@ The working tree represents the user's active work. ## 5. Verification, Hooks & CI Expectations 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 .`, `pyright`, and `pytest` before every commit. Never bypass hooks with `--no-verify`. +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. **Server-Side Gitea Actions CI (`.gitea/workflows/ci.yaml`):** Runs `nix flake check` on every push and pull request targeting `main`, executing `ruff check .`, `pyright`, `pytestCheckHook`, and `buildPythonApplication` inside the isolated Nix sandbox. Verify `nix flake check` locally before opening or updating a pull request. +3. **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. 4. **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 c612763..345258b 100644 --- a/flake.nix +++ b/flake.nix @@ -41,6 +41,7 @@ ] ++ testDeps; preCheck = '' ruff check . + ruff format --check . pyright ''; }; From 7ec752d4acbf7085f3ba1eaf48ef5289c0d37d87 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sun, 15 Nov 2026 12:59:51 -0500 Subject: [PATCH 07/12] refactor(typing): drop __future__.annotations on Python 3.14 and enable strict pyright - Set requires-python = ">=3.14" in pyproject.toml to match the Nix Python 3.14 runtime and PEP 649 native deferred annotation semantics - Remove redundant from __future__ import annotations across src/lg_smtv_mcp/ and tests/test_config.py - Add ruff TID251 rule banning __future__.annotations in package and test modules (ignoring docs/poc/*) - Switch pyright typeCheckingMode from basic to strict in pyproject.toml --- pyproject.toml | 12 +++++++++--- src/lg_smtv_mcp/__main__.py | 2 -- src/lg_smtv_mcp/cli.py | 2 -- src/lg_smtv_mcp/config.py | 2 -- src/lg_smtv_mcp/errors.py | 2 -- tests/test_config.py | 2 -- 6 files changed, 9 insertions(+), 13 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 200fa7f..6a374e3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,7 +6,7 @@ build-backend = "setuptools.build_meta" 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.11" +requires-python = ">=3.14" dependencies = [ "websockets", "mcp", @@ -29,9 +29,15 @@ 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.pyright] include = ["src", "tests"] -typeCheckingMode = "standard" +typeCheckingMode = "strict" pythonVersion = "3.14" diff --git a/src/lg_smtv_mcp/__main__.py b/src/lg_smtv_mcp/__main__.py index 415eb38..70f44e5 100644 --- a/src/lg_smtv_mcp/__main__.py +++ b/src/lg_smtv_mcp/__main__.py @@ -1,7 +1,5 @@ """Module entrypoint for `python -m lg_smtv_mcp`.""" -from __future__ import annotations - from lg_smtv_mcp.cli import main if __name__ == "__main__": diff --git a/src/lg_smtv_mcp/cli.py b/src/lg_smtv_mcp/cli.py index 41fa10b..fd29e47 100644 --- a/src/lg_smtv_mcp/cli.py +++ b/src/lg_smtv_mcp/cli.py @@ -1,7 +1,5 @@ """CLI entrypoint stub for lg-smtv-mcp (expanded in Issue #3).""" -from __future__ import annotations - from collections.abc import Sequence diff --git a/src/lg_smtv_mcp/config.py b/src/lg_smtv_mcp/config.py index a46728f..b055de4 100644 --- a/src/lg_smtv_mcp/config.py +++ b/src/lg_smtv_mcp/config.py @@ -1,7 +1,5 @@ """Runtime configuration loader and stdlib .env parser.""" -from __future__ import annotations - import os from dataclasses import dataclass from pathlib import Path diff --git a/src/lg_smtv_mcp/errors.py b/src/lg_smtv_mcp/errors.py index ac7bdee..0479fc7 100644 --- a/src/lg_smtv_mcp/errors.py +++ b/src/lg_smtv_mcp/errors.py @@ -1,7 +1,5 @@ """Typed domain error taxonomy for lg-smtv-mcp.""" -from __future__ import annotations - from enum import StrEnum diff --git a/tests/test_config.py b/tests/test_config.py index fe71c9b..ab617b8 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -1,5 +1,3 @@ -from __future__ import annotations - from enum import StrEnum from pathlib import Path From 28d3a8cbabfcabcab925c1230ea1962c702498b4 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sun, 15 Nov 2026 13:20:41 -0500 Subject: [PATCH 08/12] feat(config): enforce Pydantic v2 TvConfig validation and raise ConfigError - Add standalone ConfigError(Exception) in errors.py decoupled from runtime TvError - Convert TvConfig from dataclass to frozen Pydantic v2 BaseModel with field_validator hooks using PydanticCustomError - Validate TV_IP and WOL_BROADCAST as IPv4 addresses, PORT in 1..65535, and MAX_VOLUME in 0..100 on both load_config() and direct TvConfig instantiation - Redirect Pydantic ValidationError to ConfigError in TvConfig.__init__ and raise ConfigError from require_bearer_token/require_mac - Declare pydantic explicitly in flake.nix runtimeDeps and pyproject.toml dependencies - Expand tests/test_config.py to cover ConfigError and direct TvConfig validation --- flake.nix | 1 + pyproject.toml | 1 + src/lg_smtv_mcp/config.py | 187 ++++++++++++++++++++++++++------------ src/lg_smtv_mcp/errors.py | 8 ++ tests/test_config.py | 41 +++++++-- 5 files changed, 175 insertions(+), 63 deletions(-) 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: From 6ea84db8e135a6fa5a15320dd6eb1c09bd5a66de Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sun, 15 Nov 2026 13:37:12 -0500 Subject: [PATCH 09/12] test(config): standardize behavior-driven test names in test_config.py - Rename broad test functions to follow consistent test__ convention --- tests/test_config.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/tests/test_config.py b/tests/test_config.py index 07913bf..9a44848 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -26,7 +26,7 @@ def _clear_tv_env(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.delenv(key, raising=False) -def test_error_code_and_tv_error() -> None: +def test_error_taxonomy_defines_codes_and_decouples_config_error() -> None: expected = { "TV_OFFLINE_STANDBY", "PAIRING_REQUIRED", @@ -52,7 +52,9 @@ def test_error_code_and_tv_error() -> None: assert str(cfg_err) == "invalid TV_IP" -def test_load_config_defaults(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: +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") @@ -108,7 +110,7 @@ def test_dotenv_fallback_does_not_overwrite_existing_env( ({"TV_IP": "192.0.2.10", "PORT": "abc"}, "PORT"), ], ) -def test_load_config_validation_errors( +def test_load_config_rejects_invalid_env_values_with_config_error( monkeypatch: pytest.MonkeyPatch, tmp_path: Path, env_overrides: dict[str, str], @@ -134,7 +136,7 @@ def test_load_config_validation_errors( ({"tv_ip": "192.0.2.10", "wol_broadcast": "bad-ip"}, "WOL_BROADCAST"), ], ) -def test_tv_config_direct_instantiation_enforces_pydantic_validation( +def test_tv_config_rejects_invalid_direct_arguments_with_config_error( kwargs: dict[str, object], expected_substr: str, ) -> None: @@ -144,7 +146,9 @@ def test_tv_config_direct_instantiation_enforces_pydantic_validation( assert expected_substr in exc_info.value.message -def test_allowed_hosts_comma_separated(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: +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") From b8dc476f389af92f854cf8a4a39e7e14764237d7 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sun, 15 Nov 2026 13:39:07 -0500 Subject: [PATCH 10/12] docs(agents): enforce behavior-driven test__ naming rule - Add rule 5.3 in AGENTS.md requiring consistent test__ test function names --- AGENTS.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index cf85333..ab658a2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -47,5 +47,6 @@ The working tree represents the user's active work. 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. **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. -4. **Completion Reporting:** Report: (1) What changed, (2) Files modified/created, (3) Verification performed, (4) Unverified areas/risks. +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. **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. +5. **Completion Reporting:** Report: (1) What changed, (2) Files modified/created, (3) Verification performed, (4) Unverified areas/risks. From 80cb7594c3befce03f3e09e6802cb47b27c3e95f Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sun, 15 Nov 2026 13:47:25 -0500 Subject: [PATCH 11/12] docs(agents): codify validation, error domain, dependency, and Python 3.14 SOPs - Add section 3.2 covering Pydantic v2 boundary validation vs dataclasses, Exception subclassing, ConfigError vs TvError separation, and explicit single-sourced Nix/pyproject dependencies - Add rule 5.4 documenting Python 3.14 native PEP 649 typing (TID251) and strict pyright expectations --- AGENTS.md | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index ab658a2..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 @@ -48,5 +53,6 @@ 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. **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. -5. **Completion Reporting:** Report: (1) What changed, (2) Files modified/created, (3) Verification performed, (4) Unverified areas/risks. +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. From 290c1a1f6aed2b14ab2274b5f34f96ed4c7e1ae6 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sun, 15 Nov 2026 14:02:23 -0500 Subject: [PATCH 12/12] refactor(config): deduplicate IPv4/bounded-int validators and exclude docs/poc from ruff format - Extract shared _parse_ipv4 and _parse_bounded_int helpers in config.py and reject float/non-int values instead of truncating (CR-01) - Add direct TvConfig float rejection tests in tests/test_config.py - Exclude docs/poc/** under [tool.ruff.format] in pyproject.toml and revert formatting churn in docs/poc/tv_test.py (CR-02) --- docs/poc/tv_test.py | 4 +- pyproject.toml | 3 + src/lg_smtv_mcp/config.py | 119 +++++++++++++++----------------------- tests/test_config.py | 2 + 4 files changed, 55 insertions(+), 73 deletions(-) diff --git a/docs/poc/tv_test.py b/docs/poc/tv_test.py index 619f5c2..3b60288 100644 --- a/docs/poc/tv_test.py +++ b/docs/poc/tv_test.py @@ -205,7 +205,9 @@ async def verify_subscriptions(ip: str, port: int, key_file: Path) -> dict[str, ) ) await ws.send( - json.dumps({"id": "req_info", "type": "request", "uri": "ssap://system/getSystemInfo"}) + json.dumps( + {"id": "req_info", "type": "request", "uri": "ssap://system/getSystemInfo"} + ) ) frames: list[dict[str, Any]] = [] diff --git a/pyproject.toml b/pyproject.toml index 62ab42a..0450ecd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -38,6 +38,9 @@ select = ["E", "F", "I", "UP", "B", "TID"] [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] include = ["src", "tests"] typeCheckingMode = "strict" diff --git a/src/lg_smtv_mcp/config.py b/src/lg_smtv_mcp/config.py index 3d48520..e89da69 100644 --- a/src/lg_smtv_mcp/config.py +++ b/src/lg_smtv_mcp/config.py @@ -11,6 +11,49 @@ 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.""" @@ -40,90 +83,22 @@ class TvConfig(BaseModel): @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 + return _parse_ipv4("TV_IP", value) @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 + return _parse_ipv4("WOL_BROADCAST", value) @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 + 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: - 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 + return _parse_bounded_int("MAX_VOLUME", value, min_val=0, max_val=100) def _load_dotenv(env_path: Path) -> None: diff --git a/tests/test_config.py b/tests/test_config.py index 9a44848..dc2f2bb 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -132,7 +132,9 @@ def test_load_config_rejects_invalid_env_values_with_config_error( ({"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"), ], )