Author SHA1 Message Date
kiskaadee 84ae8b283d docs(experiments): record standardized E2E baseline on main (0d67615)
Core Architecture & Invariant CI / validate (push) Successful in 16s
- docs/experiments/crunchyroll-e2e-baseline-0d67615.md: capture 13-step / 148.40s pre-#20 baseline using e2e-benchmark-template.md, pinning the <=9,652 B inline vs >=15,744 B disk-offload threshold
2026-11-19 10:22:36 -05:00
kiskaadee 0d67615817 docs(experiments): add Crunchyroll E2E comparison report and benchmark template
Core Architecture & Invariant CI / validate (push) Successful in 17s
- docs/experiments/crunchyroll-e2e-comparison.md: compare PoC baseline against lg-smtv-mcp (aac0035) across transport, host/LLM offload, and TV settling buckets with full step telemetry

- docs/experiments/e2e-benchmark-template.md: define pinned preconditions, standardized subagent prompt, normalized scorecard, and step telemetry table for #20/#23 before-after runs
2026-11-19 10:02:26 -05:00
kiskaadee aac00356a1 fix(capture): map asyncssh.KeyImportError to SCREENSHOT_UNAVAILABLE
Core Architecture & Invariant CI / validate (push) Successful in 16s
- src/lg_smtv_mcp/tv_core/capture.py: catch asyncssh.KeyImportError (which subclasses ValueError rather than asyncssh.Error) in AsyncSshCaptureTransport.read_and_remove() and CaptureClient.capture_frame() so encrypted/invalid SSH key errors surface as TvError(SCREENSHOT_UNAVAILABLE) and degrade gracefully on composite capture calls

- tests/test_capture.py: add test_capture_client_maps_key_import_error_to_screenshot_unavailable
2026-11-19 01:59:34 -05:00
kiskaadee 85a5acad35 fix(cli): use wss://:3001 for TV pairing and catch WebSocketException
- src/lg_smtv_mcp/cli.py: update _pair_tv() to connect via wss://<ip>:3001 matching TvManager and WebOS/4.1.0 TLS SSAP endpoint; catch WebSocketException in main() so handshake errors exit cleanly with code 1

