Skip to main content
Glama

get_statistics_range

Get aggregated statistics for any Home Assistant entity over a date/time range. Analyze historical trends like monthly energy usage or hourly temperature changes.

Instructions

Get long-term aggregated statistics for an entity over a date/time range.

Same data source as get_statistics, but with an explicit window — useful for "what was my power usage from Jan 1 to Jan 31?" type questions. Aggregated bucket data survives the short-term retention window, so this works for data months/years old.

Args: entity_id: The entity (must be statistics-tracked). start_time: ISO-8601 start (2026-01-01 or 2026-01-01T00:00:00Z). UTC if no offset. end_time: ISO-8601 end. Defaults to now. period: 5minute, hour, day, week, or month.

Returns: entity_id, period, start_time, end_time, statistics.

Examples: get_statistics_range("sensor.energy", "2026-01-01", "2026-02-01", period="day") get_statistics_range("sensor.temperature", "2026-05-01", period="hour")

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
entity_idYes
start_timeYes
end_timeNo
periodNohour

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • MCP tool handler for 'get_statistics_range'. Decorated with @mcp.tool() and @async_handler. Calls get_entity_statistics_range() from app.hass with the entity_id, start_time, end_time, and period. Catches ValueError for invalid inputs.
    @mcp.tool()
    @async_handler("get_statistics_range")
    async def get_statistics_range(
        entity_id: str,
        start_time: str,
        end_time: Optional[str] = None,
        period: str = "hour",
    ) -> Dict[str, Any]:
        """
        Get long-term aggregated statistics for an entity over a date/time range.
    
        Same data source as `get_statistics`, but with an explicit window —
        useful for "what was my power usage from Jan 1 to Jan 31?" type
        questions. Aggregated bucket data survives the short-term retention
        window, so this works for data months/years old.
    
        Args:
            entity_id: The entity (must be statistics-tracked).
            start_time: ISO-8601 start (`2026-01-01` or
                        `2026-01-01T00:00:00Z`). UTC if no offset.
            end_time: ISO-8601 end. Defaults to now.
            period: `5minute`, `hour`, `day`, `week`, or `month`.
    
        Returns:
            `entity_id`, `period`, `start_time`, `end_time`, `statistics`.
    
        Examples:
            get_statistics_range("sensor.energy", "2026-01-01", "2026-02-01", period="day")
            get_statistics_range("sensor.temperature", "2026-05-01", period="hour")
        """
        logger.info(
            f"Getting statistics range for {entity_id}: "
            f"{start_time} -> {end_time or 'now'}, period={period}"
        )
        try:
            return await get_entity_statistics_range(
                entity_id, start_time, end_time, period=period
            )
        except ValueError as e:
            return {"entity_id": entity_id, "error": str(e), "statistics": []}
  • Core implementation of get_entity_statistics_range(). Validates period against _STATISTICS_PERIODS, parses ISO-8601 datetimes via _parse_iso_dt(), calls HA's WebSocket API (recorder/statistics_during_period) via app.ws.call_ws(), and returns the result dict with entity_id, period, start_time, end_time, and statistics list.
    @handle_api_errors
    async def get_entity_statistics_range(
        entity_id: str,
        start_time: Union[str, datetime],
        end_time: Optional[Union[str, datetime]] = None,
        period: str = "hour",
    ) -> Dict[str, Any]:
        """Get long-term statistics for an entity over a date/time range.
    
        Hits HA's `recorder/statistics_during_period` over the WebSocket API.
        Statistics survive the recorder's short-term retention window
        (default 10 days), so this is the right call for anything older than
        that or anything you want aggregated (mean / min / max per period).
    
        Args:
            entity_id: The entity (must have a `state_class` that HA records
                       as statistics — e.g. `measurement`, `total_increasing`).
            start_time: ISO-8601 string or datetime, UTC if naive.
            end_time: ISO-8601 string or datetime, defaults to now.
            period: Aggregation bucket — one of `5minute`, `hour`, `day`,
                    `week`, `month`. Defaults to `hour`.
    
        Returns:
            ``{"entity_id", "period", "start_time", "end_time", "statistics"}``.
            ``statistics`` is the list HA returned (each entry has `start`,
            `end`, `mean`, `min`, `max`, optionally `sum`/`state`).
        """
        if period not in _STATISTICS_PERIODS:
            raise ValueError(
                f"period must be one of {sorted(_STATISTICS_PERIODS)}, got {period!r}"
            )
        start_dt = _parse_iso_dt(start_time)
        end_dt = _parse_iso_dt(end_time) if end_time is not None else datetime.now(timezone.utc)
        if start_dt >= end_dt:
            raise ValueError("start_time must be before end_time")
    
        from app.ws import call_ws
        start_iso = start_dt.strftime("%Y-%m-%dT%H:%M:%SZ")
        end_iso = end_dt.strftime("%Y-%m-%dT%H:%M:%SZ")
        result = await call_ws(
            "recorder/statistics_during_period",
            start_time=start_iso,
            end_time=end_iso,
            statistic_ids=[entity_id],
            period=period,
        )
        return {
            "entity_id": entity_id,
            "period": period,
            "start_time": start_iso,
            "end_time": end_iso,
            # HA returns `{entity_id: [points...]}`; flatten to the list when
            # we only asked for one entity.
            "statistics": (result or {}).get(entity_id, []) if isinstance(result, dict) else result,
        }
  • Helper function _parse_iso_dt() that coerces user-supplied ISO-8601 strings or datetimes to tz-aware UTC datetimes. Used by get_entity_statistics_range() to validate and normalize start_time/end_time.
    def _parse_iso_dt(value: Union[str, datetime]) -> datetime:
        """Coerce a user-supplied datetime to a tz-aware UTC datetime.
    
        Accepts a `datetime` (assumed UTC if naive) or an ISO-8601 string
        (`2026-01-15`, `2026-01-15T12:00:00`, `2026-01-15T12:00:00Z`, or with
        explicit offset). Raises ValueError on anything else.
        """
        if isinstance(value, datetime):
            return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
        if not isinstance(value, str):
            raise ValueError(f"datetime must be str or datetime, got {type(value).__name__}")
        s = value.strip()
        # `fromisoformat` in 3.11+ accepts `Z`, but be explicit for clarity.
        if s.endswith("Z"):
            s = s[:-1] + "+00:00"
        dt = datetime.fromisoformat(s)
        return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)
  • Allowed period values (_STATISTICS_PERIODS constant): {'5minute', 'hour', 'day', 'week', 'month'}. This is the input validation constraint for the 'period' parameter.
    _STATISTICS_PERIODS = {"5minute", "hour", "day", "week", "month"}
  • WebSocket client call_ws() used by get_entity_statistics_range() to send the 'recorder/statistics_during_period' message to Home Assistant. Opens a fresh WS connection, authenticates, sends the request, and returns the result.
    async def call_ws(message_type: str, **payload: Any) -> Any:
        """Send a single request over the HA WebSocket API and return its result.
    
        Args:
            message_type: HA WS message type, e.g. ``"recorder/statistics_during_period"``.
            **payload: Additional fields merged into the request body.
    
        Returns:
            The ``result`` field of HA's success response — shape depends on
            the message type (dict, list, etc.).
    
        Raises:
            HassWebSocketError: HA replied with ``success=False`` or auth failed.
        """
        url = _ws_url()
        ssl_ctx = _build_ssl_context() if url.startswith("wss://") else None
    
        async with websockets.connect(url, ssl=ssl_ctx) as ws:
            # 1. Server sends auth_required first.
            auth_required = json.loads(await ws.recv())
            if auth_required.get("type") != "auth_required":
                raise HassWebSocketError(
                    f"Unexpected initial WS message: {auth_required}"
                )
    
            # 2. Authenticate.
            await ws.send(json.dumps({"type": "auth", "access_token": HA_TOKEN}))
            auth_result = json.loads(await ws.recv())
            if auth_result.get("type") != "auth_ok":
                raise HassWebSocketError(f"WS authentication failed: {auth_result}")
    
            # 3. Send the actual request. HA requires monotonically increasing
            #    `id` per connection; since we open a fresh connection per call,
            #    `1` is always valid.
            await ws.send(json.dumps({"id": 1, "type": message_type, **payload}))
            response = json.loads(await ws.recv())
    
            if not response.get("success", False):
                raise HassWebSocketError(
                    f"WS request {message_type!r} failed: {response.get('error', response)}"
                )
            return response.get("result")
