Core Architecture & Invariant CI / validate (push) Failing after 0s
- README.md: add step-by-step Getting Started guide (TV prerequisites, host setup, .env/token, pairing, server run, MCP client connection) so new users have a linear onboarding path; add CAPTURE_MAX_WIDTH/CAPTURE_JPEG_QUALITY, pillow, M2.1 status, and docs/experiments/ link. - ARCHITECTURE.md: add pillow to runtime dependencies and document CaptureClient host-side JPEG downscaling, KeyImportError mapping, and server.py config wiring so architecture reflects main. - ROADMAP.md: add M2.1 active items (#21-#23) to Near Term and record #20 (PR #24) plus Crunchyroll E2E benchmarks under Completed. - docs/designs/lg-smtv-mcp.md: reconcile config.py and capture.py rows in Package & Module Layout for #20 capture downscaling and KeyImportError handling.
9.2 KiB
9.2 KiB
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, Milestone M2 Developer Mode capture & systemd packaging, and M2.1 host-side JPEG downscaling).
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 maintains warm SSAP WebSocket and subscribe state, acquires ephemeral pointer sockets on demand, and exposes bounded control tools over server.py.
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 --> Capturer["CaptureClient (tv_core/capture.py)"]
Capturer --> Transport["AsyncSshCaptureTransport (asyncssh/SFTP :9922)"]
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(extra="forbid"), raisingConfigError. Runtime TV and protocol failures raiseTvError(ErrorCode, message), mapped to FastMCPToolError. - Fail-fast standby (
1008): WebSocket close code1008transitionsTvManagertoSTANDBY_OFFLINE. Mutating tools fail fast withTV_OFFLINE_STANDBYwithout implicitly sending Wake-on-LAN; read-onlyget_statebypassesui_lockand returns cached fields withconnected: false, stale: true. - Single-owner connection loop: One background loop owns
wss://<TV_IP>:3001transitions (CONNECTING,CONNECTED,STANDBY_OFFLINE,WAKING,PAIRING_REQUIRED), preventing races between stepped reconnect backoff (2s -> 5s -> 15s -> 30s) and coalescedwake()calls (45sWAKE_TIMEOUT). - Protocol-injected testability: External I/O boundaries (
WebSocketConnectFn,WebSocketTransport,CaptureTransport,FrameCapturer,wol_fn,wait_fn) are injected intotv_coreso all automated tests run offline without touching physical hardware.
Components & Responsibilities
| Component | Location | Responsibility |
|---|---|---|
| Config & Errors | config.py, errors.py |
Stdlib .env fallback loader, frozen Pydantic TvConfig, ConfigError vs. TvError(ErrorCode, message). |
| Transport Protocols | tv_core/protocols.py |
WebSocketTransport, WebSocketConnectFn, WebSocketClosedError, CaptureTransport, FrameCapturer, and frozen result dataclasses (TvStatus, TvStateSnapshot, CaptureResult, KeysResult, TextResult). |
| SSAP Client | 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 |
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 |
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 |
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 |
BearerAuthMiddleware (hmac.compare_digest on Authorization: Bearer <token>) and build_transport_security_settings for DNS-rebinding protection. |
| MCP Server | 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, __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
- Startup:
cli.py serveloadsTvConfig, requiresMCP_BEARER_TOKENforstreamable-http, builds the ASGI app viacreate_http_app, and startsuvicorn. The ASGIlifespanstartsTvManagerand registersSIGHUPfor.client_key.jsonreload. - Steady-state & Subscriptions: When connected,
SsapClient._reader_loop()routes incoming frames bymsg["id"]to either awaiting requestFutures orsubscribehandlers updatingTvState(volume,muted,sound_output,foreground_app,last_updated). - Serialized UI Control:
send_keys,type_text, andscreenshotacquireui_lockwith a25stimeout (LOCK_TIMEOUT).create_mcp_serverdefault-wiresTvManager(..., capture_client=CaptureClient(AsyncSshCaptureTransport(config), max_width=config.capture_max_width, jpeg_quality=config.capture_jpeg_quality)), socapture=Truecaptures over SFTP and optionally downscales/recompresses the JPEG in memory; when the capture transport is unavailable (Developer Mode SSH off or expired),send_keysandtype_textreturn partial success withcapture_error="SCREENSHOT_UNAVAILABLE: ..."whilescreenshotfails withSCREENSHOT_UNAVAILABLE.TvManagercloses the SFTP session on standby and transport transitions. - Shutdown: ASGI
lifespanexit removes theSIGHUPhandler and awaitsTvManager.close(), tearing down background tasks and open transports cleanly.
Boundaries
- Network & Auth: HTTP requests pass through
TransportSecuritySettings(DNS-rebinding allowlist fromHOST/PORT/ALLOWED_HOSTS) andBearerAuthMiddleware(401on missing/invalid token). - Device Boundary: SSAP (
wss://<TV_IP>:3001,ssl.CERT_NONE), pointer socket (ws:///wss://returned bygetPointerInputSocket), WoL (UDPbroadcast toWOL_BROADCAST:9), and Developer Mode SSH/SFTP (prisoner@<TV_IP>:9922withconfig=[]and explicitssh-rsahost-key/signature algorithms). Host-key verification is disabled by default on a trusted LAN (known_hosts=None) and can be pinned withSSH_KNOWN_HOSTS_PATH. - Persistence: Client pairing keys are stored as
{ip: client_key}JSON atCLIENT_KEY_PATH(written atomically viaos.replacewith0600permissions); optional SSH key retrieval inpair --fetch-ssh-keywrites with0600permissions.
Dependencies
- 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
- Python
>=3.14(PEP 649 lazy annotations;from __future__ import annotationsis banned via RuffTID251). pyrightruns instrictmode acrosssrc/andtests/.- Screenshot capture shares a
6.0sdeadline overexecuteOneShot+ SFTP read, plus a1.5sshielded cleanup grace, inside the25sui_lockbudget. - All automated tests run offline against injected
Protocoldoubles; physical TV hardware is never contacted during automated runs.