5 Commits
Author SHA1 Message Date
kiskaadee 6aff4e5411 chore: track direnv .envrc for flake devShell 2026-11-15 00:48:53 -05:00
kiskaadee 800a43456a chore: rescope repo to lg-smtv-mcp and archive PoC under doc/poc
- Move discover.py, tv_test.py, and capabilities.md into doc/poc/
- Document verified Dev Mode SSH + scp screenshot findings in doc/poc/capabilities.md
- Update README.md and flake.nix description for lg-smtv-mcp scope
- Ignore *.jpg captures in .gitignore (alongside .env and .direnv)
2026-11-15 00:42:31 -05:00
kiskaadee e06a706f0e docs: document verified LG webOS SSAP/DIAL capabilities and boundaries
- Add docs/capabilities.md recording tested endpoints, deep-link formats, and 401/capture boundaries on 65UR8750PSA
- Update README.md with setup, script overview, and link to capabilities doc
2026-11-14 23:48:25 -05:00
kiskaadee e8244dc084 feat(tv_test): expand SSAP permissions, add --re-pair, foreground, inputs, audio, and launch commands
- Expand PERMISSIONS to include READ_RUNNING_APPS, READ_INPUT_DEVICE_LIST, CONTROL_INPUT_TV, READ_POWER_STATE, and input/media scopes
- Add --re-pair flag to force a fresh TV pairing prompt after permission changes
- Add foreground, inputs, audio, and launch subcommands to tv_test.py
2026-11-14 22:05:37 -05:00
kiskaadee 9cd722ed49 feat: add Nix devShell and LG webOS discovery/control PoC scripts
- Add flake.nix, flake.lock, and pyproject.toml provisioning Python 3.14, websockets, pyright, and ruff
- Add .gitignore to exclude Python caches and local TV pairing keys
- Add discover.py for SSDP multicast discovery of LG webOS TVs
- Add tv_test.py for SSAP wss:// pairing, client-key persistence, and basic remote commands
2026-11-14 21:30:11 -05:00
9 changed files with 383 additions and 2 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
use flake
+8
View File
@@ -0,0 +1,8 @@
.env
.direnv
__pycache__/
*.pyc
.ruff_cache/
.client_key.json
.tv_state.json
*.jpg
+18 -2
View File
@@ -1,3 +1,19 @@
# webos-testing
# lg-smtv-mcp
testing webOS integration
Model Context Protocol (MCP) server for local network control of LG Smart TVs (webOS) over SSAP WebSockets, Wake-on-LAN, and optional Developer Mode SSH screenshot capture.
## Setup
```bash
nix develop
```
Provisions Python 3.14, `websockets`, `ruff`, and `pyright` via [flake.nix](flake.nix).
## Historical PoC & Empirical Notes
Initial feasibility probes and verified device findings (`65UR8750PSA` / `WebOS/4.1.0`) are archived in [`doc/poc/`](doc/poc/):
- [doc/poc/capabilities.md](doc/poc/capabilities.md) — Verified SSAP/DIAL endpoints, deep-link formats, `401` boundaries, and Developer Mode SSH screenshot pipeline.
- [doc/poc/discover.py](doc/poc/discover.py) — SSDP multicast probe (`--all` to list DIAL/DLNA/SSAP services and MAC address).
- [doc/poc/tv_test.py](doc/poc/tv_test.py) — One-shot SSAP pairing + command runner.
+46
View File
@@ -0,0 +1,46 @@
# LG webOS Control Frontier (`65UR8750PSA` / `WebOS/4.1.0`)
Empirical notes from probing `192.168.1.11` (`Ethernet`, MAC `7c:64:6c:94:d1:24`) over the local network.
## Transport & Discovery
| Protocol | Endpoint | Purpose | Notes |
| :--- | :--- | :--- | :--- |
| **SSDP** | `239.255.255.250:1900` (UDP) | Discover TV on LAN | `urn:lge-com:service:webos-second-screen:1` returns `Location: http://192.168.1.11:1783/`; `ssdp:all` also reveals DIAL (`:1978`) and Ethernet MAC (`WAKEUP: MAC=...`). |
| **SSAP** | `wss://192.168.1.11:3001` | Primary JSON RPC control bus | Self-signed TLS cert (`CN=LGE TV SSG`); requires `register` handshake and `client-key` saved after on-screen `PROMPT`. |
| **DIAL** | `http://192.168.1.11:36866/apps` | App casting / `<screenId>` lookup | Requires `Origin: https://www.youtube.com` for YouTube (`403` without it). |
---
## Verified SSAP Endpoints
### Working (Tested on `65UR8750PSA`)
- **System info**: `ssap://system/getSystemInfo` → returns `modelName`, `serialNumber`, `receiverType`, `features`.
- **Installed apps**: `ssap://com.webos.applicationManager/listLaunchPoints` → returned 28 apps (`netflix`, `youtube.leanback.v4`, `amazon`, `com.disney.disneyplus-prod`, `com.apple.appletv`, `tv.twitch.tv.starshot.lg`, etc.).
- **Foreground app**: `ssap://com.webos.applicationManager/getForegroundAppInfo` → requires `READ_RUNNING_APPS` permission.
- **Audio status**: `ssap://audio/getStatus` → returns `volume`, `maxVolume`, `mute`, `soundOutput`.
- **Notifications**: `ssap://system.notifications/createToast` with `{"message": "..."}` → displays toast on screen.
- **External inputs**: `ssap://tv/getExternalInputList` → requires `READ_INPUT_DEVICE_LIST` / `CONTROL_INPUT_TV`; returned `HDMI_1`, `HDMI_2`, `HDMI_3`.
- **Launch & close apps**:
- `ssap://system.launcher/launch` with `{"id": "<app_id>", "params": {...}}`
- `ssap://system.launcher/close` with `{"id": "<app_id>"}`
- **Deep-linking quirks observed**:
- **YouTube (`youtube.leanback.v4`)**: Expects `{"contentTarget": "v=<id>&t=<seconds>s"}` (full `https://...` URLs were ignored). If cold-started onto the profile picker, a second launch switches to the video.
- **Netflix (`netflix`)**: Expects `{"contentTarget": "m=https://www.netflix.com/title/<id>"}` (or `/watch/<episode_id>`). Without `m=`, Netflix hung on loading. Audio/subtitle track selection is not exposed via `params`.
- **Screen capture (via SSAP + Dev Mode SSH)**: `ssap://com.webos.service.capture/executeOneShot` with `{"path": "/tmp/test.jpg", "method": "DISPLAY", "format": "JPG"}` succeeded (`960x540`, `10410`–`12754` bytes):
- Calling without `"path"` fails with `5 ERROR_NOT_ENOUGH_MEMORY`.
- `/tmp/test.jpg` is not served over `https://192.168.1.11:3001/tmp/...` (timed out).
- **Verified workaround**: With **LG Developer Mode** + **Key Server** enabled (SSH on port `9922`, `ssh-rsa` host/pubkey algorithms enabled for the TV host), `scp webos-tv:/tmp/test.jpg .` transfers the `~10 KB` screenshot in `< 1s` (`1.1 MB/s`).
- Dev Mode shell environment observed: `uid=6739(prisoner) gid=5000(jailer)`, home `/media/developer`, `Linux LGwebOSTV 5.4.268-294.24.papikonda.2 #1 SMP PREEMPT ... aarch64 GNU/Linux` (`1222 MB` RAM).
### Blocked on Retail Firmware
- **`ssap://settings/getSystemSettings`**: Returned `401 insufficient permissions` (low-level picture/network/system settings are restricted to signed LG system apps).
### Not Yet Tested on This Device
- **Pointer / D-pad input socket**: `ssap://com.webos.service.networkinput/getPointerInputSocket` (second WebSocket using plain-text `type:button` / `type:move` / `type:click` frames).
- **Text input**: `ssap://com.webos.service.ime/insertText` & `sendEnterKey` (works in native webOS inputs; some third-party apps use custom keyboards).
- **Subscriptions**: `"type": "subscribe"` on `audio/getStatus` and `getForegroundAppInfo` for a persistent client.
- **Wake-on-LAN**: Magic UDP packet to MAC `7c:64:6c:94:d1:24` to power on from standby.
+65
View File
@@ -0,0 +1,65 @@
"""SSDP multicast discovery probe for LG webOS TVs on the local network."""
from __future__ import annotations
import argparse
import socket
LG_WEBOS_ST = "urn:lge-com:service:webos-second-screen:1"
SSDP_ADDR = ("239.255.255.250", 1900)
def discover(search_target: str, timeout: float = 3.0) -> list[tuple[str, str]]:
"""Send an SSDP M-SEARCH multicast packet and collect responses."""
payload = (
"M-SEARCH * HTTP/1.1\r\n"
f"HOST: {SSDP_ADDR[0]}:{SSDP_ADDR[1]}\r\n"
'MAN: "ssdp:discover"\r\n'
"MX: 2\r\n"
f"ST: {search_target}\r\n"
"\r\n"
).encode()
results: list[tuple[str, str]] = []
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
sock.settimeout(timeout)
sock.sendto(payload, SSDP_ADDR)
while True:
try:
data, addr = sock.recvfrom(4096)
except TimeoutError:
break
results.append((addr[0], data.decode(errors="replace")))
return results
def main() -> None:
"""CLI entry point for SSDP discovery."""
parser = argparse.ArgumentParser(description="Discover LG webOS TVs via SSDP.")
parser.add_argument(
"--all",
action="store_true",
help="Search for ssdp:all instead of only LG webOS devices.",
)
parser.add_argument(
"--timeout",
type=float,
default=3.0,
help="Seconds to wait for responses (default: 3.0).",
)
args = parser.parse_args()
target = "ssdp:all" if args.all else LG_WEBOS_ST
print(f"Sending SSDP M-SEARCH for {target} (timeout={args.timeout}s)...")
responses = discover(target, timeout=args.timeout)
if not responses:
print("No SSDP responses received.")
return
for ip, raw in responses:
print(f"\n=== {ip} ===")
print(raw.strip())
if __name__ == "__main__":
main()
+183
View File
@@ -0,0 +1,183 @@
"""Minimal LG webOS SSAP pairing and command test script."""
from __future__ import annotations
import argparse
import asyncio
import json
import ssl
from pathlib import Path
from typing import Any
import websockets
DEFAULT_KEY_FILE = Path(".client_key.json")
PERMISSIONS = [
"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",
]
COMMANDS: dict[str, tuple[str, dict[str, Any]]] = {
"info": ("ssap://system/getSystemInfo", {}),
"apps": ("ssap://com.webos.applicationManager/listLaunchPoints", {}),
"foreground": ("ssap://com.webos.applicationManager/getForegroundAppInfo", {}),
"inputs": ("ssap://tv/getExternalInputList", {}),
"audio": ("ssap://audio/getStatus", {}),
"vol-up": ("ssap://audio/volumeUp", {}),
"vol-down": ("ssap://audio/volumeDown", {}),
"mute": ("ssap://audio/setMute", {"mute": True}),
"unmute": ("ssap://audio/setMute", {"mute": False}),
}
def build_ssl_context() -> ssl.SSLContext:
"""Create an SSL context that accepts the TV's self-signed certificate."""
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
return ctx
def load_client_keys(key_file: Path) -> dict[str, str]:
"""Load saved IP -> client-key mappings from disk."""
if not key_file.exists():
return {}
data = json.loads(key_file.read_text(encoding="utf-8"))
return {str(k): str(v) for k, v in data.items()}
def save_client_key(key_file: Path, ip: str, client_key: str) -> None:
"""Persist a paired TV's client-key to disk."""
keys = load_client_keys(key_file)
keys[ip] = client_key
key_file.write_text(json.dumps(keys, indent=2) + "\n", encoding="utf-8")
def build_register_payload(client_key: str | None, force_pairing: bool = False) -> dict[str, Any]:
"""Build the SSAP register handshake payload."""
payload: dict[str, Any] = {
"forcePairing": force_pairing,
"pairingType": "PROMPT",
"manifest": {
"manifestVersion": 1,
"appVersion": "0.1.0",
"permissions": PERMISSIONS,
"localizedAppNames": {"": "webOS Linux Test"},
},
}
if client_key and not force_pairing:
payload["client-key"] = client_key
return {"type": "register", "id": "register_0", "payload": payload}
async def pair_and_send(
ip: str,
port: int,
uri: str,
payload: dict[str, Any],
key_file: Path,
re_pair: bool = False,
) -> dict[str, Any]:
"""Connect to the TV, complete registration/pairing, and send one SSAP request."""
keys = load_client_keys(key_file)
saved_key = None if re_pair else keys.get(ip)
scheme = "wss" if port == 3001 else "ws"
ssl_ctx = build_ssl_context() if scheme == "wss" else None
async with websockets.connect(f"{scheme}://{ip}:{port}", ssl=ssl_ctx) as ws:
await ws.send(json.dumps(build_register_payload(saved_key, force_pairing=re_pair)))
while True:
msg = json.loads(await ws.recv())
msg_type = msg.get("type")
if msg_type == "response" and msg.get("payload", {}).get("pairingType") == "PROMPT":
print("Pairing prompt sent — accept it on the TV screen...")
continue
if msg_type == "registered":
new_key = msg["payload"]["client-key"]
if new_key != saved_key:
save_client_key(key_file, ip, new_key)
print(f"Paired! Saved client-key to {key_file}")
break
if msg_type == "error":
raise RuntimeError(f"Registration failed: {msg}")
req = {"id": "cmd_1", "type": "request", "uri": uri, "payload": payload}
await ws.send(json.dumps(req))
return json.loads(await ws.recv())
def parse_args() -> argparse.Namespace:
"""Parse CLI arguments."""
parser = argparse.ArgumentParser(
description="Pair with an LG webOS TV and send a test command."
)
parser.add_argument("--ip", required=True, help="TV IP address (e.g. 192.168.1.11)")
parser.add_argument("--port", type=int, default=3001, help="WebSocket port (default: 3001)")
parser.add_argument(
"--key-file",
type=Path,
default=DEFAULT_KEY_FILE,
help="Path to store client-key (default: .client_key.json)",
)
parser.add_argument(
"--re-pair",
action="store_true",
help="Force a new pairing prompt on the TV (e.g. after expanding permissions).",
)
sub = parser.add_subparsers(dest="command", required=True)
toast_p = sub.add_parser("toast", help="Show a toast notification on the TV.")
toast_p.add_argument("message", nargs="?", default="Hello from Linux!")
launch_p = sub.add_parser("launch", help="Launch an app by ID (e.g. youtube.leanback.v4).")
launch_p.add_argument("app_id", help="App ID from `apps` output.")
launch_p.add_argument("--params", default="{}", help="Optional JSON params for the app.")
for name in COMMANDS:
sub.add_parser(name, help=f"Send {COMMANDS[name][0]}")
raw_p = sub.add_parser("raw", help="Send an arbitrary SSAP URI + JSON payload.")
raw_p.add_argument("uri", help="SSAP URI (e.g. ssap://system/getSystemInfo)")
raw_p.add_argument("--payload", default="{}", help="JSON payload string")
return parser.parse_args()
def main() -> None:
"""CLI entry point."""
args = parse_args()
if args.command == "toast":
uri = "ssap://system.notifications/createToast"
payload: dict[str, Any] = {"message": args.message}
elif args.command == "launch":
uri = "ssap://system.launcher/launch"
payload = {"id": args.app_id, "params": json.loads(args.params)}
elif args.command == "raw":
uri = args.uri
payload = json.loads(args.payload)
else:
uri, payload = COMMANDS[args.command]
response = asyncio.run(
pair_and_send(args.ip, args.port, uri, payload, args.key_file, re_pair=args.re_pair)
)
print(json.dumps(response, indent=2))
if __name__ == "__main__":
main()
Generated
+27
View File
@@ -0,0 +1,27 @@
{
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1794386569,
"narHash": "sha256-x9sADJvoVG0L6RejZB+/BB4YiGZFBZrfTlhF4uBq1tQ=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "d4f25a3e562008648d45bcf2d70bcc7422cad84e",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"nixpkgs": "nixpkgs"
}
}
},
"root": "root",
"version": 7
}
+25
View File
@@ -0,0 +1,25 @@
{
description = "LG Smart TV (webOS) MCP server and testing environment";
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
};
outputs = { self, nixpkgs }:
let
system = "x86_64-linux";
pkgs = import nixpkgs { inherit system; };
pythonEnv = pkgs.python3.withPackages (ps: [
ps.websockets
]);
in
{
devShells.${system}.default = pkgs.mkShell {
packages = [
pythonEnv
pkgs.pyright
pkgs.ruff
];
};
};
}
+10
View File
@@ -0,0 +1,10 @@
[tool.ruff]
line-length = 100
target-version = "py314"
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B"]
[tool.pyright]
typeCheckingMode = "standard"
pythonVersion = "3.14"