Skip to main content
Glama

get_entity

Retrieve the current state and attributes of any Home Assistant smart home device, with options to filter specific fields or get complete details.

Instructions

Get the state of a Home Assistant entity with optional field filtering

Args: entity_id: The entity ID to get (e.g. 'light.living_room') fields: Optional list of fields to include (e.g. ['state', 'attr.brightness']) detailed: If True, returns all entity fields without filtering

Examples: entity_id="light.living_room" - basic state check entity_id="light.living_room", fields=["state", "attr.brightness"] - specific fields entity_id="light.living_room", detailed=True - all details

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
entity_idYes
fieldsNo
detailedNo

Implementation Reference

  • The MCP tool handler for 'get_entity'. Registered via @mcp.tool() decorator. Handles input parameters (entity_id, fields, detailed) and delegates to get_entity_state helper based on flags for field filtering or detailed/lean responses.
    @mcp.tool()
    @async_handler("get_entity")
    async def get_entity(entity_id: str, fields: Optional[List[str]] = None, detailed: bool = False) -> dict:
        """
        Get the state of a Home Assistant entity with optional field filtering
        
        Args:
            entity_id: The entity ID to get (e.g. 'light.living_room')
            fields: Optional list of fields to include (e.g. ['state', 'attr.brightness'])
            detailed: If True, returns all entity fields without filtering
                    
        Examples:
            entity_id="light.living_room" - basic state check
            entity_id="light.living_room", fields=["state", "attr.brightness"] - specific fields
            entity_id="light.living_room", detailed=True - all details
        """
        logger.info(f"Getting entity state: {entity_id}")
        if detailed:
            # Return all fields
            return await get_entity_state(entity_id, lean=False)
        elif fields:
            # Return only the specified fields
            return await get_entity_state(entity_id, fields=fields)
        else:
            # Return lean format with essential fields
            return await get_entity_state(entity_id, lean=True)
  • Core helper function implementing entity state retrieval from Home Assistant API (/api/states/{entity_id}). Supports custom fields filtering and automatic lean mode with domain-specific important attributes for token efficiency.
    async def get_entity_state(
        entity_id: str,
        fields: Optional[List[str]] = None,
        lean: bool = False
    ) -> Dict[str, Any]:
        """
        Get the state of a Home Assistant entity
        
        Args:
            entity_id: The entity ID to get
            fields: Optional list of specific fields to include in the response
            lean: If True, returns a token-efficient version with minimal fields
                  (overridden by fields parameter if provided)
        
        Returns:
            Entity state dictionary, optionally filtered to include only specified fields
        """
        # Fetch directly
        client = await get_client()
        response = await client.get(
            f"{HA_URL}/api/states/{entity_id}", 
            headers=get_ha_headers()
        )
        response.raise_for_status()
        entity_data = response.json()
        
        # Apply field filtering if requested
        if fields:
            # User-specified fields take precedence
            return filter_fields(entity_data, fields)
        elif lean:
            # Build domain-specific lean fields
            lean_fields = DEFAULT_LEAN_FIELDS.copy()
            
            # Add domain-specific important attributes
            domain = entity_id.split('.')[0]
            if domain in DOMAIN_IMPORTANT_ATTRIBUTES:
                for attr in DOMAIN_IMPORTANT_ATTRIBUTES[domain]:
                    lean_fields.append(f"attr.{attr}")
            
            return filter_fields(entity_data, lean_fields)
        else:
            # Return full entity data
            return entity_data
  • Supporting utility function used by get_entity_state to filter entity data dictionary to only the requested fields or lean set, reducing response size.
    def filter_fields(data: Dict[str, Any], fields: List[str]) -> Dict[str, Any]:
        """
        Filter entity data to only include requested fields
        
        This function helps reduce token usage by returning only requested fields.
        
        Args:
            data: The complete entity data dictionary
            fields: List of fields to include in the result
                   - "state": Include the entity state
                   - "attributes": Include all attributes
                   - "attr.X": Include only attribute X (e.g. "attr.brightness")
                   - "context": Include context data
                   - "last_updated"/"last_changed": Include timestamp fields
        
        Returns:
            A filtered dictionary with only the requested fields
        """
        if not fields:
            return data
            
        result = {"entity_id": data["entity_id"]}
        
        for field in fields:
            if field == "state":
                result["state"] = data.get("state")
            elif field == "attributes":
                result["attributes"] = data.get("attributes", {})
            elif field.startswith("attr.") and len(field) > 5:
                attr_name = field[5:]
                attributes = data.get("attributes", {})
                if attr_name in attributes:
                    if "attributes" not in result:
                        result["attributes"] = {}
                    result["attributes"][attr_name] = attributes[attr_name]
            elif field == "context":
                if "context" in data:
                    result["context"] = data["context"]
            elif field in ["last_updated", "last_changed"]:
                if field in data:
                    result[field] = data[field]
        
        return result
Behavior3/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It describes what the tool does (gets entity state with filtering options) and provides examples, but doesn't mention important behavioral aspects like error handling, authentication requirements, rate limits, or what happens when an entity doesn't exist. The description doesn't contradict annotations (none exist), but leaves significant behavioral gaps.

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?

The description is well-structured and appropriately sized. It begins with a clear purpose statement, then provides parameter documentation in an 'Args' section, followed by practical examples. Every sentence serves a purpose - no wasted words. The information is front-loaded with the most important details first.

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

Completeness3/5

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

For a 3-parameter tool with no annotations and no output schema, the description provides adequate basic information but has gaps. It covers the purpose and parameters well, but doesn't describe the return format, error conditions, or how this tool relates to sibling tools. Given the complexity of entity state retrieval and the lack of structured metadata, more behavioral context would be helpful.

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

Parameters4/5

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

With 0% schema description coverage, the description must compensate for the schema's lack of parameter documentation. The description provides clear parameter semantics in the 'Args' section and examples: entity_id format examples, fields parameter purpose and examples, and detailed parameter behavior. This adds substantial value beyond the bare schema, though it could provide more detail on field syntax constraints.

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

Purpose4/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 the state of a Home Assistant entity with optional field filtering'. It specifies the verb ('Get'), resource ('Home Assistant entity'), and scope ('with optional field filtering'). However, it doesn't explicitly differentiate from siblings like 'list_entities' or 'search_entities_tool' which might provide different entity-related functionality.

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 through examples showing different scenarios (basic state check, specific fields, all details), but doesn't explicitly state when to use this tool versus alternatives like 'list_entities' or 'search_entities_tool'. The examples provide context but no explicit guidance on tool selection criteria.

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