feat(server): implement MCPServer tools, error mapping, and ASGI lifespan

- Add optional image_bytes field to KeysResult and TextResult in protocols.py and populate in TvManager
- Implement create_mcp_server registering all 12 default tools plus ENABLE_RAW_SSAP-gated raw_ssap, mapping TvError to ToolError, and returning TextContent + ImageContent for capture responses
- Implement create_http_app wiring TransportSecuritySettings, BearerAuthMiddleware, and ASGI lifespan (TvManager start/close + SIGHUP key reload)
- Remove Red-phase xfail markers in tests/test_server.py
This commit is contained in:
kiskaadee committed 2026-11-15 21:44:11 -05:00
1 parent 9958477cb3
commit 6e216787cf
4 files changed
+200 -27

No files matched your search

+180 -5
View File
@@ -1,17 +1,192 @@
"""MCP server, ASGI lifespan management, and LG webOS TV tool definitions."""
from mcp.server.mcpserver import MCPServer
import asyncio
import base64
import json
import signal
from collections.abc import AsyncGenerator, Awaitable, Callable
from contextlib import asynccontextmanager, suppress
from dataclasses import asdict
from typing import Any
from lg_smtv_mcp.auth import ASGIApp
from lg_smtv_mcp.config import TvConfig
from mcp.server.mcpserver import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
from mcp.types import ImageContent, TextContent
from lg_smtv_mcp.auth import ASGIApp, build_transport_security_settings, wrap_bearer_auth
from lg_smtv_mcp.config import TvConfig, require_bearer_token
from lg_smtv_mcp.errors import ConfigError, TvError
from lg_smtv_mcp.tv_core import TvManager
async def _run_tv_call[T](fn: Callable[[], Awaitable[T]]) -> T:
try:
return await fn()
except TvError as exc:
raise ToolError(f"{exc.code.value}: {exc.message}") from exc
except ConfigError as exc:
raise ToolError(exc.message) from exc
def _build_capture_content(
metadata: dict[str, Any],
image_bytes: bytes | None,
) -> list[TextContent | ImageContent]:
items: list[TextContent | ImageContent] = [
TextContent(type="text", text=json.dumps(metadata)),
]
if image_bytes is not None:
encoded = base64.b64encode(image_bytes).decode("ascii")
items.append(ImageContent(type="image", data=encoded, mime_type="image/jpeg"))
return items
def _register_tools(server: MCPServer, tv_manager: TvManager, config: TvConfig) -> None:
@server.tool(description="Wake the TV via Wake-on-LAN and wait until SSAP is connected.")
async def tv_wake() -> dict[str, Any]:
status = await _run_tv_call(tv_manager.wake)
return asdict(status)
@server.tool(description="Return cached TV state without blocking on standby or UI locks.")
async def get_state() -> dict[str, Any]:
return asdict(tv_manager.get_state())
@server.tool(description="Send a batch of remote control button keys with optional screenshot.")
async def keys(
keys: list[str],
delay_ms: int = 250,
settle_ms: int = 800,
capture: bool = False,
) -> list[TextContent | ImageContent]:
res = await _run_tv_call(
lambda: tv_manager.send_keys(
keys, delay_ms=delay_ms, settle_ms=settle_ms, capture=capture
)
)
metadata: dict[str, Any] = {"keys_sent": res.keys_sent, "count": res.count}
if res.frame_sha256 is not None:
metadata["frame_sha256"] = res.frame_sha256
if res.changed_since_last is not None:
metadata["changed_since_last"] = res.changed_since_last
if res.size_bytes is not None:
metadata["size_bytes"] = res.size_bytes
if res.capture_error is not None:
metadata["capture_error"] = res.capture_error
return _build_capture_content(metadata, res.image_bytes)
@server.tool(
description=(
"Insert text via webOS IME (requires the TV's native on-screen keyboard to be open), "
"optionally pressing Enter and capturing a screenshot."
)
)
async def type_text(
text: str,
send_enter: bool = True,
capture: bool = False,
) -> list[TextContent | ImageContent]:
res = await _run_tv_call(
lambda: tv_manager.type_text(text, send_enter=send_enter, capture=capture)
)
metadata: dict[str, Any] = {
"text_sent": res.text_sent,
"enter_sent": res.enter_sent,
}
if res.frame_sha256 is not None:
metadata["frame_sha256"] = res.frame_sha256
if res.changed_since_last is not None:
metadata["changed_since_last"] = res.changed_since_last
if res.size_bytes is not None:
metadata["size_bytes"] = res.size_bytes
if res.capture_error is not None:
metadata["capture_error"] = res.capture_error
return _build_capture_content(metadata, res.image_bytes)
@server.tool(description="Capture a TV screenshot and return JPEG image content plus metadata.")
async def screenshot() -> list[TextContent | ImageContent]:
res = await _run_tv_call(tv_manager.screenshot)
metadata: dict[str, Any] = {
"frame_sha256": res.frame_sha256,
"changed_since_last": res.changed_since_last,
"size_bytes": res.size_bytes,
}
return _build_capture_content(metadata, res.image_bytes)
@server.tool(description="Launch a webOS app by ID with optional contentTarget and params.")
async def launch(
app_id: str,
content_target: str | None = None,
params: dict[str, Any] | None = None,
) -> dict[str, Any]:
return await _run_tv_call(
lambda: tv_manager.launch_app(app_id, content_target=content_target, params=params)
)
@server.tool(description="List installed TV apps as [{id, title}].")
async def list_apps() -> list[dict[str, str]]:
return await _run_tv_call(tv_manager.list_apps)
@server.tool(description="Set TV volume within [0, MAX_VOLUME].")
async def set_volume(level: int) -> dict[str, Any]:
return await _run_tv_call(lambda: tv_manager.set_volume(level))
@server.tool(description="Set TV audio mute state.")
async def set_mute(muted: bool) -> dict[str, Any]:
return await _run_tv_call(lambda: tv_manager.set_mute(muted))
@server.tool(description="List external TV inputs as [{id, label, connected}].")
async def list_inputs() -> list[dict[str, Any]]:
return await _run_tv_call(tv_manager.list_inputs)
@server.tool(description="Switch active external TV input by input_id.")
async def switch_input(input_id: str) -> dict[str, Any]:
return await _run_tv_call(lambda: tv_manager.switch_input(input_id))
@server.tool(description="Power off the TV into standby.")
async def turn_off() -> dict[str, Any]:
return await _run_tv_call(tv_manager.turn_off)
if config.enable_raw_ssap:
@server.tool(
description="Send a raw SSAP request (enabled only when ENABLE_RAW_SSAP=true)."
)
async def raw_ssap(uri: str, payload: dict[str, Any] | None = None) -> dict[str, Any]:
return await _run_tv_call(lambda: tv_manager.raw_ssap(uri, payload))
def create_mcp_server(config: TvConfig, manager: TvManager | None = None) -> MCPServer:
"""Create and configure the MCPServer instance with TV tools and lifespan."""
raise NotImplementedError
tv_manager = manager if manager is not None else TvManager(config)
@asynccontextmanager
async def _lifespan(_server: MCPServer[None]) -> AsyncGenerator[None]:
loop = asyncio.get_running_loop()
await tv_manager.start()
sighup_registered = False
if hasattr(signal, "SIGHUP"):
with suppress(NotImplementedError, AttributeError, ValueError):
loop.add_signal_handler(signal.SIGHUP, tv_manager.reload_client_key)
sighup_registered = True
try:
yield
finally:
if sighup_registered and hasattr(signal, "SIGHUP"):
with suppress(NotImplementedError, AttributeError, ValueError):
loop.remove_signal_handler(signal.SIGHUP)
await tv_manager.close()
server = MCPServer(name="lg-smtv-mcp", lifespan=_lifespan)
_register_tools(server, tv_manager, config)
return server
def create_http_app(config: TvConfig, manager: TvManager | None = None) -> ASGIApp:
"""Create the Bearer-authenticated Streamable HTTP ASGI application."""
raise NotImplementedError
token = require_bearer_token(config)
server = create_mcp_server(config, manager=manager)
app = server.streamable_http_app(
transport_security=build_transport_security_settings(config),
host=config.host,
)
return wrap_bearer_auth(app, token)
+2
View File
@@ -473,6 +473,7 @@ class TvManager:
changed_since_last=cap.changed_since_last if cap is not None else None,
size_bytes=cap.size_bytes if cap is not None else None,
capture_error=cap_err,
image_bytes=cap.image_bytes if cap is not None else None,
)
async def type_text(
@@ -505,6 +506,7 @@ class TvManager:
changed_since_last=cap.changed_since_last if cap is not None else None,
size_bytes=cap.size_bytes if cap is not None else None,
capture_error=cap_err,
image_bytes=cap.image_bytes if cap is not None else None,
)
async def screenshot(self) -> CaptureResult:
+2
View File
@@ -95,6 +95,7 @@ class KeysResult:
changed_since_last: bool | None = None
size_bytes: int | None = None
capture_error: str | None = None
image_bytes: bytes | None = None
@dataclass(frozen=True, slots=True)
@@ -107,3 +108,4 @@ class TextResult:
changed_since_last: bool | None = None
size_bytes: int | None = None
capture_error: str | None = None
image_bytes: bytes | None = None
+16 -22
View File
@@ -150,7 +150,6 @@ async def _started_manager(
await mgr.close()
@pytest.mark.xfail(strict=True, reason="Red phase: server not yet implemented")
async def test_server_registers_12_default_tools_and_gates_raw_ssap(tmp_path: Path) -> None:
expected_default = {
"tv_wake",
@@ -177,7 +176,6 @@ async def test_server_registers_12_default_tools_and_gates_raw_ssap(tmp_path: Pa
assert names_on == expected_default | {"raw_ssap"}
@pytest.mark.xfail(strict=True, reason="Red phase: server not yet implemented")
async def test_server_maps_tv_error_to_tool_error_code_and_message(tmp_path: Path) -> None:
async def standby_connect(_url: str) -> FakeWebSocketTransport:
raise TvError(ErrorCode.TV_OFFLINE_STANDBY, "TV is in standby")
@@ -187,13 +185,12 @@ async def test_server_maps_tv_error_to_tool_error_code_and_message(tmp_path: Pat
await mgr.start()
try:
server = create_mcp_server(config, manager=mgr)
with pytest.raises(ToolError, match=r"^TV_OFFLINE_STANDBY: "):
with pytest.raises(ToolError, match=r"TV_OFFLINE_STANDBY: "):
await server.call_tool("turn_off", {})
finally:
await mgr.close()
@pytest.mark.xfail(strict=True, reason="Red phase: server not yet implemented")
async def test_server_launch_merges_content_target_and_omits_empty_params(
tmp_path: Path,
) -> None:
@@ -218,7 +215,6 @@ async def test_server_launch_merges_content_target_and_omits_empty_params(
]
@pytest.mark.xfail(strict=True, reason="Red phase: server not yet implemented")
@pytest.mark.parametrize(
("level", "should_succeed"),
[(-1, False), (0, True), (30, True), (31, False)],
@@ -234,12 +230,11 @@ async def test_server_set_volume_enforces_max_volume_bounds(
await server.call_tool("set_volume", {"level": level})
assert ("ssap://audio/setVolume", {"volume": level}) in sent_requests
else:
with pytest.raises(ToolError, match=r"^INVALID_ARGUMENT: "):
with pytest.raises(ToolError, match=r"INVALID_ARGUMENT: "):
await server.call_tool("set_volume", {"level": level})
assert not any(uri == "ssap://audio/setVolume" for uri, _ in sent_requests)
@pytest.mark.xfail(strict=True, reason="Red phase: server not yet implemented")
@pytest.mark.parametrize(
("text", "should_succeed"),
[("", False), ("a", True), ("x" * 500, True), ("x" * 501, False)],
@@ -258,11 +253,10 @@ async def test_server_type_text_validates_length_bounds(
{"text": text, "replace": 0},
) in sent_requests
else:
with pytest.raises(ToolError, match=r"^INVALID_ARGUMENT: "):
with pytest.raises(ToolError, match=r"INVALID_ARGUMENT: "):
await server.call_tool("type_text", {"text": text, "send_enter": False})
@pytest.mark.xfail(strict=True, reason="Red phase: server not yet implemented")
async def test_server_screenshot_returns_text_and_image_content(tmp_path: Path) -> None:
capturer = _FakeCapturer()
async with _started_manager(tmp_path, capturer=capturer) as (config, mgr, _):
@@ -281,7 +275,6 @@ async def test_server_screenshot_returns_text_and_image_content(tmp_path: Path)
assert base64.b64decode(image_block.data) == _TEST_JPEG
@pytest.mark.xfail(strict=True, reason="Red phase: server not yet implemented")
async def test_server_keys_capture_returns_text_and_image_content(tmp_path: Path) -> None:
capturer = _FakeCapturer()
async with _started_manager(tmp_path, capturer=capturer) as (config, mgr, _):
@@ -302,7 +295,6 @@ async def test_server_keys_capture_returns_text_and_image_content(tmp_path: Path
assert base64.b64decode(image_block.data) == _TEST_JPEG
@pytest.mark.xfail(strict=True, reason="Red phase: server not yet implemented")
async def test_server_type_text_capture_returns_text_and_image_content(tmp_path: Path) -> None:
capturer = _FakeCapturer()
async with _started_manager(tmp_path, capturer=capturer) as (config, mgr, _):
@@ -320,7 +312,6 @@ async def test_server_type_text_capture_returns_text_and_image_content(tmp_path:
assert base64.b64decode(image_block.data) == _TEST_JPEG
@pytest.mark.xfail(strict=True, reason="Red phase: server not yet implemented")
async def test_server_keys_capture_returns_text_only_on_capture_error(tmp_path: Path) -> None:
capturer = _FakeCapturer(error=TvError(ErrorCode.SCREENSHOT_UNAVAILABLE, "Dev Mode expired"))
async with _started_manager(tmp_path, capturer=capturer) as (config, mgr, _):
@@ -339,7 +330,6 @@ async def test_server_keys_capture_returns_text_only_on_capture_error(tmp_path:
assert meta["capture_error"] == "SCREENSHOT_UNAVAILABLE: Dev Mode expired"
@pytest.mark.xfail(strict=True, reason="Red phase: server not yet implemented")
async def test_server_http_app_rejects_unauthenticated_mcp_request_with_401(tmp_path: Path) -> None:
config = _make_config(tmp_path)
mgr = TvManager(config, backoff_steps=(10.0,))
@@ -352,17 +342,17 @@ async def test_server_http_app_rejects_unauthenticated_mcp_request_with_401(tmp_
assert unauth.status_code == 401
@pytest.mark.xfail(strict=True, reason="Red phase: server not yet implemented")
async def test_server_http_app_lifespan_starts_and_closes_manager_with_sighup(
tmp_path: Path,
) -> None:
sent_requests: list[tuple[str, dict[str, Any]]] = []
pointer_ws = FakeWebSocketTransport()
ssap_ws = _online_transport(sent_requests)
async def connect_fn(url: str) -> FakeWebSocketTransport:
if url.endswith("/pointer"):
return pointer_ws
return _online_transport(sent_requests)
return ssap_ws
config = _make_config(tmp_path)
mgr = TvManager(config, connect_fn=connect_fn, backoff_steps=(10.0,))
@@ -374,10 +364,11 @@ async def test_server_http_app_lifespan_starts_and_closes_manager_with_sighup(
]
outgoing: list[MutableMapping[str, Any]] = []
startup_done = asyncio.Event()
allow_shutdown = asyncio.Event()
async def receive() -> MutableMapping[str, Any]:
if incoming[0]["type"] == "lifespan.shutdown":
await startup_done.wait()
await allow_shutdown.wait()
return incoming.pop(0)
async def send(msg: MutableMapping[str, Any]) -> None:
@@ -389,14 +380,17 @@ async def test_server_http_app_lifespan_starts_and_closes_manager_with_sighup(
await app({"type": "lifespan"}, receive, send)
lifespan_task: asyncio.Task[None] = asyncio.create_task(_run_lifespan())
await asyncio.wait_for(startup_done.wait(), timeout=2.0)
await _wait_connected(mgr)
loop = asyncio.get_running_loop()
assert loop.remove_signal_handler(signal.SIGHUP) is True
await asyncio.wait_for(lifespan_task, timeout=2.0)
try:
await asyncio.wait_for(startup_done.wait(), timeout=2.0)
await _wait_connected(mgr)
loop = asyncio.get_running_loop()
assert loop.remove_signal_handler(signal.SIGHUP) is True
finally:
allow_shutdown.set()
await asyncio.wait_for(lifespan_task, timeout=2.0)
assert [m["type"] for m in outgoing] == [
"lifespan.startup.complete",
"lifespan.shutdown.complete",
]
assert mgr.state != ConnectionState.CONNECTED
assert ssap_ws.closed is True