homeassistant-mcp

repository·main·Indexed 20 days ago

https://github.com/tevonsb/homeassistant-mcp

A Model Context Protocol (MCP) server that bridges Home Assistant with LLM applications. It enables natural language control, automation management, and real-time state monitoring of smart home devices. Key capabilities include device control for lights and climate, system management for Home Assistant add-ons and HACS packages, and automation configuration. The server provides a REST API, WebSocket and SSE support for real-time updates, and integration with Claude Desktop.

Tokens
23.7K
Snippets
82
Records
99
Agent score
69%

What's inside homeassistant-mcp

  1. Overview of Home Assistant MCP capabilities

    main

    The Home Assistant MCP server acts as a bridge between LLMs and your smart home. It provides capabilities across three main areas:

    • Device Control: Natural language control for lights (brightness, color), climate (temp, HVAC modes), covers, switches, media players, fans, locks, vacuums, and cameras.
    • System Management:
      • Add-on Management: Browse, install, uninstall, and manage Home Assistant add-ons (requires Supervisor access).
      • Package Management (HACS): Manage custom integrations, themes, and scripts via the Home Assistant Community Store.
      • Automation Management: Create, edit, enable/disable, and manually trigger automations.
    • State Monitoring: Real-time tracking of device states and historical data access.
  2. Understand API Rate Limiting

    main

    The API implements rate limiting. General limits are 100 requests per 15-minute window per IP. Model-specific limits apply when using the NLP endpoint:

    • Claude: 100 requests/minute, 1000/hour
    • GPT-4: 50 requests/minute, 500/hour
    • Custom: 200 requests/minute, 2000/hour

    Rate limit information is provided in the response headers:

    • X-RateLimit-Limit: Total limit
    • X-RateLimit-Remaining: Remaining requests
    • X-RateLimit-Reset: Unix timestamp when the limit resets
  3. Add Home Assistant MCP to Claude Desktop

    main

    To use the server with Claude Desktop, add a configuration entry to your Claude Desktop config file. Note that this method runs the MCP server directly via Node.js and is incompatible with the Docker deployment method.

    Replace <path/to/your/dist/folder> with the absolute path to your project's build output.

    {
      "homeassistant": {
        "command": "node",
        "args": ["<path/to/your/dist/folder>"],
        "env": {
          "NODE_ENV": "development",
          "HASS_HOST": "http://homeassistant.local:8123",
          "HASS_TOKEN": "your_home_assistant_token",
          "PORT": "3000",
          "HASS_SOCKET_URL": "ws://homeassistant.local:8123/api/websocket",
          "LOG_LEVEL": "debug"
        }
      }
    }
  4. Subscribe to real-time updates via WebSocket

    main

    The server supports WebSocket connections for real-time event updates.

    Connecting and Subscribing:

    1. Establish a connection to ws://your-server/api/websocket.
    2. To subscribe to all events, send a JSON message with type: "subscribe_events".
    3. To subscribe to a specific event type, send a JSON message with type: "subscribe_events" and event_type: "<event_name>" (e.g., "state_changed").
    const ws = new WebSocket('ws://your-server/api/websocket');
    ws.onmessage = (event) => {
      const data = JSON.parse(event.data);
      console.log('Received:', data);
    };
    
    // Subscribe to specific event type
    ws.send(JSON.stringify({
      type: 'subscribe_events',
      event_type: 'state_changed'
    }));
  5. Install the Home Assistant MCP Server via Basic Setup

    main

    To install the server directly from source, clone the repository, install dependencies using npm, and build the project.

    Prerequisites:

    • Node.js 20.10.0 or higher
    • NPM package manager
    • A running Home Assistant instance with a long-lived access token
    • HACS (for package management features)
    • Supervisor access (for add-on management)
    # Clone the repository
    git clone https://github.com/tevonsb/homeassistant-mcp.git
    cd homeassistant-mcp
    
    # Install dependencies
    npm install
    
    # Build the project
    npm run build
  6. Install the Home Assistant MCP Server via Docker (Recommended)

    main

    The recommended way to deploy the server is using Docker Compose. This ensures a consistent environment and handles container lifecycle management.

    1. Clone the repository and enter the directory.
    2. Create a .env file from the example.
    3. Configure your Home Assistant credentials in the .env file.
    4. Run docker compose up -d to start the service.
    5. Verify the installation by checking http://localhost:3000/health.
    # Clone the repository
    git clone https://github.com/tevonsb/homeassistant-mcp.git
    cd homeassistant-mcp
    
    # Configure environment
    cp .env.example .env
    
    # Build and start the containers
    docker compose up -d
    
    # View logs
    docker compose logs -f
  7. Implement a robust Home Assistant SSE client

    main

    When building a client, follow these best practices to ensure stability:

    1. Reconnection Logic: Implement exponential backoff to handle connection losses.
    2. Resource Management: Always call .close() on the EventSource when the component unmounts or is no longer needed.
    3. Rate Limiting: The server allows a maximum of 1000 requests per minute per client. Exceeding this will trigger an error event.
    4. Connection Limits: The server supports a maximum of 100 concurrent clients. Connections timeout after 5 minutes of inactivity.
    5. Security: Never expose your Home Assistant token in client-side code; use a backend proxy or secure environment variables.
    class HomeAssistantSSE {
      constructor(baseUrl, token) {
        this.baseUrl = baseUrl;
        this.token = token;
        this.eventSource = null;
        this.reconnectAttempts = 0;
        this.maxReconnectAttempts = 5;
        this.reconnectDelay = 1000;
      }
    
      connect(options = {}) {
        const params = new URLSearchParams({
          token: this.token,
          ...(options.events && { events: options.events.join(',') }),
          ...(options.entity_id && { entity_id: options.entity_id }),
          ...(options.domain && { domain: options.domain })
        });
    
        this.eventSource = new EventSource(`${this.baseUrl}/subscribe_events?${params}`);
    
        this.eventSource.onmessage = (event) => {
          const data = JSON.parse(event.data);
          this.handleEvent(data);
        };
    
        this.eventSource.onerror = (error) => {
          console.error('SSE Error:', error);
          this.handleError(error);
        };
      }
    
      handleEvent(data) {
        switch (data.type) {
          case 'connection':
            this.reconnectAttempts = 0;
            console.log('Connected:', data);
            break;
          case 'ping':
            break;
          case 'error':
            console.error('Server Error:', data);
            break;
          default:
            console.log('Event:', data);
        }
      }
    
      handleError(error) {
        this.eventSource?.close();
        
        if (this.reconnectAttempts < this.maxReconnectAttempts) {
          this.reconnectAttempts++;
          const delay = this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1);
          console.log(`Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts})`);
          setTimeout(() => this.connect(), delay);
        } else {
          console.error('Max reconnection attempts reached');
        }
      }
    
      disconnect() {
        this.eventSource?.close();
        this.eventSource = null;
      }
    }
    
    // Usage example
    const client = new HomeAssistantSSE('http://localhost:3000', 'YOUR_HASS_TOKEN');
    client.connect({
      events: ['state_changed', 'automation_triggered'],
      domain: 'light'
    });
  8. Configure Home Assistant MCP Server environment variables

    main

    The server is configured via environment variables. You can define these in a .env file for Docker or directly in your client configuration (e.g., Claude Desktop).

    # Home Assistant Configuration
    HASS_HOST=http://homeassistant.local:8123  # Your Home Assistant instance URL
    HASS_TOKEN=your_home_assistant_token       # Long-lived access token
    HASS_SOCKET_URL=ws://homeassistant.local:8123/api/websocket  # WebSocket URL
    
    # Server Configuration
    PORT=3000                # Server port (default: 3000)
    NODE_ENV=production     # Environment (production/development)
    DEBUG=false             # Enable debug mode
  9. Manage real-time updates with SSEManager

    main

    The SSEManager class is a singleton responsible for managing Server-Sent Events (SSE) connections, client subscriptions, and broadcasting Home Assistant updates (state changes, events, service calls) to connected clients. It handles authentication via a token, rate limiting, and automatic client cleanup for inactive connections.

    To use it, obtain the singleton instance via SSEManager.getInstance() or use the exported sseManager constant.

    import { sseManager } from './sse/index.js';
    
    // Add a new client
    const client = sseManager.addClient({
        id: 'unique-client-id',
        send: (data) => console.log('Received:', data)
    }, 'YOUR_HASS_TOKEN');
    
    if (client) {
        // Subscribe to specific updates
        sseManager.subscribeToEntity(client.id, 'light.living_room');
        sseManager.subscribeToDomain(client.id, 'switch');
        sseManager.subscribeToEvent(client.id, 'state_changed');
    }
  10. Configure Home Assistant MCP Server Environment Variables

    main

    The server uses environment variables to connect to your Home Assistant instance. It loads configuration from files based on NODE_ENV (.env, .env.test, or .env.development).

    Required environment variables:

    • HASS_HOST: The base URL of your Home Assistant instance (defaults to http://192.168.178.63:8123).
    • HASS_TOKEN: Your Home Assistant Long-Lived Access Token.
    • PORT: The port the MCP server will run on (defaults to 3000).
    # Example .env file
    HASS_HOST=http://your-hass-ip:8123
    HASS_TOKEN=your_long_lived_access_token
    PORT=3000
  11. Troubleshoot SSE connection issues

    main

    If you encounter issues with the SSE API, check the following:

    Connection Failures

    • Ensure the token is valid.
    • Verify the server URL is accessible and check SSL/TLS settings if using HTTPS.
    • Check network connectivity.

    Missing Events

    • Verify that your subscription parameters (entity_id, domain, events) are correct.
    • Check if you have hit the rate limit (1000 requests/min).
    • Confirm that the entity or domain actually exists in Home Assistant.

    Debugging Tips

    • Enable detailed logging: Set client.debug = true if using a compatible client implementation.
    • Monitor network traffic: Add listeners for the open and error events on the EventSource object.
    • Check subscription status: Call the /get_sse_stats endpoint to see current active subscriptions.