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
Add this skill
npx mdskills install tevonsb/homeassistant-mcpComprehensive Home Assistant MCP server with extensive device control, automation, and real-time event streaming
1# Model Context Protocol Server for Home Assistant23The server uses the MCP protocol to share access to a local Home Assistant instance with an LLM application.45A 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.67891011121314## Features1516- ๐ฎ **Device Control**: Control any Home Assistant device through natural language17- ๐ **Real-time Updates**: Get instant updates through Server-Sent Events (SSE)18- ๐ค **Automation Management**: Create, update, and manage automations19- ๐ **State Monitoring**: Track and query device states20- ๐ **Secure**: Token-based authentication and rate limiting21- ๐ฑ **Mobile Ready**: Works with any HTTP-capable client2223## Real-time Updates with SSE2425The server includes a powerful Server-Sent Events (SSE) system that provides real-time updates from your Home Assistant instance. This allows you to:2627- ๐ Get instant state changes for any device28- ๐ก Monitor automation triggers and executions29- ๐ฏ Subscribe to specific domains or entities30- ๐ Track service calls and script executions3132### Quick SSE Example3334```javascript35const eventSource = new EventSource(36 'http://localhost:3000/subscribe_events?token=YOUR_TOKEN&domain=light'37);3839eventSource.onmessage = (event) => {40 const data = JSON.parse(event.data);41 console.log('Update received:', data);42};43```4445See [SSE_API.md](docs/SSE_API.md) for complete documentation of the SSE system.4647## Table of Contents4849- [Key Features](#key-features)50- [Prerequisites](#prerequisites)51- [Installation](#installation)52 - [Basic Setup](#basic-setup)53 - [Docker Setup (Recommended)](#docker-setup-recommended)54- [Configuration](#configuration)55- [Development](#development)56- [API Reference](#api-reference)57 - [Device Control](#device-control)58 - [Add-on Management](#add-on-management)59 - [Package Management](#package-management)60 - [Automation Management](#automation-management)61- [Natural Language Integration](#natural-language-integration)62- [Troubleshooting](#troubleshooting)63- [Project Status](#project-status)64- [Contributing](#contributing)65- [Resources](#resources)66- [License](#license)6768## Key Features6970### Core Functionality ๐ฎ71- **Smart Device Control**72 - ๐ก **Lights**: Brightness, color temperature, RGB color73 - ๐ก๏ธ **Climate**: Temperature, HVAC modes, fan modes, humidity74 - ๐ช **Covers**: Position and tilt control75 - ๐ **Switches**: On/off control76 - ๐จ **Sensors & Contacts**: State monitoring77 - ๐ต **Media Players**: Playback control, volume, source selection78 - ๐ช๏ธ **Fans**: Speed, oscillation, direction79 - ๐ **Locks**: Lock/unlock control80 - ๐งน **Vacuums**: Start, stop, return to base81 - ๐น **Cameras**: Motion detection, snapshots8283### System Management ๐ ๏ธ84- **Add-on Management**85 - Browse available add-ons86 - Install/uninstall add-ons87 - Start/stop/restart add-ons88 - Version management89 - Configuration access9091- **Package Management (HACS)**92 - Integration with Home Assistant Community Store93 - Multiple package types support:94 - Custom integrations95 - Frontend themes96 - Python scripts97 - AppDaemon apps98 - NetDaemon apps99 - Version control and updates100 - Repository management101102- **Automation Management**103 - Create and edit automations104 - Advanced configuration options:105 - Multiple trigger types106 - Complex conditions107 - Action sequences108 - Execution modes109 - Duplicate and modify existing automations110 - Enable/disable automation rules111 - Trigger automation manually112113### Architecture Features ๐๏ธ114- **Intelligent Organization**115 - Area and floor-based device grouping116 - State monitoring and querying117 - Smart context awareness118 - Historical data access119120- **Robust Architecture**121 - Comprehensive error handling122 - State validation123 - Secure API integration124 - TypeScript type safety125 - Extensive test coverage126127## Prerequisites128129- **Node.js** 20.10.0 or higher130- **NPM** package manager131- **Docker Compose** for containerization132- Running **Home Assistant** instance133- Home Assistant long-lived access token ([How to get token](https://community.home-assistant.io/t/how-to-get-long-lived-access-token/162159))134- **HACS** installed for package management features135- **Supervisor** access for add-on management136137## Installation138139### Basic Setup140141```bash142# Clone the repository143git clone https://github.com/tevonsb/homeassistant-mcp.git144cd homeassistant-mcp145146# Install dependencies147npm install148149# Build the project150npm run build151```152153### Docker Setup (Recommended)154155The project includes Docker support for easy deployment and consistent environments across different platforms.1561571. **Clone the repository:**158 ```bash159 git clone https://github.com/tevonsb/homeassistant-mcp.git160 cd homeassistant-mcp161 ```1621632. **Configure environment:**164 ```bash165 cp .env.example .env166 ```167 Edit the `.env` file with your Home Assistant configuration:168 ```env169 # Home Assistant Configuration170 HASS_HOST=http://homeassistant.local:8123171 HASS_TOKEN=your_home_assistant_token172 HASS_SOCKET_URL=ws://homeassistant.local:8123/api/websocket173174 # Server Configuration175 PORT=3000176 NODE_ENV=production177 DEBUG=false178 ```1791803. **Build and run with Docker Compose:**181 ```bash182 # Build and start the containers183 docker compose up -d184185 # View logs186 docker compose logs -f187188 # Stop the service189 docker compose down190 ```1911924. **Verify the installation:**193 The server should now be running at `http://localhost:3000`. You can check the health endpoint at `http://localhost:3000/health`.1941955. **Update the application:**196 ```bash197 # Pull the latest changes198 git pull199200 # Rebuild and restart the containers201 docker compose up -d --build202 ```203204#### Docker Configuration205206The Docker setup includes:207- Multi-stage build for optimal image size208- Health checks for container monitoring209- Volume mounting for environment configuration210- Automatic container restart on failure211- Exposed port 3000 for API access212213#### Docker Compose Environment Variables214215All environment variables can be configured in the `.env` file. The following variables are supported:216- `HASS_HOST`: Your Home Assistant instance URL217- `HASS_TOKEN`: Long-lived access token for Home Assistant218- `HASS_SOCKET_URL`: WebSocket URL for Home Assistant219- `PORT`: Server port (default: 3000)220- `NODE_ENV`: Environment (production/development)221- `DEBUG`: Enable debug mode (true/false)222223## Configuration224225### Environment Variables226227```env228# Home Assistant Configuration229HASS_HOST=http://homeassistant.local:8123 # Your Home Assistant instance URL230HASS_TOKEN=your_home_assistant_token # Long-lived access token231HASS_SOCKET_URL=ws://homeassistant.local:8123/api/websocket # WebSocket URL232233# Server Configuration234PORT=3000 # Server port (default: 3000)235NODE_ENV=production # Environment (production/development)236DEBUG=false # Enable debug mode237238# Test Configuration239TEST_HASS_HOST=http://localhost:8123 # Test instance URL240TEST_HASS_TOKEN=test_token # Test token241```242243### Configuration Files2442451. **Development**: Copy `.env.example` to `.env.development`2462. **Production**: Copy `.env.example` to `.env.production`2473. **Testing**: Copy `.env.example` to `.env.test`248249### Adding to Claude Desktop (or other clients)250251To use your new Home Assistant MCP server, you can add Claude Desktop as a client. Add the following to the configuration. Note this will run the MCP within claude and does not work with the Docker method.252253```254{255 "homeassistant": {256 "command": "node",257 "args": [<path/to/your/dist/folder>]258 "env": {259 NODE_ENV=development260 HASS_HOST=http://homeassistant.local:8123261 HASS_TOKEN=your_home_assistant_token262 PORT=3000263 HASS_SOCKET_URL=ws://homeassistant.local:8123/api/websocket264 LOG_LEVEL=debug265 }266 }267}268269```270271272273## API Reference274275### Device Control276277#### Common Entity Controls278```json279{280 "tool": "control",281 "command": "turn_on", // or "turn_off", "toggle"282 "entity_id": "light.living_room"283}284```285286#### Light Control287```json288{289 "tool": "control",290 "command": "turn_on",291 "entity_id": "light.living_room",292 "brightness": 128,293 "color_temp": 4000,294 "rgb_color": [255, 0, 0]295}296```297298### Add-on Management299300#### List Available Add-ons301```json302{303 "tool": "addon",304 "action": "list"305}306```307308#### Install Add-on309```json310{311 "tool": "addon",312 "action": "install",313 "slug": "core_configurator",314 "version": "5.6.0"315}316```317318#### Manage Add-on State319```json320{321 "tool": "addon",322 "action": "start", // or "stop", "restart"323 "slug": "core_configurator"324}325```326327### Package Management328329#### List HACS Packages330```json331{332 "tool": "package",333 "action": "list",334 "category": "integration" // or "plugin", "theme", "python_script", "appdaemon", "netdaemon"335}336```337338#### Install Package339```json340{341 "tool": "package",342 "action": "install",343 "category": "integration",344 "repository": "hacs/integration",345 "version": "1.32.0"346}347```348349### Automation Management350351#### Create Automation352```json353{354 "tool": "automation_config",355 "action": "create",356 "config": {357 "alias": "Motion Light",358 "description": "Turn on light when motion detected",359 "mode": "single",360 "trigger": [361 {362 "platform": "state",363 "entity_id": "binary_sensor.motion",364 "to": "on"365 }366 ],367 "action": [368 {369 "service": "light.turn_on",370 "target": {371 "entity_id": "light.living_room"372 }373 }374 ]375 }376}377```378379#### Duplicate Automation380```json381{382 "tool": "automation_config",383 "action": "duplicate",384 "automation_id": "automation.motion_light"385}386```387388### Core Functions389390#### State Management391```http392GET /api/state393POST /api/state394```395396Manages the current state of the system.397398**Example Request:**399```json400POST /api/state401{402 "context": "living_room",403 "state": {404 "lights": "on",405 "temperature": 22406 }407}408```409410#### Context Updates411```http412POST /api/context413```414415Updates the current context with new information.416417**Example Request:**418```json419POST /api/context420{421 "user": "john",422 "location": "kitchen",423 "time": "morning",424 "activity": "cooking"425}426```427428### Action Endpoints429430#### Execute Action431```http432POST /api/action433```434435Executes a specified action with given parameters.436437**Example Request:**438```json439POST /api/action440{441 "action": "turn_on_lights",442 "parameters": {443 "room": "living_room",444 "brightness": 80445 }446}447```448449#### Batch Actions450```http451POST /api/actions/batch452```453454Executes multiple actions in sequence.455456**Example Request:**457```json458POST /api/actions/batch459{460 "actions": [461 {462 "action": "turn_on_lights",463 "parameters": {464 "room": "living_room"465 }466 },467 {468 "action": "set_temperature",469 "parameters": {470 "temperature": 22471 }472 }473 ]474}475```476477### Query Functions478479#### Get Available Actions480```http481GET /api/actions482```483484Returns a list of all available actions.485486**Example Response:**487```json488{489 "actions": [490 {491 "name": "turn_on_lights",492 "parameters": ["room", "brightness"],493 "description": "Turns on lights in specified room"494 },495 {496 "name": "set_temperature",497 "parameters": ["temperature"],498 "description": "Sets temperature in current context"499 }500 ]501}502```503504#### Context Query505```http506GET /api/context?type=current507```508509Retrieves context information.510511**Example Response:**512```json513{514 "current_context": {515 "user": "john",516 "location": "kitchen",517 "time": "morning",518 "activity": "cooking"519 }520}521```522523### WebSocket Events524525The server supports real-time updates via WebSocket connections.526527```javascript528// Client-side connection example529const ws = new WebSocket('ws://localhost:3000/ws');530531ws.onmessage = (event) => {532 const data = JSON.parse(event.data);533 console.log('Received update:', data);534};535```536537#### Supported Events538539- `state_change`: Emitted when system state changes540- `context_update`: Emitted when context is updated541- `action_executed`: Emitted when an action is completed542- `error`: Emitted when an error occurs543544**Example Event Data:**545```json546{547 "event": "state_change",548 "data": {549 "previous_state": {550 "lights": "off"551 },552 "current_state": {553 "lights": "on"554 },555 "timestamp": "2024-03-20T10:30:00Z"556 }557}558```559560### Error Handling561562All endpoints return standard HTTP status codes:563564- 200: Success565- 400: Bad Request566- 401: Unauthorized567- 403: Forbidden568- 404: Not Found569- 500: Internal Server Error570571**Error Response Format:**572```json573{574 "error": {575 "code": "INVALID_PARAMETERS",576 "message": "Missing required parameter: room",577 "details": {578 "missing_fields": ["room"]579 }580 }581}582```583584### Rate Limiting585586The API implements rate limiting to prevent abuse:587588- 100 requests per minute per IP for regular endpoints589- 1000 requests per minute per IP for WebSocket connections590591When rate limit is exceeded, the server returns:592593```json594{595 "error": {596 "code": "RATE_LIMIT_EXCEEDED",597 "message": "Too many requests",598 "reset_time": "2024-03-20T10:31:00Z"599 }600}601```602603### Example Usage604605#### Using curl606```bash607# Get current state608curl -X GET \609 http://localhost:3000/api/state \610 -H 'Authorization: ApiKey your_api_key_here'611612# Execute action613curl -X POST \614 http://localhost:3000/api/action \615 -H 'Authorization: ApiKey your_api_key_here' \616 -H 'Content-Type: application/json' \617 -d '{618 "action": "turn_on_lights",619 "parameters": {620 "room": "living_room",621 "brightness": 80622 }623 }'624```625626#### Using JavaScript627```javascript628// Execute action629async function executeAction() {630 const response = await fetch('http://localhost:3000/api/action', {631 method: 'POST',632 headers: {633 'Authorization': 'ApiKey your_api_key_here',634 'Content-Type': 'application/json'635 },636 body: JSON.stringify({637 action: 'turn_on_lights',638 parameters: {639 room: 'living_room',640 brightness: 80641 }642 })643 });644645 const data = await response.json();646 console.log('Action result:', data);647}648```649650## Development651652```bash653# Development mode with hot reload654npm run dev655656# Build project657npm run build658659# Production mode660npm run start661662# Run tests663npx jest --config=jest.config.cjs664665# Run tests with coverage666npx jest --coverage667668# Lint code669npm run lint670671# Format code672npm run format673```674675## Troubleshooting676677### Common Issues6786791. **Node.js Version (`toSorted is not a function`)**680 - **Solution:** Update to Node.js 20.10.0+681 ```bash682 nvm install 20.10.0683 nvm use 20.10.0684 ```6856862. **Connection Issues**687 - Verify Home Assistant is running688 - Check `HASS_HOST` accessibility689 - Validate token permissions690 - Ensure WebSocket connection for real-time updates6916923. **Add-on Management Issues**693 - Verify Supervisor access694 - Check add-on compatibility695 - Validate system resources6966974. **HACS Integration Issues**698 - Verify HACS installation699 - Check HACS integration status700 - Validate repository access7017025. **Automation Issues**703 - Verify entity availability704 - Check trigger conditions705 - Validate service calls706 - Monitor execution logs707708## Project Status709710โ **Complete**711- Entity, Floor, and Area access712- Device control (Lights, Climate, Covers, Switches, Contacts)713- Add-on management system714- Package management through HACS715- Advanced automation configuration716- Basic state management717- Error handling and validation718- Docker containerization719- Jest testing setup720- TypeScript integration721- Environment variable management722- Home Assistant API integration723- Project documentation724725๐ง **In Progress**726- WebSocket implementation for real-time updates727- Enhanced security features728- Tool organization optimization729- Performance optimization730- Resource context integration731- API documentation generation732- Multi-platform desktop integration733- Advanced error recovery734- Custom prompt testing735- Enhanced macOS integration736- Type safety improvements737- Testing coverage expansion738739## Contributing7407411. Fork the repository7422. Create a feature branch7433. Implement your changes7444. Add tests for new functionality7455. Ensure all tests pass7466. Submit a pull request747748## Resources749750- [MCP Documentation](https://modelcontextprotocol.io/introduction)751- [Home Assistant Docs](https://www.home-assistant.io)752- [HA REST API](https://developers.home-assistant.io/docs/api/rest)753- [HACS Documentation](https://hacs.xyz)754- [TypeScript Documentation](https://www.typescriptlang.org/docs)755756## License757758MIT License - See [LICENSE](LICENSE) file759
Full transparency โ inspect the skill content before installing.