Add Claude Desktop setup script and update README for integration instructions

- Introduced `claude_desktop_setup.sh` to automate the installation and configuration of MCP integration for Claude Desktop, including Node.js installation via nvm and Brave Search MCP setup.
- Updated README.md to reflect new setup instructions, key features, and quick start guide for using the MCP with Home Assistant and Claude Desktop.
- Enhanced configuration management by detailing environment variable setup and providing examples for user configurations.
This commit is contained in:
jango-blockchained
2024-12-16 14:59:59 +01:00
parent 752b1daa9c
commit e46b72b914
2 changed files with 197 additions and 505 deletions

584
README.md
View File

@@ -1,212 +1,74 @@
# A Model Context Protocol Server for Home Assistant
# 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. It provides a comprehensive interface for controlling various Home Assistant entities through natural language.
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).
## Features
## Key Features
- **Entity Control**: Full support for controlling common Home Assistant entities:
- **Smart Device Control** 🎮
- 💡 **Lights**: Brightness, color temperature, RGB color
- 🌡️ **Climate**: Temperature, HVAC modes, fan modes, humidity
- 🚪 **Covers**: Position control, tilt control
- 🔌 **Switches**: Basic on/off control
- 🚨 **Contacts**: State monitoring
- **Entity State Access**: Query and monitor entity states
- **Area and Floor Organization**: Logical grouping of devices
- **Robust Error Handling**: Clear error messages and state validation
- 🚪 **Covers**: Position and tilt control
- 🔌 **Switches**: On/off control
- 🚨 **Sensors**: State monitoring
- **Intelligent Organization** 🏠
- Area and floor-based device grouping
- State monitoring and querying
- Smart context awareness
- **Robust Architecture** 🛠️
- Comprehensive error handling
- State validation
- Secure API integration
## Prerequisites
## Quick Start
- Node.js 20.10.0 or higher (Required for Array.prototype.toSorted())
- NPM package manager
- A running Home Assistant instance
- A long-lived access token from Home Assistant
### Prerequisites
### Node.js Version Management
- Node.js 20.10.0+ (for Array.prototype.toSorted())
- NPM
- Running Home Assistant instance
- Home Assistant long-lived access token
If you're using an older version of Node.js, you can use `nvm` (Node Version Manager) to install and use the correct version:
### Basic Installation
```bash
# Install nvm (if not already installed)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
# Reload shell configuration
source ~/.bashrc # or source ~/.zshrc for Zsh
# Install Node.js 20.10.0
nvm install 20.10.0
# Use Node.js 20.10.0
nvm use 20.10.0
```
## Installation
### Classic Installation
```bash
# Clone the repository
git clone https://github.com/jango-blockchained/homeassistant-mcp.git
cd homeassistant-mcp
# Install dependencies
npm install
# Build the server
npm run build
```
### Docker Installation
#### Using Docker Compose (Recommended)
1. Clone the repository:
```bash
git clone https://github.com/jango-blockchained/homeassistant-mcp.git
cd homeassistant-mcp
```
2. Create a `.env` file with your Home Assistant configuration:
```env
NODE_ENV=production
HASS_HOST=your_home_assistant_url
HASS_TOKEN=your_home_assistant_token
```
3. Start the container:
```bash
docker-compose up -d
```
#### Using Docker Directly
1. Build the image:
```bash
docker build -t homeassistant-mcp .
```
2. Run the container:
```bash
docker run -d \
--name homeassistant-mcp \
-e HASS_HOST=your_home_assistant_url \
-e HASS_TOKEN=your_home_assistant_token \
-p 3000:3000 \
homeassistant-mcp
```
### Docker Management Commands
### Docker Setup (Recommended)
1. Clone and prepare:
```bash
# Stop the container
docker-compose down
# View logs
docker-compose logs -f
# Restart the container
docker-compose restart
# Update to latest version
git pull
docker-compose up -d --build
git clone https://github.com/jango-blockchained/homeassistant-mcp.git
cd homeassistant-mcp
```
## Configuration
2. Configure environment:
```env
NODE_ENV=production
HASS_HOST=your_home_assistant_url
HASS_TOKEN=your_home_assistant_token
```
1. **Home Assistant Token**
- Get a long-lived access token from Home Assistant
- Guide: [How to get long-lived access token](https://community.home-assistant.io/t/how-to-get-long-lived-access-token/162159)
3. Launch:
```bash
docker-compose up -d
```
2. **Environment Variables**
Create a `.env` file with:
```env
NODE_ENV=development
HASS_HOST=your_home_assistant_url # e.g., http://homeassistant.local:8123
HASS_TOKEN=your_home_assistant_token
```
3. **MCP Client Configuration**
Configure your MCP client (like Claude Desktop) with:
```json
{
"mcpServers": {
"homeassistant": {
"command": "node",
"args": [
"/path/to/dist/index.js"
],
"env": {
"HASS_TOKEN": "your_home_assistant_token",
"HASS_HOST": "your_home_assistant_url"
}
}
}
}
```
## How to Use
The server provides two main tools for interacting with Home Assistant:
### 1. List Devices Tool
Use this tool to discover all available devices and their current states:
## Usage Guide
### Device Discovery
```json
{
"tool": "list_devices"
}
```
This will return a structured response with all devices grouped by domain:
### Basic Controls
```json
{
"success": true,
"devices": {
"light": [
{
"entity_id": "light.living_room",
"state": "on",
"attributes": {
"brightness": 128,
"color_temp": 4000,
"friendly_name": "Living Room Light"
}
}
],
"climate": [
{
"entity_id": "climate.bedroom",
"state": "heat",
"attributes": {
"temperature": 22,
"hvac_mode": "heat",
"friendly_name": "Bedroom Thermostat"
}
}
]
}
}
```
### 2. Control Tool
Use this tool to control your devices. Here are some common usage examples:
#### Light Control
```json
// Turn on a light
{
"tool": "control",
"command": "turn_on",
"entity_id": "light.living_room"
}
// Set brightness
// Light control
{
"tool": "control",
"command": "turn_on",
@@ -214,358 +76,70 @@ Use this tool to control your devices. Here are some common usage examples:
"brightness": 128
}
// Set color temperature
{
"tool": "control",
"command": "turn_on",
"entity_id": "light.living_room",
"color_temp": 4000
}
// Set RGB color (red)
{
"tool": "control",
"command": "turn_on",
"entity_id": "light.living_room",
"rgb_color": [255, 0, 0]
}
```
#### Climate Control
```json
// Set temperature
// Climate control
{
"tool": "control",
"command": "set_temperature",
"entity_id": "climate.living_room",
"entity_id": "climate.bedroom",
"temperature": 22
}
// Set HVAC mode
{
"tool": "control",
"command": "set_hvac_mode",
"entity_id": "climate.living_room",
"hvac_mode": "heat"
}
// Set fan mode
{
"tool": "control",
"command": "set_fan_mode",
"entity_id": "climate.living_room",
"fan_mode": "auto"
}
```
#### Cover Control
## Natural Language Integration
```json
// Open/Close cover
{
"tool": "control",
"command": "open_cover", // or "close_cover"
"entity_id": "cover.living_room"
}
### Example Commands
- "Turn on the living room lights"
- "Set bedroom temperature to 22 degrees"
- "Is the front door locked?"
// Set position
{
"tool": "control",
"command": "set_position",
"entity_id": "cover.living_room",
"position": 50
}
// Set tilt
{
"tool": "control",
"command": "set_tilt_position",
"entity_id": "cover.living_room",
"tilt_position": 45
}
```
#### Switch Control
```json
// Turn on/off
{
"tool": "control",
"command": "turn_on", // or "turn_off"
"entity_id": "switch.office"
}
// Toggle
{
"tool": "control",
"command": "toggle",
"entity_id": "switch.office"
}
```
### Error Handling
The server provides clear error messages when something goes wrong:
```json
{
"success": false,
"message": "Failed to execute set_temperature for light.living_room: Unsupported operation for domain: light"
}
```
Common error scenarios:
1. Invalid entity ID
2. Unsupported operation for domain
3. Invalid parameter values
4. Home Assistant connection issues
### Best Practices
1. **Entity Discovery**
- Always use `list_devices` first to discover available entities
- Note the supported attributes for each device
2. **Parameter Validation**
- Brightness: 0-255
- Position/Tilt: 0-100
- Temperature: Depends on your system's configuration
- Color temperature: Typically 2000-6500K
3. **Error Recovery**
- If a command fails, check:
- Entity ID exists and is correct
- Command is supported by the domain
- Parameters are within valid ranges
4. **State Awareness**
- Use `list_devices` to check current state before making changes
- Verify command execution by checking state afterward
### Smart Features
- Context awareness across conversations
- Natural parameter interpretation
- Intelligent error prevention
- Multi-device orchestration
## Development
```bash
# Run in development mode
yarn dev
# Build and start
yarn build:start
# Run tests
yarn test
npm run dev # Development mode
npm run build # Build project
npm test # Run tests
```
## Troubleshooting
### Common Issues
1. **Node.js Version Error (`positive.toSorted is not a function`)**
- This error occurs when using Node.js version lower than 20
- Solution: Update to Node.js 20.10.0 or higher using nvm (see Prerequisites section)
- Docker users: The container automatically uses the correct Node.js version
2. **Connection Errors**
- Verify your Home Assistant instance is running
- Check the HASS_HOST is correct and accessible
- Ensure your token has the required permissions
1. Node.js Version (`toSorted is not a function`)
- Solution: Update to Node.js 20.10.0+
2. Connection Issues
- Verify Home Assistant is running
- Check HASS_HOST accessibility
- Validate token permissions
## Project Status
### Completed
- [x] Access to entities
- [x] Access to Floors
- [x] Access to Areas
- [x] Control for entities
- [x] Lights
- [x] Thermostats
- [x] Covers
- [x] Contacts
- [x] Climates
- [x] Switches
**Complete**
- Entity, Floor, and Area access
- Device control (Lights, Climate, Covers, Switches)
- Basic state management
### In Progress
- [ ] Testing / writing custom prompts
- [ ] Testing using resources for high-level context
- [ ] Test varying tool organization
🚧 **In Progress**
- Custom prompt testing
- Resource context integration
- Tool organization optimization
## Resources
- [MCP Documentation](https://modelcontextprotocol.io/introduction)
- [Home Assistant Docs](https://www.home-assistant.io)
- [HA REST API](https://developers.home-assistant.io/docs/api/rest)
## Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
1. Fork the repository
2. Create a feature branch
3. Commit your changes
4. Push to the branch
5. Create a Pull Request
1. Fork repository
2. Create feature branch
3. Submit pull request
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
## Links
- [Model Context Protocol Documentation](https://modelcontextprotocol.io/introduction)
- [Home Assistant Documentation](https://www.home-assistant.io)
- [Home Assistant REST API](https://developers.home-assistant.io/docs/api/rest)
## Using with LLMs (AI Assistants)
The MCP server is designed to work seamlessly with AI language models. Here's how to interact with your Home Assistant using natural language:
### Natural Language Examples
1. **Discovering Devices**
```
"What devices do I have in my home?"
"Show me all my lights"
"List the climate controls in the bedroom"
```
The LLM will use the `list_devices` tool to fetch and present this information in a human-readable format.
2. **Basic Controls**
```
"Turn on the living room lights"
"Set the bedroom temperature to 22 degrees"
"Close all the blinds"
```
The LLM will translate these commands into appropriate tool calls using the `control` tool.
3. **Complex Operations**
```
"Make the living room cozy for movie night"
→ LLM might:
- Dim the lights (set brightness to 30%)
- Set warm color temperature
- Lower the blinds
- Adjust the temperature
"Set up my morning routine"
→ LLM might:
- Open the bedroom blinds
- Turn on specific lights
- Adjust the thermostat
```
4. **State-Aware Commands**
```
"Is my front door closed?"
"Which lights are currently on?"
"What's the temperature in the bedroom?"
```
The LLM will check current states using `list_devices` before responding.
### Context and Memory
The LLM can maintain context across multiple interactions:
```
User: "How warm is it in the bedroom?"
LLM: [checks temperature] "The bedroom is currently 20°C"
User: "Make it a bit warmer"
LLM: [remembers context, adjusts by reasonable increment] "I'll increase it to 22°C"
```
### Natural Parameter Handling
The LLM can interpret natural language into specific parameters:
```
"Make the lights very dim" → brightness: 10%
"Set a comfortable temperature" → temperature: 21-23°C
"Change the lights to a warm color" → color_temp: ~2700K
```
### Intelligent Error Prevention
The LLM will:
1. Validate commands before execution
2. Check device capabilities
3. Ensure parameters are within acceptable ranges
4. Provide helpful feedback if a command can't be executed
Example:
```
User: "Set the kitchen light to blue"
LLM: [checks if the light supports RGB]
- If supported: Sets rgb_color to [0, 0, 255]
- If not supported: "I'm sorry, but your kitchen light doesn't support color changes. I can only adjust its brightness."
```
### Best Practices for LLM Interactions
1. **Be Specific with Locations**
- Good: "Turn on the kitchen lights"
- Better: "Turn on the lights above the kitchen counter"
2. **Use Natural Increments**
- "Make it a little brighter" → +20% brightness
- "Make it much warmer" → +3-4°C
3. **Group Related Commands**
```
"Set up the living room for watching TV:
- Dim the lights to 20%
- Set them to a warm color
- Lower the blinds
- Set the temperature to 22 degrees"
```
4. **Ask for Confirmation**
```
User: "Turn off all lights"
LLM: "I'll turn off all 12 lights in your home. Would you like me to proceed?"
```
### Handling Complex Scenarios
1. **Conditional Commands**
```
"If the temperature is above 25°C, turn on the fan"
→ LLM will:
1. Check current temperature
2. Execute command if condition is met
```
2. **Time-Based Context**
```
"Set up my evening lighting"
→ LLM considers:
- Time of day
- Current light levels
- User preferences
```
3. **Multi-Room Coordination**
```
"Prepare the house for bedtime"
→ LLM orchestrates:
- Turning off main living area lights
- Dimming hallway lights
- Setting night mode temperatures
- Ensuring doors are locked
```
### Troubleshooting with LLMs
The LLM can help diagnose issues:
```
User: "The living room lights aren't responding"
LLM: Let me check:
1. Verifies device availability
2. Checks current state
3. Reviews recent commands
4. Suggests potential solutions
```
### Security Considerations
1. **Confirmation for Critical Actions**
- The LLM will ask for confirmation before:
- Controlling security devices
- Making large temperature changes
- Executing commands affecting multiple devices
2. **Permission Awareness**
- The LLM respects device permissions
- Provides clear feedback when actions aren't permitted
MIT License - See [LICENSE](LICENSE) file

118
claude_desktop_setup.sh Normal file
View File

@@ -0,0 +1,118 @@
#!/bin/bash
# mcp-setup.sh
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
NC='\033[0m'
echo -e "${BLUE}Setting up MCP Integration for Claude Desktop${NC}"
# Check if Node.js is installed
if ! command -v node &> /dev/null; then
echo -e "${RED}Node.js is not installed. Installing via nvm...${NC}"
# Install nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
# Load nvm
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
# Install Node.js 20.10.0
nvm install 20.10.0
nvm use 20.10.0
else
NODE_VERSION=$(node -v)
if [[ ${NODE_VERSION//v/} < "20.10.0" ]]; then
echo -e "${RED}Node.js version must be 20.10.0 or higher. Current version: $NODE_VERSION${NC}"
exit 1
fi
fi
# Install Brave Search MCP globally
echo -e "${BLUE}Installing Brave Search MCP...${NC}"
npm install -g @modelcontextprotocol/server-brave-search
# Create MCP directory if it doesn't exist
MCP_DIR="$HOME/.mcp"
mkdir -p "$MCP_DIR"
# Clone the Home Assistant MCP repository
echo -e "${BLUE}Cloning Home Assistant MCP repository...${NC}"
git clone https://github.com/jango-blockchained/homeassistant-mcp.git "$MCP_DIR/homeassistant-mcp"
cd "$MCP_DIR/homeassistant-mcp"
# Install dependencies and build
npm install
npm run build
# Prompt for configurations
echo -e "${BLUE}Please enter your configurations:${NC}"
read -p "Home Assistant URL (e.g., http://homeassistant.local:8123): " HASS_HOST
read -p "Home Assistant Long-lived access token: " HASS_TOKEN
read -p "Brave Search API Key: " BRAVE_API_KEY
# Create .env file for Home Assistant
cat > "$MCP_DIR/homeassistant-mcp/.env" << EOL
NODE_ENV=production
HASS_HOST=$HASS_HOST
HASS_TOKEN=$HASS_TOKEN
EOL
# Create Claude Desktop config directory
CLAUDE_CONFIG_DIR="$HOME/Library/Application Support/Claude"
mkdir -p "$CLAUDE_CONFIG_DIR"
# Create combined configuration file
cat > "$CLAUDE_CONFIG_DIR/claude_desktop_config.json" << EOL
{
"mcpServers": {
"homeassistant": {
"command": "node",
"args": [
"$MCP_DIR/homeassistant-mcp/dist/index.js"
],
"env": {
"HASS_TOKEN": "$HASS_TOKEN",
"HASS_HOST": "$HASS_HOST"
}
},
"brave-search": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-brave-search"
],
"env": {
"BRAVE_API_KEY": "$BRAVE_API_KEY"
}
}
}
}
EOL
# Set proper permissions
chmod 600 "$CLAUDE_CONFIG_DIR/claude_desktop_config.json"
chmod 600 "$MCP_DIR/homeassistant-mcp/.env"
echo -e "${GREEN}Installation complete!${NC}"
echo -e "${BLUE}Configuration file created at:${NC} $CLAUDE_CONFIG_DIR/claude_desktop_config.json"
echo -e "${BLUE}To use the integration:${NC}"
echo "1. Make sure Claude Desktop is installed from https://claude.ai/download"
echo "2. Restart Claude Desktop"
echo "3. Both Home Assistant and Brave Search MCP integrations should now be available"
echo -e "${RED}Note: Keep your access tokens and API keys secure and never share them with others${NC}"
# Optional: Test the installations
read -p "Would you like to test the installations? (y/n) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]
then
echo -e "${BLUE}Testing Home Assistant MCP connection...${NC}"
node "$MCP_DIR/homeassistant-mcp/dist/index.js" test
echo -e "${BLUE}Testing Brave Search MCP...${NC}"
npx @modelcontextprotocol/server-brave-search test
fi