Skip to main content
Glama

homeassistant_call_service

Execute specific actions on Home Assistant entities by calling services. Define the entity, domain, and service to automate smart home operations efficiently.

Instructions

Call a service of a Home Assistant entity

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
domainYesThe domain of the service
entity_idYesThe entity ID of the Home Assistant entity
serviceYesThe service to call

Implementation Reference

  • Handler function for the 'homeassistant_call_service' tool. It invokes the callHomeAssistantService helper, handles errors, and formats the MCP response.
    async ({ entity_id, domain, service }) => {  
      console.error(`Verificando Home Assistant`);
      
      const result = await callHomeAssistantService(entity_id, domain, service);
      
      if (!result.success) {
        return formatErrorResponse(`Failed to call service: ${result.message}`);
      }
      
      // Formata os dados da resposta
      const response = result.data;
      
      if (!response.results || response.results === 0) {
        return {
          content: [{ 
            type: "text",
             text: response == "" ? "Call service successfully" : `Name: ${response[0].attributes.friendly_name || "Unknown"}\nEntity: ${entity_id}\nState: ${response[0].state || "Unknown"}\nLast Changed: ${response[0].last_changed || "Unknown"}\n\nAttributes: ${JSON.stringify(response[0].attributes)}`
          }]
        };
      }
      
      const responseMessage = response.message;
      
      return {
        content: [{ 
          type: "text" as const, 
          text: responseMessage
        }]
      };
    }
  • Input schema for the tool using Zod, defining entity_id, domain, and service parameters.
      entity_id: z.string().describe("The entity ID of the Home Assistant entity"),
      domain: z.string().describe("The domain of the service"),
      service: z.string().describe("The service to call")
    },
  • Registration of the 'homeassistant_call_service' tool on the MCP server.
    server.tool(
      "homeassistant_call_service",  
      "Call a service of a Home Assistant entity",
      {
        entity_id: z.string().describe("The entity ID of the Home Assistant entity"),
        domain: z.string().describe("The domain of the service"),
        service: z.string().describe("The service to call")
      },
      async ({ entity_id, domain, service }) => {  
        console.error(`Verificando Home Assistant`);
        
        const result = await callHomeAssistantService(entity_id, domain, service);
        
        if (!result.success) {
          return formatErrorResponse(`Failed to call service: ${result.message}`);
        }
        
        // Formata os dados da resposta
        const response = result.data;
        
        if (!response.results || response.results === 0) {
          return {
            content: [{ 
              type: "text",
               text: response == "" ? "Call service successfully" : `Name: ${response[0].attributes.friendly_name || "Unknown"}\nEntity: ${entity_id}\nState: ${response[0].state || "Unknown"}\nLast Changed: ${response[0].last_changed || "Unknown"}\n\nAttributes: ${JSON.stringify(response[0].attributes)}`
            }]
          };
        }
        
        const responseMessage = response.message;
        
        return {
          content: [{ 
            type: "text" as const, 
            text: responseMessage
          }]
        };
      }
    );
  • Supporting utility function that makes the POST request to Home Assistant API to call the specified service on the entity.
    async function callHomeAssistantService(entity_id: string, domain: string, service: string) {
      try {
        const url = `${process.env.HOME_ASSISTANT_URL}/api/services/${domain}/${service}`;
        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.post(url, 
          {
            entity_id: entity_id
          }, 
          {
            headers: {
              'Authorization': `Bearer ${bearerToken}`
            }
          }
        );
        
        return { 
          data: response.data,
          success: true
        };
      } catch (error: any) {
        console.error(`Failed to call service: ${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/index.ts:23-23 (registration)
    Top-level call to register Home Assistant tools, including 'homeassistant_call_service', on the MCP server.
    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