HomeAssistant MCP

hybrid server

The server is able to function both locally and remotely, depending on the configuration or use case.

Integrations

  • Provides a flexible interface for Home Assistant device management and automation through a REST API and WebSocket/SSE connections, enabling basic device control, state updates, and automation rule management.

  • Enables GPU-accelerated speech processing capabilities when using NVIDIA GPUs with CUDA support, improving performance for wake word detection and speech-to-text features.

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 - Clean 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)
    • More to come...
  • 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 you can use the mock implementations for testing)

Installation

# Clone the repository git clone https://github.com/your-repo/homeassistant-mcp.git # Install dependencies cd homeassistant-mcp npm install # Build the project 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:

# Server configuration PORT=3000 NODE_ENV=development # Execution settings EXECUTION_TIMEOUT=30000 STREAMING_ENABLED=true # Transport settings USE_STDIO_TRANSPORT=true USE_HTTP_TRANSPORT=true # Debug and logging DEBUG_MODE=false DEBUG_STDIO=false DEBUG_HTTP=false SILENT_STARTUP=false # CORS settings CORS_ORIGIN=*

Architecture

The MCP server is built with a layered architecture:

  1. Transport Layer - Handles communication protocols (stdio, HTTP)
  2. Middleware Layer - Processes requests through a pipeline
  3. Tool Layer - Implements specific functionality
  4. Resource Layer - Manages stateful resources

Tools

Tools are the primary way to 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"; // Register tools server.registerTool(new LightsControlTool()); server.registerTool(new ClimateControlTool());

API

When running with HTTP transport, the server provides a JSON-RPC 2.0 API:

  • POST /api/mcp/jsonrpc - Execute a tool
  • GET /api/mcp/stream - Connect to SSE stream for real-time updates
  • GET /api/mcp/info - Get server information
  • GET /health - Health check endpoint

Integration with AI Models

Claude Integration

import { createClaudeToolDefinitions } from "./mcp/index.js"; // Generate Claude-compatible tool definitions const claudeTools = createClaudeToolDefinitions([ new LightsControlTool(), new ClimateControlTool() ]); // Use with Claude API 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

To use the Home Assistant MCP server with Cursor, add the following to your .cursor/config/config.json file:

