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
| Name | Required | Description | Default |
|---|---|---|---|
| entity_id | Yes | The entity ID of the Home Assistant entity |
Implementation Reference
- src/tools/homeassistant/index.ts:47-82 (registration)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 }] }; }
- src/utils/api.ts:75-117 (helper)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 }; } }
- src/utils/api.ts:12-20 (helper)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);