From d13610b41029d54566ffd3c7616702c7bed6de82 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Mon, 16 Nov 2026 12:52:38 -0500 Subject: [PATCH 1/2] test(e2e): add full-stack MVP lifecycle E2E test (#4) --- tests/test_e2e_mvp.py | 266 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 266 insertions(+) create mode 100644 tests/test_e2e_mvp.py diff --git a/tests/test_e2e_mvp.py b/tests/test_e2e_mvp.py new file mode 100644 index 0000000..bb27e8f --- /dev/null +++ b/tests/test_e2e_mvp.py @@ -0,0 +1,266 @@ +"""End-to-end MVP lifecycle test over in-process Streamable HTTP MCP ClientSession.""" + +import asyncio +import json +from collections.abc import MutableMapping +from contextlib import suppress +from pathlib import Path +from typing import Any, cast + +import httpx2 +from mcp import ClientSession +from mcp.client.streamable_http import streamable_http_client +from mcp.types import TextContent + +from lg_smtv_mcp.config import TvConfig +from lg_smtv_mcp.server import create_http_app +from lg_smtv_mcp.tv_core import TvManager +from tests.conftest import FakeWebSocketTransport + + +def _extract_json_text(content: list[Any]) -> dict[str, Any]: + assert content, "Expected non-empty tool content" + first = content[0] + assert isinstance(first, TextContent) + parsed: Any = json.loads(first.text) + assert isinstance(parsed, dict) + return cast(dict[str, Any], parsed) + + +def _extract_error_text(content: list[Any]) -> str: + return " ".join(item.text for item in content if isinstance(item, TextContent)) + + +async def test_e2e_mvp_lifecycle_from_standby_through_clean_shutdown(tmp_path: Path) -> None: + tasks_before = set(asyncio.all_tasks()) + + tv_ip = "192.0.2.42" + tv_mac = "AA:BB:CC:DD:EE:FF" + bearer_token = "e2e-test-bearer-token" + key_file = tmp_path / ".client_key.json" + key_file.write_text(json.dumps({tv_ip: "e2e-saved-key"}), encoding="utf-8") + + config = TvConfig( + tv_ip=tv_ip, + tv_mac=tv_mac, + client_key_path=key_file, + mcp_bearer_token=bearer_token, + max_volume=40, + ) + + tv_awake = False + wol_calls: list[tuple[str, str, int]] = [] + sent_requests: list[tuple[str, dict[str, Any]]] = [] + standby_backoff_entered = asyncio.Event() + pointer_ws = FakeWebSocketTransport() + + def fake_send_wol(mac: str, broadcast_addr: str, port: int) -> None: + nonlocal tv_awake + wol_calls.append((mac, broadcast_addr, port)) + tv_awake = True + + async def fake_wait_fn(event: asyncio.Event, timeout: float) -> None: + standby_backoff_entered.set() + with suppress(TimeoutError): + await asyncio.wait_for(event.wait(), timeout=timeout) + + def _build_online_ssap() -> FakeWebSocketTransport: + def on_send(raw: str, ws: FakeWebSocketTransport) -> None: + msg: dict[str, Any] = json.loads(raw) + msg_type = msg.get("type") + msg_id = msg.get("id") + if msg_type == "register": + ws.push_json( + { + "type": "registered", + "id": msg_id, + "payload": {"client-key": "e2e-saved-key"}, + } + ) + return + if msg_type == "subscribe": + uri = str(msg.get("uri", "")) + if uri == "ssap://audio/getStatus": + ws.push_json( + { + "type": "response", + "id": msg_id, + "payload": { + "subscribed": True, + "volume": 10, + "mute": False, + "volumeStatus": {"soundOutput": "tv_speaker"}, + }, + } + ) + return + if uri == "ssap://com.webos.applicationManager/getForegroundAppInfo": + ws.push_json( + { + "type": "response", + "id": msg_id, + "payload": { + "subscribed": True, + "appId": "com.webos.app.home", + }, + } + ) + return + ws.push_json({"type": "response", "id": msg_id, "payload": {"subscribed": True}}) + return + if msg_type == "request": + uri = str(msg.get("uri", "")) + if uri == "ssap://com.webos.service.networkinput/getPointerInputSocket": + ws.push_json( + { + "type": "response", + "id": msg_id, + "payload": { + "returnValue": True, + "socketPath": f"ws://{tv_ip}:3000/pointer", + }, + } + ) + return + payload_in = dict(msg.get("payload") or {}) + sent_requests.append((uri, payload_in)) + ws.push_json({"type": "response", "id": msg_id, "payload": {"returnValue": True}}) + + return FakeWebSocketTransport(on_send=on_send) + + async def connect_fn(url: str) -> FakeWebSocketTransport: + if url.endswith("/pointer"): + return pointer_ws + if not tv_awake: + standby_ws = FakeWebSocketTransport() + standby_ws.push_close(1008, "Try Again Later (EWS)") + return standby_ws + return _build_online_ssap() + + manager = TvManager( + config, + connect_fn=connect_fn, + wol_fn=fake_send_wol, + backoff_steps=(10.0,), + wake_poll_interval=0.01, + wait_fn=fake_wait_fn, + ) + app = create_http_app(config, manager=manager) + + incoming: list[MutableMapping[str, Any]] = [ + {"type": "lifespan.startup"}, + {"type": "lifespan.shutdown"}, + ] + startup_done = asyncio.Event() + allow_shutdown = asyncio.Event() + + async def receive() -> MutableMapping[str, Any]: + if incoming[0]["type"] == "lifespan.shutdown": + await allow_shutdown.wait() + return incoming.pop(0) + + async def send(msg: MutableMapping[str, Any]) -> None: + if msg["type"] == "lifespan.startup.complete": + startup_done.set() + + async def _run_lifespan() -> None: + await app({"type": "lifespan"}, receive, send) + + lifespan_task: asyncio.Task[None] = asyncio.create_task(_run_lifespan()) + try: + await asyncio.wait_for(startup_done.wait(), timeout=2.0) + await asyncio.wait_for(standby_backoff_entered.wait(), timeout=2.0) + + transport = httpx2.ASGITransport(app=app) + async with ( + httpx2.AsyncClient( + transport=transport, + base_url="http://127.0.0.1:8765", + headers={"Authorization": f"Bearer {bearer_token}"}, + ) as http_client, + streamable_http_client( + "http://127.0.0.1:8765/mcp", + http_client=http_client, + ) as (read_stream, write_stream), + ClientSession(read_stream, write_stream) as session, + ): + await session.initialize() + + # 1. Standby (1008): launch fails fast with TV_OFFLINE_STANDBY and no implicit WoL. + standby_launch = await session.call_tool( + "launch", + {"app_id": "youtube.leanback.v4"}, + ) + assert standby_launch.is_error is True + assert "TV_OFFLINE_STANDBY" in _extract_error_text(standby_launch.content) + assert wol_calls == [] + + # 2. tv_wake: sends WoL magic packet, connects, and subscribes. + wake_res = await session.call_tool("tv_wake", {}) + assert wake_res.is_error is False + wake_payload = _extract_json_text(wake_res.content) + assert wake_payload["status"] == "connected" + assert wol_calls == [(tv_mac, "255.255.255.255", 9)] + + # 3. get_state: returns connected, fresh subscribed state. + state_res = await session.call_tool("get_state", {}) + assert state_res.is_error is False + state_payload = _extract_json_text(state_res.content) + assert state_payload["connected"] is True + assert state_payload["stale"] is False + assert state_payload["volume"] == 10 + assert state_payload["muted"] is False + assert state_payload["sound_output"] == "tv_speaker" + assert state_payload["foreground_app"] == "com.webos.app.home" + + # 4. launch with content_target: forwards params.contentTarget. + launch_res = await session.call_tool( + "launch", + { + "app_id": "youtube.leanback.v4", + "content_target": "v=dQw4w9WgXcQ", + }, + ) + assert launch_res.is_error is False + assert ( + "ssap://system.launcher/launch", + { + "id": "youtube.leanback.v4", + "params": {"contentTarget": "v=dQw4w9WgXcQ"}, + }, + ) in sent_requests + + # 5. Batched keys: acquires pointer socket and sends both button frames. + keys_res = await session.call_tool( + "keys", + {"keys": ["DOWN", "ENTER"], "delay_ms": 0, "settle_ms": 0}, + ) + assert keys_res.is_error is False + keys_payload = _extract_json_text(keys_res.content) + assert keys_payload == {"keys_sent": True, "count": 2} + assert pointer_ws.sent == [ + "type:button\nname:DOWN\n\n", + "type:button\nname:ENTER\n\n", + ] + + # 6. set_volume(15): sends {"volume": 15}. + vol_res = await session.call_tool("set_volume", {"level": 15}) + assert vol_res.is_error is False + assert ("ssap://audio/setVolume", {"volume": 15}) in sent_requests + + # 7. turn_off(): sends ssap://system/turnOff. + off_res = await session.call_tool("turn_off", {}) + assert off_res.is_error is False + assert ("ssap://system/turnOff", {}) in sent_requests + finally: + # 8. Clean ASGI lifespan shutdown with zero orphaned asyncio tasks. + allow_shutdown.set() + await asyncio.wait_for(lifespan_task, timeout=2.0) + + # sse_starlette spawns one per-loop _shutdown_watcher() singleton polling AppStatus.should_exit. + orphaned_tasks = [ + task + for task in (asyncio.all_tasks() - tasks_before) + if getattr(task.get_coro(), "__qualname__", None) != "_shutdown_watcher" + ] + assert orphaned_tasks == [] From b215a26d0575d516bfe2c62da54968e62f827e55 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Mon, 16 Nov 2026 12:53:26 -0500 Subject: [PATCH 2/2] docs(readme): document MVP setup, pair/serve CLI, and live-TV E2E checklist (#4) --- README.md | 70 +++++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 60 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 6ac103b..fc50262 100644 --- a/README.md +++ b/README.md @@ -6,8 +6,8 @@ A Python Model Context Protocol (MCP) server for persistent, local-network contr The server is deliberately **LLM-free**: it exposes bounded, deterministic operations so external AI agents (such as Antigravity, Claude, or a vision-guided decision loop) can reason over UI state and control the television without embedding model APIs into the daemon. -> **Status: Active development (Milestone M1).** -> Configuration validation, error taxonomy, and the [`tv_core`](src/lg_smtv_mcp/tv_core/) engine (SSAP multiplexer, `PointerClient`, and `TvManager` state machine) are implemented and unit-tested offline. FastMCP tool bindings, Bearer authentication, CLI entrypoints (`pair` / `serve`), and end-to-end verification are currently in progress; Developer Mode SFTP screenshot capture is planned for M2. +> **Status: Milestone M1 complete (MVP).** +> Configuration validation, error taxonomy, [`tv_core`](src/lg_smtv_mcp/tv_core/) (SSAP multiplexer, `PointerClient`, `TvManager`), FastMCP server & Bearer auth ([`server.py`](src/lg_smtv_mcp/server.py), [`auth.py`](src/lg_smtv_mcp/auth.py)), `pair` / `serve` CLI ([`cli.py`](src/lg_smtv_mcp/cli.py)), and full-stack offline E2E verification ([`test_e2e_mvp.py`](tests/test_e2e_mvp.py)) are implemented and tested. Developer Mode SFTP screenshot capture is planned for M2. --- @@ -34,7 +34,7 @@ The codebase centers on [`tv_core`](src/lg_smtv_mcp/tv_core/), which owns the TV | [`SsapClient`](src/lg_smtv_mcp/tv_core/ssap.py) | Implemented | Persistent TLS SSAP WebSocket, `msg["id"]` request/subscribe multiplexing, `1008` standby mapping | | [`PointerClient`](src/lg_smtv_mcp/tv_core/pointer.py) | Implemented | Ephemeral webOS pointer socket for allowlisted remote button frames and mid-batch reconnect | | [`TvManager`](src/lg_smtv_mcp/tv_core/manager.py) | Implemented | Single-owner connection loop, stepped backoff, `wake()` coalescing, `subscribe` cache, `ui_lock`, control surface | -| MCP Server & CLI (`server.py`, `cli.py`) | In progress (M1) | FastMCP tools, `streamable-http` Bearer auth, `pair` / `serve` CLI, `SIGHUP` key reload | +| [`server.py`](src/lg_smtv_mcp/server.py), [`auth.py`](src/lg_smtv_mcp/auth.py), [`cli.py`](src/lg_smtv_mcp/cli.py) | Implemented | FastMCP tools, `streamable-http` Bearer auth & host validation, `pair` / `serve` CLI, `SIGHUP` key reload | | Developer Mode Capture (`capture.py`) | Planned (M2) | `asyncssh` SFTP screenshot retrieval behind the [`FrameCapturer`](src/lg_smtv_mcp/tv_core/protocols.py) protocol | ### Communication Channels @@ -60,14 +60,14 @@ Implementation is tracked on the [Project Pipeline](https://gitea.roadtotech.me/ | Milestone | Scope | Status | | :--- | :--- | :--- | -| **M1** | Core config, `tv_core` engine, FastMCP tools, Bearer auth, `pair`/`serve` CLI, E2E verification | In progress (`#1` & `#2` merged; `#3` in progress; `#4` queued) | +| **M1** | Core config, `tv_core` engine, FastMCP tools, Bearer auth, `pair`/`serve` CLI, E2E verification | Complete (`#1`–`#3` merged on `main`; `#4` E2E & docs) | | **M2** | Developer Mode SFTP screenshot capture (`asyncssh`), systemd unit, extended surface | Planned (`#5`) | -Implemented in [`TvManager`](src/lg_smtv_mcp/tv_core/manager.py) today (not yet exposed over MCP until `#3` completes): -- Persistent SSAP multiplexing and `subscribe`-backed state snapshots (`volume`, `muted`, `sound_output`, `foreground_app`) -- Stepped reconnect backoff and explicit `wake()` coalescing (`WAKE_TIMEOUT`) -- Allowlisted pointer button sequences (`send_keys`) and IME text entry (`type_text`) -- App discovery/launching (`list_apps`, `launch_app`), volume/mute guardrails (`set_volume`, `set_mute`), input discovery/switching (`list_inputs`, `switch_input`), `turn_off`, and gated `raw_ssap` +Implemented in [`TvManager`](src/lg_smtv_mcp/tv_core/manager.py) and exposed via [`server.py`](src/lg_smtv_mcp/server.py): +- Persistent SSAP multiplexing and `subscribe`-backed state snapshots (`get_state`: `volume`, `muted`, `sound_output`, `foreground_app`) +- Stepped reconnect backoff and explicit Wake-on-LAN coalescing (`tv_wake`, bounded by `WAKE_TIMEOUT`) +- Allowlisted pointer button sequences (`keys`) and IME text entry (`type_text`) with optional `capture` hook (`screenshot`) +- App discovery/launching (`list_apps`, `launch`), volume/mute guardrails (`set_volume`, `set_mute`), input discovery/switching (`list_inputs`, `switch_input`), `turn_off`, and opt-in `raw_ssap` (`ENABLE_RAW_SSAP=true`) --- @@ -109,6 +109,17 @@ Runtime configuration is loaded by [`load_config()`](src/lg_smtv_mcp/config.py) cp .env.example .env ``` +Edit `.env` with your TV's local network coordinates and a generated Bearer token (never commit `.env` or `.client_key.json`): + +```dotenv +TV_IP= +TV_MAC= +MCP_BEARER_TOKEN= +HOST=127.0.0.1 +PORT=8765 +MAX_VOLUME=40 +``` + | Variable | Purpose | Default / Requirement | | :--- | :--- | :--- | | `TV_IP` | Target TV IPv4 address | Required | @@ -125,7 +136,46 @@ cp .env.example .env | `MAX_VOLUME` | Upper bound guardrail (`0..100`) for `set_volume` | `40` | | `ENABLE_RAW_SSAP` | Enables optional `raw_ssap` pass-through (`true`/`false`) | `false` | -> **Note:** `TvConfig` and `load_config()` are implemented, while the MCP server runtime and `pair` / `serve` CLI are still under active development in M1. +--- + +## Running the MVP Server (`pair` & `serve`) + +1. **Pair with the TV (one-time per TV):** Ensure the TV is powered on with *LG Connect Apps* enabled, then run: + + ```bash + lg-smtv-mcp pair + # Optional: override IP or also fetch Developer Mode SSH key + lg-smtv-mcp pair --ip + ``` + + Accept the pairing prompt on the TV screen. The client key is saved atomically with `0600` permissions to `CLIENT_KEY_PATH` (default `.client_key.json`). + +2. **Start the MCP server:** + + ```bash + # Default: persistent Streamable HTTP daemon at http://:/mcp + # Requires Authorization: Bearer + lg-smtv-mcp serve + + # Local testing over stdio (no HTTP Bearer token required) + lg-smtv-mcp serve --transport stdio + ``` + + If you re-pair while `serve` is running, send `SIGHUP` to reload `.client_key.json` without restarting the daemon. + +--- + +## Operator Live-TV E2E Smoke Test Checklist + +Automated tests run strictly offline. After deploying or updating on a host on the same LAN as the TV, run this manual smoke checklist from an MCP client connected to `lg-smtv-mcp serve`: + +- [ ] **`pair`**: Run `lg-smtv-mcp pair`, accept the on-screen TV prompt, and confirm `CLIENT_KEY_PATH` (`.client_key.json`) exists with `0600` permissions and an entry for ``. +- [ ] **`tv_wake`**: With the TV in standby, verify a mutating tool (`launch`) fails fast with `TV_OFFLINE_STANDBY` (no implicit WoL), then call `tv_wake` and confirm the TV powers on and returns `status: "connected"`. +- [ ] **`get_state`**: Call `get_state` and confirm `connected: true`, `stale: false`, and live `volume`, `muted`, `sound_output`, and `foreground_app` values. +- [ ] **`launch`**: Call `launch` (e.g., `app_id="youtube.leanback.v4"` with an optional `content_target`) and confirm the app opens on screen. +- [ ] **`keys`**: Call `keys` with a small batch (e.g., `["DOWN", "ENTER"]`) and confirm D-pad navigation registers on the TV. +- [ ] **`set_volume`**: Call `set_volume` with a safe level within `MAX_VOLUME` (e.g., `15`) and confirm the TV volume updates. +- [ ] **`turn_off`**: Call `turn_off` and confirm the TV enters standby and subsequent `get_state` reports `connected: false, stale: true`. ---