Behavior4/5

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

With no annotations, the description carries the burden. It discloses that it uses aggregated bucket data that survives the short-term retention window, indicating behavior for old data. It doesn't mention idempotency or rate limits, but the read-only nature is clear from context and sibling names.

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

Conciseness4/5

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

Well-structured with Args, Returns, and Examples sections. Each sentence adds value, though the description is slightly longer than minimal. The examples are particularly helpful.

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 4 parameters, no annotations, and an output schema existing, the description covers all parameter semantics, return structure, and retention behavior. Examples complete the picture, making the tool's usage fully understandable.

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

Parameters5/5

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

Schema has 0% description coverage, yet the description explains all four parameters in detail: entity_id (must be statistics-tracked), start_time (ISO-8601), end_time (ISO-8601, defaults to now), and period (enum of five values). Examples further clarify usage.

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?

Description clearly states 'Get long-term aggregated statistics for an entity over a date/time range' with a specific verb and resource. It distinguishes itself from the sibling tool `get_statistics` by emphasizing the explicit date window and retention behavior.

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

Usage Guidelines5/5

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

Explicitly mentions 'Same data source as get_statistics, but with an explicit window' and provides a concrete use case example ('what was my power usage from Jan 1 to Jan 31?'). Also explains that it works for older data due to retention, helping the agent choose correctly.

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/voska/hass-mcp'

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