MCP HubMCP Hub
tevonsb

homeassistant-mcp

by: tevonsb

A MCP server for Home Assistant

212created 12/12/2024
Visit
HomeAssistant

๐Ÿ“ŒOverview

Purpose: The Model Context Protocol Server aims to facilitate seamless interaction between a Home Assistant instance and Language Learning Models (LLMs) through natural language control and comprehensive device management.

Overview: This server acts as a robust bridge, utilizing the Model Context Protocol (MCP) to provide an API for controlling and monitoring smart home devices. It enhances user experience by allowing real-time updates and sophisticated automation management from any HTTP-capable client.

Key Features:

  • Device Control: enables natural language commands for controlling various Home Assistant devices like lights, climate systems, and media players, making smart home management intuitive.

  • Real-time Updates: powered by Server-Sent Events (SSE), this feature delivers instant notifications for device state changes, automation triggers, and service executions, ensuring users are always informed.

  • Automation Management: provides tools to create, modify, and manage complex automations, allowing users to tailor their smart home experience according to personal preferences and routines.

  • Secure Access: features token-based authentication and rate limiting to protect user data and prevent abuse of the API.

  • Mobile Compatibility: optimized for any HTTP-capable client, facilitating accessibility and usability across devices.


Model Context Protocol Server for Home Assistant

The server uses the MCP protocol to share access to a local Home Assistant instance with an LLM application.

A powerful bridge between your Home Assistant instance and Language Learning Models (LLMs), enabling natural language control and monitoring of your smart home devices through the Model Context Protocol (MCP). This server provides a comprehensive API for managing your entire Home Assistant ecosystem, from device control to system administration.

Features

  • ๐ŸŽฎ Device Control: Control any Home Assistant device through natural language
  • ๐Ÿ”„ Real-time Updates: Get instant updates through Server-Sent Events (SSE)
  • ๐Ÿค– Automation Management: Create, update, and manage automations
  • ๐Ÿ“Š State Monitoring: Track and query device states
  • ๐Ÿ” Secure: Token-based authentication and rate limiting
  • ๐Ÿ“ฑ Mobile Ready: Works with any HTTP-capable client

Real-time Updates with SSE

The server includes a powerful Server-Sent Events (SSE) system that provides real-time updates from your Home Assistant instance. This allows you to:

  • ๐Ÿ”„ Get instant state changes for any device
  • ๐Ÿ“ก Monitor automation triggers and executions
  • ๐ŸŽฏ Subscribe to specific domains or entities
  • ๐Ÿ“Š Track service calls and script executions

Quick SSE Example

const eventSource = new EventSource(
  'http://localhost:3000/subscribe_events?token=YOUR_TOKEN&domain=light'
);

eventSource.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log('Update received:', data);
};

See SSE_API.md for complete documentation of the SSE system.

Table of Contents

  • Key Features
  • Prerequisites
  • Installation
    • Basic Setup
    • Docker Setup (Recommended)
  • Configuration
  • Development
  • API Reference
    • Device Control
    • Add-on Management
    • Package Management
    • Automation Management
  • Natural Language Integration
  • Troubleshooting
  • Project Status
  • Contributing
  • Resources
  • License

Key Features

Core Functionality ๐ŸŽฎ

  • Smart Device Control
    • ๐Ÿ’ก Lights: Brightness, color temperature, RGB color
    • ๐ŸŒก๏ธ Climate: Temperature, HVAC modes, fan modes, humidity
    • ๐Ÿšช Covers: Position and tilt control
    • ๐Ÿ”Œ Switches: On/off control
    • ๐Ÿšจ Sensors & Contacts: State monitoring
    • ๐ŸŽต Media Players: Playback control, volume, source selection
    • ๐ŸŒช๏ธ Fans: Speed, oscillation, direction
    • ๐Ÿ”’ Locks: Lock/unlock control
    • ๐Ÿงน Vacuums: Start, stop, return to base
    • ๐Ÿ“น Cameras: Motion detection, snapshots

System Management ๐Ÿ› ๏ธ

  • Add-on Management

    • Browse available add-ons
    • Install/uninstall add-ons
    • Start/stop/restart add-ons
    • Version management
    • Configuration access
  • Package Management (HACS)

    • Integration with Home Assistant Community Store
    • Multiple package types support: custom integrations, frontend themes, Python scripts, AppDaemon apps, NetDaemon apps
    • Version control and updates
    • Repository management
  • Automation Management

    • Create and edit automations
    • Advanced configuration options: multiple trigger types, complex conditions, action sequences, execution modes
    • Duplicate and modify existing automations
    • Enable/disable automation rules
    • Trigger automation manually

Architecture Features ๐Ÿ—๏ธ

  • Intelligent Organization

    • Area and floor-based device grouping
    • State monitoring and querying
    • Smart context awareness
    • Historical data access
  • Robust Architecture

    • Comprehensive error handling
    • State validation
    • Secure API integration
    • TypeScript type safety
    • Extensive test coverage

