- docs/designs/lg-smtv-mcp.md: update Phase 1 (#1-#5) and module table for ConfigError vs TvError separation, frozen Pydantic v2 TvConfig, single-sourced flake.nix deps, strict Pyright, Python 3.14 TID251, and nix flake check - README.md: align setup stack and pre-commit hook description with flake.nix
43 KiB
lg-smtv-mcp
- Author: kiskaadee
- Status: Approved
- Date: 2026-11-15
Overview
lg-smtv-mcp is a Python Model Context Protocol (MCP) server for local-network control of a single pre-paired LG webOS Smart TV. It runs primarily as a long-lived streamable-http daemon on a homelab server on the same LAN (with stdio supported for local testing), keeping the Simple Service Access Protocol (SSAP, LG webOS's local JSON-over-WebSocket control protocol on wss://<TV_IP>:3001), pointer input socket, subscribe state cache, and optional LG Developer Mode asyncssh/SFTP session (prisoner@<TV_IP>:9922) warm. The server contains no LLM or vision-model calls: UI navigation loops live in the MCP host (such as Antigravity, Claude, or a closed-set action-router model like gemini-decision-1), while lg-smtv-mcp exposes deterministic, decision-model-friendly tools and composite actions (such as batched key sequences with optional inline ImageContent screenshots).
The Problem
Controlling an LG webOS TV from an AI agent or automation host using one-shot CLI scripts introduces high per-step latency and reliability gaps (documented in docs/poc/capabilities.md and docs/poc/crunchyroll-e2e-experiment.md against WebOS/4.1.0):
- Per-step handshake overhead: In the Crunchyroll PoC (docs/poc/crunchyroll-e2e-experiment.md), navigating from app launch to episode playback took 13 steps and ~7 minutes (
427s), largely because each step spawned a fresh process,wss://:3001TLS +registerhandshake,getPointerInputSocketconnection, andscpsession. - Protocol hazards on persistent connections: Running
subscribestreams (audio/getStatus,getForegroundAppInfo) concurrently with tool calls breaks one-shotws.recv()patterns. Additionally, when the TV is in standby,wss://:3001accepts the WebSocket upgrade and closes immediately with1008 (Try Again Later (EWS)), andime/insertTextsilently returnsreturnValue: trueeven when the native keyboard is closed. - Unbounded token and
/tmpcosts: Without batched key execution, inline image return, and deterministic frame-change detection (frame_sha256), the host pays an extra round-trip and vision-model turn on unchanged frames. Without per-call/tmpcleanup, repeated captures can exhaust the TV's ~1.2 GB RAM.
lg-smtv-mcp solves this by keeping persistent, serialized connections inside a homelab streamable-http daemon, failing fast on 1008 standby, degrading only capture operations when the TV's Developer Mode SSH session timer expires, and returning compact state/image payloads.
Goals
- Run a continuous
streamable-httpMCP daemon bound to a configurableHOSTaddress (defaulting to127.0.0.1locally, or the homelab LAN interface when deployed) with constant-timeAuthorization: Bearer <token>authentication, plusstdiotransport for local test harnesses. - Maintain persistent SSAP (
wss://:3001), pointer input socket,subscribestate cache, and optionalasyncssh/SFTP (:9922) connections inside a unifiedtv_corepackage. - Serialize stateful UI and capture operations (
keys,type_text,screenshot) with bounded contention while keeping read-only state queries non-blocking. - Fail fast on WebSocket close code
1008(TV_OFFLINE_STANDBY) for mutating tools, return cached flat fields withconnected: false, stale: truefor read-only queries, and provide an explicittv_waketool using configurable Wake-on-LAN broadcast. - Expose decision-model-friendly composite tools (
keyswith delays and optional inlineImageContent,type_text,launchwith deep-link helpers,screenshotwithframe_sha256andchanged_since_last,set_volumewith configurablemax_volume=40cap, explicitturn_off/switch_input, and opt-inENABLE_RAW_SSAP=true). - Provide a one-time CLI
paircommand for interactive on-screenPROMPTregistration,client-keypersistence, and optional--fetch-ssh-keyDeveloper Mode key retrieval. - Verify all behavior offline via
pytestcontract tests overProtocolmocks, passingruffandpyrightinsidenix develop.
Non-Goals
- Embedding LLM/VLM API keys, outbound model calls, or an internal vision-navigation loop inside
lg-smtv-mcp. - Adding an extra HTTP or IPC wrapper service behind the MCP server.
- Exposing arbitrary SSH command execution on the TV or retaining screenshot files in
/tmp. - Multi-TV fleet management or interactive
PROMPTpairing inside MCP tool calls. - Implicitly waking the TV on normal control or state-query calls.
Open Questions
None. All architectural questions from the initial RFC have been resolved.
Critical User Journeys (CUJs)
CUJ 1: Standby Detection and Explicit Wake
- Given: The TV is in standby (
wss://<TV_IP>:3001closes with1008 Try Again Later (EWS)), and the daemon is running inSTANDBY_OFFLINEstate. - When: An MCP client calls
launch("youtube.leanback.v4"). - Then: The tool fails fast with
TV_OFFLINE_STANDBYwithout sending a Wake-on-LAN packet. The client then callstv_wake, which broadcasts the WoL magic packet to<TV_MAC>on the configured broadcast address/port, polls until1008clears andregister+subscribesucceed (~30–35stypical cold wake within a45sbudget), and returns the online status.
CUJ 2: Vision-Guided UI Navigation with Batched Keys and Change Detection
- Given: The TV is online and Developer Mode SSH (
:9922) is active. - When: A host decision loop calls
keys(["LEFT", "UP", "ENTER"], delay_ms=250, settle_ms=1000, capture=True). - Then:
tv_coreserializes the operation, validates key names against the allowlist, sends the three button frames over the persistent pointer socket, waitssettle_ms, captures and cleans up the remote screenshot into memory, and returnskeys_sent: true, inlineImageContent,frame_sha256, andchanged_since_last.
CUJ 3: Graceful Degradation When Developer Mode SSH Expires
- Given: The TV is online, SSAP and pointer sockets are connected, and Developer Mode SSH (
:9922) is disabled or expired. - When: A client calls
keys(["DOWN", "ENTER"], capture=True)orset_volume(15). - Then:
set_volume(15)succeeds.keys(..., capture=True)executes the keystrokes and returns partial success (keys_sent: true,capture_error: "SCREENSHOT_UNAVAILABLE: ...") so the caller knows not to re-send the keys.
CUJ 4: One-Time CLI Pairing
- Given: A new or reset TV has no saved
client-keyon the homelab server. - When: The operator runs
lg-smtv-mcp pair --ip <TV_IP>(optionally with--fetch-ssh-key) from the terminal and accepts the on-screenPROMPTwith the physical remote. - Then: The CLI saves the returned
client-key(and optionalwebos_rsawith0600permissions) to the configured path, allowing thestreamable-httpdaemon to start and register non-interactively.
Technical Plan (Architecture)
1. Package & Module Layout
All runtime code lives under src/lg_smtv_mcp/, separating the transport/protocol boundaries and state machine (tv_core) from the MCP tool surface (server.py), HTTP Bearer auth (auth.py), and CLI entrypoints (cli.py).
| Module | Responsibility |
|---|---|
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 |
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.Futures 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 <token>) 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). |
classDiagram
class TvManager {
+state: ConnectionState
+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
+set_volume(level) dict
+set_mute(muted) dict
+list_inputs() list
+switch_input(input_id) dict
+turn_off() dict
+raw_ssap(uri, payload) dict
}
class SsapClient {
+connect_and_register(client_key) str
+request(uri, payload) dict
+subscribe(uri, callback) void
+close() void
}
class PointerClient {
+send_buttons(keys, delay_ms) int
+close() void
}
class CaptureClient {
+capture_frame(ssap_request_fn) CaptureResult
+close() void
}
class WebSocketTransport {
<<interface>>
+send(data) void
+recv() str
+close() void
}
class CaptureTransport {
<<interface>>
+read_and_remove(remote_path, timeout, cleanup_grace) bytes
+sweep_temp_files(prefix) void
+close() void
}
TvManager --> SsapClient
TvManager --> PointerClient
TvManager --> CaptureClient
SsapClient --> WebSocketTransport
PointerClient --> WebSocketTransport
CaptureClient --> CaptureTransport
| Component | Key Contract Signatures |
|---|---|
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 |
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 |
2. Connection State Machine, Frame Dispatch & Concurrency
stateDiagram-v2
[*] --> CONNECTING: Daemon startup
CONNECTING --> CONNECTED: register succeeds and subscribe active
CONNECTING --> STANDBY_OFFLINE: WS close 1008 or connect timeout
CONNECTING --> PAIRING_REQUIRED: register returns PROMPT
CONNECTED --> STANDBY_OFFLINE: Socket closed / 1008 / ping timeout
CONNECTED --> PAIRING_REQUIRED: Pairing revoked
STANDBY_OFFLINE --> WAKING: Explicit tv_wake tool called
STANDBY_OFFLINE --> CONNECTING: Asymmetric backoff
WAKING --> CONNECTED: Poll succeeds and register active
WAKING --> PAIRING_REQUIRED: Wake register returns PROMPT
WAKING --> STANDBY_OFFLINE: Wake poll timeout (45s)
PAIRING_REQUIRED --> CONNECTING: Backoff tick or SIGHUP reloads key file
- SSAP
msg["id"]Multiplexer:SsapClientruns one background_reader_loop()task that ownsws.recv(). Responses to one-shotrequest()calls resolve matchingasyncio.Futures bymsg["id"]. Live-verifiedsubscribestreams onWebOS/4.1.0(ssap://audio/getStatus—wherevolumeandmuteare top-level andsoundOutputis nested underpayload["volumeStatus"]["soundOutput"]—andssap://com.webos.applicationManager/getForegroundAppInfo) update the in-memoryTvStateSnapshotinTvManager. Mutating requests push subscription update frames before their own request response frame, whichmsg["id"]routing demultiplexes. On disconnect,_reader_loop()'sfinally:block fails all pendingFutures withTV_OFFLINE_STANDBY. - Standby & Fail-Fast: WebSocket close code
1008(Try Again Later (EWS)), ping timeout (ping_interval=10, ping_timeout=5), oropen_timeout(3.0–4.0s) transitionsTvManagertoSTANDBY_OFFLINEand tears down any openCaptureClientSSH/SFTP session (which reconnects lazily on the next capture). Mutating tools fail fast withTV_OFFLINE_STANDBYwithout triggering WoL. Read-only queries (get_state) bypassui_lockand return the flat state dict (connected: false, stale: truewith cached values retained from the last online update). - Single-Owner Reconnect, Wake & Key Reload: A single connection loop owns
wss://:3001transitions sotv_wakeand background reconnect (2s -> 5s -> 15s -> 30s) never race. Callingtv_wakeinSTANDBY_OFFLINEsends the WoL magic packet, signals the connection loop intoWAKING(~1spolling up to a45sWAKE_TIMEOUTbudget, covering~30–35sempirical cold standby boot), and awaits a shared connection event. Concurrenttv_wakecalls inWAKINGcoalesce onto the in-flight attempt;tv_wakeinCONNECTEDreturns{status: "already_connected", elapsed_ms: 0};tv_wakeinPAIRING_REQUIREDfails fast withPAIRING_REQUIRED. InPAIRING_REQUIRED,TvManagerre-checksCLIENT_KEY_PATH({ip: client_key}JSON, written atomically viaos.replacebycli.py pair) on its backoff tick orSIGHUP(logging and remaining inPAIRING_REQUIREDif the file is missing or malformed). - UI/Capture Serialization & Timeout Budget:
send_keys,type_text, andscreenshotacquireui_lock(asyncio.Lock) with a25sacquire timeout (LOCK_TIMEOUTif exceeded).keysvalidates key names against a strict webOS button allowlist (UP,DOWN,LEFT,RIGHT,ENTER,BACK,HOME,EXIT,PLAY,PAUSE,STOP,REWIND,FASTFORWARD,RED,GREEN,YELLOW,BLUE,VOLUMEUP,VOLUMEDOWN,MUTE,CHANNELUP,CHANNELDOWN,INFO,GUIDE,MENU,CC,0–9), rejecting unknown names or control characters (\r,\n) withINVALID_ARGUMENT, and bounds1 <= len(keys) <= 20,0 <= delay_ms <= 500, and0 <= settle_ms <= 2000.CaptureClient.capture_frame()wraps SSH connect +executeOneShot+ SFTP read in a shared6sdeadline (asyncio.timeout(6.0)) plus a1–2sfinally: sftp.remove()grace period (<= 8scapture phase), keeping worst-casekeys+capturehold time within the25sui_lockbudget.
3. MCP Tool Surface
All tools return structured JSON payloads (plus inline MCP ImageContent when capture=True or screenshot succeeds).
| Tool | Inputs | Output / Behavior | Error Codes |
|---|---|---|---|
tv_wake |
(none) | Coalesced WoL wake to <TV_MAC> via WOL_BROADCAST; polls up to 45s; returns {status, elapsed_ms} (already_connected if already online). |
WAKE_TIMEOUT, PAIRING_REQUIRED |
get_state |
(none) | Lock-free read returning flat dict (connected, stale, volume, muted, sound_output, foreground_app, last_updated; cached fields retain last known values when connected: false, stale: true). |
(never fails on standby) |
keys |
keys: list[str], delay_ms: int = 250, settle_ms: int = 800, capture: bool = False |
Validates allowlist and bounds; acquires ui_lock; sends pointer buttons; if capture=True, captures frame. On SSH failure after keys succeed, returns {keys_sent: true, count, capture_error} (partial success). |
TV_OFFLINE_STANDBY, PAIRING_REQUIRED, LOCK_TIMEOUT, INVALID_ARGUMENT |
type_text |
text: str, send_enter: bool = True, capture: bool = False |
Acquires ui_lock; calls ime/insertText + optional sendEnterKey (requires native on-screen keyboard to be open); if capture=True, captures frame (returning {text_sent: true, capture_error} partial success on SSH failure). |
TV_OFFLINE_STANDBY, PAIRING_REQUIRED, LOCK_TIMEOUT |
screenshot |
(none) | Acquires ui_lock; captures frame into memory and removes remote temp file; returns ImageContent + {frame_sha256, changed_since_last, size_bytes}. |
TV_OFFLINE_STANDBY, PAIRING_REQUIRED, SCREENSHOT_UNAVAILABLE, LOCK_TIMEOUT |
launch |
app_id: str, content_target: str | None = None, params: dict | None = None |
Calls ssap://system.launcher/launch with {"id": app_id, "params": ...}. When content_target is provided, sets params["contentTarget"] = content_target (overriding any params["contentTarget"]; see docs/poc/capabilities.md). |
TV_OFFLINE_STANDBY, PAIRING_REQUIRED |
list_apps |
(none) | Calls com.webos.applicationManager/listLaunchPoints; returns compact [{id, title}]. |
TV_OFFLINE_STANDBY, PAIRING_REQUIRED |
set_volume |
level: int |
Rejects with INVALID_ARGUMENT if level < 0 or level > MAX_VOLUME (default 40); otherwise calls audio/setVolume. |
TV_OFFLINE_STANDBY, PAIRING_REQUIRED, INVALID_ARGUMENT |
set_mute |
muted: bool |
Calls audio/setMute. |
TV_OFFLINE_STANDBY, PAIRING_REQUIRED |
list_inputs |
(none) | Calls tv/getExternalInputList; returns [{id, label, connected}]. |
TV_OFFLINE_STANDBY, PAIRING_REQUIRED |
switch_input |
input_id: str |
Explicit input switch via tv/switchInput. |
TV_OFFLINE_STANDBY, PAIRING_REQUIRED |
turn_off |
(none) | Explicit power off via system/turnOff. |
TV_OFFLINE_STANDBY, PAIRING_REQUIRED |
raw_ssap |
uri: str, payload: dict | None = None |
Registered only when ENABLE_RAW_SSAP=true; forwards single SSAP request. |
TV_OFFLINE_STANDBY, PAIRING_REQUIRED |
4. Runtime Configuration, Security & Daemon Deployment
- Network & Auth:
streamable-httpbinds toHOST(default127.0.0.1for local dev;<SERVER_IP>on the LAN when deployed) andPORT(default8765). Startup fails closed ifMCP_BEARER_TOKENis unset or whitespace-only. Requests requireAuthorization: Bearer <token>verified viahmac.compare_digest.TransportSecuritySettingsderivesallowed_hosts/allowed_originsfromHOST/PORT,127.0.0.1/localhost, and optionalALLOWED_HOSTS. - ASGI
lifespanOwnership: FastMCP/Starlette's ASGIlifespancontext manager startsTvManageron Uvicorn's active event loop, registersSIGHUPvialoop.add_signal_handler, and closesSsapClient,PointerClient, andCaptureClienton shutdown. - Developer Mode SSH Lifecycle & Headless
asyncsshKeying: Retail LG webOS TVs do not serve/tmpscreenshots over HTTPS (:3001), soCaptureClientpulls captures over SFTP from the unprivileged SSH server (prisoner@<TV_IP>:9922) provided by LG's official Developer Mode app (see docs/poc/capabilities.md). Port:9922is available only while "Dev Mode Status" and "Key Server" are enabled on the TV, and LG automatically disables Developer Mode when its countdown timer expires (at which pointCaptureClientraisesSCREENSHOT_UNAVAILABLEwhile all SSAP and WoL tools continue operating). On a headlesssystemdservice,CaptureClientconnects withconfig=[],known_hosts=None(overridable viaSSH_KNOWN_HOSTS_PATH), legacyserver_host_key_algs=["ssh-rsa", ...],signature_algs=["ssh-rsa", ...], and either a dedicated passwordless service key (SSH_KEY_PATH) orWEBOS_SSH_PASSPHRASEpassed toasyncssh.connect(..., passphrase=...).lg-smtv-mcp pair --fetch-ssh-keyretrieveshttp://<TV_IP>:9991/webos_rsaand saves it with0600permissions. - WoL Broadcast:
WOL_BROADCASTdefaults to255.255.255.255and can be set to the LAN subnet broadcast (e.g.,<LAN_SUBNET_BROADCAST>) on multi-homed hosts so magic packets exit on the TV's Ethernet/Wi-Fi segment.
5. Offline Testing & Nix Environment
- Offline Contract Tests: Tests inject fake
WebSocketTransportandCaptureTransportimplementations (plus a fakesend_wolcallback) intoTvManagerto test:1008fail-fast vs.tv_wakerecovery and coalescing,CaptureClientteardown onSTANDBY_OFFLINEand/tmp/lg_smtv_cap_*.jpgsweep on reconnect,msg["id"]interleaving betweenrequest()andsubscribe(audio/getStatusnestedsoundOutput), pendingFuturefailure on disconnect, pointer socket drop + auto-reacquire,keysallowlist/bounds (INVALID_ARGUMENT),ui_lock25stimeout andCaptureClient6sdeadline +1–2scleanup isolation,keys(..., capture=True)andtype_text(..., capture=True)partial success when SSH fails,finally: sftp.remove()cleanup on failure,frame_sha256/changed_since_last,PAIRING_REQUIREDkey reload (including malformed JSON handling),MAX_VOLUMEguardrail,ENABLE_RAW_SSAPgating, and fail-closed Bearer auth. flake.nixUpdates: Exposepackages.${system}.defaultviabuildPythonApplication(pyproject = true,setuptools,websockets,mcp,asyncssh,uvicorn) and expanddevShells.${system}.default(mcp = "2.3.0",asyncssh = "2.24.0",uvicorn,httpx,pytest = "9.1.1",pytest-asyncio = "1.4.1",websockets,pyright,ruff) with aPYTHONPATH="$PWD/src:${PYTHONPATH:-}"shellHook.
Alternatives Considered
Alternative A: Single-Process stdio Per Client Only
- Pros: Zero HTTP server, port binding, or Bearer token configuration required.
- Cons: Every client session spawns a new process, repeating
wss://:3001TLS +register,getPointerInputSocket, and:9922SSH handshakes; concurrent clients contend for the TV's single pointer socket. - Reason for Rejection:
streamable-httpkeeps all TV transports and thesubscribestate cache warm continuously whilestdioremains available for local test harnesses.
Alternative B: In-Server Vision Navigation Sub-Loop
- Pros: Could encapsulate multi-step UI navigation behind a single high-level natural-language tool call.
- Cons: Couples a local hardware driver to external LLM/VLM API keys, provider SDKs, model selection, and prompt engineering.
- Reason for Rejection:
lg-smtv-mcpstays LLM-free; latency and token overhead are addressed instead via composite tools (keys(..., capture=True)) and deterministicframe_sha256/changed_since_lastmetadata.
Alternative C: OpenSSH ControlMaster Subprocess for Screenshots
- Pros: Uses system OpenSSH directly for legacy
ssh-rsacompatibility. - Cons: Requires managing background
sshcontrol sockets, parsing subprocess output/exit codes, and complicates offline unit testing. - Reason for Rejection:
asyncssh(2.24.0) was verified on Python 3.14 against:9922(config=[], explicitssh-rsaalgorithms) and wraps behind an asyncProtocolmock.
Alternative D: Fixed /tmp/test.jpg Overwrite Path
- Pros: Bounded to a single file on
/tmpwithout explicit delete calls. - Cons: If
executeOneShotfails silently or races, SFTP pull can read a stale screenshot from an earlier step. - Reason for Rejection: Capturing to
/tmp/lg_smtv_cap_<seq>.jpg, pulling only whenreturnValue: true, callingsftp.remove()infinally:, and sweeping stale files on reconnect prevents both stale reads and/tmpexhaustion on the TV's ~1.2 GB RAM.
Alternative E: Unconditional raw_ssap Tool
- Pros: Allows calling arbitrary SSAP URIs at any time without code changes.
- Cons: Expands the tool schema and weakens guardrails (
max_volume, explicitturn_off) for closed-set decision models. - Reason for Rejection:
raw_ssapis omitted by default and registered only whenENABLE_RAW_SSAP=trueis explicitly configured.
Risks & Mitigations
| Risk | Impact | Mitigation |
|---|---|---|
| Developer Mode SSH timer expires on TV | Screenshot capture fails (SCREENSHOT_UNAVAILABLE) |
Degrade only screenshot / capture=True (returning partial success on keys / type_text); keep all SSAP and WoL tools active. |
Orphaned /tmp/lg_smtv_cap_*.jpg on SSH stall |
Gradual /tmp RAM growth on TV (~1.2 GB RAM) |
Per-call finally: sftp.remove() under 1–2s grace + sweep of /tmp/lg_smtv_cap_*.jpg on SFTP connect/reconnect. |
Concurrent tv_wake / reconnect race or cold wake delay |
Duplicate sockets or premature WAKE_TIMEOUT |
Single-owner connection loop coalescing tv_wake + 45s budget (~30–35s empirical cold boot). |
Dev Mode host-key regeneration or headless known_hosts failure |
SSH connection rejected on :9922 |
Default known_hosts=None on LAN with optional SSH_KNOWN_HOSTS_PATH override. |
Pointer frame newline injection or oversized keys batch |
Unintended pointer commands or ui_lock starvation |
Strict button allowlist (rejecting \r/\n), batch/delay caps, and 25s ui_lock timeout. |
Non-Functional Requirements
- Security & Privacy:
streamable-httpbinds to configurableHOST(default127.0.0.1, or<SERVER_IP>on private LAN), fails closed ifMCP_BEARER_TOKENis unset, enforcesAuthorization: Bearer <token>viahmac.compare_digest, and configures MCPTransportSecuritySettings. Arbitrary SSH command execution is never exposed..client_key.json,.env, SSH keys, and*.jpgcaptures are excluded from version control. - Performance & Latency: Persistent SSAP, pointer, and
asyncsshSFTP connections eliminate per-step TLS/SSH handshakes (~8–10s/step in PoC); batchedkeys(..., capture=True)andframe_sha256/changed_since_lastallow the host to skip redundant vision turns. - Operational Resilience: WebSocket
1008fails fast (TV_OFFLINE_STANDBY),ui_locktimes out at25swithLOCK_TIMEOUT, and Developer Mode SSH expiration degrades onlyscreenshot/capture=Truewithout disrupting SSAP or WoL tools.
Detailed Implementation Plan
Implementation proceeds in three incremental phases, each ending with its listed verification checkpoint (pytest starts in Phase 2).
Phase 1: Environment, Packaging, Config & Error Taxonomy
1. flake.nix (Modify)
- Type / Scope: Nix package and development shell configuration.
- Proposed Changes: Expose
packages.${system}.defaultviapkgs.python3Packages.buildPythonApplication(pyproject = true,build-system = [ ps.setuptools ], single-sourcedruntimeDeps[ ps.websockets ps.mcp ps.pydantic ps.asyncssh ps.uvicorn ],testDeps[ ps.httpx ps.pytest ps.pytest-asyncio ], andpreCheckrunningruff check .,ruff format --check .,pyright, pluspytestCheckHook). UpdatedevShells.${system}.defaultto includepythonEnv(runtimeDeps ++ testDeps),pkgs.pyright, andpkgs.ruff, withshellHookexportingPYTHONPATH="$PWD/src:${PYTHONPATH:-}"and configuringgit config core.hooksPath .githooks.
2. pyproject.toml (Create)
- Type / Scope: Python package metadata, build, and tool configuration.
- Proposed Changes: Set
[build-system]tosetuptools.build_meta, definelg-smtv-mcp(requires-python = ">=3.14") undersrc/with[project].dependencies = ["websockets", "mcp", "pydantic", "asyncssh", "uvicorn"], console scriptlg-smtv-mcp = "lg_smtv_mcp.cli:main",[tool.pytest.ini_options](asyncio_mode = "auto",pythonpath = ["src"]),[tool.ruff](includingTID251banningfrom __future__ import annotationsinsrc/andtests/), and[tool.pyright](include = ["src", "tests"],typeCheckingMode = "strict",pythonVersion = "3.14").
3. .gitignore and .env.example (Modify / Create)
- Type / Scope: Secret hygiene and runtime configuration template.
- Proposed Changes: Ensure
.gitignoreexcludes.client_key.json,.env,*.jpg, and SSH keys per AGENTS.md Section 4. Create.env.examplewith placeholders (TV_IP=<TV_IP>,TV_MAC=<TV_MAC>,WOL_BROADCAST=255.255.255.255,CLIENT_KEY_PATH=.client_key.json,SSH_KEY_PATH=,WEBOS_SSH_PASSPHRASE=,SSH_KNOWN_HOSTS_PATH=,HOST=127.0.0.1,PORT=8765,ALLOWED_HOSTS=,MCP_BEARER_TOKEN=<GENERATE_TOKEN>,MAX_VOLUME=40,ENABLE_RAW_SSAP=false).
4. src/lg_smtv_mcp/__init__.py, src/lg_smtv_mcp/__main__.py, and src/lg_smtv_mcp/errors.py (Create)
- Type / Scope: Package root,
python -m lg_smtv_mcpentrypoint, and typed domain error taxonomy. - Proposed Changes: Add
__main__.pydelegating tocli.main(). Inerrors.py, defineConfigError(Exception)for startup/operator configuration failures,ErrorCode(StrEnum)(TV_OFFLINE_STANDBY,PAIRING_REQUIRED,SCREENSHOT_UNAVAILABLE,LOCK_TIMEOUT,WAKE_TIMEOUT,COMMAND_FAILED,INVALID_ARGUMENT), andTvError(Exception)carryingcode: ErrorCodeandmessage: strfor uniform MCP error mapping.
5. src/lg_smtv_mcp/config.py (Create)
-
Type / Scope: Runtime configuration loader and stdlib
.envparser. -
Proposed Changes: Implement a minimal stdlib
.envparser inload_config()that populates unsetos.environkeys from.env(if present). Define frozen Pydantic v2TvConfig(BaseModel,ConfigDict(frozen=True, extra="forbid"), remappingValidationErrortoConfigError) validatingTV_IP(required IPv4),0 <= MAX_VOLUME <= 100(default40),1 <= PORT <= 65535(default8765), comma-separatedALLOWED_HOSTS,WOL_BROADCAST(IPv4, default255.255.255.255),SSH_KNOWN_HOSTS_PATH,ENABLE_RAW_SSAP(defaultFalse), and command-specific requirements (require_bearer_token()forserve --transport streamable-http;require_mac()fortv_wake), all raisingConfigErroron invalid configuration. -
Phase 1 Checkpoint:
nix develop --command python -c "import lg_smtv_mcp",nix develop --command bash -c "ruff check . && ruff format --check . && pyright && pytest", andnix flake check.
Phase 2: tv_core Transports, State Machine & Offline Contract Tests
6. src/lg_smtv_mcp/tv_core/protocols.py (Create)
- Type / Scope: Transport abstraction boundaries (
Protocols) and result schemas. - Proposed Changes: Define
WebSocketClosedError(code: int, reason: str),WebSocketTransport(send,recv,close),WebSocketConnectFn = Callable[[str], Awaitable[WebSocketTransport]], andCaptureTransport(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), andCaptureResult(image_bytes: bytes, frame_sha256: str, changed_since_last: bool, size_bytes: int).
7. src/lg_smtv_mcp/tv_core/ssap.py (Create)
- Type / Scope: SSAP WebSocket client and frame multiplexer.
- Proposed Changes: Implement
SsapClienttakingWebSocketConnectFnwithopen_timeout = 3.5,ping_interval = 10,ping_timeout = 5, andssl.CERT_NONE/check_hostname = False. Pin the 16PERMISSIONS(LAUNCH,CONTROL_AUDIO,CONTROL_DISPLAY,CONTROL_POWER,CONTROL_INPUT_TEXT,CONTROL_INPUT_MEDIA_PLAYBACK,CONTROL_INPUT_JOYSTICK,CONTROL_INPUT_TV,CONTROL_TV_MEDIA,CONTROL_MOUSE_AND_KEYBOARD,READ_INSTALLED_APPS,READ_RUNNING_APPS,READ_INPUT_DEVICE_LIST,READ_TV_CHANNEL_LIST,READ_POWER_STATE,WRITE_NOTIFICATION_TOAST) and always send them inregister(matchingdocs/poc/tv_test.pyPERMISSIONS/build_register_payload()). MapWebSocketClosedError(code=1008)/ connect timeout toTV_OFFLINE_STANDBY, andPROMPTin daemon mode toPAIRING_REQUIRED.request(uri, payload)returnsmsg["payload"](dict[str, Any]) and raisesTvError(COMMAND_FAILED,PAIRING_REQUIREDon401 insufficient permissions, orTV_OFFLINE_STANDBY) ifmsg["type"] == "error"orpayload.get("returnValue") is False. In_reader_loop()'sfinally:, fail all pendingasyncio.Futures withTV_OFFLINE_STANDBY.
8. src/lg_smtv_mcp/tv_core/pointer.py (Create)
- Type / Scope: Pointer input WebSocket client.
- Proposed Changes: Implement
PointerClientcallingssap://com.webos.service.networkinput/getPointerInputSocketand opening the pointer socket viaWebSocketConnectFn. Normalize key names to uppercase, validate against the strict button allowlist (rejecting unknown names or\r/\nwithINVALID_ARGUMENT), formattype:button\nname:<KEY>\n\n, pace bydelay_ms, and retry once by re-acquiring the pointer socket if a mid-batch send fails due to socket drop.
9. src/lg_smtv_mcp/tv_core/capture.py (Create)
- Type / Scope: Developer Mode
asyncssh/SFTP screenshot client andCaptureTransportadapter. - Proposed Changes: Implement
AsyncSshCaptureTransport(prisoner@<TV_IP>:9922,config=[],known_hosts=Nonedefault orSSH_KNOWN_HOSTS_PATH,server_host_key_algs=["ssh-rsa"],signature_algs=["ssh-rsa"], optionalWEBOS_SSH_PASSPHRASE), lazily connecting/reconnecting itsasyncsshSFTP session insideread_and_remove()and runningsweep_temp_files("/tmp/lg_smtv_cap_")on each new SFTP connection. InCaptureClient.capture_frame(ssap_request_fn), wrapssap://com.webos.service.capture/executeOneShot({"path": "/tmp/lg_smtv_cap_<seq>.jpg", "method": "DISPLAY", "format": "JPG"}) andCaptureTransport.read_and_remove(remote_path, timeout=6.0, cleanup_grace=1.5)underasyncio.timeout(6.0). RaiseSCREENSHOT_UNAVAILABLEifexecuteOneShotreturnsreturnValue: falseor SSH fails, and computeframe_sha256andchanged_since_last.
10. src/lg_smtv_mcp/tv_core/manager.py and src/lg_smtv_mcp/tv_core/__init__.py (Create)
- Type / Scope: Single-owner connection state machine,
subscribecache, and WoL helper. - Proposed Changes:
- Implement
send_wol(mac, broadcast_addr, port=9)UDP magic packet helper. - Implement
TvManagerowning a single connection loop (CONNECTING,CONNECTED,STANDBY_OFFLINE,WAKING,PAIRING_REQUIRED), stepped reconnect backoff (2s -> 5s -> 15s -> 30s),CaptureClient.close()teardown onSTANDBY_OFFLINE, andCLIENT_KEY_PATH({ip: client_key}) reload onPAIRING_REQUIREDbackoff ticks orSIGHUP(logging and staying inPAIRING_REQUIREDon malformed JSON). - Coalesce
wake()via the connection loop (45sWAKE_TIMEOUTbudget;{status: "already_connected", elapsed_ms: 0}inCONNECTED; fast-fail inPAIRING_REQUIRED). - Subscribe to
ssap://audio/getStatus(reading top-levelvolume/muteand nestedvolumeStatus.soundOutput) andssap://com.webos.applicationManager/getForegroundAppInfo, transitioningCONNECTED -> PAIRING_REQUIREDon401 insufficient permissions. - Expose lock-free
get_state()(last_updatedviatime.time(),connected: false, stale: truewhen offline),ui_lock(asyncio.Lockwith25sacquire timeout), and exact SSAP payloads:setVolume({"volume": level}),switchInput({"inputId": input_id}),insertText({"text": text, "replace": 0}),listLaunchPoints(payload["launchPoints"]->[{id, title}]), andgetExternalInputList(payload["devices"]->[{id, label, connected}]).
- Implement
11. tests/conftest.py, tests/test_ssap.py, tests/test_capture.py, and tests/test_manager.py (Create)
-
Type / Scope: Offline
tv_corecontract tests. -
Proposed Changes:
tests/test_ssap.py: Verifymsg["id"]multiplexing with interleavedsubscribeupdates,1008->TV_OFFLINE_STANDBY,COMMAND_FAILEDonreturnValue: false, and pendingFuturefailure in_reader_loop()finally:.tests/test_capture.py: VerifyexecuteOneShotreturnValue: false->SCREENSHOT_UNAVAILABLE,finally: sftp.remove()under1.5sgrace,sweep_temp_fileson reconnect,6.0sshared deadline, andframe_sha256/changed_since_last.tests/test_manager.py: Verifytv_wakecoalescing,CONNECTEDno-op, and45sWAKE_TIMEOUT;CaptureClientteardown onSTANDBY_OFFLINE;audio/getStatusnestedsoundOutput; offlineget_stateflat dict;keysallowlist/newline/bounds rejection and mid-batch pointer re-acquire;ui_lock25stimeout;keys/type_text(..., capture=True)partial success when SSH fails;PAIRING_REQUIREDreload on backoff/SIGHUP(including malformed JSON); andMAX_VOLUMEguardrail.
-
Phase 2 Checkpoint:
nix develop --command ruff check . && nix develop --command pyright && nix develop --command pytest tests/test_ssap.py tests/test_capture.py tests/test_manager.py.
Phase 3: FastMCP Server, Bearer Auth, CLI & Deployment
12. src/lg_smtv_mcp/auth.py (Create)
- Type / Scope: HTTP Bearer token ASGI middleware and transport security.
- Proposed Changes: Implement an ASGI middleware verifying
Authorization: Bearer <token>viahmac.compare_digest(returning401on missing/invalid token) around FastMCP's built-instreamable_http_app(), and configure MCPTransportSecuritySettings(allowed_hosts/allowed_originsfromHOST/PORT,127.0.0.1/localhost, andALLOWED_HOSTS).
13. src/lg_smtv_mcp/server.py (Create)
- Type / Scope: FastMCP server, ASGI
lifespan, and tool definitions. - Proposed Changes: Bind
TvManagerstartup,SIGHUPloop.add_signal_handler, and connection/task teardown on shutdown to FastMCP's ASGIlifespancontext manager. Register all 12 default tools (tv_wake,get_state,keys,type_text,screenshot,launch,list_apps,set_volume,set_mute,list_inputs,switch_input,turn_off) and conditionally registerraw_ssaponly whenENABLE_RAW_SSAP=true. MapTvErrorto FastMCPToolError(f"{err.code.value}: {err.message}"); returnlist[TextContent | ImageContent](TextContentJSON metadata +ImageContent(type="image", data=base64_jpeg, mimeType="image/jpeg")) when an image is captured. Inlaunch, buildparams = dict(params or {}), setparams["contentTarget"] = content_targetif provided, and include"params": paramsin the SSAP payload only when non-empty. Validate1 <= len(text) <= 500intype_text(INVALID_ARGUMENT) and document the native-keyboard requirement in its tool description.
14. src/lg_smtv_mcp/cli.py (Create)
- Type / Scope: CLI entrypoint (
serve,pair). - Proposed Changes: Implement
serve --transport [streamable-http|stdio](failing closed ifMCP_BEARER_TOKENis unset/whitespace forstreamable-http; delegating to FastMCP'sstreamable_http_app()wrapped withauth.py, orFastMCP.run(transport="stdio")). Implementpair [--ip <TV_IP>] [--fetch-ssh-key] [--ssh-key-path <PATH>](defaulting--iptoTV_IPfromTvConfig), merging existing.client_key.jsonentries before atomicos.replace, and optionally fetchinghttp://<TV_IP>:9991/webos_rsavia stdliburllib.requestto--ssh-key-path(defaulting toSSH_KEY_PATHor.webos_rsa) with0600permissions (keeping any saved client key and exiting non-zero if key fetch fails).
15. tests/test_server_auth.py (Create)
- Type / Scope: Offline MCP server and HTTP auth contract tests.
- Proposed Changes: Use
httpxASGI test client against FastMCP +auth.pyto verify Bearer auth401/200constant-time checks,TransportSecuritySettingshost validation,ENABLE_RAW_SSAPgating,ToolErrorformatting,launchparamsconstruction,type_textlength bounds, andlist[TextContent | ImageContent]image responses.
16. deploy/lg-smtv-mcp.service and README.md (Create / Modify)
-
Type / Scope: Deployment template and repository documentation.
-
Proposed Changes: Add
deploy/lg-smtv-mcp.serviceusing<User>,<WorkingDirectory>, andEnvironmentFileplaceholders invokingnix develop --command python -m lg_smtv_mcp serve, and updateREADME.mdwith setup,pair --fetch-ssh-key/ Developer Mode SSH setup,.env, and verification instructions. -
Phase 3 Checkpoint:
nix develop --command ruff check . && nix develop --command pyright && nix develop --command pytest
Verification Plan
- Environment & Build:
nix develop --command python -c "import lg_smtv_mcp"andnix build - Static Analysis & Linting:
nix develop --command ruff check .andnix develop --command pyright - Offline Unit & Contract Tests:
nix develop --command pytest(offline againstProtocolmocks; zero packets sent to physical hardware) - Manual Live-TV Integration Checks: Explicit operator-run verification of
pair --fetch-ssh-key,tv_wakefrom1008standby,keys(..., capture=True)withasyncssh, andset_volumecap against<TV_IP>.
Drafted with EGM