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

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