Prerequisites

  • Node.js 20.10.0 or higher
  • NPM package manager
  • Docker Compose for containerization
  • Running Home Assistant instance
  • Home Assistant long-lived access token (see official Home Assistant community for how to get token)
  • HACS installed for package management features
  • Supervisor access for add-on management

Installation

Basic Setup

# Clone the repository
git clone https://github.com/jango-blockchained/homeassistant-mcp.git
cd homeassistant-mcp

# Install dependencies
npm install

# Build the project
npm run build

Docker Setup (Recommended)

The project includes Docker support for easy deployment and consistent environments across different platforms.

  1. Clone the repository:

    git clone https://github.com/jango-blockchained/homeassistant-mcp.git
    cd homeassistant-mcp
    
  2. Configure environment:

    cp .env.example .env
    

    Edit the .env file with your Home Assistant configuration:

    # Home Assistant Configuration
    HASS_HOST=http://homeassistant.local:8123
    HASS_TOKEN=your_home_assistant_token
    HASS_SOCKET_URL=ws://homeassistant.local:8123/api/websocket
    
    # Server Configuration
    PORT=3000
    NODE_ENV=production
    DEBUG=false
    
  3. Build and run with Docker Compose:

    docker compose up -d
    docker compose logs -f
    docker compose down
    
  4. Verify the installation: The server should be running at http://localhost:3000. Check the health endpoint at http://localhost:3000/health.

  5. Update the application:

    git pull
    docker compose up -d --build
    

Docker Configuration

  • Multi-stage build for optimal image size
  • Health checks for container monitoring
  • Volume mounting for environment configuration
  • Automatic container restart on failure
  • Exposed port 3000 for API access

Docker Compose Environment Variables

Configured via the .env file. Supported variables:

  • HASS_HOST: Home Assistant instance URL
  • HASS_TOKEN: Long-lived access token
  • HASS_SOCKET_URL: WebSocket URL for Home Assistant
  • PORT: Server port (default 3000)
  • NODE_ENV: Environment (production/development)
  • DEBUG: Enable debug mode (true/false)

Configuration

Environment Variables

# Home Assistant Configuration
HASS_HOST=http://homeassistant.local:8123
HASS_TOKEN=your_home_assistant_token
HASS_SOCKET_URL=ws://homeassistant.local:8123/api/websocket

# Server Configuration
PORT=3000
NODE_ENV=production
DEBUG=false

# Test Configuration
TEST_HASS_HOST=http://localhost:8123
TEST_HASS_TOKEN=test_token

Configuration Files

  • Development: Copy .env.example to .env.development
  • Production: Copy .env.example to .env.production
  • Testing: Copy .env.example to .env.test

Adding to Claude Desktop (or other clients)

To use the Home Assistant MCP server within Claude Desktop, add the following configuration:

{
  "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"
    }
  }
}

Note: This method runs MCP within Claude and does not work with the Docker method.

API Reference

Device Control

Common Entity Controls

{
  "tool": "control",
  "command": "turn_on", // or "turn_off", "toggle"
  "entity_id": "light.living_room"
}

Light Control

{
  "tool": "control",
  "command": "turn_on",
  "entity_id": "light.living_room",
  "brightness": 128,
  "color_temp": 4000,
  "rgb_color": [255, 0, 0]
}

Add-on Management

  • List available add-ons
{
  "tool": "addon",
  "action": "list"
}
  • Install add-on
{
  "tool": "addon",
  "action": "install",
  "slug": "core_configurator",
  "version": "5.6.0"
}
  • Manage add-on state
{
  "tool": "addon",
  "action": "start", // or "stop", "restart"
  "slug": "core_configurator"
}

Package Management

  • List HACS packages
{
  "tool": "package",
  "action": "list",
  "category": "integration" // or "plugin", "theme", "python_script", "appdaemon", "netdaemon"
}
  • Install package
{
  "tool": "package",
  "action": "install",
  "category": "integration",
  "repository": "hacs/integration",
  "version": "1.32.0"
}

Automation Management

  • Create automation
{
  "tool": "automation_config",
  "action": "create",
  "config": {
    "alias": "Motion Light",
    "description": "Turn on light when motion detected",
    "mode": "single",
    "trigger": [
      {
        "platform": "state",
        "entity_id": "binary_sensor.motion",
        "to": "on"
      }
    ],
    "action": [
      {
        "service": "light.turn_on",
        "target": {
          "entity_id": "light.living_room"
        }
      }
    ]
  }
}
  • Duplicate automation
{
  "tool": "automation_config",
  "action": "duplicate",
  "automation_id": "automation.motion_light"
}

Core Functions

State Management

GET /api/state
POST /api/state

Manages the current state of the system.

Example:

POST /api/state
{
  "context": "living_room",
  "state": {
    "lights": "on",
    "temperature": 22
  }
}

Context Updates

POST /api/context

Updates the current context with new information.

Example:

POST /api/context
{
  "user": "john",
  "location": "kitchen",
  "time": "morning",
  "activity": "cooking"
}

Action Endpoints

  • Execute Action
