From 1ab5246fbfb8235072bdc44126f0d237c85dfb01 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Mon, 16 Nov 2026 13:52:16 -0500 Subject: [PATCH] docs: reconcile M1 architecture, roadmap, ADRs, and design spec - Add ARCHITECTURE.md documenting canonical present-state M1 topology, components, boundaries, and ADR index - Add ROADMAP.md recording M1 (#1-#4) completion and M2 (#5, #11) trajectory - Extract Alternatives A-E from docs/designs/lg-smtv-mcp.md into docs/adr/0001-0005 MADR records - Update README.md milestone status (#1-#4 merged on main, #5/#11 in M2) and Documentation links - Reconcile docs/designs/lg-smtv-mcp.md module statuses, FrameCapturer seam, and KeysResult/TextResult.image_bytes --- ARCHITECTURE.md | 71 +++++++++++++++++++ README.md | 7 +- ROADMAP.md | 22 ++++++ ...eamable-http-daemon-with-stdio-fallback.md | 21 ++++++ ...lm-free-mcp-server-with-composite-tools.md | 21 ++++++ ...-protocol-boundary-for-dev-mode-capture.md | 21 ++++++ ...ed-temp-captures-with-cleanup-and-sweep.md | 21 ++++++ docs/adr/0005-opt-in-raw-ssap-tool-gating.md | 21 ++++++ docs/designs/lg-smtv-mcp.md | 29 +++++--- 9 files changed, 221 insertions(+), 13 deletions(-) create mode 100644 ARCHITECTURE.md create mode 100644 ROADMAP.md create mode 100644 docs/adr/0001-streamable-http-daemon-with-stdio-fallback.md create mode 100644 docs/adr/0002-llm-free-mcp-server-with-composite-tools.md create mode 100644 docs/adr/0003-asyncssh-protocol-boundary-for-dev-mode-capture.md create mode 100644 docs/adr/0004-sequenced-temp-captures-with-cleanup-and-sweep.md create mode 100644 docs/adr/0005-opt-in-raw-ssap-tool-gating.md diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md new file mode 100644 index 0000000..c7b6def --- /dev/null +++ b/ARCHITECTURE.md @@ -0,0 +1,71 @@ +# 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). + +## System Overview + +The server runs primarily as a persistent `streamable-http` ASGI daemon (via `uvicorn` and FastMCP's `MCPServer`), with `stdio` supported for local test harnesses. A single-owner connection loop inside [`TvManager`](src/lg_smtv_mcp/tv_core/manager.py) maintains warm SSAP WebSocket and `subscribe` state, acquires ephemeral pointer sockets on demand, and exposes bounded control tools over [`server.py`](src/lg_smtv_mcp/server.py). + +```mermaid +flowchart LR + Host["MCP Host / Agent"] -->|"HTTPS / HTTP + Bearer Token"| Auth["BearerAuthMiddleware + TransportSecuritySettings"] + Auth --> Server["MCPServer (server.py)"] + Server --> Manager["TvManager (tv_core/manager.py)"] + Manager --> SSAP["SsapClient (wss://:3001)"] + Manager --> Pointer["PointerClient (pointer socket)"] + Manager --> WoL["send_wol (UDP :9)"] + Manager -.->|"Optional Protocol Seam (None in M1)"| Capturer["FrameCapturer (protocols.py)"] +``` + +## Architectural Principles + +- **LLM-free control plane:** No model SDKs, API keys, or internal vision loops exist in the server; decision loops live in the MCP host. +- **Boundary validation vs. internal state:** Operator inputs and environment config are validated at startup via frozen Pydantic v2 [`TvConfig`](src/lg_smtv_mcp/config.py) (`extra="forbid"`), raising [`ConfigError`](src/lg_smtv_mcp/errors.py). Runtime TV and protocol failures raise [`TvError(ErrorCode, message)`](src/lg_smtv_mcp/errors.py), mapped to FastMCP `ToolError`. +- **Fail-fast standby (`1008`):** WebSocket close code `1008` transitions [`TvManager`](src/lg_smtv_mcp/tv_core/manager.py) to `STANDBY_OFFLINE`. Mutating tools fail fast with `TV_OFFLINE_STANDBY` without implicitly sending Wake-on-LAN; read-only `get_state` bypasses `ui_lock` and returns cached fields with `connected: false, stale: true`. +- **Single-owner connection loop:** One background loop owns `wss://:3001` transitions (`CONNECTING`, `CONNECTED`, `STANDBY_OFFLINE`, `WAKING`, `PAIRING_REQUIRED`), preventing races between stepped reconnect backoff (`2s -> 5s -> 15s -> 30s`) and coalesced `wake()` calls (`45s` `WAKE_TIMEOUT`). +- **Protocol-injected testability:** External I/O boundaries (`WebSocketConnectFn`, `WebSocketTransport`, `FrameCapturer`, `wol_fn`, `wait_fn`) are injected into `tv_core` so all automated tests run offline without touching physical hardware. + +## Components & Responsibilities + +| Component | Location | Responsibility | +| :--- | :--- | :--- | +| Config & Errors | [`config.py`](src/lg_smtv_mcp/config.py), [`errors.py`](src/lg_smtv_mcp/errors.py) | Stdlib `.env` fallback loader, frozen Pydantic `TvConfig`, `ConfigError` vs. `TvError(ErrorCode, message)`. | +| Transport Protocols | [`tv_core/protocols.py`](src/lg_smtv_mcp/tv_core/protocols.py) | `WebSocketTransport`, `WebSocketConnectFn`, `WebSocketClosedError`, `CaptureTransport`, `FrameCapturer`, and frozen result dataclasses (`TvStatus`, `TvStateSnapshot`, `CaptureResult`, `KeysResult`, `TextResult`). | +| 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. | +| HTTP Auth & Security | [`auth.py`](src/lg_smtv_mcp/auth.py) | `BearerAuthMiddleware` (`hmac.compare_digest` on `Authorization: Bearer `) 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`). | + +## Data Flow & Lifecycle + +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`). When `capture=True` is passed without a configured `FrameCapturer` (M1 state), `send_keys` and `type_text` return partial success with `capture_error="SCREENSHOT_UNAVAILABLE: ..."`. +4. **Shutdown:** ASGI `lifespan` exit removes the `SIGHUP` handler and awaits `TvManager.close()`, tearing down background tasks and open transports cleanly. + +## Boundaries + +- **Network & Auth:** HTTP requests pass through `TransportSecuritySettings` (DNS-rebinding allowlist from `HOST`/`PORT`/`ALLOWED_HOSTS`) and `BearerAuthMiddleware` (`401` on missing/invalid token). +- **Device Boundary:** SSAP (`wss://:3001`, `ssl.CERT_NONE`), pointer socket (`ws://` / `wss://` returned by `getPointerInputSocket`), and WoL (`UDP` broadcast to `WOL_BROADCAST:9`). +- **Persistence:** Client pairing keys are stored as `{ip: client_key}` JSON at `CLIENT_KEY_PATH` (written atomically via `os.replace` with `0600` permissions); optional SSH key retrieval in `pair --fetch-ssh-key` writes with `0600` permissions. + +## Dependencies + +- **Runtime (`pyproject.toml` / `flake.nix`):** Python `>=3.14`, `websockets`, `mcp`, `pydantic`, `asyncssh`, `uvicorn`. +- **Development / Verification:** `pytest`, `pytest-asyncio`, `httpx`, `ruff`, `pyright` (strict mode). + +## Architectural Constraints + +- Python `>=3.14` (PEP 649 lazy annotations; `from __future__ import annotations` is banned via Ruff `TID251`). +- `pyright` runs in `strict` mode across `src/` and `tests/`. +- All automated tests run offline against injected `Protocol` doubles; physical TV hardware is never contacted during automated runs. + +## Decision Log Index + +- [ADR-0001: Streamable HTTP Daemon with Stdio Fallback](docs/adr/0001-streamable-http-daemon-with-stdio-fallback.md) +- [ADR-0002: LLM-Free MCP Server with Composite Tools](docs/adr/0002-llm-free-mcp-server-with-composite-tools.md) +- [ADR-0003: Asyncssh Protocol Boundary for Dev Mode Capture](docs/adr/0003-asyncssh-protocol-boundary-for-dev-mode-capture.md) +- [ADR-0004: Sequenced Temp Captures with Cleanup and Sweep](docs/adr/0004-sequenced-temp-captures-with-cleanup-and-sweep.md) +- [ADR-0005: Opt-In Raw SSAP Tool Gating](docs/adr/0005-opt-in-raw-ssap-tool-gating.md) diff --git a/README.md b/README.md index fc50262..877a235 100644 --- a/README.md +++ b/README.md @@ -60,8 +60,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`–`#3` merged on `main`; `#4` E2E & docs) | -| **M2** | Developer Mode SFTP screenshot capture (`asyncssh`), systemd unit, extended surface | Planned (`#5`) | +| **M1** | Core config, `tv_core` engine, FastMCP tools, Bearer auth, `pair`/`serve` CLI, E2E verification | Complete (`#1`–`#4` merged on `main`) | +| **M2** | Developer Mode SFTP screenshot capture (`asyncssh`), systemd unit, E2E test hardening | Planned (`#5`, `#11`) | 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`) @@ -202,6 +202,9 @@ nix flake check ## Documentation +- [Architecture](ARCHITECTURE.md) — Canonical present-state system topology, components, and boundaries +- [Roadmap](ROADMAP.md) — Completed M1 milestones and planned M2 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 - [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 diff --git a/ROADMAP.md b/ROADMAP.md new file mode 100644 index 0000000..b9646e0 --- /dev/null +++ b/ROADMAP.md @@ -0,0 +1,22 @@ +# Roadmap + +## Current Direction + +`lg-smtv-mcp` has completed its M1 MVP control plane (persistent SSAP, pointer input, WoL recovery, FastMCP tools, Bearer auth, `pair`/`serve` CLI, and full-stack offline E2E verification) and is moving into Milestone M2 to add Developer Mode SFTP screenshot capture, deployment packaging, and E2E test hardening. + +## Near Term (Milestone M2) + +- **Developer Mode SFTP Capture & Extended Surface ([#5](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/issues/5)):** Implement `tv_core/capture.py` (`CaptureClient` + `AsyncSshCaptureTransport` behind `FrameCapturer` / `CaptureTransport`) with `6s` shared deadline, `finally: sftp.remove()` cleanup, `/tmp/lg_smtv_cap_*.jpg` reconnect sweep, `frame_sha256` / `changed_since_last` tracking, and `deploy/lg-smtv-mcp.service` systemd unit. +- **E2E Harness & Standby Parity Hardening ([#11](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/issues/11)):** Address PR `#10` review follow-ups in [`tests/test_e2e_mvp.py`](tests/test_e2e_mvp.py) (`_build_online_ssap` extraction, fast-fail ASGI lifespan startup errors, `elapsed_ms` contract check, and post-`turn_off()` `1008` -> `get_state` stale verification). + +## 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. + +## Completed + +### 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 (PR [#7](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/7)):** `tv_core` (`SsapClient` multiplexer, `PointerClient`, `TvManager` state machine, `FrameCapturer` seam). +- **#3 (PR [#9](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/9)):** `MCPServer` tools, `BearerAuthMiddleware` + `TransportSecuritySettings`, ASGI `lifespan`, and `pair` / `serve` CLI. +- **#4 (PR [#10](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/10)):** Full-stack offline MVP E2E test (`tests/test_e2e_mvp.py`) and live-TV operator smoke checklist (`README.md`). diff --git a/docs/adr/0001-streamable-http-daemon-with-stdio-fallback.md b/docs/adr/0001-streamable-http-daemon-with-stdio-fallback.md new file mode 100644 index 0000000..9b68e12 --- /dev/null +++ b/docs/adr/0001-streamable-http-daemon-with-stdio-fallback.md @@ -0,0 +1,21 @@ +# ADR-0001: Streamable HTTP Daemon with Stdio Fallback + +- Status: Accepted +- Date: 2026-11-15 +- Deciders: kiskaadee + +## Context and Problem Statement +One-shot CLI scripts against an LG webOS TV incur ~8–10s per step in repeated `wss://:3001` TLS + `register` handshakes, `getPointerInputSocket` acquisition, and SSH setup, and cannot maintain `subscribe` state streams across tool calls. + +## Decision Outcome +Chosen option: "Run `lg-smtv-mcp` primarily as a persistent `streamable-http` ASGI daemon (with `stdio` supported for local test harnesses)", because a long-lived daemon keeps SSAP, `subscribe` state, and pointer/capture sessions warm while `BearerAuthMiddleware` and `TransportSecuritySettings` secure LAN access. + +## Consequences +- Positive: Eliminates per-step TLS/SSAP handshake overhead, preserves `subscribe` cache (`volume`, `muted`, `sound_output`, `foreground_app`), and serializes `ui_lock` across concurrent calls. +- Negative: Requires `MCP_BEARER_TOKEN` configuration and daemon lifecycle management (`serve` / `SIGHUP`) when deployed over HTTP. + +## Alternatives Considered +- Single-process `stdio` per client only: Rejected because each client session spawns a fresh process, repeating handshakes and contending for the TV's single pointer socket. + +## Related Decisions +- Documented in [docs/designs/lg-smtv-mcp.md](../designs/lg-smtv-mcp.md) (Alternative A). diff --git a/docs/adr/0002-llm-free-mcp-server-with-composite-tools.md b/docs/adr/0002-llm-free-mcp-server-with-composite-tools.md new file mode 100644 index 0000000..907bd6a --- /dev/null +++ b/docs/adr/0002-llm-free-mcp-server-with-composite-tools.md @@ -0,0 +1,21 @@ +# ADR-0002: LLM-Free MCP Server with Composite Tools + +- Status: Accepted +- Date: 2026-11-15 +- Deciders: kiskaadee + +## Context and Problem Statement +Vision-guided TV UI navigation requires multi-step button presses and screen inspection, which could either be orchestrated inside the MCP server via an embedded VLM loop or delegated to the calling MCP host. + +## Decision Outcome +Chosen option: "Keep `lg-smtv-mcp` strictly LLM-free and expose decision-model-friendly composite tools (`keys(..., capture=True)`, `type_text(..., capture=True)`, `frame_sha256` / `changed_since_last`)", because it decouples a local hardware driver from external LLM/VLM SDKs, API keys, and prompt logic while still minimizing round-trips. + +## Consequences +- Positive: Zero model dependencies or outbound API keys in the daemon; deterministic tool behavior; host can skip redundant vision turns when `changed_since_last` is `false`. +- Negative: Multi-step navigation loops must be driven by the MCP host/agent rather than a single natural-language tool call. + +## Alternatives Considered +- In-server vision navigation sub-loop: Rejected because it couples the hardware control plane to external LLM/VLM providers, model selection, and prompt engineering. + +## Related Decisions +- Documented in [docs/designs/lg-smtv-mcp.md](../designs/lg-smtv-mcp.md) (Alternative B). diff --git a/docs/adr/0003-asyncssh-protocol-boundary-for-dev-mode-capture.md b/docs/adr/0003-asyncssh-protocol-boundary-for-dev-mode-capture.md new file mode 100644 index 0000000..072efc5 --- /dev/null +++ b/docs/adr/0003-asyncssh-protocol-boundary-for-dev-mode-capture.md @@ -0,0 +1,21 @@ +# ADR-0003: Asyncssh Protocol Boundary for Dev Mode Capture + +- Status: Accepted (Protocol seams `CaptureTransport` / `FrameCapturer` implemented in M1; `CaptureClient` / `AsyncSshCaptureTransport` planned for M2 `#5`) +- Date: 2026-11-15 +- Deciders: kiskaadee + +## Context and Problem Statement +Retail LG webOS TVs do not serve `/tmp` screenshots over HTTPS (`:3001`), requiring SFTP retrieval from the Developer Mode SSH server (`prisoner@:9922`) using legacy `ssh-rsa` algorithms. + +## Decision Outcome +Chosen option: "Use `asyncssh` (`config=[]`, explicit `ssh-rsa` host-key and signature algorithms) wrapped behind `CaptureTransport` / `FrameCapturer` `Protocol` interfaces", because it keeps SFTP sessions persistent in-process and enables deterministic offline contract testing via protocol doubles. + +## Consequences +- Positive: Eliminates per-capture SSH subprocess startup and `ControlMaster` socket management; cleanly mockable in `pytest`; degrades gracefully to `SCREENSHOT_UNAVAILABLE` when Developer Mode expires. +- Negative: Requires explicit legacy `ssh-rsa` algorithm configuration in `asyncssh` and `known_hosts=None` default on LAN (overridable via `SSH_KNOWN_HOSTS_PATH`). + +## Alternatives Considered +- OpenSSH `ControlMaster` subprocesses: Rejected because managing background control sockets, parsing subprocess output/exit codes, and writing offline unit tests is more brittle. + +## Related Decisions +- Documented in [docs/designs/lg-smtv-mcp.md](../designs/lg-smtv-mcp.md) (Alternative C) and [ADR-0004](0004-sequenced-temp-captures-with-cleanup-and-sweep.md). diff --git a/docs/adr/0004-sequenced-temp-captures-with-cleanup-and-sweep.md b/docs/adr/0004-sequenced-temp-captures-with-cleanup-and-sweep.md new file mode 100644 index 0000000..fb6431d --- /dev/null +++ b/docs/adr/0004-sequenced-temp-captures-with-cleanup-and-sweep.md @@ -0,0 +1,21 @@ +# ADR-0004: Sequenced Temp Captures with Cleanup and Sweep + +- Status: Accepted (Implementation planned in M2 `#5`) +- Date: 2026-11-15 +- Deciders: kiskaadee + +## Context and Problem Statement +`ssap://com.webos.service.capture/executeOneShot` writes screenshots to a path on the TV's `/tmp` filesystem (~1.2 GB RAM). Writing to a fixed path risks reading stale frames on silent failure, while uncleaned unique paths can exhaust TV RAM. + +## Decision Outcome +Chosen option: "Capture to `/tmp/lg_smtv_cap_.jpg`, pull bytes into memory only on `returnValue: true`, delete via `finally: sftp.remove()` under a `1–2s` grace period, and sweep `/tmp/lg_smtv_cap_*.jpg` on SFTP connect/reconnect", because it prevents both stale-frame reads and `/tmp` memory exhaustion. + +## Consequences +- Positive: Guarantees fresh frame reads per sequence number and bounds `/tmp` usage even when captures fail or time out. +- Negative: Requires a `6s` shared capture deadline plus `1–2s` cleanup grace inside the `25s` `ui_lock` budget. + +## Alternatives Considered +- Fixed `/tmp/test.jpg` overwrite path: Rejected because if `executeOneShot` fails silently or races, SFTP pull can read a stale screenshot from an earlier step. + +## Related Decisions +- Documented in [docs/designs/lg-smtv-mcp.md](../designs/lg-smtv-mcp.md) (Alternative D) and [ADR-0003](0003-asyncssh-protocol-boundary-for-dev-mode-capture.md). diff --git a/docs/adr/0005-opt-in-raw-ssap-tool-gating.md b/docs/adr/0005-opt-in-raw-ssap-tool-gating.md new file mode 100644 index 0000000..cf3b626 --- /dev/null +++ b/docs/adr/0005-opt-in-raw-ssap-tool-gating.md @@ -0,0 +1,21 @@ +# ADR-0005: Opt-In Raw SSAP Tool Gating + +- Status: Accepted +- Date: 2026-11-15 +- Deciders: kiskaadee + +## Context and Problem Statement +Exposing an unrestricted SSAP pass-through tool allows calling arbitrary TV URIs, which expands the MCP tool schema and can bypass safety guardrails such as `MAX_VOLUME` and explicit `turn_off`. + +## Decision Outcome +Chosen option: "Omit `raw_ssap` by default and register it only when `ENABLE_RAW_SSAP=true` is explicitly configured", because closed-set decision models stay within safe, bounded tools in normal operation while operators retain an escape hatch for debugging. + +## Consequences +- Positive: Preserves `MAX_VOLUME` and input/power guardrails by default and keeps the MCP tool schema compact. +- Negative: Ad-hoc SSAP experiments require restarting the server with `ENABLE_RAW_SSAP=true`. + +## Alternatives Considered +- Unconditional `raw_ssap` tool: Rejected because it weakens guardrails and enlarges the tool surface for decision-model callers. + +## Related Decisions +- Documented in [docs/designs/lg-smtv-mcp.md](../designs/lg-smtv-mcp.md) (Alternative E). diff --git a/docs/designs/lg-smtv-mcp.md b/docs/designs/lg-smtv-mcp.md index 920b73d..b9af8de 100644 --- a/docs/designs/lg-smtv-mcp.md +++ b/docs/designs/lg-smtv-mcp.md @@ -78,14 +78,14 @@ All runtime code lives under `src/lg_smtv_mcp/`, separating the transport/protoc | :--- | :--- | | [`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/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` *(planned)* | Thin Python `Protocol` interfaces (`WebSocketTransport`, `WebSocketConnectFn`, `WebSocketClosedError`, `CaptureTransport`) enabling offline contract tests. | -| `src/lg_smtv_mcp/tv_core/ssap.py` *(planned)* | `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` *(planned)* | `PointerClient`: acquires `getPointerInputSocket`, normalizes/validates keys, sends plain-text `type:button` frames, and automatically re-acquires the socket if dropped. | -| `src/lg_smtv_mcp/tv_core/capture.py` *(planned)* | `CaptureClient`: calls `executeOneShot` via `ssap_request_fn` and delegates SFTP I/O (`read_and_remove`, `sweep_temp_files`, `close`) to `CaptureTransport` (persistent `asyncssh` session), tracking `frame_sha256` / `changed_since_last`. | -| `src/lg_smtv_mcp/tv_core/manager.py` *(planned)* | `TvManager`: single-owner connection loop + state machine, `send_wol` helper, `subscribe` state cache, stepped reconnect backoff, `CaptureClient` 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` *(planned)* | Minimal ASGI Bearer token middleware (`hmac.compare_digest` on `Authorization: Bearer `) wrapping FastMCP's `streamable_http_app()` and `TransportSecuritySettings`. | -| `src/lg_smtv_mcp/server.py` *(planned)* | FastMCP tool definitions, `ImageContent` formatting, partial-success shaping, `max_volume` enforcement, `ENABLE_RAW_SSAP` gating, and ASGI `lifespan` wiring for `TvManager` + `SIGHUP`. | -| `src/lg_smtv_mcp/cli.py` *(planned)* | CLI entrypoint supporting `serve` (`streamable-http` with fail-closed `MCP_BEARER_TOKEN` check, or `stdio`) and one-time interactive `pair` (`.client_key.json` + optional `--fetch-ssh-key`). | +| [`src/lg_smtv_mcp/tv_core/protocols.py`](../../src/lg_smtv_mcp/tv_core/protocols.py) | Thin 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` *(planned, M2)* | `CaptureClient` (implementing `FrameCapturer`): calls `executeOneShot` via `ssap_request_fn` and delegates SFTP I/O (`read_and_remove`, `sweep_temp_files`, `close`) to `CaptureTransport` (persistent `asyncssh` session), tracking `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) | Minimal ASGI Bearer token middleware (`hmac.compare_digest` on `Authorization: Bearer `) wrapping FastMCP's `streamable_http_app()` and `TransportSecuritySettings`. | +| [`src/lg_smtv_mcp/server.py`](../../src/lg_smtv_mcp/server.py) | FastMCP tool definitions, `ImageContent` formatting, partial-success shaping, `max_volume` enforcement, `ENABLE_RAW_SSAP` gating, and ASGI `lifespan` wiring for `TvManager` + `SIGHUP`. | +| [`src/lg_smtv_mcp/cli.py`](../../src/lg_smtv_mcp/cli.py) | CLI entrypoint supporting `serve` (`streamable-http` with fail-closed `MCP_BEARER_TOKEN` check, or `stdio`) and one-time interactive `pair` (`.client_key.json` + optional `--fetch-ssh-key`). | ```mermaid classDiagram @@ -115,6 +115,11 @@ classDiagram +send_buttons(keys, delay_ms) int +close() void } + class FrameCapturer { + <> + +capture_frame(ssap_request_fn) CaptureResult + +close() void + } class CaptureClient { +capture_frame(ssap_request_fn) CaptureResult +close() void @@ -133,7 +138,8 @@ classDiagram } TvManager --> SsapClient TvManager --> PointerClient - TvManager --> CaptureClient + TvManager --> FrameCapturer + CaptureClient ..|> FrameCapturer SsapClient --> WebSocketTransport PointerClient --> WebSocketTransport CaptureClient --> CaptureTransport @@ -144,7 +150,8 @@ classDiagram | `TvManager` | `wake() -> TvStatus`, `get_state() -> TvStateSnapshot`, `send_keys(keys, delay_ms, settle_ms, capture) -> KeysResult`, `type_text(text, send_enter, capture) -> TextResult`, `screenshot() -> CaptureResult`, `launch_app(app_id, content_target, params) -> dict`, `list_apps() -> list[dict]`, `set_volume(level) -> dict`, `set_mute(muted) -> dict`, `list_inputs() -> list[dict]`, `switch_input(input_id) -> dict`, `turn_off() -> dict`, `raw_ssap(uri, payload) -> dict` | | `SsapClient` | `async connect_and_register(client_key: str \| None) -> str`, `async request(uri: str, payload: dict \| None) -> dict`, `async subscribe(uri: str, callback: Callable[[dict], None]) -> None`, `async close() -> None` | | `PointerClient` | `async send_buttons(keys: list[str], delay_ms: int) -> int`, `async close() -> None` | -| `CaptureClient` | `async capture_frame(ssap_request_fn: Callable[[str, dict], Awaitable[dict]]) -> CaptureResult`, `async close() -> None` | +| `FrameCapturer` | `async capture_frame(ssap_request_fn: Callable[[str, dict], Awaitable[dict]]) -> CaptureResult`, `async close() -> None` | +| `CaptureClient` | Implements `FrameCapturer` *(planned, M2)* | | `WebSocketTransport` | `async send(data: str) -> None`, `async recv() -> str`, `async close() -> None` (raises `WebSocketClosedError(code, reason)` on close); `WebSocketConnectFn = Callable[[str], Awaitable[WebSocketTransport]]` | | `CaptureTransport` | `async read_and_remove(remote_path: str, timeout: float, cleanup_grace: float) -> bytes`, `async sweep_temp_files(prefix: str) -> None`, `async close() -> None` | @@ -295,7 +302,7 @@ Implementation proceeds in three incremental phases, each ending with its listed #### 6. `src/lg_smtv_mcp/tv_core/protocols.py` (Create) * **Type / Scope:** Transport abstraction boundaries (`Protocol`s) and result schemas. -* **Proposed Changes:** Define `WebSocketClosedError(code: int, reason: str)`, `WebSocketTransport` (`send`, `recv`, `close`), `WebSocketConnectFn = Callable[[str], Awaitable[WebSocketTransport]]`, and `CaptureTransport` (`read_and_remove`, `sweep_temp_files`, `close`). Define frozen result dataclasses/TypedDicts: `TvStatus(status: Literal["connected", "already_connected"], elapsed_ms: int)`, `TvStateSnapshot(connected: bool, stale: bool, volume: int | None, muted: bool | None, sound_output: str | None, foreground_app: str | None, last_updated: float | None)`, `KeysResult(keys_sent: bool, count: int, frame_sha256: str | None, changed_since_last: bool | None, size_bytes: int | None, capture_error: str | None)`, `TextResult(text_sent: bool, enter_sent: bool, frame_sha256: str | None, changed_since_last: bool | None, size_bytes: int | None, capture_error: str | None)`, and `CaptureResult(image_bytes: bytes, frame_sha256: str, changed_since_last: bool, size_bytes: int)`. +* **Proposed Changes:** Define `WebSocketClosedError(code: int, reason: str)`, `WebSocketTransport` (`send`, `recv`, `close`), `WebSocketConnectFn = Callable[[str], Awaitable[WebSocketTransport]]`, `CaptureTransport` (`read_and_remove`, `sweep_temp_files`, `close`), and `FrameCapturer` (`capture_frame`, `close`). Define frozen result dataclasses: `TvStatus(status: Literal["connected", "already_connected"], elapsed_ms: int)`, `TvStateSnapshot(connected: bool, stale: bool, volume: int | None, muted: bool | None, sound_output: str | None, foreground_app: str | None, last_updated: float | None)`, `KeysResult(keys_sent: bool, count: int, frame_sha256: str | None = None, changed_since_last: bool | None = None, size_bytes: int | None = None, capture_error: str | None = None, image_bytes: bytes | None = None)`, `TextResult(text_sent: bool, enter_sent: bool, frame_sha256: str | None = None, changed_since_last: bool | None = None, size_bytes: int | None = None, capture_error: str | None = None, image_bytes: bytes | None = None)`, and `CaptureResult(image_bytes: bytes, frame_sha256: str, changed_since_last: bool, size_bytes: int)`. #### 7. `src/lg_smtv_mcp/tv_core/ssap.py` (Create)