Skip to main content
Glama

get_history_range

Retrieve raw state-change history for an entity over a specific date/time range. Use it to inspect past days or correlate with external events.

Instructions

Get raw state-change history for an entity over a date/time range.

Like get_history, but takes an explicit window instead of "N hours from now". Useful for inspecting what happened on a specific day or correlating with an external event.

Args: entity_id: The entity to fetch history for. start_time: ISO-8601 start (e.g. 2026-05-15 or 2026-05-15T08:00:00Z). Treated as UTC if no offset. end_time: ISO-8601 end. Defaults to now (UTC).

Returns: Same shape as get_history: entity_id, states, count, first_changed, last_changed.

Examples: get_history_range("light.kitchen", "2026-05-15") get_history_range("sensor.power", "2026-05-15T00:00:00Z", "2026-05-16T00:00:00Z")

Best Practices: - Bound the window — wider ranges return more data and more tokens. - For aggregated long-term data, prefer get_statistics_range.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
entity_idYes
start_timeYes
end_timeNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The main tool handler for 'get_history_range'. Decorated with @mcp.tool() and @async_handler, it takes entity_id, start_time, and optional end_time, calls get_entity_history_range from hass.py, and uses _flatten_history to format the response.
    @mcp.tool()
    @async_handler("get_history_range")
    async def get_history_range(
        entity_id: str,
        start_time: str,
        end_time: Optional[str] = None,
    ) -> Dict[str, Any]:
        """
        Get raw state-change history for an entity over a date/time range.
    
        Like `get_history`, but takes an explicit window instead of "N hours
        from now". Useful for inspecting what happened on a specific day or
        correlating with an external event.
    
        Args:
            entity_id: The entity to fetch history for.
            start_time: ISO-8601 start (e.g. `2026-05-15` or
                        `2026-05-15T08:00:00Z`). Treated as UTC if no offset.
            end_time: ISO-8601 end. Defaults to now (UTC).
    
        Returns:
            Same shape as `get_history`: `entity_id`, `states`, `count`,
            `first_changed`, `last_changed`.
    
        Examples:
            get_history_range("light.kitchen", "2026-05-15")
            get_history_range("sensor.power", "2026-05-15T00:00:00Z", "2026-05-16T00:00:00Z")
    
        Best Practices:
            - Bound the window — wider ranges return more data and more tokens.
            - For aggregated long-term data, prefer `get_statistics_range`.
        """
        logger.info(
            f"Getting history range for {entity_id}: {start_time} -> {end_time or 'now'}"
        )
        try:
            history_data = await get_entity_history_range(entity_id, start_time, end_time)
        except ValueError as e:
            return {"entity_id": entity_id, "error": str(e), "states": [], "count": 0}
        return _flatten_history(history_data, entity_id)
  • Shared helper function _flatten_history used by both get_history and get_history_range to normalize HA's list-of-lists response into a consistent dict shape with entity_id, states, count, first_changed, last_changed.
    def _flatten_history(history_data: Any, entity_id: str) -> Dict[str, Any]:
        """Shared formatter for get_history / get_history_range."""
        if isinstance(history_data, dict) and "error" in history_data:
            return {
                "entity_id": entity_id,
                "error": history_data["error"],
                "states": [],
                "count": 0,
            }
        states: List[Dict[str, Any]] = []
        if history_data and isinstance(history_data, list):
            for state_list in history_data:
                states.extend(state_list)
        if not states:
            return {
                "entity_id": entity_id,
                "states": [],
                "count": 0,
                "first_changed": None,
                "last_changed": None,
                "note": "No state changes found in the specified timeframe.",
            }
        states.sort(key=lambda x: x.get("last_changed", ""))
        return {
            "entity_id": entity_id,
            "states": states,
            "count": len(states),
            "first_changed": states[0].get("last_changed"),
            "last_changed": states[-1].get("last_changed"),
        }
  • The underlying helper function get_entity_history_range in app/hass.py that calls HA's REST API /api/history/period/<start> with end_time, filter_entity_id, and minimal_response parameters. Also validates that start_time < end_time.
    @handle_api_errors
    async def get_entity_history_range(
        entity_id: str,
        start_time: Union[str, datetime],
        end_time: Optional[Union[str, datetime]] = None,
    ) -> List[Dict[str, Any]]:
        """Get state-change history for an entity within a date/time range.
    
        Uses HA's REST history endpoint (raw state changes, not aggregated).
        Useful when you want exact state transitions over a specific window —
        e.g. "what did the front door do last Tuesday?" — without being
        boxed in to N hours back from "now".
    
        Args:
            entity_id: The entity to fetch history for.
            start_time: ISO-8601 string or datetime. Treated as UTC if naive.
            end_time: ISO-8601 string or datetime. Defaults to now (UTC).
    
        Returns:
            A list of state-change buckets exactly as HA returns them
            (`/api/history/period/...` shape).
        """
        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")
    
        client = await get_client()
        url = f"{HA_URL}/api/history/period/{start_dt.strftime('%Y-%m-%dT%H:%M:%SZ')}"
        params = {
            "filter_entity_id": entity_id,
            "minimal_response": "true",
            "end_time": end_dt.strftime("%Y-%m-%dT%H:%M:%SZ"),
        }
        response = await client.get(url, headers=get_ha_headers(), params=params)
        response.raise_for_status()
        return response.json()
  • Utility function _parse_iso_dt used by get_entity_history_range to parse ISO-8601 datetime strings or datetime objects into tz-aware UTC datetimes.
    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)
  • app/server.py:17-23 (registration)
    Import of get_entity_history_range from app.hass module at the top of app/server.py, which is the function called by the tool handler.
    from app.hass import (
        get_hass_version, get_entity_state, call_service, get_entities,
        get_automations, restart_home_assistant,
        cleanup_client, filter_fields, summarize_domain, get_system_overview,
        get_hass_error_log, get_entity_history, get_entity_history_range,
        get_entity_statistics, get_entity_statistics_range,
    )
