From a6d33ae9e375fa8b0a8fd6c64991c96f110b19b2 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sun, 15 Nov 2026 21:46:30 -0500 Subject: [PATCH] feat(cli): implement serve and pair CLI subcommands - Implement serve (--transport streamable-http|stdio) with fail-closed Bearer token enforcement via create_http_app and stdio delegation - Implement pair (--ip, --fetch-ssh-key, --ssh-key-path) with .client_key.json merging, atomic 0600 file writes, and SSH key fetch error isolation - Remove Red-phase xfail markers in tests/test_cli.py --- src/lg_smtv_mcp/cli.py | 166 ++++++++++++++++++++++++++++++++++++++++- tests/test_cli.py | 6 -- 2 files changed, 162 insertions(+), 10 deletions(-) diff --git a/src/lg_smtv_mcp/cli.py b/src/lg_smtv_mcp/cli.py index 9569adb..24de904 100644 --- a/src/lg_smtv_mcp/cli.py +++ b/src/lg_smtv_mcp/cli.py @@ -1,15 +1,25 @@ """CLI entrypoint for lg-smtv-mcp (serve and pair subcommands).""" +import argparse +import asyncio +import ipaddress +import json +import os +import sys +import tempfile from collections.abc import Callable, Sequence +from contextlib import suppress from pathlib import Path -from typing import Any +from typing import Any, cast from mcp.server.mcpserver import MCPServer from lg_smtv_mcp.auth import ASGIApp from lg_smtv_mcp.config import TvConfig, load_config +from lg_smtv_mcp.errors import ConfigError, ErrorCode, TvError +from lg_smtv_mcp.server import create_http_app, create_mcp_server from lg_smtv_mcp.tv_core.protocols import WebSocketConnectFn -from lg_smtv_mcp.tv_core.ssap import websockets_connect +from lg_smtv_mcp.tv_core.ssap import build_register_payload, websockets_connect def _default_uvicorn_run(app: ASGIApp, host: str, port: int) -> None: @@ -29,6 +39,144 @@ def _default_fetch_url(url: str) -> bytes: return bytes(resp.read()) +def _atomic_write_0600(path: Path, data: bytes) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + fd, tmp_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=str(path.parent)) + tmp_path = Path(tmp_name) + try: + os.chmod(fd, 0o600) + with os.fdopen(fd, "wb") as handle: + handle.write(data) + os.chmod(tmp_path, 0o600) + os.replace(tmp_path, path) + except BaseException: + with suppress(OSError): + tmp_path.unlink() + raise + + +def _load_existing_keys(key_path: Path) -> dict[str, str]: + if not key_path.is_file(): + return {} + try: + raw = json.loads(key_path.read_text(encoding="utf-8")) + except OSError, json.JSONDecodeError: + return {} + if not isinstance(raw, dict): + return {} + raw_dict = cast(dict[Any, Any], raw) + return {str(k): str(v) for k, v in raw_dict.items() if isinstance(v, str) and v} + + +async def _pair_tv( + ip: str, + existing_key: str | None, + connect_fn: WebSocketConnectFn, +) -> str: + ws = await connect_fn(f"ws://{ip}:3000") + try: + reg_payload = build_register_payload(existing_key) + await ws.send(json.dumps(reg_payload)) + while True: + raw = await ws.recv() + frame: dict[str, Any] = json.loads(raw) + msg_type = frame.get("type") + if msg_type == "registered": + payload = frame.get("payload") + if isinstance(payload, dict): + payload_dict = cast(dict[str, Any], payload) + client_key = payload_dict.get("client-key") + if isinstance(client_key, str) and client_key: + return client_key + raise TvError(ErrorCode.PAIRING_REQUIRED, "TV registration returned no client-key") + if msg_type == "error": + raise TvError( + ErrorCode.PAIRING_REQUIRED, + f"TV pairing rejected: {frame.get('error', 'unknown error')}", + ) + finally: + await ws.close() + + +def _build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(prog="lg-smtv-mcp") + subparsers = parser.add_subparsers(dest="command", required=True) + + serve_parser = subparsers.add_parser("serve", help="Run the MCP server.") + serve_parser.add_argument( + "--transport", + choices=["streamable-http", "stdio"], + default="streamable-http", + help="MCP transport to serve.", + ) + + pair_parser = subparsers.add_parser("pair", help="Pair with an LG webOS TV.") + pair_parser.add_argument("--ip", default=None, help="TV IPv4 address (defaults to TV_IP).") + pair_parser.add_argument( + "--fetch-ssh-key", + action="store_true", + help="Also fetch Developer Mode SSH private key from http://:9991/webos_rsa.", + ) + pair_parser.add_argument( + "--ssh-key-path", + type=Path, + default=None, + help="Destination path for fetched Developer Mode SSH key.", + ) + return parser + + +def _handle_serve( + args: argparse.Namespace, + config: TvConfig, + *, + uvicorn_run: Callable[[ASGIApp, str, int], None], + stdio_run: Callable[[MCPServer[Any]], None], +) -> int: + if args.transport == "stdio": + server = create_mcp_server(config) + stdio_run(server) + return 0 + + app = create_http_app(config) + uvicorn_run(app, config.host, config.port) + return 0 + + +def _handle_pair( + args: argparse.Namespace, + config: TvConfig, + *, + connect_fn: WebSocketConnectFn, + fetch_url: Callable[[str], bytes], +) -> int: + raw_ip: str = args.ip if args.ip is not None else config.tv_ip + try: + tv_ip = str(ipaddress.IPv4Address(raw_ip.strip())) + except ValueError as exc: + raise ConfigError(f"Invalid TV IPv4 address: {raw_ip!r}") from exc + + existing_keys = _load_existing_keys(config.client_key_path) + client_key = asyncio.run(_pair_tv(tv_ip, existing_keys.get(tv_ip), connect_fn)) + existing_keys[tv_ip] = client_key + _atomic_write_0600( + config.client_key_path, + (json.dumps(existing_keys, indent=2) + "\n").encode("utf-8"), + ) + + if args.fetch_ssh_key: + ssh_dest: Path = args.ssh_key_path or config.ssh_key_path or Path(".webos_rsa") + key_bytes = fetch_url(f"http://{tv_ip}:9991/webos_rsa") + if not key_bytes.strip(): + raise TvError( + ErrorCode.SCREENSHOT_UNAVAILABLE, + "Fetched Developer Mode SSH key was empty", + ) + _atomic_write_0600(ssh_dest, key_bytes) + + return 0 + + def main( argv: Sequence[str] | None = None, *, @@ -40,5 +188,15 @@ def main( env_path: Path | None = None, ) -> int: """CLI entrypoint for `lg-smtv-mcp serve` and `lg-smtv-mcp pair`.""" - _ = (argv, config_loader, uvicorn_run, stdio_run, connect_fn, fetch_url, env_path) - raise NotImplementedError + _ = env_path + parser = _build_parser() + args = parser.parse_args(list(argv) if argv is not None else None) + + try: + config = config_loader() + if args.command == "serve": + return _handle_serve(args, config, uvicorn_run=uvicorn_run, stdio_run=stdio_run) + return _handle_pair(args, config, connect_fn=connect_fn, fetch_url=fetch_url) + except (ConfigError, TvError, OSError, ValueError) as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 diff --git a/tests/test_cli.py b/tests/test_cli.py index 3a60a0c..86f902a 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -29,7 +29,6 @@ def _make_config( ) -@pytest.mark.xfail(strict=True, reason="Red phase: cli not yet implemented") @pytest.mark.parametrize("bad_token", [None, "", " "]) def test_cli_serve_http_fails_closed_when_bearer_token_missing_or_blank( tmp_path: Path, @@ -52,7 +51,6 @@ def test_cli_serve_http_fails_closed_when_bearer_token_missing_or_blank( assert called is False -@pytest.mark.xfail(strict=True, reason="Red phase: cli not yet implemented") def test_cli_serve_http_runs_uvicorn_with_configured_host_and_port(tmp_path: Path) -> None: captured: list[tuple[ASGIApp, str, int]] = [] @@ -72,7 +70,6 @@ def test_cli_serve_http_runs_uvicorn_with_configured_host_and_port(tmp_path: Pat assert port == 8765 -@pytest.mark.xfail(strict=True, reason="Red phase: cli not yet implemented") def test_cli_serve_stdio_delegates_to_stdio_runner_without_bearer_token(tmp_path: Path) -> None: ran: list[MCPServer[Any]] = [] @@ -90,7 +87,6 @@ def test_cli_serve_stdio_delegates_to_stdio_runner_without_bearer_token(tmp_path assert isinstance(ran[0], MCPServer) -@pytest.mark.xfail(strict=True, reason="Red phase: cli not yet implemented") def test_cli_pair_merges_existing_client_keys_and_writes_0600(tmp_path: Path) -> None: key_file = tmp_path / ".client_key.json" key_file.write_text(json.dumps({"192.0.2.10": "old-key"}), encoding="utf-8") @@ -126,7 +122,6 @@ def test_cli_pair_merges_existing_client_keys_and_writes_0600(tmp_path: Path) -> assert stat.S_IMODE(key_file.stat().st_mode) == 0o600 -@pytest.mark.xfail(strict=True, reason="Red phase: cli not yet implemented") def test_cli_pair_fetch_ssh_key_saves_key_with_0600_permissions(tmp_path: Path) -> None: ssh_dest = tmp_path / "webos_rsa" fetched_urls: list[str] = [] @@ -162,7 +157,6 @@ def test_cli_pair_fetch_ssh_key_saves_key_with_0600_permissions(tmp_path: Path) assert stat.S_IMODE(ssh_dest.stat().st_mode) == 0o600 -@pytest.mark.xfail(strict=True, reason="Red phase: cli not yet implemented") def test_cli_pair_fetch_ssh_key_failure_preserves_client_key_and_exits_nonzero( tmp_path: Path, ) -> None: