- Move doc/poc/* to docs/poc/* and update references in README.md and RFC - Add docs/designs/lg-smtv-mcp.md architecture RFC from egm-brainstorm - Link docs/designs/lg-smtv-mcp.md from README.md
11 KiB
lg-smtv-mcp
- Author: kiskaadee
- Date: 2026-11-15
Overview
lg-smtv-mcp is a Python Model Context Protocol (MCP) server for controlling a single pre-paired LG webOS Smart TV over the local network. 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 SSAP WebSocket, pointer input socket, subscribe state cache, and optional Developer Mode asyncssh/SFTP connections warm. It stays strictly LLM-free: vision-guided UI navigation lives in the MCP host (such as Antigravity, Claude, or a gemini-decision-1 loop), while the server exposes high-level, decision-model-friendly tools and composite actions (such as batched key sequences with optional inline ImageContent screenshots).
Analysis
Core Architecture & Connection Lifecycle
-
Central SSAP Frame Dispatcher: The PoC script (
docs/poc/tv_test.py) uses one-shotawait ws.recv()calls. In a persistent daemon that holds activesubscribestreams (audio/getStatus,getForegroundAppInfo) alongside tool requests, a single background reader task ownsws.recv()and routes incoming frames bymsg["id"]to pendingasyncio.Futures while dispatching subscription push updates to the state cache. -
Single-Owner Connection State Machine & Standby Handling: Empirically, when the TV is in standby or booting,
wss://192.168.1.11:3001accepts the TLS/WebSocket upgrade and immediately closes with1008 (policy violation) Try Again Later (EWS).tv_coreuses an explicit state machine (STANDBY_OFFLINE->CONNECTING->CONNECTED/WAKING) so thattv_wakepolling and background reconnect never race onwss://:3001or double-register. Mutating tools treat1008(or a ~1.5–2s connect timeout) as an immediateTV_OFFLINE_STANDBYerror rather than blocking or auto-waking the TV. -
Pointer Socket Auto-Recovery & Daemon Pairing Guard:
getPointerInputSocketopens a secondarywss://socket for plain-text button frames (type:button). If the TV drops the pointer socket independently of the main SSAP socket,keystransparently re-acquires it rather than failing the call. BecausegetPointerInputSocketrequiresmanifest.permissionseven when reusing a savedclient-key,PERMISSIONSis pinned as a shared constant between the CLIpaircommand and the daemon. If the TV responds toregisterwithpairingType: "PROMPT"during daemon operation, the daemon fails fast withPAIRING_REQUIREDinstead of hanging for a human with a physical remote. -
Read vs. Write Concurrency & Offline State: Stateful UI and capture operations (
keys,type_text,screenshot) are serialized with anasyncio.Lock(with a 10s acquire timeout) so concurrent MCP clients cannot interleave keystrokes or contend for capture resources. Read-onlysubscribe-cached queries (get_state,get_audio_status,get_foreground_app) bypass the UI lock and, when the TV is in standby, returnconnected: false, stale: truealongsidelast_knownvalues rather than failing.
Inventive Contradictions & Resolutions
-
Fail-Fast Standby (
1008) vs. Detecting Manual Power-Ons: Mutating tools need1008to fail immediately, while background reconnect needs to notice when someone turns the TV on with the physical remote without hammeringwss://:3001every second.- Resolution: Combine asymmetric reconnect backoff (e.g., 2s -> 5s -> 15s -> 30s) with passive SSDP
ssdp:alivemulticast listening (239.255.255.250:1900), which wakes the reconnect loop immediately when the TV boots, whiletv_waketriggers fast polling (~1s) after sending the Wake-on-LAN packet to255.255.255.255:9.
- Resolution: Combine asymmetric reconnect backoff (e.g., 2s -> 5s -> 15s -> 30s) with passive SSDP
-
Stale-Capture Risk vs.
/tmpRAM Budget on the TV: Overwriting a single fixed/tmp/test.jpgrisks returning a stale previous screenshot ifexecuteOneShotfails silently, while leaving unique capture files behind risks filling/tmpon the TV's ~1.2 GB RAM.- Resolution: Capture to a unique per-call path (
/tmp/lg_smtv_cap_<seq>.jpg), only pull via SFTP ifexecuteOneShotreturnsreturnValue: true, read bytes directly into memory (await f.read()), and alwaysawait sftp.remove(remote_path)in afinally:block.
- Resolution: Capture to a unique per-call path (
-
Pure LLM-Free Server vs. Vision-Loop Turn Overhead: In
docs/poc/crunchyroll-e2e-experiment.md, Step 6 (ime/insertTextbefore the native keyboard opened) returned the exact same18,947 Bscreenshot and cost an extra ~11–13s vision/LLM turn.- Resolution: Include deterministic
frame_sha256andchanged_since_last: boolmetadata on all captures so the host's decision loop can skip redundant vision-model calls when a screen has not changed.
- Resolution: Include deterministic
Tool Ergonomics, Safety & Environment
- Partial-Success Semantics: On composite actions (
keys(..., capture=True)), if keystrokes succeed and Dev Mode SSH fails, return partial success (keys_sent: true,capture_error: "...") so the caller never double-sends keystrokes. - Native Keyboard Quirk in
type_text:ssap://com.webos.service.ime/insertTextreturnsreturnValue: truesilently even when the native webOS keyboard is not open. Exposetype_text(text, send_enter=True, press_enter_first=False, capture=False)and state this requirement explicitly in the tool description. - Verified
asyncsshTransport & Headless Daemon Keying: Dev Mode SSH on port9922(userprisoner) is empirically verified on Python 3.14 withasyncssh 2.24.0usingconfig=[],server_host_key_algs=["ssh-rsa", ...], andsignature_algs=["ssh-rsa", ...]. Because a 24/7 systemd daemon onserver-localhas no interactive TTY or unlockedssh-agent,asyncssh.connectmust support a dedicated passwordless service key or an optionalWEBOS_SSH_PASSPHRASEenv/secret. - WoL Broadcast Targeting: Because
server-local(192.168.1.36) is multi-homed (LAN Ethernet + Tailscale), make the WoL broadcast address configurable (e.g., subnet broadcast192.168.1.255or255.255.255.255, port9) so magic packets exit on the LAN interface toward the TV. - Guardrails & HTTP Security: Default
max_volume = 40(configurable via env/config); keepturn_offandswitch_inputexplicit; omitraw_ssapby default (gated behind opt-inENABLE_RAW_SSAP=true). Bindstreamable-httponly to the homelab LAN/Tailscale interface, validateAuthorization: Bearer <token>withhmac.compare_digest, and configure MCPTransportSecuritySettings. - Offline Testability: Abstract SSAP, pointer socket, WoL, and
asyncssh/SFTP behind thin PythonProtocolinterfaces sopytestruns full offline contract tests without hitting the live TV.
Ideal Final Result
A single homelab streamable-http process keeps all TV transports warm with zero outbound LLM dependencies, fails fast on standby (1008), degrades cleanly when Dev Mode SSH expires, cleans up every per-call screenshot in memory, and returns compact state/image payloads with deterministic change detection so any external host or decision model can drive the TV in seconds.
Goals vs. Non-Goals
-
In-Scope Goals:
- Long-lived
streamable-httpMCP daemon (LAN/Tailscale bound, static Bearer token auth) plusstdiotransport for local testing. - Unified
tv_coreasync module with central SSAP dispatcher, pointer socket auto-recovery,subscribestate caching, andasyncio.Lockserialization for UI/capture tools. - Explicit
tv_waketool (WoL to255.255.255.255:9+ polling) and fail-fastTV_OFFLINE_STANDBYhandling on WebSocket close code1008for mutating tools. - Read-only state queries returning
connected: false, stale: truewithlast_knownvalues when offline. - Composite, decision-model-friendly tools (
keyswith delays + optional inlineImageContentand partial-success reporting,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). - One-time CLI
paircommand for interactive on-screenPROMPTregistration andclient-keypersistence. - Persistent
asyncssh/SFTP (:9922) capture to/tmp/lg_smtv_cap_<seq>.jpgwithfinally: sftp.remove(...)cleanup and graceful degradation when Dev Mode is off or expired. - Offline
pytestunit/contract test suite mocking SSAP, pointer, WoL, andasyncsshboundaries, passingpyrightandruff.
- Long-lived
-
Out-of-Scope Non-Goals:
- Outbound LLM/VLM API calls, API keys, or built-in vision-navigation loops inside
lg-smtv-mcp. - Extra HTTP or IPC wrapper servers behind the MCP server.
- Arbitrary SSH command execution on the TV or retaining screenshot files on
/tmp. - Multi-TV fleet management or automatic first-time
PROMPTpairing inside MCP tool calls. - Implicit auto-wake on normal control/query tools.
- Outbound LLM/VLM API calls, API keys, or built-in vision-navigation loops inside
Alternatives Weighed
- Single-process
stdioper client vs.streamable-httpdaemon: Rejectedstdio-only because per-session spawns repeat TLS/SSAP/SSH handshakes and allow concurrent clients to contend for the TV's single pointer socket.streamable-httpis primary;stdioremains supported for local test harnesses. - In-server vision sub-loop vs. pure device MCP: Rejected in-server vision loop because it couples a hardware interface to model API keys, providers, and prompts. Kept orchestration in the host and moved efficiency gains into composite tools and deterministic
frame_sha256/changed_since_lastmetadata. - OpenSSH
ControlMastersubprocess vs.asyncsshpersistent SFTP: Rejected OpenSSHControlMastersubprocess in favor ofasyncssh(2.24.0), which was empirically verified on Python 3.14 against192.168.1.11:9922and avoids subprocess management while keepingProtocolmocking clean. - Fixed
/tmp/test.jpgoverwrite vs. per-call/tmp/lg_smtv_cap_<seq>.jpg+finally: remove: Rejected fixed path because a failedexecuteOneShotcould return a stale prior image; per-call paths pulled into memory and deleted infinally:prevent both stale reads and/tmpexhaustion. - Unconditional
raw_ssapvs. gatedENABLE_RAW_SSAP=true: Omittedraw_ssapfrom the default tool surface to keep decision-model schemas small, while allowing opt-in debug access via config.
Key Decisions & Staging for Next Steps
- Transport & Auth:
streamable-httpdaemon (LAN/Tailscale bind,Authorization: Bearer <token>viahmac.compare_digest,TransportSecuritySettings) +stdiofor local harnesses. - SSAP & Concurrency: Background reader task routing by
msg["id"]+subscribecache;asyncio.Lock(10s timeout) on UI/capture tools; lock-free read queries returningconnected: false, stale: true+last_knownwhen offline. - Standby & Wake: Fail fast on
1008withTV_OFFLINE_STANDBY; explicittv_wakevia WoL (255.255.255.255:9); asymmetric reconnect backoff + optional passive SSDPssdp:alivelistener. - Capture & Guardrails:
asyncsshpersistent SFTP (config=[], explicitssh-rsaalgs),/tmp/lg_smtv_cap_<seq>.jpg+finally: sftp.remove,frame_sha256+changed_since_last, partial-success reporting onkeys(..., capture=True),max_volume = 40default,ENABLE_RAW_SSAP=trueopt-in. - Testing: Offline
pytestcontract tests overProtocolboundaries +pyright+ruff+ manual live-TV checks.