{ "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 configuration:

  1. Runs the MCP server with stdio transport
  2. Redirects all stderr output to /dev/null
  3. Uses grep to filter stdout for lines containing {"jsonrpc":"2.0", ensuring clean JSON-RPC output

Troubleshooting Cursor Integration

If you encounter a "failed to create client" error when using the MCP server with Cursor:

  1. Make sure you're using the correct command and arguments in your Cursor configuration
    • The bash script approach ensures only valid JSON-RPC messages reach Cursor
    • Ensure the server is built by running bun run build before trying to connect
  2. Ensure the server is properly outputting JSON-RPC messages to stdout:
    bun run dist/index.js --stdio 2>/dev/null | grep -E '\{"jsonrpc":"2\.0"' > json_only.txt
    Then examine json_only.txt to verify it contains only valid JSON-RPC messages.
  3. Make sure grep is installed on your system (it should be available by default on most systems)
  4. Try rebuilding the server with:
    bun run build
  5. Enable debug mode by setting DEBUG_STDIO=true in the environment variables

If the issue persists, you can try:

  1. Restarting Cursor
  2. Clearing Cursor's cache (Help > Developer > Clear Cache and Reload)
  3. Using a similar approach with Node.js:
    { "command": "bash", "args": ["-c", "cd ${workspaceRoot} && node dist/index.js --stdio 2>/dev/null | grep -E '\\{\"jsonrpc\":\"2\\.0\"'"] }

License

MIT

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

MCP Server for Home Assistant ๐Ÿ ๐Ÿค–

Overview ๐ŸŒ

MCP (Model Context Protocol) Server is my lightweight integration tool for Home Assistant, providing a flexible interface for device management and automation. It's designed to be fast, secure, and easy to use. Built with Bun for maximum 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 integration with Claude and other AI assistants

Why Bun? ๐Ÿš€

I chose Bun as the runtime for several key benefits:

  • โšก Blazing Fast Performance
    • Up to 4x faster than Node.js
    • Built-in TypeScript support
    • Optimized file system operations
  • ๐ŸŽฏ All-in-One Solution
    • Package manager (faster than npm/yarn)
    • Bundler (no webpack needed)
    • Test runner (built-in testing)
    • TypeScript transpiler
  • ๐Ÿ”‹ Built-in Features
    • SQLite3 driver
    • .env file loading
    • WebSocket client/server
    • File watcher
    • Test runner
  • ๐Ÿ’พ Resource Efficient
    • Lower memory usage
    • Faster cold starts
    • Better CPU utilization
  • ๐Ÿ”„ Node.js Compatibility
    • Runs most npm packages
    • Compatible with Express/Fastify
    • Native Node.js APIs

Prerequisites ๐Ÿ“‹

  • ๐Ÿš€ Bun runtime (v1.0.26+)
  • ๐Ÿก Home Assistant instance
  • ๐Ÿณ Docker (optional, recommended for deployment)
  • ๐Ÿ–ฅ๏ธ Node.js 18+ (optional, for speech features)
  • ๐ŸŽฎ NVIDIA GPU with CUDA support (optional, for faster speech processing)

Quick Start ๐Ÿš€

  1. Clone my repository:
git clone https://github.com/jango-blockchained/homeassistant-mcp.git cd homeassistant-mcp
  1. Set up the environment:
# Make my setup script executable chmod +x scripts/setup-env.sh # Run setup (defaults to development) ./scripts/setup-env.sh # Or specify an environment: NODE_ENV=production ./scripts/setup-env.sh # Force override existing files: ./scripts/setup-env.sh --force
  1. Configure your settings:
  • Edit .env file with your Home Assistant details
  • Required: Add your HASS_TOKEN (long-lived access token)
  1. Build and launch with Docker:
# Standard build ./docker-build.sh # Launch: docker compose up -d

Docker Build Options ๐Ÿณ

My Docker build script (docker-build.sh) supports different configurations:

1. Standard Build

./docker-build.sh
  • Basic MCP server functionality
  • REST API and WebSocket support
  • No speech features

2. Speech-Enabled Build

./docker-build.sh --speech
  • Includes wake word detection
  • Speech-to-text capabilities
  • Pulls required images:
    • onerahmet/openai-whisper-asr-webservice
    • rhasspy/wyoming-openwakeword

3. GPU-Accelerated Build

./docker-build.sh --speech --gpu
  • All speech features
  • CUDA GPU acceleration
  • Optimized for faster processing
  • Float16 compute type for better performance

Build Features

  • ๐Ÿ”„ Automatic resource allocation
  • ๐Ÿ’พ Memory-aware building
  • ๐Ÿ“Š CPU quota management
  • ๐Ÿงน Automatic cleanup
  • ๐Ÿ“ Detailed build logs
  • ๐Ÿ“Š Build summary and status

Environment Configuration ๐Ÿ”ง

I've implemented a hierarchical configuration system:

File Structure ๐Ÿ“

  1. .env.example - My template with all options
  2. .env - Your configuration (copy from .env.example)
  3. Environment overrides:
    • .env.dev - Development settings
    • .env.prod - Production settings
    • .env.test - Test settings

Loading Priority โšก

Files load in this order:

  1. .env (base config)
  2. Environment-specific file:
    • NODE_ENV=development โ†’ .env.dev
    • NODE_ENV=production โ†’ .env.prod
    • NODE_ENV=test โ†’ .env.test

Later files override earlier ones.

Development ๐Ÿ’ป

# Install dependencies bun install # Run in development mode bun run dev # Run tests bun test # Run with hot reload bun --hot run dev # Build for production bun build ./src/index.ts --target=bun # Run production build bun run start

Performance Comparison ๐Ÿ“Š

OperationBunNode.js
Install Dependencies~2s~15s
Cold Start300ms1000ms
Build Time150ms4000ms
Memory Usage~150MB~400MB

Documentation ๐Ÿ“š

Core Documentation

Advanced Features

Client Integration ๐Ÿ”—

Cursor Integration ๐Ÿ–ฑ๏ธ

Add to .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" } } } }

Claude Desktop ๐Ÿ’ฌ

Add to your Claude config:

{ "mcpServers": { "homeassistant-mcp": { "command": "bun", "args": ["run", "start", "--port", "8080"], "env": { "NODE_ENV": "production" } } } }

Command Line ๐Ÿ’ป

Windows users can use the provided script:

  1. Go to scripts directory
  2. Run start_mcp.cmd

Additional Features

Speech Features ๐ŸŽค

MCP Server optionally supports speech processing capabilities:

  • ๐Ÿ—ฃ๏ธ Wake word detection ("hey jarvis", "ok google", "alexa")
  • ๐ŸŽฏ Speech-to-text using fast-whisper
  • ๐ŸŒ Multiple language support
  • ๐Ÿš€ GPU acceleration support

Speech Features Setup

Prerequisites
  1. ๐Ÿณ Docker installed and running
  2. ๐ŸŽฎ NVIDIA GPU with CUDA (optional)
  3. ๐Ÿ’พ 4GB+ RAM (8GB+ recommended)
Configuration
  1. Enable speech in .env:
ENABLE_SPEECH_FEATURES=true ENABLE_WAKE_WORD=true ENABLE_SPEECH_TO_TEXT=true WHISPER_MODEL_PATH=/models WHISPER_MODEL_TYPE=base
  1. Choose your STT engine:
# For standard Whisper STT_ENGINE=whisper # For Fast Whisper (GPU recommended) STT_ENGINE=fast-whisper CUDA_VISIBLE_DEVICES=0 # Set GPU device
Available Models ๐Ÿค–

Choose based on your needs:

  • tiny.en: Fastest, basic accuracy
  • base.en: Good balance (recommended)
  • small.en: Better accuracy, slower
  • medium.en: High accuracy, resource intensive
  • large-v2: Best accuracy, very resource intensive
Launch with Speech Features
# Build with speech support ./docker-build.sh --speech # Launch with speech features: docker compose -f docker-compose.yml -f docker-compose.speech.yml up -d

Extra Tools ๐Ÿ› ๏ธ

I've included several powerful tools in the extra/ directory to enhance your Home Assistant experience:

  1. Home Assistant Analyzer CLI (ha-analyzer-cli.ts)
    • Deep automation analysis using AI models
    • Security vulnerability scanning
    • Performance optimization suggestions
    • System health metrics
  2. Speech-to-Text Example (speech-to-text-example.ts)
    • Wake word detection
    • Speech-to-text transcription
    • Multiple language support
    • GPU acceleration support
  3. Claude Desktop Setup (claude-desktop-macos-setup.sh)
    • Automated Claude Desktop installation for macOS
    • Environment configuration
    • MCP integration setup

See Extras Documentation for detailed usage instructions and examples.

License ๐Ÿ“„

MIT License. See LICENSE for details.

Author ๐Ÿ‘จโ€๐Ÿ’ป

Created by jango-blockchained

Running with Standard I/O Transport ๐Ÿ“

MCP Server supports a JSON-RPC 2.0 stdio transport mode for direct integration with AI assistants like Claude:

MCP Stdio Features

โœ… JSON-RPC 2.0 Compatibility: Full support for the MCP protocol standard
โœ… NPX Support: Run directly without installation using npx homeassistant-mcp
โœ… Auto Configuration: Creates necessary directories and default configuration
โœ… Cross-Platform: Works on macOS, Linux, and Windows
โœ… Claude Desktop Integration: Ready to use with Claude Desktop
โœ… Parameter Validation: Automatic validation of tool parameters
โœ… Error Handling: Standardized error codes and handling
โœ… Detailed Logging: Logs to files without polluting stdio

Option 1: Using NPX (Easiest)

Run the MCP server directly without installation using npx:

# Basic usage npx homeassistant-mcp # Or with environment variables HASS_URL=http://your-ha-instance:8123 HASS_TOKEN=your_token npx homeassistant-mcp

This will:

  1. Install the package temporarily
  2. Automatically run in stdio mode with JSON-RPC 2.0 transport
  3. Create a logs directory for logging
  4. Create a default .env file if not present

Perfect for integration with Claude Desktop or other MCP clients.

Integrating with Claude Desktop

To use MCP with Claude Desktop:

  1. Open Claude Desktop settings
  2. Go to the "Advanced" tab
  3. Under "MCP Server", select "Custom"
  4. Enter the command: npx homeassistant-mcp
  5. Click "Save"

Claude will now use the MCP server for Home Assistant integration, allowing you to control your smart home directly through Claude.

Option 2: Local Installation

  1. Update your .env file to enable stdio transport:
    USE_STDIO_TRANSPORT=true
  2. Run the server using the stdio-start script:
    ./stdio-start.sh
    Available options:
    ./stdio-start.sh --debug # Enable debug mode ./stdio-start.sh --rebuild # Force rebuild ./stdio-start.sh --help # Show help

When running in stdio mode:

  • The server communicates via stdin/stdout using JSON-RPC 2.0 format
  • No HTTP server is started
  • Console logging is disabled to avoid polluting the stdio stream
  • All logs are written to the log files in the logs/ directory

JSON-RPC 2.0 Message Format

Request Format

{ "jsonrpc": "2.0", "id": "unique-request-id", "method": "tool-name", "params": { "param1": "value1", "param2": "value2" } }

Response Format

{ "jsonrpc": "2.0", "id": "unique-request-id", "result": { // Tool-specific result data } }

Error Response Format

{ "jsonrpc": "2.0", "id": "unique-request-id", "error": { "code": -32000, "message": "Error message", "data": {} // Optional error details } }

Notification Format (Server to Client)

{ "jsonrpc": "2.0", "method": "notification-type", "params": { // Notification data } }

Supported Error Codes

CodeDescriptionMeaning
-32700Parse errorInvalid JSON was received
-32600Invalid requestJSON is not a valid request object
-32601Method not foundMethod does not exist or is unavailable
-32602Invalid paramsInvalid method parameters
-32603Internal errorInternal JSON-RPC error
-32000Tool executionError executing the tool
-32001Validation errorParameter validation failed

Integrating with Claude Desktop

To use this MCP server with Claude Desktop:

  1. Create or edit your Claude Desktop configuration:
    # On macOS nano ~/Library/Application\ Support/Claude/claude_desktop_config.json # On Linux nano ~/.config/Claude/claude_desktop_config.json # On Windows notepad %APPDATA%\Claude\claude_desktop_config.json
  2. Add the MCP server configuration:
    { "mcpServers": { "homeassistant-mcp": { "command": "npx", "args": ["homeassistant-mcp"], "env": { "HASS_TOKEN": "your_home_assistant_token_here", "HASS_HOST": "http://your_home_assistant_host:8123" } } } }
  3. Restart Claude Desktop.
  4. In Claude, you can now use the Home Assistant MCP tools.

JSON-RPC 2.0 Message Format

Usage

Using NPX (Easiest)

The simplest way to use the Home Assistant MCP server is through NPX:

# Start the server in stdio mode npx homeassistant-mcp

This will automatically:

  1. Start the server in stdio mode
  2. Output JSON-RPC messages to stdout
  3. Send log messages to stderr
  4. Create a logs directory if it doesn't exist

You can redirect stderr to hide logs and only see the JSON-RPC output:

npx homeassistant-mcp 2>/dev/null

Manual Installation

If you prefer to install the package globally or locally:

# Install globally npm install -g homeassistant-mcp # Then run homeassistant-mcp

Or install locally:

# Install locally npm install homeassistant-mcp # Then run using npx npx homeassistant-mcp

Advanced Usage

-
security - not tested
A
license - permissive license
-
quality - not tested

Smart Device Control ๐ŸŽฎ ๐Ÿ’ก Lights: Brightness, color, RGB ๐ŸŒก๏ธ Climate: Temperature, HVAC, humidity ๐Ÿšช Covers: Position and tilt ๐Ÿ”Œ Switches: On/off ๐Ÿšจ Sensors: State monitoring

Intelligent Organization ๐Ÿ  Grouping with context awareness.

Robust Architecture ๐Ÿ› ๏ธ Error handling, state validation ...

  1. Overview
    1. Features
      1. Getting Started
        1. Prerequisites
        2. Installation
        3. Running the Server
        4. Configuration
      2. Architecture
        1. Tools
        2. API
      3. Integration with AI Models
        1. Claude Integration
        2. Cursor Integration
      4. License
        1. Contributing
          1. MCP Server for Home Assistant ๐Ÿ ๐Ÿค–
            1. Overview ๐ŸŒ
            2. Core Features โœจ
            3. Why Bun? ๐Ÿš€
            4. Prerequisites ๐Ÿ“‹
            5. Quick Start ๐Ÿš€
            6. Docker Build Options ๐Ÿณ
            7. Environment Configuration ๐Ÿ”ง
            8. Development ๐Ÿ’ป
            9. Documentation ๐Ÿ“š
            10. Client Integration ๐Ÿ”—
            11. Additional Features
            12. License ๐Ÿ“„
            13. Author ๐Ÿ‘จโ€๐Ÿ’ป
            14. Running with Standard I/O Transport ๐Ÿ“
            15. Usage