Author SHA1 Message Date
kiskaadee 90cafe37ff fix(manager): transition to STANDBY_OFFLINE immediately on turn_off()
Core Architecture & Invariant CI / validate (pull_request) Failing after 0s
- Transition TvManager.turn_off() to STANDBY_OFFLINE, clear _connected_event, tear down active transports, and signal _on_ssap_disconnect(ErrorCode.TV_OFFLINE_STANDBY) only when response.get("returnValue") is True so get_state() reports stale immediately and wake() sends WoL without deadlocking on _connection_loop().

- Add behavior-driven unit tests in tests/test_manager.py covering immediate standby/teardown, immediate wake() with WoL and reconnection, and no-op behavior when returnValue is not True.

- Align tests/test_e2e_mvp.py to verify immediate standby after turn_off() without waiting for a delayed 1008 WebSocket close frame.
2026-11-22 14:00:16 -05:00
kiskaadee 1e760c51b2 docs(reconcile): align canonical docs with #20/M2.1 and add getting-started guide
Core Architecture & Invariant CI / validate (push) Failing after 0s
- README.md: add step-by-step Getting Started guide (TV prerequisites, host setup, .env/token, pairing, server run, MCP client connection) so new users have a linear onboarding path; add CAPTURE_MAX_WIDTH/CAPTURE_JPEG_QUALITY, pillow, M2.1 status, and docs/experiments/ link.
- ARCHITECTURE.md: add pillow to runtime dependencies and document CaptureClient host-side JPEG downscaling, KeyImportError mapping, and server.py config wiring so architecture reflects main.
- ROADMAP.md: add M2.1 active items (#21-#23) to Near Term and record #20 (PR #24) plus Crunchyroll E2E benchmarks under Completed.
- docs/designs/lg-smtv-mcp.md: reconcile config.py and capture.py rows in Package & Module Layout for #20 capture downscaling and KeyImportError handling.
2026-11-21 15:02:44 -05:00
kiskaadee a0f798d702 docs(readme): add M8ven Score badge
Core Architecture & Invariant CI / validate (push) Failing after 0s
2026-11-19 14:46:04 -05:00
kiskaadee 128752b71e docs(experiments): record post-#20 E2E benchmark (09618be)
Core Architecture & Invariant CI / validate (push) Successful in 16s
- docs/experiments/crunchyroll-e2e-post-20-09618be.md: record 17-step / 167.46s benchmark with CAPTURE_MAX_WIDTH=480 and CAPTURE_JPEG_QUALITY=55, showing -69.1% median capture size (19,045 B -> 5,893 B) and disk-only offloads reduced from 60% to 7%
2026-11-19 11:26:43 -05:00
kiskaadee 93a572cbb5 fix(capture): handle DecompressionBombError and deduplicate server test SSH scaffolding
Core Architecture & Invariant CI / validate (pull_request) Successful in 16s
Core Architecture & Invariant CI / validate (push) Successful in 16s
- src/lg_smtv_mcp/tv_core/capture.py: catch Image.DecompressionBombError alongside UnidentifiedImageError/OSError/ValueError/EOFError so oversized/malformed image headers map to TvError(ErrorCode.SCREENSHOT_UNAVAILABLE) (CR-01)
- tests/test_capture.py: add Red-Green regression test verifying DecompressionBombError maps to SCREENSHOT_UNAVAILABLE
- tests/test_server.py: extract _wire_capture_client_with_fake_ssh helper to eliminate duplicated fake SSH/SFTP scaffolding across server capture wiring tests (CR-02)
2026-11-19 10:52:35 -05:00
12 changed files with 343 additions and 132 deletions

No files matched your search

+2
View File
@@ -11,3 +11,5 @@ ALLOWED_HOSTS=
MCP_BEARER_TOKEN=<GENERATE_TOKEN>
MAX_VOLUME=40
ENABLE_RAW_SSAP=false
CAPTURE_MAX_WIDTH=480
CAPTURE_JPEG_QUALITY=55
+4 -4
View File
@@ -1,6 +1,6 @@
# Architecture
`lg-smtv-mcp` is a stateful, LLM-free Model Context Protocol (MCP) server for local-network control of a single pre-paired LG webOS Smart TV. This document describes the canonical present-state architecture implemented on `main` (Milestone M1 control plane plus the Milestone M2 Developer Mode capture slice).
`lg-smtv-mcp` is a stateful, LLM-free Model Context Protocol (MCP) server for local-network control of a single pre-paired LG webOS Smart TV. This document describes the canonical present-state architecture implemented on `main` (Milestone M1 control plane, Milestone M2 Developer Mode capture & `systemd` packaging, and M2.1 host-side JPEG downscaling).
## System Overview
@@ -35,7 +35,7 @@ flowchart LR
| SSAP Client | [`tv_core/ssap.py`](src/lg_smtv_mcp/tv_core/ssap.py) | `SsapClient` single-reader `_reader_loop()` multiplexing `msg["id"]` responses and `subscribe` callbacks; 16-permission `register` payload; `1008` and `401` mapping; pending `Future` failure on disconnect. |
| Pointer Client | [`tv_core/pointer.py`](src/lg_smtv_mcp/tv_core/pointer.py) | `PointerClient` button allowlist normalization/validation (rejecting `\r`/`\n` and unknown keys), `type:button` framing, pacing, and single mid-batch socket re-acquire. |
| TV Manager | [`tv_core/manager.py`](src/lg_smtv_mcp/tv_core/manager.py) | `TvManager` state machine, `send_wol`, `subscribe` state cache (`audio/getStatus`, `getForegroundAppInfo`), `ui_lock` (`25s` timeout), `CLIENT_KEY_PATH` reload on backoff/`SIGHUP`, and tool-backing operations. |
| Developer Mode Capture | [`tv_core/capture.py`](src/lg_smtv_mcp/tv_core/capture.py) | `CaptureClient` (`FrameCapturer`) triggers `executeOneShot` and pulls the JPEG; `AsyncSshCaptureTransport` (`CaptureTransport`) lazily opens/reuses the `asyncssh` SFTP session, sweeps stale `/tmp/lg_smtv_cap_*` files while excluding the in-flight capture, and enforces the `6.0s` read deadline plus `1.5s` shielded remove grace. |
| Developer Mode Capture | [`tv_core/capture.py`](src/lg_smtv_mcp/tv_core/capture.py) | `CaptureClient` (`FrameCapturer`) triggers `executeOneShot`, pulls the JPEG, and optionally downscales/recompresses via Pillow (`CAPTURE_MAX_WIDTH`, `CAPTURE_JPEG_QUALITY`) before hashing; `AsyncSshCaptureTransport` (`CaptureTransport`) lazily opens/reuses the `asyncssh` SFTP session, maps `KeyImportError` to `SCREENSHOT_UNAVAILABLE`, sweeps stale `/tmp/lg_smtv_cap_*` files while excluding the in-flight capture, and enforces the `6.0s` read deadline plus `1.5s` shielded remove grace. |
| HTTP Auth & Security | [`auth.py`](src/lg_smtv_mcp/auth.py) | `BearerAuthMiddleware` (`hmac.compare_digest` on `Authorization: Bearer <token>`) and `build_transport_security_settings` for DNS-rebinding protection. |
| MCP Server | [`server.py`](src/lg_smtv_mcp/server.py) | `create_mcp_server` / `create_http_app`, ASGI `lifespan` (`TvManager.start()`/`close()` + `SIGHUP`), `ToolError` mapping, 12 default tools + opt-in `raw_ssap`, `TextContent`/`ImageContent` formatting. |
| CLI Entrypoint | [`cli.py`](src/lg_smtv_mcp/cli.py), [`__main__.py`](src/lg_smtv_mcp/__main__.py) | `lg-smtv-mcp serve` (`streamable-http` with fail-closed token check, or `stdio`) and `lg-smtv-mcp pair` (atomic `0600` `.client_key.json` write + optional `--fetch-ssh-key`). |
@@ -44,7 +44,7 @@ flowchart LR
1. **Startup:** `cli.py serve` loads [`TvConfig`](src/lg_smtv_mcp/config.py), requires `MCP_BEARER_TOKEN` for `streamable-http`, builds the ASGI app via [`create_http_app`](src/lg_smtv_mcp/server.py), and starts `uvicorn`. The ASGI `lifespan` starts [`TvManager`](src/lg_smtv_mcp/tv_core/manager.py) and registers `SIGHUP` for `.client_key.json` reload.
2. **Steady-state & Subscriptions:** When connected, `SsapClient._reader_loop()` routes incoming frames by `msg["id"]` to either awaiting request `Future`s or `subscribe` handlers updating `TvState` (`volume`, `muted`, `sound_output`, `foreground_app`, `last_updated`).
3. **Serialized UI Control:** `send_keys`, `type_text`, and `screenshot` acquire `ui_lock` with a `25s` timeout (`LOCK_TIMEOUT`). `create_mcp_server` default-wires `TvManager(..., capture_client=CaptureClient(AsyncSshCaptureTransport(config)))`, so `capture=True` captures over SFTP; when the capture transport is unavailable (Developer Mode SSH off or expired), `send_keys` and `type_text` return partial success with `capture_error="SCREENSHOT_UNAVAILABLE: ..."` while `screenshot` fails with `SCREENSHOT_UNAVAILABLE`. `TvManager` closes the SFTP session on standby and transport transitions.
3. **Serialized UI Control:** `send_keys`, `type_text`, and `screenshot` acquire `ui_lock` with a `25s` timeout (`LOCK_TIMEOUT`). `create_mcp_server` default-wires `TvManager(..., capture_client=CaptureClient(AsyncSshCaptureTransport(config), max_width=config.capture_max_width, jpeg_quality=config.capture_jpeg_quality))`, so `capture=True` captures over SFTP and optionally downscales/recompresses the JPEG in memory; when the capture transport is unavailable (Developer Mode SSH off or expired), `send_keys` and `type_text` return partial success with `capture_error="SCREENSHOT_UNAVAILABLE: ..."` while `screenshot` fails with `SCREENSHOT_UNAVAILABLE`. `TvManager` closes the SFTP session on standby and transport transitions.
4. **Shutdown:** ASGI `lifespan` exit removes the `SIGHUP` handler and awaits `TvManager.close()`, tearing down background tasks and open transports cleanly.
## Boundaries
@@ -55,7 +55,7 @@ flowchart LR
## Dependencies
- **Runtime (`pyproject.toml` / `flake.nix`):** Python `>=3.14`, `websockets`, `mcp`, `pydantic`, `asyncssh`, `uvicorn`.
- **Runtime (`pyproject.toml` / `flake.nix`):** Python `>=3.14`, `websockets`, `mcp`, `pydantic`, `asyncssh`, `uvicorn`, `pillow`.
- **Development / Verification:** `pytest`, `pytest-asyncio`, `httpx`, `ruff`, `pyright` (strict mode).
## Architectural Constraints
+77 -41
View File
@@ -1,13 +1,15 @@
# lg-smtv-mcp
[![M8ven Score](https://m8ven.ai/badge/mcp/kiskaadee-lg-smtv-mcp-1hkv9o?v=e22cd6151bbeb9e9a4b51cacc3bc775e)](https://m8ven.ai/mcp/kiskaadee-lg-smtv-mcp-1hkv9o?s=readme)
A Python Model Context Protocol (MCP) server for persistent, local-network control of LG webOS Smart TVs.
`lg-smtv-mcp` provides an agent-friendly control plane over LG's Simple Service Access Protocol (SSAP), combining persistent WebSocket connections, remote pointer button input, subscription-based device state tracking, Wake-on-LAN recovery, and optional Developer Mode screenshot capture.
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: M2 delivered — capture, E2E hardening, and `systemd` deployment.**
> 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)), full-stack offline E2E verification ([`test_e2e_mvp.py`](tests/test_e2e_mvp.py)), and Developer Mode SFTP screenshot capture ([`capture.py`](src/lg_smtv_mcp/tv_core/capture.py)) are implemented and tested. Milestone M2 is delivered; `systemd` unit sandboxing hardening is implemented in [#17](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/issues/17).
> **Status: M2 delivered — M2.1 live-TV polish in progress.**
> 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)), full-stack offline E2E verification ([`test_e2e_mvp.py`](tests/test_e2e_mvp.py)), Developer Mode SFTP screenshot capture with optional host-side JPEG downscaling ([`capture.py`](src/lg_smtv_mcp/tv_core/capture.py)), and `systemd` unit sandboxing hardening ([#17](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/issues/17)) are implemented on `main`. Ongoing M2.1 polish is tracked in [ROADMAP.md](ROADMAP.md).
---
@@ -61,7 +63,8 @@ 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 | Complete (`#1`–`#4` merged on `main`) |
| **M2** | Developer Mode SFTP screenshot capture (`asyncssh`), systemd unit, E2E test hardening | Delivered — capture (`#12`), E2E hardening (`#11`), and systemd deployment (`#13`); unit sandboxing hardening tracked in `#17` |
| **M2** | Developer Mode SFTP screenshot capture (`asyncssh`), systemd unit, E2E test hardening, sandboxing | Complete (`#11`–`#13`, `#17` merged on `main`) |
| **M2.1** | Host-side JPEG downscaling (`#20`), immediate `turn_off` standby (`#21`), Nix sandbox tests (`#22`), settle retry (`#23`) | In progress (`#20` merged; `#21`–`#23` open) |
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`)
@@ -71,13 +74,19 @@ Implemented in [`TvManager`](src/lg_smtv_mcp/tv_core/manager.py) and exposed via
---
## Requirements & Tested Hardware
## Prerequisites & Tested Hardware
- **Runtime:** Python 3.14+ (or Nix with Flakes enabled)
- **Hardware:** An LG webOS Smart TV reachable on the local network (with Wake-on-LAN and LG Connect Apps enabled for power-on and SSAP control)
- **Optional:** LG Developer Mode enabled for SSH/SFTP screenshot capture
Before running the server, make sure you have:
Initial protocol exploration and empirical verification were performed against:
- **Host Runtime:** Nix with Flakes enabled (recommended) or Python `3.14+`
- **Network:** Host and LG webOS Smart TV on the **same local network** (Wake-on-LAN uses UDP broadcast; SSAP uses `wss://<TV_IP>:3001`)
- **LG webOS TV Settings:**
- **LG Connect Apps** enabled (*Settings -> General -> Devices -> External Devices -> LG Connect Apps*, or *Network -> LG Connect Apps* depending on webOS version)
- **Wake-on-LAN / Mobile TV On** enabled (*Turn On via Wi-Fi / Network*) if you want `tv_wake` to power on the TV from standby
- **Static IP / DHCP reservation** (recommended) and the TV's **MAC address**
- **Optional (for Screenshots):** An LG Developer account and the **Developer Mode** app installed on the TV with **Dev Mode Status** and **Key Server** enabled (SSH/SFTP on port `9922`)
Initial protocol exploration and live-TV verification were performed against:
- **Device:** `65UR8750PSA`
- **Platform:** `WebOS/4.1.0`
@@ -85,9 +94,11 @@ Compatibility with other LG webOS models and firmware versions has not yet been
---
## Development Setup
## Getting Started (Step-by-Step)
This repository uses Nix Flakes ([flake.nix](flake.nix)) for reproducible environments:
### Step 1: Prepare the Host Environment
Clone the repository and enter the Nix devShell ([`flake.nix`](flake.nix)):
```bash
git clone https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp.git
@@ -97,62 +108,53 @@ nix develop
If you use `direnv`, run `direnv allow` to activate [`.envrc`](.envrc) automatically.
The shell provisions Python 3.14, `websockets`, `mcp`, `pydantic`, `asyncssh`, `uvicorn`, `httpx`, `pytest`, `pytest-asyncio`, `ruff`, and `pyright`, and configures `.githooks/` as the Git hooks path.
The shell provisions Python 3.14, `websockets`, `mcp`, `pydantic`, `asyncssh`, `uvicorn`, `pillow`, `httpx`, `pytest`, `pytest-asyncio`, `ruff`, and `pyright`, and configures `.githooks/` as the Git hooks path.
---
> **Note:** Inside `nix develop`, run commands using `python -m lg_smtv_mcp <subcommand>` (or `nix run . -- <subcommand>`), as the devShell provisions the Python environment directly rather than installing package console scripts to `PATH`.
## Configuration
### Step 2: Create and Configure `.env`
Runtime configuration is loaded by [`load_config()`](src/lg_smtv_mcp/config.py) from process environment variables with `.env` fallback (existing process environment variables always take precedence). See [`.env.example`](.env.example):
Copy [`.env.example`](.env.example) to `.env` and fill in your TV's IP, MAC address, and a freshly generated Bearer token (never commit `.env`, `.client_key.json`, or SSH keys):
```bash
cp .env.example .env
openssl rand -hex 32 # use output as MCP_BEARER_TOKEN
```
Edit `.env` with your TV's local network coordinates and a generated Bearer token (never commit `.env` or `.client_key.json`):
Minimal `.env` for local use:
```dotenv
TV_IP=<TV_IP>
TV_MAC=<TV_MAC>
MCP_BEARER_TOKEN=<GENERATE_TOKEN>
MCP_BEARER_TOKEN=<GENERATED_TOKEN>
HOST=127.0.0.1
PORT=8765
MAX_VOLUME=40
```
| Variable | Purpose | Default / Requirement |
| :--- | :--- | :--- |
| `TV_IP` | Target TV IPv4 address | Required |
| `TV_MAC` | Target TV MAC address for Wake-on-LAN | Required for `wake` |
| `WOL_BROADCAST` | Wake-on-LAN UDP broadcast IPv4 address | `255.255.255.255` |
| `CLIENT_KEY_PATH` | SSAP pairing client-key JSON path | `.client_key.json` |
| `SSH_KEY_PATH` | Optional Developer Mode SSH private key path | Unset |
| `WEBOS_SSH_PASSPHRASE` | Optional SSH key passphrase | Unset |
| `SSH_KNOWN_HOSTS_PATH` | Optional SSH `known_hosts` path | Unset |
| `HOST` | HTTP server bind address | `127.0.0.1` |
| `PORT` | HTTP server port (`1..65535`) | `8765` |
| `ALLOWED_HOSTS` | Comma-separated permitted HTTP `Host` headers | Empty |
| `MCP_BEARER_TOKEN` | Bearer token for `streamable-http` transport | Required for HTTP |
| `MAX_VOLUME` | Upper bound guardrail (`0..100`) for `set_volume` | `40` |
| `ENABLE_RAW_SSAP` | Enables optional `raw_ssap` pass-through (`true`/`false`) | `false` |
If you enable Developer Mode screenshots, also consider setting `CAPTURE_MAX_WIDTH=480` and `CAPTURE_JPEG_QUALITY=55` (as in [`.env.example`](.env.example)) so screenshots stay compact enough for inline MCP delivery without disk offloading.
---
### Step 3: Pair with the TV (One-Time)
## Running the MVP Server (`pair` & `serve`)
> **Note:** Inside `nix develop`, run commands using `python -m lg_smtv_mcp <subcommand>` (or `nix run . -- <subcommand>`), as the devShell provisions the Python environment directly rather than installing package console scripts to `PATH`.
1. **Pair with the TV (one-time per TV):** Ensure the TV is powered on with *LG Connect Apps* enabled, then run:
Power **on** the TV and ensure *LG Connect Apps* is enabled. Then run:
```bash
python -m lg_smtv_mcp pair
# Optional: override IP or also fetch Developer Mode SSH key
# Or override TV_IP:
python -m lg_smtv_mcp pair --ip <TV_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`).
If you also want **Developer Mode screenshot capture**, enable *Developer Mode* and *Key Server* in the TV's Developer Mode app first, then run:
2. **Start the MCP server:**
```bash
python -m lg_smtv_mcp pair --fetch-ssh-key
```
Accept the pairing prompt on the TV screen using your physical remote:
- The SSAP client key is saved atomically with `0600` permissions to `CLIENT_KEY_PATH` (default `.client_key.json`).
- `--fetch-ssh-key` downloads the Developer Mode private key from `http://<TV_IP>:9991/webos_rsa` and saves it with `0600` permissions (default `.webos_rsa`). Set `SSH_KEY_PATH=.webos_rsa` (and `WEBOS_SSH_PASSPHRASE` if configured) in `.env`.
### Step 4: Start the MCP Server
```bash
# Default: persistent Streamable HTTP daemon at http://<HOST>:<PORT>/mcp
@@ -165,6 +167,39 @@ MAX_VOLUME=40
If you re-pair while `serve` is running, send `SIGHUP` to reload `.client_key.json` without restarting the daemon.
### Step 5: Connect Your MCP Client
Point your MCP host/client at the Streamable HTTP endpoint:
- **URL:** `http://<HOST>:<PORT>/mcp` (default `http://127.0.0.1:8765/mcp`)
- **Header:** `Authorization: Bearer <MCP_BEARER_TOKEN>`
If your MCP client runs on a different machine than the server, set **both** `HOST=0.0.0.0` (or the server's LAN IP) **and** `ALLOWED_HOSTS=<server-lan-ip-or-hostname>` in `.env`, and place the server behind an HTTPS reverse proxy or encrypted tunnel (e.g., WireGuard/Tailscale) if crossing untrusted networks.
---
## Configuration Reference
Runtime configuration is loaded by [`load_config()`](src/lg_smtv_mcp/config.py) from process environment variables with `.env` fallback (existing process environment variables always take precedence).
| Variable | Purpose | Default / Requirement |
| :--- | :--- | :--- |
| `TV_IP` | Target TV IPv4 address | Required |
| `TV_MAC` | Target TV MAC address for Wake-on-LAN | Required for `tv_wake` |
| `WOL_BROADCAST` | Wake-on-LAN UDP broadcast IPv4 address | `255.255.255.255` |
| `CLIENT_KEY_PATH` | SSAP pairing client-key JSON path | `.client_key.json` |
| `SSH_KEY_PATH` | Optional Developer Mode SSH private key path | Unset |
| `WEBOS_SSH_PASSPHRASE` | Optional SSH key passphrase | Unset |
| `SSH_KNOWN_HOSTS_PATH` | Optional SSH `known_hosts` path | Unset |
| `HOST` | HTTP server bind address | `127.0.0.1` |
| `PORT` | HTTP server port (`1..65535`) | `8765` |
| `ALLOWED_HOSTS` | Comma-separated permitted HTTP `Host` headers | Empty |
| `MCP_BEARER_TOKEN` | Bearer token for `streamable-http` transport | Required for HTTP |
| `MAX_VOLUME` | Upper bound guardrail (`0..100`) for `set_volume` | `40` |
| `ENABLE_RAW_SSAP` | Enables optional `raw_ssap` pass-through (`true`/`false`) | `false` |
| `CAPTURE_MAX_WIDTH` | Optional max width (`64..3840`) for host-side JPEG downscaling | Unset (raw passthrough) |
| `CAPTURE_JPEG_QUALITY` | Optional JPEG quality (`1..95`; defaults to `75` if only `CAPTURE_MAX_WIDTH` is set) | Unset (raw passthrough) |
---
## systemd Deployment
@@ -262,9 +297,10 @@ nix flake check
## Documentation
- [Architecture](ARCHITECTURE.md) — Canonical present-state system topology, components, and boundaries
- [Roadmap](ROADMAP.md) — Completed M1/M2 milestones and remaining M2 delivery trajectory
- [Roadmap](ROADMAP.md) — Completed M1/M2 milestones and active M2.1 delivery trajectory
- [Decision Records](docs/adr/) — MADR records for core architectural choices (`0001`–`0005`)
- [Architecture & Design RFC](docs/designs/lg-smtv-mcp.md) — Component contracts, state machine, error taxonomy, and implementation plan
- [E2E Benchmarks](docs/experiments/crunchyroll-e2e-comparison.md) — Standardized live-TV Crunchyroll navigation telemetry (baseline vs. post-`#20`)
- [Verified Capabilities](docs/poc/capabilities.md) — Empirical SSAP, DIAL, deep-link, and Developer Mode findings
- [Crunchyroll E2E Experiment](docs/poc/crunchyroll-e2e-experiment.md) — Initial vision-guided navigation experiment and latency measurements
- [Agent & Engineering Guidelines](AGENTS.md) — Coding standards, validation boundaries, protocol invariants, and CI rules
+8 -2
View File
@@ -2,14 +2,20 @@
## Current Direction
`lg-smtv-mcp` has completed Milestone M2 (capture, E2E hardening, and systemd deployment packaging) and the post-M2 `systemd` unit sandboxing hardening follow-up ([#17](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/issues/17), PR [#18](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/18)). Active work is live-TV operator smoke verification (and downstream Canopy deployment).
`lg-smtv-mcp` has completed Milestone M2 (capture, E2E hardening, and systemd deployment packaging) and `#17` (`systemd` sandboxing hardening). Active work is **Milestone M2.1: Live-TV Polish & Latency Optimizations** (1/4 complete), focused on reducing screenshot payload size/round-trips, fixing immediate `turn_off()` standby transitions, and unblocking `systemd-analyze` checks in the Nix sandbox.
## Near Term
- **Live-TV Operator Smoke Verification:** Execute the manual LAN smoke checklist in [`README.md`](README.md#operator-live-tv-e2e-smoke-test-checklist) and Developer Mode capture verification against the target `WebOS/4.1.0` TV.
- **#21 (`M2.1`):** `fix(manager): transition to STANDBY_OFFLINE immediately on turn_off()` so immediate `tv_wake()` calls do not return `already_connected` before the TV drops `1008`.
- **#22 (`M2.1`):** `fix(test): unblock systemd-analyze tests inside Nix build sandbox` (investigate `--root=<tmp_path>` or narrow sandbox-only skip while keeping `nix develop` enforcement strict).
- **#23 (`M2.1`):** `feat(capture): add optional wait_for_change settle retry on keys/type_text capture` (500ms bounded retry within the shared 6.0s capture budget when `changed_since_last=false`).
## Completed
### M2.1: Live-TV Polish & Latency Optimizations (In Progress — Completed Items)
- **#20 (PR [#24](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/24), Completed 2026-11-19):** Added optional `CAPTURE_MAX_WIDTH` (`64..3840`) and `CAPTURE_JPEG_QUALITY` (`1..95`) settings in [`config.py`](src/lg_smtv_mcp/config.py), added `pillow` runtime dependency, and implemented host-side JPEG downscaling/recompression in [`capture.py`](src/lg_smtv_mcp/tv_core/capture.py) (reducing median live-TV capture size by 69.1% and disk-only offloads from 60% to 7%).
- **Live-TV E2E Benchmarks (`0d67615`, `84ae8b2`, `128752b`):** Executed standardized Crunchyroll E2E navigation benchmarks against `65UR8750PSA` (`WebOS/4.1.0`) and recorded baseline vs. post-`#20` telemetry in [`docs/experiments/`](docs/experiments/).
### Post-M2 Hardening (Completed 2026-11-18)
- **#17 (PR [#18](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/18)):** Hardened [`deploy/lg-smtv-mcp.service`](deploy/lg-smtv-mcp.service) with bounded restart throttling (`StartLimitIntervalSec=60s`, `StartLimitBurst=5`) and a 14-directive sandboxing baseline (`9.0 UNSAFE` → `4.9 OK`), added automated `systemd-analyze` tests in [`tests/test_deploy.py`](tests/test_deploy.py), documented adopted/rejected directives in [`README.md`](README.md#sandboxing--security-profile), and fixed `asyncssh` SFTP capture reads (`sftp.open()`) in [`src/lg_smtv_mcp/tv_core/capture.py`](src/lg_smtv_mcp/tv_core/capture.py).
+3 -3
View File
@@ -3,7 +3,7 @@
* **Author:** kiskaadee
* **Status:** Approved
* **Date:** 2026-11-15
* **Last reconciled:** 2026-11-17 (M2 fully delivered: `#13` / PR [#16](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/16) merged; Milestone M2 closed)
* **Last reconciled:** 2026-11-21 (M2.1 `#20` / PR [#24](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/24) merged on `main`)
--------------------------------------------------------------------------------
@@ -77,12 +77,12 @@ All runtime code lives under `src/lg_smtv_mcp/`, separating the transport/protoc
| Module | Responsibility |
| :--- | :--- |
| [`src/lg_smtv_mcp/config.py`](../../src/lg_smtv_mcp/config.py) | Frozen Pydantic v2 `TvConfig` (`extra="forbid"`) loaded from env vars / `.env` (`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`), raising `ConfigError` on invalid operator config. |
| [`src/lg_smtv_mcp/config.py`](../../src/lg_smtv_mcp/config.py) | Frozen Pydantic v2 `TvConfig` (`extra="forbid"`) loaded from env vars / `.env` (`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`, `CAPTURE_MAX_WIDTH`, `CAPTURE_JPEG_QUALITY`), raising `ConfigError` on invalid operator config. |
| [`src/lg_smtv_mcp/errors.py`](../../src/lg_smtv_mcp/errors.py) | `ConfigError` for startup/config failures and `TvError(ErrorCode, message)` for runtime TV/tool errors (`TV_OFFLINE_STANDBY`, `PAIRING_REQUIRED`, `SCREENSHOT_UNAVAILABLE`, `LOCK_TIMEOUT`, `WAKE_TIMEOUT`, `COMMAND_FAILED`, `INVALID_ARGUMENT`). |
| [`src/lg_smtv_mcp/tv_core/protocols.py`](../../src/lg_smtv_mcp/tv_core/protocols.py) | Python `Protocol` interfaces (`WebSocketTransport`, `WebSocketConnectFn`, `WebSocketClosedError`, `CaptureTransport`, `FrameCapturer`) and frozen result dataclasses enabling offline contract tests. |
| [`src/lg_smtv_mcp/tv_core/ssap.py`](../../src/lg_smtv_mcp/tv_core/ssap.py) | `SsapClient`: single background reader task routing frames by `msg["id"]` to `asyncio.Future`s and `subscribe` callbacks; `PERMISSIONS` constant; `register` + `1008` detection; WebSocket keepalive and pending-`Future` cleanup on disconnect. |
| [`src/lg_smtv_mcp/tv_core/pointer.py`](../../src/lg_smtv_mcp/tv_core/pointer.py) | `PointerClient`: acquires `getPointerInputSocket`, normalizes/validates keys, sends plain-text `type:button` frames, and automatically re-acquires the socket if dropped. |
| [`src/lg_smtv_mcp/tv_core/capture.py`](../../src/lg_smtv_mcp/tv_core/capture.py) | `CaptureClient` (implementing `FrameCapturer`) and `AsyncSshCaptureTransport` (implementing `CaptureTransport`): calls `executeOneShot` via `ssap_request_fn`, lazily opens/reuses the `asyncssh` SFTP session (`read_and_remove`, `sweep_temp_files`, `close`), excludes the in-flight capture from each session sweep, enforces the shared deadline and shielded cleanup, and tracks `frame_sha256` / `changed_since_last`. |
| [`src/lg_smtv_mcp/tv_core/capture.py`](../../src/lg_smtv_mcp/tv_core/capture.py) | `CaptureClient` (implementing `FrameCapturer`) and `AsyncSshCaptureTransport` (implementing `CaptureTransport`): calls `executeOneShot` via `ssap_request_fn`, lazily opens/reuses the `asyncssh` SFTP session (`read_and_remove`, `sweep_temp_files`, `close`), maps `KeyImportError` to `SCREENSHOT_UNAVAILABLE`, excludes the in-flight capture from each session sweep, enforces the shared deadline and shielded cleanup, optionally downscales/recompresses JPEGs (`max_width`, `jpeg_quality`) via Pillow, and tracks `frame_sha256` / `changed_since_last`. |
| [`src/lg_smtv_mcp/tv_core/manager.py`](../../src/lg_smtv_mcp/tv_core/manager.py) | `TvManager`: single-owner connection loop + state machine, `send_wol` helper, `subscribe` state cache, stepped reconnect backoff, `FrameCapturer` teardown on `STANDBY_OFFLINE`, `.client_key.json` reload on `PAIRING_REQUIRED` backoff/`SIGHUP`, and `ui_lock` (`25s` acquire timeout) serializing UI/capture operations. |
| [`src/lg_smtv_mcp/auth.py`](../../src/lg_smtv_mcp/auth.py) | ASGI Bearer token middleware (`hmac.compare_digest` on `Authorization: Bearer <token>`) wrapping FastMCP's `streamable_http_app()` and `TransportSecuritySettings`. |
| [`src/lg_smtv_mcp/server.py`](../../src/lg_smtv_mcp/server.py) | FastMCP (`MCPServer`) tool definitions, `ImageContent` formatting, partial-success shaping, `max_volume` enforcement, `ENABLE_RAW_SSAP` gating, and ASGI `lifespan` wiring for `TvManager` + `SIGHUP`. |
@@ -0,0 +1,47 @@
# Post-#20 Standardized E2E Benchmark (`main` @ `09618be`)
Post-**#20** benchmark executed using [`e2e-benchmark-template.md`](e2e-benchmark-template.md) by subagent `9d82e846-0c13-4c82-8f8f-2780d34ad173` against `65UR8750PSA` (`WebOS/4.1.0`), compared against [`crunchyroll-e2e-baseline-0d67615.md`](crunchyroll-e2e-baseline-0d67615.md).
## Preconditions
- **Commit / Branch:** `09618be` (`main`, PR `#24`)
- **Server Config:** `CAPTURE_MAX_WIDTH=480`, `CAPTURE_JPEG_QUALITY=55`
- **TV Starting State:** Powered ON at Live TV (`com.webos.app.livetv`), Crunchyroll closed.
- **Timer Boundary:** `T0 = 11:16:18.965`, `T_end = 11:19:06.423` (`-05:00`, excluding initial schema `read_file` setup).
---
## Normalized Scorecard
| Metric | Baseline (`0d67615`, raw `960x540`) | Post-**#20** (`09618be`, `480px`, `q=55`) | Delta |
| :--- | :--- | :--- | :--- |
| **Total Timed Span (`T0 -> T_end`)** | `148.40s` (`13` steps) | `167.46s` (`17` steps) | `+19.06s` *(4 extra steps: Crunchyroll auto-resumed previous show + 1 `ENTER` retry)* |
| **Average Time per Step** | `11.42s / step` | `9.85s / step` | `-1.57s / step` |
| **Total Steps / Captures** | `13` / `10` | `17` / `14` | `+4` / `+4` |
| **Median Capture Size (B)** | `19,045 B` | `5,893 B` | `-69.1%` |
| **Disk-Only Offloads (`read_file` turns)** | `6 / 10` (`60%`) | `1 / 14` (`7%`) | `-53 pp` *(only `10,951 B` splash offloaded; all `<= 8,421 B` stayed inline)* |
| **Wasted / Retry Steps** | `0` | `1` | `+1` *(Step 6 `ENTER` on profile screen)* |
---
## Step-by-Step Telemetry Table
| Step # | `T+elapsed` | Tool + Arguments | Tool Duration | Inline / Offload | `size_bytes` | `changed_since_last` | Observed Screen / Result |
|---:|---:|---|---:|:---:|---:|:---:|---|
| 1 | `~8s` | `get_state()` | ~2s | N | — | — | `connected: true`, `foreground_app: com.webos.app.livetv` |
| 2 | `~11s` | `list_apps()` | ~5s | N | — | — | Found `com.crunchyroll.webapp` ("Crunchyroll") |
| 3 | `~19s` | `launch(app_id="com.crunchyroll.webapp")` | ~4s | N | — | — | `returnValue: true` |
| 4 | `~29s` | `screenshot()` *(+ `read_file`)* | ~4s | Y (disk only) | `10,951 B` | `true` | Crunchyroll splash screen |
| 5 | `~44s` | `screenshot()` | ~3s | Y (inline + disk) | `8,421 B` | `true` | Profile picker (`Andres` focused) |
| 6 | `~53s` | `keys(["ENTER"], settle_ms=1800, capture=True)` | ~4s | Y (inline + disk) | `8,421 B` | `false` | Still on profile picker (`Andres` focused) |
| 7 | `~64s` | `keys(["ENTER"], settle_ms=2000, capture=True)` | ~5s | Y (inline + disk) | `2,782 B` | `true` | Black loading spinner |
| 8 | `~73s` | `screenshot()` | ~4s | Y (inline + disk) | `2,812 B` | `true` | Black loading spinner |
| 9 | `~80s` | `screenshot()` | ~2s | Y (inline + disk) | `3,548 B` | `true` | Black DRM frame (auto-resumed previous show) |
| 10 | `~89s` | `keys(["DOWN"], settle_ms=1000, capture=True)` | ~4s | Y (inline + disk) | `6,454 B` | `true` | Player HUD: `Hello, I am a Witch... E1` |
| 11 | `~98s` | `keys(["BACK"], settle_ms=1500, capture=True)` | ~5s | Y (inline + disk) | `3,118 B` | `true` | Home screen loading with left sidebar |
| 12 | `~105s` | `keys(["LEFT"], settle_ms=800, capture=True)` | ~3s | Y (inline + disk) | `7,469 B` | `true` | Left sidebar open, `Inicio` focused |
| 13 | `~114s` | `keys(["UP", "ENTER"], settle_ms=1000, capture=True)` | ~4s | Y (inline + disk) | `5,499 B` | `true` | Search screen, `Ataque a los Titanes` under `Búsquedas recientes` |
| 14 | `~123s` | `keys(["DOWN", "ENTER"], settle_ms=1500, capture=True)` | ~4s | Y (inline + disk) | `7,545 B` | `true` | Series page `Ataque a los Titanes`, `Continuar E1` focused |
| 15 | `~139s` | `keys(["ENTER"], settle_ms=2000, capture=True)` | ~4s | Y (inline + disk) | `2,809 B` | `true` | Black loading spinner |
| 16 | `~146s` | `screenshot()` | ~2s | Y (inline + disk) | `3,540 B` | `true` | Black DRM frame (`16+` rating overlay) |
| 17 | `~155s` | `keys(["DOWN"], settle_ms=800, capture=True)` | ~4s | Y (inline + disk) | `6,287 B` | `true` | Player HUD: `Ataque a los Titanes` / `E1 - Para ti, en 2000 años -- La caída de Shiganshina, parte 1` (`08:02 / 17:37`) |
+7 -1
View File
@@ -44,7 +44,13 @@ def _recompress_jpeg(
out = BytesIO()
img.save(out, format="JPEG", quality=quality)
return out.getvalue()
except (UnidentifiedImageError, OSError, ValueError, EOFError) as exc:
except (
UnidentifiedImageError,
Image.DecompressionBombError,
OSError,
ValueError,
EOFError,
) as exc:
raise TvError(
ErrorCode.SCREENSHOT_UNAVAILABLE,
f"Failed to process screenshot image: {exc}",
+7 -1
View File
@@ -593,7 +593,13 @@ class TvManager:
async def turn_off(self) -> dict[str, Any]:
"""Power off the TV into standby."""
ssap = self._require_ssap()
return await ssap.request("ssap://system/turnOff", {})
response = await ssap.request("ssap://system/turnOff", {})
if response.get("returnValue") is True:
self.state = ConnectionState.STANDBY_OFFLINE
self._connected_event.clear()
await self._teardown_transports(close_capture=True)
self._on_ssap_disconnect(ErrorCode.TV_OFFLINE_STANDBY)
return response
async def raw_ssap(self, uri: str, payload: dict[str, Any] | None = None) -> dict[str, Any]:
"""Forward a raw SSAP request when enabled by configuration."""
+17
View File
@@ -653,3 +653,20 @@ async def test_capture_client_raises_screenshot_unavailable_on_corrupt_image_byt
await client.capture_frame(ssap_request)
assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE
async def test_capture_client_maps_decompression_bomb_error_to_screenshot_unavailable(
monkeypatch: pytest.MonkeyPatch,
) -> None:
raw = _make_jpeg(32, 32, quality=95)
monkeypatch.setattr(Image, "MAX_IMAGE_PIXELS", 100)
client = CaptureClient(FakeCaptureTransport(image_bytes=raw), max_width=16)
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
_ = (uri, payload)
return {"returnValue": True}
with pytest.raises(TvError) as exc_info:
await client.capture_frame(ssap_request)
assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE
+3 -14
View File
@@ -120,10 +120,7 @@ async def test_e2e_mvp_lifecycle_from_standby_through_clean_shutdown(tmp_path: P
wol_calls: list[tuple[str, str, int]] = []
sent_requests: list[tuple[str, dict[str, Any]]] = []
standby_backoff_entered = asyncio.Event()
turn_off_completed = asyncio.Event()
post_turn_off_standby_entered = asyncio.Event()
pointer_ws = FakeWebSocketTransport()
online_ssap_connections: list[FakeWebSocketTransport] = []
def fake_send_wol(mac: str, broadcast_addr: str, port: int) -> None:
nonlocal tv_awake
@@ -131,9 +128,6 @@ async def test_e2e_mvp_lifecycle_from_standby_through_clean_shutdown(tmp_path: P
tv_awake = True
async def fake_wait_fn(event: asyncio.Event, timeout: float) -> None:
if turn_off_completed.is_set():
post_turn_off_standby_entered.set()
else:
standby_backoff_entered.set()
with suppress(TimeoutError):
await asyncio.wait_for(event.wait(), timeout=timeout)
@@ -145,9 +139,7 @@ async def test_e2e_mvp_lifecycle_from_standby_through_clean_shutdown(tmp_path: P
standby_ws = FakeWebSocketTransport()
standby_ws.push_close(1008, "Try Again Later (EWS)")
return standby_ws
online_ws = _build_online_ssap(tv_ip, sent_requests)
online_ssap_connections.append(online_ws)
return online_ws
return _build_online_ssap(tv_ip, sent_requests)
manager = TvManager(
config,
@@ -282,15 +274,12 @@ async def test_e2e_mvp_lifecycle_from_standby_through_clean_shutdown(tmp_path: P
assert vol_res.is_error is False
assert ("ssap://audio/setVolume", {"volume": 15}) in sent_requests
# 7. turn_off(): sends ssap://system/turnOff.
# 7. turn_off(): sends ssap://system/turnOff and transitions immediately to standby.
off_res = await session.call_tool("turn_off", {})
assert off_res.is_error is False
assert ("ssap://system/turnOff", {}) in sent_requests
turn_off_completed.set()
online_ssap_connections[-1].push_close(1008, "Try Again Later (EWS)")
await asyncio.wait_for(post_turn_off_standby_entered.wait(), timeout=2.0)
# 8. Standby (1008) after turn_off: get_state returns cached stale values.
# 8. Immediate standby after turn_off (no 1008 needed): get_state returns stale cache.
stale_state_res = await session.call_tool("get_state", {})
assert stale_state_res.is_error is False
stale_state_payload = _extract_json_text(stale_state_res.content)
+146
View File
@@ -808,3 +808,149 @@ async def test_manager_raw_ssap_forwards_request_when_enabled(tmp_path: Path) ->
assert resp == {"returnValue": True, "ok": 1}
assert sent_requests == [("ssap://system/getSystemInfo", {"x": 1})]
async def test_manager_turn_off_transitions_immediately_to_standby_and_tears_down_transports(
tmp_path: Path,
) -> None:
sent_requests: list[tuple[str, dict[str, Any]]] = []
ssap_transports: list[FakeWebSocketTransport] = []
pointer_ws = FakeWebSocketTransport()
def on_request(msg: dict[str, Any], ws: FakeWebSocketTransport) -> None:
uri = msg["uri"]
if uri == "ssap://com.webos.service.networkinput/getPointerInputSocket":
_pointer_socket_reply(msg, ws)
return
sent_requests.append((uri, msg["payload"]))
ws.push_json({"type": "response", "id": msg["id"], "payload": {"returnValue": True}})
async def connect_fn(url: str) -> FakeWebSocketTransport:
if url == POINTER_URL:
return pointer_ws
ws = _make_online_transport(on_request=on_request)
ssap_transports.append(ws)
return ws
capturer = _FakeCapturer()
mgr = TvManager(
_make_config(tmp_path),
connect_fn=connect_fn,
capture_client=capturer,
backoff_steps=(10.0,),
)
async with _started(mgr):
await mgr.send_keys(["ENTER"], delay_ms=0)
resp = await mgr.turn_off()
assert resp == {"returnValue": True}
assert mgr.state is ConnectionState.STANDBY_OFFLINE
snapshot = mgr.get_state()
assert snapshot.connected is False
assert snapshot.stale is True
assert snapshot.volume == 22
assert snapshot.muted is False
assert snapshot.sound_output == "tv_speaker"
assert snapshot.foreground_app == "com.webos.app.livetv"
assert ssap_transports[0].closed is True
assert pointer_ws.closed is True
assert capturer.closed_count >= 1
with pytest.raises(TvError) as exc_info:
await mgr.set_volume(10)
assert exc_info.value.code is ErrorCode.TV_OFFLINE_STANDBY
async def test_manager_turn_off_allows_immediate_wake_with_wol_and_reconnection(
tmp_path: Path,
) -> None:
sent_requests: list[tuple[str, dict[str, Any]]] = []
wol_calls: list[tuple[str, str, int]] = []
connect_count = 0
def fake_wol(mac: str, broadcast_addr: str, port: int) -> None:
wol_calls.append((mac, broadcast_addr, port))
async def connect_fn(_url: str) -> FakeWebSocketTransport:
nonlocal connect_count
connect_count += 1
return _recording_transport(sent_requests)
mgr = TvManager(
_make_config(tmp_path),
connect_fn=connect_fn,
wol_fn=fake_wol,
backoff_steps=(10.0,),
wake_poll_interval=0.01,
wake_timeout=2.0,
)
async with _started(mgr):
await mgr.turn_off()
status = await mgr.wake()
assert status.status == "connected"
assert wol_calls == [("00:11:22:33:44:55", "255.255.255.255", 9)]
assert connect_count == 2
assert mgr.state is ConnectionState.CONNECTED
@pytest.mark.parametrize(
("turn_off_payload", "expect_error"),
[
({"returnValue": False}, True),
({}, False),
({"returnValue": None}, False),
],
)
async def test_manager_turn_off_leaves_state_and_transports_untouched_when_return_value_not_true(
tmp_path: Path, turn_off_payload: dict[str, Any], expect_error: bool
) -> None:
sent_requests: list[tuple[str, dict[str, Any]]] = []
ssap_transports: list[FakeWebSocketTransport] = []
pointer_ws = FakeWebSocketTransport()
def on_request(msg: dict[str, Any], ws: FakeWebSocketTransport) -> None:
uri = msg["uri"]
if uri == "ssap://com.webos.service.networkinput/getPointerInputSocket":
_pointer_socket_reply(msg, ws)
return
sent_requests.append((uri, msg["payload"]))
if uri == "ssap://system/turnOff":
ws.push_json({"type": "response", "id": msg["id"], "payload": turn_off_payload})
return
ws.push_json({"type": "response", "id": msg["id"], "payload": {"returnValue": True}})
async def connect_fn(url: str) -> FakeWebSocketTransport:
if url == POINTER_URL:
return pointer_ws
ws = _make_online_transport(on_request=on_request)
ssap_transports.append(ws)
return ws
capturer = _FakeCapturer()
mgr = TvManager(
_make_config(tmp_path),
connect_fn=connect_fn,
capture_client=capturer,
backoff_steps=(10.0,),
)
async with _started(mgr):
await mgr.send_keys(["ENTER"], delay_ms=0)
if expect_error:
with pytest.raises(TvError) as exc_info:
await mgr.turn_off()
assert exc_info.value.code is ErrorCode.COMMAND_FAILED
else:
resp = await mgr.turn_off()
assert resp == turn_off_payload
assert mgr.state is ConnectionState.CONNECTED
snapshot = mgr.get_state()
assert snapshot.connected is True
assert snapshot.stale is False
assert ssap_transports[0].closed is False
assert pointer_ws.closed is False
assert capturer.closed_count == 0
await mgr.set_volume(10)
assert ("ssap://audio/setVolume", {"volume": 10}) in sent_requests
+22 -66
View File
@@ -460,17 +460,17 @@ async def test_server_http_app_allows_authenticated_mcp_initialize_request(
await asyncio.wait_for(lifespan_task, timeout=2.0)
async def test_server_create_mcp_server_wires_default_capture_client(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
def _wire_capture_client_with_fake_ssh(
monkeypatch: pytest.MonkeyPatch,
config: TvConfig,
) -> tuple[dict[str, Any], dict[str, bytes], list[str], list[dict[str, Any]], list[Any]]:
import lg_smtv_mcp.server as server_mod
from lg_smtv_mcp.tv_core.capture import CaptureClient
config = _make_config(tmp_path)
captured: dict[str, Any] = {}
remote_files: dict[str, bytes] = {}
removed_paths: list[str] = []
connect_calls: list[dict[str, Any]] = []
sftp_sessions: list[Any] = []
class DummyManager:
async def start(self) -> None:
@@ -488,6 +488,8 @@ async def test_server_create_mcp_server_wires_default_capture_client(
return []
def open(self, path: str, mode: str = "r") -> Any:
_ = mode
class FakeFile:
async def __aenter__(self) -> FakeFile:
return self
@@ -507,8 +509,6 @@ async def test_server_create_mcp_server_wires_default_capture_client(
async def exit(self) -> None:
self.closed = True
sftp_sessions: list[FakeSftp] = []
class FakeSshConnection:
async def start_sftp_client(self) -> FakeSftp:
sftp = FakeSftp()
@@ -533,6 +533,18 @@ async def test_server_create_mcp_server_wires_default_capture_client(
monkeypatch.setattr(server_mod, "TvManager", fake_tv_manager)
monkeypatch.setattr(asyncssh, "connect", fake_connect)
server_mod.create_mcp_server(config)
return captured, remote_files, removed_paths, connect_calls, sftp_sessions
async def test_server_create_mcp_server_wires_default_capture_client(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
from lg_smtv_mcp.tv_core.capture import CaptureClient
config = _make_config(tmp_path)
captured, remote_files, removed_paths, connect_calls, sftp_sessions = (
_wire_capture_client_with_fake_ssh(monkeypatch, config)
)
assert captured["config"] is config
assert "capture_client" in captured["kwargs"]
@@ -565,7 +577,6 @@ async def test_server_create_mcp_server_wires_capture_downscaling_config(
from PIL import Image
import lg_smtv_mcp.server as server_mod
from lg_smtv_mcp.tv_core.capture import CaptureClient
config = TvConfig(
@@ -574,64 +585,9 @@ async def test_server_create_mcp_server_wires_capture_downscaling_config(
capture_max_width=640,
capture_jpeg_quality=60,
)
captured: dict[str, Any] = {}
remote_files: dict[str, bytes] = {}
class DummyManager:
async def start(self) -> None:
return None
async def close(self) -> None:
return None
class FakeSftp:
async def listdir(self, path: str) -> list[str]:
_ = path
return []
def open(self, path: str, mode: str = "r") -> Any:
_ = mode
class FakeFile:
async def __aenter__(self) -> FakeFile:
return self
async def __aexit__(self, *_exc: object) -> None:
return None
async def read(self) -> bytes:
return remote_files[path]
return FakeFile()
async def remove(self, path: str) -> None:
remote_files.pop(path, None)
async def exit(self) -> None:
return None
class FakeSshConnection:
async def start_sftp_client(self) -> FakeSftp:
return FakeSftp()
def close(self) -> None:
return None
async def wait_closed(self) -> None:
return None
def fake_tv_manager(cfg: Any, **kwargs: Any) -> DummyManager:
captured["config"] = cfg
captured["kwargs"] = kwargs
return DummyManager()
async def fake_connect(**kwargs: Any) -> FakeSshConnection:
_ = kwargs
return FakeSshConnection()
monkeypatch.setattr(server_mod, "TvManager", fake_tv_manager)
monkeypatch.setattr(asyncssh, "connect", fake_connect)
server_mod.create_mcp_server(config)
captured, remote_files, _removed_paths, _connect_calls, _sftp_sessions = (
_wire_capture_client_with_fake_ssh(monkeypatch, config)
)
capture_client = captured["kwargs"]["capture_client"]
assert isinstance(capture_client, CaptureClient)