advanced-homeassistant-mcp
by: jango-blockchained
An advanced MCP server for Home Assistant. π Batteries included.
πOverview
Purpose: To provide a standardized protocol for AI assistants to interact with Home Assistant, facilitating secure and efficient control of smart home devices.
Overview: The Model Context Protocol (MCP) server serves as an intermediary between AI models (like Claude and GPT) and the Home Assistant platform. It enables AI assistants to execute commands, retrieve home information, manage long-running operations, validate inputs, and standardize error handling, all while maintaining a robust architecture.
Key Features:
-
Modular Architecture: Ensures clean separation of components, facilitating maintenance and scalability.
-
Typed Interface: Fully utilizes TypeScript for enhanced developer experience and type safety.
-
Multiple Transports: Supports standard I/O for CLI integration and HTTP/REST API with streaming via Server-Sent Events.
-
Middleware System: Provides built-in validation, logging, timeout management, and consistent error handling.
-
Built-in Tools: Includes functionalities such as light and climate control, with the ability to expand by adding new tools.
-
Extensible Plugin System: Allows developers to easily integrate additional tools and capabilities.
-
Streaming Responses: Capable of handling long-running operations with real-time updates.
-
Parameter Validation: Ensures data integrity using Zod schemas.
-
AI Integration: Comes pre-equipped with utilities to interface with Claude and Cursor for seamless AI assistant functionality.
Home Assistant Model Context Protocol (MCP)
A standardized protocol for AI assistants to interact with Home Assistant, providing a secure, typed, and extensible interface for controlling smart home devices.
Overview
The Model Context Protocol (MCP) server acts as a bridge between AI models (like Claude, GPT, etc.) and Home Assistant, enabling AI assistants to:
- Execute commands on Home Assistant devices
- Retrieve information about the smart home
- Stream responses for long-running operations
- Validate parameters and inputs
- Provide consistent error handling
Features
- Modular Architecture - Separation between transport, middleware, and tools
- Typed Interface - Fully TypeScript typed for better developer experience
- Multiple Transports:
- Standard I/O (stdin/stdout) for CLI integration
- HTTP/REST API with Server-Sent Events support for streaming
- Middleware System - Validation, logging, timeout, and error handling
- Built-in Tools:
- Light control (brightness, color, etc.)
- Climate control (thermostats, HVAC)
- Extensible Plugin System - Easily add new tools and capabilities
- Streaming Responses - Support for long-running operations
- Parameter Validation - Using Zod schemas
- Claude & Cursor Integration - Ready-made utilities for AI assistants
Getting Started
Prerequisites
- Node.js 16+
- Home Assistant instance (or mock implementations for testing)
Installation
git clone https://github.com/your-repo/homeassistant-mcp.git
cd homeassistant-mcp
npm install
npm run build
Running the Server
# Start with standard I/O transport (for AI assistant integration)
npm start -- --stdio
# Start with HTTP transport (for API access)
npm start -- --http
# Start with both transports
npm start -- --stdio --http
Configuration
Configure the server using environment variables or a .env
file:
PORT=3000
NODE_ENV=development
EXECUTION_TIMEOUT=30000
STREAMING_ENABLED=true
USE_STDIO_TRANSPORT=true
USE_HTTP_TRANSPORT=true
DEBUG_MODE=false
DEBUG_STDIO=false
DEBUG_HTTP=false
SILENT_STARTUP=false
CORS_ORIGIN=*
Architecture
The MCP server uses a layered architecture:
- Transport Layer - Handles communication protocols (stdio, HTTP)
- Middleware Layer - Processes requests through a pipeline
- Tool Layer - Implements specific functionality
- Resource Layer - Manages stateful resources
Tools
Tools add functionality to the MCP server. Each tool:
- Has a unique name
- Accepts typed parameters
- Returns typed results
- Can stream partial results
- Validates inputs and outputs
Example tool registration:
import { LightsControlTool } from "./tools/homeassistant/lights.tool.js";
import { ClimateControlTool } from "./tools/homeassistant/climate.tool.js";
server.registerTool(new LightsControlTool());
server.registerTool(new ClimateControlTool());
API (HTTP Transport)
POST /api/mcp/jsonrpc
- Execute a toolGET /api/mcp/stream
- SSE stream for real-time updatesGET /api/mcp/info
- Server informationGET /health
- Health check endpoint
Integration with AI Models
Claude Integration
import { createClaudeToolDefinitions } from "./mcp/index.js";
const claudeTools = createClaudeToolDefinitions([
new LightsControlTool(),
new ClimateControlTool()
]);
const messages = [
{ role: "user", content: "Turn on the lights in the living room" }
];
const response = await claude.messages.create({
model: "claude-3-opus-20240229",
messages,
tools: claudeTools
});
Cursor Integration
Add to your .cursor/config/config.json
:
{
"mcpServers": {
"homeassistant-mcp": {
"command": "bash",
"args": ["-c", "cd ${workspaceRoot} && bun run dist/index.js --stdio 2>/dev/null | grep -E '\\{\"jsonrpc\":\"2\\.0\"'"],
"env": {
"NODE_ENV": "development",
"USE_STDIO_TRANSPORT": "true",
"DEBUG_STDIO": "true"
}
}
}
}
This runs the MCP server with stdio transport and filters stdout to ensure clean JSON-RPC output.
Troubleshooting Cursor Integration
If you see "failed to create client" error:
-
Verify your Cursor command uses the bash script with grep as above.
-
Ensure the server is built (
bun run build
) before connecting. -
Confirm JSON-RPC messages are output correctly by running:
bun run dist/index.js --stdio 2>/dev/null | grep -E '\{"jsonrpc":"2\.0"' > json_only.txt
-
Check
json_only.txt
for valid JSON-RPC messages. -
Confirm
grep
is installed on your system. -
Enable debug mode by setting
DEBUG_STDIO=true
. -
Restart Cursor or clear its cache if needed.
You can also try a Node.js based command:
{
"command": "bash",
"args": ["-c", "cd ${workspaceRoot} && node dist/index.js --stdio 2>/dev/null | grep -E '\\{\"jsonrpc\":\"2\\.0\"'"]
}
MCP Server for Home Assistant
MCP Server is a lightweight integration tool providing a flexible interface for device management and automation, built with Bun for performance.
Core Features
- Basic device control via REST API
- WebSocket/Server-Sent Events (SSE) for state updates
- Simple automation rule management
- JWT-based authentication
- Standard I/O (stdio) transport for AI assistant integration
Why Bun?
- Blazing fast performance (up to 4x faster than Node.js)
- Built-in TypeScript support, package manager, bundler, test runner
- SQLite3 support and .env loading
- Low memory usage and fast start times
- High Node.js compatibility
Prerequisites
- Bun runtime (v1.0.26+)
- Home Assistant instance
- Docker (optional)
- Node.js 18+ (optional for speech features)
- NVIDIA GPU with CUDA (optional for faster speech)
Quick Start
git clone https://github.com/jango-blockchained/homeassistant-mcp.git
cd homeassistant-mcp
chmod +x scripts/setup-env.sh
./scripts/setup-env.sh
# For production environment
NODE_ENV=production ./scripts/setup-env.sh
# Force override
./scripts/setup-env.sh --force
# Build and launch Docker container:
./docker-build.sh
docker compose up -d
Docker Build Options
- Standard build: basic MCP server with REST and WebSocket support
- Speech-enabled build with wake word detection and speech-to-text
- GPU-accelerated build for faster speech processing
Environment Configuration
Files load in this order with later overriding earlier:
.env
- base config.env.dev
/.env.prod
/.env.test
based onNODE_ENV
Development
bun install
bun run dev
bun test
bun --hot run dev
bun build ./src/index.ts --target=bun
bun run start
Client Integration
Cursor
Configure .cursor/config/config.json
as shown above in Cursor Integration.
Claude Desktop
Configure Claude Desktop to use the MCP server command.
Command Line
Windows users can use script scripts/start_mcp.cmd
.
Speech Features (Optional)
Supports:
- Wake word detection ("hey jarvis", "ok google", "alexa")
- Speech-to-text with fast-whisper
- Multi-language support
- GPU acceleration
Prerequisites:
- Docker running
- NVIDIA GPU with CUDA recommended
- Minimum 4GB RAM
Configuration via .env
environment variables.
Extra Tools Included
- Home Assistant Analyzer CLI: automation analysis, security scanning
- Speech-to-Text example with wake word detection
- Claude Desktop setup automation script
License
MIT License.
Running with Standard I/O Transport
Supports JSON-RPC 2.0 stdio mode for AI assistant integration (Claude, etc).
Features
- JSON-RPC 2.0 compatible
- NPX support (run without install)
- Auto configuration and directory creation
- Cross-platform
- Parameter validation via schemas
- Standardized error handling
- Detailed log files (not polluting stdio)
Option 1: Using NPX (Easiest)
npx homeassistant-mcp
# With environment variables:
HASS_URL=http://your-ha-instance:8123 HASS_TOKEN=your_token npx homeassistant-mcp
Option 2: Local Installation
Edit .env
:
USE_STDIO_TRANSPORT=true
Run:
./stdio-start.sh
# Options:
./stdio-start.sh --debug
./stdio-start.sh --rebuild
./stdio-start.sh --help
Behavior in stdio mode
- Communicates over stdin/stdout JSON-RPC 2.0 format
- No HTTP server started
- Console logging disabled (logs written to
logs/
folder)
JSON-RPC 2.0 Message Format
Request
{
"jsonrpc": "2.0",
"id": "unique-request-id",
"method": "tool-name",
"params": {
"param1": "value1",
"param2": "value2"
}
}
Response
{
"jsonrpc": "2.0",
"id": "unique-request-id",
"result": {
// Tool-specific data
}
}
Error Response
{
"jsonrpc": "2.0",
"id": "unique-request-id",
"error": {
"code": -32000,
"message": "Error message",
"data": {}
}
}
Notification (server to client)
{
"jsonrpc": "2.0",
"method": "notification-type",
"params": {
// Notification data
}
}
Supported Error Codes
Code | Description |
---|---|
-32700 | Parse error |
-32600 | Invalid request |
-32601 | Method not found |
-32602 | Invalid params |
-32603 | Internal error |
-32000 | Tool execution |
-32001 | Validation error |
Using MCP Server with Claude Desktop
To configure Claude Desktop with MCP server:
- Create or edit configuration:
# macOS
nano ~/Library/Application\ Support/Claude/claude_desktop_config.json
# Linux
nano ~/.config/Claude/claude_desktop_config.json
# Windows
notepad %APPDATA%\Claude\claude_desktop_config.json
- Add MCP server entry:
{
"mcpServers": {
"homeassistant-mcp": {
"command": "npx",
"args": ["homeassistant-mcp"],
"env": {
"HASS_TOKEN": "your_home_assistant_token_here",
"HASS_HOST": "http://your_home_assistant_host:8123"
}
}
}
}
- Restart Claude Desktop.
Claude now integrates with the Home Assistant MCP server for controlling smart devices.
Usage Summary
NPX usage (easiest)
npx homeassistant-mcp
Outputs JSON-RPC messages on stdout, logs on stderr, creates logs directory automatically.
To suppress logs:
npx homeassistant-mcp 2>/dev/null
Install Globally or Locally
npm install -g homeassistant-mcp
homeassistant-mcp
or
npm install homeassistant-mcp
npx homeassistant-mcp