π The fast, Pythonic way to build MCP servers and clients.
examples: handle malformed media links and concurrent Fire TV setup (#5390)
Jeremiah Lowin7c6c2875186b
diff --git a/examples/apps/media_picker/media_picker_server.py b/examples/apps/media_picker/media_picker_server.pyindex ec6664da1..8d137d535 100644--- a/examples/apps/media_picker/media_picker_server.py+++ b/examples/apps/media_picker/media_picker_server.py@@ -79,8 +79,11 @@ _saved: dict[str, MediaCandidate] = {}def youtube_video_id(url: str) -> str | None:"""Extract a video ID from the common YouTube URL shapes."""- parsed = urlparse(url.strip())- host = (parsed.hostname or "").lower()+ try:+ parsed = urlparse(url.strip())+ host = (parsed.hostname or "").lower()+ except ValueError:+ return Nonefor prefix in ("www.", "m.", "music."):host = host.removeprefix(prefix)parts = [part for part in parsed.path.split("/") if part]diff --git a/examples/apps/media_picker/test_media_picker.py b/examples/apps/media_picker/test_media_picker.pyindex 5cf99c4cf..5e72fb0c5 100644--- a/examples/apps/media_picker/test_media_picker.py+++ b/examples/apps/media_picker/test_media_picker.py@@ -64,6 +64,7 @@ def oembed(monkeypatch: pytest.MonkeyPatch) -> list[str]:("https://www.youtube.com/@BobbyBroccoli", None),("https://youtube.com.evil.test/watch?v=jkAw87ZIwQA", None),("https://archive.org/details/apollo", None),+ ("https://[bad", None),],)def test_youtube_video_id(url: str, expected: str | None) -> None:@@ -92,6 +93,21 @@ async def test_links_are_verified_with_youtube(oembed: list[str]) -> None:assert len(oembed) == 4+async def test_malformed_link_does_not_discard_valid_candidates(+ oembed: list[str],+) -> None:+ candidates, unsupported, unverified = await verify_links(+ [+ MediaLink(url="https://[bad"),+ MediaLink(url="https://youtu.be/jkAw87ZIwQA"),+ ]+ )++ assert [candidate["source_id"] for candidate in candidates] == ["jkAw87ZIwQA"]+ assert (unsupported, unverified) == (1, 0)+ assert oembed == ["https://www.youtube.com/watch?v=jkAw87ZIwQA"]++async def test_actions_are_idempotent_and_reject_malformed_ids() -> None:_saved.clear()diff --git a/examples/smart_home/src/smart_home/fire_tv/client.py b/examples/smart_home/src/smart_home/fire_tv/client.pyindex 645a992db..a34fcf9d0 100644--- a/examples/smart_home/src/smart_home/fire_tv/client.py+++ b/examples/smart_home/src/smart_home/fire_tv/client.py@@ -1,5 +1,6 @@"""One Fire TV connection, opened on first use and reopened when the TV drops off."""+import asynciofrom collections.abc import AsyncIteratorfrom contextlib import asynccontextmanagerfrom pathlib import Path@@ -48,30 +49,33 @@ class FireTVConnection:def __init__(self, settings: FireTVSettings) -> None:self._settings = settingsself._client: FireTVClient | None = None+ self._lock = asyncio.Lock()async def get(self) -> FireTVClient:- host = self._settings.fire_tv_host- if self._client is None:- try:- self._client = await setup_android_tv(- host=host,- port=self._settings.fire_tv_port,- adbkey=str(self._settings.fire_tv_adb_key or ""),- adb_server_ip=self._settings.fire_tv_adb_server_ip or "",- adb_server_port=self._settings.fire_tv_adb_server_port,- device_class="firetv",- )- except Exception as e:- raise ToolError(f"Fire TV at {host} is not reachable") from e- if not self._client.available:- await self._client.adb_connect(log_errors=False)- if not self._client.available:- raise ToolError(f"Fire TV at {host} is not reachable; is it asleep?")- return self._client+ async with self._lock:+ host = self._settings.fire_tv_host+ if self._client is None:+ try:+ self._client = await setup_android_tv(+ host=host,+ port=self._settings.fire_tv_port,+ adbkey=str(self._settings.fire_tv_adb_key or ""),+ adb_server_ip=self._settings.fire_tv_adb_server_ip or "",+ adb_server_port=self._settings.fire_tv_adb_server_port,+ device_class="firetv",+ )+ except Exception as e:+ raise ToolError(f"Fire TV at {host} is not reachable") from e+ if not self._client.available:+ await self._client.adb_connect(log_errors=False)+ if not self._client.available:+ raise ToolError(f"Fire TV at {host} is not reachable; is it asleep?")+ return self._clientasync def close(self) -> None:- if self._client is not None:- await self._client.adb_close()+ async with self._lock:+ if self._client is not None:+ await self._client.adb_close()@lifespandiff --git a/examples/smart_home/tests/test_fire_tv.py b/examples/smart_home/tests/test_fire_tv.pyindex bbc8508ba..400cc259b 100644--- a/examples/smart_home/tests/test_fire_tv.py+++ b/examples/smart_home/tests/test_fire_tv.py@@ -1,3 +1,5 @@+import asyncio+import pytestfrom smart_home.fire_tv import client as fire_tv_clientfrom smart_home.fire_tv.server import fire_tv_mcp@@ -131,6 +133,63 @@ async def test_status_and_commands_share_one_connection(configured_fire_tv):assert device.closed is True+async def test_concurrent_first_calls_share_one_connection(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ devices: list[FakeFireTV] = []++ async def setup(**kwargs: object) -> FakeFireTV:+ device = FakeFireTV()+ devices.append(device)+ await asyncio.sleep(0)+ return device++ monkeypatch.setattr(fire_tv_client, "setup_android_tv", setup)+ connection = fire_tv_client.FireTVConnection(+ fire_tv_client.FireTVSettings(fire_tv_host="192.0.2.10")+ )++ try:+ first, second = await asyncio.gather(connection.get(), connection.get())+ finally:+ await connection.close()++ assert len(devices) == 1+ assert first is second is devices[0]+ assert devices[0].closed is True+++async def test_concurrent_calls_reconnect_once(monkeypatch: pytest.MonkeyPatch) -> None:+ device = FakeFireTV()+ connects: list[bool] = []++ async def setup(**kwargs: object) -> FakeFireTV:+ return device++ async def adb_connect(log_errors: bool = True) -> bool:+ connects.append(log_errors)+ await asyncio.sleep(0)+ device.available = True+ return True++ device.adb_connect = adb_connect # type: ignore[attr-defined]+ monkeypatch.setattr(fire_tv_client, "setup_android_tv", setup)+ connection = fire_tv_client.FireTVConnection(+ fire_tv_client.FireTVSettings(fire_tv_host="192.0.2.10")+ )+ await connection.get()+ device.available = False++ try:+ first, second = await asyncio.gather(connection.get(), connection.get())+ finally:+ await connection.close()++ assert first is second is device+ assert connects == [False]+ assert device.closed is True++@pytest.mark.parametrize(("tool", "arguments", "message"),[