π The fast, Pythonic way to build MCP servers and clients.
Add constrained Fire TV tools to smart-home example (#5187)
nate nowack7e351469332e
diff --git a/examples/smart_home/README.md b/examples/smart_home/README.mdindex 5054465bf..5751aec23 100644--- a/examples/smart_home/README.md+++ b/examples/smart_home/README.md@@ -1,9 +1,9 @@# smart home MCP-Control Philips Hue lights through FastMCP and the `phue2` 1.0 alpha's local Hue-V2 API. An agent can discover real state and capabilities, inspect saved scenes,-and activate native candle or fire effects. The bridge runs those effects;-no agent polling loop is needed.+Control Philips Hue lights and an Amazon Fire TV through FastMCP. Hue uses the+`phue2` 1.0 alpha's local V2 API. Fire TV control reuses the `androidtv` backend+shipped by Home Assistant's Android Debug Bridge integration; raw ADB shell access+is not exposed to agents.## Run@@ -13,6 +13,8 @@ Create `.env` in this directory with your existing bridge credentials:HUE_BRIDGE_IP=<bridge IP>HUE_BRIDGE_USERNAME=<bridge application key>HUE_BRIDGE_CERTIFICATE=/absolute/path/to/trusted-bridge.pem+FIRE_TV_HOST=<Fire TV IP>+FIRE_TV_ADB_SERVER_IP=127.0.0.1```HTTPS verification is enabled. The optional certificate file is an explicitly@@ -20,16 +22,27 @@ trusted certificate obtained and verified for your bridge; its identity replaceshostname matching when connecting by IP. Without it, normal system trust andhostname verification apply. Credentials remain local and are not saved by the SDK.+`FIRE_TV_HOST` is optional. When omitted, Hue tools continue to work and Fire TV+tools return a configuration error. The example supports either an existing ADB+server via `FIRE_TV_ADB_SERVER_IP` or direct Python ADB authentication via+`FIRE_TV_ADB_KEY`. Enable ADB debugging and approve the host on the TV first.+```bashuv run smart-home```-The server owns one pooled asynchronous bridge connection in its lifespan. Tools-receive that existing connection through dependency injection. Settings load at+The server owns pooled asynchronous device connections in its lifespan. Tools+receive those existing connections through dependency injection. Settings load atstartup, so importing the example does not require live credentials.## Agent workflow+Use `fire_tv_read_status` before and after `fire_tv_press_home`,+`fire_tv_launch_app`, or `fire_tv_play_youtube_video`. App launch requires an exact+installed package ID; YouTube playback requires an 11-character video ID. Commands+return acceptance receipts, not proof that navigation completed. The constrained+surface deliberately exposes neither arbitrary URLs nor raw ADB shell commands.+Start with `hue_read_rooms` and `hue_read_lights`. Rooms include member light UUIDs;lights include state, device connectivity and supported effects. Names must matchexactly and be unique. V2 UUIDs replace the old numeric light and group IDs.diff --git a/examples/smart_home/pyproject.toml b/examples/smart_home/pyproject.tomlindex 1fd83457e..d028e8f65 100644--- a/examples/smart_home/pyproject.toml+++ b/examples/smart_home/pyproject.toml@@ -1,11 +1,12 @@[project]name = "smart-home"version = "0.1.0"-description = "Observable Philips Hue control for MCP agents"+description = "Observable Philips Hue and Fire TV control for MCP agents"readme = "README.md"authors = [{ name = "zzstoatzz", email = "[email protected]" }]requires-python = ">=3.12"dependencies = [+ "androidtv[async]==0.0.75","fastmcp>=4.0.3,<5","phue2==1.0.0a1","pydantic-settings",diff --git a/examples/smart_home/src/smart_home/fire_tv/__init__.py b/examples/smart_home/src/smart_home/fire_tv/__init__.pynew file mode 100644index 000000000..4282cb910--- /dev/null+++ b/examples/smart_home/src/smart_home/fire_tv/__init__.py@@ -0,0 +1 @@+"""Fire TV control through the Home Assistant androidtv backend."""diff --git a/examples/smart_home/src/smart_home/fire_tv/client.py b/examples/smart_home/src/smart_home/fire_tv/client.pynew file mode 100644index 000000000..8ef394826--- /dev/null+++ b/examples/smart_home/src/smart_home/fire_tv/client.py@@ -0,0 +1,77 @@+"""One pooled Fire TV connection for the server's lifetime."""++from collections.abc import AsyncIterator+from contextlib import asynccontextmanager+from pathlib import Path+from typing import Protocol++from androidtv.setup_async import setup as setup_android_tv+from pydantic_settings import BaseSettings, SettingsConfigDict++from fastmcp import Context, FastMCP+from fastmcp.dependencies import CurrentContext+from fastmcp.exceptions import ToolError+from fastmcp.server.lifespan import lifespan+++class FireTVClient(Protocol):+ available: bool+ device_properties: dict[str, str]+ installed_apps: list[str] | None++ async def update(+ self, get_running_apps: bool = True, lazy: bool = True+ ) -> tuple[str | None, str | None, list[str] | None, str | None]: ...++ async def home(self) -> None: ...++ async def launch_app(self, app: str) -> None: ...++ async def adb_shell(self, command: str) -> str | None: ...++ async def adb_close(self) -> None: ...+++class FireTVSettings(BaseSettings):+ model_config = SettingsConfigDict(env_file=".env", extra="ignore")++ fire_tv_host: str | None = None+ fire_tv_port: int = 5555+ fire_tv_adb_key: Path | None = None+ fire_tv_adb_server_ip: str | None = None+ fire_tv_adb_server_port: int = 5037+++@lifespan+async def fire_tv_lifespan(+ server: FastMCP,+) -> AsyncIterator[dict[str, FireTVClient | None]]:+ settings = FireTVSettings()+ if settings.fire_tv_host is None:+ yield {"fire_tv": None}+ return++ fire_tv = await setup_android_tv(+ host=settings.fire_tv_host,+ port=settings.fire_tv_port,+ adbkey=str(settings.fire_tv_adb_key or ""),+ adb_server_ip=settings.fire_tv_adb_server_ip or "",+ adb_server_port=settings.fire_tv_adb_server_port,+ device_class="firetv",+ )+ try:+ if not fire_tv.available:+ raise RuntimeError(f"Fire TV at {settings.fire_tv_host} is unavailable")+ yield {"fire_tv": fire_tv}+ finally:+ await fire_tv.adb_close()+++@asynccontextmanager+async def get_fire_tv(+ ctx: Context = CurrentContext(),+) -> AsyncIterator[FireTVClient]:+ fire_tv = ctx.lifespan_context["fire_tv"]+ if fire_tv is None:+ raise ToolError("Fire TV is not configured; set FIRE_TV_HOST")+ yield fire_tvdiff --git a/examples/smart_home/src/smart_home/fire_tv/models.py b/examples/smart_home/src/smart_home/fire_tv/models.pynew file mode 100644index 000000000..9d81b7a52--- /dev/null+++ b/examples/smart_home/src/smart_home/fire_tv/models.py@@ -0,0 +1,18 @@+from pydantic import BaseModel+++class FireTVStatus(BaseModel):+ available: bool+ state: str | None+ current_app: str | None+ running_apps: list[str] | None+ hdmi_input: str | None+ manufacturer: str | None+ model: str | None+++class CommandReceipt(BaseModel):+ command: str+ accepted: bool = True+ state_verified: bool = False+ next_step: str = "Read Fire TV status to verify the observed state."diff --git a/examples/smart_home/src/smart_home/fire_tv/server.py b/examples/smart_home/src/smart_home/fire_tv/server.pynew file mode 100644index 000000000..68e1820c2--- /dev/null+++ b/examples/smart_home/src/smart_home/fire_tv/server.py@@ -0,0 +1,80 @@+"""A constrained Fire TV surface backed by Home Assistant's androidtv library."""++import re++from mcp_types import ToolAnnotations++from fastmcp import FastMCP+from fastmcp.dependencies import Depends+from fastmcp.exceptions import ToolError+from smart_home.fire_tv.client import FireTVClient, fire_tv_lifespan, get_fire_tv+from smart_home.fire_tv.models import CommandReceipt, FireTVStatus++fire_tv_mcp = FastMCP(+ "Fire TV",+ lifespan=fire_tv_lifespan,+ instructions="Read status before control. Writes are accepted commands, not proof of resulting TV state; read status afterward. No raw ADB shell access is exposed.",+)+READ = ToolAnnotations(readOnlyHint=True, openWorldHint=True)+WRITE = ToolAnnotations(+ readOnlyHint=False, destructiveHint=False, idempotentHint=False, openWorldHint=True+)+YOUTUBE_VIDEO_ID = re.compile(r"^[A-Za-z0-9_-]{11}$")+++@fire_tv_mcp.tool(annotations=READ)+async def read_status(+ fire_tv: FireTVClient = Depends(get_fire_tv),+) -> FireTVStatus:+ """Read power/media state and the foreground app without changing the TV."""+ state, current_app, running_apps, hdmi_input = await fire_tv.update(+ get_running_apps=False, lazy=True+ )+ properties = fire_tv.device_properties+ return FireTVStatus(+ available=fire_tv.available,+ state=state,+ current_app=current_app,+ running_apps=running_apps,+ hdmi_input=hdmi_input,+ manufacturer=properties.get("manufacturer"),+ model=properties.get("model"),+ )+++@fire_tv_mcp.tool(annotations=WRITE)+async def press_home(+ fire_tv: FireTVClient = Depends(get_fire_tv),+) -> CommandReceipt:+ """Press Home. This changes navigation only; read status afterward to verify."""+ await fire_tv.home()+ return CommandReceipt(command="home")+++@fire_tv_mcp.tool(annotations=WRITE)+async def launch_app(+ package_id: str,+ fire_tv: FireTVClient = Depends(get_fire_tv),+) -> CommandReceipt:+ """Launch an installed app by exact package ID, then read status to verify."""+ if package_id not in (fire_tv.installed_apps or []):+ raise ToolError(f"Package {package_id!r} is not installed")+ await fire_tv.launch_app(package_id)+ return CommandReceipt(command=f"launch_app:{package_id}")+++@fire_tv_mcp.tool(annotations=WRITE)+async def play_youtube_video(+ video_id: str,+ fire_tv: FireTVClient = Depends(get_fire_tv),+) -> CommandReceipt:+ """Open one YouTube video by its 11-character ID, then verify via status."""+ if YOUTUBE_VIDEO_ID.fullmatch(video_id) is None:+ raise ToolError("YouTube video IDs must contain 11 URL-safe characters")++ await fire_tv.adb_shell(+ "am start -a android.intent.action.VIEW "+ f"-d https://www.youtube.com/watch?v={video_id} "+ "com.amazon.firetv.youtube"+ )+ return CommandReceipt(command=f"play_youtube_video:{video_id}")diff --git a/examples/smart_home/src/smart_home/hub.py b/examples/smart_home/src/smart_home/hub.pyindex 8dad0994d..a75e9220d 100644--- a/examples/smart_home/src/smart_home/hub.py+++ b/examples/smart_home/src/smart_home/hub.py@@ -1,5 +1,7 @@from fastmcp import FastMCP+from smart_home.fire_tv.server import fire_tv_mcpfrom smart_home.lights.server import lights_mcphub_mcp = FastMCP("Smart home")hub_mcp.mount(lights_mcp, namespace="hue")+hub_mcp.mount(fire_tv_mcp, namespace="fire_tv")diff --git a/examples/smart_home/tests/test_fire_tv.py b/examples/smart_home/tests/test_fire_tv.pynew file mode 100644index 000000000..49bb7a46c--- /dev/null+++ b/examples/smart_home/tests/test_fire_tv.py@@ -0,0 +1,160 @@+import pytest+from smart_home.fire_tv import client as fire_tv_client+from smart_home.fire_tv.server import fire_tv_mcp++from fastmcp import Client+++class FakeFireTV:+ def __init__(self, *, available: bool = True) -> None:+ self.available = available+ self.device_properties = {"manufacturer": "Amazon", "model": "AFTTIFF43"}+ self.installed_apps = [+ "com.amazon.firetv.youtube",+ "com.amazon.tv.launcher",+ ]+ self.commands: list[tuple[str, str | None]] = []+ self.closed = False++ async def update(+ self, get_running_apps: bool = True, lazy: bool = True+ ) -> tuple[str, str, list[str], None]:+ assert get_running_apps is False+ assert lazy is True+ return "idle", "com.amazon.tv.launcher", ["com.amazon.tv.launcher"], None++ async def home(self) -> None:+ self.commands.append(("home", None))++ async def launch_app(self, app: str) -> None:+ self.commands.append(("launch_app", app))++ async def adb_shell(self, command: str) -> str | None:+ self.commands.append(("adb_shell", command))+ return None++ async def adb_close(self) -> None:+ self.closed = True+++def configured_fire_tv(+ monkeypatch: pytest.MonkeyPatch,+) -> tuple[FakeFireTV, list[dict[str, object]]]:+ device = FakeFireTV()+ setup_calls: list[dict[str, object]] = []++ async def setup(**kwargs: object) -> FakeFireTV:+ setup_calls.append(kwargs)+ return device++ monkeypatch.setenv("FIRE_TV_HOST", "192.0.2.10")+ monkeypatch.setenv("FIRE_TV_ADB_SERVER_IP", "127.0.0.1")+ monkeypatch.setattr(fire_tv_client, "setup_android_tv", setup)+ return device, setup_calls+++async def test_status_and_commands_share_one_connection(configured_fire_tv):+ device, setup_calls = configured_fire_tv+ async with Client(fire_tv_mcp) as client:+ tools = {tool.name: tool for tool in await client.list_tools()}+ assert set(tools) == {+ "read_status",+ "press_home",+ "launch_app",+ "play_youtube_video",+ }+ assert tools["read_status"].annotations.read_only_hint is True+ assert tools["press_home"].annotations.read_only_hint is False++ status = (await client.call_tool("read_status")).data+ assert status.model == "AFTTIFF43"+ assert status.current_app == "com.amazon.tv.launcher"++ receipt = (await client.call_tool("press_home")).data+ assert receipt.accepted is True+ assert receipt.state_verified is False++ launch = (+ await client.call_tool(+ "launch_app", {"package_id": "com.amazon.firetv.youtube"}+ )+ ).data+ assert launch.command == "launch_app:com.amazon.firetv.youtube"++ video = (+ await client.call_tool("play_youtube_video", {"video_id": "D1VM6V6wmU0"})+ ).data+ assert video.command == "play_youtube_video:D1VM6V6wmU0"++ assert setup_calls == [+ {+ "host": "192.0.2.10",+ "port": 5555,+ "adbkey": "",+ "adb_server_ip": "127.0.0.1",+ "adb_server_port": 5037,+ "device_class": "firetv",+ }+ ]+ assert device.commands == [+ ("home", None),+ ("launch_app", "com.amazon.firetv.youtube"),+ (+ "adb_shell",+ "am start -a android.intent.action.VIEW "+ "-d https://www.youtube.com/watch?v=D1VM6V6wmU0 "+ "com.amazon.firetv.youtube",+ ),+ ]+ assert device.closed is True+++ ("tool", "arguments", "message"),+ [+ ("launch_app", {"package_id": "not.installed"}, "not installed"),+ (+ "play_youtube_video",+ {"video_id": "invalid; reboot"},+ "11 URL-safe characters",+ ),+ ],+)+async def test_invalid_targets_are_rejected_without_device_commands(+ configured_fire_tv,+ tool: str,+ arguments: dict[str, str],+ message: str,+):+ device, _ = configured_fire_tv+ async with Client(fire_tv_mcp) as client:+ result = await client.call_tool(tool, arguments, raise_on_error=False)+ assert result.is_error+ assert message in str(result.content)++ assert device.commands == []+++async def test_unconfigured_server_exposes_tools_but_refuses_calls(monkeypatch):+ monkeypatch.delenv("FIRE_TV_HOST", raising=False)+ async with Client(fire_tv_mcp) as client:+ result = await client.call_tool("read_status", raise_on_error=False)+ assert result.is_error+ assert "FIRE_TV_HOST" in str(result.content)+++async def test_unavailable_device_is_closed(monkeypatch):+ device = FakeFireTV(available=False)++ async def setup(**kwargs: object) -> FakeFireTV:+ return device++ monkeypatch.setenv("FIRE_TV_HOST", "192.0.2.10")+ monkeypatch.setattr(fire_tv_client, "setup_android_tv", setup)++ with pytest.raises(RuntimeError, match="unavailable"):+ async with Client(fire_tv_mcp):+ pass++ assert device.closed is Truediff --git a/examples/smart_home/tests/test_lights.py b/examples/smart_home/tests/test_lights.pyindex 822e966c3..4afac409b 100644--- a/examples/smart_home/tests/test_lights.py+++ b/examples/smart_home/tests/test_lights.py@@ -75,7 +75,7 @@ def bridge(monkeypatch):async def test_native_effect_discovery_and_lifespan(bridge):async with Client(hub_mcp) as client:tools = await client.list_tools()- assert len(tools) == 6+ assert len(tools) == 10assert all("bridge" not in tool.input_schema.get("properties", {}) for tool in tools)