Behavior3/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. The description mentions that the tool returns 'raw state-change history' and warns about token usage, but it does not explicitly disclose behavioral traits such as mutation risk, authentication needs, rate limits, or data freshness. The description adds some value beyond annotations (which are absent) but is not comprehensive.

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?

The description is front-loaded with the purpose, followed by comparisons, parameter explanations, return shape, examples, and best practices. It is structured and each section adds value. However, it is slightly verbose with repeated ISO-8601 details; could be more concise without losing clarity.

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

Completeness4/5

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

Given that the tool has an output schema (true) and the description references the return shape ('Same shape as get_history: entity_id, states, count, first_changed, last_changed'), the description is sufficiently complete. It covers parameters, usage, alternatives, and examples. It is well-rounded for a history retrieval tool.

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?

The input schema has 0% description coverage, so the description must explain parameters. It does so thoroughly: entity_id is 'the entity to fetch history for', start_time includes format 'ISO-8601 start' with examples and note about UTC, and end_time is 'ISO-8601 end. Defaults to now (UTC).' This adds significant meaning beyond the schema.

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 tool's purpose: 'Get raw state-change history for an entity over a date/time range.' It specifies the verb (Get), the resource (raw state-change history), and the scope (over a date/time range). The description also distinguishes itself from the sibling tool `get_history` by noting that `get_history_range` takes an explicit window instead of 'N hours from now', which helps the agent differentiate between the two.

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?

The description provides explicit usage context: 'Useful for inspecting what happened on a specific day or correlating with an external event.' It also includes best practices: 'Bound the window — wider ranges return more data and more tokens. For aggregated long-term data, prefer get_statistics_range.' This gives clear guidance on when to use this tool and when to use an alternative.

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