diff --git a/flake.nix b/flake.nix index fb33567..0819aac 100644 --- a/flake.nix +++ b/flake.nix @@ -17,6 +17,7 @@ ps.pydantic ps.asyncssh ps.uvicorn + ps.pillow ]; testDeps = [ diff --git a/pyproject.toml b/pyproject.toml index 0450ecd..55bf8dc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -13,6 +13,7 @@ dependencies = [ "pydantic", "asyncssh", "uvicorn", + "pillow", ] [project.scripts] diff --git a/src/lg_smtv_mcp/server.py b/src/lg_smtv_mcp/server.py index a5d3d43..3d1e247 100644 --- a/src/lg_smtv_mcp/server.py +++ b/src/lg_smtv_mcp/server.py @@ -160,7 +160,14 @@ def create_mcp_server(config: TvConfig, manager: TvManager | None = None) -> MCP tv_manager = ( manager if manager is not None - else TvManager(config, capture_client=CaptureClient(AsyncSshCaptureTransport(config))) + else TvManager( + config, + capture_client=CaptureClient( + AsyncSshCaptureTransport(config), + max_width=config.capture_max_width, + jpeg_quality=config.capture_jpeg_quality, + ), + ) ) @asynccontextmanager diff --git a/src/lg_smtv_mcp/tv_core/capture.py b/src/lg_smtv_mcp/tv_core/capture.py index a5f0301..70244dc 100644 --- a/src/lg_smtv_mcp/tv_core/capture.py +++ b/src/lg_smtv_mcp/tv_core/capture.py @@ -5,14 +5,51 @@ import hashlib import os from collections.abc import Awaitable, Callable from contextlib import suppress +from io import BytesIO from typing import Any import asyncssh +from PIL import Image, UnidentifiedImageError from lg_smtv_mcp.config import TvConfig from lg_smtv_mcp.errors import ErrorCode, TvError from lg_smtv_mcp.tv_core.protocols import CaptureResult, CaptureTransport +_DEFAULT_JPEG_QUALITY = 75 + + +def _recompress_jpeg( + raw_bytes: bytes, + *, + max_width: int | None, + jpeg_quality: int | None, +) -> bytes: + """Optionally downscale and/or recompress JPEG bytes for inline MCP delivery.""" + if max_width is None and jpeg_quality is None: + return raw_bytes + + quality = jpeg_quality if jpeg_quality is not None else _DEFAULT_JPEG_QUALITY + try: + with Image.open(BytesIO(raw_bytes)) as opened: + img: Image.Image = opened + width, height = img.size + if max_width is not None and width > max_width: + target_height = max(1, round(height * (max_width / width))) + img = img.resize( # pyright: ignore[reportUnknownMemberType] + (max_width, target_height), + Image.Resampling.LANCZOS, + ) + if img.mode != "RGB": + img = img.convert("RGB") + out = BytesIO() + img.save(out, format="JPEG", quality=quality) + return out.getvalue() + except (UnidentifiedImageError, OSError, ValueError, EOFError) as exc: + raise TvError( + ErrorCode.SCREENSHOT_UNAVAILABLE, + f"Failed to process screenshot image: {exc}", + ) from exc + class AsyncSshCaptureTransport: """SFTP transport for reading and removing Developer Mode screenshot captures.""" @@ -154,8 +191,16 @@ class AsyncSshCaptureTransport: class CaptureClient: """FrameCapturer that triggers executeOneShot and fetches JPEG via SFTP.""" - def __init__(self, transport: CaptureTransport) -> None: + def __init__( + self, + transport: CaptureTransport, + *, + max_width: int | None = None, + jpeg_quality: int | None = None, + ) -> None: self._transport = transport + self._max_width = max_width + self._jpeg_quality = jpeg_quality self._seq = 0 self._last_sha256: str | None = None @@ -203,6 +248,11 @@ class CaptureClient: "Screenshot capture timed out after 6.0s", ) from exc + image_bytes = _recompress_jpeg( + image_bytes, + max_width=self._max_width, + jpeg_quality=self._jpeg_quality, + ) frame_sha256 = hashlib.sha256(image_bytes).hexdigest() changed_since_last = self._last_sha256 != frame_sha256 self._last_sha256 = frame_sha256 diff --git a/tests/test_capture.py b/tests/test_capture.py index 145ce81..f26c2c5 100644 --- a/tests/test_capture.py +++ b/tests/test_capture.py @@ -3,11 +3,13 @@ import asyncio import hashlib import inspect +from io import BytesIO from pathlib import Path from typing import Any import asyncssh import pytest +from PIL import Image from lg_smtv_mcp.config import TvConfig from lg_smtv_mcp.errors import ErrorCode, TvError @@ -522,3 +524,132 @@ async def test_capture_client_maps_key_import_error_to_screenshot_unavailable() 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 + + +def _make_jpeg( + width: int, + height: int, + *, + color: tuple[int, int, int] = (25, 80, 160), + quality: int = 95, +) -> bytes: + buf = BytesIO() + img = Image.new("RGB", (width, height), color=color) + # Draw varied pixels so JPEG recompression has realistic entropy differences. + for x in range(0, width, 8): + img.putpixel((x, x % height), ((x * 7) % 255, (x * 13) % 255, 200)) + img.save(buf, format="JPEG", quality=quality) + return buf.getvalue() + + +async def test_capture_client_passes_raw_bytes_unchanged_when_no_resize_or_quality() -> None: + raw = b"raw-unprocessed-bytes" + client = CaptureClient(FakeCaptureTransport(image_bytes=raw)) + + async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]: + _ = (uri, payload) + return {"returnValue": True} + + result = await client.capture_frame(ssap_request) + + assert result.image_bytes == raw + assert result.size_bytes == len(raw) + assert result.frame_sha256 == hashlib.sha256(raw).hexdigest() + + +async def test_capture_client_downscales_preserving_aspect_ratio_with_default_quality_75() -> None: + raw = _make_jpeg(1920, 1080, quality=95) + client = CaptureClient(FakeCaptureTransport(image_bytes=raw), max_width=640) + + async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]: + _ = (uri, payload) + return {"returnValue": True} + + result = await client.capture_frame(ssap_request) + + with Image.open(BytesIO(result.image_bytes)) as img: + assert img.format == "JPEG" + assert img.size == (640, 360) + assert result.size_bytes == len(result.image_bytes) + assert result.frame_sha256 == hashlib.sha256(result.image_bytes).hexdigest() + assert result.image_bytes != raw + + +async def test_capture_client_never_upscales_when_width_at_or_below_max_width() -> None: + raw = _make_jpeg(800, 600, quality=95) + client = CaptureClient( + FakeCaptureTransport(image_bytes=raw), + max_width=1280, + jpeg_quality=80, + ) + + async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]: + _ = (uri, payload) + return {"returnValue": True} + + result = await client.capture_frame(ssap_request) + + with Image.open(BytesIO(result.image_bytes)) as img: + assert img.format == "JPEG" + assert img.size == (800, 600) + + +async def test_capture_client_recompresses_at_native_resolution_when_only_quality_set() -> None: + raw = _make_jpeg(1280, 720, quality=95) + client = CaptureClient(FakeCaptureTransport(image_bytes=raw), jpeg_quality=30) + + async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]: + _ = (uri, payload) + return {"returnValue": True} + + result = await client.capture_frame(ssap_request) + + with Image.open(BytesIO(result.image_bytes)) as img: + assert img.format == "JPEG" + assert img.size == (1280, 720) + assert result.size_bytes < len(raw) + assert result.frame_sha256 == hashlib.sha256(result.image_bytes).hexdigest() + + +async def test_capture_client_hashes_and_tracks_changes_on_final_delivered_bytes() -> None: + raw = _make_jpeg(1280, 720, quality=95) + client = CaptureClient( + FakeCaptureTransport(image_bytes=raw), + max_width=640, + jpeg_quality=75, + ) + + async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]: + _ = (uri, payload) + return {"returnValue": True} + + first = await client.capture_frame(ssap_request) + second = await client.capture_frame(ssap_request) + + assert first.frame_sha256 != hashlib.sha256(raw).hexdigest() + assert first.frame_sha256 == hashlib.sha256(first.image_bytes).hexdigest() + assert first.changed_since_last is True + assert second.changed_since_last is False + + +@pytest.mark.parametrize( + "kwargs", + [ + {"max_width": 640}, + {"jpeg_quality": 75}, + {"max_width": 640, "jpeg_quality": 75}, + ], +) +async def test_capture_client_raises_screenshot_unavailable_on_corrupt_image_bytes( + kwargs: dict[str, int], +) -> None: + client = CaptureClient(FakeCaptureTransport(image_bytes=b"not-a-valid-jpeg"), **kwargs) + + 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 diff --git a/tests/test_server.py b/tests/test_server.py index d53b4df..6ff2167 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -556,3 +556,100 @@ async def test_server_create_mcp_server_wires_default_capture_client( assert removed_paths == ["/tmp/lg_smtv_cap_1.jpg"] assert len(sftp_sessions) == 1 assert sftp_sessions[0].closed is True + + +async def test_server_create_mcp_server_wires_capture_downscaling_config( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + from io import BytesIO + + from PIL import Image + + import lg_smtv_mcp.server as server_mod + from lg_smtv_mcp.tv_core.capture import CaptureClient + + config = TvConfig( + tv_ip="192.0.2.10", + client_key_path=tmp_path / ".client_key.json", + capture_max_width=640, + capture_jpeg_quality=60, + ) + captured: dict[str, Any] = {} + remote_files: dict[str, bytes] = {} + + class DummyManager: + async def start(self) -> None: + return None + + async def close(self) -> None: + return None + + class FakeSftp: + async def listdir(self, path: str) -> list[str]: + _ = path + return [] + + def open(self, path: str, mode: str = "r") -> Any: + _ = mode + + 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: + remote_files.pop(path, None) + + async def exit(self) -> None: + return None + + class FakeSshConnection: + async def start_sftp_client(self) -> FakeSftp: + return FakeSftp() + + def close(self) -> None: + return None + + async def wait_closed(self) -> None: + return None + + def fake_tv_manager(cfg: Any, **kwargs: Any) -> DummyManager: + captured["config"] = cfg + captured["kwargs"] = kwargs + return DummyManager() + + async def fake_connect(**kwargs: Any) -> FakeSshConnection: + _ = kwargs + return FakeSshConnection() + + monkeypatch.setattr(server_mod, "TvManager", fake_tv_manager) + monkeypatch.setattr(asyncssh, "connect", fake_connect) + server_mod.create_mcp_server(config) + + capture_client = captured["kwargs"]["capture_client"] + assert isinstance(capture_client, CaptureClient) + + buf = BytesIO() + Image.new("RGB", (1920, 1080), color=(30, 60, 90)).save(buf, format="JPEG", quality=95) + large_jpeg = buf.getvalue() + + async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]: + _ = uri + remote_files[payload["path"]] = large_jpeg + return {"returnValue": True} + + try: + result = await capture_client.capture_frame(ssap_request) + finally: + await capture_client.close() + + with Image.open(BytesIO(result.image_bytes)) as img: + assert img.format == "JPEG" + assert img.size == (640, 360)