Skip to content
Back to search

homeassistant-mcp

A MCP server for Home Assistant

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/tevonsb--homeassistant-mcp/badge.svg)](/listings/tevonsb--homeassistant-mcp)

HTML

<a href="/listings/tevonsb--homeassistant-mcp"><img src="/api/listings/tevonsb--homeassistant-mcp/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

Basic Setup

# 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

Docker Setup (Recommended)

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

1. **Clone the repository:** ```bash git clone https://github.com/tevonsb/homeassistant-mcp.git cd homeassistant-mcp ```

2. **Configure environment:** ```bash cp .env.example .env ``` Edit the `.env` file with your Home Assistant configuration: ```env # 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:** ```bash # Build and start the containers docker compose up -d

# View logs docker compose logs -f

# Stop the service docker compose down ```

4. **Verify the installation:** The server should now be running at `http://localhost:3000`. You can check the health endpoint at `http://localhost:3000/health`.

5. **Update the application:** ```bash # Pull the latest changes git pull

# Rebuild and restart the containers docker compose up -d --build ```

Docker Configuration

The Docker setup includes: - 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

All environment variables can be configured in the `.env` file. The following variables are supported: - `HASS_HOST`: Your Home Assistant instance URL - `HASS_TOKEN`: Long-lived access token for Home Assistant - `HASS_SOCKET_URL`: WebSocket URL for Home Assistant - `PORT`: Server port (default: 3000) - `NODE_ENV`: Environment (production/development) - `DEBUG`: Enable debug mode (true/false)

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 758 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # Model Context Protocol Server for Home Assistant
  2. The server uses the MCP protocol to share access to a local Home Assistant instance with an LLM application.
  3. 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.
  4. ![License](https://img.shields.io/badge/license-MIT-blue.svg)
  5. ![Node.js](https://img.shields.io/badge/node-%3E%3D20.10.0-green.svg)
  6. ![Docker Compose](https://img.shields.io/badge/docker-compose-%3E%3D1.27.0-blue.svg)
  7. ![NPM](https://img.shields.io/badge/npm-%3E%3D7.0.0-orange.svg)
  8. ![TypeScript](https://img.shields.io/badge/typescript-%5E5.0.0-blue.svg)
  9. ![Test Coverage](https://img.shields.io/badge/coverage-95%25-brightgreen.svg)
  10. ## Features
  11. - 🎮 **Device Control**: Control any Home Assistant device through natural language
  12. - 🔄 **Real-time Updates**: Get instant updates through Server-Sent Events (SSE)
  13. - 🤖 **Automation Management**: Create, update, and manage automations
  14. - 📊 **State Monitoring**: Track and query device states
  15. - 🔐 **Secure**: Token-based authentication and rate limiting
  16. - 📱 **Mobile Ready**: Works with any HTTP-capable client
  17. ## Real-time Updates with SSE
  18. The server includes a powerful Server-Sent Events (SSE) system that provides real-time updates from your Home Assistant instance. This allows you to:
  19. - 🔄 Get instant state changes for any device
  20. - 📡 Monitor automation triggers and executions
  21. - 🎯 Subscribe to specific domains or entities
  22. - 📊 Track service calls and script executions
  23. ### Quick SSE Example
  24. ```javascript
  25. const eventSource = new EventSource(
  26. 'http://localhost:3000/subscribe_events?token=YOUR_TOKEN&domain=light'
  27. );
  28. eventSource.onmessage = (event) => {
  29. const data = JSON.parse(event.data);
  30. console.log('Update received:', data);
  31. };
  32. ```
  33. See [SSE_API.md](docs/SSE_API.md) for complete documentation of the SSE system.
  34. ## Table of Contents
  35. - [Key Features](#key-features)
  36. - [Prerequisites](#prerequisites)
  37. - [Installation](#installation)
  38. - [Basic Setup](#basic-setup)
  39. - [Docker Setup (Recommended)](#docker-setup-recommended)
  40. - [Configuration](#configuration)
  41. - [Development](#development)
  42. - [API Reference](#api-reference)
  43. - [Device Control](#device-control)
  44. - [Add-on Management](#add-on-management)
  45. - [Package Management](#package-management)
  46. - [Automation Management](#automation-management)
  47. - [Natural Language Integration](#natural-language-integration)
  48. - [Troubleshooting](#troubleshooting)
  49. - [Project Status](#project-status)
  50. - [Contributing](#contributing)
  51. - [Resources](#resources)
  52. - [License](#license)
  53. ## Key Features
  54. ### Core Functionality 🎮
  55. - **Smart Device Control**
  56. - 💡 **Lights**: Brightness, color temperature, RGB color
  57. - 🌡️ **Climate**: Temperature, HVAC modes, fan modes, humidity
  58. - 🚪 **Covers**: Position and tilt control
  59. - 🔌 **Switches**: On/off control
  60. - 🚨 **Sensors & Contacts**: State monitoring
  61. - 🎵 **Media Players**: Playback control, volume, source selection
  62. - 🌪️ **Fans**: Speed, oscillation, direction
  63. - 🔒 **Locks**: Lock/unlock control
  64. - 🧹 **Vacuums**: Start, stop, return to base
  65. - 📹 **Cameras**: Motion detection, snapshots
  66. ### System Management 🛠️
  67. - **Add-on Management**
  68. - Browse available add-ons
  69. - Install/uninstall add-ons
  70. - Start/stop/restart add-ons
  71. - Version management
  72. - Configuration access
  73. - **Package Management (HACS)**
  74. - Integration with Home Assistant Community Store
  75. - Multiple package types support:
  76. - Custom integrations
  77. - Frontend themes
  78. - Python scripts
  79. - AppDaemon apps
  80. - NetDaemon apps
  81. - Version control and updates
  82. - Repository management
  83. - **Automation Management**
  84. - Create and edit automations
  85. - Advanced configuration options:
  86. - Multiple trigger types
  87. - Complex conditions
  88. - Action sequences
  89. - Execution modes
  90. - Duplicate and modify existing automations
  91. - Enable/disable automation rules
  92. - Trigger automation manually
  93. ### Architecture Features 🏗️
  94. - **Intelligent Organization**
  95. - Area and floor-based device grouping
  96. - State monitoring and querying
  97. - Smart context awareness
  98. - Historical data access
  99. - **Robust Architecture**
  100. - Comprehensive error handling
  101. - State validation
  102. - Secure API integration
  103. - TypeScript type safety
  104. - Extensive test coverage
  105. ## Prerequisites
  106. - **Node.js** 20.10.0 or higher
  107. - **NPM** package manager
  108. - **Docker Compose** for containerization
  109. - Running **Home Assistant** instance
  110. - Home Assistant long-lived access token ([How to get token](https://community.home-assistant.io/t/how-to-get-long-lived-access-token/162159))
  111. - **HACS** installed for package management features
  112. - **Supervisor** access for add-on management
  113. ## Installation
  114. ### Basic Setup
  115. ```bash
  116. # Clone the repository
  117. git clone https://github.com/tevonsb/homeassistant-mcp.git
  118. cd homeassistant-mcp
  119. # Install dependencies
  120. npm install
  121. # Build the project
  122. npm run build
  123. ```
  124. ### Docker Setup (Recommended)
  125. The project includes Docker support for easy deployment and consistent environments across different platforms.
  126. 1. **Clone the repository:**
  127. ```bash
  128. git clone https://github.com/tevonsb/homeassistant-mcp.git
  129. cd homeassistant-mcp
  130. ```
  131. 2. **Configure environment:**
  132. ```bash
  133. cp .env.example .env
  134. ```
  135. Edit the `.env` file with your Home Assistant configuration:
  136. ```env
  137. # Home Assistant Configuration
  138. HASS_HOST=http://homeassistant.local:8123
  139. HASS_TOKEN=your_home_assistant_token
  140. HASS_SOCKET_URL=ws://homeassistant.local:8123/api/websocket
  141. # Server Configuration
  142. PORT=3000
  143. NODE_ENV=production
  144. DEBUG=false
  145. ```
  146. 3. **Build and run with Docker Compose:**
  147. ```bash
  148. # Build and start the containers
  149. docker compose up -d
  150. # View logs
  151. docker compose logs -f
  152. # Stop the service
  153. docker compose down
  154. ```
  155. 4. **Verify the installation:**
  156. The server should now be running at `http://localhost:3000`. You can check the health endpoint at `http://localhost:3000/health`.
  157. 5. **Update the application:**
  158. ```bash
  159. # Pull the latest changes
  160. git pull
  161. # Rebuild and restart the containers
  162. docker compose up -d --build
  163. ```
  164. #### Docker Configuration
  165. The Docker setup includes:
  166. - Multi-stage build for optimal image size
  167. - Health checks for container monitoring
  168. - Volume mounting for environment configuration
  169. - Automatic container restart on failure
  170. - Exposed port 3000 for API access
  171. #### Docker Compose Environment Variables
  172. All environment variables can be configured in the `.env` file. The following variables are supported:
  173. - `HASS_HOST`: Your Home Assistant instance URL
  174. - `HASS_TOKEN`: Long-lived access token for Home Assistant
  175. - `HASS_SOCKET_URL`: WebSocket URL for Home Assistant
  176. - `PORT`: Server port (default: 3000)
  177. - `NODE_ENV`: Environment (production/development)
  178. - `DEBUG`: Enable debug mode (true/false)
  179. ## Configuration
  180. ### Environment Variables
  181. ```env
  182. # Home Assistant Configuration
  183. HASS_HOST=http://homeassistant.local:8123 # Your Home Assistant instance URL
  184. HASS_TOKEN=your_home_assistant_token # Long-lived access token
  185. HASS_SOCKET_URL=ws://homeassistant.local:8123/api/websocket # WebSocket URL
  186. # Server Configuration
  187. PORT=3000 # Server port (default: 3000)
  188. NODE_ENV=production # Environment (production/development)
  189. DEBUG=false # Enable debug mode
  190. # Test Configuration
  191. TEST_HASS_HOST=http://localhost:8123 # Test instance URL
  192. TEST_HASS_TOKEN=test_token # Test token
  193. ```
  194. ### Configuration Files
  195. 1. **Development**: Copy `.env.example` to `.env.development`
  196. 2. **Production**: Copy `.env.example` to `.env.production`
  197. 3. **Testing**: Copy `.env.example` to `.env.test`
  198. ### Adding to Claude Desktop (or other clients)
  199. To 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.
  200. ```
  201. {
  202. "homeassistant": {
  203. "command": "node",
  204. "args": [<path/to/your/dist/folder>]
  205. "env": {
  206. NODE_ENV=development
  207. HASS_HOST=http://homeassistant.local:8123
  208. HASS_TOKEN=your_home_assistant_token
  209. PORT=3000
  210. HASS_SOCKET_URL=ws://homeassistant.local:8123/api/websocket
  211. LOG_LEVEL=debug
  212. }
  213. }
  214. }
  215. ```
  216. ## API Reference
  217. ### Device Control
  218. #### Common Entity Controls
  219. ```json
  220. {
  221. "tool": "control",
  222. "command": "turn_on", // or "turn_off", "toggle"
  223. "entity_id": "light.living_room"
  224. }
  225. ```
  226. #### Light Control
  227. ```json
  228. {
  229. "tool": "control",
  230. "command": "turn_on",
  231. "entity_id": "light.living_room",
  232. "brightness": 128,
  233. "color_temp": 4000,
  234. "rgb_color": [255, 0, 0]
  235. }
  236. ```
  237. ### Add-on Management
  238. #### List Available Add-ons
  239. ```json
  240. {
  241. "tool": "addon",
  242. "action": "list"
  243. }
  244. ```
  245. #### Install Add-on
  246. ```json
  247. {
  248. "tool": "addon",
  249. "action": "install",
  250. "slug": "core_configurator",
  251. "version": "5.6.0"
  252. }
  253. ```
  254. #### Manage Add-on State
  255. ```json
  256. {
  257. "tool": "addon",
  258. "action": "start", // or "stop", "restart"
  259. "slug": "core_configurator"
  260. }
  261. ```
  262. ### Package Management
  263. #### List HACS Packages
  264. ```json
  265. {
  266. "tool": "package",
  267. "action": "list",
  268. "category": "integration" // or "plugin", "theme", "python_script", "appdaemon", "netdaemon"
  269. }
  270. ```
  271. #### Install Package
  272. ```json
  273. {
  274. "tool": "package",
  275. "action": "install",
  276. "category": "integration",
  277. "repository": "hacs/integration",
  278. "version": "1.32.0"
  279. }
  280. ```
  281. ### Automation Management
  282. #### Create Automation
  283. ```json
  284. {
  285. "tool": "automation_config",
  286. "action": "create",
  287. "config": {
  288. "alias": "Motion Light",
  289. "description": "Turn on light when motion detected",
  290. "mode": "single",
  291. "trigger": [
  292. {
  293. "platform": "state",
  294. "entity_id": "binary_sensor.motion",
  295. "to": "on"
  296. }
  297. ],
  298. "action": [
  299. {
  300. "service": "light.turn_on",
  301. "target": {
  302. "entity_id": "light.living_room"
  303. }
  304. }
  305. ]
  306. }
  307. }
  308. ```
  309. #### Duplicate Automation
  310. ```json
  311. {
  312. "tool": "automation_config",
  313. "action": "duplicate",
  314. "automation_id": "automation.motion_light"
  315. }
  316. ```
  317. ### Core Functions
  318. #### State Management
  319. ```http
  320. GET /api/state
  321. POST /api/state
  322. ```
  323. Manages the current state of the system.
  324. **Example Request:**
  325. ```json
  326. POST /api/state
  327. {
  328. "context": "living_room",
  329. "state": {
  330. "lights": "on",
  331. "temperature": 22
  332. }
  333. }
  334. ```
  335. #### Context Updates
  336. ```http
  337. POST /api/context
  338. ```
  339. Updates the current context with new information.
  340. **Example Request:**
  341. ```json
  342. POST /api/context
  343. {
  344. "user": "john",
  345. "location": "kitchen",
  346. "time": "morning",
  347. "activity": "cooking"
  348. }
  349. ```
  350. ### Action Endpoints
  351. #### Execute Action
  352. ```http
  353. POST /api/action
  354. ```
  355. Executes a specified action with given parameters.
  356. **Example Request:**
  357. ```json
  358. POST /api/action
  359. {
  360. "action": "turn_on_lights",
  361. "parameters": {
  362. "room": "living_room",
  363. "brightness": 80
  364. }
  365. }
  366. ```
  367. #### Batch Actions
  368. ```http
  369. POST /api/actions/batch
  370. ```
  371. Executes multiple actions in sequence.
  372. **Example Request:**
  373. ```json
  374. POST /api/actions/batch
  375. {
  376. "actions": [
  377. {
  378. "action": "turn_on_lights",
  379. "parameters": {
  380. "room": "living_room"
  381. }
  382. },
  383. {
  384. "action": "set_temperature",
  385. "parameters": {
  386. "temperature": 22
  387. }
  388. }
  389. ]
  390. }
  391. ```
  392. ### Query Functions
  393. #### Get Available Actions
  394. ```http
  395. GET /api/actions
  396. ```
  397. Returns a list of all available actions.
  398. **Example Response:**
  399. ```json
  400. {
  401. "actions": [
  402. {
  403. "name": "turn_on_lights",
  404. "parameters": ["room", "brightness"],
  405. "description": "Turns on lights in specified room"
  406. },
  407. {
  408. "name": "set_temperature",
  409. "parameters": ["temperature"],
  410. "description": "Sets temperature in current context"
  411. }
  412. ]
  413. }
  414. ```
  415. #### Context Query
  416. ```http
  417. GET /api/context?type=current
  418. ```
  419. Retrieves context information.
  420. **Example Response:**
  421. ```json
  422. {
  423. "current_context": {
  424. "user": "john",
  425. "location": "kitchen",
  426. "time": "morning",
  427. "activity": "cooking"
  428. }
  429. }
  430. ```
  431. ### WebSocket Events
  432. The server supports real-time updates via WebSocket connections.
  433. ```javascript
  434. // Client-side connection example
  435. const ws = new WebSocket('ws://localhost:3000/ws');
  436. ws.onmessage = (event) => {
  437. const data = JSON.parse(event.data);
  438. console.log('Received update:', data);
  439. };
  440. ```
  441. #### Supported Events
  442. - `state_change`: Emitted when system state changes
  443. - `context_update`: Emitted when context is updated
  444. - `action_executed`: Emitted when an action is completed
  445. - `error`: Emitted when an error occurs
  446. **Example Event Data:**
  447. ```json
  448. {
  449. "event": "state_change",
  450. "data": {
  451. "previous_state": {
  452. "lights": "off"
  453. },
  454. "current_state": {
  455. "lights": "on"
  456. },
  457. "timestamp": "2024-03-20T10:30:00Z"
  458. }
  459. }
  460. ```
  461. ### Error Handling
  462. All endpoints return standard HTTP status codes:
  463. - 200: Success
  464. - 400: Bad Request
  465. - 401: Unauthorized
  466. - 403: Forbidden
  467. - 404: Not Found
  468. - 500: Internal Server Error
  469. **Error Response Format:**
  470. ```json
  471. {
  472. "error": {
  473. "code": "INVALID_PARAMETERS",
  474. "message": "Missing required parameter: room",
  475. "details": {
  476. "missing_fields": ["room"]
  477. }
  478. }
  479. }
  480. ```
  481. ### Rate Limiting
  482. The API implements rate limiting to prevent abuse:
  483. - 100 requests per minute per IP for regular endpoints
  484. - 1000 requests per minute per IP for WebSocket connections
  485. When rate limit is exceeded, the server returns:
  486. ```json
  487. {
  488. "error": {
  489. "code": "RATE_LIMIT_EXCEEDED",
  490. "message": "Too many requests",
  491. "reset_time": "2024-03-20T10:31:00Z"
  492. }
  493. }
  494. ```
  495. ### Example Usage
  496. #### Using curl
  497. ```bash
  498. # Get current state
  499. curl -X GET \
  500. http://localhost:3000/api/state \
  501. -H 'Authorization: ApiKey your_api_key_here'
  502. # Execute action
  503. curl -X POST \
  504. http://localhost:3000/api/action \
  505. -H 'Authorization: ApiKey your_api_key_here' \
  506. -H 'Content-Type: application/json' \
  507. -d '{
  508. "action": "turn_on_lights",
  509. "parameters": {
  510. "room": "living_room",
  511. "brightness": 80
  512. }
  513. }'
  514. ```
  515. #### Using JavaScript
  516. ```javascript
  517. // Execute action
  518. async function executeAction() {
  519. const response = await fetch('http://localhost:3000/api/action', {
  520. method: 'POST',
  521. headers: {
  522. 'Authorization': 'ApiKey your_api_key_here',
  523. 'Content-Type': 'application/json'
  524. },
  525. body: JSON.stringify({
  526. action: 'turn_on_lights',
  527. parameters: {
  528. room: 'living_room',
  529. brightness: 80
  530. }
  531. })
  532. });
  533. const data = await response.json();
  534. console.log('Action result:', data);
  535. }
  536. ```
  537. ## Development
  538. ```bash
  539. # Development mode with hot reload
  540. npm run dev
  541. # Build project
  542. npm run build
  543. # Production mode
  544. npm run start
  545. # Run tests
  546. npx jest --config=jest.config.cjs
  547. # Run tests with coverage
  548. npx jest --coverage
  549. # Lint code
  550. npm run lint
  551. # Format code
  552. npm run format
  553. ```
  554. ## Troubleshooting
  555. ### Common Issues
  556. 1. **Node.js Version (`toSorted is not a function`)**
  557. - **Solution:** Update to Node.js 20.10.0+
  558. ```bash
  559. nvm install 20.10.0
  560. nvm use 20.10.0
  561. ```
  562. 2. **Connection Issues**
  563. - Verify Home Assistant is running
  564. - Check `HASS_HOST` accessibility
  565. - Validate token permissions
  566. - Ensure WebSocket connection for real-time updates
  567. 3. **Add-on Management Issues**
  568. - Verify Supervisor access
  569. - Check add-on compatibility
  570. - Validate system resources
  571. 4. **HACS Integration Issues**
  572. - Verify HACS installation
  573. - Check HACS integration status
  574. - Validate repository access
  575. 5. **Automation Issues**
  576. - Verify entity availability
  577. - Check trigger conditions
  578. - Validate service calls
  579. - Monitor execution logs
  580. ## Project Status
  581. ✅ **Complete**
  582. - Entity, Floor, and Area access
  583. - Device control (Lights, Climate, Covers, Switches, Contacts)
  584. - Add-on management system
  585. - Package management through HACS
  586. - Advanced automation configuration
  587. - Basic state management
  588. - Error handling and validation
  589. - Docker containerization
  590. - Jest testing setup
  591. - TypeScript integration
  592. - Environment variable management
  593. - Home Assistant API integration
  594. - Project documentation
  595. 🚧 **In Progress**
  596. - WebSocket implementation for real-time updates
  597. - Enhanced security features
  598. - Tool organization optimization
  599. - Performance optimization
  600. - Resource context integration
  601. - API documentation generation
  602. - Multi-platform desktop integration
  603. - Advanced error recovery
  604. - Custom prompt testing
  605. - Enhanced macOS integration
  606. - Type safety improvements
  607. - Testing coverage expansion
  608. ## Contributing
  609. 1. Fork the repository
  610. 2. Create a feature branch
  611. 3. Implement your changes
  612. 4. Add tests for new functionality
  613. 5. Ensure all tests pass
  614. 6. Submit a pull request
  615. ## Resources
  616. - [MCP Documentation](https://modelcontextprotocol.io/introduction)
  617. - [Home Assistant Docs](https://www.home-assistant.io)
  618. - [HA REST API](https://developers.home-assistant.io/docs/api/rest)
  619. - [HACS Documentation](https://hacs.xyz)
  620. - [TypeScript Documentation](https://www.typescriptlang.org/docs)
  621. ## License
  622. MIT License - See [LICENSE](LICENSE) file

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.