- Replace initial brainstorm brief in docs/designs/lg-smtv-mcp.md with formal architecture, Mermaid class/state diagrams, 13-tool MCP contract, deployment settings, and 16-item implementation/test plan - Establish clean baseline on main before /egm:egm-review
28 KiB
lg-smtv-mcp
- Author: kiskaadee
- Status: Draft
- 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 SSAP WebSocket, pointer input socket, subscribe state cache, and optional Developer Mode asyncssh/SFTP session warm. The server contains no LLM or vision-model calls: UI navigation loops live in the MCP host (such as Antigravity, Claude, or a gemini-decision-1 runner), 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 prohibitive latency and reliability gaps:
- Per-step handshake overhead: In the 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 cleanly when Developer Mode SSH expires, and returning compact state/image payloads.
Goals
- Run a 24/7
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) via anasyncio.Lock(10s acquire timeout) while keeping read-only state queries lock-free. - Fail fast on WebSocket close code
1008(TV_OFFLINE_STANDBY) for mutating tools, returnconnected: false, stale: truewithlast_knownvalues for 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 andclient-keypersistence. - 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, 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_coreacquires the UIasyncio.Lock, sends the three button frames over the persistent pointer socket, waitssettle_ms, triggersexecuteOneShotto/tmp/lg_smtv_cap_<seq>.jpg, reads the bytes over the persistentasyncsshSFTP session, removes the remote file infinally:, 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 normally.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>from the terminal and accepts the on-screenPROMPTwith the physical remote. - Then: The CLI saves the returned
client-keyto the configured key file 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 (planned) |
Typed TvConfig loaded from env vars / .env (TV_IP, TV_MAC, WOL_BROADCAST, CLIENT_KEY_PATH, SSH_KEY_PATH, WEBOS_SSH_PASSPHRASE, HOST, PORT, MCP_BEARER_TOKEN, MAX_VOLUME, ENABLE_RAW_SSAP). |
src/lg_smtv_mcp/errors.py (planned) |
Typed domain exceptions and error codes (TV_OFFLINE_STANDBY, PAIRING_REQUIRED, SCREENSHOT_UNAVAILABLE, LOCK_TIMEOUT, INVALID_ARGUMENT). |
src/lg_smtv_mcp/tv_core/protocols.py (planned) |
Thin Python Protocol interfaces (SsapTransport, PointerTransport, CaptureTransport, WolSender, SsdpListener) 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. |
src/lg_smtv_mcp/tv_core/pointer.py (planned) |
PointerClient: acquires getPointerInputSocket, sends plain-text type:button frames, and transparently re-acquires the socket if dropped. |
src/lg_smtv_mcp/tv_core/capture.py (planned) |
CaptureClient: persistent asyncssh SFTP session (config=[], ssh-rsa host/signature algs, passwordless key or WEBOS_SSH_PASSPHRASE), /tmp/lg_smtv_cap_<seq>.jpg pull into memory, finally: sftp.remove(), and frame_sha256 / changed_since_last tracking. |
src/lg_smtv_mcp/tv_core/wol.py (planned) |
send_wol UDP magic packet (WOL_BROADCAST, port 9) and passive ssdp:alive multicast listener (239.255.255.250:1900). |
src/lg_smtv_mcp/tv_core/manager.py (planned) |
TvManager: single-owner connection state machine, subscribe state cache (audio/getStatus, getForegroundAppInfo), asymmetric reconnect loop, and asyncio.Lock (10s timeout) serializing UI/capture operations. |
src/lg_smtv_mcp/auth.py (planned) |
Starlette/ASGI Bearer token middleware (hmac.compare_digest on Authorization: Bearer <token>) and MCP TransportSecuritySettings. |
src/lg_smtv_mcp/server.py (planned) |
FastMCP tool definitions, ImageContent formatting, partial-success shaping, max_volume enforcement, and ENABLE_RAW_SSAP gating. |
src/lg_smtv_mcp/cli.py (planned) |
CLI entrypoint supporting serve (streamable-http or stdio) and one-time interactive pair. |
classDiagram
class TvManager {
+state: ConnectionState
+ui_lock: asyncio.Lock
+wake() TvStatus
+get_state() TvStateSnapshot
+send_keys(keys, delay_ms, settle_ms, capture) KeysResult
+type_text(text, send_enter, press_enter_first, capture) TextResult
+screenshot() CaptureResult
+launch_app(app_id, content_target, params) dict
+set_volume(level) dict
+set_mute(muted) dict
+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 SsapTransport {
<<interface>>
}
class CaptureTransport {
<<interface>>
}
TvManager --> SsapClient
TvManager --> PointerClient
TvManager --> CaptureClient
SsapClient --> SsapTransport
CaptureClient --> CaptureTransport
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
STANDBY_OFFLINE --> WAKING: Explicit tv_wake tool called
STANDBY_OFFLINE --> CONNECTING: Asymmetric backoff or ssdp:alive
WAKING --> CONNECTED: Poll succeeds and register active
WAKING --> STANDBY_OFFLINE: Wake poll timeout
PAIRING_REQUIRED --> CONNECTING: Operator restarts after CLI pair
- SSAP
msg["id"]Multiplexer:SsapClientruns one background reader task that ownsws.recv(). Responses to one-shotrequest()calls resolve matchingasyncio.Futures bymsg["id"]; subscriptionresponseupdates (audio/getStatus,getForegroundAppInfo) update the in-memoryTvStateSnapshotinTvManager. - Standby & Fail-Fast: WebSocket close code
1008(Try Again Later (EWS)) or a ~1.5–2s connect timeout transitionsTvManagertoSTANDBY_OFFLINE. Mutating tools fail fast withTV_OFFLINE_STANDBYwithout triggering WoL. Read-only queries (get_state) bypassui_lockand returnconnected: false, stale: truewithlast_knownvalues. - Reconnect & Wake: In
STANDBY_OFFLINE, a single background task retries with asymmetric backoff (2s -> 5s -> 15s -> 30s) and wakes early on passivessdp:alivemulticast packets from<TV_IP>. Callingtv_wakesends the WoL magic packet and switches to ~1s polling until1008clears andregister+subscribecomplete. - UI/Capture Serialization:
send_keys,type_text, andscreenshotacquireui_lock(asyncio.Lock) with a 10s timeout (LOCK_TIMEOUTif exceeded) so concurrent callers cannot interleave pointer frames or contend for SFTP capture.
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) | Sends WoL to <TV_MAC> via WOL_BROADCAST; polls until CONNECTED; returns {status, elapsed_ms}. |
WAKE_TIMEOUT |
get_state |
(none) | Lock-free read of subscribe cache (connected, stale, volume, muted, sound_output, foreground_app, last_updated). |
(never fails on standby) |
keys |
keys: list[str], delay_ms: int = 250, settle_ms: int = 800, capture: bool = False |
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 |
type_text |
text: str, send_enter: bool = True, press_enter_first: bool = False, capture: bool = False |
Acquires ui_lock; optionally sends ENTER to open native keyboard, calls ime/insertText + sendEnterKey, optionally captures. |
TV_OFFLINE_STANDBY, PAIRING_REQUIRED, LOCK_TIMEOUT |
screenshot |
(none) | Acquires ui_lock; runs executeOneShot to /tmp/lg_smtv_cap_<seq>.jpg; reads via asyncssh SFTP; removes remote file in finally:; returns ImageContent + {frame_sha256, changed_since_last, size_bytes}. |
TV_OFFLINE_STANDBY, SCREENSHOT_UNAVAILABLE, LOCK_TIMEOUT |
launch |
app_id: str, content_target: str | None = None, params: dict | None = None |
Launches app via system.launcher/launch (merges content_target into params for YouTube/Netflix deep-links). |
TV_OFFLINE_STANDBY, PAIRING_REQUIRED |
list_apps |
(none) | Calls com.webos.applicationManager/listLaunchPoints; returns compact [{id, title}]. |
TV_OFFLINE_STANDBY |
set_volume |
level: int |
Rejects with INVALID_ARGUMENT if level < 0 or level > MAX_VOLUME (default 40); otherwise calls audio/setVolume. |
TV_OFFLINE_STANDBY, INVALID_ARGUMENT |
set_mute |
muted: bool |
Calls audio/setMute. |
TV_OFFLINE_STANDBY |
list_inputs |
(none) | Calls tv/getExternalInputList; returns [{id, label, connected}]. |
TV_OFFLINE_STANDBY |
switch_input |
input_id: str |
Explicit input switch via tv/switchInput. |
TV_OFFLINE_STANDBY |
turn_off |
(none) | Explicit power off via system/turnOff. |
TV_OFFLINE_STANDBY |
raw_ssap |
uri: str, payload: dict | None = None |
Registered only when ENABLE_RAW_SSAP=true; forwards single SSAP request. |
TV_OFFLINE_STANDBY |
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). Requests requireAuthorization: Bearer <token>verified viahmac.compare_digestagainstMCP_BEARER_TOKEN. MCPTransportSecuritySettingsrestrictsHost/Originheaders to configured local hostnames/IPs. - Headless
asyncsshKeying: On asystemdservice without an interactive TTY orssh-agent,CaptureClientconnects withconfig=[],server_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=...). - 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
SsapTransport,PointerTransport,CaptureTransport, andWolSenderimplementations intoTvManagerto deterministically test:1008fail-fast vs.tv_wakerecovery,msg["id"]interleaving betweenrequest()andsubscribe, pointer socket drop + auto-reacquire,ui_lockcontention timeout,keys(..., capture=True)partial success when SSH fails,finally: sftp.remove()cleanup on failure,frame_sha256/changed_since_last,MAX_VOLUMEguardrail,ENABLE_RAW_SSAPgating, and Bearer auth rejection. flake.nixUpdates: ExpandpythonEnvto includemcp,asyncssh,uvicorn,starlette,pytest, andpytest-asyncioalongsidewebsockets,pyright, andruff.
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: Rejected by author:
streamable-httpkeeps all TV transports and thesubscribestate cache warm 24/7 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: Rejected by author:
lg-smtv-mcpstays strictly 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: Rejected by author:
asyncssh(2.24.0) was empirically verified on Python 3.14 against:9922(config=[], explicitssh-rsaalgorithms) and fits cleanly 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: Rejected by author: capturing to
/tmp/lg_smtv_cap_<seq>.jpg, pulling only whenreturnValue: true, and callingsftp.remove()infinally: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: Rejected by author:
raw_ssapis omitted by default and registered only whenENABLE_RAW_SSAP=trueis explicitly configured.
Non-Functional Requirements
- Security & Privacy:
streamable-httpbinds to configurableHOST(default127.0.0.1, or<SERVER_IP>on private LAN), 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_lasteliminate redundant host vision turns. - Operational Resilience: WebSocket
1008fails fast (TV_OFFLINE_STANDBY),ui_locktimes out cleanly at 10s (LOCK_TIMEOUT), and Developer Mode SSH expiration degrades onlyscreenshot/capture=Truewithout disrupting SSAP or WoL tools.
Detailed Implementation Plan
Target Files to Create/Modify
1. flake.nix (Modify)
- Type / Scope: Nix development shell configuration.
- Proposed Changes: Add
mcp,asyncssh,uvicorn,starlette,pytest, andpytest-asynciotopythonEnvalongsidewebsockets,pkgs.pyright, andpkgs.ruff. Verify Python 3.14 evaluation vianix develop.
2. pyproject.toml (Create)
- Type / Scope: Python package metadata, build, and tool configuration.
- Proposed Changes: Define
lg-smtv-mcppackage undersrc/, console script entrypointlg-smtv-mcp = lg_smtv_mcp.cli:main,pytest(asyncio_mode = "auto"),ruff, andpyright(src/+tests/paths, strict/standard type-checking).
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 perAGENTS.mdSection 4. Create.env.examplewith placeholder values (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=,HOST=127.0.0.1,PORT=8765,MCP_BEARER_TOKEN=<GENERATE_TOKEN>,MAX_VOLUME=40,ENABLE_RAW_SSAP=false).
4. src/lg_smtv_mcp/__init__.py and src/lg_smtv_mcp/errors.py (Create)
- Type / Scope: Package root and typed domain error taxonomy.
- Proposed Changes: Define
TvError(Exception)carryingcode: ErrorCode(TV_OFFLINE_STANDBY,PAIRING_REQUIRED,SCREENSHOT_UNAVAILABLE,LOCK_TIMEOUT,WAKE_TIMEOUT,INVALID_ARGUMENT) andmessage: strso MCP tools map failures deterministically.
5. src/lg_smtv_mcp/config.py (Create)
- Type / Scope: Runtime configuration loader.
- Proposed Changes: Define frozen
TvConfigdataclass andload_config()reading environment variables /.envwithout hardcoded personal IPs, MACs, or paths. ValidateHOST,PORT,MAX_VOLUME(default40),WOL_BROADCAST,MCP_BEARER_TOKEN(required forstreamable-http), andENABLE_RAW_SSAP(defaultFalse).
6. src/lg_smtv_mcp/tv_core/protocols.py (Create)
- Type / Scope: Transport abstraction boundaries (
Protocols). - Proposed Changes: Define
SsapTransport,PointerTransport,CaptureTransport,WolSender, andSsdpListenerProtocolinterfaces sotv_coredepends on abstractions andpytestinjects deterministic fakes offline.
7. src/lg_smtv_mcp/tv_core/ssap.py (Create)
- Type / Scope: SSAP WebSocket client and frame multiplexer.
- Proposed Changes: Implement
SsapClientwith sharedPERMISSIONSconstant (always sent inregister, even when reusingclient-key), self-signed TLS context,1008/ connect-timeout detection (TV_OFFLINE_STANDBY),PROMPTdetection (PAIRING_REQUIREDin daemon mode; interactive wait in CLIpair), and a single background_reader_loop()routing frames bymsg["id"]to pendingasyncio.Futures orsubscribehandlers.
8. src/lg_smtv_mcp/tv_core/pointer.py (Create)
- Type / Scope: Pointer input WebSocket client.
- Proposed Changes: Implement
PointerClientcallingcom.webos.service.networkinput/getPointerInputSocket, formatting plain-texttype:button\nname:<KEY>\n\nframes, pacing batches bydelay_ms, and transparently re-acquiring the socket if closed independently of SSAP.
9. src/lg_smtv_mcp/tv_core/capture.py (Create)
- Type / Scope: Developer Mode
asyncssh/SFTP screenshot client. - Proposed Changes: Implement
CaptureClientholding a persistentasyncsshSFTP connection (config=[],server_host_key_algs=["ssh-rsa", ...],signature_algs=["ssh-rsa", ...], optionalWEBOS_SSH_PASSPHRASE). On capture: allocate/tmp/lg_smtv_cap_<seq>.jpg, callexecuteOneShot, pull into memory only ifreturnValue: true,await sftp.remove(remote_path)infinally:, computeframe_sha256andchanged_since_last, and raiseSCREENSHOT_UNAVAILABLEif SSH is disabled/expired.
10. src/lg_smtv_mcp/tv_core/wol.py (Create)
- Type / Scope: Wake-on-LAN and passive SSDP listener.
- Proposed Changes: Implement
send_wol(mac, broadcast_addr, port=9)UDP magic packet sender andSsdpAliveListenerlistening forssdp:alivefromTV_IPon239.255.255.250:1900to wake the reconnect loop when the TV boots via physical remote.
11. 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 and
subscribecache. - Proposed Changes: Implement
TvManagermanagingConnectionState(CONNECTING,CONNECTED,STANDBY_OFFLINE,WAKING,PAIRING_REQUIRED),subscribecache (audio/getStatus,getForegroundAppInfo), asymmetric reconnect backoff (2s -> 5s -> 15s -> 30s),ui_lock(asyncio.Lockwith 10s acquire timeout), lock-freeget_state()returningconnected: false, stale: true+last_knownwhen offline, and partial-success handling onsend_keys(..., capture=True).
12. src/lg_smtv_mcp/auth.py (Create)
- Type / Scope: HTTP Bearer token middleware and transport security.
- Proposed Changes: Implement Starlette/ASGI middleware verifying
Authorization: Bearer <token>viahmac.compare_digest(returning401on missing/invalid token) and configure MCPTransportSecuritySettings.
13. src/lg_smtv_mcp/server.py (Create)
- Type / Scope: FastMCP server and tool definitions.
- Proposed Changes: 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. Document thetype_textnative-keyboard requirement in its tool description, enforce0 <= level <= MAX_VOLUME, and format inlineImageContent+ metadata.
14. src/lg_smtv_mcp/cli.py (Create)
- Type / Scope: CLI entrypoint (
serve,pair). - Proposed Changes: Implement
serve --transport [streamable-http|stdio](runninguvicornwithauth.pymiddleware forstreamable-http, or FastMCPstdio) andpair --ip <TV_IP>for one-time interactivePROMPTpairing and.client_key.jsonpersistence.
15. tests/ (conftest.py, test_ssap.py, test_manager.py, test_capture.py, test_server_auth.py) (Create)
- Type / Scope: Offline
pytestunit and contract test suite. - Proposed Changes: Provide
Protocolfakes and verify:msg["id"]multiplexing with interleavedsubscribeupdates;1008fail-fast vs.tv_wakerecovery; offlineget_state(connected: false, stale: true);ui_lock10s timeout; pointer auto-reacquire;keys(..., capture=True)partial success when SSH fails;finally: sftp.remove()cleanup;frame_sha256/changed_since_last;set_volumeINVALID_ARGUMENTaboveMAX_VOLUME;ENABLE_RAW_SSAPgating; and Bearer auth401/constant-time check.
16. deploy/lg-smtv-mcp.service and README.md (Create / Modify)
- Type / Scope: Deployment template and repository documentation.
- Proposed Changes: Add a placeholder
systemdunit file (deploy/lg-smtv-mcp.service) referencingEnvironmentFileandnix develop --command lg-smtv-mcp serve, and updateREADME.mdwith setup,pair,.env, and verification instructions.
Verification Plan
- Environment & Build:
nix develop --command python -c "import lg_smtv_mcp" - Static Analysis & Linting:
nix develop --command ruff check .andnix develop --command pyright - Offline Unit & Contract Tests:
nix develop --command pytest(100% offline againstProtocolmocks; zero packets sent to physical hardware) - Manual Live-TV Integration Checks: Explicit operator-run verification of
pair,tv_wakefrom1008standby,keys(..., capture=True)withasyncssh, andset_volumecap against<TV_IP>.
Drafted with EGM