Compare commits
20
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9bc29f691b | ||
|
|
1e760c51b2 | ||
|
|
a0f798d702 | ||
|
|
128752b71e | ||
|
|
93a572cbb5 | ||
|
|
09618bef3d | ||
|
|
120d3ecf32 | ||
|
|
84ae8b283d | ||
|
|
0d67615817 | ||
|
|
aac00356a1 | ||
|
|
85a5acad35 | ||
|
|
2af3c99e4c | ||
|
|
42bd4edf09 | ||
|
|
5a8ebffad2 | ||
|
|
9195d91d7d | ||
|
|
52ec28f278 | ||
|
|
0bf2923edb | ||
|
|
b2738c0d48 | ||
|
|
ea0c1d9774 | ||
|
|
4af32b993d |
No files matched your search
@@ -11,3 +11,5 @@ ALLOWED_HOSTS=
|
||||
MCP_BEARER_TOKEN=<GENERATE_TOKEN>
|
||||
MAX_VOLUME=40
|
||||
ENABLE_RAW_SSAP=false
|
||||
CAPTURE_MAX_WIDTH=480
|
||||
CAPTURE_JPEG_QUALITY=55
|
||||
@@ -9,8 +9,6 @@ on:
|
||||
jobs:
|
||||
validate:
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: nixery.dev/shell/coreutils/git/nix/nodejs:latest
|
||||
steps:
|
||||
- name: Check out repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
+4
-4
@@ -1,6 +1,6 @@
|
||||
# Architecture
|
||||
|
||||
`lg-smtv-mcp` is a stateful, LLM-free Model Context Protocol (MCP) server for local-network control of a single pre-paired LG webOS Smart TV. This document describes the canonical present-state architecture implemented on `main` (Milestone M1 control plane plus the Milestone M2 Developer Mode capture slice).
|
||||
`lg-smtv-mcp` is a stateful, LLM-free Model Context Protocol (MCP) server for local-network control of a single pre-paired LG webOS Smart TV. This document describes the canonical present-state architecture implemented on `main` (Milestone M1 control plane, Milestone M2 Developer Mode capture & `systemd` packaging, and M2.1 host-side JPEG downscaling).
|
||||
|
||||
## System Overview
|
||||
|
||||
@@ -35,7 +35,7 @@ flowchart LR
|
||||
| SSAP Client | [`tv_core/ssap.py`](src/lg_smtv_mcp/tv_core/ssap.py) | `SsapClient` single-reader `_reader_loop()` multiplexing `msg["id"]` responses and `subscribe` callbacks; 16-permission `register` payload; `1008` and `401` mapping; pending `Future` failure on disconnect. |
|
||||
| Pointer Client | [`tv_core/pointer.py`](src/lg_smtv_mcp/tv_core/pointer.py) | `PointerClient` button allowlist normalization/validation (rejecting `\r`/`\n` and unknown keys), `type:button` framing, pacing, and single mid-batch socket re-acquire. |
|
||||
| TV Manager | [`tv_core/manager.py`](src/lg_smtv_mcp/tv_core/manager.py) | `TvManager` state machine, `send_wol`, `subscribe` state cache (`audio/getStatus`, `getForegroundAppInfo`), `ui_lock` (`25s` timeout), `CLIENT_KEY_PATH` reload on backoff/`SIGHUP`, and tool-backing operations. |
|
||||
| Developer Mode Capture | [`tv_core/capture.py`](src/lg_smtv_mcp/tv_core/capture.py) | `CaptureClient` (`FrameCapturer`) triggers `executeOneShot` and pulls the JPEG; `AsyncSshCaptureTransport` (`CaptureTransport`) lazily opens/reuses the `asyncssh` SFTP session, sweeps stale `/tmp/lg_smtv_cap_*` files while excluding the in-flight capture, and enforces the `6.0s` read deadline plus `1.5s` shielded remove grace. |
|
||||
| Developer Mode Capture | [`tv_core/capture.py`](src/lg_smtv_mcp/tv_core/capture.py) | `CaptureClient` (`FrameCapturer`) triggers `executeOneShot`, pulls the JPEG, and optionally downscales/recompresses via Pillow (`CAPTURE_MAX_WIDTH`, `CAPTURE_JPEG_QUALITY`) before hashing; `AsyncSshCaptureTransport` (`CaptureTransport`) lazily opens/reuses the `asyncssh` SFTP session, maps `KeyImportError` to `SCREENSHOT_UNAVAILABLE`, sweeps stale `/tmp/lg_smtv_cap_*` files while excluding the in-flight capture, and enforces the `6.0s` read deadline plus `1.5s` shielded remove grace. |
|
||||
| HTTP Auth & Security | [`auth.py`](src/lg_smtv_mcp/auth.py) | `BearerAuthMiddleware` (`hmac.compare_digest` on `Authorization: Bearer <token>`) and `build_transport_security_settings` for DNS-rebinding protection. |
|
||||
| MCP Server | [`server.py`](src/lg_smtv_mcp/server.py) | `create_mcp_server` / `create_http_app`, ASGI `lifespan` (`TvManager.start()`/`close()` + `SIGHUP`), `ToolError` mapping, 12 default tools + opt-in `raw_ssap`, `TextContent`/`ImageContent` formatting. |
|
||||
| CLI Entrypoint | [`cli.py`](src/lg_smtv_mcp/cli.py), [`__main__.py`](src/lg_smtv_mcp/__main__.py) | `lg-smtv-mcp serve` (`streamable-http` with fail-closed token check, or `stdio`) and `lg-smtv-mcp pair` (atomic `0600` `.client_key.json` write + optional `--fetch-ssh-key`). |
|
||||
@@ -44,7 +44,7 @@ flowchart LR
|
||||
|
||||
1. **Startup:** `cli.py serve` loads [`TvConfig`](src/lg_smtv_mcp/config.py), requires `MCP_BEARER_TOKEN` for `streamable-http`, builds the ASGI app via [`create_http_app`](src/lg_smtv_mcp/server.py), and starts `uvicorn`. The ASGI `lifespan` starts [`TvManager`](src/lg_smtv_mcp/tv_core/manager.py) and registers `SIGHUP` for `.client_key.json` reload.
|
||||
2. **Steady-state & Subscriptions:** When connected, `SsapClient._reader_loop()` routes incoming frames by `msg["id"]` to either awaiting request `Future`s or `subscribe` handlers updating `TvState` (`volume`, `muted`, `sound_output`, `foreground_app`, `last_updated`).
|
||||
3. **Serialized UI Control:** `send_keys`, `type_text`, and `screenshot` acquire `ui_lock` with a `25s` timeout (`LOCK_TIMEOUT`). `create_mcp_server` default-wires `TvManager(..., capture_client=CaptureClient(AsyncSshCaptureTransport(config)))`, so `capture=True` captures over SFTP; when the capture transport is unavailable (Developer Mode SSH off or expired), `send_keys` and `type_text` return partial success with `capture_error="SCREENSHOT_UNAVAILABLE: ..."` while `screenshot` fails with `SCREENSHOT_UNAVAILABLE`. `TvManager` closes the SFTP session on standby and transport transitions.
|
||||
3. **Serialized UI Control:** `send_keys`, `type_text`, and `screenshot` acquire `ui_lock` with a `25s` timeout (`LOCK_TIMEOUT`). `create_mcp_server` default-wires `TvManager(..., capture_client=CaptureClient(AsyncSshCaptureTransport(config), max_width=config.capture_max_width, jpeg_quality=config.capture_jpeg_quality))`, so `capture=True` captures over SFTP and optionally downscales/recompresses the JPEG in memory; when the capture transport is unavailable (Developer Mode SSH off or expired), `send_keys` and `type_text` return partial success with `capture_error="SCREENSHOT_UNAVAILABLE: ..."` while `screenshot` fails with `SCREENSHOT_UNAVAILABLE`. `TvManager` closes the SFTP session on standby and transport transitions.
|
||||
4. **Shutdown:** ASGI `lifespan` exit removes the `SIGHUP` handler and awaits `TvManager.close()`, tearing down background tasks and open transports cleanly.
|
||||
|
||||
## Boundaries
|
||||
@@ -55,7 +55,7 @@ flowchart LR
|
||||
|
||||
## Dependencies
|
||||
|
||||
- **Runtime (`pyproject.toml` / `flake.nix`):** Python `>=3.14`, `websockets`, `mcp`, `pydantic`, `asyncssh`, `uvicorn`.
|
||||
- **Runtime (`pyproject.toml` / `flake.nix`):** Python `>=3.14`, `websockets`, `mcp`, `pydantic`, `asyncssh`, `uvicorn`, `pillow`.
|
||||
- **Development / Verification:** `pytest`, `pytest-asyncio`, `httpx`, `ruff`, `pyright` (strict mode).
|
||||
|
||||
## Architectural Constraints
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
# lg-smtv-mcp
|
||||
|
||||
[](https://m8ven.ai/mcp/kiskaadee-lg-smtv-mcp-1hkv9o?s=readme)
|
||||
|
||||
A Python Model Context Protocol (MCP) server for persistent, local-network control of LG webOS Smart TVs.
|
||||
|
||||
`lg-smtv-mcp` provides an agent-friendly control plane over LG's Simple Service Access Protocol (SSAP), combining persistent WebSocket connections, remote pointer button input, subscription-based device state tracking, Wake-on-LAN recovery, and optional Developer Mode screenshot capture.
|
||||
|
||||
The server is deliberately **LLM-free**: it exposes bounded, deterministic operations so external AI agents (such as Antigravity, Claude, or a vision-guided decision loop) can reason over UI state and control the television without embedding model APIs into the daemon.
|
||||
|
||||
> **Status: M2 delivered — capture, E2E hardening, and `systemd` deployment.**
|
||||
> Configuration validation, error taxonomy, [`tv_core`](src/lg_smtv_mcp/tv_core/) (SSAP multiplexer, `PointerClient`, `TvManager`), FastMCP server & Bearer auth ([`server.py`](src/lg_smtv_mcp/server.py), [`auth.py`](src/lg_smtv_mcp/auth.py)), `pair` / `serve` CLI ([`cli.py`](src/lg_smtv_mcp/cli.py)), full-stack offline E2E verification ([`test_e2e_mvp.py`](tests/test_e2e_mvp.py)), and Developer Mode SFTP screenshot capture ([`capture.py`](src/lg_smtv_mcp/tv_core/capture.py)) are implemented and tested. Milestone M2 is delivered; `systemd` unit sandboxing hardening is tracked separately in [#17](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/issues/17).
|
||||
> **Status: M2 delivered — M2.1 live-TV polish in progress.**
|
||||
> Configuration validation, error taxonomy, [`tv_core`](src/lg_smtv_mcp/tv_core/) (SSAP multiplexer, `PointerClient`, `TvManager`), FastMCP server & Bearer auth ([`server.py`](src/lg_smtv_mcp/server.py), [`auth.py`](src/lg_smtv_mcp/auth.py)), `pair` / `serve` CLI ([`cli.py`](src/lg_smtv_mcp/cli.py)), full-stack offline E2E verification ([`test_e2e_mvp.py`](tests/test_e2e_mvp.py)), Developer Mode SFTP screenshot capture with optional host-side JPEG downscaling ([`capture.py`](src/lg_smtv_mcp/tv_core/capture.py)), and `systemd` unit sandboxing hardening ([#17](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/issues/17)) are implemented on `main`. Ongoing M2.1 polish is tracked in [ROADMAP.md](ROADMAP.md).
|
||||
|
||||
---
|
||||
|
||||
@@ -61,7 +63,8 @@ Implementation is tracked on the [Project Pipeline](https://gitea.roadtotech.me/
|
||||
| Milestone | Scope | Status |
|
||||
| :--- | :--- | :--- |
|
||||
| **M1** | Core config, `tv_core` engine, FastMCP tools, Bearer auth, `pair`/`serve` CLI, E2E verification | Complete (`#1`–`#4` merged on `main`) |
|
||||
| **M2** | Developer Mode SFTP screenshot capture (`asyncssh`), systemd unit, E2E test hardening | Delivered — capture (`#12`), E2E hardening (`#11`), and systemd deployment (`#13`); unit sandboxing hardening tracked in `#17` |
|
||||
| **M2** | Developer Mode SFTP screenshot capture (`asyncssh`), systemd unit, E2E test hardening, sandboxing | Complete (`#11`–`#13`, `#17` merged on `main`) |
|
||||
| **M2.1** | Host-side JPEG downscaling (`#20`), immediate `turn_off` standby (`#21`), Nix sandbox tests (`#22`), settle retry (`#23`) | In progress (`#20` merged; `#21`–`#23` open) |
|
||||
|
||||
Implemented in [`TvManager`](src/lg_smtv_mcp/tv_core/manager.py) and exposed via [`server.py`](src/lg_smtv_mcp/server.py):
|
||||
- Persistent SSAP multiplexing and `subscribe`-backed state snapshots (`get_state`: `volume`, `muted`, `sound_output`, `foreground_app`)
|
||||
@@ -71,13 +74,19 @@ Implemented in [`TvManager`](src/lg_smtv_mcp/tv_core/manager.py) and exposed via
|
||||
|
||||
---
|
||||
|
||||
## Requirements & Tested Hardware
|
||||
## Prerequisites & Tested Hardware
|
||||
|
||||
- **Runtime:** Python 3.14+ (or Nix with Flakes enabled)
|
||||
- **Hardware:** An LG webOS Smart TV reachable on the local network (with Wake-on-LAN and LG Connect Apps enabled for power-on and SSAP control)
|
||||
- **Optional:** LG Developer Mode enabled for SSH/SFTP screenshot capture
|
||||
Before running the server, make sure you have:
|
||||
|
||||
Initial protocol exploration and empirical verification were performed against:
|
||||
- **Host Runtime:** Nix with Flakes enabled (recommended) or Python `3.14+`
|
||||
- **Network:** Host and LG webOS Smart TV on the **same local network** (Wake-on-LAN uses UDP broadcast; SSAP uses `wss://<TV_IP>:3001`)
|
||||
- **LG webOS TV Settings:**
|
||||
- **LG Connect Apps** enabled (*Settings -> General -> Devices -> External Devices -> LG Connect Apps*, or *Network -> LG Connect Apps* depending on webOS version)
|
||||
- **Wake-on-LAN / Mobile TV On** enabled (*Turn On via Wi-Fi / Network*) if you want `tv_wake` to power on the TV from standby
|
||||
- **Static IP / DHCP reservation** (recommended) and the TV's **MAC address**
|
||||
- **Optional (for Screenshots):** An LG Developer account and the **Developer Mode** app installed on the TV with **Dev Mode Status** and **Key Server** enabled (SSH/SFTP on port `9922`)
|
||||
|
||||
Initial protocol exploration and live-TV verification were performed against:
|
||||
- **Device:** `65UR8750PSA`
|
||||
- **Platform:** `WebOS/4.1.0`
|
||||
|
||||
@@ -85,9 +94,11 @@ Compatibility with other LG webOS models and firmware versions has not yet been
|
||||
|
||||
---
|
||||
|
||||
## Development Setup
|
||||
## Getting Started (Step-by-Step)
|
||||
|
||||
This repository uses Nix Flakes ([flake.nix](flake.nix)) for reproducible environments:
|
||||
### Step 1: Prepare the Host Environment
|
||||
|
||||
Clone the repository and enter the Nix devShell ([`flake.nix`](flake.nix)):
|
||||
|
||||
```bash
|
||||
git clone https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp.git
|
||||
@@ -97,33 +108,84 @@ nix develop
|
||||
|
||||
If you use `direnv`, run `direnv allow` to activate [`.envrc`](.envrc) automatically.
|
||||
|
||||
The shell provisions Python 3.14, `websockets`, `mcp`, `pydantic`, `asyncssh`, `uvicorn`, `httpx`, `pytest`, `pytest-asyncio`, `ruff`, and `pyright`, and configures `.githooks/` as the Git hooks path.
|
||||
The shell provisions Python 3.14, `websockets`, `mcp`, `pydantic`, `asyncssh`, `uvicorn`, `pillow`, `httpx`, `pytest`, `pytest-asyncio`, `ruff`, and `pyright`, and configures `.githooks/` as the Git hooks path.
|
||||
|
||||
---
|
||||
> **Note:** Inside `nix develop`, run commands using `python -m lg_smtv_mcp <subcommand>` (or `nix run . -- <subcommand>`), as the devShell provisions the Python environment directly rather than installing package console scripts to `PATH`.
|
||||
|
||||
## Configuration
|
||||
### Step 2: Create and Configure `.env`
|
||||
|
||||
Runtime configuration is loaded by [`load_config()`](src/lg_smtv_mcp/config.py) from process environment variables with `.env` fallback (existing process environment variables always take precedence). See [`.env.example`](.env.example):
|
||||
Copy [`.env.example`](.env.example) to `.env` and fill in your TV's IP, MAC address, and a freshly generated Bearer token (never commit `.env`, `.client_key.json`, or SSH keys):
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
openssl rand -hex 32 # use output as MCP_BEARER_TOKEN
|
||||
```
|
||||
|
||||
Edit `.env` with your TV's local network coordinates and a generated Bearer token (never commit `.env` or `.client_key.json`):
|
||||
Minimal `.env` for local use:
|
||||
|
||||
```dotenv
|
||||
TV_IP=<TV_IP>
|
||||
TV_MAC=<TV_MAC>
|
||||
MCP_BEARER_TOKEN=<GENERATE_TOKEN>
|
||||
MCP_BEARER_TOKEN=<GENERATED_TOKEN>
|
||||
HOST=127.0.0.1
|
||||
PORT=8765
|
||||
MAX_VOLUME=40
|
||||
```
|
||||
|
||||
If you enable Developer Mode screenshots, also consider setting `CAPTURE_MAX_WIDTH=480` and `CAPTURE_JPEG_QUALITY=55` (as in [`.env.example`](.env.example)) so screenshots stay compact enough for inline MCP delivery without disk offloading.
|
||||
|
||||
### Step 3: Pair with the TV (One-Time)
|
||||
|
||||
Power **on** the TV and ensure *LG Connect Apps* is enabled. Then run:
|
||||
|
||||
```bash
|
||||
python -m lg_smtv_mcp pair
|
||||
# Or override TV_IP:
|
||||
python -m lg_smtv_mcp pair --ip <TV_IP>
|
||||
```
|
||||
|
||||
If you also want **Developer Mode screenshot capture**, enable *Developer Mode* and *Key Server* in the TV's Developer Mode app first, then run:
|
||||
|
||||
```bash
|
||||
python -m lg_smtv_mcp pair --fetch-ssh-key
|
||||
```
|
||||
|
||||
Accept the pairing prompt on the TV screen using your physical remote:
|
||||
- The SSAP client key is saved atomically with `0600` permissions to `CLIENT_KEY_PATH` (default `.client_key.json`).
|
||||
- `--fetch-ssh-key` downloads the Developer Mode private key from `http://<TV_IP>:9991/webos_rsa` and saves it with `0600` permissions (default `.webos_rsa`). Set `SSH_KEY_PATH=.webos_rsa` (and `WEBOS_SSH_PASSPHRASE` if configured) in `.env`.
|
||||
|
||||
### Step 4: Start the MCP Server
|
||||
|
||||
```bash
|
||||
# Default: persistent Streamable HTTP daemon at http://<HOST>:<PORT>/mcp
|
||||
# Requires Authorization: Bearer <MCP_BEARER_TOKEN>
|
||||
python -m lg_smtv_mcp serve
|
||||
|
||||
# Local testing over stdio (no HTTP Bearer token required)
|
||||
python -m lg_smtv_mcp serve --transport stdio
|
||||
```
|
||||
|
||||
If you re-pair while `serve` is running, send `SIGHUP` to reload `.client_key.json` without restarting the daemon.
|
||||
|
||||
### Step 5: Connect Your MCP Client
|
||||
|
||||
Point your MCP host/client at the Streamable HTTP endpoint:
|
||||
|
||||
- **URL:** `http://<HOST>:<PORT>/mcp` (default `http://127.0.0.1:8765/mcp`)
|
||||
- **Header:** `Authorization: Bearer <MCP_BEARER_TOKEN>`
|
||||
|
||||
If your MCP client runs on a different machine than the server, set **both** `HOST=0.0.0.0` (or the server's LAN IP) **and** `ALLOWED_HOSTS=<server-lan-ip-or-hostname>` in `.env`, and place the server behind an HTTPS reverse proxy or encrypted tunnel (e.g., WireGuard/Tailscale) if crossing untrusted networks.
|
||||
|
||||
---
|
||||
|
||||
## Configuration Reference
|
||||
|
||||
Runtime configuration is loaded by [`load_config()`](src/lg_smtv_mcp/config.py) from process environment variables with `.env` fallback (existing process environment variables always take precedence).
|
||||
|
||||
| Variable | Purpose | Default / Requirement |
|
||||
| :--- | :--- | :--- |
|
||||
| `TV_IP` | Target TV IPv4 address | Required |
|
||||
| `TV_MAC` | Target TV MAC address for Wake-on-LAN | Required for `wake` |
|
||||
| `TV_MAC` | Target TV MAC address for Wake-on-LAN | Required for `tv_wake` |
|
||||
| `WOL_BROADCAST` | Wake-on-LAN UDP broadcast IPv4 address | `255.255.255.255` |
|
||||
| `CLIENT_KEY_PATH` | SSAP pairing client-key JSON path | `.client_key.json` |
|
||||
| `SSH_KEY_PATH` | Optional Developer Mode SSH private key path | Unset |
|
||||
@@ -135,33 +197,8 @@ MAX_VOLUME=40
|
||||
| `MCP_BEARER_TOKEN` | Bearer token for `streamable-http` transport | Required for HTTP |
|
||||
| `MAX_VOLUME` | Upper bound guardrail (`0..100`) for `set_volume` | `40` |
|
||||
| `ENABLE_RAW_SSAP` | Enables optional `raw_ssap` pass-through (`true`/`false`) | `false` |
|
||||
|
||||
---
|
||||
|
||||
## Running the MVP Server (`pair` & `serve`)
|
||||
|
||||
1. **Pair with the TV (one-time per TV):** Ensure the TV is powered on with *LG Connect Apps* enabled, then run:
|
||||
|
||||
```bash
|
||||
lg-smtv-mcp pair
|
||||
# Optional: override IP or also fetch Developer Mode SSH key
|
||||
lg-smtv-mcp pair --ip <TV_IP>
|
||||
```
|
||||
|
||||
Accept the pairing prompt on the TV screen. The client key is saved atomically with `0600` permissions to `CLIENT_KEY_PATH` (default `.client_key.json`).
|
||||
|
||||
2. **Start the MCP server:**
|
||||
|
||||
```bash
|
||||
# Default: persistent Streamable HTTP daemon at http://<HOST>:<PORT>/mcp
|
||||
# Requires Authorization: Bearer <MCP_BEARER_TOKEN>
|
||||
lg-smtv-mcp serve
|
||||
|
||||
# Local testing over stdio (no HTTP Bearer token required)
|
||||
lg-smtv-mcp serve --transport stdio
|
||||
```
|
||||
|
||||
If you re-pair while `serve` is running, send `SIGHUP` to reload `.client_key.json` without restarting the daemon.
|
||||
| `CAPTURE_MAX_WIDTH` | Optional max width (`64..3840`) for host-side JPEG downscaling | Unset (raw passthrough) |
|
||||
| `CAPTURE_JPEG_QUALITY` | Optional JPEG quality (`1..95`; defaults to `75` if only `CAPTURE_MAX_WIDTH` is set) | Unset (raw passthrough) |
|
||||
|
||||
---
|
||||
|
||||
@@ -189,6 +226,25 @@ The repository includes a unit template at [`deploy/lg-smtv-mcp.service`](deploy
|
||||
|
||||
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. When exposing the server remotely, set **both** `HOST=0.0.0.0` (or the LAN bind address) **and** `ALLOWED_HOSTS=<proxy-or-vpn-hostname>` in `.env`; the DNS-rebinding check in `auth.py` rejects any request whose `Host` header is not in the allowlist.
|
||||
|
||||
### Sandboxing & Security Profile
|
||||
|
||||
The unit template includes a tested systemd sandboxing baseline (Issue [#17](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/issues/17)), reducing the `systemd-analyze --offline=yes security` exposure score from **9.0 UNSAFE** to **4.9 OK**:
|
||||
|
||||
- **Adopted Directives:**
|
||||
- `StartLimitIntervalSec=60s` / `StartLimitBurst=5`: Bounded restart budget prevents runaway restart loops on persistent environment errors (e.g. missing `.env`).
|
||||
- `NoNewPrivileges=yes`: Prevents process escalation or setuid execution.
|
||||
- `PrivateTmp=yes`: Restricts `/tmp` visibility to an isolated per-service namespace.
|
||||
- `UMask=0077`: Ensures files created by the service are private to the service user.
|
||||
- `ProtectSystem=full`: Mounts `/usr`, `/boot`, and `/etc` read-only.
|
||||
- `ProtectControlGroups=yes`, `ProtectKernelModules=yes`, `ProtectKernelTunables=yes`, `ProtectKernelLogs=yes`, `ProtectClock=yes`, `ProtectHostname=yes`: Prevents tampering with kernel and OS interfaces.
|
||||
- `RestrictRealtime=yes`, `RestrictSUIDSGID=yes`, `LockPersonality=yes`: Restricts privilege escalation vectors.
|
||||
- `CapabilityBoundingSet=`: Drops all Linux kernel capabilities.
|
||||
|
||||
- **Rejected Directives (Compatibility Constraints):**
|
||||
- `ProtectHome=yes` / `ProtectHome=read-only`: Ruled out because `nix develop` requires read-write access to `~/.cache/nix/fetcher-locks` for flake evaluation, and the repository checkout resides under the operator's user directory.
|
||||
- `ProtectSystem=strict`: Ruled out because it mounts the entire filesystem read-only, including the operator's home directory and the repository checkout; `nix develop` needs write access to `~/.cache/nix/fetcher-locks` for flake evaluation (the same constraint that rules out `ProtectHome`). Writable `/tmp` is not the blocker: with `PrivateTmp=yes`, systemd keeps `/tmp` and `/var/tmp` writable even under `strict`.
|
||||
- `PrivateNetwork=yes`: Ruled out because the MCP daemon must communicate over the local network to the TV via SSAP (`wss://:3001`), Developer Mode SSH/SFTP (`:9922`), and Wake-on-LAN UDP broadcasts.
|
||||
|
||||
### 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:
|
||||
@@ -203,9 +259,9 @@ On a trusted home LAN, SSH host-key checking is disabled by default because the
|
||||
|
||||
## 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 `python -m lg_smtv_mcp serve`:
|
||||
|
||||
- [ ] **`pair`**: Run `lg-smtv-mcp pair`, accept the on-screen TV prompt, and confirm `CLIENT_KEY_PATH` (`.client_key.json`) exists with `0600` permissions and an entry for `<TV_IP>`.
|
||||
- [ ] **`pair`**: Run `python -m lg_smtv_mcp pair`, accept the on-screen TV prompt, and confirm `CLIENT_KEY_PATH` (`.client_key.json`) exists with `0600` permissions and an entry for `<TV_IP>`.
|
||||
- [ ] **`tv_wake`**: With the TV in standby, verify a mutating tool (`launch`) fails fast with `TV_OFFLINE_STANDBY` (no implicit WoL), then call `tv_wake` and confirm the TV powers on and returns `status: "connected"`.
|
||||
- [ ] **`get_state`**: Call `get_state` and confirm `connected: true`, `stale: false`, and live `volume`, `muted`, `sound_output`, and `foreground_app` values.
|
||||
- [ ] **`launch`**: Call `launch` (e.g., `app_id="youtube.leanback.v4"` with an optional `content_target`) and confirm the app opens on screen.
|
||||
@@ -241,9 +297,10 @@ nix flake check
|
||||
## Documentation
|
||||
|
||||
- [Architecture](ARCHITECTURE.md) — Canonical present-state system topology, components, and boundaries
|
||||
- [Roadmap](ROADMAP.md) — Completed M1/M2 milestones and remaining M2 delivery trajectory
|
||||
- [Roadmap](ROADMAP.md) — Completed M1/M2 milestones and active M2.1 delivery trajectory
|
||||
- [Decision Records](docs/adr/) — MADR records for core architectural choices (`0001`–`0005`)
|
||||
- [Architecture & Design RFC](docs/designs/lg-smtv-mcp.md) — Component contracts, state machine, error taxonomy, and implementation plan
|
||||
- [E2E Benchmarks](docs/experiments/crunchyroll-e2e-comparison.md) — Standardized live-TV Crunchyroll navigation telemetry (baseline vs. post-`#20`)
|
||||
- [Verified Capabilities](docs/poc/capabilities.md) — Empirical SSAP, DIAL, deep-link, and Developer Mode findings
|
||||
- [Crunchyroll E2E Experiment](docs/poc/crunchyroll-e2e-experiment.md) — Initial vision-guided navigation experiment and latency measurements
|
||||
- [Agent & Engineering Guidelines](AGENTS.md) — Coding standards, validation boundaries, protocol invariants, and CI rules
|
||||
|
||||
+14
-9
@@ -2,22 +2,27 @@
|
||||
|
||||
## 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 the M2 capture and E2E-hardening slices. Remaining M2 work is deployment packaging and its `systemd` hardening follow-up.
|
||||
`lg-smtv-mcp` has completed Milestone M2 (capture, E2E hardening, and systemd deployment packaging) and `#17` (`systemd` sandboxing hardening). Active work is **Milestone M2.1: Live-TV Polish & Latency Optimizations** (1/4 complete), focused on reducing screenshot payload size/round-trips, fixing immediate `turn_off()` standby transitions, and unblocking `systemd-analyze` checks in the Nix sandbox.
|
||||
|
||||
## Near Term (Milestone M2)
|
||||
## Near Term
|
||||
|
||||
- **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 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
|
||||
|
||||
- **Live-TV Operator Smoke Verification:** Execute the manual LAN smoke checklist in [`README.md`](README.md#operator-live-tv-e2e-smoke-test-checklist) and Developer Mode capture verification against the target `WebOS/4.1.0` TV.
|
||||
- **#21 (`M2.1`):** `fix(manager): transition to STANDBY_OFFLINE immediately on turn_off()` so immediate `tv_wake()` calls do not return `already_connected` before the TV drops `1008`.
|
||||
- **#22 (`M2.1`):** `fix(test): unblock systemd-analyze tests inside Nix build sandbox` (investigate `--root=<tmp_path>` or narrow sandbox-only skip while keeping `nix develop` enforcement strict).
|
||||
- **#23 (`M2.1`):** `feat(capture): add optional wait_for_change settle retry on keys/type_text capture` (500ms bounded retry within the shared 6.0s capture budget when `changed_since_last=false`).
|
||||
|
||||
## Completed
|
||||
|
||||
### M2: Capture & E2E Hardening (partial, 2026-11-16)
|
||||
### M2.1: Live-TV Polish & Latency Optimizations (In Progress — Completed Items)
|
||||
- **#20 (PR [#24](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/24), Completed 2026-11-19):** Added optional `CAPTURE_MAX_WIDTH` (`64..3840`) and `CAPTURE_JPEG_QUALITY` (`1..95`) settings in [`config.py`](src/lg_smtv_mcp/config.py), added `pillow` runtime dependency, and implemented host-side JPEG downscaling/recompression in [`capture.py`](src/lg_smtv_mcp/tv_core/capture.py) (reducing median live-TV capture size by 69.1% and disk-only offloads from 60% to 7%).
|
||||
- **Live-TV E2E Benchmarks (`0d67615`, `84ae8b2`, `128752b`):** Executed standardized Crunchyroll E2E navigation benchmarks against `65UR8750PSA` (`WebOS/4.1.0`) and recorded baseline vs. post-`#20` telemetry in [`docs/experiments/`](docs/experiments/).
|
||||
|
||||
### Post-M2 Hardening (Completed 2026-11-18)
|
||||
- **#17 (PR [#18](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/18)):** Hardened [`deploy/lg-smtv-mcp.service`](deploy/lg-smtv-mcp.service) with bounded restart throttling (`StartLimitIntervalSec=60s`, `StartLimitBurst=5`) and a 14-directive sandboxing baseline (`9.0 UNSAFE` → `4.9 OK`), added automated `systemd-analyze` tests in [`tests/test_deploy.py`](tests/test_deploy.py), documented adopted/rejected directives in [`README.md`](README.md#sandboxing--security-profile), and fixed `asyncssh` SFTP capture reads (`sftp.open()`) in [`src/lg_smtv_mcp/tv_core/capture.py`](src/lg_smtv_mcp/tv_core/capture.py).
|
||||
|
||||
### M2: Capture, E2E Hardening & Systemd Deployment (Completed 2026-11-17)
|
||||
- **#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`.
|
||||
- **#13 (PR [#16](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/16)):** `deploy/lg-smtv-mcp.service` systemd template, deployment + Developer Mode SSH setup docs in `README.md`, and DNS-rebinding / PATH env guidance.
|
||||
|
||||
### 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.
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
Description=LG webOS Smart TV MCP server
|
||||
Wants=network-online.target
|
||||
After=network-online.target
|
||||
StartLimitIntervalSec=60s
|
||||
StartLimitBurst=5
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
@@ -13,5 +15,21 @@ ExecStart=/usr/bin/env nix develop --command python -m lg_smtv_mcp serve
|
||||
Restart=on-failure
|
||||
RestartSec=5s
|
||||
|
||||
# Sandboxing baseline (Issue #17)
|
||||
NoNewPrivileges=yes
|
||||
PrivateTmp=yes
|
||||
UMask=0077
|
||||
ProtectSystem=full
|
||||
ProtectControlGroups=yes
|
||||
ProtectKernelModules=yes
|
||||
ProtectKernelTunables=yes
|
||||
ProtectKernelLogs=yes
|
||||
ProtectClock=yes
|
||||
ProtectHostname=yes
|
||||
RestrictRealtime=yes
|
||||
RestrictSUIDSGID=yes
|
||||
LockPersonality=yes
|
||||
CapabilityBoundingSet=
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
+12
-18
@@ -3,7 +3,7 @@
|
||||
* **Author:** kiskaadee
|
||||
* **Status:** Approved
|
||||
* **Date:** 2026-11-15
|
||||
* **Last reconciled:** 2026-11-16 (M2 `#12` / PR [#15](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/15) merged)
|
||||
* **Last reconciled:** 2026-11-21 (M2.1 `#20` / PR [#24](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/24) merged on `main`)
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
@@ -77,12 +77,12 @@ All runtime code lives under `src/lg_smtv_mcp/`, separating the transport/protoc
|
||||
|
||||
| Module | Responsibility |
|
||||
| :--- | :--- |
|
||||
| [`src/lg_smtv_mcp/config.py`](../../src/lg_smtv_mcp/config.py) | Frozen Pydantic v2 `TvConfig` (`extra="forbid"`) loaded from env vars / `.env` (`TV_IP`, `TV_MAC`, `WOL_BROADCAST`, `CLIENT_KEY_PATH`, `SSH_KEY_PATH`, `WEBOS_SSH_PASSPHRASE`, `SSH_KNOWN_HOSTS_PATH`, `HOST`, `PORT`, `ALLOWED_HOSTS`, `MCP_BEARER_TOKEN`, `MAX_VOLUME`, `ENABLE_RAW_SSAP`), raising `ConfigError` on invalid operator config. |
|
||||
| [`src/lg_smtv_mcp/config.py`](../../src/lg_smtv_mcp/config.py) | Frozen Pydantic v2 `TvConfig` (`extra="forbid"`) loaded from env vars / `.env` (`TV_IP`, `TV_MAC`, `WOL_BROADCAST`, `CLIENT_KEY_PATH`, `SSH_KEY_PATH`, `WEBOS_SSH_PASSPHRASE`, `SSH_KNOWN_HOSTS_PATH`, `HOST`, `PORT`, `ALLOWED_HOSTS`, `MCP_BEARER_TOKEN`, `MAX_VOLUME`, `ENABLE_RAW_SSAP`, `CAPTURE_MAX_WIDTH`, `CAPTURE_JPEG_QUALITY`), raising `ConfigError` on invalid operator config. |
|
||||
| [`src/lg_smtv_mcp/errors.py`](../../src/lg_smtv_mcp/errors.py) | `ConfigError` for startup/config failures and `TvError(ErrorCode, message)` for runtime TV/tool errors (`TV_OFFLINE_STANDBY`, `PAIRING_REQUIRED`, `SCREENSHOT_UNAVAILABLE`, `LOCK_TIMEOUT`, `WAKE_TIMEOUT`, `COMMAND_FAILED`, `INVALID_ARGUMENT`). |
|
||||
| [`src/lg_smtv_mcp/tv_core/protocols.py`](../../src/lg_smtv_mcp/tv_core/protocols.py) | Python `Protocol` interfaces (`WebSocketTransport`, `WebSocketConnectFn`, `WebSocketClosedError`, `CaptureTransport`, `FrameCapturer`) and frozen result dataclasses enabling offline contract tests. |
|
||||
| [`src/lg_smtv_mcp/tv_core/ssap.py`](../../src/lg_smtv_mcp/tv_core/ssap.py) | `SsapClient`: single background reader task routing frames by `msg["id"]` to `asyncio.Future`s and `subscribe` callbacks; `PERMISSIONS` constant; `register` + `1008` detection; WebSocket keepalive and pending-`Future` cleanup on disconnect. |
|
||||
| [`src/lg_smtv_mcp/tv_core/pointer.py`](../../src/lg_smtv_mcp/tv_core/pointer.py) | `PointerClient`: acquires `getPointerInputSocket`, normalizes/validates keys, sends plain-text `type:button` frames, and automatically re-acquires the socket if dropped. |
|
||||
| [`src/lg_smtv_mcp/tv_core/capture.py`](../../src/lg_smtv_mcp/tv_core/capture.py) | `CaptureClient` (implementing `FrameCapturer`) and `AsyncSshCaptureTransport` (implementing `CaptureTransport`): calls `executeOneShot` via `ssap_request_fn`, lazily opens/reuses the `asyncssh` SFTP session (`read_and_remove`, `sweep_temp_files`, `close`), excludes the in-flight capture from each session sweep, enforces the shared deadline and shielded cleanup, and tracks `frame_sha256` / `changed_since_last`. |
|
||||
| [`src/lg_smtv_mcp/tv_core/capture.py`](../../src/lg_smtv_mcp/tv_core/capture.py) | `CaptureClient` (implementing `FrameCapturer`) and `AsyncSshCaptureTransport` (implementing `CaptureTransport`): calls `executeOneShot` via `ssap_request_fn`, lazily opens/reuses the `asyncssh` SFTP session (`read_and_remove`, `sweep_temp_files`, `close`), maps `KeyImportError` to `SCREENSHOT_UNAVAILABLE`, excludes the in-flight capture from each session sweep, enforces the shared deadline and shielded cleanup, optionally downscales/recompresses JPEGs (`max_width`, `jpeg_quality`) via Pillow, and tracks `frame_sha256` / `changed_since_last`. |
|
||||
| [`src/lg_smtv_mcp/tv_core/manager.py`](../../src/lg_smtv_mcp/tv_core/manager.py) | `TvManager`: single-owner connection loop + state machine, `send_wol` helper, `subscribe` state cache, stepped reconnect backoff, `FrameCapturer` teardown on `STANDBY_OFFLINE`, `.client_key.json` reload on `PAIRING_REQUIRED` backoff/`SIGHUP`, and `ui_lock` (`25s` acquire timeout) serializing UI/capture operations. |
|
||||
| [`src/lg_smtv_mcp/auth.py`](../../src/lg_smtv_mcp/auth.py) | ASGI Bearer token middleware (`hmac.compare_digest` on `Authorization: Bearer <token>`) wrapping FastMCP's `streamable_http_app()` and `TransportSecuritySettings`. |
|
||||
| [`src/lg_smtv_mcp/server.py`](../../src/lg_smtv_mcp/server.py) | FastMCP (`MCPServer`) tool definitions, `ImageContent` formatting, partial-success shaping, `max_volume` enforcement, `ENABLE_RAW_SSAP` gating, and ASGI `lifespan` wiring for `TvManager` + `SIGHUP`. |
|
||||
@@ -267,7 +267,7 @@ All tools return structured JSON payloads (plus inline MCP `ImageContent` when `
|
||||
|
||||
## Detailed Implementation Plan
|
||||
|
||||
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`).
|
||||
Milestone M1 foundations (`#1`–`#4`), all Milestone M2 slices (`#11`, `#12`, `#13`), and the post-M2 `systemd` unit sandboxing hardening follow-up ([#17](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/issues/17), PR [#18](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/18)) are implemented, verified, and merged on `main`. The completed baselines are summarized for reference below.
|
||||
|
||||
### Completed Milestone M1 Baseline (`#1`–`#4`, Merged on `main`)
|
||||
|
||||
@@ -278,7 +278,7 @@ Milestone M1 foundations (`#1`–`#4`) and the M2 capture/E2E slices (`#11`, `#1
|
||||
|
||||
---
|
||||
|
||||
### Completed Milestone M2 Slices (`#11`, `#12` — Merged on `main`)
|
||||
### Completed Milestone M2 Slices (`#11`, `#12`, `#13` — Merged on `main`)
|
||||
|
||||
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).
|
||||
|
||||
@@ -328,21 +328,15 @@ Delivered by `#12` (PR [#15](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/p
|
||||
* 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`.
|
||||
#### 5. `deploy/lg-smtv-mcp.service` and `README.md` (Completed — Issue `#13`, PR [#16](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/16))
|
||||
|
||||
---
|
||||
* **Type / Scope:** Systemd unit template and operator deployment documentation.
|
||||
* **Delivered Changes:**
|
||||
* Created `deploy/lg-smtv-mcp.service` template invoking `nix develop --command python -m lg_smtv_mcp serve` with `<User>`, `<WorkingDirectory>`, `EnvironmentFile`, `Restart=on-failure`, and `PATH` containing `<NixBinDir>`.
|
||||
* Updated `README.md` with `systemd` setup instructions, Developer Mode pairing workflow (`python -m lg_smtv_mcp pair --fetch-ssh-key`), DNS-rebinding host configuration (`HOST` + `ALLOWED_HOSTS`), and live-TV operator smoke checklist items.
|
||||
* Follow-up unit sandboxing hardening was delivered in issue [#17](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/issues/17) (PR [#18](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/18)), adding bounded restart limits, a 14-directive sandboxing baseline (`9.0 UNSAFE` → `4.9 OK`), automated `systemd-analyze` verification in `tests/test_deploy.py`, and the `asyncssh` SFTP `open()` capture fix.
|
||||
|
||||
### 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.
|
||||
* **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`.
|
||||
* 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.
|
||||
|
||||
* **M2 Completion Checkpoint:** `nix develop --command bash -c "ruff check . && ruff format --check . && pyright && pytest"` and `nix flake check`.
|
||||
* **M2 Delivery Checkpoint:** All checks (`ruff`, `pyright`, `pytest`, `nix flake check`) passed; PR #16 merged on `main`.
|
||||
|
||||
### Verification Plan
|
||||
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
# Standardized E2E Benchmark Baseline (`main` @ `0d67615`)
|
||||
|
||||
Standardized pre-#20/#23 baseline executed using [`e2e-benchmark-template.md`](e2e-benchmark-template.md) by subagent `281cc834-58db-4ed5-9d9c-21b1dfd34d67` against `65UR8750PSA` (`WebOS/4.1.0`).
|
||||
|
||||
## Preconditions
|
||||
|
||||
- **Commit / Branch:** `0d67615` (`main`)
|
||||
- **Server Config:** `CAPTURE_MAX_WIDTH=unset`, `CAPTURE_JPEG_QUALITY=unset`
|
||||
- **TV Starting State:** Powered ON at Live TV (`com.webos.app.livetv`), Crunchyroll closed.
|
||||
- **Timer Boundary:** `T0 = 10:15:27.472`, `T_end = 10:17:55.874` (`-05:00`, excluding initial schema `read_file` setup).
|
||||
|
||||
---
|
||||
|
||||
## Normalized Scorecard
|
||||
|
||||
| Metric | Unstandardized Run (`aac0035`) | Standardized Baseline (`0d67615`) | Notes |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| **Total Timed Span (`T0 -> T_end`)** | `4m 38s` (`278s`, incl. `tv_wake`) | `2m 28s` (`148.40s`) | Zero-waste path via fixed runbook |
|
||||
| **Total Steps / Captures** | `21` / `15` | `13` / `10` | `3` non-capture + `10` capture calls |
|
||||
| **Median Capture Size (B)** | `22,824 B` | `19,045 B` | Range: `8,787 B` – `92,524 B` |
|
||||
| **Disk-Only Offloads (`read_file` turns)** | `11` / `15` | `6` / `10` | All `>= 15,744 B` offloaded; all `<= 9,652 B` stayed inline |
|
||||
| **Wasted / Retry Steps** | `4` | `0` | — |
|
||||
|
||||
---
|
||||
|
||||
## Step-by-Step Telemetry Table
|
||||
|
||||
| Step # | `T+elapsed` | Tool + Arguments | Tool Duration | Inline / Offload | `size_bytes` | `changed_since_last` | Observed Screen / Result |
|
||||
|---:|---:|---|---:|:---:|---:|:---:|---|
|
||||
| 1 | `+6.5s` | `get_state()` | ~3s | N | — | — | TV connected (`com.webos.app.livetv`) |
|
||||
| 2 | `+9.5s` | `list_apps()` | ~6s | N | — | — | Found `com.crunchyroll.webapp` ("Crunchyroll") |
|
||||
| 3 | `+18.5s` | `launch(app_id="com.crunchyroll.webapp")` | ~3s | N | — | — | App launched (`returnValue: true`) |
|
||||
| 4 | `+29.5s` | `screenshot()` | ~4s | Y (inline + disk) | `9,650 B` | `true` | Black screen with orange loading spinner |
|
||||
| 5 | `+38.5s` | `screenshot()` *(+ `read_file` ~1s)* | ~2s | Y (disk only) | `65,872 B` | `true` | Profile picker (`"¿Quién está viendo esto?"`, `Andres` focused) |
|
||||
| 6 | `+54.5s` | `keys(keys=["ENTER"], settle_ms=2000, capture=True)` *(+ `read_file` ~1s)* | ~6s | Y (disk only) | `28,663 B` | `true` | Welcome loading screen (`"¡Te damos la bienvenida, Andres!"`) |
|
||||
| 7 | `+69.5s` | `screenshot()` *(+ `read_file` ~1s)* | ~3s | Y (disk only) | `92,524 B` | `true` | Crunchyroll Home screen (`"Comenzar a Ver"` focused) |
|
||||
| 8 | `+82.5s` | `keys(keys=["LEFT", "UP", "ENTER"], delay_ms=250, settle_ms=1500, capture=True)` *(+ `read_file` ~1s)* | ~4s | Y (disk only) | `22,346 B` | `true` | Search screen; `"Ataque a los Titanes"` under `"Búsquedas recientes"` |
|
||||
| 9 | `+97.5s` | `keys(keys=["DOWN", "ENTER"], delay_ms=250, settle_ms=1500, capture=True)` *(+ `read_file` ~1s)* | ~4s | Y (disk only) | `15,744 B` | `true` | `"Ataque a los Titanes"` series page; `"Continuar E1"` focused |
|
||||
| 10 | `+113.5s` | `keys(keys=["ENTER"], settle_ms=2000, capture=True)` | ~5s | Y (inline + disk) | `9,563 B` | `true` | Black screen with bottom-left orange buffering spinner |
|
||||
| 11 | `+124.5s` | `screenshot()` | ~7s | Y (inline + disk) | `9,652 B` | `true` | Still buffering (bottom-left orange spinner) |
|
||||
| 12 | `+130.5s` | `screenshot()` | ~2s | Y (inline + disk) | `8,787 B` | `true` | Solid black DRM frame (playback started) |
|
||||
| 13 | `+137.5s` | `keys(keys=["DOWN"], settle_ms=800, capture=True)` *(+ `read_file` <1s)* | ~3s | Y (disk only) | `26,617 B` | `true` | Player HUD: `Ataque a los Titanes / E1 - Para ti, en 2000 años -- La caída de Shiganshina, parte 1` (`01:31 / 24:08`) |
|
||||
@@ -0,0 +1,65 @@
|
||||
# Crunchyroll E2E Comparative Report (PoC vs. `lg-smtv-mcp`)
|
||||
|
||||
Comparison between the initial PoC run ([`crunchyroll-e2e-experiment.md`](../poc/crunchyroll-e2e-experiment.md)) and the first live `lg-smtv-mcp` (`main` @ `aac0035`) subagent run (`b050beec-fc4c-4240-a54c-4613b8364893`) against `65UR8750PSA` (`WebOS/4.1.0`).
|
||||
|
||||
**Goal:** Launch Crunchyroll, select profile (`Andres`), open *Attack on Titan* (*Ataque a los Titanes*), and start Episode 1.
|
||||
|
||||
---
|
||||
|
||||
## Executive Summary
|
||||
|
||||
| Metric | PoC Baseline | `lg-smtv-mcp` (`aac0035`) | Notes |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| **Total Elapsed Time** | `7m 07s` (`427s`) | `4m 56s` (`296s`) | `lg-smtv-mcp` run also included `tv_wake` (`5.57s`), `T17 -> T1` (`UP x16`), and HUD verification |
|
||||
| **Timed TV Control Span** | `~7m 05s` | `4m 38s` (`09:37:29 -> 09:42:07`) | Excludes initial schema `read_file` setup |
|
||||
| **Steps / Captures** | `13` steps / `12` captures | `21` steps / `15` captures | Different reasoning paths; not 1-to-1 comparable |
|
||||
| **Per-Step Tool Duration** | `~8–10s` (fresh `nix develop` + TLS + `register` + `scp`) | `2–5s` (persistent SSAP + `asyncssh` SFTP) | Transport overhead eliminated by `TvManager` |
|
||||
| **Capture Size Range** | `9,606 B` – `101,992 B` | `8,787 B` – `103,192 B` | 11/15 captures exceeded ~10–15 KB and offloaded to disk |
|
||||
|
||||
### What MCP Bought vs. What It Didn't
|
||||
|
||||
- **What `TvManager` (not MCP itself) bought:** Persistent SSAP/pointer sockets and warm `asyncssh` SFTP cut per-step transport latency from `~8–10s` to `~2–5s`. A persistent REST API backed by `TvManager` would yield the same transport speedup.
|
||||
- **What MCP bought:** Zero-glue host integration (typed schemas, `ImageContent` multimodal blocks, and `stdio` / `streamable-http` lifecycle) across Antigravity and other MCP clients without writing custom client wrappers.
|
||||
- **What MCP did *not* buy:** Fewer UI discovery steps or faster LLM turns. Because 11 of 15 captures (`11 KB – 103 KB`) exceeded Antigravity's inline image threshold, Antigravity offloaded them to disk and spent an extra `read_file` LLM turn (`~10–15s` gap between steps) on almost every UI screen.
|
||||
|
||||
---
|
||||
|
||||
## Three-Bucket Latency Breakdown (`lg-smtv-mcp` Run)
|
||||
|
||||
1. **Transport & Process Overhead (`~45–60s` total across 21 steps):**
|
||||
Persistent SSAP + `asyncssh` SFTP took `2–5s` per capture call (including `settle_ms`).
|
||||
2. **Host / LLM Turn Overhead (`~3m 30s`):**
|
||||
- Full coding-agent turn latency (`~8–12s` per turn).
|
||||
- **11 extra `read_file` turns** caused by disk-offloaded `ImageContent` (`> ~10–15 KB`), directly motivating Issue **#20** (host-side JPEG downscaling/recompression).
|
||||
- **Retry / loading turns:** Skeleton/loading captures (Steps 5, 7, 13, 18, 19) and `type_text` without native IME (Steps 10–11), motivating Issue **#23** (`wait_for_change`).
|
||||
3. **TV / App Hardware Settling (`~20s`):**
|
||||
`tv_wake` (`5.57s`), Crunchyroll splash/profile load, `UP x16` list scroll, and video buffering.
|
||||
|
||||
---
|
||||
|
||||
## Detailed Step Log (`lg-smtv-mcp` @ `aac0035`)
|
||||
|
||||
| Step | Time (`-05:00`) | Action / Tool + Arguments | Observed Screen / Result | Capture Size | `changed_since_last` / Hash |
|
||||
| :--- | :--- | :--- | :--- | :--- | :--- |
|
||||
| 0 | `09:37:17 -> 09:37:25` | `date` + `read_file` on 7 `lg-smtv` schemas | Start `09:37:19.214`; schemas loaded | — | — |
|
||||
| 1 | `09:37:29 -> 09:37:30` | `get_state({})` | `connected: false, stale: true` (TV in standby) | — | — |
|
||||
| 2 | `09:37:34 -> 09:37:42` | `tv_wake({})` | `status: "connected"`, `elapsed_ms: 5572` | — | — |
|
||||
| 3 | `09:37:45 -> 09:37:48` | `list_apps({})` | Found `com.crunchyroll.webapp` | — | — |
|
||||
| 4 | `09:37:53 -> 09:37:57` | `launch({"app_id": "com.crunchyroll.webapp"})` | `returnValue: true` | — | — |
|
||||
| 5 | `09:38:01 -> 09:38:05` | `screenshot({})` + `read_file` | Crunchyroll splash screen | `94,613 B` | `true` / `548af733` |
|
||||
| 6 | `09:38:16 -> 09:38:19` | `screenshot({})` + `read_file` | Profile picker (`"¿Quién está viendo esto?"`, `Andres` focused) | `65,872 B` | `true` / `4cf77ce7` |
|
||||
| 7 | `09:38:31 -> 09:38:36` | `keys(["ENTER"], settle_ms=2000, capture=True)` + `read_file` | Profile selected; home sidebar rendered, content loading | `11,050 B` | `true` / `7f544a6e` |
|
||||
| 8 | `09:38:48 -> 09:38:50` | `screenshot({})` + `read_file` | Home screen loaded; focus on `"Comenzar a Ver"` | `92,524 B` | `true` / `08d99efe` |
|
||||
| 9 | `09:39:00 -> 09:39:04` | `keys(["LEFT", "UP", "ENTER"], delay_ms=250, settle_ms=800, capture=True)` + `read_file` | Search opened; `"Ataque a los Titanes"` in recent searches | `22,346 B` | `true` / `ac885345` |
|
||||
| 10 | `09:39:15 -> 09:39:17` | `keys(["ENTER"], settle_ms=800, capture=True)` | No screen change (Crunchyroll search input did not open native IME) | `22,346 B` | `false` / `ac885345` |
|
||||
| 11 | `09:39:23 -> 09:39:26` | `type_text("Attack on Titan", send_enter=True, capture=True)` | `text_sent: true`, screen unchanged (IME not open) | `22,346 B` | `false` / `ac885345` |
|
||||
| 12 | `09:39:32 -> 09:39:35` | `keys(["DOWN"], settle_ms=800, capture=True)` + `read_file` | Focused `"Ataque a los Titanes"` under `"Búsquedas recientes"` | `22,824 B` | `true` / `bce1361e` |
|
||||
| 13 | `09:39:49 -> 09:39:53` | `keys(["ENTER"], settle_ms=1500, capture=True)` + `read_file` | Series page loading (skeleton placeholders) | `16,665 B` | `true` / `463499ed` |
|
||||
| 14 | `09:40:05 -> 09:40:08` | `screenshot({})` + `read_file` | Series page loaded (`"Continuar E17"`) | `89,709 B` | `true` / `bc2357f7` |
|
||||
| 15 | `09:40:20 -> 09:40:23` | `keys(["DOWN"], settle_ms=800, capture=True)` + `read_file` | Focused `"EPISODIOS"` tab; Season 1 listed with `T17` | `96,025 B` | `true` / `e91c7353` |
|
||||
| 16 | `09:40:38 -> 09:40:41` | `keys(["DOWN", "RIGHT"], delay_ms=250, settle_ms=800, capture=True)` + `read_file` | Focused `T17 - La titán hembra...` | `102,035 B` | `true` / `59a5942b` |
|
||||
| 17 | `09:40:56 -> 09:41:01` | `keys(["UP"] * 16, delay_ms=150, settle_ms=800, capture=True)` + `read_file` | Focused `T1 - Para ti, en 2000 años -- La caída de S...` | `103,192 B` | `true` / `1f611a48` |
|
||||
| 18 | `09:41:28 -> 09:41:37` | `keys(["ENTER"], settle_ms=2000, capture=True)` *(after `settle_ms=2500` failed `INVALID_ARGUMENT`)* | Player buffering (orange spinner) | `9,608 B` | `true` / `1cf098ba` |
|
||||
| 19 | `09:41:45 -> 09:41:48` | `screenshot({})` | Still buffering (spinner rotated) | `9,565 B` | `true` / `66e7dae3` |
|
||||
| 20 | `09:41:55 -> 09:41:57` | `screenshot({})` | Spinner gone, black frame (DRM video layer) | `8,787 B` | `true` / `f6ed2d39` |
|
||||
| 21 | `09:42:05 -> 09:42:07` | `keys(["DOWN"], settle_ms=500, capture=True)` + `read_file` (`09:42:15`) | Player HUD: `E1 - Para ti, en 2000 años -- La caída de Shiganshina, parte 1` at `00:19 / 25:20` | `17,889 B` | `true` / `02654704` |
|
||||
@@ -0,0 +1,47 @@
|
||||
# Post-#20 Standardized E2E Benchmark (`main` @ `09618be`)
|
||||
|
||||
Post-**#20** benchmark executed using [`e2e-benchmark-template.md`](e2e-benchmark-template.md) by subagent `9d82e846-0c13-4c82-8f8f-2780d34ad173` against `65UR8750PSA` (`WebOS/4.1.0`), compared against [`crunchyroll-e2e-baseline-0d67615.md`](crunchyroll-e2e-baseline-0d67615.md).
|
||||
|
||||
## Preconditions
|
||||
|
||||
- **Commit / Branch:** `09618be` (`main`, PR `#24`)
|
||||
- **Server Config:** `CAPTURE_MAX_WIDTH=480`, `CAPTURE_JPEG_QUALITY=55`
|
||||
- **TV Starting State:** Powered ON at Live TV (`com.webos.app.livetv`), Crunchyroll closed.
|
||||
- **Timer Boundary:** `T0 = 11:16:18.965`, `T_end = 11:19:06.423` (`-05:00`, excluding initial schema `read_file` setup).
|
||||
|
||||
---
|
||||
|
||||
## Normalized Scorecard
|
||||
|
||||
| Metric | Baseline (`0d67615`, raw `960x540`) | Post-**#20** (`09618be`, `480px`, `q=55`) | Delta |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| **Total Timed Span (`T0 -> T_end`)** | `148.40s` (`13` steps) | `167.46s` (`17` steps) | `+19.06s` *(4 extra steps: Crunchyroll auto-resumed previous show + 1 `ENTER` retry)* |
|
||||
| **Average Time per Step** | `11.42s / step` | `9.85s / step` | `-1.57s / step` |
|
||||
| **Total Steps / Captures** | `13` / `10` | `17` / `14` | `+4` / `+4` |
|
||||
| **Median Capture Size (B)** | `19,045 B` | `5,893 B` | `-69.1%` |
|
||||
| **Disk-Only Offloads (`read_file` turns)** | `6 / 10` (`60%`) | `1 / 14` (`7%`) | `-53 pp` *(only `10,951 B` splash offloaded; all `<= 8,421 B` stayed inline)* |
|
||||
| **Wasted / Retry Steps** | `0` | `1` | `+1` *(Step 6 `ENTER` on profile screen)* |
|
||||
|
||||
---
|
||||
|
||||
## Step-by-Step Telemetry Table
|
||||
|
||||
| Step # | `T+elapsed` | Tool + Arguments | Tool Duration | Inline / Offload | `size_bytes` | `changed_since_last` | Observed Screen / Result |
|
||||
|---:|---:|---|---:|:---:|---:|:---:|---|
|
||||
| 1 | `~8s` | `get_state()` | ~2s | N | — | — | `connected: true`, `foreground_app: com.webos.app.livetv` |
|
||||
| 2 | `~11s` | `list_apps()` | ~5s | N | — | — | Found `com.crunchyroll.webapp` ("Crunchyroll") |
|
||||
| 3 | `~19s` | `launch(app_id="com.crunchyroll.webapp")` | ~4s | N | — | — | `returnValue: true` |
|
||||
| 4 | `~29s` | `screenshot()` *(+ `read_file`)* | ~4s | Y (disk only) | `10,951 B` | `true` | Crunchyroll splash screen |
|
||||
| 5 | `~44s` | `screenshot()` | ~3s | Y (inline + disk) | `8,421 B` | `true` | Profile picker (`Andres` focused) |
|
||||
| 6 | `~53s` | `keys(["ENTER"], settle_ms=1800, capture=True)` | ~4s | Y (inline + disk) | `8,421 B` | `false` | Still on profile picker (`Andres` focused) |
|
||||
| 7 | `~64s` | `keys(["ENTER"], settle_ms=2000, capture=True)` | ~5s | Y (inline + disk) | `2,782 B` | `true` | Black loading spinner |
|
||||
| 8 | `~73s` | `screenshot()` | ~4s | Y (inline + disk) | `2,812 B` | `true` | Black loading spinner |
|
||||
| 9 | `~80s` | `screenshot()` | ~2s | Y (inline + disk) | `3,548 B` | `true` | Black DRM frame (auto-resumed previous show) |
|
||||
| 10 | `~89s` | `keys(["DOWN"], settle_ms=1000, capture=True)` | ~4s | Y (inline + disk) | `6,454 B` | `true` | Player HUD: `Hello, I am a Witch... E1` |
|
||||
| 11 | `~98s` | `keys(["BACK"], settle_ms=1500, capture=True)` | ~5s | Y (inline + disk) | `3,118 B` | `true` | Home screen loading with left sidebar |
|
||||
| 12 | `~105s` | `keys(["LEFT"], settle_ms=800, capture=True)` | ~3s | Y (inline + disk) | `7,469 B` | `true` | Left sidebar open, `Inicio` focused |
|
||||
| 13 | `~114s` | `keys(["UP", "ENTER"], settle_ms=1000, capture=True)` | ~4s | Y (inline + disk) | `5,499 B` | `true` | Search screen, `Ataque a los Titanes` under `Búsquedas recientes` |
|
||||
| 14 | `~123s` | `keys(["DOWN", "ENTER"], settle_ms=1500, capture=True)` | ~4s | Y (inline + disk) | `7,545 B` | `true` | Series page `Ataque a los Titanes`, `Continuar E1` focused |
|
||||
| 15 | `~139s` | `keys(["ENTER"], settle_ms=2000, capture=True)` | ~4s | Y (inline + disk) | `2,809 B` | `true` | Black loading spinner |
|
||||
| 16 | `~146s` | `screenshot()` | ~2s | Y (inline + disk) | `3,540 B` | `true` | Black DRM frame (`16+` rating overlay) |
|
||||
| 17 | `~155s` | `keys(["DOWN"], settle_ms=800, capture=True)` | ~4s | Y (inline + disk) | `6,287 B` | `true` | Player HUD: `Ataque a los Titanes` / `E1 - Para ti, en 2000 años -- La caída de Shiganshina, parte 1` (`08:02 / 17:37`) |
|
||||
@@ -0,0 +1,51 @@
|
||||
# Standardized E2E Benchmark Template (`lg-smtv-mcp`)
|
||||
|
||||
Use this template to benchmark changes (such as **#20** JPEG downscaling or **#23** `wait_for_change`) without agent reasoning variance skewing the comparison.
|
||||
|
||||
---
|
||||
|
||||
## 1. Preconditions (Pin Before Starting)
|
||||
|
||||
- **Commit / Branch:** `<git rev-parse --short HEAD>` (`<branch>`)
|
||||
- **Server Config:** `CAPTURE_MAX_WIDTH=<value|unset>`, `CAPTURE_JPEG_QUALITY=<value|unset>`
|
||||
- **TV Starting State:** Powered ON at Live TV (or Standby — record which), Crunchyroll closed.
|
||||
- **Timer Boundary:** Start `T=0` at the first TV-control tool call (`launch` or `tv_wake`), **excluding** one-time MCP schema `read_file` setup. End `T_end` when the playback HUD is verified.
|
||||
|
||||
---
|
||||
|
||||
## 2. Standardized Subagent Prompt
|
||||
|
||||
```text
|
||||
Goal: Launch Crunchyroll, select profile "Andres", open Attack on Titan ("Ataque a los Titanes"), and start Episode 1.
|
||||
|
||||
Execution Rules (fixed policy for benchmark parity):
|
||||
1. Load any needed lg-smtv schemas first, then record `T0` (`date +"%H:%M:%S.%3N"`).
|
||||
2. Always prefer `keys(..., capture=True)` over separate `keys` + `screenshot` calls.
|
||||
3. Keep `settle_ms <= 2000` (use `1500–2000` on app launch, profile select, and series page open).
|
||||
4. On Crunchyroll Search, select "Ataque a los Titanes" from Recent Searches if visible instead of calling `type_text`.
|
||||
5. Once playback starts (black DRM frame), press `DOWN` once with `capture=True` to verify Episode 1 on the player HUD.
|
||||
6. Do NOT write or edit any repository files.
|
||||
|
||||
For every step, record:
|
||||
- Step #, T+elapsed (s), Tool + arguments, Tool duration (ms/s), Offloaded to disk? (Y/N), Capture size_bytes, changed_since_last, Observed screen.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Normalized Scorecard
|
||||
|
||||
| Metric | Baseline (`aac0035`) | Candidate (`<sha>`) | Delta |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| **Total Timed Span (`T0 -> T_end`)** | `4m 38s` (`278s`) | | |
|
||||
| **Total Steps / Captures** | `21` / `15` | | |
|
||||
| **Median Capture Size (B)** | `22,824 B` | | |
|
||||
| **Offloaded Captures (`read_file` turns)** | `11` / `15` | | |
|
||||
| **Wasted / Retry Steps** | `4` (steps 10, 11, 13→14, 18→19) | | |
|
||||
|
||||
---
|
||||
|
||||
## 4. Step-by-Step Telemetry Table
|
||||
|
||||
| Step | `T+s` | Tool + Arguments | Tool Duration | Offloaded? (`Y/N`) | `size_bytes` | `changed_since_last` | Observed Screen / Result |
|
||||
| :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- |
|
||||
| 1 | | | | | | | |
|
||||
@@ -17,6 +17,7 @@
|
||||
ps.pydantic
|
||||
ps.asyncssh
|
||||
ps.uvicorn
|
||||
ps.pillow
|
||||
];
|
||||
|
||||
testDeps = [
|
||||
@@ -25,6 +26,10 @@
|
||||
ps.pytest-asyncio
|
||||
];
|
||||
|
||||
testTools = [
|
||||
pkgs.systemd
|
||||
];
|
||||
|
||||
pythonEnv = pkgs.python3.withPackages (_: runtimeDeps ++ testDeps);
|
||||
in
|
||||
{
|
||||
@@ -39,7 +44,7 @@
|
||||
ps.pytestCheckHook
|
||||
pkgs.ruff
|
||||
pkgs.pyright
|
||||
] ++ testDeps;
|
||||
] ++ testDeps ++ testTools;
|
||||
preCheck = ''
|
||||
ruff check .
|
||||
ruff format --check .
|
||||
@@ -52,7 +57,7 @@
|
||||
pythonEnv
|
||||
pkgs.pyright
|
||||
pkgs.ruff
|
||||
];
|
||||
] ++ testTools;
|
||||
shellHook = ''
|
||||
export PYTHONPATH="$PWD/src:${PYTHONPATH:-}"
|
||||
if [ -d .git ] && [ -d .githooks ]; then
|
||||
|
||||
@@ -13,6 +13,7 @@ dependencies = [
|
||||
"pydantic",
|
||||
"asyncssh",
|
||||
"uvicorn",
|
||||
"pillow",
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
|
||||
@@ -13,6 +13,7 @@ from pathlib import Path
|
||||
from typing import Any, cast
|
||||
|
||||
from mcp.server.mcpserver import MCPServer
|
||||
from websockets.exceptions import WebSocketException
|
||||
|
||||
from lg_smtv_mcp.auth import ASGIApp
|
||||
from lg_smtv_mcp.config import TvConfig, load_config
|
||||
@@ -73,7 +74,7 @@ async def _pair_tv(
|
||||
existing_key: str | None,
|
||||
connect_fn: WebSocketConnectFn,
|
||||
) -> str:
|
||||
ws = await connect_fn(f"ws://{ip}:3000")
|
||||
ws = await connect_fn(f"wss://{ip}:3001")
|
||||
try:
|
||||
reg_payload = build_register_payload(existing_key)
|
||||
await ws.send(json.dumps(reg_payload))
|
||||
@@ -197,6 +198,6 @@ def main(
|
||||
if args.command == "serve":
|
||||
return _handle_serve(args, config, uvicorn_run=uvicorn_run, stdio_run=stdio_run)
|
||||
return _handle_pair(args, config, connect_fn=connect_fn, fetch_url=fetch_url)
|
||||
except (ConfigError, TvError, OSError, ValueError) as exc:
|
||||
except (ConfigError, TvError, WebSocketException, OSError, ValueError) as exc:
|
||||
print(f"error: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
@@ -72,6 +72,8 @@ class TvConfig(BaseModel):
|
||||
mcp_bearer_token: str | None = None
|
||||
max_volume: int = 40
|
||||
enable_raw_ssap: bool = False
|
||||
capture_max_width: int | None = None
|
||||
capture_jpeg_quality: int | None = None
|
||||
|
||||
def __init__(self, **data: Any) -> None:
|
||||
try:
|
||||
@@ -100,6 +102,20 @@ class TvConfig(BaseModel):
|
||||
def _validate_max_volume(cls, value: Any) -> int:
|
||||
return _parse_bounded_int("MAX_VOLUME", value, min_val=0, max_val=100)
|
||||
|
||||
@field_validator("capture_max_width", mode="before")
|
||||
@classmethod
|
||||
def _validate_capture_max_width(cls, value: Any) -> int | None:
|
||||
if value is None:
|
||||
return None
|
||||
return _parse_bounded_int("CAPTURE_MAX_WIDTH", value, min_val=64, max_val=3840)
|
||||
|
||||
@field_validator("capture_jpeg_quality", mode="before")
|
||||
@classmethod
|
||||
def _validate_capture_jpeg_quality(cls, value: Any) -> int | None:
|
||||
if value is None:
|
||||
return None
|
||||
return _parse_bounded_int("CAPTURE_JPEG_QUALITY", value, min_val=1, max_val=95)
|
||||
|
||||
|
||||
def _load_dotenv(env_path: Path) -> None:
|
||||
"""Populate unset os.environ keys from a .env file using stdlib only."""
|
||||
@@ -149,6 +165,8 @@ def load_config(env_path: Path | None = Path(".env")) -> TvConfig:
|
||||
tv_ip = _optional_str("TV_IP") or ""
|
||||
port_raw = _optional_str("PORT")
|
||||
max_volume_raw = _optional_str("MAX_VOLUME")
|
||||
capture_max_width_raw = _optional_str("CAPTURE_MAX_WIDTH")
|
||||
capture_jpeg_quality_raw = _optional_str("CAPTURE_JPEG_QUALITY")
|
||||
|
||||
host = _optional_str("HOST") or "127.0.0.1"
|
||||
wol_broadcast = _optional_str("WOL_BROADCAST") or "255.255.255.255"
|
||||
@@ -177,6 +195,10 @@ def load_config(env_path: Path | None = Path(".env")) -> TvConfig:
|
||||
kwargs["port"] = port_raw
|
||||
if max_volume_raw is not None:
|
||||
kwargs["max_volume"] = max_volume_raw
|
||||
if capture_max_width_raw is not None:
|
||||
kwargs["capture_max_width"] = capture_max_width_raw
|
||||
if capture_jpeg_quality_raw is not None:
|
||||
kwargs["capture_jpeg_quality"] = capture_jpeg_quality_raw
|
||||
|
||||
return TvConfig(**kwargs)
|
||||
|
||||
|
||||
@@ -160,7 +160,14 @@ def create_mcp_server(config: TvConfig, manager: TvManager | None = None) -> MCP
|
||||
tv_manager = (
|
||||
manager
|
||||
if manager is not None
|
||||
else TvManager(config, capture_client=CaptureClient(AsyncSshCaptureTransport(config)))
|
||||
else TvManager(
|
||||
config,
|
||||
capture_client=CaptureClient(
|
||||
AsyncSshCaptureTransport(config),
|
||||
max_width=config.capture_max_width,
|
||||
jpeg_quality=config.capture_jpeg_quality,
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
@asynccontextmanager
|
||||
|
||||
@@ -5,14 +5,57 @@ import hashlib
|
||||
import os
|
||||
from collections.abc import Awaitable, Callable
|
||||
from contextlib import suppress
|
||||
from io import BytesIO
|
||||
from typing import Any
|
||||
|
||||
import asyncssh
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
|
||||
from lg_smtv_mcp.config import TvConfig
|
||||
from lg_smtv_mcp.errors import ErrorCode, TvError
|
||||
from lg_smtv_mcp.tv_core.protocols import CaptureResult, CaptureTransport
|
||||
|
||||
_DEFAULT_JPEG_QUALITY = 75
|
||||
|
||||
|
||||
def _recompress_jpeg(
|
||||
raw_bytes: bytes,
|
||||
*,
|
||||
max_width: int | None,
|
||||
jpeg_quality: int | None,
|
||||
) -> bytes:
|
||||
"""Optionally downscale and/or recompress JPEG bytes for inline MCP delivery."""
|
||||
if max_width is None and jpeg_quality is None:
|
||||
return raw_bytes
|
||||
|
||||
quality = jpeg_quality if jpeg_quality is not None else _DEFAULT_JPEG_QUALITY
|
||||
try:
|
||||
with Image.open(BytesIO(raw_bytes)) as opened:
|
||||
img: Image.Image = opened
|
||||
width, height = img.size
|
||||
if max_width is not None and width > max_width:
|
||||
target_height = max(1, round(height * (max_width / width)))
|
||||
img = img.resize( # pyright: ignore[reportUnknownMemberType]
|
||||
(max_width, target_height),
|
||||
Image.Resampling.LANCZOS,
|
||||
)
|
||||
if img.mode != "RGB":
|
||||
img = img.convert("RGB")
|
||||
out = BytesIO()
|
||||
img.save(out, format="JPEG", quality=quality)
|
||||
return out.getvalue()
|
||||
except (
|
||||
UnidentifiedImageError,
|
||||
Image.DecompressionBombError,
|
||||
OSError,
|
||||
ValueError,
|
||||
EOFError,
|
||||
) as exc:
|
||||
raise TvError(
|
||||
ErrorCode.SCREENSHOT_UNAVAILABLE,
|
||||
f"Failed to process screenshot image: {exc}",
|
||||
) from exc
|
||||
|
||||
|
||||
class AsyncSshCaptureTransport:
|
||||
"""SFTP transport for reading and removing Developer Mode screenshot captures."""
|
||||
@@ -102,9 +145,10 @@ class AsyncSshCaptureTransport:
|
||||
try:
|
||||
async with asyncio.timeout(timeout):
|
||||
sftp = await self._ensure_sftp(exclude=remote_path)
|
||||
data = await sftp.read(remote_path)
|
||||
async with sftp.open(remote_path, "rb") as handle:
|
||||
data = await handle.read()
|
||||
return bytes(data)
|
||||
except asyncssh.Error, OSError:
|
||||
except asyncssh.Error, asyncssh.KeyImportError, OSError:
|
||||
await self._close_handles()
|
||||
raise
|
||||
finally:
|
||||
@@ -153,8 +197,16 @@ class AsyncSshCaptureTransport:
|
||||
class CaptureClient:
|
||||
"""FrameCapturer that triggers executeOneShot and fetches JPEG via SFTP."""
|
||||
|
||||
def __init__(self, transport: CaptureTransport) -> None:
|
||||
def __init__(
|
||||
self,
|
||||
transport: CaptureTransport,
|
||||
*,
|
||||
max_width: int | None = None,
|
||||
jpeg_quality: int | None = None,
|
||||
) -> None:
|
||||
self._transport = transport
|
||||
self._max_width = max_width
|
||||
self._jpeg_quality = jpeg_quality
|
||||
self._seq = 0
|
||||
self._last_sha256: str | None = None
|
||||
|
||||
@@ -191,7 +243,7 @@ class CaptureClient:
|
||||
)
|
||||
except TvError:
|
||||
raise
|
||||
except (asyncssh.Error, OSError) as exc:
|
||||
except (asyncssh.Error, asyncssh.KeyImportError, OSError) as exc:
|
||||
raise TvError(
|
||||
ErrorCode.SCREENSHOT_UNAVAILABLE,
|
||||
f"Failed to retrieve screenshot over SSH/SFTP: {exc}",
|
||||
@@ -202,6 +254,11 @@ class CaptureClient:
|
||||
"Screenshot capture timed out after 6.0s",
|
||||
) from exc
|
||||
|
||||
image_bytes = _recompress_jpeg(
|
||||
image_bytes,
|
||||
max_width=self._max_width,
|
||||
jpeg_quality=self._jpeg_quality,
|
||||
)
|
||||
frame_sha256 = hashlib.sha256(image_bytes).hexdigest()
|
||||
changed_since_last = self._last_sha256 != frame_sha256
|
||||
self._last_sha256 = frame_sha256
|
||||
|
||||
+239
-14
@@ -2,16 +2,49 @@
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import inspect
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import asyncssh
|
||||
import pytest
|
||||
from PIL import Image
|
||||
|
||||
from lg_smtv_mcp.config import TvConfig
|
||||
from lg_smtv_mcp.errors import ErrorCode, TvError
|
||||
from lg_smtv_mcp.tv_core.capture import AsyncSshCaptureTransport, CaptureClient
|
||||
|
||||
|
||||
class FakeSftpFile:
|
||||
"""Mirror asyncssh.SFTPClientFile: sync open(), async read(), async context manager."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
data: bytes,
|
||||
*,
|
||||
error: Exception | None = None,
|
||||
read_delay: float = 0.0,
|
||||
) -> None:
|
||||
self._data = data
|
||||
self._error = error
|
||||
self._read_delay = read_delay
|
||||
self.closed = False
|
||||
|
||||
async def __aenter__(self) -> FakeSftpFile:
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *_exc: object) -> None:
|
||||
self.closed = True
|
||||
|
||||
async def read(self) -> bytes:
|
||||
if self._read_delay > 0:
|
||||
await asyncio.sleep(self._read_delay)
|
||||
if self._error is not None:
|
||||
raise self._error
|
||||
return self._data
|
||||
|
||||
|
||||
class FakeSftpClient:
|
||||
def __init__(
|
||||
self,
|
||||
@@ -19,25 +52,34 @@ class FakeSftpClient:
|
||||
files: dict[str, bytes] | None = None,
|
||||
extra_names: list[str] | None = None,
|
||||
read_error: Exception | None = None,
|
||||
read_delay: float = 0.0,
|
||||
remove_delay: float = 0.0,
|
||||
remove_error: Exception | None = None,
|
||||
) -> None:
|
||||
self.files = dict(files or {})
|
||||
self.extra_names = list(extra_names or [])
|
||||
self.read_error = read_error
|
||||
self.read_delay = read_delay
|
||||
self.remove_delay = remove_delay
|
||||
self.remove_error = remove_error
|
||||
self.read_calls: list[str] = []
|
||||
self.open_calls: list[tuple[str, str]] = []
|
||||
self.handles: list[FakeSftpFile] = []
|
||||
self.remove_calls: list[str] = []
|
||||
self.closed = False
|
||||
|
||||
async def read(self, path: str) -> bytes:
|
||||
self.read_calls.append(path)
|
||||
if self.read_error is not None:
|
||||
raise self.read_error
|
||||
if path not in self.files:
|
||||
raise FileNotFoundError(path)
|
||||
return self.files[path]
|
||||
def open(self, path: str, mode: str = "r") -> FakeSftpFile:
|
||||
"""Mirror asyncssh.SFTPClient.open: regular function returning an async file."""
|
||||
self.open_calls.append((path, mode))
|
||||
error = self.read_error
|
||||
if error is None and path not in self.files:
|
||||
error = FileNotFoundError(path)
|
||||
handle = FakeSftpFile(
|
||||
self.files.get(path, b""),
|
||||
error=error,
|
||||
read_delay=self.read_delay,
|
||||
)
|
||||
self.handles.append(handle)
|
||||
return handle
|
||||
|
||||
async def remove(self, path: str) -> None:
|
||||
if self.remove_delay > 0:
|
||||
@@ -155,6 +197,30 @@ async def test_async_ssh_capture_transport_connect_uses_required_args(tmp_path:
|
||||
assert calls[0]["passphrase"] == "secret"
|
||||
|
||||
|
||||
async def test_async_ssh_capture_transport_reads_via_real_sftp_open_api(tmp_path: Path) -> None:
|
||||
"""Guard against reintroducing sftp.read(), which asyncssh 2.24 does not expose."""
|
||||
assert not hasattr(asyncssh.SFTPClient, "read")
|
||||
assert hasattr(asyncssh.SFTPClient, "open")
|
||||
assert hasattr(asyncssh.SFTPClientFile, "__aenter__")
|
||||
assert inspect.iscoroutinefunction(asyncssh.SFTPClientFile.read)
|
||||
|
||||
remote_path = "/tmp/lg_smtv_cap_1.jpg"
|
||||
sftp = FakeSftpClient(files={remote_path: b"jpeg"})
|
||||
conn = FakeSshConnection(sftp)
|
||||
|
||||
async def fake_connect(**kwargs: Any) -> FakeSshConnection:
|
||||
_ = kwargs
|
||||
return conn
|
||||
|
||||
transport = AsyncSshCaptureTransport(_make_config(tmp_path), connect_fn=fake_connect)
|
||||
data = await transport.read_and_remove(remote_path)
|
||||
|
||||
assert data == b"jpeg"
|
||||
assert sftp.open_calls == [(remote_path, "rb")]
|
||||
assert len(sftp.handles) == 1
|
||||
assert sftp.handles[0].closed is True
|
||||
|
||||
|
||||
async def test_async_ssh_capture_transport_sweeps_on_initial_connect_and_reconnect(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
@@ -248,12 +314,7 @@ async def test_async_ssh_capture_transport_closes_connection_when_start_sftp_cli
|
||||
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"})
|
||||
sftp = FakeSftpClient(files={"/tmp/lg_smtv_cap_1.jpg": b"bytes"}, read_delay=10.0)
|
||||
conn = FakeSshConnection(sftp)
|
||||
|
||||
async def fake_connect(**kwargs: Any) -> FakeSshConnection:
|
||||
@@ -445,3 +506,167 @@ async def test_capture_client_maps_sftp_timeout_and_cancels_read() -> None:
|
||||
|
||||
assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE
|
||||
assert transport.read_cancelled.is_set()
|
||||
|
||||
|
||||
async def test_capture_client_maps_key_import_error_to_screenshot_unavailable() -> None:
|
||||
transport = FakeCaptureTransport(
|
||||
read_error=asyncssh.KeyImportError(
|
||||
"Passphrase must be specified to import encrypted private keys"
|
||||
)
|
||||
)
|
||||
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 client.capture_frame(ssap_request)
|
||||
assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE
|
||||
assert "Passphrase must be specified" in exc_info.value.message
|
||||
|
||||
|
||||
def _make_jpeg(
|
||||
width: int,
|
||||
height: int,
|
||||
*,
|
||||
color: tuple[int, int, int] = (25, 80, 160),
|
||||
quality: int = 95,
|
||||
) -> bytes:
|
||||
buf = BytesIO()
|
||||
img = Image.new("RGB", (width, height), color=color)
|
||||
# Draw varied pixels so JPEG recompression has realistic entropy differences.
|
||||
for x in range(0, width, 8):
|
||||
img.putpixel((x, x % height), ((x * 7) % 255, (x * 13) % 255, 200))
|
||||
img.save(buf, format="JPEG", quality=quality)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
async def test_capture_client_passes_raw_bytes_unchanged_when_no_resize_or_quality() -> None:
|
||||
raw = b"raw-unprocessed-bytes"
|
||||
client = CaptureClient(FakeCaptureTransport(image_bytes=raw))
|
||||
|
||||
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
_ = (uri, payload)
|
||||
return {"returnValue": True}
|
||||
|
||||
result = await client.capture_frame(ssap_request)
|
||||
|
||||
assert result.image_bytes == raw
|
||||
assert result.size_bytes == len(raw)
|
||||
assert result.frame_sha256 == hashlib.sha256(raw).hexdigest()
|
||||
|
||||
|
||||
async def test_capture_client_downscales_preserving_aspect_ratio_with_default_quality_75() -> None:
|
||||
raw = _make_jpeg(1920, 1080, quality=95)
|
||||
client = CaptureClient(FakeCaptureTransport(image_bytes=raw), max_width=640)
|
||||
|
||||
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
_ = (uri, payload)
|
||||
return {"returnValue": True}
|
||||
|
||||
result = await client.capture_frame(ssap_request)
|
||||
|
||||
with Image.open(BytesIO(result.image_bytes)) as img:
|
||||
assert img.format == "JPEG"
|
||||
assert img.size == (640, 360)
|
||||
assert result.size_bytes == len(result.image_bytes)
|
||||
assert result.frame_sha256 == hashlib.sha256(result.image_bytes).hexdigest()
|
||||
assert result.image_bytes != raw
|
||||
|
||||
|
||||
async def test_capture_client_never_upscales_when_width_at_or_below_max_width() -> None:
|
||||
raw = _make_jpeg(800, 600, quality=95)
|
||||
client = CaptureClient(
|
||||
FakeCaptureTransport(image_bytes=raw),
|
||||
max_width=1280,
|
||||
jpeg_quality=80,
|
||||
)
|
||||
|
||||
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
_ = (uri, payload)
|
||||
return {"returnValue": True}
|
||||
|
||||
result = await client.capture_frame(ssap_request)
|
||||
|
||||
with Image.open(BytesIO(result.image_bytes)) as img:
|
||||
assert img.format == "JPEG"
|
||||
assert img.size == (800, 600)
|
||||
|
||||
|
||||
async def test_capture_client_recompresses_at_native_resolution_when_only_quality_set() -> None:
|
||||
raw = _make_jpeg(1280, 720, quality=95)
|
||||
client = CaptureClient(FakeCaptureTransport(image_bytes=raw), jpeg_quality=30)
|
||||
|
||||
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
_ = (uri, payload)
|
||||
return {"returnValue": True}
|
||||
|
||||
result = await client.capture_frame(ssap_request)
|
||||
|
||||
with Image.open(BytesIO(result.image_bytes)) as img:
|
||||
assert img.format == "JPEG"
|
||||
assert img.size == (1280, 720)
|
||||
assert result.size_bytes < len(raw)
|
||||
assert result.frame_sha256 == hashlib.sha256(result.image_bytes).hexdigest()
|
||||
|
||||
|
||||
async def test_capture_client_hashes_and_tracks_changes_on_final_delivered_bytes() -> None:
|
||||
raw = _make_jpeg(1280, 720, quality=95)
|
||||
client = CaptureClient(
|
||||
FakeCaptureTransport(image_bytes=raw),
|
||||
max_width=640,
|
||||
jpeg_quality=75,
|
||||
)
|
||||
|
||||
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
_ = (uri, payload)
|
||||
return {"returnValue": True}
|
||||
|
||||
first = await client.capture_frame(ssap_request)
|
||||
second = await client.capture_frame(ssap_request)
|
||||
|
||||
assert first.frame_sha256 != hashlib.sha256(raw).hexdigest()
|
||||
assert first.frame_sha256 == hashlib.sha256(first.image_bytes).hexdigest()
|
||||
assert first.changed_since_last is True
|
||||
assert second.changed_since_last is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"kwargs",
|
||||
[
|
||||
{"max_width": 640},
|
||||
{"jpeg_quality": 75},
|
||||
{"max_width": 640, "jpeg_quality": 75},
|
||||
],
|
||||
)
|
||||
async def test_capture_client_raises_screenshot_unavailable_on_corrupt_image_bytes(
|
||||
kwargs: dict[str, int],
|
||||
) -> None:
|
||||
client = CaptureClient(FakeCaptureTransport(image_bytes=b"not-a-valid-jpeg"), **kwargs)
|
||||
|
||||
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
_ = (uri, payload)
|
||||
return {"returnValue": True}
|
||||
|
||||
with pytest.raises(TvError) as exc_info:
|
||||
await client.capture_frame(ssap_request)
|
||||
|
||||
assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE
|
||||
|
||||
|
||||
async def test_capture_client_maps_decompression_bomb_error_to_screenshot_unavailable(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
raw = _make_jpeg(32, 32, quality=95)
|
||||
monkeypatch.setattr(Image, "MAX_IMAGE_PIXELS", 100)
|
||||
client = CaptureClient(FakeCaptureTransport(image_bytes=raw), max_width=16)
|
||||
|
||||
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
_ = (uri, payload)
|
||||
return {"returnValue": True}
|
||||
|
||||
with pytest.raises(TvError) as exc_info:
|
||||
await client.capture_frame(ssap_request)
|
||||
|
||||
assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE
|
||||
+20
-1
@@ -8,6 +8,7 @@ from typing import Any
|
||||
import httpx
|
||||
import pytest
|
||||
from mcp.server.mcpserver import MCPServer
|
||||
from websockets.exceptions import InvalidMessage
|
||||
|
||||
from lg_smtv_mcp.auth import ASGIApp
|
||||
from lg_smtv_mcp.cli import main
|
||||
@@ -122,7 +123,7 @@ def test_cli_pair_merges_existing_client_keys_and_writes_0600(tmp_path: Path) ->
|
||||
)
|
||||
|
||||
assert rc == 0
|
||||
assert connected_urls == ["ws://192.0.2.20:3000"]
|
||||
assert connected_urls == ["wss://192.0.2.20:3001"]
|
||||
saved = json.loads(key_file.read_text(encoding="utf-8"))
|
||||
assert saved == {"192.0.2.10": "old-key", "192.0.2.20": "new-key-20"}
|
||||
assert stat.S_IMODE(key_file.stat().st_mode) == 0o600
|
||||
@@ -196,3 +197,21 @@ def test_cli_pair_fetch_ssh_key_failure_preserves_client_key_and_exits_nonzero(
|
||||
assert rc == 1
|
||||
assert json.loads(key_file.read_text(encoding="utf-8")) == {"192.0.2.10": "tv-key-10"}
|
||||
assert not ssh_dest.exists()
|
||||
|
||||
|
||||
def test_cli_pair_returns_nonzero_on_websocket_handshake_error(
|
||||
tmp_path: Path,
|
||||
capsys: pytest.CaptureFixture[str],
|
||||
) -> None:
|
||||
async def failing_connect(_url: str) -> FakeWebSocketTransport:
|
||||
raise InvalidMessage("did not receive a valid HTTP response")
|
||||
|
||||
rc = main(
|
||||
["pair"],
|
||||
config_loader=lambda: _make_config(tmp_path),
|
||||
connect_fn=failing_connect,
|
||||
)
|
||||
|
||||
assert rc == 1
|
||||
captured = capsys.readouterr()
|
||||
assert "error: did not receive a valid HTTP response" in captured.err
|
||||
@@ -22,6 +22,8 @@ def _clear_tv_env(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"MCP_BEARER_TOKEN",
|
||||
"MAX_VOLUME",
|
||||
"ENABLE_RAW_SSAP",
|
||||
"CAPTURE_MAX_WIDTH",
|
||||
"CAPTURE_JPEG_QUALITY",
|
||||
):
|
||||
monkeypatch.delenv(key, raising=False)
|
||||
|
||||
@@ -74,6 +76,8 @@ def test_load_config_uses_expected_defaults_when_optional_vars_unset(
|
||||
assert cfg.allowed_hosts == ()
|
||||
assert cfg.tv_mac is None
|
||||
assert cfg.mcp_bearer_token is None
|
||||
assert cfg.capture_max_width is None
|
||||
assert cfg.capture_jpeg_quality is None
|
||||
|
||||
|
||||
def test_dotenv_fallback_does_not_overwrite_existing_env(
|
||||
@@ -108,6 +112,12 @@ def test_dotenv_fallback_does_not_overwrite_existing_env(
|
||||
({"TV_IP": "192.0.2.10", "PORT": "0"}, "PORT"),
|
||||
({"TV_IP": "192.0.2.10", "PORT": "65536"}, "PORT"),
|
||||
({"TV_IP": "192.0.2.10", "PORT": "abc"}, "PORT"),
|
||||
({"TV_IP": "192.0.2.10", "CAPTURE_MAX_WIDTH": "63"}, "CAPTURE_MAX_WIDTH"),
|
||||
({"TV_IP": "192.0.2.10", "CAPTURE_MAX_WIDTH": "3841"}, "CAPTURE_MAX_WIDTH"),
|
||||
({"TV_IP": "192.0.2.10", "CAPTURE_MAX_WIDTH": "wide"}, "CAPTURE_MAX_WIDTH"),
|
||||
({"TV_IP": "192.0.2.10", "CAPTURE_JPEG_QUALITY": "0"}, "CAPTURE_JPEG_QUALITY"),
|
||||
({"TV_IP": "192.0.2.10", "CAPTURE_JPEG_QUALITY": "96"}, "CAPTURE_JPEG_QUALITY"),
|
||||
({"TV_IP": "192.0.2.10", "CAPTURE_JPEG_QUALITY": "high"}, "CAPTURE_JPEG_QUALITY"),
|
||||
],
|
||||
)
|
||||
def test_load_config_rejects_invalid_env_values_with_config_error(
|
||||
@@ -136,6 +146,14 @@ def test_load_config_rejects_invalid_env_values_with_config_error(
|
||||
({"tv_ip": "192.0.2.10", "max_volume": 150}, "MAX_VOLUME"),
|
||||
({"tv_ip": "192.0.2.10", "max_volume": 12.5}, "MAX_VOLUME"),
|
||||
({"tv_ip": "192.0.2.10", "wol_broadcast": "bad-ip"}, "WOL_BROADCAST"),
|
||||
({"tv_ip": "192.0.2.10", "capture_max_width": 63}, "CAPTURE_MAX_WIDTH"),
|
||||
({"tv_ip": "192.0.2.10", "capture_max_width": 3841}, "CAPTURE_MAX_WIDTH"),
|
||||
({"tv_ip": "192.0.2.10", "capture_max_width": 1280.5}, "CAPTURE_MAX_WIDTH"),
|
||||
({"tv_ip": "192.0.2.10", "capture_max_width": True}, "CAPTURE_MAX_WIDTH"),
|
||||
({"tv_ip": "192.0.2.10", "capture_jpeg_quality": 0}, "CAPTURE_JPEG_QUALITY"),
|
||||
({"tv_ip": "192.0.2.10", "capture_jpeg_quality": 96}, "CAPTURE_JPEG_QUALITY"),
|
||||
({"tv_ip": "192.0.2.10", "capture_jpeg_quality": 75.5}, "CAPTURE_JPEG_QUALITY"),
|
||||
({"tv_ip": "192.0.2.10", "capture_jpeg_quality": False}, "CAPTURE_JPEG_QUALITY"),
|
||||
],
|
||||
)
|
||||
def test_tv_config_rejects_invalid_direct_arguments_with_config_error(
|
||||
@@ -210,3 +228,41 @@ def test_require_mac_returns_trimmed_value(monkeypatch: pytest.MonkeyPatch, tmp_
|
||||
|
||||
cfg = load_config(env_path=tmp_path / "missing.env")
|
||||
assert require_mac(cfg) == "AA:BB:CC:DD:EE:FF"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("width_env", "quality_env", "expected_width", "expected_quality"),
|
||||
[
|
||||
("64", "1", 64, 1),
|
||||
("3840", "95", 3840, 95),
|
||||
(" 1280 ", " 75 ", 1280, 75),
|
||||
("", " ", None, None),
|
||||
],
|
||||
)
|
||||
def test_load_config_parses_capture_max_width_and_jpeg_quality(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
tmp_path: Path,
|
||||
width_env: str,
|
||||
quality_env: str,
|
||||
expected_width: int | None,
|
||||
expected_quality: int | None,
|
||||
) -> None:
|
||||
_clear_tv_env(monkeypatch)
|
||||
monkeypatch.setenv("TV_IP", "192.0.2.10")
|
||||
monkeypatch.setenv("CAPTURE_MAX_WIDTH", width_env)
|
||||
monkeypatch.setenv("CAPTURE_JPEG_QUALITY", quality_env)
|
||||
|
||||
cfg = load_config(env_path=tmp_path / "missing.env")
|
||||
|
||||
assert cfg.capture_max_width == expected_width
|
||||
assert cfg.capture_jpeg_quality == expected_quality
|
||||
|
||||
|
||||
def test_tv_config_accepts_explicit_none_and_valid_capture_bounds() -> None:
|
||||
cfg_none = TvConfig(tv_ip="192.0.2.10", capture_max_width=None, capture_jpeg_quality=None)
|
||||
assert cfg_none.capture_max_width is None
|
||||
assert cfg_none.capture_jpeg_quality is None
|
||||
|
||||
cfg_bounds = TvConfig(tv_ip="192.0.2.10", capture_max_width=1280, capture_jpeg_quality=80)
|
||||
assert cfg_bounds.capture_max_width == 1280
|
||||
assert cfg_bounds.capture_jpeg_quality == 80
|
||||
@@ -0,0 +1,126 @@
|
||||
"""Unit tests verifying deploy/lg-smtv-mcp.service template and sandboxing directives."""
|
||||
|
||||
import configparser
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
SERVICE_TEMPLATE_PATH = Path(__file__).resolve().parent.parent / "deploy" / "lg-smtv-mcp.service"
|
||||
|
||||
|
||||
def _parse_service_template(content: str) -> configparser.ConfigParser:
|
||||
"""Parse a systemd unit file while stripping comments and preserving empty values."""
|
||||
parser = configparser.ConfigParser(
|
||||
comment_prefixes=("#", ";"),
|
||||
inline_comment_prefixes=None,
|
||||
strict=False,
|
||||
allow_no_value=True,
|
||||
)
|
||||
parser.read_string(content)
|
||||
return parser
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def systemd_analyze_bin() -> str:
|
||||
binary = shutil.which("systemd-analyze")
|
||||
if not binary:
|
||||
pytest.fail("systemd-analyze not found in PATH; ensure pkgs.systemd is in testTools")
|
||||
return binary
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def substituted_service_file(tmp_path: Path, systemd_analyze_bin: str) -> Path:
|
||||
content = SERVICE_TEMPLATE_PATH.read_text(encoding="utf-8")
|
||||
workdir = tmp_path / "workdir"
|
||||
workdir.mkdir()
|
||||
# Use neutral non-personal values derived from tmp_path (CR-02)
|
||||
substituted = (
|
||||
content.replace("<User>", "testuser")
|
||||
.replace("<WorkingDirectory>", str(workdir))
|
||||
.replace("<NixBinDir>", str(Path(systemd_analyze_bin).parent))
|
||||
)
|
||||
test_unit_file = tmp_path / "lg-smtv-mcp.service"
|
||||
test_unit_file.write_text(substituted, encoding="utf-8")
|
||||
return test_unit_file
|
||||
|
||||
|
||||
def test_service_template_exists():
|
||||
assert SERVICE_TEMPLATE_PATH.is_file(), f"Template missing at {SERVICE_TEMPLATE_PATH}"
|
||||
|
||||
|
||||
def test_service_template_declares_deployment_placeholders():
|
||||
content = SERVICE_TEMPLATE_PATH.read_text(encoding="utf-8")
|
||||
assert "<User>" in content
|
||||
assert "<WorkingDirectory>" in content
|
||||
assert "<NixBinDir>" in content
|
||||
|
||||
|
||||
def test_service_template_bounds_restart_limit_in_unit_section():
|
||||
content = SERVICE_TEMPLATE_PATH.read_text(encoding="utf-8")
|
||||
parser = _parse_service_template(content)
|
||||
|
||||
assert "Unit" in parser, "Missing [Unit] section in service template"
|
||||
unit_section = parser["Unit"]
|
||||
# CR-01: Assert exact keys and values in [Unit], not substring matches
|
||||
assert unit_section.get("startlimitintervalsec") == "60s"
|
||||
assert unit_section.get("startlimitburst") == "5"
|
||||
|
||||
|
||||
def test_service_template_enables_sandboxing_baseline_in_service_section():
|
||||
content = SERVICE_TEMPLATE_PATH.read_text(encoding="utf-8")
|
||||
parser = _parse_service_template(content)
|
||||
|
||||
assert "Service" in parser, "Missing [Service] section in service template"
|
||||
service_section = parser["Service"]
|
||||
|
||||
# CR-01: Section-aware exact-value checks; comments stripped, CapabilityBoundingSet="" enforced
|
||||
assert service_section.get("nonewprivileges") == "yes"
|
||||
assert service_section.get("privatetmp") == "yes"
|
||||
assert service_section.get("umask") == "0077"
|
||||
assert service_section.get("protectsystem") == "full"
|
||||
assert service_section.get("capabilityboundingset") == ""
|
||||
assert service_section.get("protectcontrolgroups") == "yes"
|
||||
assert service_section.get("protectkernelmodules") == "yes"
|
||||
assert service_section.get("protectkerneltunables") == "yes"
|
||||
assert service_section.get("protectkernellogs") == "yes"
|
||||
assert service_section.get("protectclock") == "yes"
|
||||
assert service_section.get("protecthostname") == "yes"
|
||||
assert service_section.get("restrictrealtime") == "yes"
|
||||
assert service_section.get("restrictsuidsgid") == "yes"
|
||||
assert service_section.get("lockpersonality") == "yes"
|
||||
|
||||
|
||||
def test_systemd_analyze_verify_succeeds_on_substituted_template(
|
||||
systemd_analyze_bin: str, substituted_service_file: Path
|
||||
):
|
||||
cmd = [systemd_analyze_bin, "verify", str(substituted_service_file)]
|
||||
# CR-04: Subprocess timeout prevents CI hang
|
||||
res = subprocess.run(cmd, capture_output=True, text=True, timeout=30.0)
|
||||
|
||||
# CR-01: Fail on warnings such as 'Unknown key' or 'Unknown lvalue' that exit 0
|
||||
assert "Unknown key" not in res.stderr, f"Unknown key in template: {res.stderr}"
|
||||
assert "Unknown lvalue" not in res.stderr, f"Unknown lvalue in template: {res.stderr}"
|
||||
assert res.returncode == 0, f"systemd-analyze verify failed: {res.stderr}"
|
||||
|
||||
|
||||
def test_systemd_analyze_security_reports_ok_exposure_bracket(
|
||||
systemd_analyze_bin: str, substituted_service_file: Path
|
||||
):
|
||||
cmd = [systemd_analyze_bin, "--offline=yes", "security", str(substituted_service_file)]
|
||||
# CR-04: Subprocess timeout prevents CI hang
|
||||
res = subprocess.run(cmd, capture_output=True, text=True, timeout=30.0)
|
||||
assert res.returncode == 0, f"systemd-analyze security failed: {res.stderr}"
|
||||
|
||||
# CR-05: Regex-parse the numeric exposure score and assert it satisfies the OK bracket (<= 5.0)
|
||||
lines = [line for line in res.stdout.splitlines() if "Overall exposure level" in line]
|
||||
assert lines, "No exposure level reported by systemd-analyze security"
|
||||
score_line = lines[0]
|
||||
|
||||
match = re.search(r"Overall exposure level.*:\s*([0-9]+\.[0-9]+)\s+OK", score_line)
|
||||
assert match is not None, f"Could not parse numeric score and OK status from: {score_line}"
|
||||
|
||||
score = float(match.group(1))
|
||||
assert score <= 5.0, f"Exposure score {score} exceeds OK bracket threshold 5.0"
|
||||
+72
-9
@@ -460,17 +460,17 @@ async def test_server_http_app_allows_authenticated_mcp_initialize_request(
|
||||
await asyncio.wait_for(lifespan_task, timeout=2.0)
|
||||
|
||||
|
||||
async def test_server_create_mcp_server_wires_default_capture_client(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
def _wire_capture_client_with_fake_ssh(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
config: TvConfig,
|
||||
) -> tuple[dict[str, Any], dict[str, bytes], list[str], list[dict[str, Any]], list[Any]]:
|
||||
import lg_smtv_mcp.server as server_mod
|
||||
from lg_smtv_mcp.tv_core.capture import CaptureClient
|
||||
|
||||
config = _make_config(tmp_path)
|
||||
captured: dict[str, Any] = {}
|
||||
remote_files: dict[str, bytes] = {}
|
||||
removed_paths: list[str] = []
|
||||
connect_calls: list[dict[str, Any]] = []
|
||||
sftp_sessions: list[Any] = []
|
||||
|
||||
class DummyManager:
|
||||
async def start(self) -> None:
|
||||
@@ -487,8 +487,20 @@ async def test_server_create_mcp_server_wires_default_capture_client(
|
||||
_ = path
|
||||
return []
|
||||
|
||||
async def read(self, path: str) -> bytes:
|
||||
return remote_files[path]
|
||||
def open(self, path: str, mode: str = "r") -> Any:
|
||||
_ = mode
|
||||
|
||||
class FakeFile:
|
||||
async def __aenter__(self) -> FakeFile:
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *_exc: object) -> None:
|
||||
return None
|
||||
|
||||
async def read(self) -> bytes:
|
||||
return remote_files[path]
|
||||
|
||||
return FakeFile()
|
||||
|
||||
async def remove(self, path: str) -> None:
|
||||
removed_paths.append(path)
|
||||
@@ -497,8 +509,6 @@ async def test_server_create_mcp_server_wires_default_capture_client(
|
||||
async def exit(self) -> None:
|
||||
self.closed = True
|
||||
|
||||
sftp_sessions: list[FakeSftp] = []
|
||||
|
||||
class FakeSshConnection:
|
||||
async def start_sftp_client(self) -> FakeSftp:
|
||||
sftp = FakeSftp()
|
||||
@@ -523,6 +533,18 @@ async def test_server_create_mcp_server_wires_default_capture_client(
|
||||
monkeypatch.setattr(server_mod, "TvManager", fake_tv_manager)
|
||||
monkeypatch.setattr(asyncssh, "connect", fake_connect)
|
||||
server_mod.create_mcp_server(config)
|
||||
return captured, remote_files, removed_paths, connect_calls, sftp_sessions
|
||||
|
||||
|
||||
async def test_server_create_mcp_server_wires_default_capture_client(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
from lg_smtv_mcp.tv_core.capture import CaptureClient
|
||||
|
||||
config = _make_config(tmp_path)
|
||||
captured, remote_files, removed_paths, connect_calls, sftp_sessions = (
|
||||
_wire_capture_client_with_fake_ssh(monkeypatch, config)
|
||||
)
|
||||
|
||||
assert captured["config"] is config
|
||||
assert "capture_client" in captured["kwargs"]
|
||||
@@ -546,3 +568,44 @@ async def test_server_create_mcp_server_wires_default_capture_client(
|
||||
assert removed_paths == ["/tmp/lg_smtv_cap_1.jpg"]
|
||||
assert len(sftp_sessions) == 1
|
||||
assert sftp_sessions[0].closed is True
|
||||
|
||||
|
||||
async def test_server_create_mcp_server_wires_capture_downscaling_config(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
from io import BytesIO
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from lg_smtv_mcp.tv_core.capture import CaptureClient
|
||||
|
||||
config = TvConfig(
|
||||
tv_ip="192.0.2.10",
|
||||
client_key_path=tmp_path / ".client_key.json",
|
||||
capture_max_width=640,
|
||||
capture_jpeg_quality=60,
|
||||
)
|
||||
captured, remote_files, _removed_paths, _connect_calls, _sftp_sessions = (
|
||||
_wire_capture_client_with_fake_ssh(monkeypatch, config)
|
||||
)
|
||||
|
||||
capture_client = captured["kwargs"]["capture_client"]
|
||||
assert isinstance(capture_client, CaptureClient)
|
||||
|
||||
buf = BytesIO()
|
||||
Image.new("RGB", (1920, 1080), color=(30, 60, 90)).save(buf, format="JPEG", quality=95)
|
||||
large_jpeg = buf.getvalue()
|
||||
|
||||
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
_ = uri
|
||||
remote_files[payload["path"]] = large_jpeg
|
||||
return {"returnValue": True}
|
||||
|
||||
try:
|
||||
result = await capture_client.capture_frame(ssap_request)
|
||||
finally:
|
||||
await capture_client.close()
|
||||
|
||||
with Image.open(BytesIO(result.image_bytes)) as img:
|
||||
assert img.format == "JPEG"
|
||||
assert img.size == (640, 360)
|
||||
Reference in new issue
Block a user