Skip to main content
Glama

homeassistant_get_state

Retrieve the current state of a Home Assistant entity by specifying its entity ID, enabling AI assistants to monitor smart home device statuses.

Instructions

Get the state of a Home Assistant entity

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
entity_idYesThe entity ID of the Home Assistant entity

Implementation Reference

  • Registration of the 'homeassistant_get_state' tool with the MCP server, including input schema (entity_id), description, and inline handler function that fetches and formats the entity state.
    server.tool(
      "homeassistant_get_state",  
      "Get the state of a Home Assistant entity",
      {
        entity_id: z.string().describe("The entity ID of the Home Assistant entity")
      },
      async ({ entity_id }) => {  
        console.error(`Verificando Home Assistant`);
        
        const result = await getHomeAssistantState(entity_id);
        
        if (!result.success) {
          return formatErrorResponse(`Erro ao pesquisar time: ${result.message}`);
        }
        
        // Formata os dados da resposta
        const response = result.data;
        
        if (!response.results || response.results === 0) {
          return {
            content: [{ 
              type: "text",
              text: `Name: ${response.attributes.friendly_name || "Unknown"}\nEntity: ${entity_id}\nState: ${response.state || "Unknown"}\nLast Changed: ${response.last_changed || "Unknown"}\n\nAttributes: ${JSON.stringify(response.attributes)}`
            }]
          };
        }
        
        const responseMessage = response.message;
        
        return {
          content: [{ 
            type: "text" as const, 
            text: responseMessage
          }]
        };
      }
  • The core helper function implementing the API call to retrieve the state of a specific Home Assistant entity using axios and Bearer token authentication.
    async function getHomeAssistantState(entity_id: string) {
      try {
        const url = `${process.env.HOME_ASSISTANT_URL}/api/states/${entity_id}`;
        console.error(`Making request to: ${url}`);
        
        // O API key deve ser configurado como variável de ambiente
        const bearerToken = process.env.HOME_ASSISTANT_TOKEN;
    
        if (!bearerToken) {
          console.error('HOME_ASSISTANT_TOKEN environment variable is not set')
          process.exit(1)
        }    
        
        const response = await axios.get(url, { 
          headers: {
            'Authorization': `Bearer ${bearerToken}`
          }
        });
        
        return { 
          data: response.data,
          success: true
        };
      } catch (error: any) {
        console.error(`Failed to get Home Assistant State: ${error.message}`);
        
        // Tratamento de erros da API de forma estruturada
        if (error.response) {
          return {
            success: false,
            statusCode: error.response.status,
            message: error.response.data?.message || error.message,
            error: error.response.data
          };
        }
        
        return {
          success: false,
          message: error.message,
          error
        };
      }
    } 
  • Utility function to format error responses in the standard MCP content format.
    export function formatErrorResponse(message: string) {
        return {
          content: [{ 
            type: "text" as const, 
            text: message 
          }],
          isError: true
        };
      }
  • src/index.ts:23-23 (registration)
    High-level registration call that invokes the Home Assistant tools registration, including homeassistant_get_state.
    registerHomeAssistantApiTools(server);
Install Server

Other Tools

Related 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/guilhermelirio/homeassistant-mpc'

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