315 lines
9.0 KiB
Markdown
315 lines
9.0 KiB
Markdown
# Home Assistant MCP Server
|
|
|
|
A Model Context Protocol (MCP) server that provides seamless integration between Large Language Models and Home Assistant. This server exposes Home Assistant's REST API through MCP resources and tools, enabling LLMs to read states, control devices, and interact with your smart home.
|
|
|
|
## Features
|
|
|
|
### MCP Resources (Read-only data access)
|
|
- **ha://states** - All entity states in Home Assistant
|
|
- **ha://states/{entity_id}** - Specific entity state
|
|
- **ha://config** - System configuration
|
|
- **ha://services** - Available services by domain
|
|
- **ha://events** - Registered events
|
|
- **ha://components** - Loaded components
|
|
- **ha://error_log** - Error log entries
|
|
|
|
### MCP Tools (Actions)
|
|
- **call_service** - Execute Home Assistant services (control lights, switches, climate, etc.)
|
|
- **get_state** - Get current state and attributes of specific entities
|
|
- **set_state** - Create or update entity states
|
|
- **fire_event** - Trigger custom events
|
|
- **render_template** - Render Jinja2 templates with current HA state
|
|
- **get_history** - Retrieve historical state data
|
|
- **get_logbook** - Get human-readable event logs
|
|
- **get_camera_image** - Retrieve camera snapshots as base64
|
|
- **get_calendar_events** - Get calendar events in a time range
|
|
|
|
## Installation
|
|
|
|
### Prerequisites
|
|
- Node.js 18 or higher
|
|
- A running Home Assistant instance
|
|
- A Home Assistant long-lived access token
|
|
|
|
### Setup
|
|
|
|
1. **Clone or navigate to the project directory:**
|
|
```bash
|
|
cd /Users/felix/Nextcloud/AI/projects/ha-mcp-server
|
|
```
|
|
|
|
2. **Install dependencies:**
|
|
```bash
|
|
npm install
|
|
```
|
|
|
|
3. **Create environment configuration:**
|
|
```bash
|
|
cp .env.example .env
|
|
```
|
|
|
|
4. **Edit `.env` with your Home Assistant details:**
|
|
```bash
|
|
HA_BASE_URL=http://homeassistant.local:8123
|
|
HA_ACCESS_TOKEN=your_long_lived_access_token_here
|
|
```
|
|
|
|
To get a long-lived access token:
|
|
- Open Home Assistant UI
|
|
- Click your profile (bottom left)
|
|
- Scroll down to "Long-Lived Access Tokens"
|
|
- Click "Create Token"
|
|
- Give it a name and copy the token
|
|
|
|
5. **Build the server:**
|
|
```bash
|
|
npm run build
|
|
```
|
|
|
|
### Docker Installation
|
|
|
|
Alternatively, run the MCP server in Docker (similar to MCP Toolkit in Docker Desktop):
|
|
|
|
1. **Create environment file:**
|
|
```bash
|
|
cp .env.example .env
|
|
# Edit .env with your Home Assistant details
|
|
```
|
|
|
|
2. **Build and run with Docker Compose:**
|
|
```bash
|
|
docker-compose up -d
|
|
```
|
|
|
|
3. **View logs:**
|
|
```bash
|
|
docker-compose logs -f
|
|
```
|
|
|
|
For detailed Docker setup including Docker Desktop MCP integration, see [DOCKER.md](DOCKER.md).
|
|
|
|
## Usage
|
|
|
|
### Running Standalone
|
|
```bash
|
|
npm start
|
|
```
|
|
|
|
### Configuring with Claude Desktop
|
|
|
|
Add this to your Claude Desktop configuration file:
|
|
|
|
**macOS:** `~/Library/Application Support/Claude/claude_desktop_config.json`
|
|
|
|
**Windows:** `%APPDATA%\Claude\claude_desktop_config.json`
|
|
|
|
**Standard Installation:**
|
|
```json
|
|
{
|
|
"mcpServers": {
|
|
"home-assistant": {
|
|
"command": "node",
|
|
"args": ["/Users/felix/Nextcloud/AI/projects/ha-mcp-server/build/index.js"],
|
|
"env": {
|
|
"HA_BASE_URL": "http://homeassistant.local:8123",
|
|
"HA_ACCESS_TOKEN": "your_long_lived_access_token_here"
|
|
}
|
|
}
|
|
}
|
|
}
|
|
```
|
|
|
|
**Docker Installation:**
|
|
```json
|
|
{
|
|
"mcpServers": {
|
|
"home-assistant": {
|
|
"command": "docker",
|
|
"args": [
|
|
"run",
|
|
"--rm",
|
|
"-i",
|
|
"--network=host",
|
|
"-e", "HA_BASE_URL=http://homeassistant.local:8123",
|
|
"-e", "HA_ACCESS_TOKEN=your_long_lived_access_token_here",
|
|
"ha-mcp-server:latest"
|
|
]
|
|
}
|
|
}
|
|
}
|
|
```
|
|
|
|
Restart Claude Desktop after updating the configuration.
|
|
|
|
### Using with other MCP Clients
|
|
|
|
Any MCP-compatible client can connect using stdio transport:
|
|
|
|
```bash
|
|
HA_BASE_URL=http://homeassistant.local:8123 \
|
|
HA_ACCESS_TOKEN=your_token \
|
|
node build/index.js
|
|
```
|
|
|
|
## Example Interactions
|
|
|
|
### Reading Entity States
|
|
```
|
|
User: What's the current temperature in the living room?
|
|
LLM: [Uses get_state tool with entity_id: "sensor.living_room_temperature"]
|
|
```
|
|
|
|
### Controlling Devices
|
|
```
|
|
User: Turn on the living room lights at 50% brightness
|
|
LLM: [Uses call_service tool with:
|
|
domain: "light"
|
|
service: "turn_on"
|
|
service_data: {
|
|
entity_id: "light.living_room",
|
|
brightness_pct: 50
|
|
}
|
|
]
|
|
```
|
|
|
|
### Complex Queries with Templates
|
|
```
|
|
User: How many lights are currently on?
|
|
LLM: [Uses render_template tool with:
|
|
template: "{{ states.light | selectattr('state', 'eq', 'on') | list | count }}"
|
|
]
|
|
```
|
|
|
|
### Historical Analysis
|
|
```
|
|
User: Show me the temperature trend for the last 24 hours
|
|
LLM: [Uses get_history tool with:
|
|
entity_ids: ["sensor.living_room_temperature"]
|
|
start_time: "2024-01-06T00:00:00Z"
|
|
end_time: "2024-01-07T00:00:00Z"
|
|
]
|
|
```
|
|
|
|
## Architecture
|
|
|
|
### Project Structure
|
|
```
|
|
ha-mcp-server/
|
|
├── src/
|
|
│ ├── index.ts # Main MCP server implementation
|
|
│ ├── ha-client.ts # Home Assistant REST API client
|
|
│ └── types.ts # TypeScript type definitions
|
|
├── build/ # Compiled JavaScript output
|
|
├── package.json # Project configuration
|
|
├── tsconfig.json # TypeScript configuration
|
|
├── .env # Environment configuration (not committed)
|
|
└── README.md # This file
|
|
```
|
|
|
|
### Design Principles
|
|
|
|
1. **Resources for Reading**: All read-only data access uses MCP resources with descriptive URIs
|
|
2. **Tools for Actions**: All state-changing operations use MCP tools with clear schemas
|
|
3. **Type Safety**: Strong TypeScript typing throughout the codebase
|
|
4. **Error Handling**: Comprehensive error handling with meaningful messages
|
|
5. **Validation**: Input validation using Zod schemas
|
|
6. **Security**: Authentication via Home Assistant access tokens
|
|
|
|
## Security Considerations
|
|
|
|
- **Access Token Protection**: Never commit your `.env` file or share your access token
|
|
- **Network Security**: Use HTTPS if exposing Home Assistant to the internet
|
|
- **Token Scope**: The access token has full access to your Home Assistant instance
|
|
- **Rate Limiting**: Consider implementing rate limiting for production use
|
|
|
|
## Troubleshooting
|
|
|
|
### Connection Issues
|
|
- Verify Home Assistant is accessible at the configured URL
|
|
- Check that the access token is valid and not expired
|
|
- Ensure there are no firewall rules blocking the connection
|
|
|
|
### Authentication Errors
|
|
- Confirm the access token is correctly copied (no extra spaces)
|
|
- Verify the token hasn't been revoked in Home Assistant
|
|
- Check that the API is enabled in Home Assistant configuration
|
|
|
|
### Tool Execution Errors
|
|
- Verify entity IDs are correct (case-sensitive)
|
|
- Check that the service exists for the domain
|
|
- Ensure required parameters are provided in service calls
|
|
|
|
### Debugging
|
|
Enable detailed logging by checking stderr output when running the server.
|
|
|
|
## Development
|
|
|
|
### Building
|
|
```bash
|
|
npm run build
|
|
```
|
|
|
|
### Watch Mode
|
|
```bash
|
|
npm run watch
|
|
```
|
|
|
|
### Adding New Tools
|
|
1. Add the tool definition in the `ListToolsRequestSchema` handler
|
|
2. Add the tool implementation in the `CallToolRequestSchema` handler
|
|
3. Add corresponding methods to `HomeAssistantClient` if needed
|
|
4. Update types in `types.ts` as necessary
|
|
|
|
### Adding New Resources
|
|
1. Add the resource definition in the `ListResourcesRequestSchema` handler
|
|
2. Add the resource read logic in the `ReadResourceRequestSchema` handler
|
|
3. Add corresponding methods to `HomeAssistantClient` if needed
|
|
|
|
## API Coverage
|
|
|
|
This MCP server implements the following Home Assistant REST API endpoints:
|
|
|
|
| Endpoint | MCP Interface | Type |
|
|
|----------|---------------|------|
|
|
| GET /api/ | Automatic (connection check) | - |
|
|
| GET /api/config | ha://config | Resource |
|
|
| GET /api/components | ha://components | Resource |
|
|
| GET /api/events | ha://events | Resource |
|
|
| GET /api/services | ha://services | Resource |
|
|
| GET /api/error_log | ha://error_log | Resource |
|
|
| GET /api/states | ha://states | Resource |
|
|
| GET /api/states/{id} | get_state tool | Tool |
|
|
| POST /api/states/{id} | set_state tool | Tool |
|
|
| POST /api/services/{domain}/{service} | call_service tool | Tool |
|
|
| POST /api/events/{event} | fire_event tool | Tool |
|
|
| POST /api/template | render_template tool | Tool |
|
|
| GET /api/history/period | get_history tool | Tool |
|
|
| GET /api/logbook | get_logbook tool | Tool |
|
|
| GET /api/calendars/{id} | get_calendar_events tool | Tool |
|
|
| GET /api/camera_proxy/{id} | get_camera_image tool | Tool |
|
|
|
|
## Contributing
|
|
|
|
Contributions are welcome! Please consider:
|
|
- Adding support for WebSocket streaming for real-time updates
|
|
- Implementing additional Home Assistant APIs
|
|
- Adding comprehensive test coverage
|
|
- Improving error messages and documentation
|
|
|
|
## License
|
|
|
|
MIT
|
|
|
|
## Resources
|
|
|
|
- [Model Context Protocol Documentation](https://modelcontextprotocol.io)
|
|
- [Home Assistant REST API Documentation](https://developers.home-assistant.io/docs/api/rest/)
|
|
- [Home Assistant Developer Documentation](https://developers.home-assistant.io/)
|
|
|
|
## Support
|
|
|
|
For issues and questions:
|
|
- Check the troubleshooting section above
|
|
- Review Home Assistant logs for API errors
|
|
- Verify MCP client configuration is correct
|