Skip to main content
Glama

get_history

Retrieve historical state changes for Home Assistant entities to analyze device behavior patterns over specified time periods.

Instructions

Get the history of an entity's state changes

Args: entity_id: The entity ID to get history for hours: Number of hours of history to retrieve (default: 24)

Returns: A dictionary containing: - entity_id: The entity ID requested - states: List of state objects with timestamps - count: Number of state changes found - first_changed: Timestamp of earliest state change - last_changed: Timestamp of most recent state change

Examples: entity_id="light.living_room" - get 24h history entity_id="sensor.temperature", hours=168 - get 7 day history Best Practices: - Keep hours reasonable (24-72) for token efficiency - Use for entities with discrete state changes rather than continuously changing sensors - Consider the state distribution rather than every individual state

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
entity_idYes
hoursNo

Implementation Reference

  • The handler function that implements the 'get_history' tool logic. It fetches entity history data using get_entity_history helper, processes and formats the state changes, handles errors, and returns a structured dictionary with history information.
    @mcp.tool()
    @async_handler("get_history")
    async def get_history(entity_id: str, hours: int = 24) -> Dict[str, Any]:
        """
        Get the history of an entity's state changes
        
        Args:
            entity_id: The entity ID to get history for
            hours: Number of hours of history to retrieve (default: 24)
        
        Returns:
            A dictionary containing:
            - entity_id: The entity ID requested
            - states: List of state objects with timestamps
            - count: Number of state changes found
            - first_changed: Timestamp of earliest state change
            - last_changed: Timestamp of most recent state change
            
        Examples:
            entity_id="light.living_room" - get 24h history
            entity_id="sensor.temperature", hours=168 - get 7 day history
        Best Practices:
            - Keep hours reasonable (24-72) for token efficiency
            - Use for entities with discrete state changes rather than continuously changing sensors
            - Consider the state distribution rather than every individual state    
        """
        logger.info(f"Getting history for entity: {entity_id}, hours: {hours}")
        
        try:
            # Call the new hass function to get history
            history_data = await get_entity_history(entity_id, hours)
            
            # Check for errors from the API call
            if isinstance(history_data, dict) and "error" in history_data:
                return {
                    "entity_id": entity_id,
                    "error": history_data["error"],
                    "states": [],
                    "count": 0
                }
            
            # The result from the API is a list of lists of state changes
            # We need to flatten it and process it
            states = []
            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."
                }
            
            # Sort states by last_changed timestamp
            states.sort(key=lambda x: x.get("last_changed", ""))
            
            # Extract first and last changed timestamps
            first_changed = states[0].get("last_changed")
            last_changed = states[-1].get("last_changed")
            
            return {
                "entity_id": entity_id,
                "states": states,
                "count": len(states),
                "first_changed": first_changed,
                "last_changed": last_changed
            }
        except Exception as e:
            logger.error(f"Error processing history for {entity_id}: {str(e)}")
            return {
                "entity_id": entity_id,
                "error": f"Error processing history: {str(e)}",
                "states": [],
                "count": 0
            }
Behavior4/5

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

With no annotations provided, the description carries full burden and does well by detailing the return structure (dictionary with specific keys), performance considerations (token efficiency), and practical limitations (preference for discrete state changes). It doesn't cover authentication or rate limits but provides substantial behavioral context beyond basic functionality.

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 clear sections (Args, Returns, Examples, Best Practices) and front-loaded purpose. Every sentence adds value, though it's moderately detailed (not maximally concise). No wasted text, but could be slightly tighter in phrasing.

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 no annotations, no output schema, and 0% schema coverage, the description provides excellent completeness: purpose, parameters, return format, examples, and best practices. It fully compensates for missing structured data, making the tool understandable and actionable for an agent.

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 description coverage is 0%, so the description must compensate fully. It does so by explaining both parameters: entity_id ('The entity ID to get history for') and hours ('Number of hours of history to retrieve'), including default values and examples. This adds complete meaning beyond the bare 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 specific action ('Get the history of an entity's state changes') and resource ('entity'), distinguishing it from siblings like get_entity (current state) or get_error_log (error data). It precisely defines what the tool does beyond just restating the name.

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 'Best Practices' section explicitly provides when-to-use guidance: 'Use for entities with discrete state changes rather than continuously changing sensors' and 'Consider the state distribution rather than every individual state.' It also advises on token efficiency with hour ranges, offering clear context for appropriate usage.

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