- tests/test_cli.py: update pairing URL assertion to wss://192.0.2.20:3001 and add test_cli_pair_returns_nonzero_on_websocket_handshake_error
2026-11-19 00:41:47 -05:00
kiskaadee 2af3c99e4c docs(reconcile): record #17 systemd hardening delivery (#19)
Core Architecture & Invariant CI / validate (push) Successful in 18s
- ROADMAP.md: move #17 (PR #18) from active Backlog/Near Term to Completed (Post-M2 Hardening) and align current direction with merged main
- docs/designs/lg-smtv-mcp.md: update implementation status and M2 delivery notes to record #17 (PR #18) as delivered rather than tracked separately
2026-11-18 23:41:56 -05:00
kiskaadee 42bd4edf09 Merge pull request 'chore(deploy): harden systemd unit sandboxing and add automated verify test (#17)' (#18) from chore/issue-17-systemd-hardening into main
Core Architecture & Invariant CI / validate (push) Successful in 24s
2026-11-18 23:40:33 -05:00
kiskaadee 5a8ebffad2 fix(capture): read Dev Mode screenshots via asyncssh SFTP open()
Core Architecture & Invariant CI / validate (pull_request) Successful in 16s
- src/lg_smtv_mcp/tv_core/capture.py: replace the nonexistent sftp.read() with sftp.open(path, 'rb') and an async context manager; the live AC#2 smoke against asyncssh 2.24.0 raised AttributeError because SFTPClient exposes open(), not read()
- tests/test_capture.py: reshape the SFTP fake to the real asyncssh contract (regular open(), async file read(), async context manager) and add a regression test asserting the real class API, closing the mock gap that let offline tests pass while the live screenshot tool failed
- tests/test_server.py: align the capture-wiring SFTP fake with the same open()/async-file contract so the default transport test exercises the real call shape
2026-11-17 16:15:56 -05:00
kiskaadee 9195d91d7d docs(deploy): correct ProtectSystem=strict rejection rationale
Core Architecture & Invariant CI / validate (pull_request) Successful in 16s
- README.md: replace the incorrect claim that ProtectSystem=strict was rejected because nix develop needs writable /tmp; systemd.exec(5) keeps /tmp and /var/tmp writable under strict when PrivateTmp=yes is set, which this unit already adopts
- README.md: state the real compatibility constraint instead — strict mounts the whole filesystem read-only including ~/.cache/nix/fetcher-locks and the checkout, matching the documented ProtectHome constraint — so issue #17 AC#4 records an accurate reason
2026-11-17 10:01:38 -05:00
kiskaadee 52ec28f278 test(deploy): harden test seams with section-aware parsing and fault-safe fixtures
Core Architecture & Invariant CI / validate (pull_request) Successful in 16s
Addresses CR-01 to CR-05 from review 10 on PR #18.

- tests/test_deploy.py: resolve CR-01 — replace substring assertions with
  configparser section-aware exact key/value checks; CapabilityBoundingSet=
  now asserts empty string ''; commented-out directives are correctly
  rejected since configparser strips comment lines; assert 'Unknown key'/
  'Unknown lvalue' absent in systemd-analyze verify stderr so wrong-section
  misplacements are caught even at exit 0

- tests/test_deploy.py: resolve CR-02 — replace hardcoded personal
  identifiers ('kiskaadee', '/home/kiskaadee/...') with neutral 'testuser'
  and pytest tmp_path-derived paths in all substitution fixtures

- tests/test_deploy.py: resolve CR-03 — split the monolithic
  test_service_template_contains_placeholders_and_hardening_directives into
  three single-behavior tests: test_service_template_exists,
  test_service_template_declares_deployment_placeholders, and
  test_service_template_bounds_restart_limit_in_unit_section

- tests/test_deploy.py: resolve CR-04 — add timeout=30.0 to all
  subprocess.run calls to prevent silent CI hangs

- tests/test_deploy.py: resolve CR-05 — regex-parse numeric exposure score
  from systemd-analyze security output and assert score <= 5.0 in lieu of
  checking 'OK' label substring; test renamed to
  test_systemd_analyze_security_reports_ok_exposure_bracket

- tests/test_deploy.py: resolve CR-08 — extract shared systemd_analyze_bin
  and substituted_service_file pytest fixtures, eliminating duplicated
  shutil.which calls and substitution setup across subprocess tests

Fault injection confirmed red before green for all sensitive seams:
  Fault A: StartLimitIntervalSec/Burst in [Service] → section-mismatch fail
  Fault B: CapabilityBoundingSet=CAP_NET_RAW → non-empty string fail
  Fault C: # NoNewPrivileges=yes (commented) → None != 'yes' fail
  Fault D: sandboxing block removed → 9.0 UNSAFE score, regex no-match fail

Verification: 144 passed, ruff/pyright/pytest all green
2026-11-17 09:53:30 -05:00
kiskaadee 0bf2923edb chore(deploy): harden systemd unit sandboxing and add automated verify test
Core Architecture & Invariant CI / validate (pull_request) Successful in 16s
- flake.nix: add pkgs.systemd to testTools (nativeCheckInputs and devShell
  packages) so systemd-analyze is hermetically available in both local dev
  and isolated Nix sandbox CI (Defect 1 / CR-03)
- deploy/lg-smtv-mcp.service: add StartLimitIntervalSec=60s and StartLimitBurst=5
  in [Unit] to prevent unbounded restart loops (CR-02); add safe sandboxing
  baseline in [Service] (NoNewPrivileges, PrivateTmp, UMask=0077, ProtectSystem=full,
  kernel/bus isolation directives, CapabilityBoundingSet=) dropping offline exposure
  score from 9.0 UNSAFE to 4.9 OK (CR-02, Issue #17)
- tests/test_deploy.py: add unit tests verifying template placeholders, directive
  presence, systemd-analyze verify exit code, and security exposure score reduction
  under 5.0 (CR-03)
- README.md: document adopted hardening baseline, score reduction (9.0 -> 4.9),
  and technical compatibility constraints that ruled out ProtectHome, ProtectSystem=strict,
  and PrivateNetwork (AC1, AC4)
2026-11-17 03:07:49 -05:00
kiskaadee b2738c0d48 docs(reconcile): fix CLI invocation syntax and reconcile #13 in design doc
Core Architecture & Invariant CI / validate (push) Successful in 15s
- README.md: update remaining CLI invocations (lines 146, 148, 158, 161,
  208) to use 'python -m lg_smtv_mcp' instead of 'lg-smtv-mcp' — the
  console script is not installed in PATH by nix develop devShell; add
  explanatory note in pair & serve section clarifying devShell execution
  mechanics (CR-08)
- docs/designs/lg-smtv-mcp.md: update section 268 to state that all M2
  slices (#11, #12, #13) are completed and merged on main; move slice
  #13 from active plan to completed baseline item 5 and reference follow-up
  sandboxing hardening in issue #17
2026-11-17 02:29:16 -05:00
kiskaadee ea0c1d9774 docs(reconcile): close M2 — align ROADMAP and design doc with merged #13 / PR #16
Core Architecture & Invariant CI / validate (push) Successful in 15s
- ROADMAP.md: mark M2 fully completed (2026-11-17); add #13 delivery
  bullet; retitle Near Term section and move #17 sandboxing to Backlog
  entry with actionable scope description
- docs/designs/lg-smtv-mcp.md: update Last reconciled header to reflect
  M2 closure and PR #16 merge
2026-11-17 01:57:53 -05:00
kiskaadee 4af32b993d Merge pull request 'chore(deploy): add systemd service and M2 deployment docs (#13)' (#16) from feat/issue-13-systemd-deployment into main
Core Architecture & Invariant CI / validate (push) Successful in 15s
2026-11-17 01:56:13 -05:00
14 changed files with 483 additions and 55 deletions

No files matched your search

+28 -7
View File
@@ -7,7 +7,7 @@ A Python Model Context Protocol (MCP) server for persistent, local-network contr
The server is deliberately **LLM-free**: it exposes bounded, deterministic operations so external AI agents (such as Antigravity, Claude, or a vision-guided decision loop) can reason over UI state and control the television without embedding model APIs into the daemon. The server is deliberately **LLM-free**: it exposes bounded, deterministic operations so external AI agents (such as Antigravity, Claude, or a vision-guided decision loop) can reason over UI state and control the television without embedding model APIs into the daemon.
> **Status: M2 delivered — capture, E2E hardening, and `systemd` deployment.** > **Status: M2 delivered — capture, E2E hardening, and `systemd` deployment.**
> Configuration validation, error taxonomy, [`tv_core`](src/lg_smtv_mcp/tv_core/) (SSAP multiplexer, `PointerClient`, `TvManager`), FastMCP server & Bearer auth ([`server.py`](src/lg_smtv_mcp/server.py), [`auth.py`](src/lg_smtv_mcp/auth.py)), `pair` / `serve` CLI ([`cli.py`](src/lg_smtv_mcp/cli.py)), full-stack offline E2E verification ([`test_e2e_mvp.py`](tests/test_e2e_mvp.py)), and Developer Mode SFTP screenshot capture ([`capture.py`](src/lg_smtv_mcp/tv_core/capture.py)) are implemented and tested. Milestone M2 is delivered; `systemd` unit sandboxing hardening is tracked separately in [#17](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/issues/17). > Configuration validation, error taxonomy, [`tv_core`](src/lg_smtv_mcp/tv_core/) (SSAP multiplexer, `PointerClient`, `TvManager`), FastMCP server & Bearer auth ([`server.py`](src/lg_smtv_mcp/server.py), [`auth.py`](src/lg_smtv_mcp/auth.py)), `pair` / `serve` CLI ([`cli.py`](src/lg_smtv_mcp/cli.py)), full-stack offline E2E verification ([`test_e2e_mvp.py`](tests/test_e2e_mvp.py)), and Developer Mode SFTP screenshot capture ([`capture.py`](src/lg_smtv_mcp/tv_core/capture.py)) are implemented and tested. Milestone M2 is delivered; `systemd` unit sandboxing hardening is implemented in [#17](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/issues/17).
--- ---
@@ -140,12 +140,14 @@ MAX_VOLUME=40
## Running the MVP Server (`pair` & `serve`) ## Running the MVP Server (`pair` & `serve`)
> **Note:** Inside `nix develop`, run commands using `python -m lg_smtv_mcp <subcommand>` (or `nix run . -- <subcommand>`), as the devShell provisions the Python environment directly rather than installing package console scripts to `PATH`.
1. **Pair with the TV (one-time per TV):** Ensure the TV is powered on with *LG Connect Apps* enabled, then run: 1. **Pair with the TV (one-time per TV):** Ensure the TV is powered on with *LG Connect Apps* enabled, then run:
```bash ```bash
lg-smtv-mcp pair python -m lg_smtv_mcp pair
# Optional: override IP or also fetch Developer Mode SSH key # Optional: override IP or also fetch Developer Mode SSH key
lg-smtv-mcp pair --ip <TV_IP> python -m lg_smtv_mcp pair --ip <TV_IP>
``` ```
Accept the pairing prompt on the TV screen. The client key is saved atomically with `0600` permissions to `CLIENT_KEY_PATH` (default `.client_key.json`). Accept the pairing prompt on the TV screen. The client key is saved atomically with `0600` permissions to `CLIENT_KEY_PATH` (default `.client_key.json`).
@@ -155,10 +157,10 @@ MAX_VOLUME=40
```bash ```bash
# Default: persistent Streamable HTTP daemon at http://<HOST>:<PORT>/mcp # Default: persistent Streamable HTTP daemon at http://<HOST>:<PORT>/mcp
# Requires Authorization: Bearer <MCP_BEARER_TOKEN> # Requires Authorization: Bearer <MCP_BEARER_TOKEN>
lg-smtv-mcp serve python -m lg_smtv_mcp serve
# Local testing over stdio (no HTTP Bearer token required) # Local testing over stdio (no HTTP Bearer token required)
lg-smtv-mcp serve --transport stdio python -m lg_smtv_mcp serve --transport stdio
``` ```
If you re-pair while `serve` is running, send `SIGHUP` to reload `.client_key.json` without restarting the daemon. If you re-pair while `serve` is running, send `SIGHUP` to reload `.client_key.json` without restarting the daemon.
@@ -189,6 +191,25 @@ The repository includes a unit template at [`deploy/lg-smtv-mcp.service`](deploy
The HTTP server binds to `127.0.0.1` by default and requires `MCP_BEARER_TOKEN`. Use a trusted reverse proxy or VPN if clients need remote access. When exposing the server remotely, set **both** `HOST=0.0.0.0` (or the LAN bind address) **and** `ALLOWED_HOSTS=<proxy-or-vpn-hostname>` in `.env`; the DNS-rebinding check in `auth.py` rejects any request whose `Host` header is not in the allowlist. The HTTP server binds to `127.0.0.1` by default and requires `MCP_BEARER_TOKEN`. Use a trusted reverse proxy or VPN if clients need remote access. When exposing the server remotely, set **both** `HOST=0.0.0.0` (or the LAN bind address) **and** `ALLOWED_HOSTS=<proxy-or-vpn-hostname>` in `.env`; the DNS-rebinding check in `auth.py` rejects any request whose `Host` header is not in the allowlist.
### Sandboxing & Security Profile
The unit template includes a tested systemd sandboxing baseline (Issue [#17](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/issues/17)), reducing the `systemd-analyze --offline=yes security` exposure score from **9.0 UNSAFE** to **4.9 OK**:
- **Adopted Directives:**
- `StartLimitIntervalSec=60s` / `StartLimitBurst=5`: Bounded restart budget prevents runaway restart loops on persistent environment errors (e.g. missing `.env`).
- `NoNewPrivileges=yes`: Prevents process escalation or setuid execution.
- `PrivateTmp=yes`: Restricts `/tmp` visibility to an isolated per-service namespace.
- `UMask=0077`: Ensures files created by the service are private to the service user.
- `ProtectSystem=full`: Mounts `/usr`, `/boot`, and `/etc` read-only.
- `ProtectControlGroups=yes`, `ProtectKernelModules=yes`, `ProtectKernelTunables=yes`, `ProtectKernelLogs=yes`, `ProtectClock=yes`, `ProtectHostname=yes`: Prevents tampering with kernel and OS interfaces.
- `RestrictRealtime=yes`, `RestrictSUIDSGID=yes`, `LockPersonality=yes`: Restricts privilege escalation vectors.
- `CapabilityBoundingSet=`: Drops all Linux kernel capabilities.
- **Rejected Directives (Compatibility Constraints):**
- `ProtectHome=yes` / `ProtectHome=read-only`: Ruled out because `nix develop` requires read-write access to `~/.cache/nix/fetcher-locks` for flake evaluation, and the repository checkout resides under the operator's user directory.
- `ProtectSystem=strict`: Ruled out because it mounts the entire filesystem read-only, including the operator's home directory and the repository checkout; `nix develop` needs write access to `~/.cache/nix/fetcher-locks` for flake evaluation (the same constraint that rules out `ProtectHome`). Writable `/tmp` is not the blocker: with `PrivateTmp=yes`, systemd keeps `/tmp` and `/var/tmp` writable even under `strict`.
- `PrivateNetwork=yes`: Ruled out because the MCP daemon must communicate over the local network to the TV via SSAP (`wss://:3001`), Developer Mode SSH/SFTP (`:9922`), and Wake-on-LAN UDP broadcasts.
### Developer Mode SSH Capture Setup ### Developer Mode SSH Capture Setup
Enable Developer Mode and the TV's Key Server in the Developer Mode app. Run pairing from the configured checkout as the same service user so the client key and SSH key are saved where the service can read them: Enable Developer Mode and the TV's Key Server in the Developer Mode app. Run pairing from the configured checkout as the same service user so the client key and SSH key are saved where the service can read them:
@@ -203,9 +224,9 @@ On a trusted home LAN, SSH host-key checking is disabled by default because the
## Operator Live-TV E2E Smoke Test Checklist ## Operator Live-TV E2E Smoke Test Checklist
Automated tests run strictly offline. After deploying or updating on a host on the same LAN as the TV, run this manual smoke checklist from an MCP client connected to `lg-smtv-mcp serve`: Automated tests run strictly offline. After deploying or updating on a host on the same LAN as the TV, run this manual smoke checklist from an MCP client connected to `python -m lg_smtv_mcp serve`:
- [ ] **`pair`**: Run `lg-smtv-mcp pair`, accept the on-screen TV prompt, and confirm `CLIENT_KEY_PATH` (`.client_key.json`) exists with `0600` permissions and an entry for `<TV_IP>`. - [ ] **`pair`**: Run `python -m lg_smtv_mcp pair`, accept the on-screen TV prompt, and confirm `CLIENT_KEY_PATH` (`.client_key.json`) exists with `0600` permissions and an entry for `<TV_IP>`.
- [ ] **`tv_wake`**: With the TV in standby, verify a mutating tool (`launch`) fails fast with `TV_OFFLINE_STANDBY` (no implicit WoL), then call `tv_wake` and confirm the TV powers on and returns `status: "connected"`. - [ ] **`tv_wake`**: With the TV in standby, verify a mutating tool (`launch`) fails fast with `TV_OFFLINE_STANDBY` (no implicit WoL), then call `tv_wake` and confirm the TV powers on and returns `status: "connected"`.
- [ ] **`get_state`**: Call `get_state` and confirm `connected: true`, `stale: false`, and live `volume`, `muted`, `sound_output`, and `foreground_app` values. - [ ] **`get_state`**: Call `get_state` and confirm `connected: true`, `stale: false`, and live `volume`, `muted`, `sound_output`, and `foreground_app` values.
- [ ] **`launch`**: Call `launch` (e.g., `app_id="youtube.leanback.v4"` with an optional `content_target`) and confirm the app opens on screen. - [ ] **`launch`**: Call `launch` (e.g., `app_id="youtube.leanback.v4"` with an optional `content_target`) and confirm the app opens on screen.
+7 -8
View File
@@ -2,22 +2,21 @@
## Current Direction ## Current Direction
`lg-smtv-mcp` has completed its M1 MVP control plane (persistent SSAP, pointer input, WoL recovery, FastMCP tools, Bearer auth, `pair`/`serve` CLI, and full-stack offline E2E verification) and the M2 capture and E2E-hardening slices. Remaining M2 work is deployment packaging and its `systemd` hardening follow-up. `lg-smtv-mcp` has completed Milestone M2 (capture, E2E hardening, and systemd deployment packaging) and the post-M2 `systemd` unit sandboxing hardening follow-up ([#17](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/issues/17), PR [#18](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/18)). Active work is live-TV operator smoke verification (and downstream Canopy deployment).
## Near Term (Milestone M2) ## Near Term
- **Systemd Unit & Deployment Docs ([#13](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/issues/13)):** Add `deploy/lg-smtv-mcp.service` template and document systemd + Developer Mode SSH setup in `README.md`.
- **Systemd Unit Sandboxing Hardening ([#17](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/issues/17)):** Follow-up to `#13`, tightening the unit's sandboxing directives once the baseline deployment template lands.
## Medium Term
- **Live-TV Operator Smoke Verification:** Execute the manual LAN smoke checklist in [`README.md`](README.md#operator-live-tv-e2e-smoke-test-checklist) and Developer Mode capture verification against the target `WebOS/4.1.0` TV. - **Live-TV Operator Smoke Verification:** Execute the manual LAN smoke checklist in [`README.md`](README.md#operator-live-tv-e2e-smoke-test-checklist) and Developer Mode capture verification against the target `WebOS/4.1.0` TV.
## Completed ## Completed
### M2: Capture & E2E Hardening (partial, 2026-11-16) ### Post-M2 Hardening (Completed 2026-11-18)
- **#17 (PR [#18](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/18)):** Hardened [`deploy/lg-smtv-mcp.service`](deploy/lg-smtv-mcp.service) with bounded restart throttling (`StartLimitIntervalSec=60s`, `StartLimitBurst=5`) and a 14-directive sandboxing baseline (`9.0 UNSAFE` → `4.9 OK`), added automated `systemd-analyze` tests in [`tests/test_deploy.py`](tests/test_deploy.py), documented adopted/rejected directives in [`README.md`](README.md#sandboxing--security-profile), and fixed `asyncssh` SFTP capture reads (`sftp.open()`) in [`src/lg_smtv_mcp/tv_core/capture.py`](src/lg_smtv_mcp/tv_core/capture.py).
### M2: Capture, E2E Hardening & Systemd Deployment (Completed 2026-11-17)
- **#11 (PR [#14](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/14)):** E2E harness hardening in [`tests/test_e2e_mvp.py`](tests/test_e2e_mvp.py) — fast-fail ASGI lifespan startup, `elapsed_ms` contract check, and post-`turn_off()` `1008` -> `get_state` stale parity. - **#11 (PR [#14](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/14)):** E2E harness hardening in [`tests/test_e2e_mvp.py`](tests/test_e2e_mvp.py) — fast-fail ASGI lifespan startup, `elapsed_ms` contract check, and post-`turn_off()` `1008` -> `get_state` stale parity.
- **#12 (PR [#15](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/15)):** `tv_core/capture.py` (`CaptureClient` + `AsyncSshCaptureTransport`), default `server.py` wiring, and offline capture contract tests; review remediation CR-01..CR-11 landed in `61d2315`. - **#12 (PR [#15](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/15)):** `tv_core/capture.py` (`CaptureClient` + `AsyncSshCaptureTransport`), default `server.py` wiring, and offline capture contract tests; review remediation CR-01..CR-11 landed in `61d2315`.
- **#13 (PR [#16](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/16)):** `deploy/lg-smtv-mcp.service` systemd template, deployment + Developer Mode SSH setup docs in `README.md`, and DNS-rebinding / PATH env guidance.
### M1: MVP Core & End-to-End Verification (Completed 2026-11-16) ### M1: MVP Core & End-to-End Verification (Completed 2026-11-16)
- **#1 (PR [#6](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/6)):** Nix flake packaging, `pyproject.toml`, Pydantic v2 `TvConfig`, and `ConfigError` / `TvError` taxonomy. - **#1 (PR [#6](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/6)):** Nix flake packaging, `pyproject.toml`, Pydantic v2 `TvConfig`, and `ConfigError` / `TvError` taxonomy.
+18
View File
@@ -2,6 +2,8 @@
Description=LG webOS Smart TV MCP server Description=LG webOS Smart TV MCP server
Wants=network-online.target Wants=network-online.target
After=network-online.target After=network-online.target
StartLimitIntervalSec=60s
StartLimitBurst=5
[Service] [Service]
Type=simple Type=simple
@@ -13,5 +15,21 @@ ExecStart=/usr/bin/env nix develop --command python -m lg_smtv_mcp serve
Restart=on-failure Restart=on-failure
RestartSec=5s RestartSec=5s
# Sandboxing baseline (Issue #17)
NoNewPrivileges=yes
PrivateTmp=yes
UMask=0077
ProtectSystem=full
ProtectControlGroups=yes
ProtectKernelModules=yes
ProtectKernelTunables=yes
ProtectKernelLogs=yes
ProtectClock=yes
ProtectHostname=yes
RestrictRealtime=yes
RestrictSUIDSGID=yes
LockPersonality=yes
CapabilityBoundingSet=
[Install] [Install]
WantedBy=multi-user.target WantedBy=multi-user.target
+10 -16
View File
@@ -3,7 +3,7 @@
* **Author:** kiskaadee * **Author:** kiskaadee
* **Status:** Approved * **Status:** Approved
* **Date:** 2026-11-15 * **Date:** 2026-11-15
* **Last reconciled:** 2026-11-16 (M2 `#12` / PR [#15](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/15) merged) * **Last reconciled:** 2026-11-17 (M2 fully delivered: `#13` / PR [#16](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/16) merged; Milestone M2 closed)
-------------------------------------------------------------------------------- --------------------------------------------------------------------------------
@@ -267,7 +267,7 @@ All tools return structured JSON payloads (plus inline MCP `ImageContent` when `
## Detailed Implementation Plan ## Detailed Implementation Plan
Milestone M1 foundations (`#1`–`#4`) and the M2 capture/E2E slices (`#11`, `#12`) are implemented, verified, and merged on `main`. The completed baselines are summarized for reference below; the active plan specifies the remaining Milestone M2 deployment slice (`#13`). Milestone M1 foundations (`#1`–`#4`), all Milestone M2 slices (`#11`, `#12`, `#13`), and the post-M2 `systemd` unit sandboxing hardening follow-up ([#17](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/issues/17), PR [#18](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/18)) are implemented, verified, and merged on `main`. The completed baselines are summarized for reference below.
### Completed Milestone M1 Baseline (`#1`–`#4`, Merged on `main`) ### Completed Milestone M1 Baseline (`#1`–`#4`, Merged on `main`)
@@ -278,7 +278,7 @@ Milestone M1 foundations (`#1`–`#4`) and the M2 capture/E2E slices (`#11`, `#1
--- ---
### Completed Milestone M2 Slices (`#11`, `#12` — Merged on `main`) ### Completed Milestone M2 Slices (`#11`, `#12`, `#13` — Merged on `main`)
Delivered by `#12` (PR [#15](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/15)) and `#11` (PR [#14](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/14)). The contracts below match `main` as merged, including the PR `#15` review remediation (CR-01..CR-11). Delivered by `#12` (PR [#15](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/15)) and `#11` (PR [#14](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/14)). The contracts below match `main` as merged, including the PR `#15` review remediation (CR-01..CR-11).
@@ -328,21 +328,15 @@ Delivered by `#12` (PR [#15](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/p
* Asserted `isinstance(wake_payload["elapsed_ms"], int) and wake_payload["elapsed_ms"] >= 0` on `tv_wake`. * Asserted `isinstance(wake_payload["elapsed_ms"], int) and wake_payload["elapsed_ms"] >= 0` on `tv_wake`.
* After `turn_off()`, simulated the TV closing the SSAP WebSocket with `1008` and re-queried `get_state` to verify `connected: false, stale: true` with cached state retained. * After `turn_off()`, simulated the TV closing the SSAP WebSocket with `1008` and re-queried `get_state` to verify `connected: false, stale: true` with cached state retained.
* **M2 Delivery Checkpoint:** `nix develop --command bash -c "ruff check . && ruff format --check . && pyright && pytest"` and `nix flake check` passed for `#11` and `#12`. #### 5. `deploy/lg-smtv-mcp.service` and `README.md` (Completed — Issue `#13`, PR [#16](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/16))
--- * **Type / Scope:** Systemd unit template and operator deployment documentation.
* **Delivered Changes:**
* Created `deploy/lg-smtv-mcp.service` template invoking `nix develop --command python -m lg_smtv_mcp serve` with `<User>`, `<WorkingDirectory>`, `EnvironmentFile`, `Restart=on-failure`, and `PATH` containing `<NixBinDir>`.
* Updated `README.md` with `systemd` setup instructions, Developer Mode pairing workflow (`python -m lg_smtv_mcp pair --fetch-ssh-key`), DNS-rebinding host configuration (`HOST` + `ALLOWED_HOSTS`), and live-TV operator smoke checklist items.
* Follow-up unit sandboxing hardening was delivered in issue [#17](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/issues/17) (PR [#18](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/18)), adding bounded restart limits, a 14-directive sandboxing baseline (`9.0 UNSAFE` → `4.9 OK`), automated `systemd-analyze` verification in `tests/test_deploy.py`, and the `asyncssh` SFTP `open()` capture fix.
### Active Milestone M2 Plan: Systemd Deployment (`#13`) * **M2 Delivery Checkpoint:** All checks (`ruff`, `pyright`, `pytest`, `nix flake check`) passed; PR #16 merged on `main`.
#### 1. `deploy/lg-smtv-mcp.service` and `README.md` (Create / Modify — Issue `#13`)
* **Type / Scope:** Systemd unit template and operator documentation.
* **Proposed Changes:**
* Create `deploy/lg-smtv-mcp.service` with `<User>`, `<WorkingDirectory>`, `EnvironmentFile`, `After=network-online.target`, `Wants=network-online.target`, and `Restart=on-failure`, invoking `nix develop --command python -m lg_smtv_mcp serve`.
* Update `README.md` with `systemd` deployment steps (including ensuring `nix` is on `systemd`'s `PATH`), Developer Mode SSH setup (`pair --fetch-ssh-key`, `:9922` session timer behavior, `SSH_KNOWN_HOSTS_PATH`), and a live-TV `screenshot` / `keys(..., capture=True)` smoke checklist item.
* A follow-up issue (`#17`) tracks tightening the unit's sandboxing directives after this baseline template lands.
* **M2 Completion Checkpoint:** `nix develop --command bash -c "ruff check . && ruff format --check . && pyright && pytest"` and `nix flake check`.
### Verification Plan ### Verification Plan
@@ -0,0 +1,42 @@
# Standardized E2E Benchmark Baseline (`main` @ `0d67615`)
Standardized pre-#20/#23 baseline executed using [`e2e-benchmark-template.md`](e2e-benchmark-template.md) by subagent `281cc834-58db-4ed5-9d9c-21b1dfd34d67` against `65UR8750PSA` (`WebOS/4.1.0`).
## Preconditions
- **Commit / Branch:** `0d67615` (`main`)
- **Server Config:** `CAPTURE_MAX_WIDTH=unset`, `CAPTURE_JPEG_QUALITY=unset`
- **TV Starting State:** Powered ON at Live TV (`com.webos.app.livetv`), Crunchyroll closed.
- **Timer Boundary:** `T0 = 10:15:27.472`, `T_end = 10:17:55.874` (`-05:00`, excluding initial schema `read_file` setup).
---
## Normalized Scorecard
| Metric | Unstandardized Run (`aac0035`) | Standardized Baseline (`0d67615`) | Notes |
| :--- | :--- | :--- | :--- |
| **Total Timed Span (`T0 -> T_end`)** | `4m 38s` (`278s`, incl. `tv_wake`) | `2m 28s` (`148.40s`) | Zero-waste path via fixed runbook |
| **Total Steps / Captures** | `21` / `15` | `13` / `10` | `3` non-capture + `10` capture calls |
| **Median Capture Size (B)** | `22,824 B` | `19,045 B` | Range: `8,787 B` – `92,524 B` |
| **Disk-Only Offloads (`read_file` turns)** | `11` / `15` | `6` / `10` | All `>= 15,744 B` offloaded; all `<= 9,652 B` stayed inline |
| **Wasted / Retry Steps** | `4` | `0` | — |
---
## Step-by-Step Telemetry Table
| Step # | `T+elapsed` | Tool + Arguments | Tool Duration | Inline / Offload | `size_bytes` | `changed_since_last` | Observed Screen / Result |
|---:|---:|---|---:|:---:|---:|:---:|---|
| 1 | `+6.5s` | `get_state()` | ~3s | N | — | — | TV connected (`com.webos.app.livetv`) |
| 2 | `+9.5s` | `list_apps()` | ~6s | N | — | — | Found `com.crunchyroll.webapp` ("Crunchyroll") |
| 3 | `+18.5s` | `launch(app_id="com.crunchyroll.webapp")` | ~3s | N | — | — | App launched (`returnValue: true`) |
| 4 | `+29.5s` | `screenshot()` | ~4s | Y (inline + disk) | `9,650 B` | `true` | Black screen with orange loading spinner |
| 5 | `+38.5s` | `screenshot()` *(+ `read_file` ~1s)* | ~2s | Y (disk only) | `65,872 B` | `true` | Profile picker (`"¿Quién está viendo esto?"`, `Andres` focused) |
| 6 | `+54.5s` | `keys(keys=["ENTER"], settle_ms=2000, capture=True)` *(+ `read_file` ~1s)* | ~6s | Y (disk only) | `28,663 B` | `true` | Welcome loading screen (`"¡Te damos la bienvenida, Andres!"`) |
| 7 | `+69.5s` | `screenshot()` *(+ `read_file` ~1s)* | ~3s | Y (disk only) | `92,524 B` | `true` | Crunchyroll Home screen (`"Comenzar a Ver"` focused) |
| 8 | `+82.5s` | `keys(keys=["LEFT", "UP", "ENTER"], delay_ms=250, settle_ms=1500, capture=True)` *(+ `read_file` ~1s)* | ~4s | Y (disk only) | `22,346 B` | `true` | Search screen; `"Ataque a los Titanes"` under `"Búsquedas recientes"` |
| 9 | `+97.5s` | `keys(keys=["DOWN", "ENTER"], delay_ms=250, settle_ms=1500, capture=True)` *(+ `read_file` ~1s)* | ~4s | Y (disk only) | `15,744 B` | `true` | `"Ataque a los Titanes"` series page; `"Continuar E1"` focused |
| 10 | `+113.5s` | `keys(keys=["ENTER"], settle_ms=2000, capture=True)` | ~5s | Y (inline + disk) | `9,563 B` | `true` | Black screen with bottom-left orange buffering spinner |
| 11 | `+124.5s` | `screenshot()` | ~7s | Y (inline + disk) | `9,652 B` | `true` | Still buffering (bottom-left orange spinner) |
| 12 | `+130.5s` | `screenshot()` | ~2s | Y (inline + disk) | `8,787 B` | `true` | Solid black DRM frame (playback started) |
| 13 | `+137.5s` | `keys(keys=["DOWN"], settle_ms=800, capture=True)` *(+ `read_file` <1s)* | ~3s | Y (disk only) | `26,617 B` | `true` | Player HUD: `Ataque a los Titanes / E1 - Para ti, en 2000 años -- La caída de Shiganshina, parte 1` (`01:31 / 24:08`) |
@@ -0,0 +1,65 @@
# Crunchyroll E2E Comparative Report (PoC vs. `lg-smtv-mcp`)
Comparison between the initial PoC run ([`crunchyroll-e2e-experiment.md`](../poc/crunchyroll-e2e-experiment.md)) and the first live `lg-smtv-mcp` (`main` @ `aac0035`) subagent run (`b050beec-fc4c-4240-a54c-4613b8364893`) against `65UR8750PSA` (`WebOS/4.1.0`).
**Goal:** Launch Crunchyroll, select profile (`Andres`), open *Attack on Titan* (*Ataque a los Titanes*), and start Episode 1.
---
## Executive Summary
| Metric | PoC Baseline | `lg-smtv-mcp` (`aac0035`) | Notes |
| :--- | :--- | :--- | :--- |
| **Total Elapsed Time** | `7m 07s` (`427s`) | `4m 56s` (`296s`) | `lg-smtv-mcp` run also included `tv_wake` (`5.57s`), `T17 -> T1` (`UP x16`), and HUD verification |
| **Timed TV Control Span** | `~7m 05s` | `4m 38s` (`09:37:29 -> 09:42:07`) | Excludes initial schema `read_file` setup |
| **Steps / Captures** | `13` steps / `12` captures | `21` steps / `15` captures | Different reasoning paths; not 1-to-1 comparable |
| **Per-Step Tool Duration** | `~8–10s` (fresh `nix develop` + TLS + `register` + `scp`) | `2–5s` (persistent SSAP + `asyncssh` SFTP) | Transport overhead eliminated by `TvManager` |
| **Capture Size Range** | `9,606 B` – `101,992 B` | `8,787 B` – `103,192 B` | 11/15 captures exceeded ~10–15 KB and offloaded to disk |
### What MCP Bought vs. What It Didn't
- **What `TvManager` (not MCP itself) bought:** Persistent SSAP/pointer sockets and warm `asyncssh` SFTP cut per-step transport latency from `~8–10s` to `~2–5s`. A persistent REST API backed by `TvManager` would yield the same transport speedup.
- **What MCP bought:** Zero-glue host integration (typed schemas, `ImageContent` multimodal blocks, and `stdio` / `streamable-http` lifecycle) across Antigravity and other MCP clients without writing custom client wrappers.
- **What MCP did *not* buy:** Fewer UI discovery steps or faster LLM turns. Because 11 of 15 captures (`11 KB – 103 KB`) exceeded Antigravity's inline image threshold, Antigravity offloaded them to disk and spent an extra `read_file` LLM turn (`~10–15s` gap between steps) on almost every UI screen.
---
## Three-Bucket Latency Breakdown (`lg-smtv-mcp` Run)
1. **Transport & Process Overhead (`~45–60s` total across 21 steps):**
Persistent SSAP + `asyncssh` SFTP took `2–5s` per capture call (including `settle_ms`).
2. **Host / LLM Turn Overhead (`~3m 30s`):**
- Full coding-agent turn latency (`~8–12s` per turn).
- **11 extra `read_file` turns** caused by disk-offloaded `ImageContent` (`> ~10–15 KB`), directly motivating Issue **#20** (host-side JPEG downscaling/recompression).
- **Retry / loading turns:** Skeleton/loading captures (Steps 5, 7, 13, 18, 19) and `type_text` without native IME (Steps 10–11), motivating Issue **#23** (`wait_for_change`).
3. **TV / App Hardware Settling (`~20s`):**
`tv_wake` (`5.57s`), Crunchyroll splash/profile load, `UP x16` list scroll, and video buffering.
---
## Detailed Step Log (`lg-smtv-mcp` @ `aac0035`)
| Step | Time (`-05:00`) | Action / Tool + Arguments | Observed Screen / Result | Capture Size | `changed_since_last` / Hash |
| :--- | :--- | :--- | :--- | :--- | :--- |
| 0 | `09:37:17 -> 09:37:25` | `date` + `read_file` on 7 `lg-smtv` schemas | Start `09:37:19.214`; schemas loaded | — | — |
| 1 | `09:37:29 -> 09:37:30` | `get_state({})` | `connected: false, stale: true` (TV in standby) | — | — |
| 2 | `09:37:34 -> 09:37:42` | `tv_wake({})` | `status: "connected"`, `elapsed_ms: 5572` | — | — |
| 3 | `09:37:45 -> 09:37:48` | `list_apps({})` | Found `com.crunchyroll.webapp` | — | — |
| 4 | `09:37:53 -> 09:37:57` | `launch({"app_id": "com.crunchyroll.webapp"})` | `returnValue: true` | — | — |
| 5 | `09:38:01 -> 09:38:05` | `screenshot({})` + `read_file` | Crunchyroll splash screen | `94,613 B` | `true` / `548af733` |
| 6 | `09:38:16 -> 09:38:19` | `screenshot({})` + `read_file` | Profile picker (`"¿Quién está viendo esto?"`, `Andres` focused) | `65,872 B` | `true` / `4cf77ce7` |
| 7 | `09:38:31 -> 09:38:36` | `keys(["ENTER"], settle_ms=2000, capture=True)` + `read_file` | Profile selected; home sidebar rendered, content loading | `11,050 B` | `true` / `7f544a6e` |
| 8 | `09:38:48 -> 09:38:50` | `screenshot({})` + `read_file` | Home screen loaded; focus on `"Comenzar a Ver"` | `92,524 B` | `true` / `08d99efe` |
| 9 | `09:39:00 -> 09:39:04` | `keys(["LEFT", "UP", "ENTER"], delay_ms=250, settle_ms=800, capture=True)` + `read_file` | Search opened; `"Ataque a los Titanes"` in recent searches | `22,346 B` | `true` / `ac885345` |
| 10 | `09:39:15 -> 09:39:17` | `keys(["ENTER"], settle_ms=800, capture=True)` | No screen change (Crunchyroll search input did not open native IME) | `22,346 B` | `false` / `ac885345` |
| 11 | `09:39:23 -> 09:39:26` | `type_text("Attack on Titan", send_enter=True, capture=True)` | `text_sent: true`, screen unchanged (IME not open) | `22,346 B` | `false` / `ac885345` |
| 12 | `09:39:32 -> 09:39:35` | `keys(["DOWN"], settle_ms=800, capture=True)` + `read_file` | Focused `"Ataque a los Titanes"` under `"Búsquedas recientes"` | `22,824 B` | `true` / `bce1361e` |
| 13 | `09:39:49 -> 09:39:53` | `keys(["ENTER"], settle_ms=1500, capture=True)` + `read_file` | Series page loading (skeleton placeholders) | `16,665 B` | `true` / `463499ed` |
| 14 | `09:40:05 -> 09:40:08` | `screenshot({})` + `read_file` | Series page loaded (`"Continuar E17"`) | `89,709 B` | `true` / `bc2357f7` |
| 15 | `09:40:20 -> 09:40:23` | `keys(["DOWN"], settle_ms=800, capture=True)` + `read_file` | Focused `"EPISODIOS"` tab; Season 1 listed with `T17` | `96,025 B` | `true` / `e91c7353` |
| 16 | `09:40:38 -> 09:40:41` | `keys(["DOWN", "RIGHT"], delay_ms=250, settle_ms=800, capture=True)` + `read_file` | Focused `T17 - La titán hembra...` | `102,035 B` | `true` / `59a5942b` |
| 17 | `09:40:56 -> 09:41:01` | `keys(["UP"] * 16, delay_ms=150, settle_ms=800, capture=True)` + `read_file` | Focused `T1 - Para ti, en 2000 años -- La caída de S...` | `103,192 B` | `true` / `1f611a48` |
| 18 | `09:41:28 -> 09:41:37` | `keys(["ENTER"], settle_ms=2000, capture=True)` *(after `settle_ms=2500` failed `INVALID_ARGUMENT`)* | Player buffering (orange spinner) | `9,608 B` | `true` / `1cf098ba` |
| 19 | `09:41:45 -> 09:41:48` | `screenshot({})` | Still buffering (spinner rotated) | `9,565 B` | `true` / `66e7dae3` |
| 20 | `09:41:55 -> 09:41:57` | `screenshot({})` | Spinner gone, black frame (DRM video layer) | `8,787 B` | `true` / `f6ed2d39` |
| 21 | `09:42:05 -> 09:42:07` | `keys(["DOWN"], settle_ms=500, capture=True)` + `read_file` (`09:42:15`) | Player HUD: `E1 - Para ti, en 2000 años -- La caída de Shiganshina, parte 1` at `00:19 / 25:20` | `17,889 B` | `true` / `02654704` |
@@ -0,0 +1,51 @@
# Standardized E2E Benchmark Template (`lg-smtv-mcp`)
Use this template to benchmark changes (such as **#20** JPEG downscaling or **#23** `wait_for_change`) without agent reasoning variance skewing the comparison.
---
## 1. Preconditions (Pin Before Starting)
- **Commit / Branch:** `<git rev-parse --short HEAD>` (`<branch>`)
- **Server Config:** `CAPTURE_MAX_WIDTH=<value|unset>`, `CAPTURE_JPEG_QUALITY=<value|unset>`
- **TV Starting State:** Powered ON at Live TV (or Standby — record which), Crunchyroll closed.
- **Timer Boundary:** Start `T=0` at the first TV-control tool call (`launch` or `tv_wake`), **excluding** one-time MCP schema `read_file` setup. End `T_end` when the playback HUD is verified.
---
## 2. Standardized Subagent Prompt
```text
Goal: Launch Crunchyroll, select profile "Andres", open Attack on Titan ("Ataque a los Titanes"), and start Episode 1.
Execution Rules (fixed policy for benchmark parity):
1. Load any needed lg-smtv schemas first, then record `T0` (`date +"%H:%M:%S.%3N"`).
2. Always prefer `keys(..., capture=True)` over separate `keys` + `screenshot` calls.
3. Keep `settle_ms <= 2000` (use `1500–2000` on app launch, profile select, and series page open).
4. On Crunchyroll Search, select "Ataque a los Titanes" from Recent Searches if visible instead of calling `type_text`.
5. Once playback starts (black DRM frame), press `DOWN` once with `capture=True` to verify Episode 1 on the player HUD.
6. Do NOT write or edit any repository files.
For every step, record:
- Step #, T+elapsed (s), Tool + arguments, Tool duration (ms/s), Offloaded to disk? (Y/N), Capture size_bytes, changed_since_last, Observed screen.
```
---
## 3. Normalized Scorecard
| Metric | Baseline (`aac0035`) | Candidate (`<sha>`) | Delta |
| :--- | :--- | :--- | :--- |
| **Total Timed Span (`T0 -> T_end`)** | `4m 38s` (`278s`) | | |
| **Total Steps / Captures** | `21` / `15` | | |
| **Median Capture Size (B)** | `22,824 B` | | |
| **Offloaded Captures (`read_file` turns)** | `11` / `15` | | |
| **Wasted / Retry Steps** | `4` (steps 10, 11, 13→14, 18→19) | | |
---
## 4. Step-by-Step Telemetry Table
| Step | `T+s` | Tool + Arguments | Tool Duration | Offloaded? (`Y/N`) | `size_bytes` | `changed_since_last` | Observed Screen / Result |
| :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- |
| 1 | | | | | | | |
+6 -2
View File
@@ -25,6 +25,10 @@
ps.pytest-asyncio ps.pytest-asyncio
]; ];
testTools = [
pkgs.systemd
];
pythonEnv = pkgs.python3.withPackages (_: runtimeDeps ++ testDeps); pythonEnv = pkgs.python3.withPackages (_: runtimeDeps ++ testDeps);
in in
{ {
@@ -39,7 +43,7 @@
ps.pytestCheckHook ps.pytestCheckHook
pkgs.ruff pkgs.ruff
pkgs.pyright pkgs.pyright
] ++ testDeps; ] ++ testDeps ++ testTools;
preCheck = '' preCheck = ''
ruff check . ruff check .
ruff format --check . ruff format --check .
@@ -52,7 +56,7 @@
pythonEnv pythonEnv
pkgs.pyright pkgs.pyright
pkgs.ruff pkgs.ruff
]; ] ++ testTools;
shellHook = '' shellHook = ''
export PYTHONPATH="$PWD/src:${PYTHONPATH:-}" export PYTHONPATH="$PWD/src:${PYTHONPATH:-}"
if [ -d .git ] && [ -d .githooks ]; then if [ -d .git ] && [ -d .githooks ]; then
+3 -2
View File
@@ -13,6 +13,7 @@ from pathlib import Path
from typing import Any, cast from typing import Any, cast
from mcp.server.mcpserver import MCPServer from mcp.server.mcpserver import MCPServer
from websockets.exceptions import WebSocketException
from lg_smtv_mcp.auth import ASGIApp from lg_smtv_mcp.auth import ASGIApp
from lg_smtv_mcp.config import TvConfig, load_config from lg_smtv_mcp.config import TvConfig, load_config
@@ -73,7 +74,7 @@ async def _pair_tv(
existing_key: str | None, existing_key: str | None,
connect_fn: WebSocketConnectFn, connect_fn: WebSocketConnectFn,
) -> str: ) -> str:
ws = await connect_fn(f"ws://{ip}:3000") ws = await connect_fn(f"wss://{ip}:3001")
try: try:
reg_payload = build_register_payload(existing_key) reg_payload = build_register_payload(existing_key)
await ws.send(json.dumps(reg_payload)) await ws.send(json.dumps(reg_payload))
@@ -197,6 +198,6 @@ def main(
if args.command == "serve": if args.command == "serve":
return _handle_serve(args, config, uvicorn_run=uvicorn_run, stdio_run=stdio_run) return _handle_serve(args, config, uvicorn_run=uvicorn_run, stdio_run=stdio_run)
return _handle_pair(args, config, connect_fn=connect_fn, fetch_url=fetch_url) return _handle_pair(args, config, connect_fn=connect_fn, fetch_url=fetch_url)
except (ConfigError, TvError, OSError, ValueError) as exc: except (ConfigError, TvError, WebSocketException, OSError, ValueError) as exc:
print(f"error: {exc}", file=sys.stderr) print(f"error: {exc}", file=sys.stderr)
return 1 return 1
+4 -3
View File
@@ -102,9 +102,10 @@ class AsyncSshCaptureTransport:
try: try:
async with asyncio.timeout(timeout): async with asyncio.timeout(timeout):
sftp = await self._ensure_sftp(exclude=remote_path) sftp = await self._ensure_sftp(exclude=remote_path)
data = await sftp.read(remote_path) async with sftp.open(remote_path, "rb") as handle:
data = await handle.read()
return bytes(data) return bytes(data)
except asyncssh.Error, OSError: except asyncssh.Error, asyncssh.KeyImportError, OSError:
await self._close_handles() await self._close_handles()
raise raise
finally: finally:
@@ -191,7 +192,7 @@ class CaptureClient:
) )
except TvError: except TvError:
raise raise
except (asyncssh.Error, OSError) as exc: except (asyncssh.Error, asyncssh.KeyImportError, OSError) as exc:
raise TvError( raise TvError(
ErrorCode.SCREENSHOT_UNAVAILABLE, ErrorCode.SCREENSHOT_UNAVAILABLE,
f"Failed to retrieve screenshot over SSH/SFTP: {exc}", f"Failed to retrieve screenshot over SSH/SFTP: {exc}",
+91 -14
View File
@@ -2,9 +2,11 @@
import asyncio import asyncio
import hashlib import hashlib
import inspect
from pathlib import Path from pathlib import Path
from typing import Any from typing import Any
import asyncssh
import pytest import pytest
from lg_smtv_mcp.config import TvConfig from lg_smtv_mcp.config import TvConfig
@@ -12,6 +14,35 @@ from lg_smtv_mcp.errors import ErrorCode, TvError
from lg_smtv_mcp.tv_core.capture import AsyncSshCaptureTransport, CaptureClient from lg_smtv_mcp.tv_core.capture import AsyncSshCaptureTransport, CaptureClient
class FakeSftpFile:
"""Mirror asyncssh.SFTPClientFile: sync open(), async read(), async context manager."""
def __init__(
self,
data: bytes,
*,
error: Exception | None = None,
read_delay: float = 0.0,
) -> None:
self._data = data
self._error = error
self._read_delay = read_delay
self.closed = False
async def __aenter__(self) -> FakeSftpFile:
return self
async def __aexit__(self, *_exc: object) -> None:
self.closed = True
async def read(self) -> bytes:
if self._read_delay > 0:
await asyncio.sleep(self._read_delay)
if self._error is not None:
raise self._error
return self._data
class FakeSftpClient: class FakeSftpClient:
def __init__( def __init__(
self, self,
@@ -19,25 +50,34 @@ class FakeSftpClient:
files: dict[str, bytes] | None = None, files: dict[str, bytes] | None = None,
extra_names: list[str] | None = None, extra_names: list[str] | None = None,
read_error: Exception | None = None, read_error: Exception | None = None,
read_delay: float = 0.0,
remove_delay: float = 0.0, remove_delay: float = 0.0,
remove_error: Exception | None = None, remove_error: Exception | None = None,
) -> None: ) -> None:
self.files = dict(files or {}) self.files = dict(files or {})
self.extra_names = list(extra_names or []) self.extra_names = list(extra_names or [])
self.read_error = read_error self.read_error = read_error
self.read_delay = read_delay
self.remove_delay = remove_delay self.remove_delay = remove_delay
self.remove_error = remove_error self.remove_error = remove_error
self.read_calls: list[str] = [] self.open_calls: list[tuple[str, str]] = []
self.handles: list[FakeSftpFile] = []
self.remove_calls: list[str] = [] self.remove_calls: list[str] = []
self.closed = False self.closed = False
async def read(self, path: str) -> bytes: def open(self, path: str, mode: str = "r") -> FakeSftpFile:
self.read_calls.append(path) """Mirror asyncssh.SFTPClient.open: regular function returning an async file."""
if self.read_error is not None: self.open_calls.append((path, mode))
raise self.read_error error = self.read_error
if path not in self.files: if error is None and path not in self.files:
raise FileNotFoundError(path) error = FileNotFoundError(path)
return self.files[path] handle = FakeSftpFile(
self.files.get(path, b""),
error=error,
read_delay=self.read_delay,
)
self.handles.append(handle)
return handle
async def remove(self, path: str) -> None: async def remove(self, path: str) -> None:
if self.remove_delay > 0: if self.remove_delay > 0:
@@ -155,6 +195,30 @@ async def test_async_ssh_capture_transport_connect_uses_required_args(tmp_path:
assert calls[0]["passphrase"] == "secret" assert calls[0]["passphrase"] == "secret"
async def test_async_ssh_capture_transport_reads_via_real_sftp_open_api(tmp_path: Path) -> None:
"""Guard against reintroducing sftp.read(), which asyncssh 2.24 does not expose."""
assert not hasattr(asyncssh.SFTPClient, "read")
assert hasattr(asyncssh.SFTPClient, "open")
assert hasattr(asyncssh.SFTPClientFile, "__aenter__")
assert inspect.iscoroutinefunction(asyncssh.SFTPClientFile.read)
remote_path = "/tmp/lg_smtv_cap_1.jpg"
sftp = FakeSftpClient(files={remote_path: b"jpeg"})
conn = FakeSshConnection(sftp)
async def fake_connect(**kwargs: Any) -> FakeSshConnection:
_ = kwargs
return conn
transport = AsyncSshCaptureTransport(_make_config(tmp_path), connect_fn=fake_connect)
data = await transport.read_and_remove(remote_path)
assert data == b"jpeg"
assert sftp.open_calls == [(remote_path, "rb")]
assert len(sftp.handles) == 1
assert sftp.handles[0].closed is True
async def test_async_ssh_capture_transport_sweeps_on_initial_connect_and_reconnect( async def test_async_ssh_capture_transport_sweeps_on_initial_connect_and_reconnect(
tmp_path: Path, tmp_path: Path,
) -> None: ) -> None:
@@ -248,12 +312,7 @@ async def test_async_ssh_capture_transport_closes_connection_when_start_sftp_cli
async def test_async_ssh_capture_transport_enforces_read_timeout( async def test_async_ssh_capture_transport_enforces_read_timeout(
tmp_path: Path, tmp_path: Path,
) -> None: ) -> None:
class HangingSftp(FakeSftpClient): sftp = FakeSftpClient(files={"/tmp/lg_smtv_cap_1.jpg": b"bytes"}, read_delay=10.0)
async def read(self, path: str) -> bytes:
await asyncio.sleep(10.0)
return b"never"
sftp = HangingSftp(files={"/tmp/lg_smtv_cap_1.jpg": b"bytes"})
conn = FakeSshConnection(sftp) conn = FakeSshConnection(sftp)
async def fake_connect(**kwargs: Any) -> FakeSshConnection: async def fake_connect(**kwargs: Any) -> FakeSshConnection:
@@ -445,3 +504,21 @@ async def test_capture_client_maps_sftp_timeout_and_cancels_read() -> None:
assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE
assert transport.read_cancelled.is_set() assert transport.read_cancelled.is_set()
async def test_capture_client_maps_key_import_error_to_screenshot_unavailable() -> None:
transport = FakeCaptureTransport(
read_error=asyncssh.KeyImportError(
"Passphrase must be specified to import encrypted private keys"
)
)
client = CaptureClient(transport)
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
_ = (uri, payload)
return {"returnValue": True}
with pytest.raises(TvError) as exc_info:
await client.capture_frame(ssap_request)
assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE
assert "Passphrase must be specified" in exc_info.value.message
+20 -1
View File
@@ -8,6 +8,7 @@ from typing import Any
import httpx import httpx
import pytest import pytest
from mcp.server.mcpserver import MCPServer from mcp.server.mcpserver import MCPServer
from websockets.exceptions import InvalidMessage
from lg_smtv_mcp.auth import ASGIApp from lg_smtv_mcp.auth import ASGIApp
from lg_smtv_mcp.cli import main from lg_smtv_mcp.cli import main
@@ -122,7 +123,7 @@ def test_cli_pair_merges_existing_client_keys_and_writes_0600(tmp_path: Path) ->
) )
assert rc == 0 assert rc == 0
assert connected_urls == ["ws://192.0.2.20:3000"] assert connected_urls == ["wss://192.0.2.20:3001"]
saved = json.loads(key_file.read_text(encoding="utf-8")) saved = json.loads(key_file.read_text(encoding="utf-8"))
assert saved == {"192.0.2.10": "old-key", "192.0.2.20": "new-key-20"} assert saved == {"192.0.2.10": "old-key", "192.0.2.20": "new-key-20"}
assert stat.S_IMODE(key_file.stat().st_mode) == 0o600 assert stat.S_IMODE(key_file.stat().st_mode) == 0o600
@@ -196,3 +197,21 @@ def test_cli_pair_fetch_ssh_key_failure_preserves_client_key_and_exits_nonzero(
assert rc == 1 assert rc == 1
assert json.loads(key_file.read_text(encoding="utf-8")) == {"192.0.2.10": "tv-key-10"} assert json.loads(key_file.read_text(encoding="utf-8")) == {"192.0.2.10": "tv-key-10"}
assert not ssh_dest.exists() assert not ssh_dest.exists()
def test_cli_pair_returns_nonzero_on_websocket_handshake_error(
tmp_path: Path,
capsys: pytest.CaptureFixture[str],
) -> None:
async def failing_connect(_url: str) -> FakeWebSocketTransport:
raise InvalidMessage("did not receive a valid HTTP response")
rc = main(
["pair"],
config_loader=lambda: _make_config(tmp_path),
connect_fn=failing_connect,
)
assert rc == 1
captured = capsys.readouterr()
assert "error: did not receive a valid HTTP response" in captured.err
+126
View File
@@ -0,0 +1,126 @@
"""Unit tests verifying deploy/lg-smtv-mcp.service template and sandboxing directives."""
import configparser
import re
import shutil
import subprocess
from pathlib import Path
import pytest
SERVICE_TEMPLATE_PATH = Path(__file__).resolve().parent.parent / "deploy" / "lg-smtv-mcp.service"
def _parse_service_template(content: str) -> configparser.ConfigParser:
"""Parse a systemd unit file while stripping comments and preserving empty values."""
parser = configparser.ConfigParser(
comment_prefixes=("#", ";"),
inline_comment_prefixes=None,
strict=False,
allow_no_value=True,
)
parser.read_string(content)
return parser
@pytest.fixture
def systemd_analyze_bin() -> str:
binary = shutil.which("systemd-analyze")
if not binary:
pytest.fail("systemd-analyze not found in PATH; ensure pkgs.systemd is in testTools")
return binary
@pytest.fixture
def substituted_service_file(tmp_path: Path, systemd_analyze_bin: str) -> Path:
content = SERVICE_TEMPLATE_PATH.read_text(encoding="utf-8")
workdir = tmp_path / "workdir"
workdir.mkdir()
# Use neutral non-personal values derived from tmp_path (CR-02)
substituted = (
content.replace("<User>", "testuser")
.replace("<WorkingDirectory>", str(workdir))
.replace("<NixBinDir>", str(Path(systemd_analyze_bin).parent))
)
test_unit_file = tmp_path / "lg-smtv-mcp.service"
test_unit_file.write_text(substituted, encoding="utf-8")
return test_unit_file
def test_service_template_exists():
assert SERVICE_TEMPLATE_PATH.is_file(), f"Template missing at {SERVICE_TEMPLATE_PATH}"
def test_service_template_declares_deployment_placeholders():
content = SERVICE_TEMPLATE_PATH.read_text(encoding="utf-8")
assert "<User>" in content
assert "<WorkingDirectory>" in content
assert "<NixBinDir>" in content
def test_service_template_bounds_restart_limit_in_unit_section():
content = SERVICE_TEMPLATE_PATH.read_text(encoding="utf-8")
parser = _parse_service_template(content)
assert "Unit" in parser, "Missing [Unit] section in service template"
unit_section = parser["Unit"]
# CR-01: Assert exact keys and values in [Unit], not substring matches
assert unit_section.get("startlimitintervalsec") == "60s"
assert unit_section.get("startlimitburst") == "5"
def test_service_template_enables_sandboxing_baseline_in_service_section():
content = SERVICE_TEMPLATE_PATH.read_text(encoding="utf-8")
parser = _parse_service_template(content)
assert "Service" in parser, "Missing [Service] section in service template"
service_section = parser["Service"]
# CR-01: Section-aware exact-value checks; comments stripped, CapabilityBoundingSet="" enforced
assert service_section.get("nonewprivileges") == "yes"
assert service_section.get("privatetmp") == "yes"
assert service_section.get("umask") == "0077"
assert service_section.get("protectsystem") == "full"
assert service_section.get("capabilityboundingset") == ""
assert service_section.get("protectcontrolgroups") == "yes"
assert service_section.get("protectkernelmodules") == "yes"
assert service_section.get("protectkerneltunables") == "yes"
assert service_section.get("protectkernellogs") == "yes"
assert service_section.get("protectclock") == "yes"
assert service_section.get("protecthostname") == "yes"
assert service_section.get("restrictrealtime") == "yes"
assert service_section.get("restrictsuidsgid") == "yes"
assert service_section.get("lockpersonality") == "yes"
def test_systemd_analyze_verify_succeeds_on_substituted_template(
systemd_analyze_bin: str, substituted_service_file: Path
):
cmd = [systemd_analyze_bin, "verify", str(substituted_service_file)]
# CR-04: Subprocess timeout prevents CI hang
res = subprocess.run(cmd, capture_output=True, text=True, timeout=30.0)
# CR-01: Fail on warnings such as 'Unknown key' or 'Unknown lvalue' that exit 0
assert "Unknown key" not in res.stderr, f"Unknown key in template: {res.stderr}"
assert "Unknown lvalue" not in res.stderr, f"Unknown lvalue in template: {res.stderr}"
assert res.returncode == 0, f"systemd-analyze verify failed: {res.stderr}"
def test_systemd_analyze_security_reports_ok_exposure_bracket(
systemd_analyze_bin: str, substituted_service_file: Path
):
cmd = [systemd_analyze_bin, "--offline=yes", "security", str(substituted_service_file)]
# CR-04: Subprocess timeout prevents CI hang
res = subprocess.run(cmd, capture_output=True, text=True, timeout=30.0)
assert res.returncode == 0, f"systemd-analyze security failed: {res.stderr}"
# CR-05: Regex-parse the numeric exposure score and assert it satisfies the OK bracket (<= 5.0)
lines = [line for line in res.stdout.splitlines() if "Overall exposure level" in line]
assert lines, "No exposure level reported by systemd-analyze security"
score_line = lines[0]
match = re.search(r"Overall exposure level.*:\s*([0-9]+\.[0-9]+)\s+OK", score_line)
assert match is not None, f"Could not parse numeric score and OK status from: {score_line}"
score = float(match.group(1))
assert score <= 5.0, f"Exposure score {score} exceeds OK bracket threshold 5.0"
+12 -2
View File
@@ -487,8 +487,18 @@ async def test_server_create_mcp_server_wires_default_capture_client(
_ = path _ = path
return [] return []
async def read(self, path: str) -> bytes: def open(self, path: str, mode: str = "r") -> Any:
return remote_files[path] class FakeFile:
async def __aenter__(self) -> FakeFile:
return self
async def __aexit__(self, *_exc: object) -> None:
return None
async def read(self) -> bytes:
return remote_files[path]
return FakeFile()
async def remove(self, path: str) -> None: async def remove(self, path: str) -> None:
removed_paths.append(path) removed_paths.append(path)