Skip to main content
Glama
adrighem

Domoticz MCP Server

by adrighem

get_battery_levels

Retrieve devices with battery levels at or below a specified threshold to identify low-power devices needing replacement.

Instructions

Get a list of devices with battery levels at or below the specified threshold.

Args: threshold: Battery percentage threshold (default: 20).

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
thresholdNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The main handler function for the 'get_battery_levels' MCP tool. It fetches all devices, filters those with a BatteryLevel at or below the given threshold (excluding 255=no-battery), sorts ascending by battery level, and returns a JSON response.
    @mcp.tool()
    async def get_battery_levels(threshold: int = 20) -> str:
        """Get a list of devices with battery levels at or below the specified threshold.
        
        Args:
            threshold: Battery percentage threshold (default: 20).
        """
        async with create_client() as client:
            devices = await _get_cached_data(client, _device_cache, f"{DOMOTICZ_API_URL}?type=command¶m=getdevices&filter=all&used=true")
            results = []
            for dev in devices:
                battery = dev.get("BatteryLevel", 255)
                # BatteryLevel 255 often means no battery or not reporting
                if battery != 255 and battery <= threshold:
                    results.append({
                        "idx": dev.get("idx"),
                        "Name": dev.get("Name"),
                        "BatteryLevel": battery,
                        "HardwareName": dev.get("HardwareName"),
                        "LastUpdate": dev.get("LastUpdate")
                    })
            # Sort by battery level ascending
            results.sort(key=lambda x: x["BatteryLevel"])
            return json.dumps({"status": "OK", "result": results})
  • The tool is registered as an MCP tool via the @mcp.tool() decorator on line 768, using the FastMCP instance created on line 70.
    @mcp.tool()
  • The input schema defines an optional 'threshold' parameter (integer, default 20). The output is a JSON string containing 'status' and 'result' array with fields: idx, Name, BatteryLevel, HardwareName, LastUpdate.
    async def get_battery_levels(threshold: int = 20) -> str:
        """Get a list of devices with battery levels at or below the specified threshold.
        
        Args:
            threshold: Battery percentage threshold (default: 20).
        """
  • The _simplify_device helper function is used elsewhere to reduce device payload, but for get_battery_levels the handler manually constructs a simplified dict inline.
    def _simplify_device(dev: Dict[str, Any]) -> Dict[str, Any]:
        """Reduce device dictionary to essential fields to save context space."""
        keys_to_keep = [
            "idx", "Name", "Type", "SubType", "Data", "Status", 
            "BatteryLevel", "Favorite", "HardwareName", "LastUpdate", 
            "TypeImg", "Usage", "CounterToday", "Temp", "Humidity"
        ]
        return {k: dev[k] for k in keys_to_keep if k in dev}
  • The _get_cached_data helper is used by get_battery_levels to fetch and cache devices data from the Domoticz API.
    async def _get_cached_data(client: "httpx.AsyncClient", cache_obj: Dict[str, Any], api_url: str, key_path: str = "result") -> List[Dict[str, Any]]:
        now = time.time()
        if cache_obj["data"] is None or (now - cache_obj["timestamp"]) > CACHE_TTL:
            response = await _do_request(client, "GET", api_url)
            cache_obj["data"] = response.json().get(key_path, [])
            cache_obj["timestamp"] = now
        return cache_obj["data"]
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Without annotations, the description carries full burden. It states the condition for inclusion (battery levels at or below threshold), but it does not specify edge cases (e.g., threshold bounds, inclusivity) or whether the result includes only devices with battery data. Nonetheless, the core behavior is clear and non-destructive.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Two sentences: one for the overall purpose and one for the single parameter. No redundant or extraneous text.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's simplicity (one parameter, output schema present), the description covers the essential use case. The existence of an output schema means return values do not need to be explained in the description.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The description restates the parameter name, type, and default from the schema without adding new semantic information (e.g., range of valid values, that it is a percentage). Since schema coverage is 0%, the description provides minimal compensation.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('Get'), the resource ('devices with battery levels'), and the filtering condition ('at or below the specified threshold'). It distinguishes from siblings like 'get_all_devices' by specifying the filtering criterion.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage when needing devices with low battery, but it does not provide alternatives or exclusion criteria. For example, it doesn't mention when to use 'get_all_devices' instead or that only devices with battery info are returned.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/adrighem/domoticz-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server