Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

Refresh the smart-home example with Hue V2 and native effects (#5009)

nate nowacke3fb4af36892
diff --git a/examples/smart_home/README.md b/examples/smart_home/README.md
index 5d065f594..5054465bf 100644
--- a/examples/smart_home/README.md
+++ b/examples/smart_home/README.md
@@ -1,15 +1,97 @@
-# smart home mcp server
+# smart home MCP
-```bash
-cd examples/smart_home
-mcp install src/smart_home/hub.py:hub_mcp -f .env
+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.
+
+## Run
+
+Create `.env` in this directory with your existing bridge credentials:
+
+```dotenv
+HUE_BRIDGE_IP=<bridge IP>
+HUE_BRIDGE_USERNAME=<bridge application key>
+HUE_BRIDGE_CERTIFICATE=/absolute/path/to/trusted-bridge.pem
```
-where `.env` contains the following:
+
+HTTPS verification is enabled. The optional certificate file is an explicitly
+trusted certificate obtained and verified for your bridge; its identity replaces
+hostname matching when connecting by IP. Without it, normal system trust and
+hostname verification apply. Credentials remain local and are not saved by the SDK.
+
+```bash
+uv run smart-home
```
-HUE_BRIDGE_IP=<your hue bridge ip>
-HUE_BRIDGE_USERNAME=<your hue bridge username>
+
+The server owns one pooled asynchronous bridge connection in its lifespan. Tools
+receive that existing connection through dependency injection. Settings load at
+startup, so importing the example does not require live credentials.
+
+## Agent workflow
+
+Start with `hue_read_rooms` and `hue_read_lights`. Rooms include member light UUIDs;
+lights include state, device connectivity and supported effects. Names must match
+exactly and be unique. V2 UUIDs replace the old numeric light and group IDs.
+
+To turn on candle flicker, check each room member's `supported_effects` and call
+`hue_set_light` for each supported bulb:
+
+```json
+{
+ "target": "<light UUID>",
+ "state": {"on": true, "effect": "candle", "effect_speed": 0.5}
+}
```
+This preserves brightness. Read `state.effect` and `state.effect_parameters` afterward to verify the active
+effect; use `effect: "no_effect"` to stop it. Effect names and support come from the
+bulb, not a fixed list. Speed is between zero and one; color or temperature supplied
+with an active effect changes its parameters.
+
+For ordinary room-wide lighting, use `hue_set_room` with brightness percent,
+`temperature_kelvin`, and optional `transition_seconds`. Color can instead use CIE
+`xy` coordinates. Native effects target individual bulbs. Brightness, color and
+effects do not implicitly turn lights on; include `on: true` when desired.
+
+Use `hue_read_scenes` to inspect room associations, palettes and per-light actions.
+That distinguishes a scene with warm static colors from one with candle or fire
+effects. `hue_activate_scene` resolves names within the chosen room and recalls the
+saved actions. Its optional `dynamic_palette` action requests palette cycling where
+supported by Hue.
+
+A write acknowledgement does not prove the resulting state. Read lights after a
+transition. Hue may partially apply a command before reporting an error; failures
+are exposed as MCP tool errors. This example does not implement scheduling,
+custom animation loops, or entertainment streaming.
+
+## Test with an agent
+
```bash
-open -a Claude
-```
\ No newline at end of file
+uv run pytest
+uv run scripts/pi_harness.py --json
+```
+
+The tests exercise actual MCP calls with a simulated bridge. The Pi harness
+requires Pi and `pi-mcp-adapter`, exposes only this MCP, disables built-in tools,
+and defaults to read-only discovery. Pass `--env-file /path/to/existing.env` if
+credentials live elsewhere; `HUE_BRIDGE_CERTIFICATE` can also be exported in the
+launching environment. A quoted prompt may request real changes to lights.
+`--json` records tool calls and results for verification.
+
+## Discovery and result metadata
+
+`hue_read_lights(room="living room")` and `hue_read_scenes(room="living room")`
+limit discovery to a room, using its exact unique name or UUID. Light results put
+observed state, supported effects and capabilities first. `details=true` includes
+the complete Hue light resource when needed. Unknown observations remain null;
+color temperature is reported only when Hue marks it valid.
+
+`hue_set_room` exposes ordinary lighting controls only. Apply native effects with
+`hue_set_light` to each supported bulb. All writes return an accepted receipt with
+`state_verified=false`; read the affected room after a transition to verify state.
+Repeating an effect or scene command may restart its animation or transition, so
+write tools do not promise idempotence. Tools interact with the external bridge.
+
+Clients should rediscover tools after this update: the former group tools are now
+`hue_read_rooms` and `hue_set_room`, and scene activation takes a `room` argument.
diff --git a/examples/smart_home/pyproject.toml b/examples/smart_home/pyproject.toml
index e38609d6e..1fd83457e 100644
--- a/examples/smart_home/pyproject.toml
+++ b/examples/smart_home/pyproject.toml
@@ -1,19 +1,30 @@
[project]
name = "smart-home"
version = "0.1.0"
-description = "Add your description here"
+description = "Observable Philips Hue control for MCP agents"
readme = "README.md"
authors = [{ name = "zzstoatzz", email = "[email protected]" }]
requires-python = ">=3.12"
-dependencies = ["fastmcp@git+https://github.com/PrefectHQ/fastmcp.git", "phue2"]
+dependencies = [
+ "fastmcp>=4.0.3,<5",
+ "phue2==1.0.0a1",
+ "pydantic-settings",
+]
[project.scripts]
smart-home = "smart_home.__main__:main"
[dependency-groups]
-dev = ["ruff", "ipython"]
+dev = ["ruff", "pytest", "pytest-asyncio"]
[build-system]
requires = ["uv_build"]
build-backend = "uv_build"
+
+[tool.pytest.ini_options]
+asyncio_mode = "auto"
+testpaths = ["tests"]
+
+[tool.uv]
+exclude-newer-package = { phue2 = false }
diff --git a/examples/smart_home/scripts/pi_harness.py b/examples/smart_home/scripts/pi_harness.py
new file mode 100644
index 000000000..c2e2a87a3
--- /dev/null
+++ b/examples/smart_home/scripts/pi_harness.py
@@ -0,0 +1,68 @@
+"""Run Pi with only this example's Hue MCP tools."""
+
+import argparse
+import json
+import os
+import subprocess
+import tempfile
+from pathlib import Path
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument(
+ "prompt",
+ nargs="?",
+ default="Read-only check: discover the Hue tools and inspect light state and capabilities. Do not change any lights.",
+ )
+ parser.add_argument(
+ "--env-file", type=Path, help="Existing dotenv file with bridge credentials"
+ )
+ parser.add_argument(
+ "--json",
+ action="store_true",
+ help="Emit Pi's JSON event stream for a tool-call audit",
+ )
+ args = parser.parse_args()
+ project = Path(__file__).resolve().parents[1]
+ agent_dir = Path(os.environ.get("PI_CODING_AGENT_DIR", Path.home() / ".pi/agent"))
+ adapter = agent_dir / "npm/node_modules/pi-mcp-adapter/index.ts"
+ if not adapter.is_file():
+ parser.error("Install the adapter first: pi install npm:pi-mcp-adapter")
+ command = ["run", "--directory", str(project)]
+ if args.env_file is not None:
+ command.extend(["--env-file", str(args.env_file.resolve())])
+ command.append("smart-home")
+ config = {
+ "mcpServers": {
+ "smart-home": {"command": "uv", "args": command, "lifecycle": "eager"}
+ }
+ }
+ with tempfile.TemporaryDirectory(prefix="hue-pi-") as directory:
+ extension = Path(directory) / "lights.ts"
+ extension.write_text(
+ f"import {{ createMcpAdapter }} from {json.dumps(str(adapter))};\n"
+ f"export default createMcpAdapter({{ config: {json.dumps(config)} }});\n"
+ )
+ pi_args = [
+ "pi",
+ "--no-session",
+ "--no-extensions",
+ "--extension",
+ str(extension),
+ "--no-context-files",
+ "--no-skills",
+ "--no-prompt-templates",
+ "--no-builtin-tools",
+ "--tools",
+ "mcp",
+ "--print",
+ ]
+ if args.json:
+ pi_args.extend(["--mode", "json"])
+ pi_args.append(args.prompt)
+ subprocess.run(pi_args, cwd=directory, check=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/smart_home/src/smart_home/__init__.py b/examples/smart_home/src/smart_home/__init__.py
index dad7ea2e0..d8ad739bb 100644
--- a/examples/smart_home/src/smart_home/__init__.py
+++ b/examples/smart_home/src/smart_home/__init__.py
@@ -1,3 +1 @@
-from smart_home.settings import settings
-
-__all__ = ["settings"]
+"""Smart-home MCP example."""
diff --git a/examples/smart_home/src/smart_home/hub.py b/examples/smart_home/src/smart_home/hub.py
index be2efc2f1..8dad0994d 100644
--- a/examples/smart_home/src/smart_home/hub.py
+++ b/examples/smart_home/src/smart_home/hub.py
@@ -1,31 +1,5 @@
-from mcp_types import ToolAnnotations
-from phue import Bridge
-
from fastmcp import FastMCP
from smart_home.lights.server import lights_mcp
-from smart_home.settings import settings
-
-hub_mcp = FastMCP("Smart Home Hub (phue2)")
-# Mount the lights service under the 'hue' namespace
+hub_mcp = FastMCP("Smart home")
hub_mcp.mount(lights_mcp, namespace="hue")
-
-
-# Add a status check for the hub
-@hub_mcp.tool(annotations=ToolAnnotations(readOnlyHint=True, openWorldHint=True))
-def hub_status() -> str:
- """Checks the status of the main hub and connections."""
- try:
- bridge = Bridge(
- ip=settings.hue_bridge_ip,
- username=settings.hue_bridge_username,
- save_config=False,
- )
- bridge.connect()
- return "Hub OK. Hue Bridge Connected (via phue2)."
- except Exception as e:
- return f"Hub Warning: Hue Bridge connection failed or not attempted: {e}"
-
-
-# Add mounting points for other services later
-# hub_mcp.mount("thermo", thermostat_mcp)
diff --git a/examples/smart_home/src/smart_home/lights/hue_utils.py b/examples/smart_home/src/smart_home/lights/hue_utils.py
index 4ec5e7106..c45fa27ef 100644
--- a/examples/smart_home/src/smart_home/lights/hue_utils.py
+++ b/examples/smart_home/src/smart_home/lights/hue_utils.py
@@ -1,34 +1,33 @@
-from typing import Any
+"""One verified, pooled Hue connection for the server's lifetime."""
+
+import ssl
+from collections.abc import AsyncIterator
+from contextlib import asynccontextmanager
from phue import Bridge
-from phue.exceptions import PhueException
-from smart_home.settings import settings
+from fastmcp import Context, FastMCP
+from fastmcp.dependencies import CurrentContext
+from fastmcp.server.lifespan import lifespan
+from smart_home.settings import Settings
-def _get_bridge() -> Bridge | None:
- """Attempts to connect to the Hue bridge using settings."""
- try:
- return Bridge(
- ip=settings.hue_bridge_ip,
- username=settings.hue_bridge_username,
- save_config=False,
- )
- except Exception:
- # Broad exception to catch potential connection issues
- # TODO: Add more specific logging or error handling
- return None
+@lifespan
+async def hue_lifespan(server: FastMCP) -> AsyncIterator[dict[str, Bridge]]:
+ settings = Settings()
+ verify: bool | ssl.SSLContext = True
+ if settings.hue_bridge_certificate is not None:
+ verify = ssl.create_default_context(cafile=str(settings.hue_bridge_certificate))
+ verify.verify_flags |= ssl.VERIFY_X509_PARTIAL_CHAIN
+ # The explicitly trusted bridge certificate identifies the bridge, not its IP.
+ verify.check_hostname = False
+ async with Bridge(
+ settings.hue_bridge_ip, settings.hue_bridge_username, verify=verify
+ ) as bridge:
+ yield {"bridge": bridge}
-def handle_phue_error(
- light_or_group: str, operation: str, error: Exception
-) -> dict[str, Any]:
- """Creates a standardized error response for phue operations."""
- base_info = {"target": light_or_group, "operation": operation, "success": False}
- if isinstance(error, KeyError):
- base_info["error"] = f"Target '{light_or_group}' not found"
- elif isinstance(error, PhueException):
- base_info["error"] = f"phue error during {operation}: {error}"
- else:
- base_info["error"] = f"Unexpected error during {operation}: {error}"
- return base_info
+@asynccontextmanager
+async def get_bridge(ctx: Context = CurrentContext()) -> AsyncIterator[Bridge]:
+ # Yield an already-open client; returning it would make DI enter it again.
+ yield ctx.lifespan_context["bridge"]
diff --git a/examples/smart_home/src/smart_home/lights/models.py b/examples/smart_home/src/smart_home/lights/models.py
new file mode 100644
index 000000000..c9b27197c
--- /dev/null
+++ b/examples/smart_home/src/smart_home/lights/models.py
@@ -0,0 +1,103 @@
+"""The agent-facing lighting contract, independent of Hue's wire representation."""
+
+from typing import Any, Literal
+
+from phue import LightState
+from phue.models import Light, ResourceIdentifier
+from pydantic import BaseModel, ConfigDict, Field, model_validator
+
+
+class RoomState(BaseModel):
+ """Ordinary room controls. Native effects must target individual lights."""
+
+ model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
+ on: bool | None = None
+ brightness: float | None = Field(
+ default=None, ge=0, le=100, description="Brightness percent."
+ )
+ temperature_kelvin: int | None = Field(
+ default=None, ge=2000, le=6500, description="Color temperature in kelvin."
+ )
+ xy: tuple[float, float] | None = Field(
+ default=None,
+ description="CIE color coordinates [x, y], mutually exclusive with temperature.",
+ )
+ transition_seconds: float | None = Field(default=None, ge=0, le=3600)
+
+ @model_validator(mode="after")
+ def validate_update(self) -> "RoomState":
+ self.to_light_state()
+ return self
+
+ def to_light_state(self) -> LightState:
+ return LightState.model_validate(self.model_dump(exclude_none=True))
+
+
+class ObservedState(BaseModel):
+ on: bool | None
+ brightness: float | None = Field(
+ description="Observed brightness percent; an effect may vary it over time."
+ )
+ xy: tuple[float, float] | None
+ temperature_kelvin: int | None = Field(
+ description="Current valid color temperature, otherwise null."
+ )
+ effect: str | None
+ effect_speed: float | None = Field(
+ description="Native effect speed, 0–1; not flicker amplitude."
+ )
+ effect_parameters: dict[str, Any] = Field(
+ description="Reported native effect parameters, including its color."
+ )
+
+
+class LightInfo(BaseModel):
+ name: str
+ state: ObservedState
+ connectivity: str | None
+ supported_effects: list[str]
+ capabilities: dict[str, Any]
+ hue_details: dict[str, Any] | None = Field(
+ default=None, description="Full Hue resource, included only when details=true."
+ )
+
+
+def describe_light(light: Light, connectivity: str | None, details: bool) -> LightInfo:
+ status = (light.effects_v2 or {}).get("status", {})
+ parameters = status.get("parameters", {})
+ xy = (light.color or {}).get("xy")
+ temperature = light.color_temperature or {}
+ mirek = temperature.get("mirek")
+ return LightInfo(
+ name=light.metadata.name,
+ state=ObservedState(
+ on=light.on.get("on"),
+ brightness=light.dimming.get("brightness"),
+ xy=(xy["x"], xy["y"]) if xy else None,
+ temperature_kelvin=round(1_000_000 / mirek)
+ if mirek and temperature.get("mirek_valid")
+ else None,
+ effect=status.get("effect"),
+ effect_speed=parameters.get("speed"),
+ effect_parameters=parameters,
+ ),
+ connectivity=connectivity,
+ supported_effects=light.supported_effects
+ if light.effects_v2 is not None
+ else [],
+ capabilities={
+ "color": light.color is not None,
+ "color_gamut": (light.color or {}).get("gamut"),
+ "temperature_mirek_range": temperature.get("mirek_schema"),
+ "minimum_brightness": light.dimming.get("min_dim_level"),
+ },
+ hue_details=light.model_dump(exclude_none=True) if details else None,
+ )
+
+
+class WriteReceipt(BaseModel):
+ target_id: str
+ status: Literal["accepted"] = "accepted"
+ accepted: list[ResourceIdentifier]
+ state_verified: Literal[False] = False
+ next_step: str = "Read lights in the affected room after any transition to verify observed state."
diff --git a/examples/smart_home/src/smart_home/lights/server.py b/examples/smart_home/src/smart_home/lights/server.py
index 6fffcb298..911b71dff 100644
--- a/examples/smart_home/src/smart_home/lights/server.py
+++ b/examples/smart_home/src/smart_home/lights/server.py
@@ -1,318 +1,181 @@
-# /// script
-# dependencies = [
-# "smart_home@git+https://github.com/PrefectHQ/fastmcp.git#subdirectory=examples/smart_home",
-# "fastmcp",
-# ]
-# ///
+"""Hue V2 discovery, saved scenes, and native effects."""
-from typing import Annotated, Any, Literal, TypedDict
+from typing import Any, Literal
from mcp_types import ToolAnnotations
-from phue.exceptions import PhueException
-from pydantic import Field
-from typing_extensions import NotRequired
+from phue import Bridge, LightState
from fastmcp import FastMCP
-from smart_home.lights.hue_utils import _get_bridge, handle_phue_error
-
-
-class HueAttributes(TypedDict, total=False):
- """TypedDict for optional light attributes."""
-
- on: NotRequired[Annotated[bool, Field(description="on/off state")]]
- bri: NotRequired[Annotated[int, Field(ge=0, le=254, description="brightness")]]
- hue: NotRequired[
- Annotated[
- int,
- Field(
- ge=0,
- le=65535,
- description="hue (color wheel position)",
- ),
- ]
- ]
- sat: NotRequired[
- Annotated[
- int,
- Field(
- ge=0,
- le=254,
- description="saturation",
- ),
- ]
- ]
- xy: NotRequired[Annotated[list[float], Field(description="xy color coordinates")]]
- ct: NotRequired[
- Annotated[
- int,
- Field(ge=153, le=500, description="color temperature"),
- ]
- ]
- alert: NotRequired[Literal["none", "select", "lselect"]]
- effect: NotRequired[Literal["none", "colorloop"]]
- transitiontime: NotRequired[Annotated[int, Field(description="deciseconds")]]
-
-
-# Dependencies are configured in lights.fastmcp.json
-lights_mcp = FastMCP("Hue Lights Service (phue2)")
-
-
-@lights_mcp.tool(annotations=ToolAnnotations(readOnlyHint=True, openWorldHint=True))
-def read_all_lights() -> list[str]:
- """Lists the names of all available Hue lights using phue2."""
- if not (bridge := _get_bridge()):
- return ["Error: Bridge not connected"]
- try:
- light_dict = bridge.get_light_objects("list")
- return [light.name for light in light_dict]
- except (PhueException, Exception) as e:
- # Simplified error handling for list return type
- return [f"Error listing lights: {e}"]
-
-
-# --- Tools ---
-
-
-@lights_mcp.tool(annotations=ToolAnnotations(readOnlyHint=False, openWorldHint=True))
-def toggle_light(light_name: str, state: bool) -> dict[str, Any]:
- """Turns a specific light on (true) or off (false) using phue2."""
- if not (bridge := _get_bridge()):
- return {"error": "Bridge not connected", "success": False}
- try:
- result = bridge.set_light(light_name, "on", state)
- return {
- "light": light_name,
- "set_on_state": state,
- "success": True,
- "phue2_result": result,
- }
- except (KeyError, PhueException, Exception) as e:
- return handle_phue_error(light_name, "toggle_light", e)
-
-
-@lights_mcp.tool(annotations=ToolAnnotations(readOnlyHint=False, openWorldHint=True))
-def set_brightness(light_name: str, brightness: int) -> dict[str, Any]:
- """Sets the brightness of a specific light (0-254) using phue2."""
- if not (bridge := _get_bridge()):
- return {"error": "Bridge not connected", "success": False}
- if not 0 <= brightness <= 254:
- # Keep specific input validation error here
- return {
- "light": light_name,
- "error": "Brightness must be between 0 and 254",
- "success": False,
- }
- try:
- result = bridge.set_light(light_name, "bri", brightness)
- return {
- "light": light_name,
- "set_brightness": brightness,
- "success": True,
- "phue2_result": result,
- }
- except (KeyError, PhueException, Exception) as e:
- return handle_phue_error(light_name, "set_brightness", e)
-
-
-@lights_mcp.tool(annotations=ToolAnnotations(readOnlyHint=True, openWorldHint=True))
-def list_groups() -> list[str]:
- """Lists the names of all available Hue light groups."""
- if not (bridge := _get_bridge()):
- return ["Error: Bridge not connected"]
- try:
- # phue2 get_group() returns a dict {id: {details}} including name
- groups = bridge.get_group()
- return [group_details["name"] for group_details in groups.values()]
- except (PhueException, Exception) as e:
- return [f"Error listing groups: {e}"]
-
-
-@lights_mcp.tool(annotations=ToolAnnotations(readOnlyHint=True, openWorldHint=True))
-def list_scenes() -> dict[str, list[str]] | list[str]:
- """Lists Hue scenes, grouped by the light group they belong to.
-
- Returns:
- dict[str, list[str]]: A dictionary mapping group names to a list of scene names within that group.
- list[str]: An error message list if the bridge connection fails or an error occurs.
+from fastmcp.dependencies import Depends
+from fastmcp.exceptions import ToolError
+from smart_home.lights.hue_utils import get_bridge, hue_lifespan
+from smart_home.lights.models import LightInfo, RoomState, WriteReceipt, describe_light
+
+lights_mcp = FastMCP(
+ "Hue lights",
+ lifespan=hue_lifespan,
+ instructions="Discover rooms, lights and scenes before changing them. Prefer IDs; names must be exact and unique. Check each bulb's supported_effects before applying a native effect. Effects run on the bulb without a polling loop. Use no_effect to stop. Changes can partially succeed before an error; read back current state to verify.",
+)
+READ = ToolAnnotations(readOnlyHint=True, openWorldHint=True)
+WRITE = ToolAnnotations(
+ readOnlyHint=False, destructiveHint=False, idempotentHint=False, openWorldHint=True
+)
+
+
+def resolve(items: dict[str, Any], target: str) -> str:
+ if target in items:
+ return target
+ matches = [key for key, item in items.items() if item["metadata"]["name"] == target]
+ if len(matches) != 1:
+ raise ToolError(
+ f"Target {target!r} is {'ambiguous; use an ID' if matches else 'unknown; list available targets first'}"
+ )
+ return matches[0]
+
+
+async def resolve_room(bridge: Bridge, target: str) -> tuple[str, dict[str, Any]]:
+ rooms = {room.id: room.model_dump() for room in await bridge.rooms()}
+ room_id = resolve(rooms, target)
+ return room_id, rooms[room_id]
+
+
+async def room_members(bridge: Bridge, target: str) -> set[str]:
+ _, room = await resolve_room(bridge, target)
+ return {child["rid"] for child in room["children"] if child["rtype"] == "device"}
+
+
+@lights_mcp.tool(annotations=READ)
+async def read_lights(
+ room: str | None = None, details: bool = False, bridge: Bridge = Depends(get_bridge)
+) -> dict[str, LightInfo]:
+ """Read lights keyed by V2 UUID, with current state and supported native effects.
+
+ Filter by room UUID or unique exact room name. State uses brightness percent
+ and kelvin; effect speed is 0–1, not amplitude. Missing values mean unknown.
+ Set details=true only when the full Hue resource is needed.
"""
- if not (bridge := _get_bridge()):
- return ["Error: Bridge not connected"]
- try:
- scenes_data = bridge.get_scene() # Returns dict {scene_id: {details...}}
- groups_data = bridge.get_group() # Returns dict {group_id: {details...}}
-
- # Create a lookup for group name by group ID
- group_id_to_name = {gid: ginfo["name"] for gid, ginfo in groups_data.items()}
-
- scenes_by_group: dict[str, list[str]] = {}
- for scene_id, scene_details in scenes_data.items():
- scene_name = scene_details.get("name")
- # Scenes might be associated with a group via 'group' key or lights
- # Using 'group' key if available is more direct for group scenes
- group_id = scene_details.get("group")
- if scene_name and group_id and group_id in group_id_to_name:
- group_name = group_id_to_name[group_id]
- if group_name not in scenes_by_group:
- scenes_by_group[group_name] = []
- # Avoid duplicate scene names within a group listing (though unlikely)
- if scene_name not in scenes_by_group[group_name]:
- scenes_by_group[group_name].append(scene_name)
-
- # Sort scenes within each group for consistent output
- for group_name in scenes_by_group:
- scenes_by_group[group_name].sort()
-
- return scenes_by_group
- except (PhueException, Exception) as e:
- # Return error as list to match other list-returning tools on error
- return [f"Error listing scenes by group: {e}"]
-
-
-@lights_mcp.tool(annotations=ToolAnnotations(readOnlyHint=False, openWorldHint=True))
-def activate_scene(group_name: str, scene_name: str) -> dict[str, Any]:
- """Activates a specific scene within a specified light group, verifying the scene belongs to the group."""
- if not (bridge := _get_bridge()):
- return {"error": "Bridge not connected", "success": False}
- try:
- # 1. Find the target group ID
- groups_data = bridge.get_group()
- target_group_id = None
- for gid, ginfo in groups_data.items():
- if ginfo.get("name") == group_name:
- target_group_id = gid
- break
- if not target_group_id:
- return {"error": f"Group '{group_name}' not found", "success": False}
-
- # 2. Find the target scene and check its group association
- scenes_data = bridge.get_scene()
- scene_found = False
- scene_in_correct_group = False
- for sinfo in scenes_data.values():
- if sinfo.get("name") == scene_name:
- scene_found = True
- # Check if this scene is associated with the target group ID
- if sinfo.get("group") == target_group_id:
- scene_in_correct_group = True
- break # Found the scene in the correct group
-
- if not scene_found:
- return {"error": f"Scene '{scene_name}' not found", "success": False}
-
- if not scene_in_correct_group:
- return {
- "error": f"Scene '{scene_name}' does not belong to group '{group_name}'",
- "success": False,
- }
-
- # 3. Activate the scene (now that we've verified it)
- result = bridge.run_scene(group_name=group_name, scene_name=scene_name)
-
- if result:
- return {
- "group": group_name,
- "activated_scene": scene_name,
- "success": True,
- "phue2_result": result,
- }
- else:
- # This case might indicate the scene/group exists but activation failed internally
- return {
- "group": group_name,
- "scene": scene_name,
- "error": "Scene activation failed (phue2 returned False)",
- "success": False,
- }
-
- except (KeyError, PhueException, Exception) as e:
- # Handle potential errors during bridge communication or data parsing
- return handle_phue_error(f"{group_name}/{scene_name}", "activate_scene", e)
-
-
-@lights_mcp.tool(annotations=ToolAnnotations(readOnlyHint=False, openWorldHint=True))
-def set_light_attributes(light_name: str, attributes: HueAttributes) -> dict[str, Any]:
- """Sets multiple attributes (e.g., hue, sat, bri, ct, xy, transitiontime) for a specific light."""
- if not (bridge := _get_bridge()):
- return {"error": "Bridge not connected", "success": False}
-
- # Basic validation (more specific validation could be added)
- if not isinstance(attributes, dict) or not attributes:
- return {
- "error": "Attributes must be a non-empty dictionary",
- "success": False,
- "light": light_name,
- }
-
- try:
- result = bridge.set_light(light_name, dict(attributes))
- return {
- "light": light_name,
- "set_attributes": attributes,
- "success": True,
- "phue2_result": result,
+ members = await room_members(bridge, room) if room is not None else None
+ connectivity = {
+ item.model_dump().get("owner", {}).get("rid"): item.model_dump().get("status")
+ for item in await bridge.resources()
+ if item.type == "zigbee_connectivity"
+ }
+ return {
+ light.id: describe_light(
+ light, connectivity.get(light.owner.rid if light.owner else None), details
+ )
+ for light in await bridge.lights()
+ if members is None or light.owner and light.owner.rid in members
+ }
+
+
+@lights_mcp.tool(annotations=READ)
+async def read_rooms(bridge: Bridge = Depends(get_bridge)) -> dict[str, Any]:
+ """Read rooms keyed by V2 UUID, including member light UUIDs and services.
+
+ Native effects must target each member light individually. Other room-wide
+ settings use set_room. Room UUIDs and member light UUIDs are distinct.
+ """
+ lights = await bridge.lights()
+ return {
+ room.id: {
+ "name": room.metadata.name,
+ "lights": [
+ light.id
+ for light in lights
+ if light.owner
+ and light.owner.rid in {child.rid for child in room.children}
+ ],
}
- except (KeyError, PhueException, ValueError, Exception) as e:
- # ValueError might occur for invalid attribute values
- return handle_phue_error(light_name, "set_light_attributes", e)
+ for room in await bridge.rooms()
+ }
-@lights_mcp.tool(annotations=ToolAnnotations(readOnlyHint=False, openWorldHint=True))
-def set_group_attributes(group_name: str, attributes: HueAttributes) -> dict[str, Any]:
- """Sets multiple attributes for all lights within a specific group."""
- if not (bridge := _get_bridge()):
- return {"error": "Bridge not connected", "success": False}
+@lights_mcp.tool(annotations=READ)
+async def read_scenes(
+ room: str | None = None, bridge: Bridge = Depends(get_bridge)
+) -> dict[str, Any]:
+ """Inspect saved scenes, including room references, palettes and per-light effects.
- if not isinstance(attributes, dict) or not attributes:
- return {
- "error": "Attributes must be a non-empty dictionary",
- "success": False,
- "group": group_name,
- }
-
- try:
- result = bridge.set_group(group_name, dict(attributes))
- return {
- "group": group_name,
- "set_attributes": attributes,
- "success": True,
- "phue2_result": result,
+ Inspect actions to distinguish a static warm scene from native candle flicker.
+ Filter by room UUID or unique exact name to avoid unrelated scenes. Scene
+ actions retain Hue units: brightness percent, xy colors and mirek temperature.
+ """
+ room_id = (await resolve_room(bridge, room))[0] if room is not None else None
+ return {
+ scene.id: {
+ "name": scene.metadata.name,
+ "room_id": scene.group.rid,
+ "actions": scene.actions,
+ "palette": scene.palette,
+ "status": scene.status,
+ "speed": scene.speed,
+ "auto_dynamic": scene.auto_dynamic,
}
- except (KeyError, PhueException, ValueError, Exception) as e:
- return handle_phue_error(group_name, "set_group_attributes", e)
-
-
-@lights_mcp.tool(annotations=ToolAnnotations(readOnlyHint=True, openWorldHint=True))
-def list_lights_by_group() -> dict[str, list[str]] | list[str]:
- """Lists Hue lights, grouped by the room/group they belong to.
-
- Returns:
- dict[str, list[str]]: A dictionary mapping group names to a list of light names within that group.
- list[str]: An error message list if the bridge connection fails or an error occurs.
+ for scene in await bridge.scenes()
+ if room_id is None or scene.group.rid == room_id
+ }
+
+
+@lights_mcp.tool(annotations=WRITE)
+async def set_light(
+ target: str, state: LightState, bridge: Bridge = Depends(get_bridge)
+) -> WriteReceipt:
+ """Change one light by UUID or unique exact name, including native candle/fire effects.
+
+ Set effect to a name advertised by the bulb; no_effect stops it. effect_speed
+ is 0–1. brightness is percent, temperature_kelvin is kelvin, and
+ transition_seconds controls ordinary transitions, not effect speed. xy is a
+ two-number array [x, y]. Color supplied with an active effect sets its color
+ parameter. Speed is not flicker amplitude; no amplitude control is exposed.
+ Brightness/effects do not implicitly turn on the light; include on=true if
+ desired. Acceptance is not state verification: read_lights afterward.
"""
- if not (bridge := _get_bridge()):
- return ["Error: Bridge not connected"]
- try:
- groups_data = bridge.get_group() # dict {group_id: {details}}
- lights_data = bridge.get_light_objects("id") # dict {light_id: {details}}
+ lights = {light.id: light.model_dump() for light in await bridge.lights()}
+ light_id = resolve(lights, target)
+ accepted = await bridge.set_light(light_id, state)
+ return WriteReceipt(target_id=light_id, accepted=accepted)
- lights_by_group: dict[str, list[str]] = {}
- for group_details in groups_data.values():
- group_name = group_details.get("name")
- light_ids = group_details.get("lights", [])
- if group_name and light_ids:
- light_names = []
- for light_id in light_ids:
- # phue uses string IDs for lights in group, but int IDs in get_light_objects
- light_id_int = int(light_id)
- if light_id_int in lights_data:
- light_name = lights_data[light_id_int].name
- if light_name:
- light_names.append(light_name)
- if light_names:
- light_names.sort()
- lights_by_group[group_name] = light_names
- return lights_by_group
+@lights_mcp.tool(annotations=WRITE)
+async def set_room(
+ target: str, state: RoomState, bridge: Bridge = Depends(get_bridge)
+) -> WriteReceipt:
+ """Change a room by UUID or unique exact name using its grouped_light service.
- except (PhueException, Exception) as e:
- return [f"Error listing lights by group: {e}"]
+ For native effects, set each member light individually after checking support.
+ Mixed groups may only partially accept color settings. Use read_lights(room=...) to verify.
+ """
+ rooms = {room.id: room.model_dump() for room in await bridge.rooms()}
+ room_id = resolve(rooms, target)
+ services = [
+ s["rid"] for s in rooms[room_id]["services"] if s["rtype"] == "grouped_light"
+ ]
+ if len(services) != 1:
+ raise ToolError("Room does not expose exactly one grouped_light service")
+ accepted = await bridge.set_group(services[0], state.to_light_state())
+ return WriteReceipt(target_id=room_id, accepted=accepted)
+
+
+@lights_mcp.tool(annotations=WRITE)
+async def activate_scene(
+ room: str,
+ scene: str,
+ action: Literal["active", "dynamic_palette", "static"] = "active",
+ bridge: Bridge = Depends(get_bridge),
+) -> WriteReceipt:
+ """Recall a saved scene within a room, including its native per-light effects.
+
+ active recalls the saved look; dynamic_palette requests palette cycling where
+ supported. Use read_scenes to inspect what will change before recalling.
+ """
+ rooms = {room.id: room.model_dump() for room in await bridge.rooms()}
+ room_id = resolve(rooms, room)
+ scenes = {
+ item.id: item.model_dump()
+ for item in await bridge.scenes()
+ if item.group and item.group.rid == room_id
+ }
+ scene_id = resolve(scenes, scene)
+ accepted = await bridge.recall_scene(scene_id, action=action)
+ return WriteReceipt(target_id=scene_id, accepted=accepted)
diff --git a/examples/smart_home/src/smart_home/settings.py b/examples/smart_home/src/smart_home/settings.py
index d6b09acdd..28a6abe5a 100644
--- a/examples/smart_home/src/smart_home/settings.py
+++ b/examples/smart_home/src/smart_home/settings.py
@@ -1,12 +1,11 @@
-from pydantic import Field
+from pathlib import Path
+
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
- hue_bridge_ip: str = Field(default=...)
- hue_bridge_username: str = Field(default=...)
-
-
-settings = Settings()
+ hue_bridge_ip: str
+ hue_bridge_username: str
+ hue_bridge_certificate: Path | None = None
diff --git a/examples/smart_home/tests/test_lights.py b/examples/smart_home/tests/test_lights.py
new file mode 100644
index 000000000..822e966c3
--- /dev/null
+++ b/examples/smart_home/tests/test_lights.py
@@ -0,0 +1,183 @@
+import json
+from unittest.mock import AsyncMock
+
+import pytest
+from phue import Bridge, HueAPIError, LightState
+from phue.models import Light, Room, Scene
+from smart_home.hub import hub_mcp
+from smart_home.lights import hue_utils
+
+from fastmcp import Client
+
+
+def bridge(monkeypatch):
+ bridge = AsyncMock(spec=Bridge)
+ bridge.__aenter__.return_value = bridge
+ bridge.lights.return_value = [
+ Light(
+ id="1",
+ type="light",
+ metadata={"name": "lamp"},
+ owner={"rid": "d1", "rtype": "device"},
+ effects_v2={
+ "action": {"effect_values": ["candle", "no_effect"]},
+ "status": {"effect": "candle"},
+ },
+ ),
+ Light(
+ id="2",
+ type="light",
+ metadata={"name": "lamp"},
+ owner={"rid": "d2", "rtype": "device"},
+ ),
+ ]
+ bridge.rooms.return_value = [
+ Room(
+ id="r1",
+ type="room",
+ metadata={"name": "living room"},
+ children=[{"rid": "d1", "rtype": "device"}],
+ services=[{"rid": "g1", "rtype": "grouped_light"}],
+ ),
+ Room(
+ id="r2",
+ type="room",
+ metadata={"name": "bedroom"},
+ children=[{"rid": "d2", "rtype": "device"}],
+ ),
+ ]
+ bridge.scenes.return_value = [
+ Scene(
+ id="s1",
+ type="scene",
+ metadata={"name": "Candle"},
+ group={"rid": "r1", "rtype": "room"},
+ actions=[{"effects_v2": {"action": {"effect": "candle"}}}],
+ ),
+ Scene(
+ id="s2",
+ type="scene",
+ metadata={"name": "Candle"},
+ group={"rid": "r2", "rtype": "room"},
+ ),
+ ]
+ bridge.resources.return_value = []
+ bridge.set_light.return_value = []
+ bridge.set_group.return_value = []
+ bridge.recall_scene.return_value = []
+ monkeypatch.setenv("HUE_BRIDGE_IP", "test-bridge")
+ monkeypatch.setenv("HUE_BRIDGE_USERNAME", "test-user")
+ monkeypatch.setattr(hue_utils, "Bridge", lambda *a, **kw: bridge)
+ return bridge
+
+
+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 all(
+ "bridge" not in tool.input_schema.get("properties", {}) for tool in tools
+ )
+ lights = (await client.call_tool("hue_read_lights")).data
+ assert lights["1"].supported_effects == ["candle", "no_effect"]
+ assert lights["1"].state.effect == "candle"
+ rooms = (await client.call_tool("hue_read_rooms")).data
+ assert rooms["r1"]["lights"] == ["1"]
+ scenes = (await client.call_tool("hue_read_scenes")).data
+ assert scenes["s1"]["actions"][0]["effects_v2"]["action"]["effect"] == "candle"
+ await client.call_tool(
+ "hue_set_light",
+ {"target": "1", "state": {"effect": "candle", "effect_speed": 0.5}},
+ )
+ bridge.set_light.assert_awaited_once_with(
+ "1", LightState(effect="candle", effect_speed=0.5)
+ )
+ bridge.__aenter__.assert_awaited_once()
+ bridge.__aexit__.assert_awaited_once()
+
+
+async def test_room_and_scene_routing(bridge):
+ async with Client(hub_mcp) as client:
+ await client.call_tool(
+ "hue_set_room", {"target": "living room", "state": {"brightness": 30}}
+ )
+ bridge.set_group.assert_awaited_once_with("g1", LightState(brightness=30))
+ await client.call_tool(
+ "hue_activate_scene", {"room": "living room", "scene": "Candle"}
+ )
+ bridge.recall_scene.assert_awaited_once_with("s1", action="active")
+ result = await client.call_tool(
+ "hue_activate_scene",
+ {"room": "living room", "scene": "s2"},
+ raise_on_error=False,
+ )
+ assert result.is_error
+ assert bridge.recall_scene.await_count == 1
+
+
+async def test_ambiguous_name_never_writes(bridge):
+ async with Client(hub_mcp) as client:
+ result = await client.call_tool(
+ "hue_set_light",
+ {"target": "lamp", "state": {"on": True}},
+ raise_on_error=False,
+ )
+ assert result.is_error
+ bridge.set_light.assert_not_awaited()
+
+
+async def test_sdk_failure_is_tool_error(bridge):
+ bridge.set_light.side_effect = HueAPIError([{"description": "unavailable"}], [])
+ async with Client(hub_mcp) as client:
+ result = await client.call_tool(
+ "hue_set_light",
+ {"target": "1", "state": {"on": True}},
+ raise_on_error=False,
+ )
+ assert result.is_error
+
+
+async def test_room_filtered_discovery_and_unknown_room(bridge):
+ async with Client(hub_mcp) as client:
+ lights = (
+ await client.call_tool("hue_read_lights", {"room": "living room"})
+ ).data
+ assert set(lights) == {"1"}
+ assert lights["1"].hue_details is None
+ assert lights["1"].state.temperature_kelvin is None
+ details = (
+ await client.call_tool("hue_read_lights", {"room": "r1", "details": True})
+ ).data
+ assert details["1"].hue_details["owner"]["rid"] == "d1"
+ scenes = (
+ await client.call_tool("hue_read_scenes", {"room": "living room"})
+ ).data
+ assert set(scenes) == {"s1"}
+ assert scenes["s1"]["room_id"] == "r1"
+ result = await client.call_tool(
+ "hue_read_lights", {"room": "missing"}, raise_on_error=False
+ )
+ assert result.is_error
+
+
+async def test_control_schema_and_receipt(bridge):
+ async with Client(hub_mcp) as client:
+ tools = {tool.name: tool for tool in await client.list_tools()}
+ room_schema = tools["hue_set_room"].input_schema
+ assert '"effect"' not in json.dumps(room_schema)
+ assert all(tool.annotations.open_world_hint for tool in tools.values())
+ result = await client.call_tool(
+ "hue_set_room",
+ {"target": "r1", "state": {"effect": "candle"}},
+ raise_on_error=False,
+ )
+ assert result.is_error
+ bridge.set_group.assert_not_awaited()
+ receipt = (
+ await client.call_tool(
+ "hue_set_light", {"target": "1", "state": {"on": True}}
+ )
+ ).data
+ assert receipt.status == "accepted"
+ assert receipt.state_verified is False