Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
80cb7594c3 | ||
|
|
b8dc476f38 | ||
|
|
6ea84db8e1 | ||
|
|
28d3a8cbab | ||
|
|
7ec752d4ac | ||
|
|
a5d69eb37d | ||
|
|
165a6c28da | ||
|
|
7ea45c3d3b | ||
|
|
98ffc65cb1 | ||
|
|
c549c83e2c |
No files matched your search
@@ -0,0 +1,13 @@
|
|||||||
|
TV_IP=<TV_IP>
|
||||||
|
TV_MAC=<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=<GENERATE_TOKEN>
|
||||||
|
MAX_VOLUME=40
|
||||||
|
ENABLE_RAW_SSAP=false
|
||||||
@@ -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
|
||||||
Executable
+11
@@ -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
|
||||||
@@ -7,3 +7,9 @@ __pycache__/
|
|||||||
.tv_state.json
|
.tv_state.json
|
||||||
*.jpg
|
*.jpg
|
||||||
.internal/
|
.internal/
|
||||||
|
webos_rsa
|
||||||
|
.webos_rsa
|
||||||
|
*.pem
|
||||||
|
*.key
|
||||||
|
id_rsa*
|
||||||
|
id_ed25519*
|
||||||
@@ -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).
|
- **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.
|
- **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
|
## 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:
|
Every task and commit must pass automated verification inside `nix develop`:
|
||||||
1. Run linters, formatters, and type checks: `nix develop --command ruff check .` and `nix develop --command pyright`.
|
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. Run test suites when tests are present: `nix develop --command pytest`.
|
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. 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_<unit>_<behavior>` 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.
|
||||||
+1
-3
@@ -205,9 +205,7 @@ async def verify_subscriptions(ip: str, port: int, key_file: Path) -> dict[str,
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
await ws.send(
|
await ws.send(
|
||||||
json.dumps(
|
json.dumps({"id": "req_info", "type": "request", "uri": "ssap://system/getSystemInfo"})
|
||||||
{"id": "req_info", "type": "request", "uri": "ssap://system/getSystemInfo"}
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
|
|
||||||
frames: list[dict[str, Any]] = []
|
frames: list[dict[str, Any]] = []
|
||||||
|
|||||||
@@ -9,29 +9,42 @@
|
|||||||
let
|
let
|
||||||
system = "x86_64-linux";
|
system = "x86_64-linux";
|
||||||
pkgs = import nixpkgs { inherit system; };
|
pkgs = import nixpkgs { inherit system; };
|
||||||
pythonEnv = pkgs.python3.withPackages (ps: [
|
ps = pkgs.python3Packages;
|
||||||
|
|
||||||
|
runtimeDeps = [
|
||||||
ps.websockets
|
ps.websockets
|
||||||
ps.mcp
|
ps.mcp
|
||||||
|
ps.pydantic
|
||||||
ps.asyncssh
|
ps.asyncssh
|
||||||
ps.uvicorn
|
ps.uvicorn
|
||||||
|
];
|
||||||
|
|
||||||
|
testDeps = [
|
||||||
ps.httpx
|
ps.httpx
|
||||||
ps.pytest
|
ps.pytest
|
||||||
ps.pytest-asyncio
|
ps.pytest-asyncio
|
||||||
]);
|
];
|
||||||
|
|
||||||
|
pythonEnv = pkgs.python3.withPackages (_: runtimeDeps ++ testDeps);
|
||||||
in
|
in
|
||||||
{
|
{
|
||||||
packages.${system}.default = pkgs.python3Packages.buildPythonApplication {
|
packages.${system}.default = ps.buildPythonApplication {
|
||||||
pname = "lg-smtv-mcp";
|
pname = "lg-smtv-mcp";
|
||||||
version = "0.1.0";
|
version = "0.1.0";
|
||||||
src = ./.;
|
src = ./.;
|
||||||
pyproject = true;
|
pyproject = true;
|
||||||
build-system = [ pkgs.python3Packages.setuptools ];
|
build-system = [ ps.setuptools ];
|
||||||
dependencies = with pkgs.python3Packages; [
|
dependencies = runtimeDeps;
|
||||||
websockets
|
nativeCheckInputs = [
|
||||||
mcp
|
ps.pytestCheckHook
|
||||||
asyncssh
|
pkgs.ruff
|
||||||
uvicorn
|
pkgs.pyright
|
||||||
];
|
] ++ testDeps;
|
||||||
|
preCheck = ''
|
||||||
|
ruff check .
|
||||||
|
ruff format --check .
|
||||||
|
pyright
|
||||||
|
'';
|
||||||
};
|
};
|
||||||
|
|
||||||
devShells.${system}.default = pkgs.mkShell {
|
devShells.${system}.default = pkgs.mkShell {
|
||||||
@@ -42,6 +55,9 @@
|
|||||||
];
|
];
|
||||||
shellHook = ''
|
shellHook = ''
|
||||||
export PYTHONPATH="$PWD/src:${PYTHONPATH:-}"
|
export PYTHONPATH="$PWD/src:${PYTHONPATH:-}"
|
||||||
|
if [ -d .git ] && [ -d .githooks ]; then
|
||||||
|
git config core.hooksPath .githooks
|
||||||
|
fi
|
||||||
'';
|
'';
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|||||||
+10
-3
@@ -6,10 +6,11 @@ build-backend = "setuptools.build_meta"
|
|||||||
name = "lg-smtv-mcp"
|
name = "lg-smtv-mcp"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
description = "MCP server for controlling an LG webOS Smart TV over the local network"
|
description = "MCP server for controlling an LG webOS Smart TV over the local network"
|
||||||
requires-python = ">=3.11"
|
requires-python = ">=3.14"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"websockets",
|
"websockets",
|
||||||
"mcp",
|
"mcp",
|
||||||
|
"pydantic",
|
||||||
"asyncssh",
|
"asyncssh",
|
||||||
"uvicorn",
|
"uvicorn",
|
||||||
]
|
]
|
||||||
@@ -29,9 +30,15 @@ line-length = 100
|
|||||||
target-version = "py314"
|
target-version = "py314"
|
||||||
|
|
||||||
[tool.ruff.lint]
|
[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]
|
[tool.pyright]
|
||||||
include = ["src", "tests"]
|
include = ["src", "tests"]
|
||||||
typeCheckingMode = "standard"
|
typeCheckingMode = "strict"
|
||||||
pythonVersion = "3.14"
|
pythonVersion = "3.14"
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
"""LG webOS Smart TV MCP server package."""
|
||||||
|
|
||||||
|
__all__ = ["__version__"]
|
||||||
|
|
||||||
|
__version__ = "0.1.0"
|
||||||
@@ -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())
|
||||||
@@ -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
|
||||||
@@ -0,0 +1,220 @@
|
|||||||
|
"""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
|
||||||
|
|
||||||
|
|
||||||
|
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:
|
||||||
|
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."""
|
||||||
|
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()
|
||||||
@@ -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
|
||||||
+40
-21
@@ -1,12 +1,10 @@
|
|||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from enum import StrEnum
|
from enum import StrEnum
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from lg_smtv_mcp.config import TvConfig, load_config, require_bearer_token, require_mac
|
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:
|
def _clear_tv_env(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
@@ -28,7 +26,7 @@ def _clear_tv_env(monkeypatch: pytest.MonkeyPatch) -> None:
|
|||||||
monkeypatch.delenv(key, raising=False)
|
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 = {
|
expected = {
|
||||||
"TV_OFFLINE_STANDBY",
|
"TV_OFFLINE_STANDBY",
|
||||||
"PAIRING_REQUIRED",
|
"PAIRING_REQUIRED",
|
||||||
@@ -47,8 +45,14 @@ def test_error_code_and_tv_error() -> None:
|
|||||||
assert err.message == "bad input"
|
assert err.message == "bad input"
|
||||||
assert "bad input" in str(err)
|
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(
|
|
||||||
|
def test_load_config_uses_expected_defaults_when_optional_vars_unset(
|
||||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||||
) -> None:
|
) -> None:
|
||||||
_clear_tv_env(monkeypatch)
|
_clear_tv_env(monkeypatch)
|
||||||
@@ -78,11 +82,7 @@ def test_dotenv_fallback_does_not_overwrite_existing_env(
|
|||||||
_clear_tv_env(monkeypatch)
|
_clear_tv_env(monkeypatch)
|
||||||
env_file = tmp_path / ".env"
|
env_file = tmp_path / ".env"
|
||||||
env_file.write_text(
|
env_file.write_text(
|
||||||
"# comment line\n"
|
"# comment line\nTV_IP=192.0.2.20\nPORT='9000'\nHOST=\"0.0.0.0\"\nENABLE_RAW_SSAP=true\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",
|
encoding="utf-8",
|
||||||
)
|
)
|
||||||
monkeypatch.setenv("TV_IP", "192.0.2.99")
|
monkeypatch.setenv("TV_IP", "192.0.2.99")
|
||||||
@@ -100,6 +100,8 @@ def test_dotenv_fallback_does_not_overwrite_existing_env(
|
|||||||
[
|
[
|
||||||
({}, "TV_IP"),
|
({}, "TV_IP"),
|
||||||
({"TV_IP": " "}, "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": "-1"}, "MAX_VOLUME"),
|
||||||
({"TV_IP": "192.0.2.10", "MAX_VOLUME": "101"}, "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", "MAX_VOLUME": "loud"}, "MAX_VOLUME"),
|
||||||
@@ -108,7 +110,7 @@ def test_dotenv_fallback_does_not_overwrite_existing_env(
|
|||||||
({"TV_IP": "192.0.2.10", "PORT": "abc"}, "PORT"),
|
({"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,
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
tmp_path: Path,
|
tmp_path: Path,
|
||||||
env_overrides: dict[str, str],
|
env_overrides: dict[str, str],
|
||||||
@@ -118,14 +120,33 @@ def test_load_config_validation_errors(
|
|||||||
for k, v in env_overrides.items():
|
for k, v in env_overrides.items():
|
||||||
monkeypatch.setenv(k, v)
|
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")
|
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
|
assert expected_substr in exc_info.value.message
|
||||||
|
|
||||||
|
|
||||||
def test_allowed_hosts_comma_separated(
|
@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_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
|
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||||
) -> None:
|
) -> None:
|
||||||
_clear_tv_env(monkeypatch)
|
_clear_tv_env(monkeypatch)
|
||||||
@@ -147,10 +168,10 @@ def test_require_bearer_token_rejects_missing_or_blank(
|
|||||||
monkeypatch.setenv("MCP_BEARER_TOKEN", token)
|
monkeypatch.setenv("MCP_BEARER_TOKEN", token)
|
||||||
|
|
||||||
cfg = load_config(env_path=tmp_path / "missing.env")
|
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)
|
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(
|
def test_require_bearer_token_returns_trimmed_value(
|
||||||
@@ -174,15 +195,13 @@ def test_require_mac_rejects_missing_or_blank(
|
|||||||
monkeypatch.setenv("TV_MAC", mac)
|
monkeypatch.setenv("TV_MAC", mac)
|
||||||
|
|
||||||
cfg = load_config(env_path=tmp_path / "missing.env")
|
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)
|
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(
|
def test_require_mac_returns_trimmed_value(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
||||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
|
||||||
) -> None:
|
|
||||||
_clear_tv_env(monkeypatch)
|
_clear_tv_env(monkeypatch)
|
||||||
monkeypatch.setenv("TV_IP", "192.0.2.10")
|
monkeypatch.setenv("TV_IP", "192.0.2.10")
|
||||||
monkeypatch.setenv("TV_MAC", " AA:BB:CC:DD:EE:FF ")
|
monkeypatch.setenv("TV_MAC", " AA:BB:CC:DD:EE:FF ")
|
||||||
|
|||||||
Reference in new issue
Block a user