Compare commits
6
Commits
96068cacf2
...
3aa198a787
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3aa198a787 | ||
|
|
80dc58ea4a | ||
|
|
b41a721086 | ||
|
|
c7e261880a | ||
|
|
61d231523e | ||
|
|
260a792e0b |
No files matched your search
+8
-5
@@ -1,6 +1,6 @@
|
|||||||
# Architecture
|
# 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).
|
`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).
|
||||||
|
|
||||||
## System Overview
|
## System Overview
|
||||||
|
|
||||||
@@ -14,7 +14,8 @@ flowchart LR
|
|||||||
Manager --> SSAP["SsapClient (wss://:3001)"]
|
Manager --> SSAP["SsapClient (wss://:3001)"]
|
||||||
Manager --> Pointer["PointerClient (pointer socket)"]
|
Manager --> Pointer["PointerClient (pointer socket)"]
|
||||||
Manager --> WoL["send_wol (UDP :9)"]
|
Manager --> WoL["send_wol (UDP :9)"]
|
||||||
Manager -.->|"Optional Protocol Seam (None in M1)"| Capturer["FrameCapturer (protocols.py)"]
|
Manager --> Capturer["CaptureClient (tv_core/capture.py)"]
|
||||||
|
Capturer --> Transport["AsyncSshCaptureTransport (asyncssh/SFTP :9922)"]
|
||||||
```
|
```
|
||||||
|
|
||||||
## Architectural Principles
|
## Architectural Principles
|
||||||
@@ -23,7 +24,7 @@ flowchart LR
|
|||||||
- **Boundary validation vs. internal state:** Operator inputs and environment config are validated at startup via frozen Pydantic v2 [`TvConfig`](src/lg_smtv_mcp/config.py) (`extra="forbid"`), raising [`ConfigError`](src/lg_smtv_mcp/errors.py). Runtime TV and protocol failures raise [`TvError(ErrorCode, message)`](src/lg_smtv_mcp/errors.py), mapped to FastMCP `ToolError`.
|
- **Boundary validation vs. internal state:** Operator inputs and environment config are validated at startup via frozen Pydantic v2 [`TvConfig`](src/lg_smtv_mcp/config.py) (`extra="forbid"`), raising [`ConfigError`](src/lg_smtv_mcp/errors.py). Runtime TV and protocol failures raise [`TvError(ErrorCode, message)`](src/lg_smtv_mcp/errors.py), mapped to FastMCP `ToolError`.
|
||||||
- **Fail-fast standby (`1008`):** WebSocket close code `1008` transitions [`TvManager`](src/lg_smtv_mcp/tv_core/manager.py) to `STANDBY_OFFLINE`. Mutating tools fail fast with `TV_OFFLINE_STANDBY` without implicitly sending Wake-on-LAN; read-only `get_state` bypasses `ui_lock` and returns cached fields with `connected: false, stale: true`.
|
- **Fail-fast standby (`1008`):** WebSocket close code `1008` transitions [`TvManager`](src/lg_smtv_mcp/tv_core/manager.py) to `STANDBY_OFFLINE`. Mutating tools fail fast with `TV_OFFLINE_STANDBY` without implicitly sending Wake-on-LAN; read-only `get_state` bypasses `ui_lock` and returns cached fields with `connected: false, stale: true`.
|
||||||
- **Single-owner connection loop:** One background loop owns `wss://<TV_IP>:3001` transitions (`CONNECTING`, `CONNECTED`, `STANDBY_OFFLINE`, `WAKING`, `PAIRING_REQUIRED`), preventing races between stepped reconnect backoff (`2s -> 5s -> 15s -> 30s`) and coalesced `wake()` calls (`45s` `WAKE_TIMEOUT`).
|
- **Single-owner connection loop:** One background loop owns `wss://<TV_IP>:3001` transitions (`CONNECTING`, `CONNECTED`, `STANDBY_OFFLINE`, `WAKING`, `PAIRING_REQUIRED`), preventing races between stepped reconnect backoff (`2s -> 5s -> 15s -> 30s`) and coalesced `wake()` calls (`45s` `WAKE_TIMEOUT`).
|
||||||
- **Protocol-injected testability:** External I/O boundaries (`WebSocketConnectFn`, `WebSocketTransport`, `FrameCapturer`, `wol_fn`, `wait_fn`) are injected into `tv_core` so all automated tests run offline without touching physical hardware.
|
- **Protocol-injected testability:** External I/O boundaries (`WebSocketConnectFn`, `WebSocketTransport`, `CaptureTransport`, `FrameCapturer`, `wol_fn`, `wait_fn`) are injected into `tv_core` so all automated tests run offline without touching physical hardware.
|
||||||
|
|
||||||
## Components & Responsibilities
|
## Components & Responsibilities
|
||||||
|
|
||||||
@@ -34,6 +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. |
|
| 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. |
|
| 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. |
|
| 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. |
|
||||||
| 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. |
|
| 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. |
|
| 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`). |
|
| 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`). |
|
||||||
@@ -42,13 +44,13 @@ 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.
|
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`).
|
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`). When `capture=True` is passed without a configured `FrameCapturer` (M1 state), `send_keys` and `type_text` return partial success with `capture_error="SCREENSHOT_UNAVAILABLE: ..."`.
|
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.
|
||||||
4. **Shutdown:** ASGI `lifespan` exit removes the `SIGHUP` handler and awaits `TvManager.close()`, tearing down background tasks and open transports cleanly.
|
4. **Shutdown:** ASGI `lifespan` exit removes the `SIGHUP` handler and awaits `TvManager.close()`, tearing down background tasks and open transports cleanly.
|
||||||
|
|
||||||
## Boundaries
|
## Boundaries
|
||||||
|
|
||||||
- **Network & Auth:** HTTP requests pass through `TransportSecuritySettings` (DNS-rebinding allowlist from `HOST`/`PORT`/`ALLOWED_HOSTS`) and `BearerAuthMiddleware` (`401` on missing/invalid token).
|
- **Network & Auth:** HTTP requests pass through `TransportSecuritySettings` (DNS-rebinding allowlist from `HOST`/`PORT`/`ALLOWED_HOSTS`) and `BearerAuthMiddleware` (`401` on missing/invalid token).
|
||||||
- **Device Boundary:** SSAP (`wss://<TV_IP>:3001`, `ssl.CERT_NONE`), pointer socket (`ws://` / `wss://` returned by `getPointerInputSocket`), and WoL (`UDP` broadcast to `WOL_BROADCAST:9`).
|
- **Device Boundary:** SSAP (`wss://<TV_IP>:3001`, `ssl.CERT_NONE`), pointer socket (`ws://` / `wss://` returned by `getPointerInputSocket`), WoL (`UDP` broadcast to `WOL_BROADCAST:9`), and Developer Mode SSH/SFTP (`prisoner@<TV_IP>:9922` with `config=[]` and explicit `ssh-rsa` host-key/signature algorithms). Host-key verification is disabled by default on a trusted LAN (`known_hosts=None`) and can be pinned with `SSH_KNOWN_HOSTS_PATH`.
|
||||||
- **Persistence:** Client pairing keys are stored as `{ip: client_key}` JSON at `CLIENT_KEY_PATH` (written atomically via `os.replace` with `0600` permissions); optional SSH key retrieval in `pair --fetch-ssh-key` writes with `0600` permissions.
|
- **Persistence:** Client pairing keys are stored as `{ip: client_key}` JSON at `CLIENT_KEY_PATH` (written atomically via `os.replace` with `0600` permissions); optional SSH key retrieval in `pair --fetch-ssh-key` writes with `0600` permissions.
|
||||||
|
|
||||||
## Dependencies
|
## Dependencies
|
||||||
@@ -60,6 +62,7 @@ flowchart LR
|
|||||||
|
|
||||||
- Python `>=3.14` (PEP 649 lazy annotations; `from __future__ import annotations` is banned via Ruff `TID251`).
|
- Python `>=3.14` (PEP 649 lazy annotations; `from __future__ import annotations` is banned via Ruff `TID251`).
|
||||||
- `pyright` runs in `strict` mode across `src/` and `tests/`.
|
- `pyright` runs in `strict` mode across `src/` and `tests/`.
|
||||||
|
- Screenshot capture shares a `6.0s` deadline over `executeOneShot` + SFTP read, plus a `1.5s` shielded cleanup grace, inside the `25s` `ui_lock` budget.
|
||||||
- All automated tests run offline against injected `Protocol` doubles; physical TV hardware is never contacted during automated runs.
|
- All automated tests run offline against injected `Protocol` doubles; physical TV hardware is never contacted during automated runs.
|
||||||
|
|
||||||
## Decision Log Index
|
## Decision Log Index
|
||||||
|
|||||||
@@ -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.
|
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: Milestone M1 complete (MVP).**
|
> **Status: M2 in progress — capture delivered.**
|
||||||
> 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.
|
> 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. The remaining M2 work is the `systemd` unit and deployment documentation ([#13](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/issues/13)).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -35,14 +35,14 @@ The codebase centers on [`tv_core`](src/lg_smtv_mcp/tv_core/), which owns the TV
|
|||||||
| [`PointerClient`](src/lg_smtv_mcp/tv_core/pointer.py) | Implemented | Ephemeral webOS pointer socket for allowlisted remote button frames and mid-batch reconnect |
|
| [`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 |
|
| [`TvManager`](src/lg_smtv_mcp/tv_core/manager.py) | Implemented | Single-owner connection loop, stepped backoff, `wake()` coalescing, `subscribe` cache, `ui_lock`, control surface |
|
||||||
| [`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 |
|
| [`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 |
|
| Developer Mode Capture ([`capture.py`](src/lg_smtv_mcp/tv_core/capture.py)) | Implemented | `CaptureClient` + `AsyncSshCaptureTransport`: `asyncssh` SFTP screenshot retrieval behind the [`FrameCapturer`](src/lg_smtv_mcp/tv_core/protocols.py) / `CaptureTransport` protocols, with a shared `6s` deadline and `/tmp` sweep |
|
||||||
|
|
||||||
### Communication Channels
|
### Communication Channels
|
||||||
|
|
||||||
- **SSAP (`wss://<TV_IP>:3001`):** JSON-over-WebSocket for device control, app launching, IME text input, external input switching, and `subscribe` state streams (`audio/getStatus`, `getForegroundAppInfo`).
|
- **SSAP (`wss://<TV_IP>:3001`):** JSON-over-WebSocket for device control, app launching, IME text input, external input switching, and `subscribe` state streams (`audio/getStatus`, `getForegroundAppInfo`).
|
||||||
- **Pointer Input Socket (`wss://...`):** Line-oriented socket obtained via SSAP for remote D-pad and navigation button events (`UP`, `DOWN`, `ENTER`, `HOME`, `BACK`, etc.).
|
- **Pointer Input Socket (`wss://...`):** Line-oriented socket obtained via SSAP for remote D-pad and navigation button events (`UP`, `DOWN`, `ENTER`, `HOME`, `BACK`, etc.).
|
||||||
- **Wake-on-LAN (UDP):** Explicit device wake-up via magic packets, separated from normal control requests so standby detection fails fast instead of silently waking the TV.
|
- **Wake-on-LAN (UDP):** Explicit device wake-up via magic packets, separated from normal control requests so standby detection fails fast instead of silently waking the TV.
|
||||||
- **Developer Mode SSH/SFTP (Planned M2):** Optional remote screenshot capture (`FrameCapturer` interface already wired in `TvManager` with graceful partial-success degradation when unavailable).
|
- **Developer Mode SSH/SFTP (`prisoner@<TV_IP>:9922`):** Optional remote screenshot capture over a reusable `asyncssh` session (`CaptureClient` behind the `FrameCapturer` protocol, default-wired in [`server.py`](src/lg_smtv_mcp/server.py)). When Developer Mode SSH is unavailable, `keys`/`type_text` still return partial success with `capture_error`, and `screenshot` fails with `SCREENSHOT_UNAVAILABLE`.
|
||||||
|
|
||||||
### Design Principles
|
### Design Principles
|
||||||
|
|
||||||
@@ -61,7 +61,7 @@ Implementation is tracked on the [Project Pipeline](https://gitea.roadtotech.me/
|
|||||||
| Milestone | Scope | Status |
|
| Milestone | Scope | Status |
|
||||||
| :--- | :--- | :--- |
|
| :--- | :--- | :--- |
|
||||||
| **M1** | Core config, `tv_core` engine, FastMCP tools, Bearer auth, `pair`/`serve` CLI, E2E verification | Complete (`#1`–`#4` merged on `main`) |
|
| **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 | Planned (`#11`, `#12`, `#13`) |
|
| **M2** | Developer Mode SFTP screenshot capture (`asyncssh`), systemd unit, E2E test hardening | In progress — capture (`#12`) and E2E hardening (`#11`) merged; systemd deployment (`#13`) open |
|
||||||
|
|
||||||
Implemented in [`TvManager`](src/lg_smtv_mcp/tv_core/manager.py) and exposed via [`server.py`](src/lg_smtv_mcp/server.py):
|
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`)
|
- Persistent SSAP multiplexing and `subscribe`-backed state snapshots (`get_state`: `volume`, `muted`, `sound_output`, `foreground_app`)
|
||||||
@@ -75,7 +75,7 @@ Implemented in [`TvManager`](src/lg_smtv_mcp/tv_core/manager.py) and exposed via
|
|||||||
|
|
||||||
- **Runtime:** Python 3.14+ (or Nix with Flakes enabled)
|
- **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)
|
- **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 (M2):** LG Developer Mode enabled for SSH/SFTP screenshot capture
|
- **Optional:** LG Developer Mode enabled for SSH/SFTP screenshot capture
|
||||||
|
|
||||||
Initial protocol exploration and empirical verification were performed against:
|
Initial protocol exploration and empirical verification were performed against:
|
||||||
- **Device:** `65UR8750PSA`
|
- **Device:** `65UR8750PSA`
|
||||||
@@ -165,6 +165,42 @@ MAX_VOLUME=40
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## systemd Deployment
|
||||||
|
|
||||||
|
The repository includes a unit template at [`deploy/lg-smtv-mcp.service`](deploy/lg-smtv-mcp.service). It runs the server from the project checkout so `nix develop` can use the repository flake.
|
||||||
|
|
||||||
|
1. Prepare the host on the same trusted network as the TV. Install Nix with Flakes enabled, clone this repository to a stable directory, copy `.env.example` to `.env`, and set the required TV coordinates and `MCP_BEARER_TOKEN`. Keep `.env` readable by the service user and private (for example, mode `0600`).
|
||||||
|
2. Copy the template into systemd's unit directory, then replace `<User>` with the account that will run the server and `<WorkingDirectory>` with the absolute repository checkout path. Set `EnvironmentFile` to the `.env` file used for that checkout:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo cp deploy/lg-smtv-mcp.service /etc/systemd/system/lg-smtv-mcp.service
|
||||||
|
sudoedit /etc/systemd/system/lg-smtv-mcp.service
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Check where Nix is installed with `command -v nix`. Replace `<NixBinDir>` in the unit's `PATH` with the directory containing that `nix` executable, keeping the standard system binary directories in the value. The unit starts `/usr/bin/env` by its absolute path; `env` then finds `nix` using the service's configured `PATH`.
|
||||||
|
4. Reload systemd and start the service:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo systemctl daemon-reload
|
||||||
|
sudo systemctl enable --now lg-smtv-mcp.service
|
||||||
|
sudo systemctl status lg-smtv-mcp.service
|
||||||
|
sudo journalctl -u lg-smtv-mcp.service
|
||||||
|
```
|
||||||
|
|
||||||
|
The HTTP server binds to `127.0.0.1` by default and requires `MCP_BEARER_TOKEN`. Use a trusted reverse proxy or VPN if clients need remote access.
|
||||||
|
|
||||||
|
### Developer Mode SSH Capture Setup
|
||||||
|
|
||||||
|
Enable Developer Mode and the TV's Key Server in the Developer Mode app. Run pairing from the configured checkout as the same service user so the client key and SSH key are saved where the service can read them:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
lg-smtv-mcp pair --fetch-ssh-key
|
||||||
|
```
|
||||||
|
|
||||||
|
Accept the on-screen pairing prompt. The command fetches the SSH key from the TV and saves it with mode `0600` (default path `.webos_rsa`); set `SSH_KEY_PATH` in `.env` to that path. Developer Mode provides SSH/SFTP on port `9922`. Its on-TV countdown timer eventually expires and disables Developer Mode, so screenshot capture then returns `SCREENSHOT_UNAVAILABLE` until Developer Mode is enabled again. Other SSAP tools remain available.
|
||||||
|
|
||||||
|
On a trusted home LAN, SSH host-key checking is disabled by default because the TV regenerates its SSH host key when Developer Mode is reinitialized. To pin the host key instead, set `SSH_KNOWN_HOSTS_PATH` to a `known_hosts` file and update it after Developer Mode renewals.
|
||||||
|
|
||||||
## Operator Live-TV E2E Smoke Test Checklist
|
## 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`:
|
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`:
|
||||||
@@ -174,6 +210,8 @@ Automated tests run strictly offline. After deploying or updating on a host on t
|
|||||||
- [ ] **`get_state`**: Call `get_state` and confirm `connected: true`, `stale: false`, and live `volume`, `muted`, `sound_output`, and `foreground_app` values.
|
- [ ] **`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.
|
- [ ] **`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.
|
- [ ] **`keys`**: Call `keys` with a small batch (e.g., `["DOWN", "ENTER"]`) and confirm D-pad navigation registers on the TV.
|
||||||
|
- [ ] **`screenshot`**: With Developer Mode active and SSH configured, call `screenshot` and confirm the response includes JPEG image content and capture metadata.
|
||||||
|
- [ ] **`keys(..., capture=True)`**: Send a small key batch with capture enabled; confirm the response reports successful key delivery and includes the screenshot. If the Developer Mode timer has expired, confirm the response reports the capture failure while preserving `keys_sent: true`.
|
||||||
- [ ] **`set_volume`**: Call `set_volume` with a safe level within `MAX_VOLUME` (e.g., `15`) and confirm the TV volume updates.
|
- [ ] **`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`.
|
- [ ] **`turn_off`**: Call `turn_off` and confirm the TV enters standby and subsequent `get_state` reports `connected: false, stale: true`.
|
||||||
|
|
||||||
@@ -203,7 +241,7 @@ nix flake check
|
|||||||
## Documentation
|
## Documentation
|
||||||
|
|
||||||
- [Architecture](ARCHITECTURE.md) — Canonical present-state system topology, components, and boundaries
|
- [Architecture](ARCHITECTURE.md) — Canonical present-state system topology, components, and boundaries
|
||||||
- [Roadmap](ROADMAP.md) — Completed M1 milestones and planned M2 delivery trajectory
|
- [Roadmap](ROADMAP.md) — Completed M1/M2 milestones and remaining M2 delivery trajectory
|
||||||
- [Decision Records](docs/adr/) — MADR records for core architectural choices (`0001`–`0005`)
|
- [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
|
- [Architecture & Design RFC](docs/designs/lg-smtv-mcp.md) — Component contracts, state machine, error taxonomy, and implementation plan
|
||||||
- [Verified Capabilities](docs/poc/capabilities.md) — Empirical SSAP, DIAL, deep-link, and Developer Mode findings
|
- [Verified Capabilities](docs/poc/capabilities.md) — Empirical SSAP, DIAL, deep-link, and Developer Mode findings
|
||||||
|
|||||||
+6
-3
@@ -2,13 +2,12 @@
|
|||||||
|
|
||||||
## Current Direction
|
## Current Direction
|
||||||
|
|
||||||
`lg-smtv-mcp` has completed its M1 MVP control plane (persistent SSAP, pointer input, WoL recovery, FastMCP tools, Bearer auth, `pair`/`serve` CLI, and full-stack offline E2E verification) and is moving into Milestone M2 to add Developer Mode SFTP screenshot capture, deployment packaging, and E2E test hardening.
|
`lg-smtv-mcp` has completed its M1 MVP control plane (persistent SSAP, pointer input, WoL recovery, FastMCP tools, Bearer auth, `pair`/`serve` CLI, and full-stack offline E2E verification) and the M2 capture and E2E-hardening slices. Remaining M2 work is deployment packaging and its `systemd` hardening follow-up.
|
||||||
|
|
||||||
## Near Term (Milestone M2)
|
## Near Term (Milestone M2)
|
||||||
|
|
||||||
- **Developer Mode SFTP Capture ([#12](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/issues/12)):** Implement `tv_core/capture.py` (`CaptureClient` + `AsyncSshCaptureTransport` behind `FrameCapturer` / `CaptureTransport`) with `6s` shared deadline, shielded `finally: sftp.remove()` cleanup, `/tmp/lg_smtv_cap_*.jpg` reconnect sweep, `frame_sha256` / `changed_since_last` tracking, and default `server.py` wiring.
|
|
||||||
- **Systemd Unit & Deployment Docs ([#13](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/issues/13)):** Add `deploy/lg-smtv-mcp.service` template and document systemd + Developer Mode SSH setup in `README.md`.
|
- **Systemd Unit & Deployment Docs ([#13](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/issues/13)):** Add `deploy/lg-smtv-mcp.service` template and document systemd + Developer Mode SSH setup in `README.md`.
|
||||||
- **E2E Harness & Standby Parity Hardening ([#11](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/issues/11)):** Address PR `#10` review follow-ups in [`tests/test_e2e_mvp.py`](tests/test_e2e_mvp.py) (`_build_online_ssap` extraction, fast-fail ASGI lifespan startup errors, `elapsed_ms` contract check, and post-`turn_off()` `1008` -> `get_state` stale verification).
|
- **Systemd Unit Sandboxing Hardening ([#17](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/issues/17)):** Follow-up to `#13`, tightening the unit's sandboxing directives once the baseline deployment template lands.
|
||||||
|
|
||||||
## Medium Term
|
## Medium Term
|
||||||
|
|
||||||
@@ -16,6 +15,10 @@
|
|||||||
|
|
||||||
## Completed
|
## Completed
|
||||||
|
|
||||||
|
### M2: Capture & E2E Hardening (partial, 2026-11-16)
|
||||||
|
- **#11 (PR [#14](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/14)):** E2E harness hardening in [`tests/test_e2e_mvp.py`](tests/test_e2e_mvp.py) — fast-fail ASGI lifespan startup, `elapsed_ms` contract check, and post-`turn_off()` `1008` -> `get_state` stale parity.
|
||||||
|
- **#12 (PR [#15](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/15)):** `tv_core/capture.py` (`CaptureClient` + `AsyncSshCaptureTransport`), default `server.py` wiring, and offline capture contract tests; review remediation CR-01..CR-11 landed in `61d2315`.
|
||||||
|
|
||||||
### M1: MVP Core & End-to-End Verification (Completed 2026-11-16)
|
### M1: MVP Core & End-to-End Verification (Completed 2026-11-16)
|
||||||
- **#1 (PR [#6](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/6)):** Nix flake packaging, `pyproject.toml`, Pydantic v2 `TvConfig`, and `ConfigError` / `TvError` taxonomy.
|
- **#1 (PR [#6](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/6)):** Nix flake packaging, `pyproject.toml`, Pydantic v2 `TvConfig`, and `ConfigError` / `TvError` taxonomy.
|
||||||
- **#2 (PR [#7](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/7)):** `tv_core` (`SsapClient` multiplexer, `PointerClient`, `TvManager` state machine, `FrameCapturer` seam).
|
- **#2 (PR [#7](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/7)):** `tv_core` (`SsapClient` multiplexer, `PointerClient`, `TvManager` state machine, `FrameCapturer` seam).
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=LG webOS Smart TV MCP server
|
||||||
|
Wants=network-online.target
|
||||||
|
After=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
User=<User>
|
||||||
|
WorkingDirectory=<WorkingDirectory>
|
||||||
|
EnvironmentFile=<WorkingDirectory>/.env
|
||||||
|
Environment="PATH=<NixBinDir>:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
|
||||||
|
ExecStart=/usr/bin/env nix develop --command python -m lg_smtv_mcp serve
|
||||||
|
Restart=on-failure
|
||||||
|
RestartSec=5s
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
# ADR-0003: Asyncssh Protocol Boundary for Dev Mode Capture
|
# ADR-0003: Asyncssh Protocol Boundary for Dev Mode Capture
|
||||||
|
|
||||||
- Status: Accepted (Protocol seams `CaptureTransport` / `FrameCapturer` implemented in M1; `CaptureClient` / `AsyncSshCaptureTransport` planned for M2 `#12`)
|
- Status: Accepted (implemented in M2 `#12` / PR [#15](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/15))
|
||||||
- Date: 2026-11-15
|
- Date: 2026-11-15
|
||||||
- Deciders: kiskaadee
|
- Deciders: kiskaadee
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# ADR-0004: Sequenced Temp Captures with Cleanup and Sweep
|
# ADR-0004: Sequenced Temp Captures with Cleanup and Sweep
|
||||||
|
|
||||||
- Status: Accepted (Implementation planned in M2 `#12`)
|
- Status: Accepted (implemented in M2 `#12` / PR [#15](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/15); amended 2026-11-16)
|
||||||
- Date: 2026-11-15
|
- Date: 2026-11-15
|
||||||
- Deciders: kiskaadee
|
- Deciders: kiskaadee
|
||||||
|
|
||||||
@@ -17,5 +17,9 @@ Chosen option: "Capture to `/tmp/lg_smtv_cap_<seq>.jpg`, pull bytes into memory
|
|||||||
## Alternatives Considered
|
## Alternatives Considered
|
||||||
- Fixed `/tmp/test.jpg` overwrite path: Rejected because if `executeOneShot` fails silently or races, SFTP pull can read a stale screenshot from an earlier step.
|
- Fixed `/tmp/test.jpg` overwrite path: Rejected because if `executeOneShot` fails silently or races, SFTP pull can read a stale screenshot from an earlier step.
|
||||||
|
|
||||||
|
## Amendment (2026-11-16)
|
||||||
|
|
||||||
|
PR [#15](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/15) review (CR-01) found that sweeping unconditionally on a new SFTP session deletes the screenshot `executeOneShot` has just written, because the transport connects lazily **after** the capture request. The decision above stands, with one refinement: `sweep_temp_files` accepts `exclude: str | None`, and `_ensure_sftp` passes the in-flight `remote_path`, so a session sweep removes only stale captures left by earlier sessions or crashes. Guarded by `test_async_ssh_capture_transport_sweep_preserves_in_flight_remote_path`.
|
||||||
|
|
||||||
## Related Decisions
|
## Related Decisions
|
||||||
- Documented in [docs/designs/lg-smtv-mcp.md](../designs/lg-smtv-mcp.md) (Alternative D) and [ADR-0003](0003-asyncssh-protocol-boundary-for-dev-mode-capture.md).
|
- Documented in [docs/designs/lg-smtv-mcp.md](../designs/lg-smtv-mcp.md) (Alternative D) and [ADR-0003](0003-asyncssh-protocol-boundary-for-dev-mode-capture.md).
|
||||||
+61
-50
@@ -3,12 +3,13 @@
|
|||||||
* **Author:** kiskaadee
|
* **Author:** kiskaadee
|
||||||
* **Status:** Approved
|
* **Status:** Approved
|
||||||
* **Date:** 2026-11-15
|
* **Date:** 2026-11-15
|
||||||
|
* **Last reconciled:** 2026-11-16 (M2 `#12` / PR [#15](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/15) merged)
|
||||||
|
|
||||||
--------------------------------------------------------------------------------
|
--------------------------------------------------------------------------------
|
||||||
|
|
||||||
## Overview
|
## Overview
|
||||||
|
|
||||||
`lg-smtv-mcp` is a Python Model Context Protocol (MCP) server for local-network control of a single pre-paired LG webOS Smart TV. It runs primarily as a long-lived `streamable-http` daemon on a homelab server on the same LAN (with `stdio` supported for local testing), keeping the Simple Service Access Protocol (`SSAP`, LG webOS's local JSON-over-WebSocket control protocol on `wss://<TV_IP>:3001`), pointer input socket, and `subscribe` state cache warm, and lazily opening a reusable [LG Developer Mode](https://webostv.developer.lge.com/develop/getting-started/developer-mode-app) `asyncssh`/SFTP session (`prisoner@<TV_IP>:9922`, planned in M2 `#12`) across captures while the TV is awake. The server contains no LLM or vision-model calls: UI navigation loops live in the MCP host (such as Antigravity, Claude, or a closed-set action-router model like `gemini-decision-1`), while `lg-smtv-mcp` exposes bounded, deterministic tools and composite actions (such as batched key sequences with optional inline `ImageContent` screenshots, frame-hash change flags, and gated raw SSAP access).
|
`lg-smtv-mcp` is a Python Model Context Protocol (MCP) server for local-network control of a single pre-paired LG webOS Smart TV. It runs primarily as a long-lived `streamable-http` daemon on a homelab server on the same LAN (with `stdio` supported for local testing), keeping the Simple Service Access Protocol (`SSAP`, LG webOS's local JSON-over-WebSocket control protocol on `wss://<TV_IP>:3001`), pointer input socket, and `subscribe` state cache warm, and lazily opening a reusable [LG Developer Mode](https://webostv.developer.lge.com/develop/getting-started/developer-mode-app) `asyncssh`/SFTP session (`prisoner@<TV_IP>:9922`) across captures while the TV is awake. The server contains no LLM or vision-model calls: UI navigation loops live in the MCP host (such as Antigravity, Claude, or a closed-set action-router model like `gemini-decision-1`), while `lg-smtv-mcp` exposes bounded, deterministic tools and composite actions (such as batched key sequences with optional inline `ImageContent` screenshots, frame-hash change flags, and gated raw SSAP access).
|
||||||
|
|
||||||
## The Problem
|
## The Problem
|
||||||
|
|
||||||
@@ -18,17 +19,17 @@ Controlling an LG webOS TV from an AI agent or automation host using one-shot CL
|
|||||||
2. **Protocol hazards on persistent connections:** Running `subscribe` streams (`audio/getStatus`, `getForegroundAppInfo`) concurrently with tool calls breaks one-shot `ws.recv()` patterns. Additionally, when the TV is in standby, `wss://:3001` accepts the WebSocket upgrade and closes immediately with `1008 (Try Again Later (EWS))`, and `ime/insertText` silently returns `returnValue: true` even when the native keyboard is closed.
|
2. **Protocol hazards on persistent connections:** Running `subscribe` streams (`audio/getStatus`, `getForegroundAppInfo`) concurrently with tool calls breaks one-shot `ws.recv()` patterns. Additionally, when the TV is in standby, `wss://:3001` accepts the WebSocket upgrade and closes immediately with `1008 (Try Again Later (EWS))`, and `ime/insertText` silently returns `returnValue: true` even when the native keyboard is closed.
|
||||||
3. **Redundant host round-trips and `/tmp` accumulation risk:** Without batched key execution, inline image return, and deterministic frame-change detection (`frame_sha256`), the host must issue separate key and capture calls and cannot detect unchanged frames without inspecting image bytes. Without per-call `/tmp` cleanup, repeated screenshot files accumulate in the TV's `/tmp` filesystem (~1.2 GB system RAM).
|
3. **Redundant host round-trips and `/tmp` accumulation risk:** Without batched key execution, inline image return, and deterministic frame-change detection (`frame_sha256`), the host must issue separate key and capture calls and cannot detect unchanged frames without inspecting image bytes. Without per-call `/tmp` cleanup, repeated screenshot files accumulate in the TV's `/tmp` filesystem (~1.2 GB system RAM).
|
||||||
|
|
||||||
`lg-smtv-mcp` addresses this by maintaining persistent, serialized SSAP and pointer connections inside a homelab `streamable-http` daemon (implemented in M1), failing fast on `1008` standby, and designing optional Developer Mode SFTP capture (planned for M2 `#12`) so SSH expiration degrades only screenshot capture while returning compact state and image payloads.
|
`lg-smtv-mcp` addresses this by maintaining persistent, serialized SSAP and pointer connections inside a homelab `streamable-http` daemon (implemented in M1), failing fast on `1008` standby, and implementing optional Developer Mode SFTP capture (M2 `#12`, merged in PR `#15`) so SSH expiration degrades only screenshot capture while returning compact state and image payloads.
|
||||||
|
|
||||||
## Goals
|
## Goals
|
||||||
|
|
||||||
* Run a continuous `streamable-http` MCP daemon bound to a configurable `HOST` address (defaulting to `127.0.0.1` locally, or a trusted homelab LAN interface when deployed) with `Authorization: Bearer <token>` verification via `hmac.compare_digest`, plus `stdio` transport for local test harnesses.
|
* Run a continuous `streamable-http` MCP daemon bound to a configurable `HOST` address (defaulting to `127.0.0.1` locally, or a trusted homelab LAN interface when deployed) with `Authorization: Bearer <token>` verification via `hmac.compare_digest`, plus `stdio` transport for local test harnesses.
|
||||||
* Maintain persistent SSAP (`wss://:3001`), pointer input socket, and `subscribe` state cache connections inside `tv_core`, plus an on-demand `asyncssh`/SFTP (`:9922`) session (planned in M2 `#12`) that stays open across captures while the TV is online and closes on standby.
|
* Maintain persistent SSAP (`wss://:3001`), pointer input socket, and `subscribe` state cache connections inside `tv_core`, plus an on-demand `asyncssh`/SFTP (`:9922`) session that stays open across captures while the TV is online and closes on standby.
|
||||||
* Serialize stateful UI and capture operations (`keys`, `type_text`, `screenshot`) with bounded contention while keeping read-only state queries non-blocking.
|
* Serialize stateful UI and capture operations (`keys`, `type_text`, `screenshot`) with bounded contention while keeping read-only state queries non-blocking.
|
||||||
* Fail fast on WebSocket close code `1008` (`TV_OFFLINE_STANDBY`) for mutating tools, return cached flat fields with `connected: false, stale: true` for read-only queries, and provide an explicit `tv_wake` tool using configurable Wake-on-LAN broadcast.
|
* Fail fast on WebSocket close code `1008` (`TV_OFFLINE_STANDBY`) for mutating tools, return cached flat fields with `connected: false, stale: true` for read-only queries, and provide an explicit `tv_wake` tool using configurable Wake-on-LAN broadcast.
|
||||||
* Expose bounded composite tools (`keys` with allowlisted buttons, delays, and optional inline `ImageContent`; `type_text`; `launch` with deep-link helpers; `screenshot` with `frame_sha256` and `changed_since_last`; `set_volume` with configurable `max_volume=40` cap; explicit `turn_off` / `switch_input`; and opt-in `ENABLE_RAW_SSAP=true`).
|
* Expose bounded composite tools (`keys` with allowlisted buttons, delays, and optional inline `ImageContent`; `type_text`; `launch` with deep-link helpers; `screenshot` with `frame_sha256` and `changed_since_last`; `set_volume` with configurable `max_volume=40` cap; explicit `turn_off` / `switch_input`; and opt-in `ENABLE_RAW_SSAP=true`).
|
||||||
* Provide a one-time CLI `pair` command for interactive on-screen `PROMPT` registration, `client-key` persistence, and optional `--fetch-ssh-key` Developer Mode key retrieval.
|
* Provide a one-time CLI `pair` command for interactive on-screen `PROMPT` registration, `client-key` persistence, and optional `--fetch-ssh-key` Developer Mode key retrieval.
|
||||||
* Verify M1 and planned M2 behavior offline via `pytest` contract tests over `Protocol` mocks, passing `ruff` and `pyright` inside `nix develop`.
|
* Verify M1 and M2 behavior offline via `pytest` contract tests over `Protocol` mocks, passing `ruff` and `pyright` inside `nix develop`.
|
||||||
|
|
||||||
## Non-Goals
|
## Non-Goals
|
||||||
|
|
||||||
@@ -81,7 +82,7 @@ All runtime code lives under `src/lg_smtv_mcp/`, separating the transport/protoc
|
|||||||
| [`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/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/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/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` *(planned, M2 `#12`)* | `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`), 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`), 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/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/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/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`. |
|
| [`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`. |
|
||||||
@@ -133,7 +134,7 @@ classDiagram
|
|||||||
class CaptureTransport {
|
class CaptureTransport {
|
||||||
<<interface>>
|
<<interface>>
|
||||||
+read_and_remove(remote_path, timeout, cleanup_grace) bytes
|
+read_and_remove(remote_path, timeout, cleanup_grace) bytes
|
||||||
+sweep_temp_files(prefix) void
|
+sweep_temp_files(prefix, exclude) void
|
||||||
+close() void
|
+close() void
|
||||||
}
|
}
|
||||||
TvManager --> SsapClient
|
TvManager --> SsapClient
|
||||||
@@ -151,9 +152,9 @@ classDiagram
|
|||||||
| `SsapClient` | `async connect_and_register(client_key: str \| None) -> str`, `async request(uri: str, payload: dict \| None) -> dict`, `async subscribe(uri: str, callback: Callable[[dict], None]) -> None`, `async close() -> None` |
|
| `SsapClient` | `async connect_and_register(client_key: str \| None) -> str`, `async request(uri: str, payload: dict \| None) -> dict`, `async subscribe(uri: str, callback: Callable[[dict], None]) -> None`, `async close() -> None` |
|
||||||
| `PointerClient` | `async send_buttons(keys: list[str], delay_ms: int) -> int`, `async close() -> None` |
|
| `PointerClient` | `async send_buttons(keys: list[str], delay_ms: int) -> int`, `async close() -> None` |
|
||||||
| `FrameCapturer` | `async capture_frame(ssap_request_fn: Callable[[str, dict], Awaitable[dict]]) -> CaptureResult`, `async close() -> None` |
|
| `FrameCapturer` | `async capture_frame(ssap_request_fn: Callable[[str, dict], Awaitable[dict]]) -> CaptureResult`, `async close() -> None` |
|
||||||
| `CaptureClient` | `__init__(transport: CaptureTransport)`, implements `FrameCapturer` *(planned, M2 `#12`)* |
|
| `CaptureClient` | `__init__(transport: CaptureTransport)`, implements `FrameCapturer` |
|
||||||
| `WebSocketTransport` | `async send(data: str) -> None`, `async recv() -> str`, `async close() -> None` (raises `WebSocketClosedError(code, reason)` on close); `WebSocketConnectFn = Callable[[str], Awaitable[WebSocketTransport]]` |
|
| `WebSocketTransport` | `async send(data: str) -> None`, `async recv() -> str`, `async close() -> None` (raises `WebSocketClosedError(code, reason)` on close); `WebSocketConnectFn = Callable[[str], Awaitable[WebSocketTransport]]` |
|
||||||
| `CaptureTransport` | `async read_and_remove(remote_path: str, timeout: float, cleanup_grace: float) -> bytes`, `async sweep_temp_files(prefix: str) -> None`, `async close() -> None`; implemented by `AsyncSshCaptureTransport(config: TvConfig, connect_fn: ...)` *(planned, M2 `#12`)* |
|
| `CaptureTransport` | `async read_and_remove(remote_path: str, timeout: float, cleanup_grace: float) -> bytes`, `async sweep_temp_files(prefix: str, exclude: str \| None = None) -> None`, `async close() -> None`; implemented by `AsyncSshCaptureTransport(config: TvConfig, connect_fn: ...)` |
|
||||||
|
|
||||||
### 2. Connection State Machine, Frame Dispatch & Concurrency
|
### 2. Connection State Machine, Frame Dispatch & Concurrency
|
||||||
|
|
||||||
@@ -176,7 +177,7 @@ stateDiagram-v2
|
|||||||
* **SSAP `msg["id"]` Multiplexer:** `SsapClient` runs one background `_reader_loop()` task that owns `ws.recv()`. Responses to one-shot `request()` calls resolve matching `asyncio.Future`s by `msg["id"]`. Live-verified `subscribe` streams on `WebOS/4.1.0` (`ssap://audio/getStatus`—where `volume` and `mute` are top-level and `soundOutput` is nested under `payload["volumeStatus"]["soundOutput"]`—and `ssap://com.webos.applicationManager/getForegroundAppInfo`) update the in-memory `TvStateSnapshot` in `TvManager`. Mutating requests push subscription update frames before their own request response frame, which `msg["id"]` routing demultiplexes. On disconnect, `_reader_loop()`'s `finally:` block fails all pending `Future`s with `TV_OFFLINE_STANDBY`.
|
* **SSAP `msg["id"]` Multiplexer:** `SsapClient` runs one background `_reader_loop()` task that owns `ws.recv()`. Responses to one-shot `request()` calls resolve matching `asyncio.Future`s by `msg["id"]`. Live-verified `subscribe` streams on `WebOS/4.1.0` (`ssap://audio/getStatus`—where `volume` and `mute` are top-level and `soundOutput` is nested under `payload["volumeStatus"]["soundOutput"]`—and `ssap://com.webos.applicationManager/getForegroundAppInfo`) update the in-memory `TvStateSnapshot` in `TvManager`. Mutating requests push subscription update frames before their own request response frame, which `msg["id"]` routing demultiplexes. On disconnect, `_reader_loop()`'s `finally:` block fails all pending `Future`s with `TV_OFFLINE_STANDBY`.
|
||||||
* **Standby & Fail-Fast:** WebSocket close code `1008` (`Try Again Later (EWS)`), ping timeout (`ping_interval=10, ping_timeout=5`), or `open_timeout` (`3.0–4.0s`) transitions `TvManager` to `STANDBY_OFFLINE` and tears down any open `CaptureClient` SSH/SFTP session (which reconnects lazily on the next capture). Mutating tools fail fast with `TV_OFFLINE_STANDBY` without triggering WoL. Read-only queries (`get_state`) bypass `ui_lock` and return the flat state dict (`connected: false, stale: true` with cached values retained from the last online update).
|
* **Standby & Fail-Fast:** WebSocket close code `1008` (`Try Again Later (EWS)`), ping timeout (`ping_interval=10, ping_timeout=5`), or `open_timeout` (`3.0–4.0s`) transitions `TvManager` to `STANDBY_OFFLINE` and tears down any open `CaptureClient` SSH/SFTP session (which reconnects lazily on the next capture). Mutating tools fail fast with `TV_OFFLINE_STANDBY` without triggering WoL. Read-only queries (`get_state`) bypass `ui_lock` and return the flat state dict (`connected: false, stale: true` with cached values retained from the last online update).
|
||||||
* **Single-Owner Reconnect, Wake & Key Reload:** A single connection loop owns `wss://:3001` transitions so `tv_wake` and stepped background reconnect (`2s -> 5s -> 15s -> 30s`) never race. Calling `tv_wake` in `STANDBY_OFFLINE` sends the WoL magic packet, signals the connection loop into `WAKING` (`~1s` polling up to a `45s` `WAKE_TIMEOUT` budget, covering `~30–35s` empirical cold standby boot), and awaits a shared connection event. Concurrent `tv_wake` calls in `WAKING` coalesce onto the in-flight attempt; `tv_wake` in `CONNECTED` returns `{status: "already_connected", elapsed_ms: 0}`; `tv_wake` in `PAIRING_REQUIRED` fails fast with `PAIRING_REQUIRED`. In `PAIRING_REQUIRED`, `TvManager` re-checks `CLIENT_KEY_PATH` (`{ip: client_key}` JSON, written atomically via `os.replace` by `cli.py pair`) on its backoff tick or `SIGHUP` (logging and remaining in `PAIRING_REQUIRED` if the file is missing or malformed).
|
* **Single-Owner Reconnect, Wake & Key Reload:** A single connection loop owns `wss://:3001` transitions so `tv_wake` and stepped background reconnect (`2s -> 5s -> 15s -> 30s`) never race. Calling `tv_wake` in `STANDBY_OFFLINE` sends the WoL magic packet, signals the connection loop into `WAKING` (`~1s` polling up to a `45s` `WAKE_TIMEOUT` budget, covering `~30–35s` empirical cold standby boot), and awaits a shared connection event. Concurrent `tv_wake` calls in `WAKING` coalesce onto the in-flight attempt; `tv_wake` in `CONNECTED` returns `{status: "already_connected", elapsed_ms: 0}`; `tv_wake` in `PAIRING_REQUIRED` fails fast with `PAIRING_REQUIRED`. In `PAIRING_REQUIRED`, `TvManager` re-checks `CLIENT_KEY_PATH` (`{ip: client_key}` JSON, written atomically via `os.replace` by `cli.py pair`) on its backoff tick or `SIGHUP` (logging and remaining in `PAIRING_REQUIRED` if the file is missing or malformed).
|
||||||
* **UI/Capture Serialization & Timeout Budget:** `send_keys`, `type_text`, and `screenshot` acquire `ui_lock` (`asyncio.Lock`) with a `25s` acquire timeout (`LOCK_TIMEOUT` if exceeded). `keys` validates key names against a strict webOS button allowlist (`UP`, `DOWN`, `LEFT`, `RIGHT`, `ENTER`, `BACK`, `HOME`, `EXIT`, `PLAY`, `PAUSE`, `STOP`, `REWIND`, `FASTFORWARD`, `RED`, `GREEN`, `YELLOW`, `BLUE`, `VOLUMEUP`, `VOLUMEDOWN`, `MUTE`, `CHANNELUP`, `CHANNELDOWN`, `INFO`, `GUIDE`, `MENU`, `CC`, `0`–`9`), rejecting unknown names or control characters (`\r`, `\n`) with `INVALID_ARGUMENT`, and bounds `1 <= len(keys) <= 20`, `0 <= delay_ms <= 500`, and `0 <= settle_ms <= 2000`. In M2 (`#12`), `CaptureClient.capture_frame()` wraps `executeOneShot` + SFTP read in a shared `6.0s` operation deadline (`asyncio.timeout(6.0)`), while `AsyncSshCaptureTransport.read_and_remove()` shields its `finally: sftp.remove(remote_path)` under a separate `1.5s` cleanup grace (`asyncio.shield` + `asyncio.wait_for(..., timeout=cleanup_grace)`) so outer timeout cancellation cannot abort remote `/tmp` file deletion (`<= 7.5s` worst-case capture phase within the `25s` `ui_lock` budget).
|
* **UI/Capture Serialization & Timeout Budget:** `send_keys`, `type_text`, and `screenshot` acquire `ui_lock` (`asyncio.Lock`) with a `25s` acquire timeout (`LOCK_TIMEOUT` if exceeded). `keys` validates key names against a strict webOS button allowlist (`UP`, `DOWN`, `LEFT`, `RIGHT`, `ENTER`, `BACK`, `HOME`, `EXIT`, `PLAY`, `PAUSE`, `STOP`, `REWIND`, `FASTFORWARD`, `RED`, `GREEN`, `YELLOW`, `BLUE`, `VOLUMEUP`, `VOLUMEDOWN`, `MUTE`, `CHANNELUP`, `CHANNELDOWN`, `INFO`, `GUIDE`, `MENU`, `CC`, `0`–`9`), rejecting unknown names or control characters (`\r`, `\n`) with `INVALID_ARGUMENT`, and bounds `1 <= len(keys) <= 20`, `0 <= delay_ms <= 500`, and `0 <= settle_ms <= 2000`. `CaptureClient.capture_frame()` wraps `executeOneShot` + SFTP read in a shared `6.0s` operation deadline (`asyncio.timeout(6.0)`), while `AsyncSshCaptureTransport.read_and_remove()` enforces its own `timeout` budget and shields its `finally: sftp.remove(remote_path)` under a separate `1.5s` cleanup grace (`asyncio.shield` + `asyncio.wait_for(..., timeout=cleanup_grace)`) so outer timeout cancellation cannot abort remote `/tmp` file deletion (`<= 7.5s` worst-case capture phase within the `25s` `ui_lock` budget). Any new SFTP session runs `sweep_temp_files("/tmp/lg_smtv_cap_", exclude=remote_path)`, so stale captures from earlier sessions or crashes are removed while the frame about to be read survives.
|
||||||
|
|
||||||
### 3. MCP Tool Surface
|
### 3. MCP Tool Surface
|
||||||
|
|
||||||
@@ -202,12 +203,12 @@ All tools return structured JSON payloads (plus inline MCP `ImageContent` when `
|
|||||||
|
|
||||||
* **Network, Transport Security & Trust Policy:** `streamable-http` binds to `HOST` (default `127.0.0.1` for local dev; `<SERVER_IP>` on a trusted home LAN when deployed) and `PORT` (default `8765`). Startup fails closed if `MCP_BEARER_TOKEN` is unset or whitespace-only, and every HTTP request requires `Authorization: Bearer <token>` verified via `hmac.compare_digest`. `TransportSecuritySettings` derives `allowed_hosts` / `allowed_origins` from `HOST`/`PORT`, `127.0.0.1`/`localhost`, and optional `ALLOWED_HOSTS`. Because `uvicorn` serves plain HTTP by default, direct LAN binding assumes a trusted home network segment; if accessed across untrusted networks, operators must place the daemon behind an HTTPS reverse proxy / TLS terminator or an encrypted overlay tunnel (e.g., WireGuard or Tailscale). On the TV link (`wss://<TV_IP>:3001`), `SsapClient` uses `ssl.CERT_NONE` because retail LG webOS TVs present a device-generated self-signed certificate without CA chain provisioning; session authorization relies on the paired `client-key` on the local LAN.
|
* **Network, Transport Security & Trust Policy:** `streamable-http` binds to `HOST` (default `127.0.0.1` for local dev; `<SERVER_IP>` on a trusted home LAN when deployed) and `PORT` (default `8765`). Startup fails closed if `MCP_BEARER_TOKEN` is unset or whitespace-only, and every HTTP request requires `Authorization: Bearer <token>` verified via `hmac.compare_digest`. `TransportSecuritySettings` derives `allowed_hosts` / `allowed_origins` from `HOST`/`PORT`, `127.0.0.1`/`localhost`, and optional `ALLOWED_HOSTS`. Because `uvicorn` serves plain HTTP by default, direct LAN binding assumes a trusted home network segment; if accessed across untrusted networks, operators must place the daemon behind an HTTPS reverse proxy / TLS terminator or an encrypted overlay tunnel (e.g., WireGuard or Tailscale). On the TV link (`wss://<TV_IP>:3001`), `SsapClient` uses `ssl.CERT_NONE` because retail LG webOS TVs present a device-generated self-signed certificate without CA chain provisioning; session authorization relies on the paired `client-key` on the local LAN.
|
||||||
* **ASGI `lifespan` Ownership:** FastMCP (`MCPServer`) / Starlette's ASGI `lifespan` context manager starts `TvManager` on Uvicorn's active event loop, registers `SIGHUP` via `loop.add_signal_handler`, and closes `SsapClient`, `PointerClient`, and `FrameCapturer` on shutdown.
|
* **ASGI `lifespan` Ownership:** FastMCP (`MCPServer`) / Starlette's ASGI `lifespan` context manager starts `TvManager` on Uvicorn's active event loop, registers `SIGHUP` via `loop.add_signal_handler`, and closes `SsapClient`, `PointerClient`, and `FrameCapturer` on shutdown.
|
||||||
* **Developer Mode SSH Lifecycle & Host-Key Trust (`#12`):** Retail LG webOS TVs do not serve `/tmp` screenshots over HTTPS (`:3001`), so `CaptureClient` pulls captures over SFTP from the unprivileged SSH server (`prisoner@<TV_IP>:9922`) provided by LG's official [Developer Mode app](https://webostv.developer.lge.com/develop/getting-started/developer-mode-app) (see [docs/poc/capabilities.md](../poc/capabilities.md)). Port `:9922` is available only while "Dev Mode Status" and "Key Server" are enabled on the TV, and LG automatically disables Developer Mode when its countdown timer expires (at which point `CaptureClient` raises `SCREENSHOT_UNAVAILABLE` while all SSAP and WoL tools continue operating). `AsyncSshCaptureTransport` opens its `asyncssh` SFTP connection lazily on the first capture request, reuses it across subsequent captures while the TV stays online, sweeps stale `/tmp/lg_smtv_cap_*` files on each new SFTP session, and closes the session when `TvManager` transitions to `STANDBY_OFFLINE` or on transport errors. On a headless `systemd` service, `AsyncSshCaptureTransport` connects with `config=[]`, legacy `server_host_key_algs=["ssh-rsa"]`, `signature_algs=["ssh-rsa"]`, and either a key path (`SSH_KEY_PATH`) or `WEBOS_SSH_PASSPHRASE`. Because the TV's Developer Mode container regenerates its SSH host key across Developer Mode renewals, `known_hosts=None` is the default on a trusted home LAN (accepting the LAN peer's host key to prevent unattended daemon breakage); operators requiring strict SSH host authentication can set `SSH_KNOWN_HOSTS_PATH` to pin the TV's host key and update that file whenever Developer Mode is re-initialized. `lg-smtv-mcp pair --fetch-ssh-key` retrieves `http://<TV_IP>:9991/webos_rsa` and saves it with `0600` permissions.
|
* **Developer Mode SSH Lifecycle & Host-Key Trust (`#12`):** Retail LG webOS TVs do not serve `/tmp` screenshots over HTTPS (`:3001`), so `CaptureClient` pulls captures over SFTP from the unprivileged SSH server (`prisoner@<TV_IP>:9922`) provided by LG's official [Developer Mode app](https://webostv.developer.lge.com/develop/getting-started/developer-mode-app) (see [docs/poc/capabilities.md](../poc/capabilities.md)). Port `:9922` is available only while "Dev Mode Status" and "Key Server" are enabled on the TV, and LG automatically disables Developer Mode when its countdown timer expires (at which point `CaptureClient` raises `SCREENSHOT_UNAVAILABLE` while all SSAP and WoL tools continue operating). `AsyncSshCaptureTransport` opens its `asyncssh` SFTP connection lazily on the first capture request, reuses it across subsequent captures while the TV stays online, sweeps stale `/tmp/lg_smtv_cap_*` files on each new SFTP session while excluding the in-flight capture path, and closes the session when `TvManager` transitions to `STANDBY_OFFLINE` or on transport errors. On a headless `systemd` service, `AsyncSshCaptureTransport` connects with `config=[]`, legacy `server_host_key_algs=["ssh-rsa"]`, `signature_algs=["ssh-rsa"]`, and either a key path (`SSH_KEY_PATH`) or `WEBOS_SSH_PASSPHRASE`. Because the TV's Developer Mode container regenerates its SSH host key across Developer Mode renewals, `known_hosts=None` is the default on a trusted home LAN (accepting the LAN peer's host key to prevent unattended daemon breakage); operators requiring strict SSH host authentication can set `SSH_KNOWN_HOSTS_PATH` to pin the TV's host key and update that file whenever Developer Mode is re-initialized. `lg-smtv-mcp pair --fetch-ssh-key` retrieves `http://<TV_IP>:9991/webos_rsa` and saves it with `0600` permissions.
|
||||||
* **WoL Broadcast:** `WOL_BROADCAST` defaults to `255.255.255.255` and can be set to the LAN subnet broadcast (e.g., `<LAN_SUBNET_BROADCAST>`) on multi-homed hosts so magic packets exit on the TV's Ethernet/Wi-Fi segment.
|
* **WoL Broadcast:** `WOL_BROADCAST` defaults to `255.255.255.255` and can be set to the LAN subnet broadcast (e.g., `<LAN_SUBNET_BROADCAST>`) on multi-homed hosts so magic packets exit on the TV's Ethernet/Wi-Fi segment.
|
||||||
|
|
||||||
### 5. Offline Testing & Nix Environment
|
### 5. Offline Testing & Nix Environment
|
||||||
|
|
||||||
* **Offline Contract Tests:** All automated tests run offline against injected `WebSocketTransport`, `CaptureTransport`, and `FrameCapturer` implementations (plus fake `wol_fn` and `wait_fn` callbacks). M1 offline coverage (`tests/test_config.py`, `tests/test_protocols.py`, `tests/test_ssap.py`, `tests/test_pointer.py`, `tests/test_manager.py`, `tests/test_auth.py`, `tests/test_server.py`, `tests/test_cli.py`, `tests/test_e2e_mvp.py`) is implemented and passing on `main`. M2 adds `tests/test_capture.py` (`#12`) and hardens `tests/test_e2e_mvp.py` (`#11`).
|
* **Offline Contract Tests:** All automated tests run offline against injected `WebSocketTransport`, `CaptureTransport`, and `FrameCapturer` implementations (plus fake `wol_fn` and `wait_fn` callbacks). M1 offline coverage (`tests/test_config.py`, `tests/test_protocols.py`, `tests/test_ssap.py`, `tests/test_pointer.py`, `tests/test_manager.py`, `tests/test_auth.py`, `tests/test_server.py`, `tests/test_cli.py`, `tests/test_e2e_mvp.py`) is implemented and passing on `main`. M2 adds `tests/test_capture.py` and hardens `tests/test_e2e_mvp.py`; both are implemented and passing on `main` (PR `#15` and PR `#14`).
|
||||||
* **`flake.nix` Packaging:** Exposes `packages.${system}.default` via `buildPythonApplication` (`pyproject = true`, `setuptools`, single-sourced `runtimeDeps` and `testDeps`, `preCheck` running `ruff check .`, `ruff format --check .`, `pyright`, and `pytestCheckHook`) and `devShells.${system}.default` with `.githooks` pre-commit enforcement.
|
* **`flake.nix` Packaging:** Exposes `packages.${system}.default` via `buildPythonApplication` (`pyproject = true`, `setuptools`, single-sourced `runtimeDeps` and `testDeps`, `preCheck` running `ruff check .`, `ruff format --check .`, `pyright`, and `pytestCheckHook`) and `devShells.${system}.default` with `.githooks` pre-commit enforcement.
|
||||||
|
|
||||||
## Alternatives Considered
|
## Alternatives Considered
|
||||||
@@ -249,7 +250,7 @@ All tools return structured JSON payloads (plus inline MCP `ImageContent` when `
|
|||||||
| Risk | Impact | Mitigation |
|
| Risk | Impact | Mitigation |
|
||||||
| :--- | :--- | :--- |
|
| :--- | :--- | :--- |
|
||||||
| Developer Mode SSH timer expires on TV | Screenshot capture fails (`SCREENSHOT_UNAVAILABLE`) | Degrade only `screenshot` / `capture=True` (returning partial success on `keys` / `type_text`); keep all SSAP and WoL tools active. |
|
| Developer Mode SSH timer expires on TV | Screenshot capture fails (`SCREENSHOT_UNAVAILABLE`) | Degrade only `screenshot` / `capture=True` (returning partial success on `keys` / `type_text`); keep all SSAP and WoL tools active. |
|
||||||
| Orphaned `/tmp/lg_smtv_cap_*.jpg` on SSH stall | Gradual `/tmp` RAM growth on TV (~1.2 GB RAM) | Per-call shielded `finally: sftp.remove()` under `1.5s` grace + sweep of `/tmp/lg_smtv_cap_*.jpg` on SFTP connect/reconnect. |
|
| Orphaned `/tmp/lg_smtv_cap_*.jpg` on SSH stall | Gradual `/tmp` RAM growth on TV (~1.2 GB RAM) | Per-call shielded `finally: sftp.remove()` under `1.5s` grace + sweep of `/tmp/lg_smtv_cap_*.jpg` on SFTP connect/reconnect, excluding the in-flight capture path. |
|
||||||
| Concurrent `tv_wake` / reconnect race or cold wake delay | Duplicate sockets or premature `WAKE_TIMEOUT` | Single-owner connection loop coalescing `tv_wake` + `45s` budget (`~30–35s` empirical cold boot). |
|
| Concurrent `tv_wake` / reconnect race or cold wake delay | Duplicate sockets or premature `WAKE_TIMEOUT` | Single-owner connection loop coalescing `tv_wake` + `45s` budget (`~30–35s` empirical cold boot). |
|
||||||
| Dev Mode host-key regeneration or LAN peer spoofing on `:9922` | Unattended SSH failure on key rotation, or unauthenticated SFTP peer when `known_hosts=None` | Default `known_hosts=None` on trusted home LAN; support `SSH_KNOWN_HOSTS_PATH` for explicit host-key pinning (updated by operator when Developer Mode regenerates keys). |
|
| Dev Mode host-key regeneration or LAN peer spoofing on `:9922` | Unattended SSH failure on key rotation, or unauthenticated SFTP peer when `known_hosts=None` | Default `known_hosts=None` on trusted home LAN; support `SSH_KNOWN_HOSTS_PATH` for explicit host-key pinning (updated by operator when Developer Mode regenerates keys). |
|
||||||
| Plain-HTTP bearer token exposure on untrusted networks | Token interception on non-private network segments | Bind to `127.0.0.1` by default; restrict direct LAN binding to trusted home networks or terminate HTTPS via reverse proxy / WireGuard / Tailscale tunnel. |
|
| Plain-HTTP bearer token exposure on untrusted networks | Token interception on non-private network segments | Bind to `127.0.0.1` by default; restrict direct LAN binding to trusted home networks or terminate HTTPS via reverse proxy / WireGuard / Tailscale tunnel. |
|
||||||
@@ -261,12 +262,12 @@ All tools return structured JSON payloads (plus inline MCP `ImageContent` when `
|
|||||||
## Non-Functional Requirements
|
## Non-Functional Requirements
|
||||||
|
|
||||||
* **Security & Privacy:** `streamable-http` binds to configurable `HOST` (default `127.0.0.1`, or `<SERVER_IP>` on a trusted home LAN; HTTPS reverse proxy or VPN tunnel required across untrusted networks), fails closed if `MCP_BEARER_TOKEN` is unset, enforces `Authorization: Bearer <token>` via `hmac.compare_digest`, and configures MCP `TransportSecuritySettings`. Arbitrary SSH command execution is never exposed. `.client_key.json`, `.env`, SSH keys, and `*.jpg` captures are excluded from version control.
|
* **Security & Privacy:** `streamable-http` binds to configurable `HOST` (default `127.0.0.1`, or `<SERVER_IP>` on a trusted home LAN; HTTPS reverse proxy or VPN tunnel required across untrusted networks), fails closed if `MCP_BEARER_TOKEN` is unset, enforces `Authorization: Bearer <token>` via `hmac.compare_digest`, and configures MCP `TransportSecuritySettings`. Arbitrary SSH command execution is never exposed. `.client_key.json`, `.env`, SSH keys, and `*.jpg` captures are excluded from version control.
|
||||||
* **Performance & Latency:** Persistent SSAP and pointer connections (plus reusable on-demand `asyncssh` SFTP in M2 `#12`) avoid repeating per-step TLS/SSH handshakes (~8–10s/step in the one-shot PoC); batched `keys(..., capture=True)` and `frame_sha256` / `changed_since_last` are designed to let the host skip redundant vision turns.
|
* **Performance & Latency:** Persistent SSAP and pointer connections (plus the reusable on-demand `asyncssh` SFTP session) avoid repeating per-step TLS/SSH handshakes (~8–10s/step in the one-shot PoC); batched `keys(..., capture=True)` and `frame_sha256` / `changed_since_last` are designed to let the host skip redundant vision turns.
|
||||||
* **Operational Resilience:** WebSocket `1008` fails fast (`TV_OFFLINE_STANDBY`), `ui_lock` times out at `25s` with `LOCK_TIMEOUT`, and Developer Mode SSH unavailability degrades only `screenshot` / `capture=True` without disrupting SSAP or WoL tools.
|
* **Operational Resilience:** WebSocket `1008` fails fast (`TV_OFFLINE_STANDBY`), `ui_lock` times out at `25s` with `LOCK_TIMEOUT`, and Developer Mode SSH unavailability degrades only `screenshot` / `capture=True` without disrupting SSAP or WoL tools.
|
||||||
|
|
||||||
## Detailed Implementation Plan
|
## Detailed Implementation Plan
|
||||||
|
|
||||||
Milestone M1 foundations (`#1`–`#4`) are implemented, verified, and merged on `main`. The active implementation plan below summarizes the completed M1 baseline for reference and specifies the exact contracts and file actions for the remaining Milestone M2 slices (`#12`, `#13`, `#11`).
|
Milestone M1 foundations (`#1`–`#4`) and the M2 capture/E2E slices (`#11`, `#12`) are implemented, verified, and merged on `main`. The completed baselines are summarized for reference below; the active plan specifies the remaining Milestone M2 deployment slice (`#13`).
|
||||||
|
|
||||||
### Completed Milestone M1 Baseline (`#1`–`#4`, Merged on `main`)
|
### Completed Milestone M1 Baseline (`#1`–`#4`, Merged on `main`)
|
||||||
|
|
||||||
@@ -277,61 +278,71 @@ Milestone M1 foundations (`#1`–`#4`) are implemented, verified, and merged on
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### Active Milestone M2 Plan: Developer Mode Capture, Deployment & E2E Hardening
|
### Completed Milestone M2 Slices (`#11`, `#12` — Merged on `main`)
|
||||||
|
|
||||||
#### 1. `src/lg_smtv_mcp/tv_core/capture.py` and `src/lg_smtv_mcp/tv_core/__init__.py` (Create / Modify — Issue `#12`)
|
Delivered by `#12` (PR [#15](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/15)) and `#11` (PR [#14](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/14)). The contracts below match `main` as merged, including the PR `#15` review remediation (CR-01..CR-11).
|
||||||
|
|
||||||
|
#### 1. `src/lg_smtv_mcp/tv_core/capture.py` and `src/lg_smtv_mcp/tv_core/__init__.py` (Completed — Issue `#12`)
|
||||||
|
|
||||||
* **Type / Scope:** Developer Mode `asyncssh`/SFTP screenshot client (`CaptureClient`) and transport adapter (`AsyncSshCaptureTransport`).
|
* **Type / Scope:** Developer Mode `asyncssh`/SFTP screenshot client (`CaptureClient`) and transport adapter (`AsyncSshCaptureTransport`).
|
||||||
* **Proposed Changes:**
|
* **Delivered Contract:**
|
||||||
* Implement `AsyncSshCaptureTransport(config: TvConfig, connect_fn: Callable[..., Awaitable[ Any ]] | None = None)` satisfying [`CaptureTransport`](../../src/lg_smtv_mcp/tv_core/protocols.py):
|
* Implemented `AsyncSshCaptureTransport(config: TvConfig, connect_fn: Callable[..., Awaitable[ Any ]] | None = None)` satisfying [`CaptureTransport`](../../src/lg_smtv_mcp/tv_core/protocols.py):
|
||||||
* Default `connect_fn` to `asyncssh.connect`. Connect to `host=config.tv_ip`, `port=9922`, `username="prisoner"`, `config=[]`, `known_hosts=str(config.ssh_known_hosts_path) if config.ssh_known_hosts_path is not None else None`, `server_host_key_algs=["ssh-rsa"]`, `signature_algs=["ssh-rsa"]`, `client_keys=[str(config.ssh_key_path)] if config.ssh_key_path is not None else None`, and `passphrase=config.webos_ssh_passphrase`.
|
* Defaults `connect_fn` to `asyncssh.connect`. Connects to `host=config.tv_ip`, `port=9922`, `username="prisoner"`, `config=[]`, `known_hosts=str(config.ssh_known_hosts_path) if config.ssh_known_hosts_path is not None else None`, `server_host_key_algs=["ssh-rsa"]`, `signature_algs=["ssh-rsa"]`, `client_keys=[str(config.ssh_key_path)] if config.ssh_key_path is not None else None`, and `passphrase=config.webos_ssh_passphrase`.
|
||||||
* Lazily open (or reconnect) the SSH connection and SFTP client (`await conn.start_sftp_client()`) on demand inside `read_and_remove()`. Whenever a new SFTP session is established, run best-effort `await self.sweep_temp_files("/tmp/lg_smtv_cap_")` (listing `/tmp`, removing matching `lg_smtv_cap_*` entries, and ignoring individual file removal errors).
|
* Lazily opens (or reconnects) the SSH connection and SFTP client (`await conn.start_sftp_client()`) on demand inside `read_and_remove()`. Whenever a new SFTP session is established, runs best-effort `await self.sweep_temp_files("/tmp/lg_smtv_cap_", exclude=remote_path)` (listing `/tmp`, removing matching `lg_smtv_cap_*` entries except the in-flight capture, and ignoring individual file removal errors). `start_sftp_client()` failures and cancellation close the connection deterministically before re-raising.
|
||||||
* In `read_and_remove(remote_path: str, timeout: float = 6.0, cleanup_grace: float = 1.5) -> bytes`, read the remote file bytes via SFTP and guarantee remote deletion in `finally:` using `await asyncio.wait_for(asyncio.shield(sftp.remove(remote_path)), timeout=cleanup_grace)` (suppressing cleanup exceptions so the primary result or error propagates, while ensuring outer cancellation does not abort `sftp.remove`). On SSH/SFTP transport errors, close and clear cached connection/SFTP handles so the next capture reconnects cleanly.
|
* In `read_and_remove(remote_path: str, timeout: float = 6.0, cleanup_grace: float = 1.5) -> bytes`, enforces the caller budget with `async with asyncio.timeout(timeout)`, reads the remote file bytes via SFTP, and guarantees remote deletion in `finally:` using `await asyncio.wait_for(asyncio.shield(sftp.remove(remote_path)), timeout=cleanup_grace)` (suppressing cleanup exceptions so the primary result or error propagates, while ensuring outer cancellation does not abort `sftp.remove`; the detached task's exception is consumed by a done-callback). On SSH/SFTP transport errors, closes and clears cached connection/SFTP handles so the next capture reconnects cleanly.
|
||||||
* In `close()`, close the cached SFTP and SSH connections and clear cached handles.
|
* In `close()`, closes the cached SFTP and SSH connections and clears cached handles.
|
||||||
* Implement `CaptureClient(transport: CaptureTransport)` satisfying [`FrameCapturer`](../../src/lg_smtv_mcp/tv_core/protocols.py):
|
* Implemented `CaptureClient(transport: CaptureTransport)` satisfying [`FrameCapturer`](../../src/lg_smtv_mcp/tv_core/protocols.py):
|
||||||
* Maintain an instance sequence counter `_seq: int = 0` (incremented per `capture_frame` call to form `/tmp/lg_smtv_cap_{self._seq}.jpg`) and `_last_sha256: str | None = None`.
|
* Maintains an instance sequence counter `_seq: int = 0` (incremented per `capture_frame` call to form `/tmp/lg_smtv_cap_{self._seq}.jpg`) and `_last_sha256: str | None = None`.
|
||||||
* In `capture_frame(ssap_request_fn)`, wrap both `await ssap_request_fn("ssap://com.webos.service.capture/executeOneShot", {"path": remote_path, "method": "DISPLAY", "format": "JPG"})` and `await self._transport.read_and_remove(remote_path, timeout=6.0, cleanup_grace=1.5)` inside a shared `async with asyncio.timeout(6.0):` block.
|
* In `capture_frame(ssap_request_fn)`, wraps both `await ssap_request_fn("ssap://com.webos.service.capture/executeOneShot", {"path": remote_path, "method": "DISPLAY", "format": "JPG"})` and `await self._transport.read_and_remove(remote_path, timeout=6.0, cleanup_grace=1.5)` inside a shared `async with asyncio.timeout(6.0):` block.
|
||||||
* If `executeOneShot` returns `returnValue: false`, raises `TvError(ErrorCode.COMMAND_FAILED, ...)`, times out, or `read_and_remove` raises an SSH/SFTP/`OSError`, raise `TvError(ErrorCode.SCREENSHOT_UNAVAILABLE, ...)` without calling `read_and_remove` when `executeOneShot` itself failed. Propagate `TvError` with `TV_OFFLINE_STANDBY` or `PAIRING_REQUIRED` unchanged.
|
* Requires `response.get("returnValue") is True` (exactly `true`; `false`, missing, or `null` all fail). If `executeOneShot` raises a `TvError` other than `TV_OFFLINE_STANDBY`/`PAIRING_REQUIRED`, returns a non-true `returnValue`, times out, or `read_and_remove` raises an SSH/SFTP/`OSError`, raises `TvError(ErrorCode.SCREENSHOT_UNAVAILABLE, ...)` without calling `read_and_remove` when `executeOneShot` itself failed. Propagates `TvError` with `TV_OFFLINE_STANDBY` or `PAIRING_REQUIRED` unchanged.
|
||||||
* Compute `frame_sha256 = hashlib.sha256(image_bytes).hexdigest()`, set `changed_since_last = (self._last_sha256 != frame_sha256)` (`True` on the first capture after init or `close()`), update `self._last_sha256 = frame_sha256`, and return `CaptureResult(image_bytes=image_bytes, frame_sha256=frame_sha256, changed_since_last=changed_since_last, size_bytes=len(image_bytes))`.
|
* Computes `frame_sha256 = hashlib.sha256(image_bytes).hexdigest()`, sets `changed_since_last = (self._last_sha256 != frame_sha256)` (`True` on the first capture after init or `close()`), updates `self._last_sha256 = frame_sha256`, and returns `CaptureResult(image_bytes=image_bytes, frame_sha256=frame_sha256, changed_since_last=changed_since_last, size_bytes=len(image_bytes))`.
|
||||||
* In `close()`, reset `self._last_sha256 = None` and await `self._transport.close()`.
|
* In `close()`, resets `self._last_sha256 = None` and awaits `self._transport.close()`.
|
||||||
* Export `AsyncSshCaptureTransport` and `CaptureClient` in `src/lg_smtv_mcp/tv_core/__init__.py`.
|
* Exported `AsyncSshCaptureTransport` and `CaptureClient` in `src/lg_smtv_mcp/tv_core/__init__.py`.
|
||||||
|
|
||||||
#### 2. `src/lg_smtv_mcp/server.py` (Modify — Issue `#12`)
|
#### 2. `src/lg_smtv_mcp/server.py` (Completed — Issue `#12`)
|
||||||
|
|
||||||
* **Type / Scope:** Default `CaptureClient` wiring in `create_mcp_server`.
|
* **Type / Scope:** Default `CaptureClient` wiring in `create_mcp_server`.
|
||||||
* **Proposed Changes:**
|
* **Delivered Changes:**
|
||||||
* When `create_mcp_server(config: TvConfig, manager: TvManager | None = None)` constructs its default `TvManager` (`manager is None`), pass `capture_client=CaptureClient(AsyncSshCaptureTransport(config))`.
|
* When `create_mcp_server(config: TvConfig, manager: TvManager | None = None)` constructs its default `TvManager` (`manager is None`), it passes `capture_client=CaptureClient(AsyncSshCaptureTransport(config))`.
|
||||||
* Keep `TvManager.__init__`'s `capture_client: FrameCapturer | None = None` default unchanged so existing offline `TvManager` unit tests remain isolated without touching SSH.
|
* `TvManager.__init__`'s `capture_client: FrameCapturer | None = None` default is unchanged so existing offline `TvManager` unit tests remain isolated without touching SSH.
|
||||||
|
|
||||||
#### 3. `tests/test_capture.py` and `tests/test_server.py` (Create / Modify — Issue `#12`)
|
#### 3. `tests/test_capture.py` and `tests/test_server.py` (Completed — Issue `#12`)
|
||||||
|
|
||||||
* **Type / Scope:** Offline contract tests for `CaptureClient`, `AsyncSshCaptureTransport`, and `server.py` default wiring.
|
* **Type / Scope:** Offline contract tests for `CaptureClient`, `AsyncSshCaptureTransport`, and `server.py` default wiring.
|
||||||
* **Proposed Changes:**
|
* **Delivered Changes:**
|
||||||
* Create `tests/test_capture.py` verifying:
|
* Created `tests/test_capture.py` covering:
|
||||||
* `AsyncSshCaptureTransport` passes `host`, `port=9922`, `username="prisoner"`, `config=[]`, `server_host_key_algs=["ssh-rsa"]`, `signature_algs=["ssh-rsa"]`, optional `known_hosts`, `client_keys`, and `passphrase` to `connect_fn`.
|
* `AsyncSshCaptureTransport` passes `host`, `port=9922`, `username="prisoner"`, `config=[]`, `server_host_key_algs=["ssh-rsa"]`, `signature_algs=["ssh-rsa"]`, optional `known_hosts`, `client_keys`, and `passphrase` to `connect_fn`.
|
||||||
* `AsyncSshCaptureTransport` runs `sweep_temp_files("/tmp/lg_smtv_cap_")` on initial SFTP connect and after reconnecting following a transport failure, removing only matching `lg_smtv_cap_*` files.
|
* `AsyncSshCaptureTransport` runs `sweep_temp_files("/tmp/lg_smtv_cap_", exclude=...)` on initial SFTP connect and after reconnecting following a transport failure, removing only matching `lg_smtv_cap_*` files and preserving the in-flight capture path.
|
||||||
|
* `AsyncSshCaptureTransport` closes the SSH connection when `start_sftp_client()` fails, and enforces `read_and_remove`'s `timeout` budget.
|
||||||
* `AsyncSshCaptureTransport.read_and_remove` shields `sftp.remove(remote_path)` under `cleanup_grace=1.5` even when `read` fails or the outer task is cancelled.
|
* `AsyncSshCaptureTransport.read_and_remove` shields `sftp.remove(remote_path)` under `cleanup_grace=1.5` even when `read` fails or the outer task is cancelled.
|
||||||
* `CaptureClient.capture_frame` sends `ssap://com.webos.service.capture/executeOneShot` with `{"path": "/tmp/lg_smtv_cap_1.jpg", "method": "DISPLAY", "format": "JPG"}`, skips SFTP read if `returnValue` is `False` or `COMMAND_FAILED`, maps `returnValue: false` / `COMMAND_FAILED` / SSH errors / `6.0s` timeout to `ErrorCode.SCREENSHOT_UNAVAILABLE`, and preserves `TV_OFFLINE_STANDBY` / `PAIRING_REQUIRED`.
|
* `CaptureClient.capture_frame` sends `ssap://com.webos.service.capture/executeOneShot` with `{"path": "/tmp/lg_smtv_cap_1.jpg", "method": "DISPLAY", "format": "JPG"}`, skips SFTP read if `returnValue` is not exactly `true` or `COMMAND_FAILED`, maps non-true `returnValue` / `COMMAND_FAILED` / SSH errors / `6.0s` timeout to `ErrorCode.SCREENSHOT_UNAVAILABLE`, and preserves `TV_OFFLINE_STANDBY` / `PAIRING_REQUIRED`.
|
||||||
* `CaptureClient.capture_frame` computes `frame_sha256`, sets `changed_since_last=True` on first frame, `False` on identical consecutive frame, `True` after `close()` resets `_last_sha256`, and reports `size_bytes=len(image_bytes)`.
|
* `CaptureClient.capture_frame` computes `frame_sha256`, sets `changed_since_last=True` on first frame, `False` on identical consecutive frame, `True` after `close()` resets `_last_sha256`, and reports `size_bytes=len(image_bytes)`.
|
||||||
* Extend `tests/test_server.py` to verify `create_mcp_server(config)` wires a `CaptureClient` into the default `TvManager`.
|
* Extended `tests/test_server.py` to verify `create_mcp_server(config)` wires a `CaptureClient` into the default `TvManager`.
|
||||||
|
|
||||||
#### 4. `deploy/lg-smtv-mcp.service` and `README.md` (Create / Modify — Issue `#13`)
|
#### 4. `tests/test_e2e_mvp.py` (Completed — Issue `#11`, PR [#14](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/14))
|
||||||
|
|
||||||
|
* **Type / Scope:** E2E test harness and standby parity hardening (PR `#10` follow-up).
|
||||||
|
* **Delivered Changes:**
|
||||||
|
* Extracted `_build_online_ssap` to a module-level helper in `tests/test_e2e_mvp.py`.
|
||||||
|
* Handled `lifespan.startup.failed` (or raced `startup_done.wait()` against `lifespan_task`) in the ASGI lifespan helper so startup failures surface immediately without waiting for the `2.0s` timeout.
|
||||||
|
* Asserted `isinstance(wake_payload["elapsed_ms"], int) and wake_payload["elapsed_ms"] >= 0` on `tv_wake`.
|
||||||
|
* After `turn_off()`, simulated the TV closing the SSAP WebSocket with `1008` and re-queried `get_state` to verify `connected: false, stale: true` with cached state retained.
|
||||||
|
|
||||||
|
* **M2 Delivery Checkpoint:** `nix develop --command bash -c "ruff check . && ruff format --check . && pyright && pytest"` and `nix flake check` passed for `#11` and `#12`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Active Milestone M2 Plan: Systemd Deployment (`#13`)
|
||||||
|
|
||||||
|
#### 1. `deploy/lg-smtv-mcp.service` and `README.md` (Create / Modify — Issue `#13`)
|
||||||
|
|
||||||
* **Type / Scope:** Systemd unit template and operator documentation.
|
* **Type / Scope:** Systemd unit template and operator documentation.
|
||||||
* **Proposed Changes:**
|
* **Proposed Changes:**
|
||||||
* Create `deploy/lg-smtv-mcp.service` with `<User>`, `<WorkingDirectory>`, `EnvironmentFile`, `After=network-online.target`, `Wants=network-online.target`, and `Restart=on-failure`, invoking `nix develop --command python -m lg_smtv_mcp serve`.
|
* Create `deploy/lg-smtv-mcp.service` with `<User>`, `<WorkingDirectory>`, `EnvironmentFile`, `After=network-online.target`, `Wants=network-online.target`, and `Restart=on-failure`, invoking `nix develop --command python -m lg_smtv_mcp serve`.
|
||||||
* Update `README.md` with `systemd` deployment steps (including ensuring `nix` is on `systemd`'s `PATH`), Developer Mode SSH setup (`pair --fetch-ssh-key`, `:9922` session timer behavior, `SSH_KNOWN_HOSTS_PATH`), and a live-TV `screenshot` / `keys(..., capture=True)` smoke checklist item.
|
* Update `README.md` with `systemd` deployment steps (including ensuring `nix` is on `systemd`'s `PATH`), Developer Mode SSH setup (`pair --fetch-ssh-key`, `:9922` session timer behavior, `SSH_KNOWN_HOSTS_PATH`), and a live-TV `screenshot` / `keys(..., capture=True)` smoke checklist item.
|
||||||
|
* A follow-up issue (`#17`) tracks tightening the unit's sandboxing directives after this baseline template lands.
|
||||||
|
|
||||||
#### 5. `tests/test_e2e_mvp.py` (Modify — Issue `#11`)
|
* **M2 Completion Checkpoint:** `nix develop --command bash -c "ruff check . && ruff format --check . && pyright && pytest"` and `nix flake check`.
|
||||||
|
|
||||||
* **Type / Scope:** E2E test harness and standby parity hardening (PR `#10` follow-up).
|
|
||||||
* **Proposed Changes:**
|
|
||||||
* Extract `_build_online_ssap` to a module-level helper in `tests/test_e2e_mvp.py`.
|
|
||||||
* Handle `lifespan.startup.failed` (or race `startup_done.wait()` against `lifespan_task`) in the ASGI lifespan helper so startup failures surface immediately without waiting for the `2.0s` timeout.
|
|
||||||
* Assert `isinstance(wake_payload["elapsed_ms"], int) and wake_payload["elapsed_ms"] >= 0` on `tv_wake`.
|
|
||||||
* After `turn_off()`, simulate the TV closing the SSAP WebSocket with `1008` and re-query `get_state` to verify `connected: false, stale: true` with cached state retained.
|
|
||||||
|
|
||||||
* **M2 Verification Checkpoint:** `nix develop --command bash -c "ruff check . && ruff format --check . && pyright && pytest"` and `nix flake check`.
|
|
||||||
|
|
||||||
### Verification Plan
|
### Verification Plan
|
||||||
|
|
||||||
|
|||||||
@@ -54,12 +54,12 @@ class AsyncSshCaptureTransport:
|
|||||||
if asyncio.iscoroutine(res):
|
if asyncio.iscoroutine(res):
|
||||||
await res
|
await res
|
||||||
|
|
||||||
async def _ensure_sftp(self) -> Any:
|
async def _ensure_sftp(self, exclude: str | None = None) -> Any:
|
||||||
if self._sftp is not None:
|
if self._sftp is not None:
|
||||||
return self._sftp
|
return self._sftp
|
||||||
|
|
||||||
config = self._config
|
config = self._config
|
||||||
self._conn = await self._connect_fn(
|
conn = await self._connect_fn(
|
||||||
host=config.tv_ip,
|
host=config.tv_ip,
|
||||||
port=9922,
|
port=9922,
|
||||||
username="prisoner",
|
username="prisoner",
|
||||||
@@ -74,9 +74,22 @@ class AsyncSshCaptureTransport:
|
|||||||
client_keys=[str(config.ssh_key_path)] if config.ssh_key_path is not None else None,
|
client_keys=[str(config.ssh_key_path)] if config.ssh_key_path is not None else None,
|
||||||
passphrase=config.webos_ssh_passphrase,
|
passphrase=config.webos_ssh_passphrase,
|
||||||
)
|
)
|
||||||
self._sftp = await self._conn.start_sftp_client()
|
try:
|
||||||
|
sftp = await conn.start_sftp_client()
|
||||||
|
except BaseException:
|
||||||
|
conn.close()
|
||||||
with suppress(Exception):
|
with suppress(Exception):
|
||||||
await self.sweep_temp_files("/tmp/lg_smtv_cap_")
|
wait_closed = getattr(conn, "wait_closed", None)
|
||||||
|
if callable(wait_closed):
|
||||||
|
res = wait_closed()
|
||||||
|
if asyncio.iscoroutine(res):
|
||||||
|
await res
|
||||||
|
raise
|
||||||
|
|
||||||
|
self._conn = conn
|
||||||
|
self._sftp = sftp
|
||||||
|
with suppress(Exception):
|
||||||
|
await self.sweep_temp_files("/tmp/lg_smtv_cap_", exclude=exclude)
|
||||||
return self._sftp
|
return self._sftp
|
||||||
|
|
||||||
async def read_and_remove(
|
async def read_and_remove(
|
||||||
@@ -85,32 +98,41 @@ class AsyncSshCaptureTransport:
|
|||||||
timeout: float = 6.0,
|
timeout: float = 6.0,
|
||||||
cleanup_grace: float = 1.5,
|
cleanup_grace: float = 1.5,
|
||||||
) -> bytes:
|
) -> bytes:
|
||||||
_ = timeout # timeout budget is enforced by CaptureClient around the full operation
|
sftp = None
|
||||||
try:
|
|
||||||
sftp = await self._ensure_sftp()
|
|
||||||
try:
|
try:
|
||||||
|
async with asyncio.timeout(timeout):
|
||||||
|
sftp = await self._ensure_sftp(exclude=remote_path)
|
||||||
data = await sftp.read(remote_path)
|
data = await sftp.read(remote_path)
|
||||||
if not isinstance(data, (bytes, bytearray)):
|
return bytes(data)
|
||||||
data = bytes(data)
|
|
||||||
else:
|
|
||||||
data = bytes(data)
|
|
||||||
finally:
|
|
||||||
with suppress(Exception):
|
|
||||||
await asyncio.wait_for(
|
|
||||||
asyncio.shield(sftp.remove(remote_path)),
|
|
||||||
timeout=cleanup_grace,
|
|
||||||
)
|
|
||||||
return data
|
|
||||||
except asyncssh.Error, OSError:
|
except asyncssh.Error, OSError:
|
||||||
await self._close_handles()
|
await self._close_handles()
|
||||||
raise
|
raise
|
||||||
|
finally:
|
||||||
|
if sftp is not None:
|
||||||
|
remove_task = asyncio.create_task(sftp.remove(remote_path))
|
||||||
|
|
||||||
async def sweep_temp_files(self, prefix: str = "/tmp/lg_smtv_cap_") -> None:
|
def _consume_exception(task: asyncio.Task[Any]) -> None:
|
||||||
|
with suppress(Exception):
|
||||||
|
_ = task.exception()
|
||||||
|
|
||||||
|
remove_task.add_done_callback(_consume_exception)
|
||||||
|
with suppress(Exception):
|
||||||
|
await asyncio.wait_for(
|
||||||
|
asyncio.shield(remove_task),
|
||||||
|
timeout=cleanup_grace,
|
||||||
|
)
|
||||||
|
|
||||||
|
async def sweep_temp_files(
|
||||||
|
self,
|
||||||
|
prefix: str = "/tmp/lg_smtv_cap_",
|
||||||
|
exclude: str | None = None,
|
||||||
|
) -> None:
|
||||||
sftp = self._sftp
|
sftp = self._sftp
|
||||||
if sftp is None:
|
if sftp is None:
|
||||||
return
|
return
|
||||||
directory = os.path.dirname(prefix) or "/tmp"
|
directory = os.path.dirname(prefix) or "/tmp"
|
||||||
name_prefix = os.path.basename(prefix)
|
name_prefix = os.path.basename(prefix)
|
||||||
|
exclude_name = os.path.basename(exclude) if exclude else None
|
||||||
try:
|
try:
|
||||||
entries = await sftp.listdir(directory)
|
entries = await sftp.listdir(directory)
|
||||||
except Exception:
|
except Exception:
|
||||||
@@ -118,6 +140,8 @@ class AsyncSshCaptureTransport:
|
|||||||
for entry in entries:
|
for entry in entries:
|
||||||
if not isinstance(entry, str) or not entry.startswith(name_prefix):
|
if not isinstance(entry, str) or not entry.startswith(name_prefix):
|
||||||
continue
|
continue
|
||||||
|
if exclude_name is not None and entry == exclude_name:
|
||||||
|
continue
|
||||||
remote_path = f"{directory.rstrip('/')}/{entry}"
|
remote_path = f"{directory.rstrip('/')}/{entry}"
|
||||||
with suppress(Exception):
|
with suppress(Exception):
|
||||||
await sftp.remove(remote_path)
|
await sftp.remove(remote_path)
|
||||||
@@ -150,20 +174,15 @@ class CaptureClient:
|
|||||||
except TvError as exc:
|
except TvError as exc:
|
||||||
if exc.code in (ErrorCode.TV_OFFLINE_STANDBY, ErrorCode.PAIRING_REQUIRED):
|
if exc.code in (ErrorCode.TV_OFFLINE_STANDBY, ErrorCode.PAIRING_REQUIRED):
|
||||||
raise
|
raise
|
||||||
if exc.code is ErrorCode.COMMAND_FAILED:
|
|
||||||
raise TvError(
|
|
||||||
ErrorCode.SCREENSHOT_UNAVAILABLE,
|
|
||||||
f"executeOneShot failed: {exc.message}",
|
|
||||||
) from exc
|
|
||||||
raise TvError(
|
raise TvError(
|
||||||
ErrorCode.SCREENSHOT_UNAVAILABLE,
|
ErrorCode.SCREENSHOT_UNAVAILABLE,
|
||||||
f"executeOneShot failed: {exc.message}",
|
f"executeOneShot failed: {exc.message}",
|
||||||
) from exc
|
) from exc
|
||||||
|
|
||||||
if response.get("returnValue") is False:
|
if response.get("returnValue") is not True:
|
||||||
raise TvError(
|
raise TvError(
|
||||||
ErrorCode.SCREENSHOT_UNAVAILABLE,
|
ErrorCode.SCREENSHOT_UNAVAILABLE,
|
||||||
"executeOneShot returned returnValue false",
|
"executeOneShot did not return returnValue true",
|
||||||
)
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -38,7 +38,11 @@ class CaptureTransport(Protocol):
|
|||||||
cleanup_grace: float = 1.5,
|
cleanup_grace: float = 1.5,
|
||||||
) -> bytes: ...
|
) -> bytes: ...
|
||||||
|
|
||||||
async def sweep_temp_files(self, prefix: str = "/tmp/lg_smtv_cap_") -> None: ...
|
async def sweep_temp_files(
|
||||||
|
self,
|
||||||
|
prefix: str = "/tmp/lg_smtv_cap_",
|
||||||
|
exclude: str | None = None,
|
||||||
|
) -> None: ...
|
||||||
|
|
||||||
async def close(self) -> None: ...
|
async def close(self) -> None: ...
|
||||||
|
|
||||||
|
|||||||
+193
-150
@@ -17,13 +17,13 @@ class FakeSftpClient:
|
|||||||
self,
|
self,
|
||||||
*,
|
*,
|
||||||
files: dict[str, bytes] | None = None,
|
files: dict[str, bytes] | None = None,
|
||||||
list_names: list[str] | None = None,
|
extra_names: list[str] | None = None,
|
||||||
read_error: Exception | None = None,
|
read_error: Exception | None = None,
|
||||||
remove_delay: float = 0.0,
|
remove_delay: float = 0.0,
|
||||||
remove_error: Exception | None = None,
|
remove_error: Exception | None = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
self.files = dict(files or {})
|
self.files = dict(files or {})
|
||||||
self.list_names = list(list_names or [])
|
self.extra_names = list(extra_names or [])
|
||||||
self.read_error = read_error
|
self.read_error = read_error
|
||||||
self.remove_delay = remove_delay
|
self.remove_delay = remove_delay
|
||||||
self.remove_error = remove_error
|
self.remove_error = remove_error
|
||||||
@@ -46,12 +46,11 @@ class FakeSftpClient:
|
|||||||
if self.remove_error is not None:
|
if self.remove_error is not None:
|
||||||
raise self.remove_error
|
raise self.remove_error
|
||||||
self.files.pop(path, None)
|
self.files.pop(path, None)
|
||||||
if path in self.list_names:
|
|
||||||
self.list_names.remove(path)
|
|
||||||
|
|
||||||
async def listdir(self, path: str) -> list[str]:
|
async def listdir(self, path: str) -> list[str]:
|
||||||
_ = path
|
_ = path
|
||||||
return list(self.list_names)
|
names = {Path(p).name for p in self.files} | set(self.extra_names)
|
||||||
|
return sorted(names)
|
||||||
|
|
||||||
async def exit(self) -> None:
|
async def exit(self) -> None:
|
||||||
self.closed = True
|
self.closed = True
|
||||||
@@ -74,6 +73,48 @@ class FakeSshConnection:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
class FakeCaptureTransport:
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
image_bytes: bytes = b"default-image",
|
||||||
|
read_error: Exception | None = None,
|
||||||
|
block_read: bool = False,
|
||||||
|
) -> None:
|
||||||
|
self.image_bytes = image_bytes
|
||||||
|
self.read_error = read_error
|
||||||
|
self.block_read = block_read
|
||||||
|
self.read_calls: list[tuple[str, float, float]] = []
|
||||||
|
self.read_cancelled = asyncio.Event()
|
||||||
|
self.closed = False
|
||||||
|
|
||||||
|
async def read_and_remove(
|
||||||
|
self,
|
||||||
|
remote_path: str,
|
||||||
|
timeout: float = 6.0,
|
||||||
|
cleanup_grace: float = 1.5,
|
||||||
|
) -> bytes:
|
||||||
|
self.read_calls.append((remote_path, timeout, cleanup_grace))
|
||||||
|
if self.block_read:
|
||||||
|
try:
|
||||||
|
await asyncio.Event().wait()
|
||||||
|
finally:
|
||||||
|
self.read_cancelled.set()
|
||||||
|
if self.read_error is not None:
|
||||||
|
raise self.read_error
|
||||||
|
return self.image_bytes
|
||||||
|
|
||||||
|
async def sweep_temp_files(
|
||||||
|
self,
|
||||||
|
prefix: str = "/tmp/lg_smtv_cap_",
|
||||||
|
exclude: str | None = None,
|
||||||
|
) -> None:
|
||||||
|
_ = (prefix, exclude)
|
||||||
|
|
||||||
|
async def close(self) -> None:
|
||||||
|
self.closed = True
|
||||||
|
|
||||||
|
|
||||||
def _make_config(tmp_path: Path, *, with_ssh: bool = False) -> TvConfig:
|
def _make_config(tmp_path: Path, *, with_ssh: bool = False) -> TvConfig:
|
||||||
ssh_key = tmp_path / "id_rsa"
|
ssh_key = tmp_path / "id_rsa"
|
||||||
known_hosts = tmp_path / "known_hosts"
|
known_hosts = tmp_path / "known_hosts"
|
||||||
@@ -89,7 +130,7 @@ def _make_config(tmp_path: Path, *, with_ssh: bool = False) -> TvConfig:
|
|||||||
|
|
||||||
|
|
||||||
async def test_async_ssh_capture_transport_connect_uses_required_args(tmp_path: Path) -> None:
|
async def test_async_ssh_capture_transport_connect_uses_required_args(tmp_path: Path) -> None:
|
||||||
sftp = FakeSftpClient(files={"/tmp/lg_smtv_cap_1.jpg": b"jpeg"}, list_names=[])
|
sftp = FakeSftpClient(files={"/tmp/lg_smtv_cap_1.jpg": b"jpeg"})
|
||||||
conn = FakeSshConnection(sftp)
|
conn = FakeSshConnection(sftp)
|
||||||
calls: list[dict[str, Any]] = []
|
calls: list[dict[str, Any]] = []
|
||||||
|
|
||||||
@@ -119,12 +160,12 @@ async def test_async_ssh_capture_transport_sweeps_on_initial_connect_and_reconne
|
|||||||
) -> None:
|
) -> None:
|
||||||
sftp1 = FakeSftpClient(
|
sftp1 = FakeSftpClient(
|
||||||
files={"/tmp/lg_smtv_cap_1.jpg": b"one"},
|
files={"/tmp/lg_smtv_cap_1.jpg": b"one"},
|
||||||
list_names=["lg_smtv_cap_old.jpg", "other.txt"],
|
extra_names=["lg_smtv_cap_old.jpg", "other.txt"],
|
||||||
)
|
)
|
||||||
conn1 = FakeSshConnection(sftp1)
|
conn1 = FakeSshConnection(sftp1)
|
||||||
sftp2 = FakeSftpClient(
|
sftp2 = FakeSftpClient(
|
||||||
files={"/tmp/lg_smtv_cap_2.jpg": b"two"},
|
files={"/tmp/lg_smtv_cap_2.jpg": b"two"},
|
||||||
list_names=["lg_smtv_cap_stale.jpg", "keep.txt"],
|
extra_names=["lg_smtv_cap_stale.jpg", "keep.txt"],
|
||||||
)
|
)
|
||||||
conn2 = FakeSshConnection(sftp2)
|
conn2 = FakeSshConnection(sftp2)
|
||||||
conns = [conn1, conn2]
|
conns = [conn1, conn2]
|
||||||
@@ -149,11 +190,16 @@ async def test_async_ssh_capture_transport_sweeps_on_initial_connect_and_reconne
|
|||||||
assert "/tmp/keep.txt" not in sftp2.remove_calls
|
assert "/tmp/keep.txt" not in sftp2.remove_calls
|
||||||
|
|
||||||
|
|
||||||
async def test_async_ssh_capture_transport_shields_remove_on_read_error(tmp_path: Path) -> None:
|
async def test_async_ssh_capture_transport_sweep_preserves_in_flight_remote_path(
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
remote_path = "/tmp/lg_smtv_cap_1.jpg"
|
||||||
sftp = FakeSftpClient(
|
sftp = FakeSftpClient(
|
||||||
files={"/tmp/lg_smtv_cap_1.jpg": b"jpeg"},
|
files={
|
||||||
read_error=OSError("read failed"),
|
remote_path: b"fresh-frame",
|
||||||
remove_delay=0.05,
|
"/tmp/lg_smtv_cap_stale.jpg": b"stale-frame",
|
||||||
|
},
|
||||||
|
extra_names=["other_file.txt"],
|
||||||
)
|
)
|
||||||
conn = FakeSshConnection(sftp)
|
conn = FakeSshConnection(sftp)
|
||||||
|
|
||||||
@@ -162,35 +208,110 @@ async def test_async_ssh_capture_transport_shields_remove_on_read_error(tmp_path
|
|||||||
return conn
|
return conn
|
||||||
|
|
||||||
transport = AsyncSshCaptureTransport(_make_config(tmp_path), connect_fn=fake_connect)
|
transport = AsyncSshCaptureTransport(_make_config(tmp_path), connect_fn=fake_connect)
|
||||||
with pytest.raises(OSError, match="read failed"):
|
data = await transport.read_and_remove(remote_path)
|
||||||
await transport.read_and_remove("/tmp/lg_smtv_cap_1.jpg", timeout=6.0, cleanup_grace=1.5)
|
|
||||||
|
|
||||||
assert "/tmp/lg_smtv_cap_1.jpg" in sftp.remove_calls
|
assert data == b"fresh-frame"
|
||||||
|
assert "/tmp/lg_smtv_cap_stale.jpg" in sftp.remove_calls
|
||||||
|
assert remote_path in sftp.remove_calls
|
||||||
|
assert "/tmp/other_file.txt" not in sftp.remove_calls
|
||||||
|
|
||||||
|
|
||||||
async def test_capture_client_sends_execute_one_shot_and_returns_metadata(tmp_path: Path) -> None:
|
async def test_async_ssh_capture_transport_closes_connection_when_start_sftp_client_fails(
|
||||||
_ = tmp_path
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
class FailingSshConnection:
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.closed = False
|
||||||
|
|
||||||
|
async def start_sftp_client(self) -> Any:
|
||||||
|
raise OSError("sftp start failed")
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
self.closed = True
|
||||||
|
|
||||||
|
async def wait_closed(self) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
conn = FailingSshConnection()
|
||||||
|
|
||||||
|
async def fake_connect(**kwargs: Any) -> FailingSshConnection:
|
||||||
|
_ = kwargs
|
||||||
|
return conn
|
||||||
|
|
||||||
|
transport = AsyncSshCaptureTransport(_make_config(tmp_path), connect_fn=fake_connect)
|
||||||
|
with pytest.raises(OSError):
|
||||||
|
await transport.read_and_remove("/tmp/lg_smtv_cap_1.jpg")
|
||||||
|
|
||||||
|
assert conn.closed is True
|
||||||
|
|
||||||
|
|
||||||
|
async def test_async_ssh_capture_transport_enforces_read_timeout(
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
class HangingSftp(FakeSftpClient):
|
||||||
|
async def read(self, path: str) -> bytes:
|
||||||
|
await asyncio.sleep(10.0)
|
||||||
|
return b"never"
|
||||||
|
|
||||||
|
sftp = HangingSftp(files={"/tmp/lg_smtv_cap_1.jpg": b"bytes"})
|
||||||
|
conn = FakeSshConnection(sftp)
|
||||||
|
|
||||||
|
async def fake_connect(**kwargs: Any) -> FakeSshConnection:
|
||||||
|
_ = kwargs
|
||||||
|
return conn
|
||||||
|
|
||||||
|
transport = AsyncSshCaptureTransport(_make_config(tmp_path), connect_fn=fake_connect)
|
||||||
|
with pytest.raises(TimeoutError):
|
||||||
|
await transport.read_and_remove("/tmp/lg_smtv_cap_1.jpg", timeout=0.05)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_async_ssh_capture_transport_finishes_remove_after_cancellation(
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
remote_path = "/tmp/lg_smtv_cap_1.jpg"
|
||||||
|
|
||||||
|
class BlockingRemoveSftp(FakeSftpClient):
|
||||||
|
def __init__(self) -> None:
|
||||||
|
super().__init__(files={remote_path: b"jpeg"})
|
||||||
|
self.remove_started = asyncio.Event()
|
||||||
|
self.allow_remove = asyncio.Event()
|
||||||
|
self.remove_finished = asyncio.Event()
|
||||||
|
|
||||||
|
async def remove(self, path: str) -> None:
|
||||||
|
self.remove_started.set()
|
||||||
|
await self.allow_remove.wait()
|
||||||
|
await super().remove(path)
|
||||||
|
self.remove_finished.set()
|
||||||
|
|
||||||
|
sftp = BlockingRemoveSftp()
|
||||||
|
conn = FakeSshConnection(sftp)
|
||||||
|
|
||||||
|
async def fake_connect(**kwargs: Any) -> FakeSshConnection:
|
||||||
|
_ = kwargs
|
||||||
|
return conn
|
||||||
|
|
||||||
|
transport = AsyncSshCaptureTransport(_make_config(tmp_path), connect_fn=fake_connect)
|
||||||
|
read_task = asyncio.create_task(transport.read_and_remove(remote_path, cleanup_grace=0.05))
|
||||||
|
try:
|
||||||
|
await asyncio.wait_for(sftp.remove_started.wait(), timeout=1.0)
|
||||||
|
read_task.cancel()
|
||||||
|
with pytest.raises(asyncio.CancelledError):
|
||||||
|
await read_task
|
||||||
|
finally:
|
||||||
|
sftp.allow_remove.set()
|
||||||
|
if not read_task.done():
|
||||||
|
read_task.cancel()
|
||||||
|
await asyncio.gather(read_task, return_exceptions=True)
|
||||||
|
|
||||||
|
await asyncio.wait_for(sftp.remove_finished.wait(), timeout=1.0)
|
||||||
|
assert remote_path in sftp.remove_calls
|
||||||
|
|
||||||
|
|
||||||
|
async def test_capture_client_sends_execute_one_shot_and_returns_metadata() -> None:
|
||||||
image = b"frame-bytes"
|
image = b"frame-bytes"
|
||||||
expected_sha = hashlib.sha256(image).hexdigest()
|
expected_sha = hashlib.sha256(image).hexdigest()
|
||||||
|
|
||||||
class FakeTransport:
|
transport = FakeCaptureTransport(image_bytes=image)
|
||||||
def __init__(self) -> None:
|
|
||||||
self.read_calls: list[tuple[str, float, float]] = []
|
|
||||||
self.closed = False
|
|
||||||
|
|
||||||
async def read_and_remove(
|
|
||||||
self, remote_path: str, timeout: float = 6.0, cleanup_grace: float = 1.5
|
|
||||||
) -> bytes:
|
|
||||||
self.read_calls.append((remote_path, timeout, cleanup_grace))
|
|
||||||
return image
|
|
||||||
|
|
||||||
async def sweep_temp_files(self, prefix: str = "/tmp/lg_smtv_cap_") -> None:
|
|
||||||
_ = prefix
|
|
||||||
|
|
||||||
async def close(self) -> None:
|
|
||||||
self.closed = True
|
|
||||||
|
|
||||||
transport = FakeTransport()
|
|
||||||
client = CaptureClient(transport)
|
client = CaptureClient(transport)
|
||||||
calls: list[tuple[str, dict[str, Any]]] = []
|
calls: list[tuple[str, dict[str, Any]]] = []
|
||||||
|
|
||||||
@@ -213,24 +334,8 @@ async def test_capture_client_sends_execute_one_shot_and_returns_metadata(tmp_pa
|
|||||||
assert result.size_bytes == len(image)
|
assert result.size_bytes == len(image)
|
||||||
|
|
||||||
|
|
||||||
async def test_capture_client_changed_since_last_and_close_resets(tmp_path: Path) -> None:
|
async def test_capture_client_changed_since_last_and_close_resets() -> None:
|
||||||
_ = tmp_path
|
client = CaptureClient(FakeCaptureTransport(image_bytes=b"same"))
|
||||||
image = b"same"
|
|
||||||
|
|
||||||
class FakeTransport:
|
|
||||||
async def read_and_remove(
|
|
||||||
self, remote_path: str, timeout: float = 6.0, cleanup_grace: float = 1.5
|
|
||||||
) -> bytes:
|
|
||||||
_ = (remote_path, timeout, cleanup_grace)
|
|
||||||
return image
|
|
||||||
|
|
||||||
async def sweep_temp_files(self, prefix: str = "/tmp/lg_smtv_cap_") -> None:
|
|
||||||
_ = prefix
|
|
||||||
|
|
||||||
async def close(self) -> None:
|
|
||||||
return None
|
|
||||||
|
|
||||||
client = CaptureClient(FakeTransport())
|
|
||||||
|
|
||||||
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
_ = (uri, payload)
|
_ = (uri, payload)
|
||||||
@@ -246,58 +351,29 @@ async def test_capture_client_changed_since_last_and_close_resets(tmp_path: Path
|
|||||||
assert third.changed_since_last is True
|
assert third.changed_since_last is True
|
||||||
|
|
||||||
|
|
||||||
async def test_capture_client_maps_execute_one_shot_failure_without_sftp_read(
|
@pytest.mark.parametrize(
|
||||||
tmp_path: Path,
|
"response",
|
||||||
|
[{"returnValue": False}, {}, {"returnValue": None}],
|
||||||
|
ids=["false", "missing", "null"],
|
||||||
|
)
|
||||||
|
async def test_capture_client_rejects_non_true_return_value_without_sftp_read(
|
||||||
|
response: dict[str, Any],
|
||||||
) -> None:
|
) -> None:
|
||||||
_ = tmp_path
|
transport = FakeCaptureTransport()
|
||||||
|
|
||||||
class FakeTransport:
|
|
||||||
def __init__(self) -> None:
|
|
||||||
self.read_calls = 0
|
|
||||||
|
|
||||||
async def read_and_remove(
|
|
||||||
self, remote_path: str, timeout: float = 6.0, cleanup_grace: float = 1.5
|
|
||||||
) -> bytes:
|
|
||||||
_ = (remote_path, timeout, cleanup_grace)
|
|
||||||
self.read_calls += 1
|
|
||||||
return b"nope"
|
|
||||||
|
|
||||||
async def sweep_temp_files(self, prefix: str = "/tmp/lg_smtv_cap_") -> None:
|
|
||||||
_ = prefix
|
|
||||||
|
|
||||||
async def close(self) -> None:
|
|
||||||
return None
|
|
||||||
|
|
||||||
transport = FakeTransport()
|
|
||||||
client = CaptureClient(transport)
|
client = CaptureClient(transport)
|
||||||
|
|
||||||
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
_ = (uri, payload)
|
_ = (uri, payload)
|
||||||
return {"returnValue": False}
|
return response
|
||||||
|
|
||||||
with pytest.raises(TvError) as exc_info:
|
with pytest.raises(TvError) as exc_info:
|
||||||
await client.capture_frame(ssap_request)
|
await client.capture_frame(ssap_request)
|
||||||
assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE
|
assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE
|
||||||
assert transport.read_calls == 0
|
assert len(transport.read_calls) == 0
|
||||||
|
|
||||||
|
|
||||||
async def test_capture_client_preserves_standby_and_pairing_errors(tmp_path: Path) -> None:
|
async def test_capture_client_preserves_standby_and_pairing_errors() -> None:
|
||||||
_ = tmp_path
|
client = CaptureClient(FakeCaptureTransport())
|
||||||
|
|
||||||
class FakeTransport:
|
|
||||||
async def read_and_remove(
|
|
||||||
self, remote_path: str, timeout: float = 6.0, cleanup_grace: float = 1.5
|
|
||||||
) -> bytes:
|
|
||||||
_ = (remote_path, timeout, cleanup_grace)
|
|
||||||
return b"img"
|
|
||||||
|
|
||||||
async def sweep_temp_files(self, prefix: str = "/tmp/lg_smtv_cap_") -> None:
|
|
||||||
_ = prefix
|
|
||||||
|
|
||||||
async def close(self) -> None:
|
|
||||||
return None
|
|
||||||
|
|
||||||
client = CaptureClient(FakeTransport())
|
|
||||||
|
|
||||||
async def standby_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
async def standby_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
_ = (uri, payload)
|
_ = (uri, payload)
|
||||||
@@ -316,27 +392,8 @@ async def test_capture_client_preserves_standby_and_pairing_errors(tmp_path: Pat
|
|||||||
assert pairing_exc.value.code is ErrorCode.PAIRING_REQUIRED
|
assert pairing_exc.value.code is ErrorCode.PAIRING_REQUIRED
|
||||||
|
|
||||||
|
|
||||||
async def test_capture_client_maps_command_failed_without_sftp_read(tmp_path: Path) -> None:
|
async def test_capture_client_maps_command_failed_without_sftp_read() -> None:
|
||||||
_ = tmp_path
|
transport = FakeCaptureTransport()
|
||||||
|
|
||||||
class FakeTransport:
|
|
||||||
def __init__(self) -> None:
|
|
||||||
self.read_calls = 0
|
|
||||||
|
|
||||||
async def read_and_remove(
|
|
||||||
self, remote_path: str, timeout: float = 6.0, cleanup_grace: float = 1.5
|
|
||||||
) -> bytes:
|
|
||||||
_ = (remote_path, timeout, cleanup_grace)
|
|
||||||
self.read_calls += 1
|
|
||||||
return b"nope"
|
|
||||||
|
|
||||||
async def sweep_temp_files(self, prefix: str = "/tmp/lg_smtv_cap_") -> None:
|
|
||||||
_ = prefix
|
|
||||||
|
|
||||||
async def close(self) -> None:
|
|
||||||
return None
|
|
||||||
|
|
||||||
transport = FakeTransport()
|
|
||||||
client = CaptureClient(transport)
|
client = CaptureClient(transport)
|
||||||
|
|
||||||
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
@@ -346,26 +403,12 @@ async def test_capture_client_maps_command_failed_without_sftp_read(tmp_path: Pa
|
|||||||
with pytest.raises(TvError) as exc_info:
|
with pytest.raises(TvError) as exc_info:
|
||||||
await client.capture_frame(ssap_request)
|
await client.capture_frame(ssap_request)
|
||||||
assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE
|
assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE
|
||||||
assert transport.read_calls == 0
|
assert len(transport.read_calls) == 0
|
||||||
|
|
||||||
|
|
||||||
async def test_capture_client_maps_sftp_os_error_to_screenshot_unavailable(tmp_path: Path) -> None:
|
async def test_capture_client_maps_sftp_os_error_to_screenshot_unavailable() -> None:
|
||||||
_ = tmp_path
|
transport = FakeCaptureTransport(read_error=OSError("sftp read failed"))
|
||||||
|
client = CaptureClient(transport)
|
||||||
class FakeTransport:
|
|
||||||
async def read_and_remove(
|
|
||||||
self, remote_path: str, timeout: float = 6.0, cleanup_grace: float = 1.5
|
|
||||||
) -> bytes:
|
|
||||||
_ = (remote_path, timeout, cleanup_grace)
|
|
||||||
raise OSError("sftp read failed")
|
|
||||||
|
|
||||||
async def sweep_temp_files(self, prefix: str = "/tmp/lg_smtv_cap_") -> None:
|
|
||||||
_ = prefix
|
|
||||||
|
|
||||||
async def close(self) -> None:
|
|
||||||
return None
|
|
||||||
|
|
||||||
client = CaptureClient(FakeTransport())
|
|
||||||
|
|
||||||
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
_ = (uri, payload)
|
_ = (uri, payload)
|
||||||
@@ -376,23 +419,8 @@ async def test_capture_client_maps_sftp_os_error_to_screenshot_unavailable(tmp_p
|
|||||||
assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE
|
assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE
|
||||||
|
|
||||||
|
|
||||||
async def test_capture_client_maps_timeout_to_screenshot_unavailable(tmp_path: Path) -> None:
|
async def test_capture_client_maps_timeout_to_screenshot_unavailable() -> None:
|
||||||
_ = tmp_path
|
client = CaptureClient(FakeCaptureTransport())
|
||||||
|
|
||||||
class FakeTransport:
|
|
||||||
async def read_and_remove(
|
|
||||||
self, remote_path: str, timeout: float = 6.0, cleanup_grace: float = 1.5
|
|
||||||
) -> bytes:
|
|
||||||
_ = (remote_path, timeout, cleanup_grace)
|
|
||||||
return b"img"
|
|
||||||
|
|
||||||
async def sweep_temp_files(self, prefix: str = "/tmp/lg_smtv_cap_") -> None:
|
|
||||||
_ = prefix
|
|
||||||
|
|
||||||
async def close(self) -> None:
|
|
||||||
return None
|
|
||||||
|
|
||||||
client = CaptureClient(FakeTransport())
|
|
||||||
|
|
||||||
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
_ = (uri, payload)
|
_ = (uri, payload)
|
||||||
@@ -402,3 +430,18 @@ async def test_capture_client_maps_timeout_to_screenshot_unavailable(tmp_path: P
|
|||||||
with pytest.raises(TvError) as exc_info:
|
with pytest.raises(TvError) as exc_info:
|
||||||
await client.capture_frame(ssap_request)
|
await client.capture_frame(ssap_request)
|
||||||
assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE
|
assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE
|
||||||
|
|
||||||
|
|
||||||
|
async def test_capture_client_maps_sftp_timeout_and_cancels_read() -> None:
|
||||||
|
transport = FakeCaptureTransport(block_read=True)
|
||||||
|
client = CaptureClient(transport)
|
||||||
|
|
||||||
|
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 asyncio.wait_for(client.capture_frame(ssap_request), timeout=7.0)
|
||||||
|
|
||||||
|
assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE
|
||||||
|
assert transport.read_cancelled.is_set()
|
||||||
+64
-9
@@ -10,6 +10,7 @@ from contextlib import asynccontextmanager
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
|
import asyncssh
|
||||||
import httpx
|
import httpx
|
||||||
import pytest
|
import pytest
|
||||||
from mcp.server.mcpserver.exceptions import ToolError
|
from mcp.server.mcpserver.exceptions import ToolError
|
||||||
@@ -459,13 +460,17 @@ async def test_server_http_app_allows_authenticated_mcp_initialize_request(
|
|||||||
await asyncio.wait_for(lifespan_task, timeout=2.0)
|
await asyncio.wait_for(lifespan_task, timeout=2.0)
|
||||||
|
|
||||||
|
|
||||||
async def test_server_create_mcp_server_wires_default_capture_client(tmp_path: Path) -> None:
|
async def test_server_create_mcp_server_wires_default_capture_client(
|
||||||
|
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||||
|
) -> None:
|
||||||
import lg_smtv_mcp.server as server_mod
|
import lg_smtv_mcp.server as server_mod
|
||||||
from lg_smtv_mcp.tv_core.capture import AsyncSshCaptureTransport, CaptureClient
|
from lg_smtv_mcp.tv_core.capture import CaptureClient
|
||||||
|
|
||||||
config = _make_config(tmp_path)
|
config = _make_config(tmp_path)
|
||||||
captured: dict[str, Any] = {}
|
captured: dict[str, Any] = {}
|
||||||
original_tv_manager = server_mod.TvManager
|
remote_files: dict[str, bytes] = {}
|
||||||
|
removed_paths: list[str] = []
|
||||||
|
connect_calls: list[dict[str, Any]] = []
|
||||||
|
|
||||||
class DummyManager:
|
class DummyManager:
|
||||||
async def start(self) -> None:
|
async def start(self) -> None:
|
||||||
@@ -474,20 +479,70 @@ async def test_server_create_mcp_server_wires_default_capture_client(tmp_path: P
|
|||||||
async def close(self) -> None:
|
async def close(self) -> None:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
class FakeSftp:
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.closed = False
|
||||||
|
|
||||||
|
async def listdir(self, path: str) -> list[str]:
|
||||||
|
_ = path
|
||||||
|
return []
|
||||||
|
|
||||||
|
async def read(self, path: str) -> bytes:
|
||||||
|
return remote_files[path]
|
||||||
|
|
||||||
|
async def remove(self, path: str) -> None:
|
||||||
|
removed_paths.append(path)
|
||||||
|
remote_files.pop(path, None)
|
||||||
|
|
||||||
|
async def exit(self) -> None:
|
||||||
|
self.closed = True
|
||||||
|
|
||||||
|
sftp_sessions: list[FakeSftp] = []
|
||||||
|
|
||||||
|
class FakeSshConnection:
|
||||||
|
async def start_sftp_client(self) -> FakeSftp:
|
||||||
|
sftp = FakeSftp()
|
||||||
|
sftp_sessions.append(sftp)
|
||||||
|
return sftp
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def wait_closed(self) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
def fake_tv_manager(cfg: Any, **kwargs: Any) -> DummyManager:
|
def fake_tv_manager(cfg: Any, **kwargs: Any) -> DummyManager:
|
||||||
captured["config"] = cfg
|
captured["config"] = cfg
|
||||||
captured["kwargs"] = kwargs
|
captured["kwargs"] = kwargs
|
||||||
return DummyManager()
|
return DummyManager()
|
||||||
|
|
||||||
server_mod.TvManager = fake_tv_manager # type: ignore[assignment]
|
async def fake_connect(**kwargs: Any) -> FakeSshConnection:
|
||||||
try:
|
connect_calls.append(kwargs)
|
||||||
|
return FakeSshConnection()
|
||||||
|
|
||||||
|
monkeypatch.setattr(server_mod, "TvManager", fake_tv_manager)
|
||||||
|
monkeypatch.setattr(asyncssh, "connect", fake_connect)
|
||||||
server_mod.create_mcp_server(config)
|
server_mod.create_mcp_server(config)
|
||||||
finally:
|
|
||||||
server_mod.TvManager = original_tv_manager # type: ignore[assignment]
|
|
||||||
|
|
||||||
assert captured["config"] is config
|
assert captured["config"] is config
|
||||||
assert "capture_client" in captured["kwargs"]
|
assert "capture_client" in captured["kwargs"]
|
||||||
capture_client = captured["kwargs"]["capture_client"]
|
capture_client = captured["kwargs"]["capture_client"]
|
||||||
assert isinstance(capture_client, CaptureClient)
|
assert isinstance(capture_client, CaptureClient)
|
||||||
transport = capture_client._transport # pyright: ignore[reportPrivateUsage]
|
|
||||||
assert isinstance(transport, AsyncSshCaptureTransport)
|
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
assert uri == "ssap://com.webos.service.capture/executeOneShot"
|
||||||
|
remote_files[payload["path"]] = _TEST_JPEG
|
||||||
|
return {"returnValue": True}
|
||||||
|
|
||||||
|
try:
|
||||||
|
result = await capture_client.capture_frame(ssap_request)
|
||||||
|
finally:
|
||||||
|
await capture_client.close()
|
||||||
|
|
||||||
|
assert result.image_bytes == _TEST_JPEG
|
||||||
|
assert len(connect_calls) == 1
|
||||||
|
assert connect_calls[0]["host"] == config.tv_ip
|
||||||
|
assert connect_calls[0]["port"] == 9922
|
||||||
|
assert removed_paths == ["/tmp/lg_smtv_cap_1.jpg"]
|
||||||
|
assert len(sftp_sessions) == 1
|
||||||
|
assert sftp_sessions[0].closed is True
|
||||||
Reference in new issue
Block a user