POST /api/action

Example:

POST /api/action
{
  "action": "turn_on_lights",
  "parameters": {
    "room": "living_room",
    "brightness": 80
  }
}
  • Batch Actions
POST /api/actions/batch

Example:

POST /api/actions/batch
{
  "actions": [
    {
      "action": "turn_on_lights",
      "parameters": {
        "room": "living_room"
      }
    },
    {
      "action": "set_temperature",
      "parameters": {
        "temperature": 22
      }
    }
  ]
}

Query Functions

  • Get Available Actions
GET /api/actions

Returns all available actions:

{
  "actions": [
    {
      "name": "turn_on_lights",
      "parameters": ["room", "brightness"],
      "description": "Turns on lights in specified room"
    },
    {
      "name": "set_temperature",
      "parameters": ["temperature"],
      "description": "Sets temperature in current context"
    }
  ]
}
  • Context Query
GET /api/context?type=current

Example response:

{
  "current_context": {
    "user": "john",
    "location": "kitchen",
    "time": "morning",
    "activity": "cooking"
  }
}

WebSocket Events

Supports real-time updates via WebSocket connections.

const ws = new WebSocket('ws://localhost:3000/ws');

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log('Received update:', data);
};

Supported events:

  • state_change
  • context_update
  • action_executed
  • error

Example event data:

{
  "event": "state_change",
  "data": {
    "previous_state": { "lights": "off" },
    "current_state": { "lights": "on" },
    "timestamp": "2024-03-20T10:30:00Z"
  }
}

Error Handling

Standard HTTP status codes are used:

  • 200: Success
  • 400: Bad Request
  • 401: Unauthorized
  • 403: Forbidden
  • 404: Not Found
  • 500: Internal Server Error

Error response example:

{
  "error": {
    "code": "INVALID_PARAMETERS",
    "message": "Missing required parameter: room",
    "details": { "missing_fields": ["room"] }
  }
}

Rate Limiting

Limits:

  • 100 requests per minute per IP for regular endpoints
  • 1000 requests per minute per IP for WebSocket connections

Rate limit exceeded response:

{
  "error": {
    "code": "RATE_LIMIT_EXCEEDED",
    "message": "Too many requests",
    "reset_time": "2024-03-20T10:31:00Z"
  }
}

Example Usage

Using curl

# Get current state
curl -X GET \
  http://localhost:3000/api/state \
  -H 'Authorization: ApiKey your_api_key_here'

# Execute action
curl -X POST \
  http://localhost:3000/api/action \
  -H 'Authorization: ApiKey your_api_key_here' \
  -H 'Content-Type: application/json' \
  -d '{
    "action": "turn_on_lights",
    "parameters": {
      "room": "living_room",
      "brightness": 80
    }
  }'

Using JavaScript

async function executeAction() {
  const response = await fetch('http://localhost:3000/api/action', {
    method: 'POST',
    headers: {
      'Authorization': 'ApiKey your_api_key_here',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      action: 'turn_on_lights',
      parameters: { room: 'living_room', brightness: 80 }
    })
  });
  const data = await response.json();
  console.log('Action result:', data);
}

Development

# Development mode with hot reload
npm run dev

# Build project
npm run build

# Production mode
npm run start

# Run tests
npx jest --config=jest.config.cjs

# Run tests with coverage
npx jest --coverage

# Lint code
npm run lint

# Format code
npm run format

Troubleshooting

Common Issues

  1. Node.js Version (toSorted is not a function)
    Update to Node.js 20.10.0+

    nvm install 20.10.0
    nvm use 20.10.0
    
  2. Connection Issues

    • Verify Home Assistant is running
    • Check HASS_HOST accessibility
    • Validate token permissions
    • Ensure WebSocket connection for real-time updates
  3. Add-on Management Issues

    • Verify Supervisor access
    • Check add-on compatibility
    • Validate system resources
  4. HACS Integration Issues

    • Verify HACS installation
    • Check HACS integration status
    • Validate repository access
  5. Automation Issues

    • Verify entity availability
    • Check trigger conditions
    • Validate service calls
    • Monitor execution logs

Project Status

โœ… Complete

  • Entity, Floor, and Area access
  • Device control (Lights, Climate, Covers, Switches, Contacts)
  • Add-on management system
  • Package management through HACS
  • Advanced automation configuration
  • Basic state management
  • Error handling and validation
  • Docker containerization
  • Jest testing setup
  • TypeScript integration
  • Environment variable management
  • Home Assistant API integration
  • Project documentation

๐Ÿšง In Progress

  • WebSocket implementation for real-time updates
  • Enhanced security features
  • Tool organization optimization
  • Performance optimization
  • Resource context integration
  • API documentation generation
  • Multi-platform desktop integration
  • Advanced error recovery
  • Custom prompt testing
  • Enhanced macOS integration
  • Type safety improvements
  • Testing coverage expansion

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Implement your changes
  4. Add tests for new functionality
  5. Ensure all tests pass
  6. Submit a pull request

Resources

License

MIT License - See LICENSE file