From 0320223593dc5918a6939da22be2097f7ef89a54 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Thu, 6 Feb 2025 03:40:45 +0000 Subject: [PATCH] Deployed cc9eede with MkDocs version: 1.6.1 --- configuration.html | 77 +++++++++++++++++++++++++++++++++------ features/speech.html | 52 ++++++++++++++++++++++++++ search/search_index.js | 2 +- search/search_index.json | 2 +- sitemap.xml | 4 ++ sitemap.xml.gz | Bin 538 -> 553 bytes 6 files changed, 123 insertions(+), 14 deletions(-) create mode 100644 features/speech.html diff --git a/configuration.html b/configuration.html index 01415b4..3f67eca 100644 --- a/configuration.html +++ b/configuration.html @@ -1,10 +1,10 @@ - System Configuration - MCP Server for Home Assistant
Skip to content

System Configuration

This document provides detailed information about configuring the Home Assistant MCP Server.

Configuration File Structure

The MCP Server uses environment variables for configuration, with support for different environments (development, test, production):

# .env, .env.development, or .env.test
+ System Configuration - MCP Server for Home Assistant      

System Configuration

This document provides detailed information about configuring the Home Assistant MCP Server.

Configuration File Structure

The MCP Server uses environment variables for configuration, with support for different environments (development, test, production):

# .env, .env.development, or .env.test
 PORT=4000
 NODE_ENV=development
 HASS_HOST=http://192.168.178.63:8123
 HASS_TOKEN=your_token_here
 JWT_SECRET=your_secret_key
-

Server Settings

Basic Server Configuration

  • PORT: Server port number (default: 4000)
  • NODE_ENV: Environment mode (development, production, test)
  • HASS_HOST: Home Assistant instance URL
  • HASS_TOKEN: Home Assistant long-lived access token

Security Settings

  • JWT_SECRET: Secret key for JWT token generation
  • RATE_LIMIT: Rate limiting configuration
  • windowMs: Time window in milliseconds (default: 15 minutes)
  • max: Maximum requests per window (default: 100)

WebSocket Settings

  • SSE: Server-Sent Events configuration
  • MAX_CLIENTS: Maximum concurrent clients (default: 1000)
  • PING_INTERVAL: Keep-alive ping interval in ms (default: 30000)

Environment Variables

All configuration is managed through environment variables:

# Server
+

Server Settings

Basic Server Configuration

  • PORT: Server port number (default: 4000)
  • NODE_ENV: Environment mode (development, production, test)
  • HASS_HOST: Home Assistant instance URL
  • HASS_TOKEN: Home Assistant long-lived access token

Security Settings

  • JWT_SECRET: Secret key for JWT token generation
  • RATE_LIMIT: Rate limiting configuration
  • windowMs: Time window in milliseconds (default: 15 minutes)
  • max: Maximum requests per window (default: 100)

WebSocket Settings

  • SSE: Server-Sent Events configuration
  • MAX_CLIENTS: Maximum concurrent clients (default: 1000)
  • PING_INTERVAL: Keep-alive ping interval in ms (default: 30000)

Speech Features (Optional)

  • ENABLE_SPEECH_FEATURES: Enable speech processing features (default: false)
  • ENABLE_WAKE_WORD: Enable wake word detection (default: false)
  • ENABLE_SPEECH_TO_TEXT: Enable speech-to-text conversion (default: false)
  • WHISPER_MODEL_PATH: Path to Whisper models directory (default: /models)
  • WHISPER_MODEL_TYPE: Whisper model type (default: base)
  • Available models: tiny.en, base.en, small.en, medium.en, large-v2

Environment Variables

All configuration is managed through environment variables:

# Server
 PORT=4000
 NODE_ENV=development
 
@@ -22,6 +22,13 @@
 LOG_MAX_DAYS=14d
 LOG_COMPRESS=true
 LOG_REQUESTS=true
+
+# Speech Features (Optional)
+ENABLE_SPEECH_FEATURES=false
+ENABLE_WAKE_WORD=false
+ENABLE_SPEECH_TO_TEXT=false
+WHISPER_MODEL_PATH=/models
+WHISPER_MODEL_TYPE=base
 

Advanced Configuration

Security Rate Limiting

Rate limiting is enabled by default to protect against brute force attacks:

RATE_LIMIT: {
   windowMs: 15 * 60 * 1000,  // 15 minutes
   max: 100  // limit each IP to 100 requests per window
@@ -35,13 +42,59 @@
   TIMESTAMP_FORMAT: "YYYY-MM-DD HH:mm:ss:ms",
   LOG_REQUESTS: true
 }
-

For production deployments, we recommend using system tools like logrotate for log management.

Example logrotate configuration (/etc/logrotate.d/mcp-server):

/var/log/mcp-server.log {
-    daily
-    rotate 7
-    compress
-    delaycompress
-    missingok
-    notifempty
-    create 644 mcp mcp
-}
-

Best Practices

  1. Always use environment variables for sensitive information
  2. Keep .env files secure and never commit them to version control
  3. Use different environment files for development, test, and production
  4. Enable SSL/TLS in production (preferably via reverse proxy)
  5. Monitor log files for issues
  6. Regularly rotate logs in production

Validation

The server validates configuration on startup using Zod schemas: - Required fields are checked (e.g., HASS_TOKEN) - Value types are verified - Enums are validated (e.g., LOG_LEVEL) - Default values are applied when not specified

Troubleshooting

Common configuration issues: 1. Missing required environment variables 2. Invalid environment variable values 3. Permission issues with log directories 4. Rate limiting too restrictive

See the Troubleshooting Guide for solutions.

\ No newline at end of file +

Speech-to-Text Configuration

When speech features are enabled, you can configure the following options:

SPEECH: {
+  ENABLED: false,  // Master switch for all speech features
+  WAKE_WORD_ENABLED: false,  // Enable wake word detection
+  SPEECH_TO_TEXT_ENABLED: false,  // Enable speech-to-text
+  WHISPER_MODEL_PATH: "/models",  // Path to Whisper models
+  WHISPER_MODEL_TYPE: "base",  // Model type to use
+}
+

Available Whisper models: - tiny.en: Fastest, lowest accuracy - base.en: Good balance of speed and accuracy - small.en: Better accuracy, slower - medium.en: High accuracy, much slower - large-v2: Best accuracy, very slow

For production deployments, we recommend using system tools like logrotate for log management.

Example logrotate configuration (/etc/logrotate.d/mcp-server):

/var/log/mcp-server.log {
+    daily
+    rotate 7
+    compress
+    delaycompress
+    missingok
+    notifempty
+    create 644 mcp mcp
+}
+

Best Practices

  1. Always use environment variables for sensitive information
  2. Keep .env files secure and never commit them to version control
  3. Use different environment files for development, test, and production
  4. Enable SSL/TLS in production (preferably via reverse proxy)
  5. Monitor log files for issues
  6. Regularly rotate logs in production
  7. Start with smaller Whisper models and upgrade if needed
  8. Consider GPU acceleration for larger Whisper models

Validation

The server validates configuration on startup using Zod schemas: - Required fields are checked (e.g., HASS_TOKEN) - Value types are verified - Enums are validated (e.g., LOG_LEVEL, WHISPER_MODEL_TYPE) - Default values are applied when not specified

Troubleshooting

Common configuration issues: 1. Missing required environment variables 2. Invalid environment variable values 3. Permission issues with log directories 4. Rate limiting too restrictive 5. Speech model loading failures 6. Docker not available for speech features 7. Insufficient system resources for larger models

See the Troubleshooting Guide for solutions.

Configuration Guide

This document describes all available configuration options for the Home Assistant MCP Server.

Environment Variables

Required Settings

# Server Configuration
+PORT=3000                      # Server port
+HOST=localhost                 # Server host
+
+# Home Assistant
+HASS_URL=http://localhost:8123 # Home Assistant URL
+HASS_TOKEN=your_token         # Long-lived access token
+
+# Security
+JWT_SECRET=your_secret        # JWT signing secret
+

Optional Settings

# Rate Limiting
+RATE_LIMIT_WINDOW=60000       # Time window in ms (default: 60000)
+RATE_LIMIT_MAX=100           # Max requests per window (default: 100)
+
+# Logging
+LOG_LEVEL=info               # debug, info, warn, error (default: info)
+LOG_DIR=logs                 # Log directory (default: logs)
+LOG_MAX_SIZE=10m            # Max log file size (default: 10m)
+LOG_MAX_FILES=5             # Max number of log files (default: 5)
+
+# WebSocket/SSE
+WS_HEARTBEAT=30000          # WebSocket heartbeat interval in ms (default: 30000)
+SSE_RETRY=3000             # SSE retry interval in ms (default: 3000)
+
+# Speech Features
+ENABLE_SPEECH_FEATURES=false # Enable speech processing (default: false)
+ENABLE_WAKE_WORD=false      # Enable wake word detection (default: false)
+ENABLE_SPEECH_TO_TEXT=false # Enable speech-to-text (default: false)
+
+# Speech Model Configuration
+WHISPER_MODEL_PATH=/models  # Path to whisper models (default: /models)
+WHISPER_MODEL_TYPE=base     # Model type: tiny|base|small|medium|large-v2 (default: base)
+WHISPER_LANGUAGE=en        # Primary language (default: en)
+WHISPER_TASK=transcribe    # Task type: transcribe|translate (default: transcribe)
+WHISPER_DEVICE=cuda        # Processing device: cpu|cuda (default: cuda if available, else cpu)
+
+# Wake Word Configuration
+WAKE_WORDS=hey jarvis,ok google,alexa  # Comma-separated wake words (default: hey jarvis)
+WAKE_WORD_SENSITIVITY=0.5   # Detection sensitivity 0-1 (default: 0.5)
+

Speech Features

Model Selection

Choose a model based on your needs:

Model Size Memory Required Speed Accuracy
tiny.en 75MB 1GB Fast Basic
base.en 150MB 2GB Good Good
small.en 500MB 4GB Med Better
medium.en 1.5GB 8GB Slow High
large-v2 3GB 16GB Slow Best

GPU Acceleration

When WHISPER_DEVICE=cuda: - NVIDIA GPU with CUDA support required - Significantly faster processing - Higher memory requirements

Wake Word Detection

  • Multiple wake words supported via comma-separated list
  • Adjustable sensitivity (0-1):
  • Lower values: Fewer false positives, may miss some triggers
  • Higher values: More responsive, may have false triggers
  • Default (0.5): Balanced detection

Best Practices

  1. Model Selection:
  2. Start with base.en model
  3. Upgrade if better accuracy needed
  4. Downgrade if performance issues

  5. Resource Management:

  6. Monitor memory usage
  7. Use GPU acceleration when available
  8. Consider model size vs available resources

  9. Wake Word Configuration:

  10. Use distinct wake words
  11. Adjust sensitivity based on environment
  12. Limit number of wake words for better performance
\ No newline at end of file diff --git a/features/speech.html b/features/speech.html new file mode 100644 index 0000000..6087a47 --- /dev/null +++ b/features/speech.html @@ -0,0 +1,52 @@ + Speech Features - MCP Server for Home Assistant
Skip to content

Speech Features

The Home Assistant MCP Server includes powerful speech processing capabilities powered by fast-whisper and custom wake word detection. This guide explains how to set up and use these features effectively.

Overview

The speech processing system consists of two main components: 1. Wake Word Detection - Listens for specific trigger phrases 2. Speech-to-Text - Transcribes spoken commands using fast-whisper

Setup

Prerequisites

  1. Docker environment:

    docker --version  # Should be 20.10.0 or higher
    +

  2. For GPU acceleration:

  3. NVIDIA GPU with CUDA support
  4. NVIDIA Container Toolkit installed
  5. NVIDIA drivers 450.80.02 or higher

Installation

  1. Enable speech features in your .env:

    ENABLE_SPEECH_FEATURES=true
    +ENABLE_WAKE_WORD=true
    +ENABLE_SPEECH_TO_TEXT=true
    +

  2. Configure model settings:

    WHISPER_MODEL_PATH=/models
    +WHISPER_MODEL_TYPE=base
    +WHISPER_LANGUAGE=en
    +WHISPER_TASK=transcribe
    +WHISPER_DEVICE=cuda  # or cpu
    +

  3. Start the services:

    docker-compose up -d
    +

Usage

Wake Word Detection

The wake word detector continuously listens for configured trigger phrases. Default wake words: - "hey jarvis" - "ok google" - "alexa"

Custom wake words can be configured:

WAKE_WORDS=computer,jarvis,assistant
+

When a wake word is detected: 1. The system starts recording audio 2. Audio is processed through the speech-to-text pipeline 3. The resulting command is processed by the server

Speech-to-Text

Automatic Transcription

After wake word detection: 1. Audio is automatically captured (default: 5 seconds) 2. The audio is transcribed using the configured whisper model 3. The transcribed text is processed as a command

Manual Transcription

You can also manually transcribe audio using the API:

// Using the TypeScript client
+import { SpeechService } from '@ha-mcp/client';
+
+const speech = new SpeechService();
+
+// Transcribe from audio buffer
+const buffer = await getAudioBuffer();
+const text = await speech.transcribe(buffer);
+
+// Transcribe from file
+const text = await speech.transcribeFile('command.wav');
+
// Using the REST API
+POST /api/speech/transcribe
+Content-Type: multipart/form-data
+
+file: <audio file>
+

Event Handling

The system emits various events during speech processing:

speech.on('wakeWord', (word: string) => {
+  console.log(`Wake word detected: ${word}`);
+});
+
+speech.on('listening', () => {
+  console.log('Listening for command...');
+});
+
+speech.on('transcribing', () => {
+  console.log('Processing speech...');
+});
+
+speech.on('transcribed', (text: string) => {
+  console.log(`Transcribed text: ${text}`);
+});
+
+speech.on('error', (error: Error) => {
+  console.error('Speech processing error:', error);
+});
+

Performance Optimization

Model Selection

Choose an appropriate model based on your needs:

  1. Resource-constrained environments:
  2. Use tiny.en or base.en
  3. Run on CPU if GPU unavailable
  4. Limit concurrent processing

  5. High-accuracy requirements:

  6. Use small.en or medium.en
  7. Enable GPU acceleration
  8. Increase audio quality

  9. Production environments:

  10. Use base.en or small.en
  11. Enable GPU acceleration
  12. Configure appropriate timeouts

GPU Acceleration

When using GPU acceleration:

  1. Monitor GPU memory usage:

    nvidia-smi -l 1
    +

  2. Adjust model size if needed:

    WHISPER_MODEL_TYPE=small  # Decrease if GPU memory limited
    +

  3. Configure processing device:

    WHISPER_DEVICE=cuda      # Use GPU
    +WHISPER_DEVICE=cpu      # Use CPU if GPU unavailable
    +

Troubleshooting

Common Issues

  1. Wake word detection not working:
  2. Check microphone permissions
  3. Adjust WAKE_WORD_SENSITIVITY
  4. Verify wake words configuration

  5. Poor transcription quality:

  6. Check audio input quality
  7. Try a larger model
  8. Verify language settings

  9. Performance issues:

  10. Monitor resource usage
  11. Consider smaller model
  12. Check GPU acceleration status

Logging

Enable debug logging for detailed information:

LOG_LEVEL=debug
+

Speech-specific logs will be tagged with [SPEECH] prefix.

Security Considerations

  1. Audio Privacy:
  2. Audio is processed locally
  3. No data sent to external services
  4. Temporary files automatically cleaned

  5. Access Control:

  6. Speech endpoints require authentication
  7. Rate limiting applies to transcription
  8. Configurable command restrictions

  9. Resource Protection:

  10. Timeouts prevent hanging
  11. Memory limits enforced
  12. Graceful error handling
\ No newline at end of file diff --git a/search/search_index.js b/search/search_index.js index 35bde1f..d9721e7 100644 --- a/search/search_index.js +++ b/search/search_index.js @@ -1 +1 @@ -var __index = {"config":{"lang":["en"],"separator":"[\\s\\-,:!=\\[\\]()\"/]+|(?!\\b)(?=[A-Z][a-z])|\\.(?!\\d)|&[lg]t;","pipeline":["stopWordFilter"]},"docs":[{"location":"index.html","title":"Advanced Home Assistant MCP","text":"

Welcome to the Advanced Home Assistant Master Control Program documentation.

This documentation provides comprehensive information about setting up, configuring, and using the Advanced Home Assistant MCP system.

"},{"location":"index.html#quick-links","title":"Quick Links","text":""},{"location":"index.html#what-is-mcp-server","title":"What is MCP Server?","text":"

MCP Server is a bridge between Home Assistant and custom automation tools, enabling basic device control and real-time monitoring of your smart home environment. It provides a flexible interface for managing and interacting with your home automation setup.

"},{"location":"index.html#key-features","title":"Key Features","text":""},{"location":"index.html#device-control","title":"\ud83c\udfae Device Control","text":""},{"location":"index.html#security-performance","title":"\ud83d\udee1\ufe0f Security & Performance","text":""},{"location":"index.html#documentation-structure","title":"Documentation Structure","text":""},{"location":"index.html#getting-started","title":"Getting Started","text":""},{"location":"index.html#core-documentation","title":"Core Documentation","text":""},{"location":"index.html#support","title":"Support","text":"

Need help or want to report issues?

"},{"location":"index.html#license","title":"License","text":"

This project is licensed under the MIT License. See the LICENSE file for details.

"},{"location":"api.html","title":"Home Assistant MCP Server API Documentation","text":""},{"location":"api.html#overview","title":"Overview","text":"

This document provides a reference for the MCP Server API, which offers basic device control and state management for Home Assistant.

"},{"location":"api.html#authentication","title":"Authentication","text":"

All API requests require a valid JWT token in the Authorization header:

Authorization: Bearer YOUR_TOKEN\n
"},{"location":"api.html#core-endpoints","title":"Core Endpoints","text":""},{"location":"api.html#device-state-management","title":"Device State Management","text":""},{"location":"api.html#get-device-state","title":"Get Device State","text":"
GET /api/state/{entity_id}\n

Response:

{\n  \"entity_id\": \"light.living_room\",\n  \"state\": \"on\",\n  \"attributes\": {\n    \"brightness\": 128\n  }\n}\n

"},{"location":"api.html#update-device-state","title":"Update Device State","text":"
POST /api/state\nContent-Type: application/json\n\n{\n  \"entity_id\": \"light.living_room\",\n  \"state\": \"on\",\n  \"attributes\": {\n    \"brightness\": 128\n  }\n}\n
"},{"location":"api.html#device-control","title":"Device Control","text":""},{"location":"api.html#execute-device-command","title":"Execute Device Command","text":"
POST /api/control\nContent-Type: application/json\n\n{\n  \"entity_id\": \"light.living_room\",\n  \"command\": \"turn_on\",\n  \"parameters\": {\n    \"brightness\": 50\n  }\n}\n
"},{"location":"api.html#real-time-updates","title":"Real-Time Updates","text":""},{"location":"api.html#websocket-connection","title":"WebSocket Connection","text":"

Connect to real-time updates:

const ws = new WebSocket('ws://localhost:3000/events');\nws.onmessage = (event) => {\n  const deviceUpdate = JSON.parse(event.data);\n  console.log('Device state changed:', deviceUpdate);\n};\n
"},{"location":"api.html#error-handling","title":"Error Handling","text":""},{"location":"api.html#common-error-responses","title":"Common Error Responses","text":"
{\n  \"error\": {\n    \"code\": \"INVALID_REQUEST\",\n    \"message\": \"Invalid request parameters\",\n    \"details\": \"Entity ID not found or invalid command\"\n  }\n}\n
"},{"location":"api.html#rate-limiting","title":"Rate Limiting","text":"

Basic rate limiting is implemented: - Maximum of 100 requests per minute - Excess requests will receive a 429 Too Many Requests response

"},{"location":"api.html#supported-operations","title":"Supported Operations","text":""},{"location":"api.html#supported-commands","title":"Supported Commands","text":""},{"location":"api.html#supported-entities","title":"Supported Entities","text":""},{"location":"api.html#limitations","title":"Limitations","text":""},{"location":"api.html#best-practices","title":"Best Practices","text":"
  1. Always include a valid JWT token
  2. Handle potential errors in your client code
  3. Use WebSocket for real-time updates when possible
  4. Validate entity IDs before sending commands
"},{"location":"api.html#example-client-usage","title":"Example Client Usage","text":"
async function controlDevice(entityId: string, command: string, params?: Record<string, unknown>) {\n  try {\n    const response = await fetch('/api/control', {\n    method: 'POST',\n    headers: {\n        'Content-Type': 'application/json',\n        'Authorization': `Bearer ${token}`\n    },\n    body: JSON.stringify({\n        entity_id: entityId,\n        command,\n        parameters: params\n    })\n  });\n\n    if (!response.ok) {\n      const error = await response.json();\n      throw new Error(error.message);\n    }\n\n    return await response.json();\n} catch (error) {\n    console.error('Device control failed:', error);\n    throw error;\n  }\n}\n\n// Usage example\ncontrolDevice('light.living_room', 'turn_on', { brightness: 50 })\n  .then(result => console.log('Device controlled successfully'))\n  .catch(error => console.error('Control failed', error));\n
"},{"location":"api.html#future-development","title":"Future Development","text":"

Planned improvements: - Enhanced error handling - More comprehensive device support - Improved authentication mechanisms

API is subject to change. Always refer to the latest documentation.

"},{"location":"architecture.html","title":"Architecture Overview \ud83c\udfd7\ufe0f","text":"

This document describes the architecture of the MCP Server, explaining how different components work together to provide a bridge between Home Assistant and custom automation tools.

"},{"location":"architecture.html#system-architecture","title":"System Architecture","text":"
graph TD\n    subgraph \"Client Layer\"\n        WC[Web Clients]\n        MC[Mobile Clients]\n    end\n\n    subgraph \"MCP Server\"\n        API[API Gateway]\n        SSE[SSE Manager]\n        WS[WebSocket Server]\n        CM[Command Manager]\n    end\n\n    subgraph \"Home Assistant\"\n        HA[Home Assistant Core]\n        Dev[Devices & Services]\n    end\n\n    WC --> |HTTP/WS| API\n    MC --> |HTTP/WS| API\n\n    API --> |Events| SSE\n    API --> |Real-time| WS\n\n    API --> HA\n    HA --> API
"},{"location":"architecture.html#core-components","title":"Core Components","text":""},{"location":"architecture.html#api-gateway","title":"API Gateway","text":""},{"location":"architecture.html#sse-manager","title":"SSE Manager","text":""},{"location":"architecture.html#websocket-server","title":"WebSocket Server","text":""},{"location":"architecture.html#command-manager","title":"Command Manager","text":""},{"location":"architecture.html#communication-flow","title":"Communication Flow","text":"
  1. Client sends a request to the MCP Server API
  2. API Gateway authenticates the request
  3. Command Manager processes the request
  4. Request is forwarded to Home Assistant
  5. Response is sent back to the client via API or WebSocket
"},{"location":"architecture.html#key-design-principles","title":"Key Design Principles","text":""},{"location":"architecture.html#limitations","title":"Limitations","text":""},{"location":"architecture.html#future-improvements","title":"Future Improvements","text":"

Architecture is subject to change as the project evolves.

"},{"location":"configuration.html","title":"System Configuration","text":"

This document provides detailed information about configuring the Home Assistant MCP Server.

"},{"location":"configuration.html#configuration-file-structure","title":"Configuration File Structure","text":"

The MCP Server uses environment variables for configuration, with support for different environments (development, test, production):

# .env, .env.development, or .env.test\nPORT=4000\nNODE_ENV=development\nHASS_HOST=http://192.168.178.63:8123\nHASS_TOKEN=your_token_here\nJWT_SECRET=your_secret_key\n
"},{"location":"configuration.html#server-settings","title":"Server Settings","text":""},{"location":"configuration.html#basic-server-configuration","title":"Basic Server Configuration","text":""},{"location":"configuration.html#security-settings","title":"Security Settings","text":""},{"location":"configuration.html#websocket-settings","title":"WebSocket Settings","text":""},{"location":"configuration.html#environment-variables","title":"Environment Variables","text":"

All configuration is managed through environment variables:

# Server\nPORT=4000\nNODE_ENV=development\n\n# Home Assistant\nHASS_HOST=http://your-hass-instance:8123\nHASS_TOKEN=your_token_here\n\n# Security\nJWT_SECRET=your-secret-key\n\n# Logging\nLOG_LEVEL=info\nLOG_DIR=logs\nLOG_MAX_SIZE=20m\nLOG_MAX_DAYS=14d\nLOG_COMPRESS=true\nLOG_REQUESTS=true\n
"},{"location":"configuration.html#advanced-configuration","title":"Advanced Configuration","text":""},{"location":"configuration.html#security-rate-limiting","title":"Security Rate Limiting","text":"

Rate limiting is enabled by default to protect against brute force attacks:

RATE_LIMIT: {\n  windowMs: 15 * 60 * 1000,  // 15 minutes\n  max: 100  // limit each IP to 100 requests per window\n}\n
"},{"location":"configuration.html#logging","title":"Logging","text":"

The server uses Bun's built-in logging capabilities with additional configuration:

LOGGING: {\n  LEVEL: \"info\",  // debug, info, warn, error\n  DIR: \"logs\",\n  MAX_SIZE: \"20m\",\n  MAX_DAYS: \"14d\",\n  COMPRESS: true,\n  TIMESTAMP_FORMAT: \"YYYY-MM-DD HH:mm:ss:ms\",\n  LOG_REQUESTS: true\n}\n

For production deployments, we recommend using system tools like logrotate for log management.

Example logrotate configuration (/etc/logrotate.d/mcp-server):

/var/log/mcp-server.log {\n    daily\n    rotate 7\n    compress\n    delaycompress\n    missingok\n    notifempty\n    create 644 mcp mcp\n}\n

"},{"location":"configuration.html#best-practices","title":"Best Practices","text":"
  1. Always use environment variables for sensitive information
  2. Keep .env files secure and never commit them to version control
  3. Use different environment files for development, test, and production
  4. Enable SSL/TLS in production (preferably via reverse proxy)
  5. Monitor log files for issues
  6. Regularly rotate logs in production
"},{"location":"configuration.html#validation","title":"Validation","text":"

The server validates configuration on startup using Zod schemas: - Required fields are checked (e.g., HASS_TOKEN) - Value types are verified - Enums are validated (e.g., LOG_LEVEL) - Default values are applied when not specified

"},{"location":"configuration.html#troubleshooting","title":"Troubleshooting","text":"

Common configuration issues: 1. Missing required environment variables 2. Invalid environment variable values 3. Permission issues with log directories 4. Rate limiting too restrictive

See the Troubleshooting Guide for solutions.

"},{"location":"contributing.html","title":"Contributing Guide \ud83e\udd1d","text":"

Thank you for your interest in contributing to the MCP Server project!

"},{"location":"contributing.html#getting-started","title":"Getting Started","text":""},{"location":"contributing.html#prerequisites","title":"Prerequisites","text":""},{"location":"contributing.html#development-setup","title":"Development Setup","text":"
  1. Fork the repository
  2. Clone your fork:

    git clone https://github.com/YOUR_USERNAME/homeassistant-mcp.git\ncd homeassistant-mcp\n

  3. Install dependencies:

    bun install\n

  4. Configure environment:

    cp .env.example .env\n# Edit .env with your Home Assistant details\n

"},{"location":"contributing.html#development-workflow","title":"Development Workflow","text":""},{"location":"contributing.html#branch-naming","title":"Branch Naming","text":"

Example:

git checkout -b feature/device-control-improvements\n

"},{"location":"contributing.html#commit-messages","title":"Commit Messages","text":"

Follow simple, clear commit messages:

type: brief description\n\n[optional detailed explanation]\n

Types: - feat: - New feature - fix: - Bug fix - docs: - Documentation - chore: - Maintenance

"},{"location":"contributing.html#code-style","title":"Code Style","text":""},{"location":"contributing.html#testing","title":"Testing","text":"

Run tests before submitting:

# Run all tests\nbun test\n\n# Run specific test\nbun test test/api/control.test.ts\n
"},{"location":"contributing.html#pull-request-process","title":"Pull Request Process","text":"
  1. Ensure tests pass
  2. Update documentation if needed
  3. Provide clear description of changes
"},{"location":"contributing.html#pr-template","title":"PR Template","text":"
## Description\nBrief explanation of the changes\n\n## Type of Change\n- [ ] Bug fix\n- [ ] New feature\n- [ ] Documentation update\n\n## Testing\nDescribe how you tested these changes\n
"},{"location":"contributing.html#reporting-issues","title":"Reporting Issues","text":""},{"location":"contributing.html#code-of-conduct","title":"Code of Conduct","text":""},{"location":"contributing.html#resources","title":"Resources","text":"

Thank you for contributing!

"},{"location":"deployment.html","title":"Deployment Guide","text":"

This documentation is automatically deployed to GitHub Pages using GitHub Actions. Here's how it works and how to manage deployments.

"},{"location":"deployment.html#automatic-deployment","title":"Automatic Deployment","text":"

The documentation is automatically deployed when changes are pushed to the main or master branch. The deployment process:

  1. Triggers on push to main/master
  2. Sets up Python environment
  3. Installs required dependencies
  4. Builds the documentation
  5. Deploys to the gh-pages branch
"},{"location":"deployment.html#github-actions-workflow","title":"GitHub Actions Workflow","text":"

The deployment is handled by the workflow in .github/workflows/deploy-docs.yml. This is the single source of truth for documentation deployment:

name: Deploy MkDocs\non:\n  push:\n    branches:\n      - main\n      - master\n  workflow_dispatch:  # Allow manual trigger\n
"},{"location":"deployment.html#manual-deployment","title":"Manual Deployment","text":"

If needed, you can deploy manually using:

# Create a virtual environment\npython -m venv venv\n\n# Activate the virtual environment\nsource venv/bin/activate\n\n# Install dependencies\npip install -r docs/requirements.txt\n\n# Build the documentation\nmkdocs build\n\n# Deploy to GitHub Pages\nmkdocs gh-deploy --force\n
"},{"location":"deployment.html#best-practices","title":"Best Practices","text":""},{"location":"deployment.html#1-documentation-updates","title":"1. Documentation Updates","text":""},{"location":"deployment.html#2-version-control","title":"2. Version Control","text":""},{"location":"deployment.html#3-content-guidelines","title":"3. Content Guidelines","text":""},{"location":"deployment.html#4-maintenance","title":"4. Maintenance","text":""},{"location":"deployment.html#troubleshooting","title":"Troubleshooting","text":""},{"location":"deployment.html#common-issues","title":"Common Issues","text":"
  1. Failed Deployments
  2. Check GitHub Actions logs
  3. Verify dependencies are up to date
  4. Ensure all required files exist

  5. Broken Links

  6. Run mkdocs build --strict
  7. Use relative paths in markdown
  8. Check case sensitivity

  9. Style Issues

  10. Verify theme configuration
  11. Check CSS customizations
  12. Test on multiple browsers
"},{"location":"deployment.html#configuration-files","title":"Configuration Files","text":""},{"location":"deployment.html#requirementstxt","title":"requirements.txt","text":"

Create a requirements file for documentation dependencies:

mkdocs-material\nmkdocs-minify-plugin\nmkdocs-git-revision-date-plugin\nmkdocs-mkdocstrings\nmkdocs-social-plugin\nmkdocs-redirects\n
"},{"location":"deployment.html#monitoring","title":"Monitoring","text":""},{"location":"deployment.html#workflow-features","title":"Workflow Features","text":""},{"location":"deployment.html#caching","title":"Caching","text":"

The workflow implements caching for Python dependencies to speed up deployments: - Pip cache for Python packages - MkDocs dependencies cache

"},{"location":"deployment.html#deployment-checks","title":"Deployment Checks","text":"

Several checks are performed during deployment: 1. Link validation with mkdocs build --strict 2. Build verification 3. Post-deployment site accessibility check

"},{"location":"deployment.html#manual-triggers","title":"Manual Triggers","text":"

You can manually trigger deployments using the \"workflow_dispatch\" event in GitHub Actions.

"},{"location":"deployment.html#cleanup","title":"Cleanup","text":"

To clean up duplicate workflow files, run:

# Make the script executable\nchmod +x scripts/cleanup-workflows.sh\n\n# Run the cleanup script\n./scripts/cleanup-workflows.sh\n
"},{"location":"roadmap.html","title":"Roadmap for MCP Server","text":"

The following roadmap outlines our planned enhancements and future directions for the Home Assistant MCP Server. This document is a living guide that will be updated as new features are developed.

"},{"location":"roadmap.html#near-term-goals","title":"Near-Term Goals","text":""},{"location":"roadmap.html#mid-term-goals","title":"Mid-Term Goals","text":""},{"location":"roadmap.html#long-term-vision","title":"Long-Term Vision","text":""},{"location":"roadmap.html#how-to-follow-the-roadmap","title":"How to Follow the Roadmap","text":"

This roadmap is intended as a guide and may evolve based on community needs, technological advancements, and strategic priorities.

"},{"location":"security.html","title":"Security Guide","text":"

This document outlines security best practices and configurations for the Home Assistant MCP Server.

"},{"location":"security.html#authentication","title":"Authentication","text":""},{"location":"security.html#jwt-authentication","title":"JWT Authentication","text":"

The server uses JWT (JSON Web Tokens) for API authentication:

Authorization: Bearer YOUR_JWT_TOKEN\n
"},{"location":"security.html#token-configuration","title":"Token Configuration","text":"
security:\n  jwt_secret: YOUR_SECRET_KEY\n  token_expiry: 24h\n  refresh_token_expiry: 7d\n
"},{"location":"security.html#access-control","title":"Access Control","text":""},{"location":"security.html#cors-configuration","title":"CORS Configuration","text":"

Configure allowed origins to prevent unauthorized access:

security:\n  allowed_origins:\n    - http://localhost:3000\n    - https://your-domain.com\n
"},{"location":"security.html#ip-filtering","title":"IP Filtering","text":"

Restrict access by IP address:

security:\n  allowed_ips:\n    - 192.168.1.0/24\n    - 10.0.0.0/8\n
"},{"location":"security.html#ssltls-configuration","title":"SSL/TLS Configuration","text":""},{"location":"security.html#enable-https","title":"Enable HTTPS","text":"
ssl:\n  enabled: true\n  cert_file: /path/to/cert.pem\n  key_file: /path/to/key.pem\n
"},{"location":"security.html#certificate-management","title":"Certificate Management","text":"
  1. Use Let's Encrypt for free SSL certificates
  2. Regularly renew certificates
  3. Monitor certificate expiration
"},{"location":"security.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"security.html#basic-rate-limiting","title":"Basic Rate Limiting","text":"
rate_limit:\n  enabled: true\n  requests_per_minute: 100\n  burst: 20\n
"},{"location":"security.html#advanced-rate-limiting","title":"Advanced Rate Limiting","text":"
rate_limit:\n  rules:\n    - endpoint: /api/control\n      requests_per_minute: 50\n    - endpoint: /api/state\n      requests_per_minute: 200\n
"},{"location":"security.html#data-protection","title":"Data Protection","text":""},{"location":"security.html#sensitive-data","title":"Sensitive Data","text":""},{"location":"security.html#logging-security","title":"Logging Security","text":""},{"location":"security.html#best-practices","title":"Best Practices","text":"
  1. Regular Security Updates
  2. Keep dependencies updated
  3. Monitor security advisories
  4. Apply patches promptly

  5. Password Policies

  6. Enforce strong passwords
  7. Implement password expiration
  8. Use secure password storage

  9. Monitoring

  10. Log security events
  11. Monitor access patterns
  12. Set up alerts for suspicious activity

  13. Network Security

  14. Use VPN for remote access
  15. Implement network segmentation
  16. Configure firewalls properly
"},{"location":"security.html#security-checklist","title":"Security Checklist","text":""},{"location":"security.html#incident-response","title":"Incident Response","text":"
  1. Detection
  2. Monitor security logs
  3. Set up intrusion detection
  4. Configure alerts

  5. Response

  6. Document incident details
  7. Isolate affected systems
  8. Investigate root cause

  9. Recovery

  10. Apply security fixes
  11. Restore from backups
  12. Update security measures
"},{"location":"security.html#additional-resources","title":"Additional Resources","text":""},{"location":"testing.html","title":"Testing Documentation","text":""},{"location":"testing.html#quick-reference","title":"Quick Reference","text":"
# Most Common Commands\nbun test                    # Run all tests\nbun test --watch           # Run tests in watch mode\nbun test --coverage        # Run tests with coverage\nbun test path/to/test.ts   # Run a specific test file\n\n# Additional Options\nDEBUG=true bun test        # Run with debug output\nbun test --pattern \"auth\"  # Run tests matching a pattern\nbun test --timeout 60000   # Run with a custom timeout\n
"},{"location":"testing.html#overview","title":"Overview","text":"

This document describes the testing setup and practices used in the Home Assistant MCP project. We use Bun's test runner for both unit and integration testing, ensuring comprehensive coverage across modules.

"},{"location":"testing.html#test-structure","title":"Test Structure","text":"

Tests are organized in two main locations:

  1. Root Level Integration Tests (/__tests__/):
__tests__/\n\u251c\u2500\u2500 ai/              # AI/ML component tests\n\u251c\u2500\u2500 api/             # API integration tests\n\u251c\u2500\u2500 context/         # Context management tests\n\u251c\u2500\u2500 hass/            # Home Assistant integration tests\n\u251c\u2500\u2500 schemas/         # Schema validation tests\n\u251c\u2500\u2500 security/        # Security integration tests\n\u251c\u2500\u2500 tools/           # Tools and utilities tests\n\u251c\u2500\u2500 websocket/       # WebSocket integration tests\n\u251c\u2500\u2500 helpers.test.ts  # Helper function tests\n\u251c\u2500\u2500 index.test.ts    # Main application tests\n\u2514\u2500\u2500 server.test.ts   # Server integration tests\n
  1. Component Level Unit Tests (src/**/):
src/\n\u251c\u2500\u2500 __tests__/   # Global test setup and utilities\n\u2502   \u2514\u2500\u2500 setup.ts # Global test configuration\n\u251c\u2500\u2500 component/\n\u2502   \u251c\u2500\u2500 __tests__/   # Component-specific unit tests\n\u2502   \u2514\u2500\u2500 component.ts\n
"},{"location":"testing.html#test-configuration","title":"Test Configuration","text":""},{"location":"testing.html#bun-test-configuration-bunfigtoml","title":"Bun Test Configuration (bunfig.toml)","text":"
[test]\npreload = [\"./src/__tests__/setup.ts\"]  # Global test setup\ncoverage = true                         # Enable coverage by default\ntimeout = 30000                         # Test timeout in milliseconds\ntestMatch = [\"**/__tests__/**/*.test.ts\"] # Test file patterns\n
"},{"location":"testing.html#bun-scripts","title":"Bun Scripts","text":"

Available test commands in package.json:

# Run all tests\nbun test\n\n# Watch mode for development\nbun test --watch\n\n# Generate coverage report\nbun test --coverage\n\n# Run linting\nbun run lint\n\n# Format code\nbun run format\n
"},{"location":"testing.html#test-setup","title":"Test Setup","text":""},{"location":"testing.html#global-configuration","title":"Global Configuration","text":"

A global test setup file (src/__tests__/setup.ts) provides: - Environment configuration - Mock utilities - Test helper functions - Global lifecycle hooks

"},{"location":"testing.html#test-environment","title":"Test Environment","text":""},{"location":"testing.html#running-tests","title":"Running Tests","text":"
# Basic test run\nbun test\n\n# Run tests with coverage\nbun test --coverage\n\n# Run a specific test file\nbun test path/to/test.test.ts\n\n# Run tests in watch mode\nbun test --watch\n\n# Run tests with debug output\nDEBUG=true bun test\n\n# Run tests with increased timeout\nbun test --timeout 60000\n\n# Run tests matching a pattern\nbun test --pattern \"auth\"\n
"},{"location":"testing.html#advanced-debugging","title":"Advanced Debugging","text":""},{"location":"testing.html#using-node-inspector","title":"Using Node Inspector","text":"
# Start tests with inspector\nbun test --inspect\n\n# Start tests with inspector and break on first line\nbun test --inspect-brk\n
"},{"location":"testing.html#using-vs-code","title":"Using VS Code","text":"

Create a launch configuration in .vscode/launch.json:

{\n  \"version\": \"0.2.0\",\n  \"configurations\": [\n    {\n      \"type\": \"bun\",\n      \"request\": \"launch\",\n      \"name\": \"Debug Tests\",\n      \"program\": \"${workspaceFolder}/node_modules/bun/bin/bun\",\n      \"args\": [\"test\", \"${file}\"],\n      \"cwd\": \"${workspaceFolder}\",\n      \"env\": { \"DEBUG\": \"true\" }\n    }\n  ]\n}\n
"},{"location":"testing.html#test-isolation","title":"Test Isolation","text":"

To run a single test in isolation:

describe.only(\"specific test suite\", () => {\n  it.only(\"specific test case\", () => {\n    // Only this test will run\n  });\n});\n
"},{"location":"testing.html#writing-tests","title":"Writing Tests","text":""},{"location":"testing.html#test-file-naming","title":"Test File Naming","text":""},{"location":"testing.html#example-test-structure","title":"Example Test Structure","text":"
describe(\"Security Features\", () => {\n  it(\"should validate tokens correctly\", () => {\n    const payload = { userId: \"123\", role: \"user\" };\n    const token = jwt.sign(payload, validSecret, { expiresIn: \"1h\" });\n    const result = TokenManager.validateToken(token, testIp);\n    expect(result.valid).toBe(true);\n  });\n});\n
"},{"location":"testing.html#coverage","title":"Coverage","text":"

The project maintains strict coverage: - Overall coverage: at least 80% - Critical paths: 90%+ - New features: \u226585% coverage

Generate a coverage report with:

bun test --coverage\n
"},{"location":"testing.html#security-middleware-testing","title":"Security Middleware Testing","text":""},{"location":"testing.html#utility-function-testing","title":"Utility Function Testing","text":"

The security middleware now uses a utility-first approach, which allows for more granular and comprehensive testing. Each security function is now independently testable, improving code reliability and maintainability.

"},{"location":"testing.html#key-utility-functions","title":"Key Utility Functions","text":"
  1. Rate Limiting (checkRateLimit)
  2. Tests multiple scenarios:
    • Requests under threshold
    • Requests exceeding threshold
    • Rate limit reset after window expiration
// Example test\nit('should throw when requests exceed threshold', () => {\n  const ip = '127.0.0.2';\n  for (let i = 0; i < 11; i++) {\n    if (i < 10) {\n      expect(() => checkRateLimit(ip, 10)).not.toThrow();\n    } else {\n      expect(() => checkRateLimit(ip, 10)).toThrow('Too many requests from this IP');\n    }\n  }\n});\n
  1. Request Validation (validateRequestHeaders)
  2. Tests content type validation
  3. Checks request size limits
  4. Validates authorization headers
it('should reject invalid content type', () => {\n  const mockRequest = new Request('http://localhost', {\n    method: 'POST',\n    headers: { 'content-type': 'text/plain' }\n  });\n  expect(() => validateRequestHeaders(mockRequest)).toThrow('Content-Type must be application/json');\n});\n
  1. Input Sanitization (sanitizeValue)
  2. Sanitizes HTML tags
  3. Handles nested objects
  4. Preserves non-string values
it('should sanitize HTML tags', () => {\n  const input = '<script>alert(\"xss\")</script>Hello';\n  const sanitized = sanitizeValue(input);\n  expect(sanitized).toBe('&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;Hello');\n});\n
  1. Security Headers (applySecurityHeaders)
  2. Verifies correct security header application
  3. Checks CSP, frame options, and other security headers
it('should apply security headers', () => {\n  const mockRequest = new Request('http://localhost');\n  const headers = applySecurityHeaders(mockRequest);\n  expect(headers['content-security-policy']).toBeDefined();\n  expect(headers['x-frame-options']).toBeDefined();\n});\n
  1. Error Handling (handleError)
  2. Tests error responses in production and development modes
  3. Verifies error message and stack trace inclusion
it('should include error details in development mode', () => {\n  const error = new Error('Test error');\n  const result = handleError(error, 'development');\n  expect(result).toEqual({\n    error: true,\n    message: 'Internal server error',\n    error: 'Test error',\n    stack: expect.any(String)\n  });\n});\n
"},{"location":"testing.html#testing-philosophy","title":"Testing Philosophy","text":""},{"location":"testing.html#best-practices","title":"Best Practices","text":"
  1. Use minimal, focused test cases
  2. Test both successful and failure scenarios
  3. Verify input sanitization and security measures
  4. Mock external dependencies when necessary
"},{"location":"testing.html#running-security-tests","title":"Running Security Tests","text":"
# Run all tests\nbun test\n\n# Run specific security tests\nbun test __tests__/security/\n
"},{"location":"testing.html#continuous-improvement","title":"Continuous Improvement","text":""},{"location":"testing.html#best-practices_1","title":"Best Practices","text":"
  1. Isolation: Each test should be independent and not rely on the state of other tests.
  2. Mocking: Use the provided mock utilities for external dependencies.
  3. Cleanup: Clean up any resources or state modifications in afterEach or afterAll hooks.
  4. Descriptive Names: Use clear, descriptive test names that explain the expected behavior.
  5. Assertions: Make specific, meaningful assertions rather than general ones.
  6. Setup: Use beforeEach for common test setup to avoid repetition.
  7. Error Cases: Test both success and error cases for complete coverage.
"},{"location":"testing.html#coverage_1","title":"Coverage","text":"

The project aims for high test coverage, particularly focusing on: - Security-critical code paths - API endpoints - Data validation - Error handling - Event broadcasting

Run coverage reports using:

bun test --coverage\n

"},{"location":"testing.html#debugging-tests","title":"Debugging Tests","text":"

To debug tests: 1. Set DEBUG=true to enable console output during tests 2. Use the --watch flag for development 3. Add console.log() statements (they're only shown when DEBUG is true) 4. Use the test utilities' debugging helpers

"},{"location":"testing.html#advanced-debugging_1","title":"Advanced Debugging","text":"
  1. Using Node Inspector:

    # Start tests with inspector\nbun test --inspect\n\n# Start tests with inspector and break on first line\nbun test --inspect-brk\n

  2. Using VS Code:

    // .vscode/launch.json\n{\n  \"version\": \"0.2.0\",\n  \"configurations\": [\n    {\n      \"type\": \"bun\",\n      \"request\": \"launch\",\n      \"name\": \"Debug Tests\",\n      \"program\": \"${workspaceFolder}/node_modules/bun/bin/bun\",\n      \"args\": [\"test\", \"${file}\"],\n      \"cwd\": \"${workspaceFolder}\",\n      \"env\": { \"DEBUG\": \"true\" }\n    }\n  ]\n}\n

  3. Test Isolation: To run a single test in isolation:

    describe.only(\"specific test suite\", () => {\n  it.only(\"specific test case\", () => {\n    // Only this test will run\n  });\n});\n

"},{"location":"testing.html#contributing","title":"Contributing","text":"

When contributing new code: 1. Add tests for new features 2. Ensure existing tests pass 3. Maintain or improve coverage 4. Follow the existing test patterns and naming conventions 5. Document any new test utilities or patterns

"},{"location":"testing.html#coverage-requirements","title":"Coverage Requirements","text":"

The project maintains strict coverage requirements:

Coverage reports are generated in multiple formats: - Console summary - HTML report (./coverage/index.html) - LCOV report (./coverage/lcov.info)

To view detailed coverage:

# Generate and open coverage report\nbun test --coverage && open coverage/index.html\n

"},{"location":"troubleshooting.html","title":"Troubleshooting Guide \ud83d\udd27","text":"

This guide helps you diagnose and resolve common issues with MCP Server.

"},{"location":"troubleshooting.html#quick-diagnostics","title":"Quick Diagnostics","text":""},{"location":"troubleshooting.html#health-check","title":"Health Check","text":"

First, verify the server's health:

curl http://localhost:3000/health\n

Expected response:

{\n  \"status\": \"healthy\",\n  \"version\": \"1.0.0\",\n  \"uptime\": 3600,\n  \"homeAssistant\": {\n    \"connected\": true,\n    \"version\": \"2024.1.0\"\n  }\n}\n

"},{"location":"troubleshooting.html#common-issues","title":"Common Issues","text":""},{"location":"troubleshooting.html#1-connection-issues","title":"1. Connection Issues","text":""},{"location":"troubleshooting.html#cannot-connect-to-mcp-server","title":"Cannot Connect to MCP Server","text":"

Symptoms: - Server not responding - Connection refused errors - Timeout errors

Solutions:

  1. Check if the server is running:

    # For Docker installation\ndocker compose ps\n\n# For manual installation\nps aux | grep mcp\n

  2. Verify port availability:

    # Check if port is in use\nnetstat -tuln | grep 3000\n

  3. Check logs:

    # Docker logs\ndocker compose logs mcp\n\n# Manual installation logs\nbun run dev\n

"},{"location":"troubleshooting.html#home-assistant-connection-failed","title":"Home Assistant Connection Failed","text":"

Symptoms: - \"Connection Error\" in health check - Cannot control devices - State updates not working

Solutions:

  1. Verify Home Assistant URL and token in .env:

    HA_URL=http://homeassistant:8123\nHA_TOKEN=your_long_lived_access_token\n

  2. Test Home Assistant connection:

    curl -H \"Authorization: Bearer YOUR_HA_TOKEN\" \\\n     http://your-homeassistant:8123/api/\n

  3. Check network connectivity:

    # For Docker setup\ndocker compose exec mcp ping homeassistant\n

"},{"location":"troubleshooting.html#2-authentication-issues","title":"2. Authentication Issues","text":""},{"location":"troubleshooting.html#invalid-token","title":"Invalid Token","text":"

Symptoms: - 401 Unauthorized responses - \"Invalid token\" errors

Solutions:

  1. Generate a new token:

    curl -X POST http://localhost:3000/auth/token \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"username\": \"your_username\", \"password\": \"your_password\"}'\n

  2. Verify token format:

    // Token should be in format:\nAuthorization: Bearer eyJhbGciOiJIUzI1NiIs...\n

"},{"location":"troubleshooting.html#rate-limiting","title":"Rate Limiting","text":"

Symptoms: - 429 Too Many Requests - \"Rate limit exceeded\" errors

Solutions:

  1. Check current rate limit status:

    curl -I http://localhost:3000/api/state\n

  2. Adjust rate limits in configuration:

    security:\n  rateLimit: 100  # Increase if needed\n  rateLimitWindow: 60000  # Window in milliseconds\n

"},{"location":"troubleshooting.html#3-real-time-updates-issues","title":"3. Real-time Updates Issues","text":""},{"location":"troubleshooting.html#sse-connection-drops","title":"SSE Connection Drops","text":"

Symptoms: - Frequent disconnections - Missing state updates - EventSource errors

Solutions:

  1. Implement proper reconnection logic:

    class SSEClient {\n    constructor() {\n        this.connect();\n    }\n\n    connect() {\n        this.eventSource = new EventSource('/subscribe_events');\n        this.eventSource.onerror = this.handleError.bind(this);\n    }\n\n    handleError(error) {\n        console.error('SSE Error:', error);\n        this.eventSource.close();\n        setTimeout(() => this.connect(), 1000);\n    }\n}\n

  2. Check network stability:

    # Monitor connection stability\nping -c 100 localhost\n

"},{"location":"troubleshooting.html#4-performance-issues","title":"4. Performance Issues","text":""},{"location":"troubleshooting.html#high-latency","title":"High Latency","text":"

Symptoms: - Slow response times - Command execution delays - UI lag

Solutions:

  1. Enable Redis caching:

    REDIS_ENABLED=true\nREDIS_URL=redis://localhost:6379\n

  2. Monitor system resources:

    # Check CPU and memory usage\ndocker stats\n\n# Or for manual installation\ntop -p $(pgrep -f mcp)\n

  3. Optimize database queries and caching:

    // Use batch operations\nconst results = await Promise.all([\n    cache.get('key1'),\n    cache.get('key2')\n]);\n

"},{"location":"troubleshooting.html#5-device-control-issues","title":"5. Device Control Issues","text":""},{"location":"troubleshooting.html#commands-not-executing","title":"Commands Not Executing","text":"

Symptoms: - Commands appear successful but no device response - Inconsistent device states - Error messages from Home Assistant

Solutions:

  1. Verify device availability:

    curl http://localhost:3000/api/state/light.living_room\n

  2. Check command syntax:

    # Test basic command\ncurl -X POST http://localhost:3000/api/command \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"command\": \"Turn on living room lights\"}'\n

  3. Review Home Assistant logs:

    docker compose exec homeassistant journalctl -f\n

"},{"location":"troubleshooting.html#debugging-tools","title":"Debugging Tools","text":""},{"location":"troubleshooting.html#log-analysis","title":"Log Analysis","text":"

Enable debug logging:

LOG_LEVEL=debug\nDEBUG=mcp:*\n
"},{"location":"troubleshooting.html#network-debugging","title":"Network Debugging","text":"

Monitor network traffic:

# TCP dump for API traffic\ntcpdump -i any port 3000 -w debug.pcap\n
"},{"location":"troubleshooting.html#performance-profiling","title":"Performance Profiling","text":"

Enable performance monitoring:

ENABLE_METRICS=true\nMETRICS_PORT=9090\n
"},{"location":"troubleshooting.html#getting-help","title":"Getting Help","text":"

If you're still experiencing issues:

  1. Check the GitHub Issues
  2. Search Discussions
  3. Create a new issue with:
  4. Detailed description
  5. Logs
  6. Configuration (sanitized)
  7. Steps to reproduce
"},{"location":"troubleshooting.html#maintenance","title":"Maintenance","text":""},{"location":"troubleshooting.html#regular-health-checks","title":"Regular Health Checks","text":"

Run periodic health checks:

# Create a cron job\n*/5 * * * * curl -f http://localhost:3000/health || notify-admin\n
"},{"location":"troubleshooting.html#log-rotation","title":"Log Rotation","text":"

Configure log rotation:

logging:\n  maxSize: \"100m\"\n  maxFiles: \"7d\"\n  compress: true\n
"},{"location":"troubleshooting.html#backup-configuration","title":"Backup Configuration","text":"

Regularly backup your configuration:

# Backup script\ntar -czf mcp-backup-$(date +%Y%m%d).tar.gz \\\n    .env \\\n    config/ \\\n    data/\n
"},{"location":"troubleshooting.html#faq","title":"FAQ","text":""},{"location":"troubleshooting.html#general-questions","title":"General Questions","text":""},{"location":"troubleshooting.html#q-what-is-mcp-server","title":"Q: What is MCP Server?","text":"

A: MCP Server is a bridge between Home Assistant and Language Learning Models, enabling natural language control and automation of your smart home devices.

"},{"location":"troubleshooting.html#q-what-are-the-system-requirements","title":"Q: What are the system requirements?","text":"

A: MCP Server requires: - Node.js 16 or higher - Home Assistant instance - 1GB RAM minimum - 1GB disk space

"},{"location":"troubleshooting.html#q-how-do-i-update-mcp-server","title":"Q: How do I update MCP Server?","text":"

A: For Docker installation:

docker compose pull\ndocker compose up -d\n
For manual installation:
git pull\nbun install\nbun run build\n

"},{"location":"troubleshooting.html#integration-questions","title":"Integration Questions","text":""},{"location":"troubleshooting.html#q-can-i-use-mcp-server-with-any-home-assistant-instance","title":"Q: Can I use MCP Server with any Home Assistant instance?","text":"

A: Yes, MCP Server works with any Home Assistant instance that has the REST API enabled and a valid long-lived access token.

"},{"location":"troubleshooting.html#q-does-mcp-server-support-all-home-assistant-integrations","title":"Q: Does MCP Server support all Home Assistant integrations?","text":"

A: MCP Server supports all Home Assistant devices and services that are accessible via the REST API.

"},{"location":"troubleshooting.html#security-questions","title":"Security Questions","text":""},{"location":"troubleshooting.html#q-is-my-home-assistant-token-secure","title":"Q: Is my Home Assistant token secure?","text":"

A: Yes, your Home Assistant token is stored securely and only used for authenticated communication between MCP Server and your Home Assistant instance.

"},{"location":"troubleshooting.html#q-can-i-use-mcp-server-remotely","title":"Q: Can I use MCP Server remotely?","text":"

A: Yes, but we recommend using a secure connection (HTTPS) and proper authentication when exposing MCP Server to the internet.

"},{"location":"troubleshooting.html#troubleshooting-questions","title":"Troubleshooting Questions","text":""},{"location":"troubleshooting.html#q-why-are-my-device-states-not-updating","title":"Q: Why are my device states not updating?","text":"

A: Check: 1. Home Assistant connection 2. WebSocket connection status 3. Device availability in Home Assistant 4. Network connectivity

"},{"location":"troubleshooting.html#q-why-are-my-commands-not-working","title":"Q: Why are my commands not working?","text":"

A: Verify: 1. Command syntax 2. Device availability 3. User permissions 4. Home Assistant API access

"},{"location":"usage.html","title":"Usage Guide","text":"

This guide explains how to use the Home Assistant MCP Server for basic device management and integration.

"},{"location":"usage.html#basic-setup","title":"Basic Setup","text":"
  1. Starting the Server:
  2. Development mode: bun run dev
  3. Production mode: bun run start

  4. Accessing the Server:

  5. Default URL: http://localhost:3000
  6. Ensure Home Assistant credentials are configured in .env
"},{"location":"usage.html#device-control","title":"Device Control","text":""},{"location":"usage.html#rest-api-interactions","title":"REST API Interactions","text":"

Basic device control can be performed via the REST API:

// Turn on a light\nfetch('http://localhost:3000/api/control', {\n  method: 'POST',\n  headers: {\n    'Content-Type': 'application/json',\n    'Authorization': `Bearer ${token}`\n  },\n  body: JSON.stringify({\n    entity_id: 'light.living_room',\n    command: 'turn_on',\n    parameters: { brightness: 50 }\n  })\n});\n
"},{"location":"usage.html#supported-commands","title":"Supported Commands","text":""},{"location":"usage.html#supported-entities","title":"Supported Entities","text":""},{"location":"usage.html#real-time-updates","title":"Real-Time Updates","text":""},{"location":"usage.html#websocket-connection","title":"WebSocket Connection","text":"

Subscribe to real-time device state changes:

const ws = new WebSocket('ws://localhost:3000/events');\nws.onmessage = (event) => {\n  const deviceUpdate = JSON.parse(event.data);\n  console.log('Device state changed:', deviceUpdate);\n};\n
"},{"location":"usage.html#authentication","title":"Authentication","text":"

All API requests require a valid JWT token in the Authorization header.

"},{"location":"usage.html#limitations","title":"Limitations","text":""},{"location":"usage.html#troubleshooting","title":"Troubleshooting","text":"
  1. Verify Home Assistant connection
  2. Check JWT token validity
  3. Ensure correct entity IDs
  4. Review server logs for detailed errors
"},{"location":"usage.html#configuration","title":"Configuration","text":"

Configure the server using environment variables in .env:

HA_URL=http://homeassistant:8123\nHA_TOKEN=your_home_assistant_token\nJWT_SECRET=your_jwt_secret\n
"},{"location":"usage.html#next-steps","title":"Next Steps","text":""},{"location":"api/index.html","title":"API Documentation \ud83d\udcda","text":"

Welcome to the MCP Server API documentation. This guide covers all available endpoints, authentication methods, and integration patterns.

"},{"location":"api/index.html#api-overview","title":"API Overview","text":"

The MCP Server provides several API categories:

  1. Core API - Basic device control and state management
  2. SSE API - Real-time event subscriptions
  3. Scene API - Scene management and automation
  4. Voice API - Natural language command processing
"},{"location":"api/index.html#authentication","title":"Authentication","text":"

All API endpoints require authentication using JWT tokens:

# Include the token in your requests\ncurl -H \"Authorization: Bearer YOUR_JWT_TOKEN\" http://localhost:3000/api/state\n

To obtain a token:

curl -X POST http://localhost:3000/auth/token \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"username\": \"your_username\", \"password\": \"your_password\"}'\n
"},{"location":"api/index.html#core-endpoints","title":"Core Endpoints","text":""},{"location":"api/index.html#device-state","title":"Device State","text":"
GET /api/state\n

Retrieve the current state of all devices:

curl http://localhost:3000/api/state\n

Response:

{\n  \"devices\": [\n    {\n      \"id\": \"light.living_room\",\n      \"state\": \"on\",\n      \"attributes\": {\n        \"brightness\": 255,\n        \"color_temp\": 370\n      }\n    }\n  ]\n}\n

"},{"location":"api/index.html#command-execution","title":"Command Execution","text":"
POST /api/command\n

Execute a natural language command:

curl -X POST http://localhost:3000/api/command \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"command\": \"Turn on the kitchen lights\"}'\n

Response:

{\n  \"success\": true,\n  \"action\": \"turn_on\",\n  \"device\": \"light.kitchen\",\n  \"message\": \"Kitchen lights turned on\"\n}\n

"},{"location":"api/index.html#real-time-events","title":"Real-Time Events","text":""},{"location":"api/index.html#event-subscription","title":"Event Subscription","text":"
GET /subscribe_events\n

Subscribe to device state changes:

const eventSource = new EventSource('http://localhost:3000/subscribe_events?token=YOUR_TOKEN');\n\neventSource.onmessage = (event) => {\n    const data = JSON.parse(event.data);\n    console.log('State changed:', data);\n};\n
"},{"location":"api/index.html#filtered-subscriptions","title":"Filtered Subscriptions","text":"

Subscribe to specific device types:

GET /subscribe_events?domain=light\nGET /subscribe_events?entity_id=light.living_room\n
"},{"location":"api/index.html#scene-management","title":"Scene Management","text":""},{"location":"api/index.html#create-scene","title":"Create Scene","text":"
POST /api/scene\n

Create a new scene:

curl -X POST http://localhost:3000/api/scene \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"Movie Night\",\n    \"actions\": [\n      {\"device\": \"light.living_room\", \"action\": \"dim\", \"value\": 20},\n      {\"device\": \"media_player.tv\", \"action\": \"on\"}\n    ]\n  }'\n
"},{"location":"api/index.html#activate-scene","title":"Activate Scene","text":"
POST /api/scene/activate\n

Activate an existing scene:

curl -X POST http://localhost:3000/api/scene/activate \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"name\": \"Movie Night\"}'\n
"},{"location":"api/index.html#error-handling","title":"Error Handling","text":"

The API uses standard HTTP status codes:

Error responses include detailed messages:

{\n  \"error\": true,\n  \"message\": \"Device not found\",\n  \"code\": \"DEVICE_NOT_FOUND\",\n  \"details\": {\n    \"device_id\": \"light.nonexistent\"\n  }\n}\n
"},{"location":"api/index.html#rate-limiting","title":"Rate Limiting","text":"

API requests are rate-limited to prevent abuse:

X-RateLimit-Limit: 100\nX-RateLimit-Remaining: 99\nX-RateLimit-Reset: 1640995200\n

When exceeded, returns 429 Too Many Requests:

{\n  \"error\": true,\n  \"message\": \"Rate limit exceeded\",\n  \"reset\": 1640995200\n}\n
"},{"location":"api/index.html#websocket-api","title":"WebSocket API","text":"

For bi-directional communication:

const ws = new WebSocket('ws://localhost:3000/ws');\n\nws.onmessage = (event) => {\n    const data = JSON.parse(event.data);\n    console.log('Received:', data);\n};\n\nws.send(JSON.stringify({\n    type: 'command',\n    payload: {\n        command: 'Turn on lights'\n    }\n}));\n
"},{"location":"api/index.html#api-versioning","title":"API Versioning","text":"

The current API version is v1. Include the version in the URL:

/api/v1/state\n/api/v1/command\n
"},{"location":"api/index.html#further-reading","title":"Further Reading","text":""},{"location":"api/index.html#api-reference","title":"API Reference","text":"

The Advanced Home Assistant MCP provides several APIs for integration and automation:

"},{"location":"api/core.html","title":"Core Functions API \ud83d\udd27","text":"

The Core Functions API provides the fundamental operations for interacting with Home Assistant devices and services through MCP Server.

"},{"location":"api/core.html#device-control","title":"Device Control","text":""},{"location":"api/core.html#get-device-state","title":"Get Device State","text":"

Retrieve the current state of devices.

GET /api/state\nGET /api/state/{entity_id}\n

Parameters: - entity_id (optional): Specific device ID to query

# Get all states\ncurl http://localhost:3000/api/state\n\n# Get specific device state\ncurl http://localhost:3000/api/state/light.living_room\n

Response:

{\n  \"entity_id\": \"light.living_room\",\n  \"state\": \"on\",\n  \"attributes\": {\n    \"brightness\": 255,\n    \"color_temp\": 370,\n    \"friendly_name\": \"Living Room Light\"\n  },\n  \"last_changed\": \"2024-01-20T15:30:00Z\"\n}\n

"},{"location":"api/core.html#control-device","title":"Control Device","text":"

Execute device commands.

POST /api/device/control\n

Request body:

{\n  \"entity_id\": \"light.living_room\",\n  \"action\": \"turn_on\",\n  \"parameters\": {\n    \"brightness\": 200,\n    \"color_temp\": 400\n  }\n}\n

Available actions: - turn_on - turn_off - toggle - set_value

Example with curl:

curl -X POST http://localhost:3000/api/device/control \\\n  -H \"Content-Type: application/json\" \\\n  -H \"Authorization: Bearer YOUR_JWT_TOKEN\" \\\n  -d '{\n    \"entity_id\": \"light.living_room\",\n    \"action\": \"turn_on\",\n    \"parameters\": {\n      \"brightness\": 200\n    }\n  }'\n

"},{"location":"api/core.html#natural-language-commands","title":"Natural Language Commands","text":""},{"location":"api/core.html#execute-command","title":"Execute Command","text":"

Process natural language commands.

POST /api/command\n

Request body:

{\n  \"command\": \"Turn on the living room lights and set them to 50% brightness\"\n}\n

Example usage:

curl -X POST http://localhost:3000/api/command \\\n  -H \"Content-Type: application/json\" \\\n  -H \"Authorization: Bearer YOUR_JWT_TOKEN\" \\\n  -d '{\n    \"command\": \"Turn on the living room lights and set them to 50% brightness\"\n  }'\n

Response:

{\n  \"success\": true,\n  \"actions\": [\n    {\n      \"entity_id\": \"light.living_room\",\n      \"action\": \"turn_on\",\n      \"parameters\": {\n        \"brightness\": 127\n      },\n      \"status\": \"completed\"\n    }\n  ],\n  \"message\": \"Command executed successfully\"\n}\n

"},{"location":"api/core.html#scene-management","title":"Scene Management","text":""},{"location":"api/core.html#create-scene","title":"Create Scene","text":"

Define a new scene with multiple actions.

POST /api/scene\n

Request body:

{\n  \"name\": \"Movie Night\",\n  \"description\": \"Perfect lighting for movie watching\",\n  \"actions\": [\n    {\n      \"entity_id\": \"light.living_room\",\n      \"action\": \"turn_on\",\n      \"parameters\": {\n        \"brightness\": 50,\n        \"color_temp\": 500\n      }\n    },\n    {\n      \"entity_id\": \"cover.living_room\",\n      \"action\": \"close\"\n    }\n  ]\n}\n

"},{"location":"api/core.html#activate-scene","title":"Activate Scene","text":"

Trigger a predefined scene.

POST /api/scene/{scene_name}/activate\n

Example:

curl -X POST http://localhost:3000/api/scene/movie_night/activate \\\n  -H \"Authorization: Bearer YOUR_JWT_TOKEN\"\n

"},{"location":"api/core.html#groups","title":"Groups","text":""},{"location":"api/core.html#create-device-group","title":"Create Device Group","text":"

Create a group of devices for collective control.

POST /api/group\n

Request body:

{\n  \"name\": \"Living Room\",\n  \"entities\": [\n    \"light.living_room_main\",\n    \"light.living_room_accent\",\n    \"switch.living_room_fan\"\n  ]\n}\n

"},{"location":"api/core.html#control-group","title":"Control Group","text":"

Control multiple devices in a group.

POST /api/group/{group_name}/control\n

Request body:

{\n  \"action\": \"turn_off\"\n}\n

"},{"location":"api/core.html#system-operations","title":"System Operations","text":""},{"location":"api/core.html#health-check","title":"Health Check","text":"

Check server status and connectivity.

GET /health\n

Response:

{\n  \"status\": \"healthy\",\n  \"version\": \"1.0.0\",\n  \"uptime\": 3600,\n  \"homeAssistant\": {\n    \"connected\": true,\n    \"version\": \"2024.1.0\"\n  }\n}\n

"},{"location":"api/core.html#configuration","title":"Configuration","text":"

Get current server configuration.

GET /api/config\n

Response:

{\n  \"server\": {\n    \"port\": 3000,\n    \"host\": \"0.0.0.0\",\n    \"version\": \"1.0.0\"\n  },\n  \"homeAssistant\": {\n    \"url\": \"http://homeassistant:8123\",\n    \"connected\": true\n  },\n  \"features\": {\n    \"nlp\": true,\n    \"scenes\": true,\n    \"groups\": true\n  }\n}\n

"},{"location":"api/core.html#error-handling","title":"Error Handling","text":"

All endpoints follow standard HTTP status codes and return detailed error messages:

{\n  \"error\": true,\n  \"code\": \"INVALID_ENTITY\",\n  \"message\": \"Device 'light.nonexistent' not found\",\n  \"details\": {\n    \"entity_id\": \"light.nonexistent\",\n    \"available_entities\": [\n      \"light.living_room\",\n      \"light.kitchen\"\n    ]\n  }\n}\n

Common error codes: - INVALID_ENTITY: Device not found - INVALID_ACTION: Unsupported action - INVALID_PARAMETERS: Invalid command parameters - AUTHENTICATION_ERROR: Invalid or missing token - CONNECTION_ERROR: Home Assistant connection issue

"},{"location":"api/core.html#typescript-interfaces","title":"TypeScript Interfaces","text":"
interface DeviceState {\n  entity_id: string;\n  state: string;\n  attributes: Record<string, any>;\n  last_changed: string;\n}\n\ninterface DeviceCommand {\n  entity_id: string;\n  action: 'turn_on' | 'turn_off' | 'toggle' | 'set_value';\n  parameters?: Record<string, any>;\n}\n\ninterface Scene {\n  name: string;\n  description?: string;\n  actions: DeviceCommand[];\n}\n\ninterface Group {\n  name: string;\n  entities: string[];\n}\n
"},{"location":"api/core.html#related-resources","title":"Related Resources","text":""},{"location":"api/sse.html","title":"Server-Sent Events (SSE) API \ud83d\udce1","text":"

The SSE API provides real-time updates about device states and events from your Home Assistant setup. This guide covers how to use and implement SSE connections in your applications.

"},{"location":"api/sse.html#overview","title":"Overview","text":"

Server-Sent Events (SSE) is a standard that enables servers to push real-time updates to clients over HTTP connections. MCP Server uses SSE to provide:

"},{"location":"api/sse.html#basic-usage","title":"Basic Usage","text":""},{"location":"api/sse.html#establishing-a-connection","title":"Establishing a Connection","text":"

Create an EventSource connection to receive updates:

const eventSource = new EventSource('http://localhost:3000/subscribe_events?token=YOUR_JWT_TOKEN');\n\neventSource.onmessage = (event) => {\n    const data = JSON.parse(event.data);\n    console.log('Received update:', data);\n};\n
"},{"location":"api/sse.html#connection-states","title":"Connection States","text":"

Handle different connection states:

eventSource.onopen = () => {\n    console.log('Connection established');\n};\n\neventSource.onerror = (error) => {\n    console.error('Connection error:', error);\n    // Implement reconnection logic if needed\n};\n
"},{"location":"api/sse.html#event-types","title":"Event Types","text":""},{"location":"api/sse.html#device-state-events","title":"Device State Events","text":"

Subscribe to all device state changes:

const stateEvents = new EventSource('http://localhost:3000/subscribe_events?type=state');\n\nstateEvents.onmessage = (event) => {\n    const state = JSON.parse(event.data);\n    console.log('Device state changed:', state);\n};\n

Example state event:

{\n  \"type\": \"state_changed\",\n  \"entity_id\": \"light.living_room\",\n  \"state\": \"on\",\n  \"attributes\": {\n    \"brightness\": 255,\n    \"color_temp\": 370\n  },\n  \"timestamp\": \"2024-01-20T15:30:00Z\"\n}\n

"},{"location":"api/sse.html#filtered-subscriptions","title":"Filtered Subscriptions","text":""},{"location":"api/sse.html#by-domain","title":"By Domain","text":"

Subscribe to specific device types:

// Subscribe to only light events\nconst lightEvents = new EventSource('http://localhost:3000/subscribe_events?domain=light');\n\n// Subscribe to multiple domains\nconst multiEvents = new EventSource('http://localhost:3000/subscribe_events?domain=light,switch,sensor');\n
"},{"location":"api/sse.html#by-entity-id","title":"By Entity ID","text":"

Subscribe to specific devices:

// Single entity\nconst livingRoomLight = new EventSource(\n    'http://localhost:3000/subscribe_events?entity_id=light.living_room'\n);\n\n// Multiple entities\nconst kitchenDevices = new EventSource(\n    'http://localhost:3000/subscribe_events?entity_id=light.kitchen,switch.coffee_maker'\n);\n
"},{"location":"api/sse.html#advanced-usage","title":"Advanced Usage","text":""},{"location":"api/sse.html#connection-management","title":"Connection Management","text":"

Implement robust connection handling:

class SSEManager {\n    constructor(url, options = {}) {\n        this.url = url;\n        this.options = {\n            maxRetries: 3,\n            retryDelay: 1000,\n            ...options\n        };\n        this.retryCount = 0;\n        this.connect();\n    }\n\n    connect() {\n        this.eventSource = new EventSource(this.url);\n\n        this.eventSource.onopen = () => {\n            this.retryCount = 0;\n            console.log('Connected to SSE stream');\n        };\n\n        this.eventSource.onerror = (error) => {\n            this.handleError(error);\n        };\n\n        this.eventSource.onmessage = (event) => {\n            this.handleMessage(event);\n        };\n    }\n\n    handleError(error) {\n        console.error('SSE Error:', error);\n        this.eventSource.close();\n\n        if (this.retryCount < this.options.maxRetries) {\n            this.retryCount++;\n            setTimeout(() => {\n                console.log(`Retrying connection (${this.retryCount}/${this.options.maxRetries})`);\n                this.connect();\n            }, this.options.retryDelay * this.retryCount);\n        }\n    }\n\n    handleMessage(event) {\n        try {\n            const data = JSON.parse(event.data);\n            // Handle the event data\n            console.log('Received:', data);\n        } catch (error) {\n            console.error('Error parsing SSE data:', error);\n        }\n    }\n\n    disconnect() {\n        if (this.eventSource) {\n            this.eventSource.close();\n        }\n    }\n}\n\n// Usage\nconst sseManager = new SSEManager('http://localhost:3000/subscribe_events?token=YOUR_TOKEN');\n
"},{"location":"api/sse.html#event-filtering","title":"Event Filtering","text":"

Filter events on the client side:

class EventFilter {\n    constructor(conditions) {\n        this.conditions = conditions;\n    }\n\n    matches(event) {\n        return Object.entries(this.conditions).every(([key, value]) => {\n            if (Array.isArray(value)) {\n                return value.includes(event[key]);\n            }\n            return event[key] === value;\n        });\n    }\n}\n\n// Usage\nconst filter = new EventFilter({\n    domain: ['light', 'switch'],\n    state: 'on'\n});\n\neventSource.onmessage = (event) => {\n    const data = JSON.parse(event.data);\n    if (filter.matches(data)) {\n        console.log('Matched event:', data);\n    }\n};\n
"},{"location":"api/sse.html#best-practices","title":"Best Practices","text":"
  1. Authentication
  2. Always include authentication tokens
  3. Implement token refresh mechanisms
  4. Handle authentication errors gracefully

  5. Error Handling

  6. Implement progressive retry logic
  7. Log connection issues
  8. Notify users of connection status

  9. Resource Management

  10. Close EventSource connections when not needed
  11. Limit the number of concurrent connections
  12. Use filtered subscriptions when possible

  13. Performance

  14. Process events efficiently
  15. Batch UI updates
  16. Consider debouncing frequent updates
"},{"location":"api/sse.html#common-issues","title":"Common Issues","text":""},{"location":"api/sse.html#connection-drops","title":"Connection Drops","text":"

If the connection drops, the EventSource will automatically attempt to reconnect. You can customize this behavior:

eventSource.addEventListener('error', (error) => {\n    if (eventSource.readyState === EventSource.CLOSED) {\n        // Connection closed, implement custom retry logic\n    }\n});\n
"},{"location":"api/sse.html#memory-leaks","title":"Memory Leaks","text":"

Always clean up EventSource connections:

// In a React component\nuseEffect(() => {\n    const eventSource = new EventSource('http://localhost:3000/subscribe_events');\n\n    return () => {\n        eventSource.close(); // Cleanup on unmount\n    };\n}, []);\n
"},{"location":"api/sse.html#related-resources","title":"Related Resources","text":""},{"location":"config/index.html","title":"Configuration","text":"

This section covers the configuration options available in the Home Assistant MCP Server.

"},{"location":"config/index.html#overview","title":"Overview","text":"

The MCP Server can be configured through various configuration files and environment variables. This section will guide you through the available options and their usage.

"},{"location":"config/index.html#configuration-files","title":"Configuration Files","text":"

The main configuration files are:

  1. .env - Environment variables
  2. config.yaml - Main configuration file
  3. devices.yaml - Device-specific configurations
"},{"location":"config/index.html#environment-variables","title":"Environment Variables","text":"

Key environment variables that can be set:

"},{"location":"config/index.html#next-steps","title":"Next Steps","text":""},{"location":"development/index.html","title":"Development Guide","text":"

Welcome to the development guide for the Home Assistant MCP Server. This section provides comprehensive information for developers who want to contribute to or extend the project.

"},{"location":"development/index.html#development-overview","title":"Development Overview","text":"

The MCP Server is built with modern development practices in mind, focusing on:

"},{"location":"development/index.html#getting-started","title":"Getting Started","text":"
  1. Set up your development environment
  2. Fork the repository
  3. Install dependencies
  4. Run tests
  5. Make your changes
  6. Submit a pull request
"},{"location":"development/index.html#development-topics","title":"Development Topics","text":""},{"location":"development/index.html#best-practices","title":"Best Practices","text":""},{"location":"development/index.html#development-workflow","title":"Development Workflow","text":"
  1. Create a feature branch
  2. Make your changes
  3. Run tests
  4. Update documentation
  5. Submit a pull request
  6. Address review comments
  7. Merge when approved
"},{"location":"development/index.html#next-steps","title":"Next Steps","text":""},{"location":"development/best-practices.html","title":"Development Best Practices","text":"

This guide outlines the best practices for developing tools and features for the Home Assistant MCP.

"},{"location":"development/best-practices.html#code-style","title":"Code Style","text":""},{"location":"development/best-practices.html#typescript","title":"TypeScript","text":"
  1. Use TypeScript for all new code
  2. Enable strict mode
  3. Use explicit types
  4. Avoid any type
  5. Use interfaces over types
  6. Document with JSDoc comments
/** \n * Represents a device in the system.\n * @interface\n */\ninterface Device {\n    /** Unique device identifier */\n    id: string;\n\n    /** Human-readable device name */\n    name: string;\n\n    /** Device state */\n    state: DeviceState;\n}\n
"},{"location":"development/best-practices.html#naming-conventions","title":"Naming Conventions","text":"
  1. Use PascalCase for:
  2. Classes
  3. Interfaces
  4. Types
  5. Enums

  6. Use camelCase for:

  7. Variables
  8. Functions
  9. Methods
  10. Properties

  11. Use UPPER_SNAKE_CASE for:

  12. Constants
  13. Enum values
class DeviceManager {\n    private readonly DEFAULT_TIMEOUT = 5000;\n\n    async getDeviceState(deviceId: string): Promise<DeviceState> {\n        // Implementation\n    }\n}\n
"},{"location":"development/best-practices.html#architecture","title":"Architecture","text":""},{"location":"development/best-practices.html#solid-principles","title":"SOLID Principles","text":"
  1. Single Responsibility
  2. Each class/module has one job
  3. Split complex functionality

  4. Open/Closed

  5. Open for extension
  6. Closed for modification

  7. Liskov Substitution

  8. Subtypes must be substitutable
  9. Use interfaces properly

  10. Interface Segregation

  11. Keep interfaces focused
  12. Split large interfaces

  13. Dependency Inversion

  14. Depend on abstractions
  15. Use dependency injection
"},{"location":"development/best-practices.html#example","title":"Example","text":"
// Bad\nclass DeviceManager {\n    async getState() { /* ... */ }\n    async setState() { /* ... */ }\n    async sendNotification() { /* ... */ }  // Wrong responsibility\n}\n\n// Good\nclass DeviceManager {\n    constructor(\n        private notifier: NotificationService\n    ) {}\n\n    async getState() { /* ... */ }\n    async setState() { /* ... */ }\n}\n\nclass NotificationService {\n    async send() { /* ... */ }\n}\n
"},{"location":"development/best-practices.html#error-handling","title":"Error Handling","text":""},{"location":"development/best-practices.html#best-practices","title":"Best Practices","text":"
  1. Use custom error classes
  2. Include error codes
  3. Provide meaningful messages
  4. Include error context
  5. Handle async errors
  6. Log appropriately
class DeviceError extends Error {\n    constructor(\n        message: string,\n        public code: string,\n        public context: Record<string, any>\n    ) {\n        super(message);\n        this.name = 'DeviceError';\n    }\n}\n\ntry {\n    await device.connect();\n} catch (error) {\n    throw new DeviceError(\n        'Failed to connect to device',\n        'DEVICE_CONNECTION_ERROR',\n        { deviceId: device.id, attempt: 1 }\n    );\n}\n
"},{"location":"development/best-practices.html#testing","title":"Testing","text":""},{"location":"development/best-practices.html#guidelines","title":"Guidelines","text":"
  1. Write unit tests first
  2. Use meaningful descriptions
  3. Test edge cases
  4. Mock external dependencies
  5. Keep tests focused
  6. Use test fixtures
describe('DeviceManager', () => {\n    let manager: DeviceManager;\n    let mockDevice: jest.Mocked<Device>;\n\n    beforeEach(() => {\n        mockDevice = {\n            id: 'test_device',\n            getState: jest.fn()\n        };\n        manager = new DeviceManager(mockDevice);\n    });\n\n    it('should get device state', async () => {\n        mockDevice.getState.mockResolvedValue('on');\n        const state = await manager.getDeviceState();\n        expect(state).toBe('on');\n    });\n});\n
"},{"location":"development/best-practices.html#performance","title":"Performance","text":""},{"location":"development/best-practices.html#optimization","title":"Optimization","text":"
  1. Use caching
  2. Implement pagination
  3. Optimize database queries
  4. Use connection pooling
  5. Implement rate limiting
  6. Batch operations
class DeviceCache {\n    private cache = new Map<string, CacheEntry>();\n    private readonly TTL = 60000;  // 1 minute\n\n    async getDevice(id: string): Promise<Device> {\n        const cached = this.cache.get(id);\n        if (cached && Date.now() - cached.timestamp < this.TTL) {\n            return cached.device;\n        }\n\n        const device = await this.fetchDevice(id);\n        this.cache.set(id, {\n            device,\n            timestamp: Date.now()\n        });\n\n        return device;\n    }\n}\n
"},{"location":"development/best-practices.html#security","title":"Security","text":""},{"location":"development/best-practices.html#guidelines_1","title":"Guidelines","text":"
  1. Validate all input
  2. Use parameterized queries
  3. Implement rate limiting
  4. Use proper authentication
  5. Follow OWASP guidelines
  6. Sanitize output
class InputValidator {\n    static validateDeviceId(id: string): boolean {\n        return /^[a-zA-Z0-9_-]{1,64}$/.test(id);\n    }\n\n    static sanitizeOutput(data: any): any {\n        // Implement output sanitization\n        return data;\n    }\n}\n
"},{"location":"development/best-practices.html#documentation","title":"Documentation","text":""},{"location":"development/best-practices.html#standards","title":"Standards","text":"
  1. Use JSDoc comments
  2. Document interfaces
  3. Include examples
  4. Document errors
  5. Keep docs updated
  6. Use markdown
/**\n * Manages device operations.\n * @class\n */\nclass DeviceManager {\n    /**\n     * Gets the current state of a device.\n     * @param {string} deviceId - The device identifier.\n     * @returns {Promise<DeviceState>} The current device state.\n     * @throws {DeviceError} If device is not found or unavailable.\n     * @example\n     * const state = await deviceManager.getDeviceState('living_room_light');\n     */\n    async getDeviceState(deviceId: string): Promise<DeviceState> {\n        // Implementation\n    }\n}\n
"},{"location":"development/best-practices.html#logging","title":"Logging","text":""},{"location":"development/best-practices.html#best-practices_1","title":"Best Practices","text":"
  1. Use appropriate levels
  2. Include context
  3. Structure log data
  4. Handle sensitive data
  5. Implement rotation
  6. Use correlation IDs
class Logger {\n    info(message: string, context: Record<string, any>) {\n        console.log(JSON.stringify({\n            level: 'info',\n            message,\n            context,\n            timestamp: new Date().toISOString(),\n            correlationId: context.correlationId\n        }));\n    }\n}\n
"},{"location":"development/best-practices.html#version-control","title":"Version Control","text":""},{"location":"development/best-practices.html#guidelines_2","title":"Guidelines","text":"
  1. Use meaningful commits
  2. Follow branching strategy
  3. Write good PR descriptions
  4. Review code thoroughly
  5. Keep changes focused
  6. Use conventional commits
# Good commit messages\ngit commit -m \"feat(device): add support for zigbee devices\"\ngit commit -m \"fix(api): handle timeout errors properly\"\n
"},{"location":"development/best-practices.html#see-also","title":"See Also","text":""},{"location":"development/environment.html","title":"Development Environment Setup","text":"

This guide will help you set up your development environment for the Home Assistant MCP Server.

"},{"location":"development/environment.html#prerequisites","title":"Prerequisites","text":""},{"location":"development/environment.html#required-software","title":"Required Software","text":""},{"location":"development/environment.html#system-requirements","title":"System Requirements","text":""},{"location":"development/environment.html#initial-setup","title":"Initial Setup","text":"
  1. Clone the Repository

    git clone https://github.com/jango-blockchained/homeassistant-mcp.git\ncd homeassistant-mcp\n

  2. Create Virtual Environment

    python -m venv .venv\nsource .venv/bin/activate  # Linux/macOS\n# or\n.venv\\Scripts\\activate  # Windows\n

  3. Install Dependencies

    pip install -r requirements.txt\npip install -r docs/requirements.txt  # for documentation\n

"},{"location":"development/environment.html#development-tools","title":"Development Tools","text":""},{"location":"development/environment.html#code-editor-setup","title":"Code Editor Setup","text":"

We recommend using Visual Studio Code with these extensions: - Python - Docker - YAML - ESLint - Prettier

"},{"location":"development/environment.html#vs-code-settings","title":"VS Code Settings","text":"
{\n  \"python.linting.enabled\": true,\n  \"python.linting.pylintEnabled\": true,\n  \"python.formatting.provider\": \"black\",\n  \"editor.formatOnSave\": true\n}\n
"},{"location":"development/environment.html#configuration","title":"Configuration","text":"
  1. Create Local Config

    cp config.example.yaml config.yaml\n

  2. Set Environment Variables

    cp .env.example .env\n# Edit .env with your settings\n

"},{"location":"development/environment.html#running-tests","title":"Running Tests","text":""},{"location":"development/environment.html#unit-tests","title":"Unit Tests","text":"
pytest tests/unit\n
"},{"location":"development/environment.html#integration-tests","title":"Integration Tests","text":"
pytest tests/integration\n
"},{"location":"development/environment.html#coverage-report","title":"Coverage Report","text":"
pytest --cov=src tests/\n
"},{"location":"development/environment.html#docker-development","title":"Docker Development","text":""},{"location":"development/environment.html#build-container","title":"Build Container","text":"
docker build -t mcp-server-dev -f Dockerfile.dev .\n
"},{"location":"development/environment.html#run-development-container","title":"Run Development Container","text":"
docker run -it --rm \\\n  -v $(pwd):/app \\\n  -p 8123:8123 \\\n  mcp-server-dev\n
"},{"location":"development/environment.html#database-setup","title":"Database Setup","text":""},{"location":"development/environment.html#local-development-database","title":"Local Development Database","text":"
docker run -d \\\n  -p 5432:5432 \\\n  -e POSTGRES_USER=mcp \\\n  -e POSTGRES_PASSWORD=development \\\n  -e POSTGRES_DB=mcp_dev \\\n  postgres:14\n
"},{"location":"development/environment.html#run-migrations","title":"Run Migrations","text":"
alembic upgrade head\n
"},{"location":"development/environment.html#frontend-development","title":"Frontend Development","text":"
  1. Install Node.js Dependencies

    cd frontend\nnpm install\n

  2. Start Development Server

    npm run dev\n

"},{"location":"development/environment.html#documentation","title":"Documentation","text":""},{"location":"development/environment.html#build-documentation","title":"Build Documentation","text":"
mkdocs serve\n
"},{"location":"development/environment.html#view-documentation","title":"View Documentation","text":"

Open http://localhost:8000 in your browser

"},{"location":"development/environment.html#debugging","title":"Debugging","text":""},{"location":"development/environment.html#vs-code-launch-configuration","title":"VS Code Launch Configuration","text":"
{\n  \"version\": \"0.2.0\",\n  \"configurations\": [\n    {\n      \"name\": \"Python: MCP Server\",\n      \"type\": \"python\",\n      \"request\": \"launch\",\n      \"program\": \"src/main.py\",\n      \"console\": \"integratedTerminal\"\n    }\n  ]\n}\n
"},{"location":"development/environment.html#git-hooks","title":"Git Hooks","text":""},{"location":"development/environment.html#install-pre-commit","title":"Install Pre-commit","text":"
pip install pre-commit\npre-commit install\n
"},{"location":"development/environment.html#available-hooks","title":"Available Hooks","text":""},{"location":"development/environment.html#troubleshooting","title":"Troubleshooting","text":"

Common Issues: 1. Port already in use - Check for running processes: lsof -i :8123 - Kill process if needed: kill -9 PID

  1. Database connection issues
  2. Verify PostgreSQL is running
  3. Check connection settings in .env

  4. Virtual environment problems

  5. Delete and recreate: rm -rf .venv && python -m venv .venv
  6. Reinstall dependencies
"},{"location":"development/environment.html#next-steps","title":"Next Steps","text":"
  1. Review the Architecture Guide
  2. Check Contributing Guidelines
  3. Start with Simple Issues
"},{"location":"development/interfaces.html","title":"Interface Documentation","text":"

This document describes the core interfaces used throughout the Home Assistant MCP.

"},{"location":"development/interfaces.html#core-interfaces","title":"Core Interfaces","text":""},{"location":"development/interfaces.html#tool-interface","title":"Tool Interface","text":"
interface Tool {\n    /** Unique identifier for the tool */\n    id: string;\n\n    /** Human-readable name */\n    name: string;\n\n    /** Detailed description */\n    description: string;\n\n    /** Semantic version */\n    version: string;\n\n    /** Tool category */\n    category: ToolCategory;\n\n    /** Execute tool functionality */\n    execute(params: any): Promise<ToolResult>;\n}\n
"},{"location":"development/interfaces.html#tool-result","title":"Tool Result","text":"
interface ToolResult {\n    /** Operation success status */\n    success: boolean;\n\n    /** Response data */\n    data?: any;\n\n    /** Error message if failed */\n    message?: string;\n\n    /** Error code if failed */\n    error_code?: string;\n}\n
"},{"location":"development/interfaces.html#tool-category","title":"Tool Category","text":"
enum ToolCategory {\n    DeviceManagement = 'device_management',\n    HistoryState = 'history_state',\n    Automation = 'automation',\n    AddonsPackages = 'addons_packages',\n    Notifications = 'notifications',\n    Events = 'events',\n    Utility = 'utility'\n}\n
"},{"location":"development/interfaces.html#event-interfaces","title":"Event Interfaces","text":""},{"location":"development/interfaces.html#event-subscription","title":"Event Subscription","text":"
interface EventSubscription {\n    /** Unique subscription ID */\n    id: string;\n\n    /** Event type to subscribe to */\n    event_type: string;\n\n    /** Optional entity ID filter */\n    entity_id?: string;\n\n    /** Optional domain filter */\n    domain?: string;\n\n    /** Subscription creation timestamp */\n    created_at: string;\n\n    /** Last event timestamp */\n    last_event?: string;\n}\n
"},{"location":"development/interfaces.html#event-message","title":"Event Message","text":"
interface EventMessage {\n    /** Event type */\n    event_type: string;\n\n    /** Entity ID if applicable */\n    entity_id?: string;\n\n    /** Event data */\n    data: any;\n\n    /** Event origin */\n    origin: 'LOCAL' | 'REMOTE';\n\n    /** Event timestamp */\n    time_fired: string;\n\n    /** Event context */\n    context: EventContext;\n}\n
"},{"location":"development/interfaces.html#device-interfaces","title":"Device Interfaces","text":""},{"location":"development/interfaces.html#device","title":"Device","text":"
interface Device {\n    /** Device ID */\n    id: string;\n\n    /** Device name */\n    name: string;\n\n    /** Device domain */\n    domain: string;\n\n    /** Current state */\n    state: string;\n\n    /** Device attributes */\n    attributes: Record<string, any>;\n\n    /** Device capabilities */\n    capabilities: DeviceCapabilities;\n}\n
"},{"location":"development/interfaces.html#device-capabilities","title":"Device Capabilities","text":"
interface DeviceCapabilities {\n    /** Supported features */\n    features: string[];\n\n    /** Supported commands */\n    commands: string[];\n\n    /** State attributes */\n    attributes: {\n        /** Attribute name */\n        [key: string]: {\n            /** Attribute type */\n            type: 'string' | 'number' | 'boolean' | 'object';\n            /** Attribute description */\n            description: string;\n            /** Optional value constraints */\n            constraints?: {\n                min?: number;\n                max?: number;\n                enum?: any[];\n            };\n        };\n    };\n}\n
"},{"location":"development/interfaces.html#authentication-interfaces","title":"Authentication Interfaces","text":""},{"location":"development/interfaces.html#auth-token","title":"Auth Token","text":"
interface AuthToken {\n    /** Token value */\n    token: string;\n\n    /** Token type */\n    type: 'bearer' | 'jwt';\n\n    /** Expiration timestamp */\n    expires_at: string;\n\n    /** Token refresh info */\n    refresh?: {\n        token: string;\n        expires_at: string;\n    };\n}\n
"},{"location":"development/interfaces.html#user","title":"User","text":"
interface User {\n    /** User ID */\n    id: string;\n\n    /** Username */\n    username: string;\n\n    /** User type */\n    type: 'admin' | 'user' | 'service';\n\n    /** User permissions */\n    permissions: string[];\n}\n
"},{"location":"development/interfaces.html#error-interfaces","title":"Error Interfaces","text":""},{"location":"development/interfaces.html#tool-error","title":"Tool Error","text":"
interface ToolError extends Error {\n    /** Error code */\n    code: string;\n\n    /** HTTP status code */\n    status: number;\n\n    /** Error details */\n    details?: Record<string, any>;\n}\n
"},{"location":"development/interfaces.html#validation-error","title":"Validation Error","text":"
interface ValidationError {\n    /** Error path */\n    path: string;\n\n    /** Error message */\n    message: string;\n\n    /** Error code */\n    code: string;\n}\n
"},{"location":"development/interfaces.html#configuration-interfaces","title":"Configuration Interfaces","text":""},{"location":"development/interfaces.html#tool-configuration","title":"Tool Configuration","text":"
interface ToolConfig {\n    /** Enable/disable tool */\n    enabled: boolean;\n\n    /** Tool-specific settings */\n    settings: Record<string, any>;\n\n    /** Rate limiting */\n    rate_limit?: {\n        /** Max requests */\n        max: number;\n        /** Time window in seconds */\n        window: number;\n    };\n}\n
"},{"location":"development/interfaces.html#system-configuration","title":"System Configuration","text":"
interface SystemConfig {\n    /** System name */\n    name: string;\n\n    /** Environment */\n    environment: 'development' | 'production';\n\n    /** Log level */\n    log_level: 'debug' | 'info' | 'warn' | 'error';\n\n    /** Tool configurations */\n    tools: Record<string, ToolConfig>;\n}\n
"},{"location":"development/interfaces.html#best-practices","title":"Best Practices","text":"
  1. Use TypeScript for all interfaces
  2. Include JSDoc comments
  3. Use strict typing
  4. Keep interfaces focused
  5. Use consistent naming
  6. Document constraints
  7. Version interfaces
  8. Include examples
"},{"location":"development/interfaces.html#see-also","title":"See Also","text":""},{"location":"development/test-migration-guide.html","title":"Migrating Tests from Jest to Bun","text":"

This guide provides instructions for migrating test files from Jest to Bun's test framework.

"},{"location":"development/test-migration-guide.html#table-of-contents","title":"Table of Contents","text":""},{"location":"development/test-migration-guide.html#basic-setup","title":"Basic Setup","text":"
  1. Remove Jest-related dependencies from package.json:

    {\n  \"devDependencies\": {\n    \"@jest/globals\": \"...\",\n    \"jest\": \"...\",\n    \"ts-jest\": \"...\"\n  }\n}\n

  2. Remove Jest configuration files:

  3. jest.config.js
  4. jest.setup.js

  5. Update test scripts in package.json:

    {\n  \"scripts\": {\n    \"test\": \"bun test\",\n    \"test:watch\": \"bun test --watch\",\n    \"test:coverage\": \"bun test --coverage\"\n  }\n}\n

"},{"location":"development/test-migration-guide.html#import-changes","title":"Import Changes","text":""},{"location":"development/test-migration-guide.html#before-jest","title":"Before (Jest):","text":"
import { jest, describe, it, expect, beforeEach, afterEach } from '@jest/globals';\n
"},{"location":"development/test-migration-guide.html#after-bun","title":"After (Bun):","text":"
import { describe, expect, test, beforeEach, afterEach, mock } from \"bun:test\";\nimport type { Mock } from \"bun:test\";\n

Note: it is replaced with test in Bun.

"},{"location":"development/test-migration-guide.html#api-changes","title":"API Changes","text":""},{"location":"development/test-migration-guide.html#test-structure","title":"Test Structure","text":"
// Jest\ndescribe('Suite', () => {\n  it('should do something', () => {\n    // test\n  });\n});\n\n// Bun\ndescribe('Suite', () => {\n  test('should do something', () => {\n    // test\n  });\n});\n
"},{"location":"development/test-migration-guide.html#assertions","title":"Assertions","text":"

Most Jest assertions work the same in Bun:

// These work the same in both:\nexpect(value).toBe(expected);\nexpect(value).toEqual(expected);\nexpect(value).toBeDefined();\nexpect(value).toBeUndefined();\nexpect(value).toBeTruthy();\nexpect(value).toBeFalsy();\nexpect(array).toContain(item);\nexpect(value).toBeInstanceOf(Class);\nexpect(spy).toHaveBeenCalled();\nexpect(spy).toHaveBeenCalledWith(...args);\n
"},{"location":"development/test-migration-guide.html#mocking","title":"Mocking","text":""},{"location":"development/test-migration-guide.html#function-mocking","title":"Function Mocking","text":""},{"location":"development/test-migration-guide.html#before-jest_1","title":"Before (Jest):","text":"
const mockFn = jest.fn();\nmockFn.mockImplementation(() => 'result');\nmockFn.mockResolvedValue('result');\nmockFn.mockRejectedValue(new Error());\n
"},{"location":"development/test-migration-guide.html#after-bun_1","title":"After (Bun):","text":"
const mockFn = mock(() => 'result');\nconst mockAsyncFn = mock(() => Promise.resolve('result'));\nconst mockErrorFn = mock(() => Promise.reject(new Error()));\n
"},{"location":"development/test-migration-guide.html#module-mocking","title":"Module Mocking","text":""},{"location":"development/test-migration-guide.html#before-jest_2","title":"Before (Jest):","text":"
jest.mock('module-name', () => ({\n  default: jest.fn(),\n  namedExport: jest.fn()\n}));\n
"},{"location":"development/test-migration-guide.html#after-bun_2","title":"After (Bun):","text":"
// Option 1: Using vi.mock (if available)\nvi.mock('module-name', () => ({\n  default: mock(() => {}),\n  namedExport: mock(() => {})\n}));\n\n// Option 2: Using dynamic imports\nconst mockModule = {\n  default: mock(() => {}),\n  namedExport: mock(() => {})\n};\n
"},{"location":"development/test-migration-guide.html#mock-resetclear","title":"Mock Reset/Clear","text":""},{"location":"development/test-migration-guide.html#before-jest_3","title":"Before (Jest):","text":"
jest.clearAllMocks();\nmockFn.mockClear();\njest.resetModules();\n
"},{"location":"development/test-migration-guide.html#after-bun_3","title":"After (Bun):","text":"
mockFn.mockReset();\n// or for specific calls\nmockFn.mock.calls = [];\n
"},{"location":"development/test-migration-guide.html#spy-on-methods","title":"Spy on Methods","text":""},{"location":"development/test-migration-guide.html#before-jest_4","title":"Before (Jest):","text":"
jest.spyOn(object, 'method');\n
"},{"location":"development/test-migration-guide.html#after-bun_4","title":"After (Bun):","text":"
const spy = mock(((...args) => object.method(...args)));\nobject.method = spy;\n
"},{"location":"development/test-migration-guide.html#common-patterns","title":"Common Patterns","text":""},{"location":"development/test-migration-guide.html#async-tests","title":"Async Tests","text":"
// Works the same in both Jest and Bun:\ntest('async test', async () => {\n  const result = await someAsyncFunction();\n  expect(result).toBe(expected);\n});\n
"},{"location":"development/test-migration-guide.html#setup-and-teardown","title":"Setup and Teardown","text":"
describe('Suite', () => {\n  beforeEach(() => {\n    // setup\n  });\n\n  afterEach(() => {\n    // cleanup\n  });\n\n  test('test', () => {\n    // test\n  });\n});\n
"},{"location":"development/test-migration-guide.html#mocking-fetch","title":"Mocking Fetch","text":"
// Before (Jest)\nglobal.fetch = jest.fn(() => Promise.resolve(new Response()));\n\n// After (Bun)\nconst mockFetch = mock(() => Promise.resolve(new Response()));\nglobal.fetch = mockFetch as unknown as typeof fetch;\n
"},{"location":"development/test-migration-guide.html#mocking-websocket","title":"Mocking WebSocket","text":"
// Create a MockWebSocket class implementing WebSocket interface\nclass MockWebSocket implements WebSocket {\n  public static readonly CONNECTING = 0;\n  public static readonly OPEN = 1;\n  public static readonly CLOSING = 2;\n  public static readonly CLOSED = 3;\n\n  public readyState: 0 | 1 | 2 | 3 = MockWebSocket.OPEN;\n  public addEventListener = mock(() => undefined);\n  public removeEventListener = mock(() => undefined);\n  public send = mock(() => undefined);\n  public close = mock(() => undefined);\n  // ... implement other required methods\n}\n\n// Use it in tests\nglobal.WebSocket = MockWebSocket as unknown as typeof WebSocket;\n
"},{"location":"development/test-migration-guide.html#examples","title":"Examples","text":""},{"location":"development/test-migration-guide.html#basic-test","title":"Basic Test","text":"
import { describe, expect, test } from \"bun:test\";\n\ndescribe('formatToolCall', () => {\n  test('should format an object into the correct structure', () => {\n    const testObj = { name: 'test', value: 123 };\n    const result = formatToolCall(testObj);\n\n    expect(result).toEqual({\n      content: [{\n        type: 'text',\n        text: JSON.stringify(testObj, null, 2),\n        isError: false\n      }]\n    });\n  });\n});\n
"},{"location":"development/test-migration-guide.html#async-test-with-mocking","title":"Async Test with Mocking","text":"
import { describe, expect, test, mock } from \"bun:test\";\n\ndescribe('API Client', () => {\n  test('should fetch data', async () => {\n    const mockResponse = { data: 'test' };\n    const mockFetch = mock(() => Promise.resolve(new Response(\n      JSON.stringify(mockResponse),\n      { status: 200, headers: new Headers() }\n    )));\n    global.fetch = mockFetch as unknown as typeof fetch;\n\n    const result = await apiClient.getData();\n    expect(result).toEqual(mockResponse);\n  });\n});\n
"},{"location":"development/test-migration-guide.html#complex-mocking-example","title":"Complex Mocking Example","text":"
import { describe, expect, test, mock } from \"bun:test\";\nimport type { Mock } from \"bun:test\";\n\ninterface MockServices {\n  light: {\n    turn_on: Mock<() => Promise<{ success: boolean }>>;\n    turn_off: Mock<() => Promise<{ success: boolean }>>;\n  };\n}\n\nconst mockServices: MockServices = {\n  light: {\n    turn_on: mock(() => Promise.resolve({ success: true })),\n    turn_off: mock(() => Promise.resolve({ success: true }))\n  }\n};\n\ndescribe('Home Assistant Service', () => {\n  test('should control lights', async () => {\n    const result = await mockServices.light.turn_on();\n    expect(result.success).toBe(true);\n  });\n});\n
"},{"location":"development/test-migration-guide.html#best-practices","title":"Best Practices","text":"
  1. Use TypeScript for better type safety in mocks
  2. Keep mocks as simple as possible
  3. Prefer interface-based mocks over concrete implementations
  4. Use proper type assertions when necessary
  5. Clean up mocks in afterEach blocks
  6. Use descriptive test names
  7. Group related tests using describe blocks
"},{"location":"development/test-migration-guide.html#common-issues-and-solutions","title":"Common Issues and Solutions","text":""},{"location":"development/test-migration-guide.html#issue-type-errors-with-mocks","title":"Issue: Type Errors with Mocks","text":"
// Solution: Use proper typing with Mock type\nimport type { Mock } from \"bun:test\";\nconst mockFn: Mock<() => string> = mock(() => \"result\");\n
"},{"location":"development/test-migration-guide.html#issue-global-object-mocking","title":"Issue: Global Object Mocking","text":"
// Solution: Use type assertions carefully\nglobal.someGlobal = mockImplementation as unknown as typeof someGlobal;\n
"},{"location":"development/test-migration-guide.html#issue-module-mocking","title":"Issue: Module Mocking","text":"
// Solution: Use dynamic imports or vi.mock if available\nconst mockModule = {\n  default: mock(() => mockImplementation)\n};\n
"},{"location":"development/tools.html","title":"Tool Development Guide","text":"

This guide explains how to create new tools for the Home Assistant MCP.

"},{"location":"development/tools.html#tool-structure","title":"Tool Structure","text":"

Each tool should follow this basic structure:

interface Tool {\n    id: string;\n    name: string;\n    description: string;\n    version: string;\n    category: ToolCategory;\n    execute(params: any): Promise<ToolResult>;\n}\n
"},{"location":"development/tools.html#creating-a-new-tool","title":"Creating a New Tool","text":"
  1. Create a new file in the appropriate category directory
  2. Implement the Tool interface
  3. Add API endpoints
  4. Add WebSocket handlers
  5. Add documentation
  6. Add tests
"},{"location":"development/tools.html#example-tool-implementation","title":"Example Tool Implementation","text":"
import { Tool, ToolCategory, ToolResult } from '../interfaces';\n\nexport class MyCustomTool implements Tool {\n    id = 'my_custom_tool';\n    name = 'My Custom Tool';\n    description = 'Description of what the tool does';\n    version = '1.0.0';\n    category = ToolCategory.Utility;\n\n    async execute(params: any): Promise<ToolResult> {\n        // Tool implementation\n        return {\n            success: true,\n            data: {\n                // Tool-specific response data\n            }\n        };\n    }\n}\n
"},{"location":"development/tools.html#tool-categories","title":"Tool Categories","text":""},{"location":"development/tools.html#api-integration","title":"API Integration","text":""},{"location":"development/tools.html#rest-endpoint","title":"REST Endpoint","text":"
import { Router } from 'express';\nimport { MyCustomTool } from './my-custom-tool';\n\nconst router = Router();\nconst tool = new MyCustomTool();\n\nrouter.post('/api/tools/custom', async (req, res) => {\n    try {\n        const result = await tool.execute(req.body);\n        res.json(result);\n    } catch (error) {\n        res.status(500).json({\n            success: false,\n            message: error.message\n        });\n    }\n});\n
"},{"location":"development/tools.html#websocket-handler","title":"WebSocket Handler","text":"
import { WebSocketServer } from 'ws';\nimport { MyCustomTool } from './my-custom-tool';\n\nconst tool = new MyCustomTool();\n\nwss.on('connection', (ws) => {\n    ws.on('message', async (message) => {\n        const { type, params } = JSON.parse(message);\n        if (type === 'my_custom_tool') {\n            const result = await tool.execute(params);\n            ws.send(JSON.stringify(result));\n        }\n    });\n});\n
"},{"location":"development/tools.html#error-handling","title":"Error Handling","text":"
class ToolError extends Error {\n    constructor(\n        message: string,\n        public code: string,\n        public status: number = 500\n    ) {\n        super(message);\n        this.name = 'ToolError';\n    }\n}\n\n// Usage in tool\nasync execute(params: any): Promise<ToolResult> {\n    try {\n        // Tool implementation\n    } catch (error) {\n        throw new ToolError(\n            'Operation failed',\n            'TOOL_ERROR',\n            500\n        );\n    }\n}\n
"},{"location":"development/tools.html#testing","title":"Testing","text":"
import { MyCustomTool } from './my-custom-tool';\n\ndescribe('MyCustomTool', () => {\n    let tool: MyCustomTool;\n\n    beforeEach(() => {\n        tool = new MyCustomTool();\n    });\n\n    it('should execute successfully', async () => {\n        const result = await tool.execute({\n            // Test parameters\n        });\n        expect(result.success).toBe(true);\n    });\n\n    it('should handle errors', async () => {\n        // Error test cases\n    });\n});\n
"},{"location":"development/tools.html#documentation","title":"Documentation","text":"
  1. Create tool documentation in docs/tools/category/tool-name.md
  2. Update tools/tools.md with tool reference
  3. Add tool to navigation in mkdocs.yml
"},{"location":"development/tools.html#documentation-template","title":"Documentation Template","text":"
# Tool Name\n\nDescription of the tool.\n\n## Features\n\n- Feature 1\n- Feature 2\n\n## Usage\n\n### REST API\n\n```typescript\n// API endpoints\n
"},{"location":"development/tools.html#websocket","title":"WebSocket","text":"
// WebSocket usage\n
"},{"location":"development/tools.html#examples","title":"Examples","text":""},{"location":"development/tools.html#example-1","title":"Example 1","text":"
// Usage example\n
"},{"location":"development/tools.html#response-format","title":"Response Format","text":"

{\n    \"success\": true,\n    \"data\": {\n        // Response data structure\n    }\n}\n
```

"},{"location":"development/tools.html#best-practices","title":"Best Practices","text":"
  1. Follow consistent naming conventions
  2. Implement proper error handling
  3. Add comprehensive documentation
  4. Write thorough tests
  5. Use TypeScript for type safety
  6. Follow SOLID principles
  7. Implement rate limiting
  8. Add proper logging
"},{"location":"development/tools.html#see-also","title":"See Also","text":""},{"location":"examples/index.html","title":"Example Projects \ud83d\udcda","text":"

This section contains examples and tutorials for common MCP Server integrations.

"},{"location":"examples/index.html#speech-to-text-integration","title":"Speech-to-Text Integration","text":"

Example of integrating speech recognition with MCP Server:

// From examples/speech-to-text-example.ts\n// Add example code and explanation\n
"},{"location":"examples/index.html#more-examples-coming-soon","title":"More Examples Coming Soon","text":"

...

"},{"location":"getting-started/index.html","title":"Getting Started","text":"

Welcome to the Advanced Home Assistant MCP getting started guide. Follow these steps to begin:

  1. Installation
  2. Configuration
  3. Docker Setup
  4. Quick Start
"},{"location":"getting-started/configuration.html","title":"Configuration","text":""},{"location":"getting-started/configuration.html#basic-configuration","title":"Basic Configuration","text":""},{"location":"getting-started/configuration.html#advanced-settings","title":"Advanced Settings","text":""},{"location":"getting-started/docker.html","title":"Docker Deployment Guide \ud83d\udc33","text":"

Detailed guide for deploying MCP Server with Docker...

"},{"location":"getting-started/installation.html","title":"Installation Guide \ud83d\udee0\ufe0f","text":"

This guide covers different methods to install and set up the MCP Server for Home Assistant. Choose the installation method that best suits your needs.

"},{"location":"getting-started/installation.html#prerequisites","title":"Prerequisites","text":"

Before installing MCP Server, ensure you have:

"},{"location":"getting-started/installation.html#installation-methods","title":"Installation Methods","text":""},{"location":"getting-started/installation.html#1-smithery-installation-recommended","title":"1. \ud83d\udd27 Smithery Installation (Recommended)","text":"

The easiest way to install MCP Server is through Smithery:

"},{"location":"getting-started/installation.html#smithery-configuration","title":"Smithery Configuration","text":"

The project includes a smithery.yaml configuration:

# Add smithery.yaml contents and explanation\n
"},{"location":"getting-started/installation.html#installation-steps","title":"Installation Steps","text":"
npx -y @smithery/cli install @jango-blockchained/advanced-homeassistant-mcp --client claude\n
"},{"location":"getting-started/installation.html#2-docker-installation","title":"2. \ud83d\udc33 Docker Installation","text":"

For a containerized deployment:

# Clone the repository\ngit clone --depth 1 https://github.com/jango-blockchained/advanced-homeassistant-mcp.git\ncd advanced-homeassistant-mcp\n\n# Configure environment variables\ncp .env.example .env\n# Edit .env with your Home Assistant details:\n# - HA_URL: Your Home Assistant URL\n# - HA_TOKEN: Your Long-Lived Access Token\n# - Other configuration options\n\n# Build and start containers\ndocker compose up -d --build\n\n# View logs (optional)\ndocker compose logs -f --tail=50\n
"},{"location":"getting-started/installation.html#3-manual-installation","title":"3. \ud83d\udcbb Manual Installation","text":"

For direct installation on your system:

# Install Bun runtime\ncurl -fsSL https://bun.sh/install | bash\n\n# Clone and install\ngit clone https://github.com/jango-blockchained/advanced-homeassistant-mcp.git\ncd advanced-homeassistant-mcp\nbun install --frozen-lockfile\n\n# Configure environment\ncp .env.example .env\n# Edit .env with your configuration\n\n# Start the server\nbun run dev --watch\n
"},{"location":"getting-started/installation.html#configuration","title":"Configuration","text":""},{"location":"getting-started/installation.html#environment-variables","title":"Environment Variables","text":"

Key configuration options in your .env file:

# Home Assistant Configuration\nHA_URL=http://your-homeassistant:8123\nHA_TOKEN=your_long_lived_access_token\n\n# Server Configuration\nPORT=3000\nHOST=0.0.0.0\nNODE_ENV=production\n\n# Security Settings\nJWT_SECRET=your_secure_jwt_secret\nRATE_LIMIT=100\n
"},{"location":"getting-started/installation.html#client-integration","title":"Client Integration","text":""},{"location":"getting-started/installation.html#cursor-integration","title":"Cursor Integration","text":"

Add to .cursor/config/config.json:

{\n  \"mcpServers\": {\n    \"homeassistant-mcp\": {\n      \"command\": \"bun\",\n      \"args\": [\"run\", \"start\"],\n      \"cwd\": \"${workspaceRoot}\",\n      \"env\": {\n        \"NODE_ENV\": \"development\"\n      }\n    }\n  }\n}\n
"},{"location":"getting-started/installation.html#claude-desktop-integration","title":"Claude Desktop Integration","text":"

Add to your Claude configuration:

{\n  \"mcpServers\": {\n    \"homeassistant-mcp\": {\n      \"command\": \"bun\",\n      \"args\": [\"run\", \"start\", \"--port\", \"8080\"],\n      \"env\": {\n        \"NODE_ENV\": \"production\"\n      }\n    }\n  }\n}\n
"},{"location":"getting-started/installation.html#verification","title":"Verification","text":"

To verify your installation:

  1. Check server status:

    curl http://localhost:3000/health\n

  2. Test Home Assistant connection:

    curl http://localhost:3000/api/state\n

"},{"location":"getting-started/installation.html#troubleshooting","title":"Troubleshooting","text":"

If you encounter issues:

  1. Check the Troubleshooting Guide
  2. Verify your environment variables
  3. Check server logs:
    # For Docker installation\ndocker compose logs -f\n\n# For manual installation\nbun run dev\n
"},{"location":"getting-started/installation.html#next-steps","title":"Next Steps","text":""},{"location":"getting-started/installation.html#support","title":"Support","text":"

Need help? Check our Support Resources or open an issue.

"},{"location":"getting-started/quickstart.html","title":"Quick Start Guide \ud83d\ude80","text":"

This guide will help you get started with MCP Server after installation. We'll cover basic usage, common commands, and simple integrations.

"},{"location":"getting-started/quickstart.html#first-steps","title":"First Steps","text":""},{"location":"getting-started/quickstart.html#1-verify-connection","title":"1. Verify Connection","text":"

After installation, verify your MCP Server is running and connected to Home Assistant:

# Check server health\ncurl http://localhost:3000/health\n\n# Verify Home Assistant connection\ncurl http://localhost:3000/api/state\n
"},{"location":"getting-started/quickstart.html#2-basic-voice-commands","title":"2. Basic Voice Commands","text":"

Try these basic voice commands to test your setup:

# Example using curl for testing\ncurl -X POST http://localhost:3000/api/command \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"command\": \"Turn on the living room lights\"}'\n

Common voice commands: - \"Turn on/off [device name]\" - \"Set [device] to [value]\" - \"What's the temperature in [room]?\" - \"Is [device] on or off?\"

"},{"location":"getting-started/quickstart.html#real-world-examples","title":"Real-World Examples","text":""},{"location":"getting-started/quickstart.html#1-smart-lighting-control","title":"1. Smart Lighting Control","text":"
// Browser example using fetch\nconst response = await fetch('http://localhost:3000/api/command', {\n  method: 'POST',\n  headers: {\n    'Content-Type': 'application/json',\n  },\n  body: JSON.stringify({\n    command: 'Set living room lights to 50% brightness and warm white color'\n  })\n});\n
"},{"location":"getting-started/quickstart.html#2-real-time-updates","title":"2. Real-Time Updates","text":"

Subscribe to device state changes using Server-Sent Events (SSE):

const eventSource = new EventSource('http://localhost:3000/subscribe_events?token=YOUR_TOKEN&domain=light');\n\neventSource.onmessage = (event) => {\n    const data = JSON.parse(event.data);\n    console.log('Device state changed:', data);\n    // Update your UI here\n};\n
"},{"location":"getting-started/quickstart.html#3-scene-automation","title":"3. Scene Automation","text":"

Create and trigger scenes for different activities:

// Create a \"Movie Night\" scene\nconst createScene = async () => {\n  await fetch('http://localhost:3000/api/scene', {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application/json',\n    },\n    body: JSON.stringify({\n      name: 'Movie Night',\n      actions: [\n        { device: 'living_room_lights', action: 'dim', value: 20 },\n        { device: 'tv', action: 'on' },\n        { device: 'soundbar', action: 'on' }\n      ]\n    })\n  });\n};\n\n// Trigger the scene with voice command:\n// \"Hey MCP, activate movie night scene\"\n
"},{"location":"getting-started/quickstart.html#integration-examples","title":"Integration Examples","text":""},{"location":"getting-started/quickstart.html#1-web-dashboard-integration","title":"1. Web Dashboard Integration","text":"
// React component example\nfunction SmartHomeControl() {\n    const [devices, setDevices] = useState([]);\n\n    useEffect(() => {\n        // Subscribe to device updates\n        const events = new EventSource('http://localhost:3000/subscribe_events');\n        events.onmessage = (event) => {\n            const data = JSON.parse(event.data);\n            setDevices(currentDevices => \n                currentDevices.map(device => \n                    device.id === data.id ? {...device, ...data} : device\n                )\n            );\n        };\n\n        return () => events.close();\n    }, []);\n\n    return (\n        <div className=\"dashboard\">\n            {devices.map(device => (\n                <DeviceCard key={device.id} device={device} />\n            ))}\n        </div>\n    );\n}\n
"},{"location":"getting-started/quickstart.html#2-voice-assistant-integration","title":"2. Voice Assistant Integration","text":"
// Example using speech-to-text with MCP\nasync function handleVoiceCommand(audioBlob: Blob) {\n    // First, convert speech to text\n    const text = await speechToText(audioBlob);\n\n    // Then send command to MCP\n    const response = await fetch('http://localhost:3000/api/command', {\n        method: 'POST',\n        headers: {\n            'Content-Type': 'application/json',\n        },\n        body: JSON.stringify({ command: text })\n    });\n\n    return response.json();\n}\n
"},{"location":"getting-started/quickstart.html#best-practices","title":"Best Practices","text":"
  1. Error Handling

    try {\n    const response = await fetch('http://localhost:3000/api/command', {\n        method: 'POST',\n        headers: {\n            'Content-Type': 'application/json',\n        },\n        body: JSON.stringify({ command: 'Turn on lights' })\n    });\n\n    if (!response.ok) {\n        throw new Error(`HTTP error! status: ${response.status}`);\n    }\n\n    const data = await response.json();\n} catch (error) {\n    console.error('Error:', error);\n    // Handle error appropriately\n}\n

  2. Connection Management

    class MCPConnection {\n    constructor() {\n        this.eventSource = null;\n        this.reconnectAttempts = 0;\n    }\n\n    connect() {\n        this.eventSource = new EventSource('http://localhost:3000/subscribe_events');\n        this.eventSource.onerror = this.handleError.bind(this);\n    }\n\n    handleError() {\n        if (this.reconnectAttempts < 3) {\n            setTimeout(() => {\n                this.reconnectAttempts++;\n                this.connect();\n            }, 1000 * this.reconnectAttempts);\n        }\n    }\n}\n

"},{"location":"getting-started/quickstart.html#next-steps","title":"Next Steps","text":""},{"location":"getting-started/quickstart.html#troubleshooting","title":"Troubleshooting","text":"

If you encounter issues: - Verify your authentication token - Check server logs for errors - Ensure Home Assistant is accessible - Review the Troubleshooting Guide

Need more help? Visit our Support Resources.

"},{"location":"tools/index.html","title":"Tools Overview","text":"

The Home Assistant MCP Server provides a variety of tools to help you manage and interact with your home automation system.

"},{"location":"tools/index.html#available-tools","title":"Available Tools","text":""},{"location":"tools/index.html#device-management","title":"Device Management","text":""},{"location":"tools/index.html#history-state","title":"History & State","text":""},{"location":"tools/index.html#automation","title":"Automation","text":""},{"location":"tools/index.html#add-ons-packages","title":"Add-ons & Packages","text":""},{"location":"tools/index.html#notifications","title":"Notifications","text":""},{"location":"tools/index.html#events","title":"Events","text":""},{"location":"tools/index.html#getting-started","title":"Getting Started","text":"

To get started with these tools:

  1. Ensure you have the MCP Server properly installed and configured
  2. Check the specific tool documentation for detailed usage instructions
  3. Use the API endpoints or command-line interface as needed
"},{"location":"tools/index.html#next-steps","title":"Next Steps","text":""},{"location":"tools/addons-packages/addon.html","title":"Add-on Management Tool","text":"

The Add-on Management tool provides functionality to manage Home Assistant add-ons through the MCP interface.

"},{"location":"tools/addons-packages/addon.html#features","title":"Features","text":""},{"location":"tools/addons-packages/addon.html#usage","title":"Usage","text":""},{"location":"tools/addons-packages/addon.html#rest-api","title":"REST API","text":"
GET /api/addons\nGET /api/addons/{addon_slug}\nPOST /api/addons/{addon_slug}/install\nPOST /api/addons/{addon_slug}/uninstall\nPOST /api/addons/{addon_slug}/start\nPOST /api/addons/{addon_slug}/stop\nPOST /api/addons/{addon_slug}/restart\nGET /api/addons/{addon_slug}/logs\nPUT /api/addons/{addon_slug}/config\nGET /api/addons/{addon_slug}/stats\n
"},{"location":"tools/addons-packages/addon.html#websocket","title":"WebSocket","text":"
// List add-ons\n{\n    \"type\": \"get_addons\"\n}\n\n// Get add-on info\n{\n    \"type\": \"get_addon_info\",\n    \"addon_slug\": \"required_addon_slug\"\n}\n\n// Install add-on\n{\n    \"type\": \"install_addon\",\n    \"addon_slug\": \"required_addon_slug\",\n    \"version\": \"optional_version\"\n}\n\n// Control add-on\n{\n    \"type\": \"control_addon\",\n    \"addon_slug\": \"required_addon_slug\",\n    \"action\": \"start|stop|restart\"\n}\n
"},{"location":"tools/addons-packages/addon.html#examples","title":"Examples","text":""},{"location":"tools/addons-packages/addon.html#list-all-add-ons","title":"List All Add-ons","text":"
const response = await fetch('http://your-ha-mcp/api/addons', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst addons = await response.json();\n
"},{"location":"tools/addons-packages/addon.html#install-add-on","title":"Install Add-on","text":"
const response = await fetch('http://your-ha-mcp/api/addons/mosquitto/install', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"version\": \"latest\"\n    })\n});\n
"},{"location":"tools/addons-packages/addon.html#configure-add-on","title":"Configure Add-on","text":"
const response = await fetch('http://your-ha-mcp/api/addons/mosquitto/config', {\n    method: 'PUT',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"logins\": [\n            {\n                \"username\": \"mqtt_user\",\n                \"password\": \"mqtt_password\"\n            }\n        ],\n        \"customize\": {\n            \"active\": true,\n            \"folder\": \"mosquitto\"\n        }\n    })\n});\n
"},{"location":"tools/addons-packages/addon.html#response-format","title":"Response Format","text":""},{"location":"tools/addons-packages/addon.html#add-on-list-response","title":"Add-on List Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"addons\": [\n            {\n                \"slug\": \"addon_slug\",\n                \"name\": \"Add-on Name\",\n                \"version\": \"1.0.0\",\n                \"state\": \"started\",\n                \"repository\": \"core\",\n                \"installed\": true,\n                \"update_available\": false\n            }\n        ]\n    }\n}\n
"},{"location":"tools/addons-packages/addon.html#add-on-info-response","title":"Add-on Info Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"addon\": {\n            \"slug\": \"addon_slug\",\n            \"name\": \"Add-on Name\",\n            \"version\": \"1.0.0\",\n            \"description\": \"Add-on description\",\n            \"long_description\": \"Detailed description\",\n            \"repository\": \"core\",\n            \"installed\": true,\n            \"state\": \"started\",\n            \"webui\": \"http://[HOST]:[PORT:80]\",\n            \"boot\": \"auto\",\n            \"options\": {\n                // Add-on specific options\n            },\n            \"schema\": {\n                // Add-on options schema\n            },\n            \"ports\": {\n                \"80/tcp\": 8080\n            },\n            \"ingress\": true,\n            \"ingress_port\": 8099\n        }\n    }\n}\n
"},{"location":"tools/addons-packages/addon.html#add-on-stats-response","title":"Add-on Stats Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"stats\": {\n            \"cpu_percent\": 2.5,\n            \"memory_usage\": 128974848,\n            \"memory_limit\": 536870912,\n            \"network_rx\": 1234,\n            \"network_tx\": 5678,\n            \"blk_read\": 12345,\n            \"blk_write\": 67890\n        }\n    }\n}\n
"},{"location":"tools/addons-packages/addon.html#error-handling","title":"Error Handling","text":""},{"location":"tools/addons-packages/addon.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/addons-packages/addon.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/addons-packages/addon.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/addons-packages/addon.html#best-practices","title":"Best Practices","text":"
  1. Always check add-on compatibility
  2. Back up configurations before updates
  3. Monitor resource usage
  4. Use appropriate update strategies
  5. Implement proper error handling
  6. Test configurations in safe environment
  7. Handle rate limiting gracefully
  8. Keep add-ons updated
"},{"location":"tools/addons-packages/addon.html#add-on-security","title":"Add-on Security","text":""},{"location":"tools/addons-packages/addon.html#see-also","title":"See Also","text":""},{"location":"tools/addons-packages/package.html","title":"Package Management Tool","text":"

The Package Management tool provides functionality to manage Home Assistant Community Store (HACS) packages through the MCP interface.

"},{"location":"tools/addons-packages/package.html#features","title":"Features","text":""},{"location":"tools/addons-packages/package.html#usage","title":"Usage","text":""},{"location":"tools/addons-packages/package.html#rest-api","title":"REST API","text":"
GET /api/packages\nGET /api/packages/{package_id}\nPOST /api/packages/{package_id}/install\nPOST /api/packages/{package_id}/uninstall\nPOST /api/packages/{package_id}/update\nGET /api/packages/search\nGET /api/packages/categories\nGET /api/packages/repositories\n
"},{"location":"tools/addons-packages/package.html#websocket","title":"WebSocket","text":"
// List packages\n{\n    \"type\": \"get_packages\",\n    \"category\": \"optional_category\"\n}\n\n// Search packages\n{\n    \"type\": \"search_packages\",\n    \"query\": \"search_query\",\n    \"category\": \"optional_category\"\n}\n\n// Install package\n{\n    \"type\": \"install_package\",\n    \"package_id\": \"required_package_id\",\n    \"version\": \"optional_version\"\n}\n
"},{"location":"tools/addons-packages/package.html#package-categories","title":"Package Categories","text":""},{"location":"tools/addons-packages/package.html#examples","title":"Examples","text":""},{"location":"tools/addons-packages/package.html#list-all-packages","title":"List All Packages","text":"
const response = await fetch('http://your-ha-mcp/api/packages', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst packages = await response.json();\n
"},{"location":"tools/addons-packages/package.html#search-packages","title":"Search Packages","text":"
const response = await fetch('http://your-ha-mcp/api/packages/search?q=weather&category=integrations', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst searchResults = await response.json();\n
"},{"location":"tools/addons-packages/package.html#install-package","title":"Install Package","text":"
const response = await fetch('http://your-ha-mcp/api/packages/custom-weather-card/install', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"version\": \"latest\"\n    })\n});\n
"},{"location":"tools/addons-packages/package.html#response-format","title":"Response Format","text":""},{"location":"tools/addons-packages/package.html#package-list-response","title":"Package List Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"packages\": [\n            {\n                \"id\": \"package_id\",\n                \"name\": \"Package Name\",\n                \"category\": \"integrations\",\n                \"description\": \"Package description\",\n                \"version\": \"1.0.0\",\n                \"installed\": true,\n                \"update_available\": false,\n                \"stars\": 150,\n                \"downloads\": 10000\n            }\n        ]\n    }\n}\n
"},{"location":"tools/addons-packages/package.html#package-info-response","title":"Package Info Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"package\": {\n            \"id\": \"package_id\",\n            \"name\": \"Package Name\",\n            \"category\": \"integrations\",\n            \"description\": \"Package description\",\n            \"long_description\": \"Detailed description\",\n            \"version\": \"1.0.0\",\n            \"installed_version\": \"0.9.0\",\n            \"available_version\": \"1.0.0\",\n            \"installed\": true,\n            \"update_available\": true,\n            \"stars\": 150,\n            \"downloads\": 10000,\n            \"repository\": \"https://github.com/author/repo\",\n            \"author\": {\n                \"name\": \"Author Name\",\n                \"url\": \"https://github.com/author\"\n            },\n            \"documentation\": \"https://github.com/author/repo/wiki\",\n            \"dependencies\": [\n                \"dependency1\",\n                \"dependency2\"\n            ]\n        }\n    }\n}\n
"},{"location":"tools/addons-packages/package.html#search-response","title":"Search Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"results\": [\n            {\n                \"id\": \"package_id\",\n                \"name\": \"Package Name\",\n                \"category\": \"integrations\",\n                \"description\": \"Package description\",\n                \"version\": \"1.0.0\",\n                \"score\": 0.95\n            }\n        ],\n        \"total\": 42\n    }\n}\n
"},{"location":"tools/addons-packages/package.html#error-handling","title":"Error Handling","text":""},{"location":"tools/addons-packages/package.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/addons-packages/package.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/addons-packages/package.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/addons-packages/package.html#best-practices","title":"Best Practices","text":"
  1. Check package compatibility
  2. Review package documentation
  3. Verify package dependencies
  4. Back up before updates
  5. Test in safe environment
  6. Monitor resource usage
  7. Keep packages updated
  8. Handle rate limiting gracefully
"},{"location":"tools/addons-packages/package.html#package-security","title":"Package Security","text":""},{"location":"tools/addons-packages/package.html#see-also","title":"See Also","text":""},{"location":"tools/automation/automation-config.html","title":"Automation Configuration Tool","text":"

The Automation Configuration tool provides functionality to create, update, and manage Home Assistant automation configurations.

"},{"location":"tools/automation/automation-config.html#features","title":"Features","text":""},{"location":"tools/automation/automation-config.html#usage","title":"Usage","text":""},{"location":"tools/automation/automation-config.html#rest-api","title":"REST API","text":"
POST /api/automations\nPUT /api/automations/{automation_id}\nDELETE /api/automations/{automation_id}\nPOST /api/automations/{automation_id}/duplicate\nPOST /api/automations/validate\n
"},{"location":"tools/automation/automation-config.html#websocket","title":"WebSocket","text":"
// Create automation\n{\n    \"type\": \"create_automation\",\n    \"automation\": {\n        // Automation configuration\n    }\n}\n\n// Update automation\n{\n    \"type\": \"update_automation\",\n    \"automation_id\": \"required_automation_id\",\n    \"automation\": {\n        // Updated configuration\n    }\n}\n\n// Delete automation\n{\n    \"type\": \"delete_automation\",\n    \"automation_id\": \"required_automation_id\"\n}\n
"},{"location":"tools/automation/automation-config.html#automation-configuration","title":"Automation Configuration","text":""},{"location":"tools/automation/automation-config.html#basic-structure","title":"Basic Structure","text":"
{\n    \"id\": \"morning_routine\",\n    \"alias\": \"Morning Routine\",\n    \"description\": \"Turn on lights and adjust temperature in the morning\",\n    \"trigger\": [\n        {\n            \"platform\": \"time\",\n            \"at\": \"07:00:00\"\n        }\n    ],\n    \"condition\": [\n        {\n            \"condition\": \"time\",\n            \"weekday\": [\"mon\", \"tue\", \"wed\", \"thu\", \"fri\"]\n        }\n    ],\n    \"action\": [\n        {\n            \"service\": \"light.turn_on\",\n            \"target\": {\n                \"entity_id\": \"light.bedroom\"\n            },\n            \"data\": {\n                \"brightness\": 255,\n                \"transition\": 300\n            }\n        }\n    ],\n    \"mode\": \"single\"\n}\n
"},{"location":"tools/automation/automation-config.html#trigger-types","title":"Trigger Types","text":"
// Time-based trigger\n{\n    \"platform\": \"time\",\n    \"at\": \"07:00:00\"\n}\n\n// State-based trigger\n{\n    \"platform\": \"state\",\n    \"entity_id\": \"binary_sensor.motion\",\n    \"to\": \"on\"\n}\n\n// Event-based trigger\n{\n    \"platform\": \"event\",\n    \"event_type\": \"custom_event\"\n}\n\n// Numeric state trigger\n{\n    \"platform\": \"numeric_state\",\n    \"entity_id\": \"sensor.temperature\",\n    \"above\": 25\n}\n
"},{"location":"tools/automation/automation-config.html#condition-types","title":"Condition Types","text":"
// Time condition\n{\n    \"condition\": \"time\",\n    \"after\": \"07:00:00\",\n    \"before\": \"22:00:00\"\n}\n\n// State condition\n{\n    \"condition\": \"state\",\n    \"entity_id\": \"device_tracker.phone\",\n    \"state\": \"home\"\n}\n\n// Numeric state condition\n{\n    \"condition\": \"numeric_state\",\n    \"entity_id\": \"sensor.temperature\",\n    \"below\": 25\n}\n
"},{"location":"tools/automation/automation-config.html#action-types","title":"Action Types","text":"
// Service call action\n{\n    \"service\": \"light.turn_on\",\n    \"target\": {\n        \"entity_id\": \"light.bedroom\"\n    }\n}\n\n// Delay action\n{\n    \"delay\": \"00:00:30\"\n}\n\n// Scene activation\n{\n    \"scene\": \"scene.evening_mode\"\n}\n\n// Conditional action\n{\n    \"choose\": [\n        {\n            \"conditions\": [\n                {\n                    \"condition\": \"state\",\n                    \"entity_id\": \"sun.sun\",\n                    \"state\": \"below_horizon\"\n                }\n            ],\n            \"sequence\": [\n                {\n                    \"service\": \"light.turn_on\",\n                    \"target\": {\n                        \"entity_id\": \"light.living_room\"\n                    }\n                }\n            ]\n        }\n    ]\n}\n
"},{"location":"tools/automation/automation-config.html#examples","title":"Examples","text":""},{"location":"tools/automation/automation-config.html#create-new-automation","title":"Create New Automation","text":"
const response = await fetch('http://your-ha-mcp/api/automations', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"alias\": \"Morning Routine\",\n        \"description\": \"Turn on lights in the morning\",\n        \"trigger\": [\n            {\n                \"platform\": \"time\",\n                \"at\": \"07:00:00\"\n            }\n        ],\n        \"action\": [\n            {\n                \"service\": \"light.turn_on\",\n                \"target\": {\n                    \"entity_id\": \"light.bedroom\"\n                }\n            }\n        ]\n    })\n});\n
"},{"location":"tools/automation/automation-config.html#update-existing-automation","title":"Update Existing Automation","text":"
const response = await fetch('http://your-ha-mcp/api/automations/morning_routine', {\n    method: 'PUT',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"alias\": \"Morning Routine\",\n        \"trigger\": [\n            {\n                \"platform\": \"time\",\n                \"at\": \"07:30:00\"  // Updated time\n            }\n        ],\n        \"action\": [\n            {\n                \"service\": \"light.turn_on\",\n                \"target\": {\n                    \"entity_id\": \"light.bedroom\"\n                }\n            }\n        ]\n    })\n});\n
"},{"location":"tools/automation/automation-config.html#response-format","title":"Response Format","text":""},{"location":"tools/automation/automation-config.html#success-response","title":"Success Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"automation\": {\n            \"id\": \"created_automation_id\",\n            // Full automation configuration\n        }\n    }\n}\n
"},{"location":"tools/automation/automation-config.html#validation-response","title":"Validation Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"valid\": true,\n        \"warnings\": [\n            \"No conditions specified\"\n        ]\n    }\n}\n
"},{"location":"tools/automation/automation-config.html#error-handling","title":"Error Handling","text":""},{"location":"tools/automation/automation-config.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/automation/automation-config.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\",\n    \"validation_errors\": [\n        {\n            \"path\": \"trigger[0].platform\",\n            \"message\": \"Invalid trigger platform\"\n        }\n    ]\n}\n
"},{"location":"tools/automation/automation-config.html#best-practices","title":"Best Practices","text":"
  1. Always validate configurations before saving
  2. Use descriptive aliases and descriptions
  3. Group related automations
  4. Test automations in a safe environment
  5. Document automation dependencies
  6. Use variables for reusable values
  7. Implement proper error handling
  8. Consider automation modes carefully
"},{"location":"tools/automation/automation-config.html#see-also","title":"See Also","text":""},{"location":"tools/automation/automation.html","title":"Automation Management Tool","text":"

The Automation Management tool provides functionality to manage and control Home Assistant automations.

"},{"location":"tools/automation/automation.html#features","title":"Features","text":""},{"location":"tools/automation/automation.html#usage","title":"Usage","text":""},{"location":"tools/automation/automation.html#rest-api","title":"REST API","text":"
GET /api/automations\nGET /api/automations/{automation_id}\nPOST /api/automations/{automation_id}/toggle\nPOST /api/automations/{automation_id}/trigger\nGET /api/automations/{automation_id}/history\n
"},{"location":"tools/automation/automation.html#websocket","title":"WebSocket","text":"
// List automations\n{\n    \"type\": \"get_automations\"\n}\n\n// Toggle automation\n{\n    \"type\": \"toggle_automation\",\n    \"automation_id\": \"required_automation_id\"\n}\n\n// Trigger automation\n{\n    \"type\": \"trigger_automation\",\n    \"automation_id\": \"required_automation_id\",\n    \"variables\": {\n        // Optional variables\n    }\n}\n
"},{"location":"tools/automation/automation.html#examples","title":"Examples","text":""},{"location":"tools/automation/automation.html#list-all-automations","title":"List All Automations","text":"
const response = await fetch('http://your-ha-mcp/api/automations', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst automations = await response.json();\n
"},{"location":"tools/automation/automation.html#toggle-automation-state","title":"Toggle Automation State","text":"
const response = await fetch('http://your-ha-mcp/api/automations/morning_routine/toggle', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\n
"},{"location":"tools/automation/automation.html#trigger-automation-manually","title":"Trigger Automation Manually","text":"
const response = await fetch('http://your-ha-mcp/api/automations/morning_routine/trigger', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"variables\": {\n            \"brightness\": 100,\n            \"temperature\": 22\n        }\n    })\n});\n
"},{"location":"tools/automation/automation.html#response-format","title":"Response Format","text":""},{"location":"tools/automation/automation.html#automation-list-response","title":"Automation List Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"automations\": [\n            {\n                \"id\": \"automation_id\",\n                \"name\": \"Automation Name\",\n                \"enabled\": true,\n                \"last_triggered\": \"2024-02-05T12:00:00Z\",\n                \"trigger_count\": 42\n            }\n        ]\n    }\n}\n
"},{"location":"tools/automation/automation.html#automation-details-response","title":"Automation Details Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"automation\": {\n            \"id\": \"automation_id\",\n            \"name\": \"Automation Name\",\n            \"enabled\": true,\n            \"triggers\": [\n                {\n                    \"platform\": \"time\",\n                    \"at\": \"07:00:00\"\n                }\n            ],\n            \"conditions\": [],\n            \"actions\": [\n                {\n                    \"service\": \"light.turn_on\",\n                    \"target\": {\n                        \"entity_id\": \"light.bedroom\"\n                    }\n                }\n            ],\n            \"mode\": \"single\",\n            \"max\": 10,\n            \"last_triggered\": \"2024-02-05T12:00:00Z\",\n            \"trigger_count\": 42\n        }\n    }\n}\n
"},{"location":"tools/automation/automation.html#automation-history-response","title":"Automation History Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"history\": [\n            {\n                \"timestamp\": \"2024-02-05T12:00:00Z\",\n                \"trigger\": {\n                    \"platform\": \"time\",\n                    \"at\": \"07:00:00\"\n                },\n                \"context\": {\n                    \"user_id\": \"user_123\",\n                    \"variables\": {}\n                },\n                \"result\": \"success\"\n            }\n        ]\n    }\n}\n
"},{"location":"tools/automation/automation.html#error-handling","title":"Error Handling","text":""},{"location":"tools/automation/automation.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/automation/automation.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/automation/automation.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/automation/automation.html#best-practices","title":"Best Practices","text":"
  1. Monitor automation execution history
  2. Use descriptive automation names
  3. Implement proper error handling
  4. Cache automation configurations when possible
  5. Handle rate limiting gracefully
  6. Test automations before enabling
  7. Use variables for flexible automation behavior
"},{"location":"tools/automation/automation.html#see-also","title":"See Also","text":""},{"location":"tools/device-management/control.html","title":"Device Control Tool","text":"

The Device Control tool provides functionality to control various types of devices in your Home Assistant instance.

"},{"location":"tools/device-management/control.html#supported-device-types","title":"Supported Device Types","text":""},{"location":"tools/device-management/control.html#usage","title":"Usage","text":""},{"location":"tools/device-management/control.html#rest-api","title":"REST API","text":"
POST /api/devices/{device_id}/control\n
"},{"location":"tools/device-management/control.html#websocket","title":"WebSocket","text":"
{\n    \"type\": \"control_device\",\n    \"device_id\": \"required_device_id\",\n    \"domain\": \"required_domain\",\n    \"service\": \"required_service\",\n    \"data\": {\n        // Service-specific data\n    }\n}\n
"},{"location":"tools/device-management/control.html#domain-specific-commands","title":"Domain-Specific Commands","text":""},{"location":"tools/device-management/control.html#lights","title":"Lights","text":"
// Turn on/off\nPOST /api/devices/light/{device_id}/control\n{\n    \"service\": \"turn_on\",  // or \"turn_off\"\n}\n\n// Set brightness\n{\n    \"service\": \"turn_on\",\n    \"data\": {\n        \"brightness\": 255  // 0-255\n    }\n}\n\n// Set color\n{\n    \"service\": \"turn_on\",\n    \"data\": {\n        \"rgb_color\": [255, 0, 0]  // Red\n    }\n}\n
"},{"location":"tools/device-management/control.html#covers","title":"Covers","text":"
// Open/close\nPOST /api/devices/cover/{device_id}/control\n{\n    \"service\": \"open_cover\",  // or \"close_cover\"\n}\n\n// Set position\n{\n    \"service\": \"set_cover_position\",\n    \"data\": {\n        \"position\": 50  // 0-100\n    }\n}\n
"},{"location":"tools/device-management/control.html#climate","title":"Climate","text":"
// Set temperature\nPOST /api/devices/climate/{device_id}/control\n{\n    \"service\": \"set_temperature\",\n    \"data\": {\n        \"temperature\": 22.5\n    }\n}\n\n// Set mode\n{\n    \"service\": \"set_hvac_mode\",\n    \"data\": {\n        \"hvac_mode\": \"heat\"  // heat, cool, auto, off\n    }\n}\n
"},{"location":"tools/device-management/control.html#examples","title":"Examples","text":""},{"location":"tools/device-management/control.html#control-light-brightness","title":"Control Light Brightness","text":"
const response = await fetch('http://your-ha-mcp/api/devices/light/living_room/control', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"service\": \"turn_on\",\n        \"data\": {\n            \"brightness\": 128\n        }\n    })\n});\n
"},{"location":"tools/device-management/control.html#control-cover-position","title":"Control Cover Position","text":"
const response = await fetch('http://your-ha-mcp/api/devices/cover/bedroom/control', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"service\": \"set_cover_position\",\n        \"data\": {\n            \"position\": 75\n        }\n    })\n});\n
"},{"location":"tools/device-management/control.html#response-format","title":"Response Format","text":""},{"location":"tools/device-management/control.html#success-response","title":"Success Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"state\": \"on\",\n        \"attributes\": {\n            // Updated device attributes\n        }\n    }\n}\n
"},{"location":"tools/device-management/control.html#error-response","title":"Error Response","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/device-management/control.html#error-handling","title":"Error Handling","text":""},{"location":"tools/device-management/control.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/device-management/control.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/device-management/control.html#best-practices","title":"Best Practices","text":"
  1. Validate device availability before sending commands
  2. Implement proper error handling
  3. Use appropriate retry strategies for failed commands
  4. Cache device capabilities when possible
  5. Handle rate limiting gracefully
"},{"location":"tools/device-management/control.html#see-also","title":"See Also","text":""},{"location":"tools/device-management/list-devices.html","title":"List Devices Tool","text":"

The List Devices tool provides functionality to retrieve and manage device information from your Home Assistant instance.

"},{"location":"tools/device-management/list-devices.html#features","title":"Features","text":""},{"location":"tools/device-management/list-devices.html#usage","title":"Usage","text":""},{"location":"tools/device-management/list-devices.html#rest-api","title":"REST API","text":"
GET /api/devices\nGET /api/devices/{domain}\nGET /api/devices/{device_id}/state\n
"},{"location":"tools/device-management/list-devices.html#websocket","title":"WebSocket","text":"
// List all devices\n{\n    \"type\": \"list_devices\",\n    \"domain\": \"optional_domain\"\n}\n\n// Get device state\n{\n    \"type\": \"get_device_state\",\n    \"device_id\": \"required_device_id\"\n}\n
"},{"location":"tools/device-management/list-devices.html#examples","title":"Examples","text":""},{"location":"tools/device-management/list-devices.html#list-all-devices","title":"List All Devices","text":"
const response = await fetch('http://your-ha-mcp/api/devices', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst devices = await response.json();\n
"},{"location":"tools/device-management/list-devices.html#get-devices-by-domain","title":"Get Devices by Domain","text":"
const response = await fetch('http://your-ha-mcp/api/devices/light', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst lightDevices = await response.json();\n
"},{"location":"tools/device-management/list-devices.html#response-format","title":"Response Format","text":""},{"location":"tools/device-management/list-devices.html#device-list-response","title":"Device List Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"devices\": [\n            {\n                \"id\": \"device_id\",\n                \"name\": \"Device Name\",\n                \"domain\": \"light\",\n                \"state\": \"on\",\n                \"attributes\": {\n                    \"brightness\": 255,\n                    \"color_temp\": 370\n                }\n            }\n        ]\n    }\n}\n
"},{"location":"tools/device-management/list-devices.html#device-state-response","title":"Device State Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"state\": \"on\",\n        \"attributes\": {\n            \"brightness\": 255,\n            \"color_temp\": 370\n        },\n        \"last_changed\": \"2024-02-05T12:00:00Z\",\n        \"last_updated\": \"2024-02-05T12:00:00Z\"\n    }\n}\n
"},{"location":"tools/device-management/list-devices.html#error-handling","title":"Error Handling","text":""},{"location":"tools/device-management/list-devices.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/device-management/list-devices.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/device-management/list-devices.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/device-management/list-devices.html#best-practices","title":"Best Practices","text":"
  1. Cache device lists when possible
  2. Use domain filtering for better performance
  3. Implement proper error handling
  4. Handle rate limiting gracefully
"},{"location":"tools/device-management/list-devices.html#see-also","title":"See Also","text":""},{"location":"tools/events/sse-stats.html","title":"SSE Statistics Tool","text":"

The SSE Statistics tool provides functionality to monitor and analyze Server-Sent Events (SSE) connections and performance in your Home Assistant MCP instance.

"},{"location":"tools/events/sse-stats.html#features","title":"Features","text":""},{"location":"tools/events/sse-stats.html#usage","title":"Usage","text":""},{"location":"tools/events/sse-stats.html#rest-api","title":"REST API","text":"
GET /api/sse/stats\nGET /api/sse/connections\nGET /api/sse/connections/{connection_id}\nGET /api/sse/metrics\nGET /api/sse/history\n
"},{"location":"tools/events/sse-stats.html#websocket","title":"WebSocket","text":"
// Get SSE stats\n{\n    \"type\": \"get_sse_stats\"\n}\n\n// Get connection details\n{\n    \"type\": \"get_sse_connection\",\n    \"connection_id\": \"required_connection_id\"\n}\n\n// Get performance metrics\n{\n    \"type\": \"get_sse_metrics\",\n    \"period\": \"1h|24h|7d|30d\"\n}\n
"},{"location":"tools/events/sse-stats.html#examples","title":"Examples","text":""},{"location":"tools/events/sse-stats.html#get-current-statistics","title":"Get Current Statistics","text":"
const response = await fetch('http://your-ha-mcp/api/sse/stats', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst stats = await response.json();\n
"},{"location":"tools/events/sse-stats.html#get-connection-details","title":"Get Connection Details","text":"
const response = await fetch('http://your-ha-mcp/api/sse/connections/conn_123', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst connection = await response.json();\n
"},{"location":"tools/events/sse-stats.html#get-performance-metrics","title":"Get Performance Metrics","text":"
const response = await fetch('http://your-ha-mcp/api/sse/metrics?period=24h', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst metrics = await response.json();\n
"},{"location":"tools/events/sse-stats.html#response-format","title":"Response Format","text":""},{"location":"tools/events/sse-stats.html#statistics-response","title":"Statistics Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"active_connections\": 42,\n        \"total_events_sent\": 12345,\n        \"events_per_second\": 5.2,\n        \"memory_usage\": 128974848,\n        \"cpu_usage\": 2.5,\n        \"uptime\": \"PT24H\",\n        \"event_backlog\": 0\n    }\n}\n
"},{"location":"tools/events/sse-stats.html#connection-details-response","title":"Connection Details Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"connection\": {\n            \"id\": \"conn_123\",\n            \"client_id\": \"client_456\",\n            \"user_id\": \"user_789\",\n            \"connected_at\": \"2024-02-05T12:00:00Z\",\n            \"last_event_at\": \"2024-02-05T12:05:00Z\",\n            \"events_sent\": 150,\n            \"subscriptions\": [\n                {\n                    \"event_type\": \"state_changed\",\n                    \"entity_id\": \"light.living_room\"\n                }\n            ],\n            \"state\": \"active\",\n            \"ip_address\": \"192.168.1.100\",\n            \"user_agent\": \"Mozilla/5.0 ...\"\n        }\n    }\n}\n
"},{"location":"tools/events/sse-stats.html#performance-metrics-response","title":"Performance Metrics Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"metrics\": {\n            \"connections\": {\n                \"current\": 42,\n                \"max\": 100,\n                \"average\": 35.5\n            },\n            \"events\": {\n                \"total\": 12345,\n                \"rate\": {\n                    \"current\": 5.2,\n                    \"max\": 15.0,\n                    \"average\": 4.8\n                }\n            },\n            \"latency\": {\n                \"p50\": 15,\n                \"p95\": 45,\n                \"p99\": 100\n            },\n            \"resources\": {\n                \"memory\": {\n                    \"current\": 128974848,\n                    \"max\": 536870912\n                },\n                \"cpu\": {\n                    \"current\": 2.5,\n                    \"max\": 10.0,\n                    \"average\": 3.2\n                }\n            }\n        },\n        \"period\": \"24h\",\n        \"timestamp\": \"2024-02-05T12:00:00Z\"\n    }\n}\n
"},{"location":"tools/events/sse-stats.html#error-handling","title":"Error Handling","text":""},{"location":"tools/events/sse-stats.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/events/sse-stats.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/events/sse-stats.html#monitoring-metrics","title":"Monitoring Metrics","text":""},{"location":"tools/events/sse-stats.html#connection-metrics","title":"Connection Metrics","text":""},{"location":"tools/events/sse-stats.html#event-metrics","title":"Event Metrics","text":""},{"location":"tools/events/sse-stats.html#resource-metrics","title":"Resource Metrics","text":""},{"location":"tools/events/sse-stats.html#alert-thresholds","title":"Alert Thresholds","text":""},{"location":"tools/events/sse-stats.html#best-practices","title":"Best Practices","text":"
  1. Monitor connection health
  2. Track resource usage
  3. Set up alerts
  4. Analyze usage patterns
  5. Optimize performance
  6. Plan capacity
  7. Implement failover
  8. Regular maintenance
"},{"location":"tools/events/sse-stats.html#performance-optimization","title":"Performance Optimization","text":""},{"location":"tools/events/sse-stats.html#see-also","title":"See Also","text":""},{"location":"tools/events/subscribe-events.html","title":"Event Subscription Tool","text":"

The Event Subscription tool provides functionality to subscribe to and monitor real-time events from your Home Assistant instance.

"},{"location":"tools/events/subscribe-events.html#features","title":"Features","text":""},{"location":"tools/events/subscribe-events.html#usage","title":"Usage","text":""},{"location":"tools/events/subscribe-events.html#rest-api","title":"REST API","text":"
POST /api/events/subscribe\nDELETE /api/events/unsubscribe\nGET /api/events/subscriptions\nGET /api/events/history\n
"},{"location":"tools/events/subscribe-events.html#websocket","title":"WebSocket","text":"
// Subscribe to events\n{\n    \"type\": \"subscribe_events\",\n    \"event_type\": \"optional_event_type\",\n    \"entity_id\": \"optional_entity_id\",\n    \"domain\": \"optional_domain\"\n}\n\n// Unsubscribe from events\n{\n    \"type\": \"unsubscribe_events\",\n    \"subscription_id\": \"required_subscription_id\"\n}\n
"},{"location":"tools/events/subscribe-events.html#server-sent-events-sse","title":"Server-Sent Events (SSE)","text":"
GET /api/events/stream?event_type=state_changed&entity_id=light.living_room\n
"},{"location":"tools/events/subscribe-events.html#event-types","title":"Event Types","text":""},{"location":"tools/events/subscribe-events.html#examples","title":"Examples","text":""},{"location":"tools/events/subscribe-events.html#subscribe-to-all-state-changes","title":"Subscribe to All State Changes","text":"
const response = await fetch('http://your-ha-mcp/api/events/subscribe', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"event_type\": \"state_changed\"\n    })\n});\n
"},{"location":"tools/events/subscribe-events.html#monitor-specific-entity","title":"Monitor Specific Entity","text":"
const response = await fetch('http://your-ha-mcp/api/events/subscribe', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"event_type\": \"state_changed\",\n        \"entity_id\": \"light.living_room\"\n    })\n});\n
"},{"location":"tools/events/subscribe-events.html#domain-based-monitoring","title":"Domain-Based Monitoring","text":"
const response = await fetch('http://your-ha-mcp/api/events/subscribe', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"event_type\": \"state_changed\",\n        \"domain\": \"light\"\n    })\n});\n
"},{"location":"tools/events/subscribe-events.html#sse-connection-example","title":"SSE Connection Example","text":"
const eventSource = new EventSource(\n    'http://your-ha-mcp/api/events/stream?event_type=state_changed&entity_id=light.living_room',\n    {\n        headers: {\n            'Authorization': 'Bearer your_access_token'\n        }\n    }\n);\n\neventSource.onmessage = (event) => {\n    const data = JSON.parse(event.data);\n    console.log('Event received:', data);\n};\n\neventSource.onerror = (error) => {\n    console.error('SSE error:', error);\n    eventSource.close();\n};\n
"},{"location":"tools/events/subscribe-events.html#response-format","title":"Response Format","text":""},{"location":"tools/events/subscribe-events.html#subscription-response","title":"Subscription Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"subscription_id\": \"sub_123\",\n        \"event_type\": \"state_changed\",\n        \"entity_id\": \"light.living_room\",\n        \"created_at\": \"2024-02-05T12:00:00Z\"\n    }\n}\n
"},{"location":"tools/events/subscribe-events.html#event-message-format","title":"Event Message Format","text":"
{\n    \"event_type\": \"state_changed\",\n    \"entity_id\": \"light.living_room\",\n    \"data\": {\n        \"old_state\": {\n            \"state\": \"off\",\n            \"attributes\": {},\n            \"last_changed\": \"2024-02-05T11:55:00Z\"\n        },\n        \"new_state\": {\n            \"state\": \"on\",\n            \"attributes\": {\n                \"brightness\": 255\n            },\n            \"last_changed\": \"2024-02-05T12:00:00Z\"\n        }\n    },\n    \"origin\": \"LOCAL\",\n    \"time_fired\": \"2024-02-05T12:00:00Z\",\n    \"context\": {\n        \"id\": \"context_123\",\n        \"parent_id\": null,\n        \"user_id\": \"user_123\"\n    }\n}\n
"},{"location":"tools/events/subscribe-events.html#subscriptions-list-response","title":"Subscriptions List Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"subscriptions\": [\n            {\n                \"id\": \"sub_123\",\n                \"event_type\": \"state_changed\",\n                \"entity_id\": \"light.living_room\",\n                \"created_at\": \"2024-02-05T12:00:00Z\",\n                \"last_event\": \"2024-02-05T12:05:00Z\"\n            }\n        ]\n    }\n}\n
"},{"location":"tools/events/subscribe-events.html#error-handling","title":"Error Handling","text":""},{"location":"tools/events/subscribe-events.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/events/subscribe-events.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/events/subscribe-events.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/events/subscribe-events.html#best-practices","title":"Best Practices","text":"
  1. Use specific event types when possible
  2. Implement proper error handling
  3. Handle connection interruptions
  4. Process events asynchronously
  5. Implement backoff strategies
  6. Monitor subscription health
  7. Clean up unused subscriptions
  8. Handle rate limiting gracefully
"},{"location":"tools/events/subscribe-events.html#connection-management","title":"Connection Management","text":""},{"location":"tools/events/subscribe-events.html#see-also","title":"See Also","text":""},{"location":"tools/history-state/history.html","title":"Device History Tool","text":"

The Device History tool allows you to retrieve historical state information for devices in your Home Assistant instance.

"},{"location":"tools/history-state/history.html#features","title":"Features","text":""},{"location":"tools/history-state/history.html#usage","title":"Usage","text":""},{"location":"tools/history-state/history.html#rest-api","title":"REST API","text":"
GET /api/history/{device_id}\nGET /api/history/{device_id}/period/{start_time}\nGET /api/history/{device_id}/period/{start_time}/{end_time}\n
"},{"location":"tools/history-state/history.html#websocket","title":"WebSocket","text":"
{\n    \"type\": \"get_history\",\n    \"device_id\": \"required_device_id\",\n    \"start_time\": \"optional_iso_timestamp\",\n    \"end_time\": \"optional_iso_timestamp\",\n    \"significant_changes_only\": false\n}\n
"},{"location":"tools/history-state/history.html#query-parameters","title":"Query Parameters","text":"Parameter Type Description start_time ISO timestamp Start of the period to fetch history for end_time ISO timestamp End of the period to fetch history for significant_changes_only boolean Only return significant state changes minimal_response boolean Return minimal state information no_attributes boolean Exclude attribute data from response"},{"location":"tools/history-state/history.html#examples","title":"Examples","text":""},{"location":"tools/history-state/history.html#get-recent-history","title":"Get Recent History","text":"
const response = await fetch('http://your-ha-mcp/api/history/light.living_room', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst history = await response.json();\n
"},{"location":"tools/history-state/history.html#get-history-for-specific-period","title":"Get History for Specific Period","text":"
const startTime = '2024-02-01T00:00:00Z';\nconst endTime = '2024-02-02T00:00:00Z';\nconst response = await fetch(\n    `http://your-ha-mcp/api/history/light.living_room/period/${startTime}/${endTime}`, \n    {\n        headers: {\n            'Authorization': 'Bearer your_access_token'\n        }\n    }\n);\nconst history = await response.json();\n
"},{"location":"tools/history-state/history.html#response-format","title":"Response Format","text":""},{"location":"tools/history-state/history.html#history-response","title":"History Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"history\": [\n            {\n                \"state\": \"on\",\n                \"attributes\": {\n                    \"brightness\": 255\n                },\n                \"last_changed\": \"2024-02-05T12:00:00Z\",\n                \"last_updated\": \"2024-02-05T12:00:00Z\"\n            },\n            {\n                \"state\": \"off\",\n                \"last_changed\": \"2024-02-05T13:00:00Z\",\n                \"last_updated\": \"2024-02-05T13:00:00Z\"\n            }\n        ]\n    }\n}\n
"},{"location":"tools/history-state/history.html#aggregated-history-response","title":"Aggregated History Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"aggregates\": {\n            \"daily\": [\n                {\n                    \"date\": \"2024-02-05\",\n                    \"on_time\": \"PT5H30M\",\n                    \"off_time\": \"PT18H30M\",\n                    \"changes\": 10\n                }\n            ]\n        }\n    }\n}\n
"},{"location":"tools/history-state/history.html#error-handling","title":"Error Handling","text":""},{"location":"tools/history-state/history.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/history-state/history.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/history-state/history.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/history-state/history.html#data-retention","title":"Data Retention","text":""},{"location":"tools/history-state/history.html#best-practices","title":"Best Practices","text":"
  1. Use appropriate time ranges to avoid large responses
  2. Enable significant_changes_only for better performance
  3. Use minimal_response when full state data isn't needed
  4. Implement proper error handling
  5. Cache frequently accessed historical data
  6. Handle rate limiting gracefully
"},{"location":"tools/history-state/history.html#see-also","title":"See Also","text":""},{"location":"tools/history-state/scene.html","title":"Scene Management Tool","text":"

The Scene Management tool provides functionality to manage and control scenes in your Home Assistant instance.

"},{"location":"tools/history-state/scene.html#features","title":"Features","text":""},{"location":"tools/history-state/scene.html#usage","title":"Usage","text":""},{"location":"tools/history-state/scene.html#rest-api","title":"REST API","text":"
GET /api/scenes\nGET /api/scenes/{scene_id}\nPOST /api/scenes/{scene_id}/activate\nPOST /api/scenes\nPUT /api/scenes/{scene_id}\nDELETE /api/scenes/{scene_id}\n
"},{"location":"tools/history-state/scene.html#websocket","title":"WebSocket","text":"
// List scenes\n{\n    \"type\": \"get_scenes\"\n}\n\n// Activate scene\n{\n    \"type\": \"activate_scene\",\n    \"scene_id\": \"required_scene_id\"\n}\n\n// Create/Update scene\n{\n    \"type\": \"create_scene\",\n    \"scene\": {\n        \"name\": \"required_scene_name\",\n        \"entities\": {\n            // Entity states\n        }\n    }\n}\n
"},{"location":"tools/history-state/scene.html#scene-configuration","title":"Scene Configuration","text":""},{"location":"tools/history-state/scene.html#scene-definition","title":"Scene Definition","text":"
{\n    \"name\": \"Movie Night\",\n    \"entities\": {\n        \"light.living_room\": {\n            \"state\": \"on\",\n            \"brightness\": 50,\n            \"color_temp\": 2700\n        },\n        \"cover.living_room\": {\n            \"state\": \"closed\"\n        },\n        \"media_player.tv\": {\n            \"state\": \"on\",\n            \"source\": \"HDMI 1\"\n        }\n    }\n}\n
"},{"location":"tools/history-state/scene.html#examples","title":"Examples","text":""},{"location":"tools/history-state/scene.html#list-all-scenes","title":"List All Scenes","text":"
const response = await fetch('http://your-ha-mcp/api/scenes', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst scenes = await response.json();\n
"},{"location":"tools/history-state/scene.html#activate-a-scene","title":"Activate a Scene","text":"
const response = await fetch('http://your-ha-mcp/api/scenes/movie_night/activate', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\n
"},{"location":"tools/history-state/scene.html#create-a-new-scene","title":"Create a New Scene","text":"
const response = await fetch('http://your-ha-mcp/api/scenes', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"name\": \"Movie Night\",\n        \"entities\": {\n            \"light.living_room\": {\n                \"state\": \"on\",\n                \"brightness\": 50\n            },\n            \"cover.living_room\": {\n                \"state\": \"closed\"\n            }\n        }\n    })\n});\n
"},{"location":"tools/history-state/scene.html#response-format","title":"Response Format","text":""},{"location":"tools/history-state/scene.html#scene-list-response","title":"Scene List Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"scenes\": [\n            {\n                \"id\": \"scene_id\",\n                \"name\": \"Scene Name\",\n                \"entities\": {\n                    // Entity configurations\n                }\n            }\n        ]\n    }\n}\n
"},{"location":"tools/history-state/scene.html#scene-activation-response","title":"Scene Activation Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"scene_id\": \"activated_scene_id\",\n        \"status\": \"activated\",\n        \"timestamp\": \"2024-02-05T12:00:00Z\"\n    }\n}\n
"},{"location":"tools/history-state/scene.html#error-handling","title":"Error Handling","text":""},{"location":"tools/history-state/scene.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/history-state/scene.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/history-state/scene.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/history-state/scene.html#best-practices","title":"Best Practices","text":"
  1. Validate entity availability before creating scenes
  2. Use meaningful scene names
  3. Group related entities in scenes
  4. Implement proper error handling
  5. Cache scene configurations when possible
  6. Handle rate limiting gracefully
"},{"location":"tools/history-state/scene.html#scene-transitions","title":"Scene Transitions","text":"

Scenes can include transition settings for smooth state changes:

{\n    \"name\": \"Sunset Mode\",\n    \"entities\": {\n        \"light.living_room\": {\n            \"state\": \"on\",\n            \"brightness\": 128,\n            \"transition\": 5  // 5 seconds\n        }\n    }\n}\n
"},{"location":"tools/history-state/scene.html#see-also","title":"See Also","text":""},{"location":"tools/notifications/notify.html","title":"Notification Tool","text":"

The Notification tool provides functionality to send notifications through various services in your Home Assistant instance.

"},{"location":"tools/notifications/notify.html#features","title":"Features","text":""},{"location":"tools/notifications/notify.html#usage","title":"Usage","text":""},{"location":"tools/notifications/notify.html#rest-api","title":"REST API","text":"
POST /api/notify\nPOST /api/notify/{service_id}\nGET /api/notify/services\nGET /api/notify/history\n
"},{"location":"tools/notifications/notify.html#websocket","title":"WebSocket","text":"
// Send notification\n{\n    \"type\": \"send_notification\",\n    \"service\": \"required_service_id\",\n    \"message\": \"required_message\",\n    \"title\": \"optional_title\",\n    \"data\": {\n        // Service-specific data\n    }\n}\n\n// Get notification services\n{\n    \"type\": \"get_notification_services\"\n}\n
"},{"location":"tools/notifications/notify.html#supported-services","title":"Supported Services","text":""},{"location":"tools/notifications/notify.html#examples","title":"Examples","text":""},{"location":"tools/notifications/notify.html#basic-notification","title":"Basic Notification","text":"
const response = await fetch('http://your-ha-mcp/api/notify/mobile_app', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"message\": \"Motion detected in living room\",\n        \"title\": \"Security Alert\"\n    })\n});\n
"},{"location":"tools/notifications/notify.html#rich-notification","title":"Rich Notification","text":"
const response = await fetch('http://your-ha-mcp/api/notify/mobile_app', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"message\": \"Motion detected in living room\",\n        \"title\": \"Security Alert\",\n        \"data\": {\n            \"image\": \"https://your-camera-snapshot.jpg\",\n            \"actions\": [\n                {\n                    \"action\": \"view_camera\",\n                    \"title\": \"View Camera\"\n                },\n                {\n                    \"action\": \"dismiss\",\n                    \"title\": \"Dismiss\"\n                }\n            ],\n            \"priority\": \"high\",\n            \"ttl\": 3600,\n            \"group\": \"security\"\n        }\n    })\n});\n
"},{"location":"tools/notifications/notify.html#service-specific-example-telegram","title":"Service-Specific Example (Telegram)","text":"
const response = await fetch('http://your-ha-mcp/api/notify/telegram', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"message\": \"Temperature is too high!\",\n        \"title\": \"Climate Alert\",\n        \"data\": {\n            \"parse_mode\": \"markdown\",\n            \"inline_keyboard\": [\n                [\n                    {\n                        \"text\": \"Turn On AC\",\n                        \"callback_data\": \"turn_on_ac\"\n                    }\n                ]\n            ]\n        }\n    })\n});\n
"},{"location":"tools/notifications/notify.html#response-format","title":"Response Format","text":""},{"location":"tools/notifications/notify.html#success-response","title":"Success Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"notification_id\": \"notification_123\",\n        \"status\": \"sent\",\n        \"timestamp\": \"2024-02-05T12:00:00Z\",\n        \"service\": \"mobile_app\"\n    }\n}\n
"},{"location":"tools/notifications/notify.html#services-list-response","title":"Services List Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"services\": [\n            {\n                \"id\": \"mobile_app\",\n                \"name\": \"Mobile App\",\n                \"enabled\": true,\n                \"features\": [\n                    \"actions\",\n                    \"images\",\n                    \"sound\"\n                ]\n            }\n        ]\n    }\n}\n
"},{"location":"tools/notifications/notify.html#notification-history-response","title":"Notification History Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"history\": [\n            {\n                \"id\": \"notification_123\",\n                \"service\": \"mobile_app\",\n                \"message\": \"Motion detected\",\n                \"title\": \"Security Alert\",\n                \"timestamp\": \"2024-02-05T12:00:00Z\",\n                \"status\": \"delivered\"\n            }\n        ]\n    }\n}\n
"},{"location":"tools/notifications/notify.html#error-handling","title":"Error Handling","text":""},{"location":"tools/notifications/notify.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/notifications/notify.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/notifications/notify.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/notifications/notify.html#best-practices","title":"Best Practices","text":"
  1. Use appropriate priority levels
  2. Group related notifications
  3. Include relevant context
  4. Implement proper error handling
  5. Use templates for consistency
  6. Consider time zones
  7. Respect user preferences
  8. Handle rate limiting gracefully
"},{"location":"tools/notifications/notify.html#notification-templates","title":"Notification Templates","text":"
// Template example\n{\n    \"template\": \"security_alert\",\n    \"data\": {\n        \"location\": \"living_room\",\n        \"event_type\": \"motion\",\n        \"timestamp\": \"2024-02-05T12:00:00Z\"\n    }\n}\n
"},{"location":"tools/notifications/notify.html#see-also","title":"See Also","text":""}]} \ No newline at end of file +var __index = {"config":{"lang":["en"],"separator":"[\\s\\-,:!=\\[\\]()\"/]+|(?!\\b)(?=[A-Z][a-z])|\\.(?!\\d)|&[lg]t;","pipeline":["stopWordFilter"]},"docs":[{"location":"index.html","title":"Advanced Home Assistant MCP","text":"

Welcome to the Advanced Home Assistant Master Control Program documentation.

This documentation provides comprehensive information about setting up, configuring, and using the Advanced Home Assistant MCP system.

"},{"location":"index.html#quick-links","title":"Quick Links","text":""},{"location":"index.html#what-is-mcp-server","title":"What is MCP Server?","text":"

MCP Server is a bridge between Home Assistant and custom automation tools, enabling basic device control and real-time monitoring of your smart home environment. It provides a flexible interface for managing and interacting with your home automation setup.

"},{"location":"index.html#key-features","title":"Key Features","text":""},{"location":"index.html#device-control","title":"\ud83c\udfae Device Control","text":""},{"location":"index.html#security-performance","title":"\ud83d\udee1\ufe0f Security & Performance","text":""},{"location":"index.html#documentation-structure","title":"Documentation Structure","text":""},{"location":"index.html#getting-started","title":"Getting Started","text":""},{"location":"index.html#core-documentation","title":"Core Documentation","text":""},{"location":"index.html#support","title":"Support","text":"

Need help or want to report issues?

"},{"location":"index.html#license","title":"License","text":"

This project is licensed under the MIT License. See the LICENSE file for details.

"},{"location":"api.html","title":"Home Assistant MCP Server API Documentation","text":""},{"location":"api.html#overview","title":"Overview","text":"

This document provides a reference for the MCP Server API, which offers basic device control and state management for Home Assistant.

"},{"location":"api.html#authentication","title":"Authentication","text":"

All API requests require a valid JWT token in the Authorization header:

Authorization: Bearer YOUR_TOKEN\n
"},{"location":"api.html#core-endpoints","title":"Core Endpoints","text":""},{"location":"api.html#device-state-management","title":"Device State Management","text":""},{"location":"api.html#get-device-state","title":"Get Device State","text":"
GET /api/state/{entity_id}\n

Response:

{\n  \"entity_id\": \"light.living_room\",\n  \"state\": \"on\",\n  \"attributes\": {\n    \"brightness\": 128\n  }\n}\n

"},{"location":"api.html#update-device-state","title":"Update Device State","text":"
POST /api/state\nContent-Type: application/json\n\n{\n  \"entity_id\": \"light.living_room\",\n  \"state\": \"on\",\n  \"attributes\": {\n    \"brightness\": 128\n  }\n}\n
"},{"location":"api.html#device-control","title":"Device Control","text":""},{"location":"api.html#execute-device-command","title":"Execute Device Command","text":"
POST /api/control\nContent-Type: application/json\n\n{\n  \"entity_id\": \"light.living_room\",\n  \"command\": \"turn_on\",\n  \"parameters\": {\n    \"brightness\": 50\n  }\n}\n
"},{"location":"api.html#real-time-updates","title":"Real-Time Updates","text":""},{"location":"api.html#websocket-connection","title":"WebSocket Connection","text":"

Connect to real-time updates:

const ws = new WebSocket('ws://localhost:3000/events');\nws.onmessage = (event) => {\n  const deviceUpdate = JSON.parse(event.data);\n  console.log('Device state changed:', deviceUpdate);\n};\n
"},{"location":"api.html#error-handling","title":"Error Handling","text":""},{"location":"api.html#common-error-responses","title":"Common Error Responses","text":"
{\n  \"error\": {\n    \"code\": \"INVALID_REQUEST\",\n    \"message\": \"Invalid request parameters\",\n    \"details\": \"Entity ID not found or invalid command\"\n  }\n}\n
"},{"location":"api.html#rate-limiting","title":"Rate Limiting","text":"

Basic rate limiting is implemented: - Maximum of 100 requests per minute - Excess requests will receive a 429 Too Many Requests response

"},{"location":"api.html#supported-operations","title":"Supported Operations","text":""},{"location":"api.html#supported-commands","title":"Supported Commands","text":""},{"location":"api.html#supported-entities","title":"Supported Entities","text":""},{"location":"api.html#limitations","title":"Limitations","text":""},{"location":"api.html#best-practices","title":"Best Practices","text":"
  1. Always include a valid JWT token
  2. Handle potential errors in your client code
  3. Use WebSocket for real-time updates when possible
  4. Validate entity IDs before sending commands
"},{"location":"api.html#example-client-usage","title":"Example Client Usage","text":"
async function controlDevice(entityId: string, command: string, params?: Record<string, unknown>) {\n  try {\n    const response = await fetch('/api/control', {\n    method: 'POST',\n    headers: {\n        'Content-Type': 'application/json',\n        'Authorization': `Bearer ${token}`\n    },\n    body: JSON.stringify({\n        entity_id: entityId,\n        command,\n        parameters: params\n    })\n  });\n\n    if (!response.ok) {\n      const error = await response.json();\n      throw new Error(error.message);\n    }\n\n    return await response.json();\n} catch (error) {\n    console.error('Device control failed:', error);\n    throw error;\n  }\n}\n\n// Usage example\ncontrolDevice('light.living_room', 'turn_on', { brightness: 50 })\n  .then(result => console.log('Device controlled successfully'))\n  .catch(error => console.error('Control failed', error));\n
"},{"location":"api.html#future-development","title":"Future Development","text":"

Planned improvements: - Enhanced error handling - More comprehensive device support - Improved authentication mechanisms

API is subject to change. Always refer to the latest documentation.

"},{"location":"architecture.html","title":"Architecture Overview \ud83c\udfd7\ufe0f","text":"

This document describes the architecture of the MCP Server, explaining how different components work together to provide a bridge between Home Assistant and custom automation tools.

"},{"location":"architecture.html#system-architecture","title":"System Architecture","text":"
graph TD\n    subgraph \"Client Layer\"\n        WC[Web Clients]\n        MC[Mobile Clients]\n    end\n\n    subgraph \"MCP Server\"\n        API[API Gateway]\n        SSE[SSE Manager]\n        WS[WebSocket Server]\n        CM[Command Manager]\n    end\n\n    subgraph \"Home Assistant\"\n        HA[Home Assistant Core]\n        Dev[Devices & Services]\n    end\n\n    WC --> |HTTP/WS| API\n    MC --> |HTTP/WS| API\n\n    API --> |Events| SSE\n    API --> |Real-time| WS\n\n    API --> HA\n    HA --> API
"},{"location":"architecture.html#core-components","title":"Core Components","text":""},{"location":"architecture.html#api-gateway","title":"API Gateway","text":""},{"location":"architecture.html#sse-manager","title":"SSE Manager","text":""},{"location":"architecture.html#websocket-server","title":"WebSocket Server","text":""},{"location":"architecture.html#command-manager","title":"Command Manager","text":""},{"location":"architecture.html#communication-flow","title":"Communication Flow","text":"
  1. Client sends a request to the MCP Server API
  2. API Gateway authenticates the request
  3. Command Manager processes the request
  4. Request is forwarded to Home Assistant
  5. Response is sent back to the client via API or WebSocket
"},{"location":"architecture.html#key-design-principles","title":"Key Design Principles","text":""},{"location":"architecture.html#limitations","title":"Limitations","text":""},{"location":"architecture.html#future-improvements","title":"Future Improvements","text":"

Architecture is subject to change as the project evolves.

"},{"location":"configuration.html","title":"System Configuration","text":"

This document provides detailed information about configuring the Home Assistant MCP Server.

"},{"location":"configuration.html#configuration-file-structure","title":"Configuration File Structure","text":"

The MCP Server uses environment variables for configuration, with support for different environments (development, test, production):

# .env, .env.development, or .env.test\nPORT=4000\nNODE_ENV=development\nHASS_HOST=http://192.168.178.63:8123\nHASS_TOKEN=your_token_here\nJWT_SECRET=your_secret_key\n
"},{"location":"configuration.html#server-settings","title":"Server Settings","text":""},{"location":"configuration.html#basic-server-configuration","title":"Basic Server Configuration","text":""},{"location":"configuration.html#security-settings","title":"Security Settings","text":""},{"location":"configuration.html#websocket-settings","title":"WebSocket Settings","text":""},{"location":"configuration.html#speech-features-optional","title":"Speech Features (Optional)","text":""},{"location":"configuration.html#environment-variables","title":"Environment Variables","text":"

All configuration is managed through environment variables:

# Server\nPORT=4000\nNODE_ENV=development\n\n# Home Assistant\nHASS_HOST=http://your-hass-instance:8123\nHASS_TOKEN=your_token_here\n\n# Security\nJWT_SECRET=your-secret-key\n\n# Logging\nLOG_LEVEL=info\nLOG_DIR=logs\nLOG_MAX_SIZE=20m\nLOG_MAX_DAYS=14d\nLOG_COMPRESS=true\nLOG_REQUESTS=true\n\n# Speech Features (Optional)\nENABLE_SPEECH_FEATURES=false\nENABLE_WAKE_WORD=false\nENABLE_SPEECH_TO_TEXT=false\nWHISPER_MODEL_PATH=/models\nWHISPER_MODEL_TYPE=base\n
"},{"location":"configuration.html#advanced-configuration","title":"Advanced Configuration","text":""},{"location":"configuration.html#security-rate-limiting","title":"Security Rate Limiting","text":"

Rate limiting is enabled by default to protect against brute force attacks:

RATE_LIMIT: {\n  windowMs: 15 * 60 * 1000,  // 15 minutes\n  max: 100  // limit each IP to 100 requests per window\n}\n
"},{"location":"configuration.html#logging","title":"Logging","text":"

The server uses Bun's built-in logging capabilities with additional configuration:

LOGGING: {\n  LEVEL: \"info\",  // debug, info, warn, error\n  DIR: \"logs\",\n  MAX_SIZE: \"20m\",\n  MAX_DAYS: \"14d\",\n  COMPRESS: true,\n  TIMESTAMP_FORMAT: \"YYYY-MM-DD HH:mm:ss:ms\",\n  LOG_REQUESTS: true\n}\n
"},{"location":"configuration.html#speech-to-text-configuration","title":"Speech-to-Text Configuration","text":"

When speech features are enabled, you can configure the following options:

SPEECH: {\n  ENABLED: false,  // Master switch for all speech features\n  WAKE_WORD_ENABLED: false,  // Enable wake word detection\n  SPEECH_TO_TEXT_ENABLED: false,  // Enable speech-to-text\n  WHISPER_MODEL_PATH: \"/models\",  // Path to Whisper models\n  WHISPER_MODEL_TYPE: \"base\",  // Model type to use\n}\n

Available Whisper models: - tiny.en: Fastest, lowest accuracy - base.en: Good balance of speed and accuracy - small.en: Better accuracy, slower - medium.en: High accuracy, much slower - large-v2: Best accuracy, very slow

For production deployments, we recommend using system tools like logrotate for log management.

Example logrotate configuration (/etc/logrotate.d/mcp-server):

/var/log/mcp-server.log {\n    daily\n    rotate 7\n    compress\n    delaycompress\n    missingok\n    notifempty\n    create 644 mcp mcp\n}\n

"},{"location":"configuration.html#best-practices","title":"Best Practices","text":"
  1. Always use environment variables for sensitive information
  2. Keep .env files secure and never commit them to version control
  3. Use different environment files for development, test, and production
  4. Enable SSL/TLS in production (preferably via reverse proxy)
  5. Monitor log files for issues
  6. Regularly rotate logs in production
  7. Start with smaller Whisper models and upgrade if needed
  8. Consider GPU acceleration for larger Whisper models
"},{"location":"configuration.html#validation","title":"Validation","text":"

The server validates configuration on startup using Zod schemas: - Required fields are checked (e.g., HASS_TOKEN) - Value types are verified - Enums are validated (e.g., LOG_LEVEL, WHISPER_MODEL_TYPE) - Default values are applied when not specified

"},{"location":"configuration.html#troubleshooting","title":"Troubleshooting","text":"

Common configuration issues: 1. Missing required environment variables 2. Invalid environment variable values 3. Permission issues with log directories 4. Rate limiting too restrictive 5. Speech model loading failures 6. Docker not available for speech features 7. Insufficient system resources for larger models

See the Troubleshooting Guide for solutions.

"},{"location":"configuration.html#configuration-guide","title":"Configuration Guide","text":"

This document describes all available configuration options for the Home Assistant MCP Server.

"},{"location":"configuration.html#environment-variables_1","title":"Environment Variables","text":""},{"location":"configuration.html#required-settings","title":"Required Settings","text":"
# Server Configuration\nPORT=3000                      # Server port\nHOST=localhost                 # Server host\n\n# Home Assistant\nHASS_URL=http://localhost:8123 # Home Assistant URL\nHASS_TOKEN=your_token         # Long-lived access token\n\n# Security\nJWT_SECRET=your_secret        # JWT signing secret\n
"},{"location":"configuration.html#optional-settings","title":"Optional Settings","text":"
# Rate Limiting\nRATE_LIMIT_WINDOW=60000       # Time window in ms (default: 60000)\nRATE_LIMIT_MAX=100           # Max requests per window (default: 100)\n\n# Logging\nLOG_LEVEL=info               # debug, info, warn, error (default: info)\nLOG_DIR=logs                 # Log directory (default: logs)\nLOG_MAX_SIZE=10m            # Max log file size (default: 10m)\nLOG_MAX_FILES=5             # Max number of log files (default: 5)\n\n# WebSocket/SSE\nWS_HEARTBEAT=30000          # WebSocket heartbeat interval in ms (default: 30000)\nSSE_RETRY=3000             # SSE retry interval in ms (default: 3000)\n\n# Speech Features\nENABLE_SPEECH_FEATURES=false # Enable speech processing (default: false)\nENABLE_WAKE_WORD=false      # Enable wake word detection (default: false)\nENABLE_SPEECH_TO_TEXT=false # Enable speech-to-text (default: false)\n\n# Speech Model Configuration\nWHISPER_MODEL_PATH=/models  # Path to whisper models (default: /models)\nWHISPER_MODEL_TYPE=base     # Model type: tiny|base|small|medium|large-v2 (default: base)\nWHISPER_LANGUAGE=en        # Primary language (default: en)\nWHISPER_TASK=transcribe    # Task type: transcribe|translate (default: transcribe)\nWHISPER_DEVICE=cuda        # Processing device: cpu|cuda (default: cuda if available, else cpu)\n\n# Wake Word Configuration\nWAKE_WORDS=hey jarvis,ok google,alexa  # Comma-separated wake words (default: hey jarvis)\nWAKE_WORD_SENSITIVITY=0.5   # Detection sensitivity 0-1 (default: 0.5)\n
"},{"location":"configuration.html#speech-features","title":"Speech Features","text":""},{"location":"configuration.html#model-selection","title":"Model Selection","text":"

Choose a model based on your needs:

Model Size Memory Required Speed Accuracy tiny.en 75MB 1GB Fast Basic base.en 150MB 2GB Good Good small.en 500MB 4GB Med Better medium.en 1.5GB 8GB Slow High large-v2 3GB 16GB Slow Best"},{"location":"configuration.html#gpu-acceleration","title":"GPU Acceleration","text":"

When WHISPER_DEVICE=cuda: - NVIDIA GPU with CUDA support required - Significantly faster processing - Higher memory requirements

"},{"location":"configuration.html#wake-word-detection","title":"Wake Word Detection","text":""},{"location":"configuration.html#best-practices_1","title":"Best Practices","text":"
  1. Model Selection:
  2. Start with base.en model
  3. Upgrade if better accuracy needed
  4. Downgrade if performance issues

  5. Resource Management:

  6. Monitor memory usage
  7. Use GPU acceleration when available
  8. Consider model size vs available resources

  9. Wake Word Configuration:

  10. Use distinct wake words
  11. Adjust sensitivity based on environment
  12. Limit number of wake words for better performance
"},{"location":"contributing.html","title":"Contributing Guide \ud83e\udd1d","text":"

Thank you for your interest in contributing to the MCP Server project!

"},{"location":"contributing.html#getting-started","title":"Getting Started","text":""},{"location":"contributing.html#prerequisites","title":"Prerequisites","text":""},{"location":"contributing.html#development-setup","title":"Development Setup","text":"
  1. Fork the repository
  2. Clone your fork:

    git clone https://github.com/YOUR_USERNAME/homeassistant-mcp.git\ncd homeassistant-mcp\n

  3. Install dependencies:

    bun install\n

  4. Configure environment:

    cp .env.example .env\n# Edit .env with your Home Assistant details\n

"},{"location":"contributing.html#development-workflow","title":"Development Workflow","text":""},{"location":"contributing.html#branch-naming","title":"Branch Naming","text":"

Example:

git checkout -b feature/device-control-improvements\n

"},{"location":"contributing.html#commit-messages","title":"Commit Messages","text":"

Follow simple, clear commit messages:

type: brief description\n\n[optional detailed explanation]\n

Types: - feat: - New feature - fix: - Bug fix - docs: - Documentation - chore: - Maintenance

"},{"location":"contributing.html#code-style","title":"Code Style","text":""},{"location":"contributing.html#testing","title":"Testing","text":"

Run tests before submitting:

# Run all tests\nbun test\n\n# Run specific test\nbun test test/api/control.test.ts\n
"},{"location":"contributing.html#pull-request-process","title":"Pull Request Process","text":"
  1. Ensure tests pass
  2. Update documentation if needed
  3. Provide clear description of changes
"},{"location":"contributing.html#pr-template","title":"PR Template","text":"
## Description\nBrief explanation of the changes\n\n## Type of Change\n- [ ] Bug fix\n- [ ] New feature\n- [ ] Documentation update\n\n## Testing\nDescribe how you tested these changes\n
"},{"location":"contributing.html#reporting-issues","title":"Reporting Issues","text":""},{"location":"contributing.html#code-of-conduct","title":"Code of Conduct","text":""},{"location":"contributing.html#resources","title":"Resources","text":"

Thank you for contributing!

"},{"location":"deployment.html","title":"Deployment Guide","text":"

This documentation is automatically deployed to GitHub Pages using GitHub Actions. Here's how it works and how to manage deployments.

"},{"location":"deployment.html#automatic-deployment","title":"Automatic Deployment","text":"

The documentation is automatically deployed when changes are pushed to the main or master branch. The deployment process:

  1. Triggers on push to main/master
  2. Sets up Python environment
  3. Installs required dependencies
  4. Builds the documentation
  5. Deploys to the gh-pages branch
"},{"location":"deployment.html#github-actions-workflow","title":"GitHub Actions Workflow","text":"

The deployment is handled by the workflow in .github/workflows/deploy-docs.yml. This is the single source of truth for documentation deployment:

name: Deploy MkDocs\non:\n  push:\n    branches:\n      - main\n      - master\n  workflow_dispatch:  # Allow manual trigger\n
"},{"location":"deployment.html#manual-deployment","title":"Manual Deployment","text":"

If needed, you can deploy manually using:

# Create a virtual environment\npython -m venv venv\n\n# Activate the virtual environment\nsource venv/bin/activate\n\n# Install dependencies\npip install -r docs/requirements.txt\n\n# Build the documentation\nmkdocs build\n\n# Deploy to GitHub Pages\nmkdocs gh-deploy --force\n
"},{"location":"deployment.html#best-practices","title":"Best Practices","text":""},{"location":"deployment.html#1-documentation-updates","title":"1. Documentation Updates","text":""},{"location":"deployment.html#2-version-control","title":"2. Version Control","text":""},{"location":"deployment.html#3-content-guidelines","title":"3. Content Guidelines","text":""},{"location":"deployment.html#4-maintenance","title":"4. Maintenance","text":""},{"location":"deployment.html#troubleshooting","title":"Troubleshooting","text":""},{"location":"deployment.html#common-issues","title":"Common Issues","text":"
  1. Failed Deployments
  2. Check GitHub Actions logs
  3. Verify dependencies are up to date
  4. Ensure all required files exist

  5. Broken Links

  6. Run mkdocs build --strict
  7. Use relative paths in markdown
  8. Check case sensitivity

  9. Style Issues

  10. Verify theme configuration
  11. Check CSS customizations
  12. Test on multiple browsers
"},{"location":"deployment.html#configuration-files","title":"Configuration Files","text":""},{"location":"deployment.html#requirementstxt","title":"requirements.txt","text":"

Create a requirements file for documentation dependencies:

mkdocs-material\nmkdocs-minify-plugin\nmkdocs-git-revision-date-plugin\nmkdocs-mkdocstrings\nmkdocs-social-plugin\nmkdocs-redirects\n
"},{"location":"deployment.html#monitoring","title":"Monitoring","text":""},{"location":"deployment.html#workflow-features","title":"Workflow Features","text":""},{"location":"deployment.html#caching","title":"Caching","text":"

The workflow implements caching for Python dependencies to speed up deployments: - Pip cache for Python packages - MkDocs dependencies cache

"},{"location":"deployment.html#deployment-checks","title":"Deployment Checks","text":"

Several checks are performed during deployment: 1. Link validation with mkdocs build --strict 2. Build verification 3. Post-deployment site accessibility check

"},{"location":"deployment.html#manual-triggers","title":"Manual Triggers","text":"

You can manually trigger deployments using the \"workflow_dispatch\" event in GitHub Actions.

"},{"location":"deployment.html#cleanup","title":"Cleanup","text":"

To clean up duplicate workflow files, run:

# Make the script executable\nchmod +x scripts/cleanup-workflows.sh\n\n# Run the cleanup script\n./scripts/cleanup-workflows.sh\n
"},{"location":"roadmap.html","title":"Roadmap for MCP Server","text":"

The following roadmap outlines our planned enhancements and future directions for the Home Assistant MCP Server. This document is a living guide that will be updated as new features are developed.

"},{"location":"roadmap.html#near-term-goals","title":"Near-Term Goals","text":""},{"location":"roadmap.html#mid-term-goals","title":"Mid-Term Goals","text":""},{"location":"roadmap.html#long-term-vision","title":"Long-Term Vision","text":""},{"location":"roadmap.html#how-to-follow-the-roadmap","title":"How to Follow the Roadmap","text":"

This roadmap is intended as a guide and may evolve based on community needs, technological advancements, and strategic priorities.

"},{"location":"security.html","title":"Security Guide","text":"

This document outlines security best practices and configurations for the Home Assistant MCP Server.

"},{"location":"security.html#authentication","title":"Authentication","text":""},{"location":"security.html#jwt-authentication","title":"JWT Authentication","text":"

The server uses JWT (JSON Web Tokens) for API authentication:

Authorization: Bearer YOUR_JWT_TOKEN\n
"},{"location":"security.html#token-configuration","title":"Token Configuration","text":"
security:\n  jwt_secret: YOUR_SECRET_KEY\n  token_expiry: 24h\n  refresh_token_expiry: 7d\n
"},{"location":"security.html#access-control","title":"Access Control","text":""},{"location":"security.html#cors-configuration","title":"CORS Configuration","text":"

Configure allowed origins to prevent unauthorized access:

security:\n  allowed_origins:\n    - http://localhost:3000\n    - https://your-domain.com\n
"},{"location":"security.html#ip-filtering","title":"IP Filtering","text":"

Restrict access by IP address:

security:\n  allowed_ips:\n    - 192.168.1.0/24\n    - 10.0.0.0/8\n
"},{"location":"security.html#ssltls-configuration","title":"SSL/TLS Configuration","text":""},{"location":"security.html#enable-https","title":"Enable HTTPS","text":"
ssl:\n  enabled: true\n  cert_file: /path/to/cert.pem\n  key_file: /path/to/key.pem\n
"},{"location":"security.html#certificate-management","title":"Certificate Management","text":"
  1. Use Let's Encrypt for free SSL certificates
  2. Regularly renew certificates
  3. Monitor certificate expiration
"},{"location":"security.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"security.html#basic-rate-limiting","title":"Basic Rate Limiting","text":"
rate_limit:\n  enabled: true\n  requests_per_minute: 100\n  burst: 20\n
"},{"location":"security.html#advanced-rate-limiting","title":"Advanced Rate Limiting","text":"
rate_limit:\n  rules:\n    - endpoint: /api/control\n      requests_per_minute: 50\n    - endpoint: /api/state\n      requests_per_minute: 200\n
"},{"location":"security.html#data-protection","title":"Data Protection","text":""},{"location":"security.html#sensitive-data","title":"Sensitive Data","text":""},{"location":"security.html#logging-security","title":"Logging Security","text":""},{"location":"security.html#best-practices","title":"Best Practices","text":"
  1. Regular Security Updates
  2. Keep dependencies updated
  3. Monitor security advisories
  4. Apply patches promptly

  5. Password Policies

  6. Enforce strong passwords
  7. Implement password expiration
  8. Use secure password storage

  9. Monitoring

  10. Log security events
  11. Monitor access patterns
  12. Set up alerts for suspicious activity

  13. Network Security

  14. Use VPN for remote access
  15. Implement network segmentation
  16. Configure firewalls properly
"},{"location":"security.html#security-checklist","title":"Security Checklist","text":""},{"location":"security.html#incident-response","title":"Incident Response","text":"
  1. Detection
  2. Monitor security logs
  3. Set up intrusion detection
  4. Configure alerts

  5. Response

  6. Document incident details
  7. Isolate affected systems
  8. Investigate root cause

  9. Recovery

  10. Apply security fixes
  11. Restore from backups
  12. Update security measures
"},{"location":"security.html#additional-resources","title":"Additional Resources","text":""},{"location":"testing.html","title":"Testing Documentation","text":""},{"location":"testing.html#quick-reference","title":"Quick Reference","text":"
# Most Common Commands\nbun test                    # Run all tests\nbun test --watch           # Run tests in watch mode\nbun test --coverage        # Run tests with coverage\nbun test path/to/test.ts   # Run a specific test file\n\n# Additional Options\nDEBUG=true bun test        # Run with debug output\nbun test --pattern \"auth\"  # Run tests matching a pattern\nbun test --timeout 60000   # Run with a custom timeout\n
"},{"location":"testing.html#overview","title":"Overview","text":"

This document describes the testing setup and practices used in the Home Assistant MCP project. We use Bun's test runner for both unit and integration testing, ensuring comprehensive coverage across modules.

"},{"location":"testing.html#test-structure","title":"Test Structure","text":"

Tests are organized in two main locations:

  1. Root Level Integration Tests (/__tests__/):
__tests__/\n\u251c\u2500\u2500 ai/              # AI/ML component tests\n\u251c\u2500\u2500 api/             # API integration tests\n\u251c\u2500\u2500 context/         # Context management tests\n\u251c\u2500\u2500 hass/            # Home Assistant integration tests\n\u251c\u2500\u2500 schemas/         # Schema validation tests\n\u251c\u2500\u2500 security/        # Security integration tests\n\u251c\u2500\u2500 tools/           # Tools and utilities tests\n\u251c\u2500\u2500 websocket/       # WebSocket integration tests\n\u251c\u2500\u2500 helpers.test.ts  # Helper function tests\n\u251c\u2500\u2500 index.test.ts    # Main application tests\n\u2514\u2500\u2500 server.test.ts   # Server integration tests\n
  1. Component Level Unit Tests (src/**/):
src/\n\u251c\u2500\u2500 __tests__/   # Global test setup and utilities\n\u2502   \u2514\u2500\u2500 setup.ts # Global test configuration\n\u251c\u2500\u2500 component/\n\u2502   \u251c\u2500\u2500 __tests__/   # Component-specific unit tests\n\u2502   \u2514\u2500\u2500 component.ts\n
"},{"location":"testing.html#test-configuration","title":"Test Configuration","text":""},{"location":"testing.html#bun-test-configuration-bunfigtoml","title":"Bun Test Configuration (bunfig.toml)","text":"
[test]\npreload = [\"./src/__tests__/setup.ts\"]  # Global test setup\ncoverage = true                         # Enable coverage by default\ntimeout = 30000                         # Test timeout in milliseconds\ntestMatch = [\"**/__tests__/**/*.test.ts\"] # Test file patterns\n
"},{"location":"testing.html#bun-scripts","title":"Bun Scripts","text":"

Available test commands in package.json:

# Run all tests\nbun test\n\n# Watch mode for development\nbun test --watch\n\n# Generate coverage report\nbun test --coverage\n\n# Run linting\nbun run lint\n\n# Format code\nbun run format\n
"},{"location":"testing.html#test-setup","title":"Test Setup","text":""},{"location":"testing.html#global-configuration","title":"Global Configuration","text":"

A global test setup file (src/__tests__/setup.ts) provides: - Environment configuration - Mock utilities - Test helper functions - Global lifecycle hooks

"},{"location":"testing.html#test-environment","title":"Test Environment","text":""},{"location":"testing.html#running-tests","title":"Running Tests","text":"
# Basic test run\nbun test\n\n# Run tests with coverage\nbun test --coverage\n\n# Run a specific test file\nbun test path/to/test.test.ts\n\n# Run tests in watch mode\nbun test --watch\n\n# Run tests with debug output\nDEBUG=true bun test\n\n# Run tests with increased timeout\nbun test --timeout 60000\n\n# Run tests matching a pattern\nbun test --pattern \"auth\"\n
"},{"location":"testing.html#advanced-debugging","title":"Advanced Debugging","text":""},{"location":"testing.html#using-node-inspector","title":"Using Node Inspector","text":"
# Start tests with inspector\nbun test --inspect\n\n# Start tests with inspector and break on first line\nbun test --inspect-brk\n
"},{"location":"testing.html#using-vs-code","title":"Using VS Code","text":"

Create a launch configuration in .vscode/launch.json:

{\n  \"version\": \"0.2.0\",\n  \"configurations\": [\n    {\n      \"type\": \"bun\",\n      \"request\": \"launch\",\n      \"name\": \"Debug Tests\",\n      \"program\": \"${workspaceFolder}/node_modules/bun/bin/bun\",\n      \"args\": [\"test\", \"${file}\"],\n      \"cwd\": \"${workspaceFolder}\",\n      \"env\": { \"DEBUG\": \"true\" }\n    }\n  ]\n}\n
"},{"location":"testing.html#test-isolation","title":"Test Isolation","text":"

To run a single test in isolation:

describe.only(\"specific test suite\", () => {\n  it.only(\"specific test case\", () => {\n    // Only this test will run\n  });\n});\n
"},{"location":"testing.html#writing-tests","title":"Writing Tests","text":""},{"location":"testing.html#test-file-naming","title":"Test File Naming","text":""},{"location":"testing.html#example-test-structure","title":"Example Test Structure","text":"
describe(\"Security Features\", () => {\n  it(\"should validate tokens correctly\", () => {\n    const payload = { userId: \"123\", role: \"user\" };\n    const token = jwt.sign(payload, validSecret, { expiresIn: \"1h\" });\n    const result = TokenManager.validateToken(token, testIp);\n    expect(result.valid).toBe(true);\n  });\n});\n
"},{"location":"testing.html#coverage","title":"Coverage","text":"

The project maintains strict coverage: - Overall coverage: at least 80% - Critical paths: 90%+ - New features: \u226585% coverage

Generate a coverage report with:

bun test --coverage\n
"},{"location":"testing.html#security-middleware-testing","title":"Security Middleware Testing","text":""},{"location":"testing.html#utility-function-testing","title":"Utility Function Testing","text":"

The security middleware now uses a utility-first approach, which allows for more granular and comprehensive testing. Each security function is now independently testable, improving code reliability and maintainability.

"},{"location":"testing.html#key-utility-functions","title":"Key Utility Functions","text":"
  1. Rate Limiting (checkRateLimit)
  2. Tests multiple scenarios:
    • Requests under threshold
    • Requests exceeding threshold
    • Rate limit reset after window expiration
// Example test\nit('should throw when requests exceed threshold', () => {\n  const ip = '127.0.0.2';\n  for (let i = 0; i < 11; i++) {\n    if (i < 10) {\n      expect(() => checkRateLimit(ip, 10)).not.toThrow();\n    } else {\n      expect(() => checkRateLimit(ip, 10)).toThrow('Too many requests from this IP');\n    }\n  }\n});\n
  1. Request Validation (validateRequestHeaders)
  2. Tests content type validation
  3. Checks request size limits
  4. Validates authorization headers
it('should reject invalid content type', () => {\n  const mockRequest = new Request('http://localhost', {\n    method: 'POST',\n    headers: { 'content-type': 'text/plain' }\n  });\n  expect(() => validateRequestHeaders(mockRequest)).toThrow('Content-Type must be application/json');\n});\n
  1. Input Sanitization (sanitizeValue)
  2. Sanitizes HTML tags
  3. Handles nested objects
  4. Preserves non-string values
it('should sanitize HTML tags', () => {\n  const input = '<script>alert(\"xss\")</script>Hello';\n  const sanitized = sanitizeValue(input);\n  expect(sanitized).toBe('&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;Hello');\n});\n
  1. Security Headers (applySecurityHeaders)
  2. Verifies correct security header application
  3. Checks CSP, frame options, and other security headers
it('should apply security headers', () => {\n  const mockRequest = new Request('http://localhost');\n  const headers = applySecurityHeaders(mockRequest);\n  expect(headers['content-security-policy']).toBeDefined();\n  expect(headers['x-frame-options']).toBeDefined();\n});\n
  1. Error Handling (handleError)
  2. Tests error responses in production and development modes
  3. Verifies error message and stack trace inclusion
it('should include error details in development mode', () => {\n  const error = new Error('Test error');\n  const result = handleError(error, 'development');\n  expect(result).toEqual({\n    error: true,\n    message: 'Internal server error',\n    error: 'Test error',\n    stack: expect.any(String)\n  });\n});\n
"},{"location":"testing.html#testing-philosophy","title":"Testing Philosophy","text":""},{"location":"testing.html#best-practices","title":"Best Practices","text":"
  1. Use minimal, focused test cases
  2. Test both successful and failure scenarios
  3. Verify input sanitization and security measures
  4. Mock external dependencies when necessary
"},{"location":"testing.html#running-security-tests","title":"Running Security Tests","text":"
# Run all tests\nbun test\n\n# Run specific security tests\nbun test __tests__/security/\n
"},{"location":"testing.html#continuous-improvement","title":"Continuous Improvement","text":""},{"location":"testing.html#best-practices_1","title":"Best Practices","text":"
  1. Isolation: Each test should be independent and not rely on the state of other tests.
  2. Mocking: Use the provided mock utilities for external dependencies.
  3. Cleanup: Clean up any resources or state modifications in afterEach or afterAll hooks.
  4. Descriptive Names: Use clear, descriptive test names that explain the expected behavior.
  5. Assertions: Make specific, meaningful assertions rather than general ones.
  6. Setup: Use beforeEach for common test setup to avoid repetition.
  7. Error Cases: Test both success and error cases for complete coverage.
"},{"location":"testing.html#coverage_1","title":"Coverage","text":"

The project aims for high test coverage, particularly focusing on: - Security-critical code paths - API endpoints - Data validation - Error handling - Event broadcasting

Run coverage reports using:

bun test --coverage\n

"},{"location":"testing.html#debugging-tests","title":"Debugging Tests","text":"

To debug tests: 1. Set DEBUG=true to enable console output during tests 2. Use the --watch flag for development 3. Add console.log() statements (they're only shown when DEBUG is true) 4. Use the test utilities' debugging helpers

"},{"location":"testing.html#advanced-debugging_1","title":"Advanced Debugging","text":"
  1. Using Node Inspector:

    # Start tests with inspector\nbun test --inspect\n\n# Start tests with inspector and break on first line\nbun test --inspect-brk\n

  2. Using VS Code:

    // .vscode/launch.json\n{\n  \"version\": \"0.2.0\",\n  \"configurations\": [\n    {\n      \"type\": \"bun\",\n      \"request\": \"launch\",\n      \"name\": \"Debug Tests\",\n      \"program\": \"${workspaceFolder}/node_modules/bun/bin/bun\",\n      \"args\": [\"test\", \"${file}\"],\n      \"cwd\": \"${workspaceFolder}\",\n      \"env\": { \"DEBUG\": \"true\" }\n    }\n  ]\n}\n

  3. Test Isolation: To run a single test in isolation:

    describe.only(\"specific test suite\", () => {\n  it.only(\"specific test case\", () => {\n    // Only this test will run\n  });\n});\n

"},{"location":"testing.html#contributing","title":"Contributing","text":"

When contributing new code: 1. Add tests for new features 2. Ensure existing tests pass 3. Maintain or improve coverage 4. Follow the existing test patterns and naming conventions 5. Document any new test utilities or patterns

"},{"location":"testing.html#coverage-requirements","title":"Coverage Requirements","text":"

The project maintains strict coverage requirements:

Coverage reports are generated in multiple formats: - Console summary - HTML report (./coverage/index.html) - LCOV report (./coverage/lcov.info)

To view detailed coverage:

# Generate and open coverage report\nbun test --coverage && open coverage/index.html\n

"},{"location":"troubleshooting.html","title":"Troubleshooting Guide \ud83d\udd27","text":"

This guide helps you diagnose and resolve common issues with MCP Server.

"},{"location":"troubleshooting.html#quick-diagnostics","title":"Quick Diagnostics","text":""},{"location":"troubleshooting.html#health-check","title":"Health Check","text":"

First, verify the server's health:

curl http://localhost:3000/health\n

Expected response:

{\n  \"status\": \"healthy\",\n  \"version\": \"1.0.0\",\n  \"uptime\": 3600,\n  \"homeAssistant\": {\n    \"connected\": true,\n    \"version\": \"2024.1.0\"\n  }\n}\n

"},{"location":"troubleshooting.html#common-issues","title":"Common Issues","text":""},{"location":"troubleshooting.html#1-connection-issues","title":"1. Connection Issues","text":""},{"location":"troubleshooting.html#cannot-connect-to-mcp-server","title":"Cannot Connect to MCP Server","text":"

Symptoms: - Server not responding - Connection refused errors - Timeout errors

Solutions:

  1. Check if the server is running:

    # For Docker installation\ndocker compose ps\n\n# For manual installation\nps aux | grep mcp\n

  2. Verify port availability:

    # Check if port is in use\nnetstat -tuln | grep 3000\n

  3. Check logs:

    # Docker logs\ndocker compose logs mcp\n\n# Manual installation logs\nbun run dev\n

"},{"location":"troubleshooting.html#home-assistant-connection-failed","title":"Home Assistant Connection Failed","text":"

Symptoms: - \"Connection Error\" in health check - Cannot control devices - State updates not working

Solutions:

  1. Verify Home Assistant URL and token in .env:

    HA_URL=http://homeassistant:8123\nHA_TOKEN=your_long_lived_access_token\n

  2. Test Home Assistant connection:

    curl -H \"Authorization: Bearer YOUR_HA_TOKEN\" \\\n     http://your-homeassistant:8123/api/\n

  3. Check network connectivity:

    # For Docker setup\ndocker compose exec mcp ping homeassistant\n

"},{"location":"troubleshooting.html#2-authentication-issues","title":"2. Authentication Issues","text":""},{"location":"troubleshooting.html#invalid-token","title":"Invalid Token","text":"

Symptoms: - 401 Unauthorized responses - \"Invalid token\" errors

Solutions:

  1. Generate a new token:

    curl -X POST http://localhost:3000/auth/token \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"username\": \"your_username\", \"password\": \"your_password\"}'\n

  2. Verify token format:

    // Token should be in format:\nAuthorization: Bearer eyJhbGciOiJIUzI1NiIs...\n

"},{"location":"troubleshooting.html#rate-limiting","title":"Rate Limiting","text":"

Symptoms: - 429 Too Many Requests - \"Rate limit exceeded\" errors

Solutions:

  1. Check current rate limit status:

    curl -I http://localhost:3000/api/state\n

  2. Adjust rate limits in configuration:

    security:\n  rateLimit: 100  # Increase if needed\n  rateLimitWindow: 60000  # Window in milliseconds\n

"},{"location":"troubleshooting.html#3-real-time-updates-issues","title":"3. Real-time Updates Issues","text":""},{"location":"troubleshooting.html#sse-connection-drops","title":"SSE Connection Drops","text":"

Symptoms: - Frequent disconnections - Missing state updates - EventSource errors

Solutions:

  1. Implement proper reconnection logic:

    class SSEClient {\n    constructor() {\n        this.connect();\n    }\n\n    connect() {\n        this.eventSource = new EventSource('/subscribe_events');\n        this.eventSource.onerror = this.handleError.bind(this);\n    }\n\n    handleError(error) {\n        console.error('SSE Error:', error);\n        this.eventSource.close();\n        setTimeout(() => this.connect(), 1000);\n    }\n}\n

  2. Check network stability:

    # Monitor connection stability\nping -c 100 localhost\n

"},{"location":"troubleshooting.html#4-performance-issues","title":"4. Performance Issues","text":""},{"location":"troubleshooting.html#high-latency","title":"High Latency","text":"

Symptoms: - Slow response times - Command execution delays - UI lag

Solutions:

  1. Enable Redis caching:

    REDIS_ENABLED=true\nREDIS_URL=redis://localhost:6379\n

  2. Monitor system resources:

    # Check CPU and memory usage\ndocker stats\n\n# Or for manual installation\ntop -p $(pgrep -f mcp)\n

  3. Optimize database queries and caching:

    // Use batch operations\nconst results = await Promise.all([\n    cache.get('key1'),\n    cache.get('key2')\n]);\n

"},{"location":"troubleshooting.html#5-device-control-issues","title":"5. Device Control Issues","text":""},{"location":"troubleshooting.html#commands-not-executing","title":"Commands Not Executing","text":"

Symptoms: - Commands appear successful but no device response - Inconsistent device states - Error messages from Home Assistant

Solutions:

  1. Verify device availability:

    curl http://localhost:3000/api/state/light.living_room\n

  2. Check command syntax:

    # Test basic command\ncurl -X POST http://localhost:3000/api/command \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"command\": \"Turn on living room lights\"}'\n

  3. Review Home Assistant logs:

    docker compose exec homeassistant journalctl -f\n

"},{"location":"troubleshooting.html#debugging-tools","title":"Debugging Tools","text":""},{"location":"troubleshooting.html#log-analysis","title":"Log Analysis","text":"

Enable debug logging:

LOG_LEVEL=debug\nDEBUG=mcp:*\n
"},{"location":"troubleshooting.html#network-debugging","title":"Network Debugging","text":"

Monitor network traffic:

# TCP dump for API traffic\ntcpdump -i any port 3000 -w debug.pcap\n
"},{"location":"troubleshooting.html#performance-profiling","title":"Performance Profiling","text":"

Enable performance monitoring:

ENABLE_METRICS=true\nMETRICS_PORT=9090\n
"},{"location":"troubleshooting.html#getting-help","title":"Getting Help","text":"

If you're still experiencing issues:

  1. Check the GitHub Issues
  2. Search Discussions
  3. Create a new issue with:
  4. Detailed description
  5. Logs
  6. Configuration (sanitized)
  7. Steps to reproduce
"},{"location":"troubleshooting.html#maintenance","title":"Maintenance","text":""},{"location":"troubleshooting.html#regular-health-checks","title":"Regular Health Checks","text":"

Run periodic health checks:

# Create a cron job\n*/5 * * * * curl -f http://localhost:3000/health || notify-admin\n
"},{"location":"troubleshooting.html#log-rotation","title":"Log Rotation","text":"

Configure log rotation:

logging:\n  maxSize: \"100m\"\n  maxFiles: \"7d\"\n  compress: true\n
"},{"location":"troubleshooting.html#backup-configuration","title":"Backup Configuration","text":"

Regularly backup your configuration:

# Backup script\ntar -czf mcp-backup-$(date +%Y%m%d).tar.gz \\\n    .env \\\n    config/ \\\n    data/\n
"},{"location":"troubleshooting.html#faq","title":"FAQ","text":""},{"location":"troubleshooting.html#general-questions","title":"General Questions","text":""},{"location":"troubleshooting.html#q-what-is-mcp-server","title":"Q: What is MCP Server?","text":"

A: MCP Server is a bridge between Home Assistant and Language Learning Models, enabling natural language control and automation of your smart home devices.

"},{"location":"troubleshooting.html#q-what-are-the-system-requirements","title":"Q: What are the system requirements?","text":"

A: MCP Server requires: - Node.js 16 or higher - Home Assistant instance - 1GB RAM minimum - 1GB disk space

"},{"location":"troubleshooting.html#q-how-do-i-update-mcp-server","title":"Q: How do I update MCP Server?","text":"

A: For Docker installation:

docker compose pull\ndocker compose up -d\n
For manual installation:
git pull\nbun install\nbun run build\n

"},{"location":"troubleshooting.html#integration-questions","title":"Integration Questions","text":""},{"location":"troubleshooting.html#q-can-i-use-mcp-server-with-any-home-assistant-instance","title":"Q: Can I use MCP Server with any Home Assistant instance?","text":"

A: Yes, MCP Server works with any Home Assistant instance that has the REST API enabled and a valid long-lived access token.

"},{"location":"troubleshooting.html#q-does-mcp-server-support-all-home-assistant-integrations","title":"Q: Does MCP Server support all Home Assistant integrations?","text":"

A: MCP Server supports all Home Assistant devices and services that are accessible via the REST API.

"},{"location":"troubleshooting.html#security-questions","title":"Security Questions","text":""},{"location":"troubleshooting.html#q-is-my-home-assistant-token-secure","title":"Q: Is my Home Assistant token secure?","text":"

A: Yes, your Home Assistant token is stored securely and only used for authenticated communication between MCP Server and your Home Assistant instance.

"},{"location":"troubleshooting.html#q-can-i-use-mcp-server-remotely","title":"Q: Can I use MCP Server remotely?","text":"

A: Yes, but we recommend using a secure connection (HTTPS) and proper authentication when exposing MCP Server to the internet.

"},{"location":"troubleshooting.html#troubleshooting-questions","title":"Troubleshooting Questions","text":""},{"location":"troubleshooting.html#q-why-are-my-device-states-not-updating","title":"Q: Why are my device states not updating?","text":"

A: Check: 1. Home Assistant connection 2. WebSocket connection status 3. Device availability in Home Assistant 4. Network connectivity

"},{"location":"troubleshooting.html#q-why-are-my-commands-not-working","title":"Q: Why are my commands not working?","text":"

A: Verify: 1. Command syntax 2. Device availability 3. User permissions 4. Home Assistant API access

"},{"location":"usage.html","title":"Usage Guide","text":"

This guide explains how to use the Home Assistant MCP Server for basic device management and integration.

"},{"location":"usage.html#basic-setup","title":"Basic Setup","text":"
  1. Starting the Server:
  2. Development mode: bun run dev
  3. Production mode: bun run start

  4. Accessing the Server:

  5. Default URL: http://localhost:3000
  6. Ensure Home Assistant credentials are configured in .env
"},{"location":"usage.html#device-control","title":"Device Control","text":""},{"location":"usage.html#rest-api-interactions","title":"REST API Interactions","text":"

Basic device control can be performed via the REST API:

// Turn on a light\nfetch('http://localhost:3000/api/control', {\n  method: 'POST',\n  headers: {\n    'Content-Type': 'application/json',\n    'Authorization': `Bearer ${token}`\n  },\n  body: JSON.stringify({\n    entity_id: 'light.living_room',\n    command: 'turn_on',\n    parameters: { brightness: 50 }\n  })\n});\n
"},{"location":"usage.html#supported-commands","title":"Supported Commands","text":""},{"location":"usage.html#supported-entities","title":"Supported Entities","text":""},{"location":"usage.html#real-time-updates","title":"Real-Time Updates","text":""},{"location":"usage.html#websocket-connection","title":"WebSocket Connection","text":"

Subscribe to real-time device state changes:

const ws = new WebSocket('ws://localhost:3000/events');\nws.onmessage = (event) => {\n  const deviceUpdate = JSON.parse(event.data);\n  console.log('Device state changed:', deviceUpdate);\n};\n
"},{"location":"usage.html#authentication","title":"Authentication","text":"

All API requests require a valid JWT token in the Authorization header.

"},{"location":"usage.html#limitations","title":"Limitations","text":""},{"location":"usage.html#troubleshooting","title":"Troubleshooting","text":"
  1. Verify Home Assistant connection
  2. Check JWT token validity
  3. Ensure correct entity IDs
  4. Review server logs for detailed errors
"},{"location":"usage.html#configuration","title":"Configuration","text":"

Configure the server using environment variables in .env:

HA_URL=http://homeassistant:8123\nHA_TOKEN=your_home_assistant_token\nJWT_SECRET=your_jwt_secret\n
"},{"location":"usage.html#next-steps","title":"Next Steps","text":""},{"location":"api/index.html","title":"API Documentation \ud83d\udcda","text":"

Welcome to the MCP Server API documentation. This guide covers all available endpoints, authentication methods, and integration patterns.

"},{"location":"api/index.html#api-overview","title":"API Overview","text":"

The MCP Server provides several API categories:

  1. Core API - Basic device control and state management
  2. SSE API - Real-time event subscriptions
  3. Scene API - Scene management and automation
  4. Voice API - Natural language command processing
"},{"location":"api/index.html#authentication","title":"Authentication","text":"

All API endpoints require authentication using JWT tokens:

# Include the token in your requests\ncurl -H \"Authorization: Bearer YOUR_JWT_TOKEN\" http://localhost:3000/api/state\n

To obtain a token:

curl -X POST http://localhost:3000/auth/token \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"username\": \"your_username\", \"password\": \"your_password\"}'\n
"},{"location":"api/index.html#core-endpoints","title":"Core Endpoints","text":""},{"location":"api/index.html#device-state","title":"Device State","text":"
GET /api/state\n

Retrieve the current state of all devices:

curl http://localhost:3000/api/state\n

Response:

{\n  \"devices\": [\n    {\n      \"id\": \"light.living_room\",\n      \"state\": \"on\",\n      \"attributes\": {\n        \"brightness\": 255,\n        \"color_temp\": 370\n      }\n    }\n  ]\n}\n

"},{"location":"api/index.html#command-execution","title":"Command Execution","text":"
POST /api/command\n

Execute a natural language command:

curl -X POST http://localhost:3000/api/command \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"command\": \"Turn on the kitchen lights\"}'\n

Response:

{\n  \"success\": true,\n  \"action\": \"turn_on\",\n  \"device\": \"light.kitchen\",\n  \"message\": \"Kitchen lights turned on\"\n}\n

"},{"location":"api/index.html#real-time-events","title":"Real-Time Events","text":""},{"location":"api/index.html#event-subscription","title":"Event Subscription","text":"
GET /subscribe_events\n

Subscribe to device state changes:

const eventSource = new EventSource('http://localhost:3000/subscribe_events?token=YOUR_TOKEN');\n\neventSource.onmessage = (event) => {\n    const data = JSON.parse(event.data);\n    console.log('State changed:', data);\n};\n
"},{"location":"api/index.html#filtered-subscriptions","title":"Filtered Subscriptions","text":"

Subscribe to specific device types:

GET /subscribe_events?domain=light\nGET /subscribe_events?entity_id=light.living_room\n
"},{"location":"api/index.html#scene-management","title":"Scene Management","text":""},{"location":"api/index.html#create-scene","title":"Create Scene","text":"
POST /api/scene\n

Create a new scene:

curl -X POST http://localhost:3000/api/scene \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"Movie Night\",\n    \"actions\": [\n      {\"device\": \"light.living_room\", \"action\": \"dim\", \"value\": 20},\n      {\"device\": \"media_player.tv\", \"action\": \"on\"}\n    ]\n  }'\n
"},{"location":"api/index.html#activate-scene","title":"Activate Scene","text":"
POST /api/scene/activate\n

Activate an existing scene:

curl -X POST http://localhost:3000/api/scene/activate \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"name\": \"Movie Night\"}'\n
"},{"location":"api/index.html#error-handling","title":"Error Handling","text":"

The API uses standard HTTP status codes:

Error responses include detailed messages:

{\n  \"error\": true,\n  \"message\": \"Device not found\",\n  \"code\": \"DEVICE_NOT_FOUND\",\n  \"details\": {\n    \"device_id\": \"light.nonexistent\"\n  }\n}\n
"},{"location":"api/index.html#rate-limiting","title":"Rate Limiting","text":"

API requests are rate-limited to prevent abuse:

X-RateLimit-Limit: 100\nX-RateLimit-Remaining: 99\nX-RateLimit-Reset: 1640995200\n

When exceeded, returns 429 Too Many Requests:

{\n  \"error\": true,\n  \"message\": \"Rate limit exceeded\",\n  \"reset\": 1640995200\n}\n
"},{"location":"api/index.html#websocket-api","title":"WebSocket API","text":"

For bi-directional communication:

const ws = new WebSocket('ws://localhost:3000/ws');\n\nws.onmessage = (event) => {\n    const data = JSON.parse(event.data);\n    console.log('Received:', data);\n};\n\nws.send(JSON.stringify({\n    type: 'command',\n    payload: {\n        command: 'Turn on lights'\n    }\n}));\n
"},{"location":"api/index.html#api-versioning","title":"API Versioning","text":"

The current API version is v1. Include the version in the URL:

/api/v1/state\n/api/v1/command\n
"},{"location":"api/index.html#further-reading","title":"Further Reading","text":""},{"location":"api/index.html#api-reference","title":"API Reference","text":"

The Advanced Home Assistant MCP provides several APIs for integration and automation:

"},{"location":"api/core.html","title":"Core Functions API \ud83d\udd27","text":"

The Core Functions API provides the fundamental operations for interacting with Home Assistant devices and services through MCP Server.

"},{"location":"api/core.html#device-control","title":"Device Control","text":""},{"location":"api/core.html#get-device-state","title":"Get Device State","text":"

Retrieve the current state of devices.

GET /api/state\nGET /api/state/{entity_id}\n

Parameters: - entity_id (optional): Specific device ID to query

# Get all states\ncurl http://localhost:3000/api/state\n\n# Get specific device state\ncurl http://localhost:3000/api/state/light.living_room\n

Response:

{\n  \"entity_id\": \"light.living_room\",\n  \"state\": \"on\",\n  \"attributes\": {\n    \"brightness\": 255,\n    \"color_temp\": 370,\n    \"friendly_name\": \"Living Room Light\"\n  },\n  \"last_changed\": \"2024-01-20T15:30:00Z\"\n}\n

"},{"location":"api/core.html#control-device","title":"Control Device","text":"

Execute device commands.

POST /api/device/control\n

Request body:

{\n  \"entity_id\": \"light.living_room\",\n  \"action\": \"turn_on\",\n  \"parameters\": {\n    \"brightness\": 200,\n    \"color_temp\": 400\n  }\n}\n

Available actions: - turn_on - turn_off - toggle - set_value

Example with curl:

curl -X POST http://localhost:3000/api/device/control \\\n  -H \"Content-Type: application/json\" \\\n  -H \"Authorization: Bearer YOUR_JWT_TOKEN\" \\\n  -d '{\n    \"entity_id\": \"light.living_room\",\n    \"action\": \"turn_on\",\n    \"parameters\": {\n      \"brightness\": 200\n    }\n  }'\n

"},{"location":"api/core.html#natural-language-commands","title":"Natural Language Commands","text":""},{"location":"api/core.html#execute-command","title":"Execute Command","text":"

Process natural language commands.

POST /api/command\n

Request body:

{\n  \"command\": \"Turn on the living room lights and set them to 50% brightness\"\n}\n

Example usage:

curl -X POST http://localhost:3000/api/command \\\n  -H \"Content-Type: application/json\" \\\n  -H \"Authorization: Bearer YOUR_JWT_TOKEN\" \\\n  -d '{\n    \"command\": \"Turn on the living room lights and set them to 50% brightness\"\n  }'\n

Response:

{\n  \"success\": true,\n  \"actions\": [\n    {\n      \"entity_id\": \"light.living_room\",\n      \"action\": \"turn_on\",\n      \"parameters\": {\n        \"brightness\": 127\n      },\n      \"status\": \"completed\"\n    }\n  ],\n  \"message\": \"Command executed successfully\"\n}\n

"},{"location":"api/core.html#scene-management","title":"Scene Management","text":""},{"location":"api/core.html#create-scene","title":"Create Scene","text":"

Define a new scene with multiple actions.

POST /api/scene\n

Request body:

{\n  \"name\": \"Movie Night\",\n  \"description\": \"Perfect lighting for movie watching\",\n  \"actions\": [\n    {\n      \"entity_id\": \"light.living_room\",\n      \"action\": \"turn_on\",\n      \"parameters\": {\n        \"brightness\": 50,\n        \"color_temp\": 500\n      }\n    },\n    {\n      \"entity_id\": \"cover.living_room\",\n      \"action\": \"close\"\n    }\n  ]\n}\n

"},{"location":"api/core.html#activate-scene","title":"Activate Scene","text":"

Trigger a predefined scene.

POST /api/scene/{scene_name}/activate\n

Example:

curl -X POST http://localhost:3000/api/scene/movie_night/activate \\\n  -H \"Authorization: Bearer YOUR_JWT_TOKEN\"\n

"},{"location":"api/core.html#groups","title":"Groups","text":""},{"location":"api/core.html#create-device-group","title":"Create Device Group","text":"

Create a group of devices for collective control.

POST /api/group\n

Request body:

{\n  \"name\": \"Living Room\",\n  \"entities\": [\n    \"light.living_room_main\",\n    \"light.living_room_accent\",\n    \"switch.living_room_fan\"\n  ]\n}\n

"},{"location":"api/core.html#control-group","title":"Control Group","text":"

Control multiple devices in a group.

POST /api/group/{group_name}/control\n

Request body:

{\n  \"action\": \"turn_off\"\n}\n

"},{"location":"api/core.html#system-operations","title":"System Operations","text":""},{"location":"api/core.html#health-check","title":"Health Check","text":"

Check server status and connectivity.

GET /health\n

Response:

{\n  \"status\": \"healthy\",\n  \"version\": \"1.0.0\",\n  \"uptime\": 3600,\n  \"homeAssistant\": {\n    \"connected\": true,\n    \"version\": \"2024.1.0\"\n  }\n}\n

"},{"location":"api/core.html#configuration","title":"Configuration","text":"

Get current server configuration.

GET /api/config\n

Response:

{\n  \"server\": {\n    \"port\": 3000,\n    \"host\": \"0.0.0.0\",\n    \"version\": \"1.0.0\"\n  },\n  \"homeAssistant\": {\n    \"url\": \"http://homeassistant:8123\",\n    \"connected\": true\n  },\n  \"features\": {\n    \"nlp\": true,\n    \"scenes\": true,\n    \"groups\": true\n  }\n}\n

"},{"location":"api/core.html#error-handling","title":"Error Handling","text":"

All endpoints follow standard HTTP status codes and return detailed error messages:

{\n  \"error\": true,\n  \"code\": \"INVALID_ENTITY\",\n  \"message\": \"Device 'light.nonexistent' not found\",\n  \"details\": {\n    \"entity_id\": \"light.nonexistent\",\n    \"available_entities\": [\n      \"light.living_room\",\n      \"light.kitchen\"\n    ]\n  }\n}\n

Common error codes: - INVALID_ENTITY: Device not found - INVALID_ACTION: Unsupported action - INVALID_PARAMETERS: Invalid command parameters - AUTHENTICATION_ERROR: Invalid or missing token - CONNECTION_ERROR: Home Assistant connection issue

"},{"location":"api/core.html#typescript-interfaces","title":"TypeScript Interfaces","text":"
interface DeviceState {\n  entity_id: string;\n  state: string;\n  attributes: Record<string, any>;\n  last_changed: string;\n}\n\ninterface DeviceCommand {\n  entity_id: string;\n  action: 'turn_on' | 'turn_off' | 'toggle' | 'set_value';\n  parameters?: Record<string, any>;\n}\n\ninterface Scene {\n  name: string;\n  description?: string;\n  actions: DeviceCommand[];\n}\n\ninterface Group {\n  name: string;\n  entities: string[];\n}\n
"},{"location":"api/core.html#related-resources","title":"Related Resources","text":""},{"location":"api/sse.html","title":"Server-Sent Events (SSE) API \ud83d\udce1","text":"

The SSE API provides real-time updates about device states and events from your Home Assistant setup. This guide covers how to use and implement SSE connections in your applications.

"},{"location":"api/sse.html#overview","title":"Overview","text":"

Server-Sent Events (SSE) is a standard that enables servers to push real-time updates to clients over HTTP connections. MCP Server uses SSE to provide:

"},{"location":"api/sse.html#basic-usage","title":"Basic Usage","text":""},{"location":"api/sse.html#establishing-a-connection","title":"Establishing a Connection","text":"

Create an EventSource connection to receive updates:

const eventSource = new EventSource('http://localhost:3000/subscribe_events?token=YOUR_JWT_TOKEN');\n\neventSource.onmessage = (event) => {\n    const data = JSON.parse(event.data);\n    console.log('Received update:', data);\n};\n
"},{"location":"api/sse.html#connection-states","title":"Connection States","text":"

Handle different connection states:

eventSource.onopen = () => {\n    console.log('Connection established');\n};\n\neventSource.onerror = (error) => {\n    console.error('Connection error:', error);\n    // Implement reconnection logic if needed\n};\n
"},{"location":"api/sse.html#event-types","title":"Event Types","text":""},{"location":"api/sse.html#device-state-events","title":"Device State Events","text":"

Subscribe to all device state changes:

const stateEvents = new EventSource('http://localhost:3000/subscribe_events?type=state');\n\nstateEvents.onmessage = (event) => {\n    const state = JSON.parse(event.data);\n    console.log('Device state changed:', state);\n};\n

Example state event:

{\n  \"type\": \"state_changed\",\n  \"entity_id\": \"light.living_room\",\n  \"state\": \"on\",\n  \"attributes\": {\n    \"brightness\": 255,\n    \"color_temp\": 370\n  },\n  \"timestamp\": \"2024-01-20T15:30:00Z\"\n}\n

"},{"location":"api/sse.html#filtered-subscriptions","title":"Filtered Subscriptions","text":""},{"location":"api/sse.html#by-domain","title":"By Domain","text":"

Subscribe to specific device types:

// Subscribe to only light events\nconst lightEvents = new EventSource('http://localhost:3000/subscribe_events?domain=light');\n\n// Subscribe to multiple domains\nconst multiEvents = new EventSource('http://localhost:3000/subscribe_events?domain=light,switch,sensor');\n
"},{"location":"api/sse.html#by-entity-id","title":"By Entity ID","text":"

Subscribe to specific devices:

// Single entity\nconst livingRoomLight = new EventSource(\n    'http://localhost:3000/subscribe_events?entity_id=light.living_room'\n);\n\n// Multiple entities\nconst kitchenDevices = new EventSource(\n    'http://localhost:3000/subscribe_events?entity_id=light.kitchen,switch.coffee_maker'\n);\n
"},{"location":"api/sse.html#advanced-usage","title":"Advanced Usage","text":""},{"location":"api/sse.html#connection-management","title":"Connection Management","text":"

Implement robust connection handling:

class SSEManager {\n    constructor(url, options = {}) {\n        this.url = url;\n        this.options = {\n            maxRetries: 3,\n            retryDelay: 1000,\n            ...options\n        };\n        this.retryCount = 0;\n        this.connect();\n    }\n\n    connect() {\n        this.eventSource = new EventSource(this.url);\n\n        this.eventSource.onopen = () => {\n            this.retryCount = 0;\n            console.log('Connected to SSE stream');\n        };\n\n        this.eventSource.onerror = (error) => {\n            this.handleError(error);\n        };\n\n        this.eventSource.onmessage = (event) => {\n            this.handleMessage(event);\n        };\n    }\n\n    handleError(error) {\n        console.error('SSE Error:', error);\n        this.eventSource.close();\n\n        if (this.retryCount < this.options.maxRetries) {\n            this.retryCount++;\n            setTimeout(() => {\n                console.log(`Retrying connection (${this.retryCount}/${this.options.maxRetries})`);\n                this.connect();\n            }, this.options.retryDelay * this.retryCount);\n        }\n    }\n\n    handleMessage(event) {\n        try {\n            const data = JSON.parse(event.data);\n            // Handle the event data\n            console.log('Received:', data);\n        } catch (error) {\n            console.error('Error parsing SSE data:', error);\n        }\n    }\n\n    disconnect() {\n        if (this.eventSource) {\n            this.eventSource.close();\n        }\n    }\n}\n\n// Usage\nconst sseManager = new SSEManager('http://localhost:3000/subscribe_events?token=YOUR_TOKEN');\n
"},{"location":"api/sse.html#event-filtering","title":"Event Filtering","text":"

Filter events on the client side:

class EventFilter {\n    constructor(conditions) {\n        this.conditions = conditions;\n    }\n\n    matches(event) {\n        return Object.entries(this.conditions).every(([key, value]) => {\n            if (Array.isArray(value)) {\n                return value.includes(event[key]);\n            }\n            return event[key] === value;\n        });\n    }\n}\n\n// Usage\nconst filter = new EventFilter({\n    domain: ['light', 'switch'],\n    state: 'on'\n});\n\neventSource.onmessage = (event) => {\n    const data = JSON.parse(event.data);\n    if (filter.matches(data)) {\n        console.log('Matched event:', data);\n    }\n};\n
"},{"location":"api/sse.html#best-practices","title":"Best Practices","text":"
  1. Authentication
  2. Always include authentication tokens
  3. Implement token refresh mechanisms
  4. Handle authentication errors gracefully

  5. Error Handling

  6. Implement progressive retry logic
  7. Log connection issues
  8. Notify users of connection status

  9. Resource Management

  10. Close EventSource connections when not needed
  11. Limit the number of concurrent connections
  12. Use filtered subscriptions when possible

  13. Performance

  14. Process events efficiently
  15. Batch UI updates
  16. Consider debouncing frequent updates
"},{"location":"api/sse.html#common-issues","title":"Common Issues","text":""},{"location":"api/sse.html#connection-drops","title":"Connection Drops","text":"

If the connection drops, the EventSource will automatically attempt to reconnect. You can customize this behavior:

eventSource.addEventListener('error', (error) => {\n    if (eventSource.readyState === EventSource.CLOSED) {\n        // Connection closed, implement custom retry logic\n    }\n});\n
"},{"location":"api/sse.html#memory-leaks","title":"Memory Leaks","text":"

Always clean up EventSource connections:

// In a React component\nuseEffect(() => {\n    const eventSource = new EventSource('http://localhost:3000/subscribe_events');\n\n    return () => {\n        eventSource.close(); // Cleanup on unmount\n    };\n}, []);\n
"},{"location":"api/sse.html#related-resources","title":"Related Resources","text":""},{"location":"config/index.html","title":"Configuration","text":"

This section covers the configuration options available in the Home Assistant MCP Server.

"},{"location":"config/index.html#overview","title":"Overview","text":"

The MCP Server can be configured through various configuration files and environment variables. This section will guide you through the available options and their usage.

"},{"location":"config/index.html#configuration-files","title":"Configuration Files","text":"

The main configuration files are:

  1. .env - Environment variables
  2. config.yaml - Main configuration file
  3. devices.yaml - Device-specific configurations
"},{"location":"config/index.html#environment-variables","title":"Environment Variables","text":"

Key environment variables that can be set:

"},{"location":"config/index.html#next-steps","title":"Next Steps","text":""},{"location":"development/index.html","title":"Development Guide","text":"

Welcome to the development guide for the Home Assistant MCP Server. This section provides comprehensive information for developers who want to contribute to or extend the project.

"},{"location":"development/index.html#development-overview","title":"Development Overview","text":"

The MCP Server is built with modern development practices in mind, focusing on:

"},{"location":"development/index.html#getting-started","title":"Getting Started","text":"
  1. Set up your development environment
  2. Fork the repository
  3. Install dependencies
  4. Run tests
  5. Make your changes
  6. Submit a pull request
"},{"location":"development/index.html#development-topics","title":"Development Topics","text":""},{"location":"development/index.html#best-practices","title":"Best Practices","text":""},{"location":"development/index.html#development-workflow","title":"Development Workflow","text":"
  1. Create a feature branch
  2. Make your changes
  3. Run tests
  4. Update documentation
  5. Submit a pull request
  6. Address review comments
  7. Merge when approved
"},{"location":"development/index.html#next-steps","title":"Next Steps","text":""},{"location":"development/best-practices.html","title":"Development Best Practices","text":"

This guide outlines the best practices for developing tools and features for the Home Assistant MCP.

"},{"location":"development/best-practices.html#code-style","title":"Code Style","text":""},{"location":"development/best-practices.html#typescript","title":"TypeScript","text":"
  1. Use TypeScript for all new code
  2. Enable strict mode
  3. Use explicit types
  4. Avoid any type
  5. Use interfaces over types
  6. Document with JSDoc comments
/** \n * Represents a device in the system.\n * @interface\n */\ninterface Device {\n    /** Unique device identifier */\n    id: string;\n\n    /** Human-readable device name */\n    name: string;\n\n    /** Device state */\n    state: DeviceState;\n}\n
"},{"location":"development/best-practices.html#naming-conventions","title":"Naming Conventions","text":"
  1. Use PascalCase for:
  2. Classes
  3. Interfaces
  4. Types
  5. Enums

  6. Use camelCase for:

  7. Variables
  8. Functions
  9. Methods
  10. Properties

  11. Use UPPER_SNAKE_CASE for:

  12. Constants
  13. Enum values
class DeviceManager {\n    private readonly DEFAULT_TIMEOUT = 5000;\n\n    async getDeviceState(deviceId: string): Promise<DeviceState> {\n        // Implementation\n    }\n}\n
"},{"location":"development/best-practices.html#architecture","title":"Architecture","text":""},{"location":"development/best-practices.html#solid-principles","title":"SOLID Principles","text":"
  1. Single Responsibility
  2. Each class/module has one job
  3. Split complex functionality

  4. Open/Closed

  5. Open for extension
  6. Closed for modification

  7. Liskov Substitution

  8. Subtypes must be substitutable
  9. Use interfaces properly

  10. Interface Segregation

  11. Keep interfaces focused
  12. Split large interfaces

  13. Dependency Inversion

  14. Depend on abstractions
  15. Use dependency injection
"},{"location":"development/best-practices.html#example","title":"Example","text":"
// Bad\nclass DeviceManager {\n    async getState() { /* ... */ }\n    async setState() { /* ... */ }\n    async sendNotification() { /* ... */ }  // Wrong responsibility\n}\n\n// Good\nclass DeviceManager {\n    constructor(\n        private notifier: NotificationService\n    ) {}\n\n    async getState() { /* ... */ }\n    async setState() { /* ... */ }\n}\n\nclass NotificationService {\n    async send() { /* ... */ }\n}\n
"},{"location":"development/best-practices.html#error-handling","title":"Error Handling","text":""},{"location":"development/best-practices.html#best-practices","title":"Best Practices","text":"
  1. Use custom error classes
  2. Include error codes
  3. Provide meaningful messages
  4. Include error context
  5. Handle async errors
  6. Log appropriately
class DeviceError extends Error {\n    constructor(\n        message: string,\n        public code: string,\n        public context: Record<string, any>\n    ) {\n        super(message);\n        this.name = 'DeviceError';\n    }\n}\n\ntry {\n    await device.connect();\n} catch (error) {\n    throw new DeviceError(\n        'Failed to connect to device',\n        'DEVICE_CONNECTION_ERROR',\n        { deviceId: device.id, attempt: 1 }\n    );\n}\n
"},{"location":"development/best-practices.html#testing","title":"Testing","text":""},{"location":"development/best-practices.html#guidelines","title":"Guidelines","text":"
  1. Write unit tests first
  2. Use meaningful descriptions
  3. Test edge cases
  4. Mock external dependencies
  5. Keep tests focused
  6. Use test fixtures
describe('DeviceManager', () => {\n    let manager: DeviceManager;\n    let mockDevice: jest.Mocked<Device>;\n\n    beforeEach(() => {\n        mockDevice = {\n            id: 'test_device',\n            getState: jest.fn()\n        };\n        manager = new DeviceManager(mockDevice);\n    });\n\n    it('should get device state', async () => {\n        mockDevice.getState.mockResolvedValue('on');\n        const state = await manager.getDeviceState();\n        expect(state).toBe('on');\n    });\n});\n
"},{"location":"development/best-practices.html#performance","title":"Performance","text":""},{"location":"development/best-practices.html#optimization","title":"Optimization","text":"
  1. Use caching
  2. Implement pagination
  3. Optimize database queries
  4. Use connection pooling
  5. Implement rate limiting
  6. Batch operations
class DeviceCache {\n    private cache = new Map<string, CacheEntry>();\n    private readonly TTL = 60000;  // 1 minute\n\n    async getDevice(id: string): Promise<Device> {\n        const cached = this.cache.get(id);\n        if (cached && Date.now() - cached.timestamp < this.TTL) {\n            return cached.device;\n        }\n\n        const device = await this.fetchDevice(id);\n        this.cache.set(id, {\n            device,\n            timestamp: Date.now()\n        });\n\n        return device;\n    }\n}\n
"},{"location":"development/best-practices.html#security","title":"Security","text":""},{"location":"development/best-practices.html#guidelines_1","title":"Guidelines","text":"
  1. Validate all input
  2. Use parameterized queries
  3. Implement rate limiting
  4. Use proper authentication
  5. Follow OWASP guidelines
  6. Sanitize output
class InputValidator {\n    static validateDeviceId(id: string): boolean {\n        return /^[a-zA-Z0-9_-]{1,64}$/.test(id);\n    }\n\n    static sanitizeOutput(data: any): any {\n        // Implement output sanitization\n        return data;\n    }\n}\n
"},{"location":"development/best-practices.html#documentation","title":"Documentation","text":""},{"location":"development/best-practices.html#standards","title":"Standards","text":"
  1. Use JSDoc comments
  2. Document interfaces
  3. Include examples
  4. Document errors
  5. Keep docs updated
  6. Use markdown
/**\n * Manages device operations.\n * @class\n */\nclass DeviceManager {\n    /**\n     * Gets the current state of a device.\n     * @param {string} deviceId - The device identifier.\n     * @returns {Promise<DeviceState>} The current device state.\n     * @throws {DeviceError} If device is not found or unavailable.\n     * @example\n     * const state = await deviceManager.getDeviceState('living_room_light');\n     */\n    async getDeviceState(deviceId: string): Promise<DeviceState> {\n        // Implementation\n    }\n}\n
"},{"location":"development/best-practices.html#logging","title":"Logging","text":""},{"location":"development/best-practices.html#best-practices_1","title":"Best Practices","text":"
  1. Use appropriate levels
  2. Include context
  3. Structure log data
  4. Handle sensitive data
  5. Implement rotation
  6. Use correlation IDs
class Logger {\n    info(message: string, context: Record<string, any>) {\n        console.log(JSON.stringify({\n            level: 'info',\n            message,\n            context,\n            timestamp: new Date().toISOString(),\n            correlationId: context.correlationId\n        }));\n    }\n}\n
"},{"location":"development/best-practices.html#version-control","title":"Version Control","text":""},{"location":"development/best-practices.html#guidelines_2","title":"Guidelines","text":"
  1. Use meaningful commits
  2. Follow branching strategy
  3. Write good PR descriptions
  4. Review code thoroughly
  5. Keep changes focused
  6. Use conventional commits
# Good commit messages\ngit commit -m \"feat(device): add support for zigbee devices\"\ngit commit -m \"fix(api): handle timeout errors properly\"\n
"},{"location":"development/best-practices.html#see-also","title":"See Also","text":""},{"location":"development/environment.html","title":"Development Environment Setup","text":"

This guide will help you set up your development environment for the Home Assistant MCP Server.

"},{"location":"development/environment.html#prerequisites","title":"Prerequisites","text":""},{"location":"development/environment.html#required-software","title":"Required Software","text":""},{"location":"development/environment.html#system-requirements","title":"System Requirements","text":""},{"location":"development/environment.html#initial-setup","title":"Initial Setup","text":"
  1. Clone the Repository

    git clone https://github.com/jango-blockchained/homeassistant-mcp.git\ncd homeassistant-mcp\n

  2. Create Virtual Environment

    python -m venv .venv\nsource .venv/bin/activate  # Linux/macOS\n# or\n.venv\\Scripts\\activate  # Windows\n

  3. Install Dependencies

    pip install -r requirements.txt\npip install -r docs/requirements.txt  # for documentation\n

"},{"location":"development/environment.html#development-tools","title":"Development Tools","text":""},{"location":"development/environment.html#code-editor-setup","title":"Code Editor Setup","text":"

We recommend using Visual Studio Code with these extensions: - Python - Docker - YAML - ESLint - Prettier

"},{"location":"development/environment.html#vs-code-settings","title":"VS Code Settings","text":"
{\n  \"python.linting.enabled\": true,\n  \"python.linting.pylintEnabled\": true,\n  \"python.formatting.provider\": \"black\",\n  \"editor.formatOnSave\": true\n}\n
"},{"location":"development/environment.html#configuration","title":"Configuration","text":"
  1. Create Local Config

    cp config.example.yaml config.yaml\n

  2. Set Environment Variables

    cp .env.example .env\n# Edit .env with your settings\n

"},{"location":"development/environment.html#running-tests","title":"Running Tests","text":""},{"location":"development/environment.html#unit-tests","title":"Unit Tests","text":"
pytest tests/unit\n
"},{"location":"development/environment.html#integration-tests","title":"Integration Tests","text":"
pytest tests/integration\n
"},{"location":"development/environment.html#coverage-report","title":"Coverage Report","text":"
pytest --cov=src tests/\n
"},{"location":"development/environment.html#docker-development","title":"Docker Development","text":""},{"location":"development/environment.html#build-container","title":"Build Container","text":"
docker build -t mcp-server-dev -f Dockerfile.dev .\n
"},{"location":"development/environment.html#run-development-container","title":"Run Development Container","text":"
docker run -it --rm \\\n  -v $(pwd):/app \\\n  -p 8123:8123 \\\n  mcp-server-dev\n
"},{"location":"development/environment.html#database-setup","title":"Database Setup","text":""},{"location":"development/environment.html#local-development-database","title":"Local Development Database","text":"
docker run -d \\\n  -p 5432:5432 \\\n  -e POSTGRES_USER=mcp \\\n  -e POSTGRES_PASSWORD=development \\\n  -e POSTGRES_DB=mcp_dev \\\n  postgres:14\n
"},{"location":"development/environment.html#run-migrations","title":"Run Migrations","text":"
alembic upgrade head\n
"},{"location":"development/environment.html#frontend-development","title":"Frontend Development","text":"
  1. Install Node.js Dependencies

    cd frontend\nnpm install\n

  2. Start Development Server

    npm run dev\n

"},{"location":"development/environment.html#documentation","title":"Documentation","text":""},{"location":"development/environment.html#build-documentation","title":"Build Documentation","text":"
mkdocs serve\n
"},{"location":"development/environment.html#view-documentation","title":"View Documentation","text":"

Open http://localhost:8000 in your browser

"},{"location":"development/environment.html#debugging","title":"Debugging","text":""},{"location":"development/environment.html#vs-code-launch-configuration","title":"VS Code Launch Configuration","text":"
{\n  \"version\": \"0.2.0\",\n  \"configurations\": [\n    {\n      \"name\": \"Python: MCP Server\",\n      \"type\": \"python\",\n      \"request\": \"launch\",\n      \"program\": \"src/main.py\",\n      \"console\": \"integratedTerminal\"\n    }\n  ]\n}\n
"},{"location":"development/environment.html#git-hooks","title":"Git Hooks","text":""},{"location":"development/environment.html#install-pre-commit","title":"Install Pre-commit","text":"
pip install pre-commit\npre-commit install\n
"},{"location":"development/environment.html#available-hooks","title":"Available Hooks","text":""},{"location":"development/environment.html#troubleshooting","title":"Troubleshooting","text":"

Common Issues: 1. Port already in use - Check for running processes: lsof -i :8123 - Kill process if needed: kill -9 PID

  1. Database connection issues
  2. Verify PostgreSQL is running
  3. Check connection settings in .env

  4. Virtual environment problems

  5. Delete and recreate: rm -rf .venv && python -m venv .venv
  6. Reinstall dependencies
"},{"location":"development/environment.html#next-steps","title":"Next Steps","text":"
  1. Review the Architecture Guide
  2. Check Contributing Guidelines
  3. Start with Simple Issues
"},{"location":"development/interfaces.html","title":"Interface Documentation","text":"

This document describes the core interfaces used throughout the Home Assistant MCP.

"},{"location":"development/interfaces.html#core-interfaces","title":"Core Interfaces","text":""},{"location":"development/interfaces.html#tool-interface","title":"Tool Interface","text":"
interface Tool {\n    /** Unique identifier for the tool */\n    id: string;\n\n    /** Human-readable name */\n    name: string;\n\n    /** Detailed description */\n    description: string;\n\n    /** Semantic version */\n    version: string;\n\n    /** Tool category */\n    category: ToolCategory;\n\n    /** Execute tool functionality */\n    execute(params: any): Promise<ToolResult>;\n}\n
"},{"location":"development/interfaces.html#tool-result","title":"Tool Result","text":"
interface ToolResult {\n    /** Operation success status */\n    success: boolean;\n\n    /** Response data */\n    data?: any;\n\n    /** Error message if failed */\n    message?: string;\n\n    /** Error code if failed */\n    error_code?: string;\n}\n
"},{"location":"development/interfaces.html#tool-category","title":"Tool Category","text":"
enum ToolCategory {\n    DeviceManagement = 'device_management',\n    HistoryState = 'history_state',\n    Automation = 'automation',\n    AddonsPackages = 'addons_packages',\n    Notifications = 'notifications',\n    Events = 'events',\n    Utility = 'utility'\n}\n
"},{"location":"development/interfaces.html#event-interfaces","title":"Event Interfaces","text":""},{"location":"development/interfaces.html#event-subscription","title":"Event Subscription","text":"
interface EventSubscription {\n    /** Unique subscription ID */\n    id: string;\n\n    /** Event type to subscribe to */\n    event_type: string;\n\n    /** Optional entity ID filter */\n    entity_id?: string;\n\n    /** Optional domain filter */\n    domain?: string;\n\n    /** Subscription creation timestamp */\n    created_at: string;\n\n    /** Last event timestamp */\n    last_event?: string;\n}\n
"},{"location":"development/interfaces.html#event-message","title":"Event Message","text":"
interface EventMessage {\n    /** Event type */\n    event_type: string;\n\n    /** Entity ID if applicable */\n    entity_id?: string;\n\n    /** Event data */\n    data: any;\n\n    /** Event origin */\n    origin: 'LOCAL' | 'REMOTE';\n\n    /** Event timestamp */\n    time_fired: string;\n\n    /** Event context */\n    context: EventContext;\n}\n
"},{"location":"development/interfaces.html#device-interfaces","title":"Device Interfaces","text":""},{"location":"development/interfaces.html#device","title":"Device","text":"
interface Device {\n    /** Device ID */\n    id: string;\n\n    /** Device name */\n    name: string;\n\n    /** Device domain */\n    domain: string;\n\n    /** Current state */\n    state: string;\n\n    /** Device attributes */\n    attributes: Record<string, any>;\n\n    /** Device capabilities */\n    capabilities: DeviceCapabilities;\n}\n
"},{"location":"development/interfaces.html#device-capabilities","title":"Device Capabilities","text":"
interface DeviceCapabilities {\n    /** Supported features */\n    features: string[];\n\n    /** Supported commands */\n    commands: string[];\n\n    /** State attributes */\n    attributes: {\n        /** Attribute name */\n        [key: string]: {\n            /** Attribute type */\n            type: 'string' | 'number' | 'boolean' | 'object';\n            /** Attribute description */\n            description: string;\n            /** Optional value constraints */\n            constraints?: {\n                min?: number;\n                max?: number;\n                enum?: any[];\n            };\n        };\n    };\n}\n
"},{"location":"development/interfaces.html#authentication-interfaces","title":"Authentication Interfaces","text":""},{"location":"development/interfaces.html#auth-token","title":"Auth Token","text":"
interface AuthToken {\n    /** Token value */\n    token: string;\n\n    /** Token type */\n    type: 'bearer' | 'jwt';\n\n    /** Expiration timestamp */\n    expires_at: string;\n\n    /** Token refresh info */\n    refresh?: {\n        token: string;\n        expires_at: string;\n    };\n}\n
"},{"location":"development/interfaces.html#user","title":"User","text":"
interface User {\n    /** User ID */\n    id: string;\n\n    /** Username */\n    username: string;\n\n    /** User type */\n    type: 'admin' | 'user' | 'service';\n\n    /** User permissions */\n    permissions: string[];\n}\n
"},{"location":"development/interfaces.html#error-interfaces","title":"Error Interfaces","text":""},{"location":"development/interfaces.html#tool-error","title":"Tool Error","text":"
interface ToolError extends Error {\n    /** Error code */\n    code: string;\n\n    /** HTTP status code */\n    status: number;\n\n    /** Error details */\n    details?: Record<string, any>;\n}\n
"},{"location":"development/interfaces.html#validation-error","title":"Validation Error","text":"
interface ValidationError {\n    /** Error path */\n    path: string;\n\n    /** Error message */\n    message: string;\n\n    /** Error code */\n    code: string;\n}\n
"},{"location":"development/interfaces.html#configuration-interfaces","title":"Configuration Interfaces","text":""},{"location":"development/interfaces.html#tool-configuration","title":"Tool Configuration","text":"
interface ToolConfig {\n    /** Enable/disable tool */\n    enabled: boolean;\n\n    /** Tool-specific settings */\n    settings: Record<string, any>;\n\n    /** Rate limiting */\n    rate_limit?: {\n        /** Max requests */\n        max: number;\n        /** Time window in seconds */\n        window: number;\n    };\n}\n
"},{"location":"development/interfaces.html#system-configuration","title":"System Configuration","text":"
interface SystemConfig {\n    /** System name */\n    name: string;\n\n    /** Environment */\n    environment: 'development' | 'production';\n\n    /** Log level */\n    log_level: 'debug' | 'info' | 'warn' | 'error';\n\n    /** Tool configurations */\n    tools: Record<string, ToolConfig>;\n}\n
"},{"location":"development/interfaces.html#best-practices","title":"Best Practices","text":"
  1. Use TypeScript for all interfaces
  2. Include JSDoc comments
  3. Use strict typing
  4. Keep interfaces focused
  5. Use consistent naming
  6. Document constraints
  7. Version interfaces
  8. Include examples
"},{"location":"development/interfaces.html#see-also","title":"See Also","text":""},{"location":"development/test-migration-guide.html","title":"Migrating Tests from Jest to Bun","text":"

This guide provides instructions for migrating test files from Jest to Bun's test framework.

"},{"location":"development/test-migration-guide.html#table-of-contents","title":"Table of Contents","text":""},{"location":"development/test-migration-guide.html#basic-setup","title":"Basic Setup","text":"
  1. Remove Jest-related dependencies from package.json:

    {\n  \"devDependencies\": {\n    \"@jest/globals\": \"...\",\n    \"jest\": \"...\",\n    \"ts-jest\": \"...\"\n  }\n}\n

  2. Remove Jest configuration files:

  3. jest.config.js
  4. jest.setup.js

  5. Update test scripts in package.json:

    {\n  \"scripts\": {\n    \"test\": \"bun test\",\n    \"test:watch\": \"bun test --watch\",\n    \"test:coverage\": \"bun test --coverage\"\n  }\n}\n

"},{"location":"development/test-migration-guide.html#import-changes","title":"Import Changes","text":""},{"location":"development/test-migration-guide.html#before-jest","title":"Before (Jest):","text":"
import { jest, describe, it, expect, beforeEach, afterEach } from '@jest/globals';\n
"},{"location":"development/test-migration-guide.html#after-bun","title":"After (Bun):","text":"
import { describe, expect, test, beforeEach, afterEach, mock } from \"bun:test\";\nimport type { Mock } from \"bun:test\";\n

Note: it is replaced with test in Bun.

"},{"location":"development/test-migration-guide.html#api-changes","title":"API Changes","text":""},{"location":"development/test-migration-guide.html#test-structure","title":"Test Structure","text":"
// Jest\ndescribe('Suite', () => {\n  it('should do something', () => {\n    // test\n  });\n});\n\n// Bun\ndescribe('Suite', () => {\n  test('should do something', () => {\n    // test\n  });\n});\n
"},{"location":"development/test-migration-guide.html#assertions","title":"Assertions","text":"

Most Jest assertions work the same in Bun:

// These work the same in both:\nexpect(value).toBe(expected);\nexpect(value).toEqual(expected);\nexpect(value).toBeDefined();\nexpect(value).toBeUndefined();\nexpect(value).toBeTruthy();\nexpect(value).toBeFalsy();\nexpect(array).toContain(item);\nexpect(value).toBeInstanceOf(Class);\nexpect(spy).toHaveBeenCalled();\nexpect(spy).toHaveBeenCalledWith(...args);\n
"},{"location":"development/test-migration-guide.html#mocking","title":"Mocking","text":""},{"location":"development/test-migration-guide.html#function-mocking","title":"Function Mocking","text":""},{"location":"development/test-migration-guide.html#before-jest_1","title":"Before (Jest):","text":"
const mockFn = jest.fn();\nmockFn.mockImplementation(() => 'result');\nmockFn.mockResolvedValue('result');\nmockFn.mockRejectedValue(new Error());\n
"},{"location":"development/test-migration-guide.html#after-bun_1","title":"After (Bun):","text":"
const mockFn = mock(() => 'result');\nconst mockAsyncFn = mock(() => Promise.resolve('result'));\nconst mockErrorFn = mock(() => Promise.reject(new Error()));\n
"},{"location":"development/test-migration-guide.html#module-mocking","title":"Module Mocking","text":""},{"location":"development/test-migration-guide.html#before-jest_2","title":"Before (Jest):","text":"
jest.mock('module-name', () => ({\n  default: jest.fn(),\n  namedExport: jest.fn()\n}));\n
"},{"location":"development/test-migration-guide.html#after-bun_2","title":"After (Bun):","text":"
// Option 1: Using vi.mock (if available)\nvi.mock('module-name', () => ({\n  default: mock(() => {}),\n  namedExport: mock(() => {})\n}));\n\n// Option 2: Using dynamic imports\nconst mockModule = {\n  default: mock(() => {}),\n  namedExport: mock(() => {})\n};\n
"},{"location":"development/test-migration-guide.html#mock-resetclear","title":"Mock Reset/Clear","text":""},{"location":"development/test-migration-guide.html#before-jest_3","title":"Before (Jest):","text":"
jest.clearAllMocks();\nmockFn.mockClear();\njest.resetModules();\n
"},{"location":"development/test-migration-guide.html#after-bun_3","title":"After (Bun):","text":"
mockFn.mockReset();\n// or for specific calls\nmockFn.mock.calls = [];\n
"},{"location":"development/test-migration-guide.html#spy-on-methods","title":"Spy on Methods","text":""},{"location":"development/test-migration-guide.html#before-jest_4","title":"Before (Jest):","text":"
jest.spyOn(object, 'method');\n
"},{"location":"development/test-migration-guide.html#after-bun_4","title":"After (Bun):","text":"
const spy = mock(((...args) => object.method(...args)));\nobject.method = spy;\n
"},{"location":"development/test-migration-guide.html#common-patterns","title":"Common Patterns","text":""},{"location":"development/test-migration-guide.html#async-tests","title":"Async Tests","text":"
// Works the same in both Jest and Bun:\ntest('async test', async () => {\n  const result = await someAsyncFunction();\n  expect(result).toBe(expected);\n});\n
"},{"location":"development/test-migration-guide.html#setup-and-teardown","title":"Setup and Teardown","text":"
describe('Suite', () => {\n  beforeEach(() => {\n    // setup\n  });\n\n  afterEach(() => {\n    // cleanup\n  });\n\n  test('test', () => {\n    // test\n  });\n});\n
"},{"location":"development/test-migration-guide.html#mocking-fetch","title":"Mocking Fetch","text":"
// Before (Jest)\nglobal.fetch = jest.fn(() => Promise.resolve(new Response()));\n\n// After (Bun)\nconst mockFetch = mock(() => Promise.resolve(new Response()));\nglobal.fetch = mockFetch as unknown as typeof fetch;\n
"},{"location":"development/test-migration-guide.html#mocking-websocket","title":"Mocking WebSocket","text":"
// Create a MockWebSocket class implementing WebSocket interface\nclass MockWebSocket implements WebSocket {\n  public static readonly CONNECTING = 0;\n  public static readonly OPEN = 1;\n  public static readonly CLOSING = 2;\n  public static readonly CLOSED = 3;\n\n  public readyState: 0 | 1 | 2 | 3 = MockWebSocket.OPEN;\n  public addEventListener = mock(() => undefined);\n  public removeEventListener = mock(() => undefined);\n  public send = mock(() => undefined);\n  public close = mock(() => undefined);\n  // ... implement other required methods\n}\n\n// Use it in tests\nglobal.WebSocket = MockWebSocket as unknown as typeof WebSocket;\n
"},{"location":"development/test-migration-guide.html#examples","title":"Examples","text":""},{"location":"development/test-migration-guide.html#basic-test","title":"Basic Test","text":"
import { describe, expect, test } from \"bun:test\";\n\ndescribe('formatToolCall', () => {\n  test('should format an object into the correct structure', () => {\n    const testObj = { name: 'test', value: 123 };\n    const result = formatToolCall(testObj);\n\n    expect(result).toEqual({\n      content: [{\n        type: 'text',\n        text: JSON.stringify(testObj, null, 2),\n        isError: false\n      }]\n    });\n  });\n});\n
"},{"location":"development/test-migration-guide.html#async-test-with-mocking","title":"Async Test with Mocking","text":"
import { describe, expect, test, mock } from \"bun:test\";\n\ndescribe('API Client', () => {\n  test('should fetch data', async () => {\n    const mockResponse = { data: 'test' };\n    const mockFetch = mock(() => Promise.resolve(new Response(\n      JSON.stringify(mockResponse),\n      { status: 200, headers: new Headers() }\n    )));\n    global.fetch = mockFetch as unknown as typeof fetch;\n\n    const result = await apiClient.getData();\n    expect(result).toEqual(mockResponse);\n  });\n});\n
"},{"location":"development/test-migration-guide.html#complex-mocking-example","title":"Complex Mocking Example","text":"
import { describe, expect, test, mock } from \"bun:test\";\nimport type { Mock } from \"bun:test\";\n\ninterface MockServices {\n  light: {\n    turn_on: Mock<() => Promise<{ success: boolean }>>;\n    turn_off: Mock<() => Promise<{ success: boolean }>>;\n  };\n}\n\nconst mockServices: MockServices = {\n  light: {\n    turn_on: mock(() => Promise.resolve({ success: true })),\n    turn_off: mock(() => Promise.resolve({ success: true }))\n  }\n};\n\ndescribe('Home Assistant Service', () => {\n  test('should control lights', async () => {\n    const result = await mockServices.light.turn_on();\n    expect(result.success).toBe(true);\n  });\n});\n
"},{"location":"development/test-migration-guide.html#best-practices","title":"Best Practices","text":"
  1. Use TypeScript for better type safety in mocks
  2. Keep mocks as simple as possible
  3. Prefer interface-based mocks over concrete implementations
  4. Use proper type assertions when necessary
  5. Clean up mocks in afterEach blocks
  6. Use descriptive test names
  7. Group related tests using describe blocks
"},{"location":"development/test-migration-guide.html#common-issues-and-solutions","title":"Common Issues and Solutions","text":""},{"location":"development/test-migration-guide.html#issue-type-errors-with-mocks","title":"Issue: Type Errors with Mocks","text":"
// Solution: Use proper typing with Mock type\nimport type { Mock } from \"bun:test\";\nconst mockFn: Mock<() => string> = mock(() => \"result\");\n
"},{"location":"development/test-migration-guide.html#issue-global-object-mocking","title":"Issue: Global Object Mocking","text":"
// Solution: Use type assertions carefully\nglobal.someGlobal = mockImplementation as unknown as typeof someGlobal;\n
"},{"location":"development/test-migration-guide.html#issue-module-mocking","title":"Issue: Module Mocking","text":"
// Solution: Use dynamic imports or vi.mock if available\nconst mockModule = {\n  default: mock(() => mockImplementation)\n};\n
"},{"location":"development/tools.html","title":"Tool Development Guide","text":"

This guide explains how to create new tools for the Home Assistant MCP.

"},{"location":"development/tools.html#tool-structure","title":"Tool Structure","text":"

Each tool should follow this basic structure:

interface Tool {\n    id: string;\n    name: string;\n    description: string;\n    version: string;\n    category: ToolCategory;\n    execute(params: any): Promise<ToolResult>;\n}\n
"},{"location":"development/tools.html#creating-a-new-tool","title":"Creating a New Tool","text":"
  1. Create a new file in the appropriate category directory
  2. Implement the Tool interface
  3. Add API endpoints
  4. Add WebSocket handlers
  5. Add documentation
  6. Add tests
"},{"location":"development/tools.html#example-tool-implementation","title":"Example Tool Implementation","text":"
import { Tool, ToolCategory, ToolResult } from '../interfaces';\n\nexport class MyCustomTool implements Tool {\n    id = 'my_custom_tool';\n    name = 'My Custom Tool';\n    description = 'Description of what the tool does';\n    version = '1.0.0';\n    category = ToolCategory.Utility;\n\n    async execute(params: any): Promise<ToolResult> {\n        // Tool implementation\n        return {\n            success: true,\n            data: {\n                // Tool-specific response data\n            }\n        };\n    }\n}\n
"},{"location":"development/tools.html#tool-categories","title":"Tool Categories","text":""},{"location":"development/tools.html#api-integration","title":"API Integration","text":""},{"location":"development/tools.html#rest-endpoint","title":"REST Endpoint","text":"
import { Router } from 'express';\nimport { MyCustomTool } from './my-custom-tool';\n\nconst router = Router();\nconst tool = new MyCustomTool();\n\nrouter.post('/api/tools/custom', async (req, res) => {\n    try {\n        const result = await tool.execute(req.body);\n        res.json(result);\n    } catch (error) {\n        res.status(500).json({\n            success: false,\n            message: error.message\n        });\n    }\n});\n
"},{"location":"development/tools.html#websocket-handler","title":"WebSocket Handler","text":"
import { WebSocketServer } from 'ws';\nimport { MyCustomTool } from './my-custom-tool';\n\nconst tool = new MyCustomTool();\n\nwss.on('connection', (ws) => {\n    ws.on('message', async (message) => {\n        const { type, params } = JSON.parse(message);\n        if (type === 'my_custom_tool') {\n            const result = await tool.execute(params);\n            ws.send(JSON.stringify(result));\n        }\n    });\n});\n
"},{"location":"development/tools.html#error-handling","title":"Error Handling","text":"
class ToolError extends Error {\n    constructor(\n        message: string,\n        public code: string,\n        public status: number = 500\n    ) {\n        super(message);\n        this.name = 'ToolError';\n    }\n}\n\n// Usage in tool\nasync execute(params: any): Promise<ToolResult> {\n    try {\n        // Tool implementation\n    } catch (error) {\n        throw new ToolError(\n            'Operation failed',\n            'TOOL_ERROR',\n            500\n        );\n    }\n}\n
"},{"location":"development/tools.html#testing","title":"Testing","text":"
import { MyCustomTool } from './my-custom-tool';\n\ndescribe('MyCustomTool', () => {\n    let tool: MyCustomTool;\n\n    beforeEach(() => {\n        tool = new MyCustomTool();\n    });\n\n    it('should execute successfully', async () => {\n        const result = await tool.execute({\n            // Test parameters\n        });\n        expect(result.success).toBe(true);\n    });\n\n    it('should handle errors', async () => {\n        // Error test cases\n    });\n});\n
"},{"location":"development/tools.html#documentation","title":"Documentation","text":"
  1. Create tool documentation in docs/tools/category/tool-name.md
  2. Update tools/tools.md with tool reference
  3. Add tool to navigation in mkdocs.yml
"},{"location":"development/tools.html#documentation-template","title":"Documentation Template","text":"
# Tool Name\n\nDescription of the tool.\n\n## Features\n\n- Feature 1\n- Feature 2\n\n## Usage\n\n### REST API\n\n```typescript\n// API endpoints\n
"},{"location":"development/tools.html#websocket","title":"WebSocket","text":"
// WebSocket usage\n
"},{"location":"development/tools.html#examples","title":"Examples","text":""},{"location":"development/tools.html#example-1","title":"Example 1","text":"
// Usage example\n
"},{"location":"development/tools.html#response-format","title":"Response Format","text":"

{\n    \"success\": true,\n    \"data\": {\n        // Response data structure\n    }\n}\n
```

"},{"location":"development/tools.html#best-practices","title":"Best Practices","text":"
  1. Follow consistent naming conventions
  2. Implement proper error handling
  3. Add comprehensive documentation
  4. Write thorough tests
  5. Use TypeScript for type safety
  6. Follow SOLID principles
  7. Implement rate limiting
  8. Add proper logging
"},{"location":"development/tools.html#see-also","title":"See Also","text":""},{"location":"examples/index.html","title":"Example Projects \ud83d\udcda","text":"

This section contains examples and tutorials for common MCP Server integrations.

"},{"location":"examples/index.html#speech-to-text-integration","title":"Speech-to-Text Integration","text":"

Example of integrating speech recognition with MCP Server:

// From examples/speech-to-text-example.ts\n// Add example code and explanation\n
"},{"location":"examples/index.html#more-examples-coming-soon","title":"More Examples Coming Soon","text":"

...

"},{"location":"features/speech.html","title":"Speech Features","text":"

The Home Assistant MCP Server includes powerful speech processing capabilities powered by fast-whisper and custom wake word detection. This guide explains how to set up and use these features effectively.

"},{"location":"features/speech.html#overview","title":"Overview","text":"

The speech processing system consists of two main components: 1. Wake Word Detection - Listens for specific trigger phrases 2. Speech-to-Text - Transcribes spoken commands using fast-whisper

"},{"location":"features/speech.html#setup","title":"Setup","text":""},{"location":"features/speech.html#prerequisites","title":"Prerequisites","text":"
  1. Docker environment:

    docker --version  # Should be 20.10.0 or higher\n

  2. For GPU acceleration:

  3. NVIDIA GPU with CUDA support
  4. NVIDIA Container Toolkit installed
  5. NVIDIA drivers 450.80.02 or higher
"},{"location":"features/speech.html#installation","title":"Installation","text":"
  1. Enable speech features in your .env:

    ENABLE_SPEECH_FEATURES=true\nENABLE_WAKE_WORD=true\nENABLE_SPEECH_TO_TEXT=true\n

  2. Configure model settings:

    WHISPER_MODEL_PATH=/models\nWHISPER_MODEL_TYPE=base\nWHISPER_LANGUAGE=en\nWHISPER_TASK=transcribe\nWHISPER_DEVICE=cuda  # or cpu\n

  3. Start the services:

    docker-compose up -d\n

"},{"location":"features/speech.html#usage","title":"Usage","text":""},{"location":"features/speech.html#wake-word-detection","title":"Wake Word Detection","text":"

The wake word detector continuously listens for configured trigger phrases. Default wake words: - \"hey jarvis\" - \"ok google\" - \"alexa\"

Custom wake words can be configured:

WAKE_WORDS=computer,jarvis,assistant\n

When a wake word is detected: 1. The system starts recording audio 2. Audio is processed through the speech-to-text pipeline 3. The resulting command is processed by the server

"},{"location":"features/speech.html#speech-to-text","title":"Speech-to-Text","text":""},{"location":"features/speech.html#automatic-transcription","title":"Automatic Transcription","text":"

After wake word detection: 1. Audio is automatically captured (default: 5 seconds) 2. The audio is transcribed using the configured whisper model 3. The transcribed text is processed as a command

"},{"location":"features/speech.html#manual-transcription","title":"Manual Transcription","text":"

You can also manually transcribe audio using the API:

// Using the TypeScript client\nimport { SpeechService } from '@ha-mcp/client';\n\nconst speech = new SpeechService();\n\n// Transcribe from audio buffer\nconst buffer = await getAudioBuffer();\nconst text = await speech.transcribe(buffer);\n\n// Transcribe from file\nconst text = await speech.transcribeFile('command.wav');\n
// Using the REST API\nPOST /api/speech/transcribe\nContent-Type: multipart/form-data\n\nfile: <audio file>\n
"},{"location":"features/speech.html#event-handling","title":"Event Handling","text":"

The system emits various events during speech processing:

speech.on('wakeWord', (word: string) => {\n  console.log(`Wake word detected: ${word}`);\n});\n\nspeech.on('listening', () => {\n  console.log('Listening for command...');\n});\n\nspeech.on('transcribing', () => {\n  console.log('Processing speech...');\n});\n\nspeech.on('transcribed', (text: string) => {\n  console.log(`Transcribed text: ${text}`);\n});\n\nspeech.on('error', (error: Error) => {\n  console.error('Speech processing error:', error);\n});\n
"},{"location":"features/speech.html#performance-optimization","title":"Performance Optimization","text":""},{"location":"features/speech.html#model-selection","title":"Model Selection","text":"

Choose an appropriate model based on your needs:

  1. Resource-constrained environments:
  2. Use tiny.en or base.en
  3. Run on CPU if GPU unavailable
  4. Limit concurrent processing

  5. High-accuracy requirements:

  6. Use small.en or medium.en
  7. Enable GPU acceleration
  8. Increase audio quality

  9. Production environments:

  10. Use base.en or small.en
  11. Enable GPU acceleration
  12. Configure appropriate timeouts
"},{"location":"features/speech.html#gpu-acceleration","title":"GPU Acceleration","text":"

When using GPU acceleration:

  1. Monitor GPU memory usage:

    nvidia-smi -l 1\n

  2. Adjust model size if needed:

    WHISPER_MODEL_TYPE=small  # Decrease if GPU memory limited\n

  3. Configure processing device:

    WHISPER_DEVICE=cuda      # Use GPU\nWHISPER_DEVICE=cpu      # Use CPU if GPU unavailable\n

"},{"location":"features/speech.html#troubleshooting","title":"Troubleshooting","text":""},{"location":"features/speech.html#common-issues","title":"Common Issues","text":"
  1. Wake word detection not working:
  2. Check microphone permissions
  3. Adjust WAKE_WORD_SENSITIVITY
  4. Verify wake words configuration

  5. Poor transcription quality:

  6. Check audio input quality
  7. Try a larger model
  8. Verify language settings

  9. Performance issues:

  10. Monitor resource usage
  11. Consider smaller model
  12. Check GPU acceleration status
"},{"location":"features/speech.html#logging","title":"Logging","text":"

Enable debug logging for detailed information:

LOG_LEVEL=debug\n

Speech-specific logs will be tagged with [SPEECH] prefix.

"},{"location":"features/speech.html#security-considerations","title":"Security Considerations","text":"
  1. Audio Privacy:
  2. Audio is processed locally
  3. No data sent to external services
  4. Temporary files automatically cleaned

  5. Access Control:

  6. Speech endpoints require authentication
  7. Rate limiting applies to transcription
  8. Configurable command restrictions

  9. Resource Protection:

  10. Timeouts prevent hanging
  11. Memory limits enforced
  12. Graceful error handling
"},{"location":"getting-started/index.html","title":"Getting Started","text":"

Welcome to the Advanced Home Assistant MCP getting started guide. Follow these steps to begin:

  1. Installation
  2. Configuration
  3. Docker Setup
  4. Quick Start
"},{"location":"getting-started/configuration.html","title":"Configuration","text":""},{"location":"getting-started/configuration.html#basic-configuration","title":"Basic Configuration","text":""},{"location":"getting-started/configuration.html#advanced-settings","title":"Advanced Settings","text":""},{"location":"getting-started/docker.html","title":"Docker Deployment Guide \ud83d\udc33","text":"

Detailed guide for deploying MCP Server with Docker...

"},{"location":"getting-started/installation.html","title":"Installation Guide \ud83d\udee0\ufe0f","text":"

This guide covers different methods to install and set up the MCP Server for Home Assistant. Choose the installation method that best suits your needs.

"},{"location":"getting-started/installation.html#prerequisites","title":"Prerequisites","text":"

Before installing MCP Server, ensure you have:

"},{"location":"getting-started/installation.html#installation-methods","title":"Installation Methods","text":""},{"location":"getting-started/installation.html#1-smithery-installation-recommended","title":"1. \ud83d\udd27 Smithery Installation (Recommended)","text":"

The easiest way to install MCP Server is through Smithery:

"},{"location":"getting-started/installation.html#smithery-configuration","title":"Smithery Configuration","text":"

The project includes a smithery.yaml configuration:

# Add smithery.yaml contents and explanation\n
"},{"location":"getting-started/installation.html#installation-steps","title":"Installation Steps","text":"
npx -y @smithery/cli install @jango-blockchained/advanced-homeassistant-mcp --client claude\n
"},{"location":"getting-started/installation.html#2-docker-installation","title":"2. \ud83d\udc33 Docker Installation","text":"

For a containerized deployment:

# Clone the repository\ngit clone --depth 1 https://github.com/jango-blockchained/advanced-homeassistant-mcp.git\ncd advanced-homeassistant-mcp\n\n# Configure environment variables\ncp .env.example .env\n# Edit .env with your Home Assistant details:\n# - HA_URL: Your Home Assistant URL\n# - HA_TOKEN: Your Long-Lived Access Token\n# - Other configuration options\n\n# Build and start containers\ndocker compose up -d --build\n\n# View logs (optional)\ndocker compose logs -f --tail=50\n
"},{"location":"getting-started/installation.html#3-manual-installation","title":"3. \ud83d\udcbb Manual Installation","text":"

For direct installation on your system:

# Install Bun runtime\ncurl -fsSL https://bun.sh/install | bash\n\n# Clone and install\ngit clone https://github.com/jango-blockchained/advanced-homeassistant-mcp.git\ncd advanced-homeassistant-mcp\nbun install --frozen-lockfile\n\n# Configure environment\ncp .env.example .env\n# Edit .env with your configuration\n\n# Start the server\nbun run dev --watch\n
"},{"location":"getting-started/installation.html#configuration","title":"Configuration","text":""},{"location":"getting-started/installation.html#environment-variables","title":"Environment Variables","text":"

Key configuration options in your .env file:

# Home Assistant Configuration\nHA_URL=http://your-homeassistant:8123\nHA_TOKEN=your_long_lived_access_token\n\n# Server Configuration\nPORT=3000\nHOST=0.0.0.0\nNODE_ENV=production\n\n# Security Settings\nJWT_SECRET=your_secure_jwt_secret\nRATE_LIMIT=100\n
"},{"location":"getting-started/installation.html#client-integration","title":"Client Integration","text":""},{"location":"getting-started/installation.html#cursor-integration","title":"Cursor Integration","text":"

Add to .cursor/config/config.json:

{\n  \"mcpServers\": {\n    \"homeassistant-mcp\": {\n      \"command\": \"bun\",\n      \"args\": [\"run\", \"start\"],\n      \"cwd\": \"${workspaceRoot}\",\n      \"env\": {\n        \"NODE_ENV\": \"development\"\n      }\n    }\n  }\n}\n
"},{"location":"getting-started/installation.html#claude-desktop-integration","title":"Claude Desktop Integration","text":"

Add to your Claude configuration:

{\n  \"mcpServers\": {\n    \"homeassistant-mcp\": {\n      \"command\": \"bun\",\n      \"args\": [\"run\", \"start\", \"--port\", \"8080\"],\n      \"env\": {\n        \"NODE_ENV\": \"production\"\n      }\n    }\n  }\n}\n
"},{"location":"getting-started/installation.html#verification","title":"Verification","text":"

To verify your installation:

  1. Check server status:

    curl http://localhost:3000/health\n

  2. Test Home Assistant connection:

    curl http://localhost:3000/api/state\n

"},{"location":"getting-started/installation.html#troubleshooting","title":"Troubleshooting","text":"

If you encounter issues:

  1. Check the Troubleshooting Guide
  2. Verify your environment variables
  3. Check server logs:
    # For Docker installation\ndocker compose logs -f\n\n# For manual installation\nbun run dev\n
"},{"location":"getting-started/installation.html#next-steps","title":"Next Steps","text":""},{"location":"getting-started/installation.html#support","title":"Support","text":"

Need help? Check our Support Resources or open an issue.

"},{"location":"getting-started/quickstart.html","title":"Quick Start Guide \ud83d\ude80","text":"

This guide will help you get started with MCP Server after installation. We'll cover basic usage, common commands, and simple integrations.

"},{"location":"getting-started/quickstart.html#first-steps","title":"First Steps","text":""},{"location":"getting-started/quickstart.html#1-verify-connection","title":"1. Verify Connection","text":"

After installation, verify your MCP Server is running and connected to Home Assistant:

# Check server health\ncurl http://localhost:3000/health\n\n# Verify Home Assistant connection\ncurl http://localhost:3000/api/state\n
"},{"location":"getting-started/quickstart.html#2-basic-voice-commands","title":"2. Basic Voice Commands","text":"

Try these basic voice commands to test your setup:

# Example using curl for testing\ncurl -X POST http://localhost:3000/api/command \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"command\": \"Turn on the living room lights\"}'\n

Common voice commands: - \"Turn on/off [device name]\" - \"Set [device] to [value]\" - \"What's the temperature in [room]?\" - \"Is [device] on or off?\"

"},{"location":"getting-started/quickstart.html#real-world-examples","title":"Real-World Examples","text":""},{"location":"getting-started/quickstart.html#1-smart-lighting-control","title":"1. Smart Lighting Control","text":"
// Browser example using fetch\nconst response = await fetch('http://localhost:3000/api/command', {\n  method: 'POST',\n  headers: {\n    'Content-Type': 'application/json',\n  },\n  body: JSON.stringify({\n    command: 'Set living room lights to 50% brightness and warm white color'\n  })\n});\n
"},{"location":"getting-started/quickstart.html#2-real-time-updates","title":"2. Real-Time Updates","text":"

Subscribe to device state changes using Server-Sent Events (SSE):

const eventSource = new EventSource('http://localhost:3000/subscribe_events?token=YOUR_TOKEN&domain=light');\n\neventSource.onmessage = (event) => {\n    const data = JSON.parse(event.data);\n    console.log('Device state changed:', data);\n    // Update your UI here\n};\n
"},{"location":"getting-started/quickstart.html#3-scene-automation","title":"3. Scene Automation","text":"

Create and trigger scenes for different activities:

// Create a \"Movie Night\" scene\nconst createScene = async () => {\n  await fetch('http://localhost:3000/api/scene', {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application/json',\n    },\n    body: JSON.stringify({\n      name: 'Movie Night',\n      actions: [\n        { device: 'living_room_lights', action: 'dim', value: 20 },\n        { device: 'tv', action: 'on' },\n        { device: 'soundbar', action: 'on' }\n      ]\n    })\n  });\n};\n\n// Trigger the scene with voice command:\n// \"Hey MCP, activate movie night scene\"\n
"},{"location":"getting-started/quickstart.html#integration-examples","title":"Integration Examples","text":""},{"location":"getting-started/quickstart.html#1-web-dashboard-integration","title":"1. Web Dashboard Integration","text":"
// React component example\nfunction SmartHomeControl() {\n    const [devices, setDevices] = useState([]);\n\n    useEffect(() => {\n        // Subscribe to device updates\n        const events = new EventSource('http://localhost:3000/subscribe_events');\n        events.onmessage = (event) => {\n            const data = JSON.parse(event.data);\n            setDevices(currentDevices => \n                currentDevices.map(device => \n                    device.id === data.id ? {...device, ...data} : device\n                )\n            );\n        };\n\n        return () => events.close();\n    }, []);\n\n    return (\n        <div className=\"dashboard\">\n            {devices.map(device => (\n                <DeviceCard key={device.id} device={device} />\n            ))}\n        </div>\n    );\n}\n
"},{"location":"getting-started/quickstart.html#2-voice-assistant-integration","title":"2. Voice Assistant Integration","text":"
// Example using speech-to-text with MCP\nasync function handleVoiceCommand(audioBlob: Blob) {\n    // First, convert speech to text\n    const text = await speechToText(audioBlob);\n\n    // Then send command to MCP\n    const response = await fetch('http://localhost:3000/api/command', {\n        method: 'POST',\n        headers: {\n            'Content-Type': 'application/json',\n        },\n        body: JSON.stringify({ command: text })\n    });\n\n    return response.json();\n}\n
"},{"location":"getting-started/quickstart.html#best-practices","title":"Best Practices","text":"
  1. Error Handling

    try {\n    const response = await fetch('http://localhost:3000/api/command', {\n        method: 'POST',\n        headers: {\n            'Content-Type': 'application/json',\n        },\n        body: JSON.stringify({ command: 'Turn on lights' })\n    });\n\n    if (!response.ok) {\n        throw new Error(`HTTP error! status: ${response.status}`);\n    }\n\n    const data = await response.json();\n} catch (error) {\n    console.error('Error:', error);\n    // Handle error appropriately\n}\n

  2. Connection Management

    class MCPConnection {\n    constructor() {\n        this.eventSource = null;\n        this.reconnectAttempts = 0;\n    }\n\n    connect() {\n        this.eventSource = new EventSource('http://localhost:3000/subscribe_events');\n        this.eventSource.onerror = this.handleError.bind(this);\n    }\n\n    handleError() {\n        if (this.reconnectAttempts < 3) {\n            setTimeout(() => {\n                this.reconnectAttempts++;\n                this.connect();\n            }, 1000 * this.reconnectAttempts);\n        }\n    }\n}\n

"},{"location":"getting-started/quickstart.html#next-steps","title":"Next Steps","text":""},{"location":"getting-started/quickstart.html#troubleshooting","title":"Troubleshooting","text":"

If you encounter issues: - Verify your authentication token - Check server logs for errors - Ensure Home Assistant is accessible - Review the Troubleshooting Guide

Need more help? Visit our Support Resources.

"},{"location":"tools/index.html","title":"Tools Overview","text":"

The Home Assistant MCP Server provides a variety of tools to help you manage and interact with your home automation system.

"},{"location":"tools/index.html#available-tools","title":"Available Tools","text":""},{"location":"tools/index.html#device-management","title":"Device Management","text":""},{"location":"tools/index.html#history-state","title":"History & State","text":""},{"location":"tools/index.html#automation","title":"Automation","text":""},{"location":"tools/index.html#add-ons-packages","title":"Add-ons & Packages","text":""},{"location":"tools/index.html#notifications","title":"Notifications","text":""},{"location":"tools/index.html#events","title":"Events","text":""},{"location":"tools/index.html#getting-started","title":"Getting Started","text":"

To get started with these tools:

  1. Ensure you have the MCP Server properly installed and configured
  2. Check the specific tool documentation for detailed usage instructions
  3. Use the API endpoints or command-line interface as needed
"},{"location":"tools/index.html#next-steps","title":"Next Steps","text":""},{"location":"tools/addons-packages/addon.html","title":"Add-on Management Tool","text":"

The Add-on Management tool provides functionality to manage Home Assistant add-ons through the MCP interface.

"},{"location":"tools/addons-packages/addon.html#features","title":"Features","text":""},{"location":"tools/addons-packages/addon.html#usage","title":"Usage","text":""},{"location":"tools/addons-packages/addon.html#rest-api","title":"REST API","text":"
GET /api/addons\nGET /api/addons/{addon_slug}\nPOST /api/addons/{addon_slug}/install\nPOST /api/addons/{addon_slug}/uninstall\nPOST /api/addons/{addon_slug}/start\nPOST /api/addons/{addon_slug}/stop\nPOST /api/addons/{addon_slug}/restart\nGET /api/addons/{addon_slug}/logs\nPUT /api/addons/{addon_slug}/config\nGET /api/addons/{addon_slug}/stats\n
"},{"location":"tools/addons-packages/addon.html#websocket","title":"WebSocket","text":"
// List add-ons\n{\n    \"type\": \"get_addons\"\n}\n\n// Get add-on info\n{\n    \"type\": \"get_addon_info\",\n    \"addon_slug\": \"required_addon_slug\"\n}\n\n// Install add-on\n{\n    \"type\": \"install_addon\",\n    \"addon_slug\": \"required_addon_slug\",\n    \"version\": \"optional_version\"\n}\n\n// Control add-on\n{\n    \"type\": \"control_addon\",\n    \"addon_slug\": \"required_addon_slug\",\n    \"action\": \"start|stop|restart\"\n}\n
"},{"location":"tools/addons-packages/addon.html#examples","title":"Examples","text":""},{"location":"tools/addons-packages/addon.html#list-all-add-ons","title":"List All Add-ons","text":"
const response = await fetch('http://your-ha-mcp/api/addons', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst addons = await response.json();\n
"},{"location":"tools/addons-packages/addon.html#install-add-on","title":"Install Add-on","text":"
const response = await fetch('http://your-ha-mcp/api/addons/mosquitto/install', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"version\": \"latest\"\n    })\n});\n
"},{"location":"tools/addons-packages/addon.html#configure-add-on","title":"Configure Add-on","text":"
const response = await fetch('http://your-ha-mcp/api/addons/mosquitto/config', {\n    method: 'PUT',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"logins\": [\n            {\n                \"username\": \"mqtt_user\",\n                \"password\": \"mqtt_password\"\n            }\n        ],\n        \"customize\": {\n            \"active\": true,\n            \"folder\": \"mosquitto\"\n        }\n    })\n});\n
"},{"location":"tools/addons-packages/addon.html#response-format","title":"Response Format","text":""},{"location":"tools/addons-packages/addon.html#add-on-list-response","title":"Add-on List Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"addons\": [\n            {\n                \"slug\": \"addon_slug\",\n                \"name\": \"Add-on Name\",\n                \"version\": \"1.0.0\",\n                \"state\": \"started\",\n                \"repository\": \"core\",\n                \"installed\": true,\n                \"update_available\": false\n            }\n        ]\n    }\n}\n
"},{"location":"tools/addons-packages/addon.html#add-on-info-response","title":"Add-on Info Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"addon\": {\n            \"slug\": \"addon_slug\",\n            \"name\": \"Add-on Name\",\n            \"version\": \"1.0.0\",\n            \"description\": \"Add-on description\",\n            \"long_description\": \"Detailed description\",\n            \"repository\": \"core\",\n            \"installed\": true,\n            \"state\": \"started\",\n            \"webui\": \"http://[HOST]:[PORT:80]\",\n            \"boot\": \"auto\",\n            \"options\": {\n                // Add-on specific options\n            },\n            \"schema\": {\n                // Add-on options schema\n            },\n            \"ports\": {\n                \"80/tcp\": 8080\n            },\n            \"ingress\": true,\n            \"ingress_port\": 8099\n        }\n    }\n}\n
"},{"location":"tools/addons-packages/addon.html#add-on-stats-response","title":"Add-on Stats Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"stats\": {\n            \"cpu_percent\": 2.5,\n            \"memory_usage\": 128974848,\n            \"memory_limit\": 536870912,\n            \"network_rx\": 1234,\n            \"network_tx\": 5678,\n            \"blk_read\": 12345,\n            \"blk_write\": 67890\n        }\n    }\n}\n
"},{"location":"tools/addons-packages/addon.html#error-handling","title":"Error Handling","text":""},{"location":"tools/addons-packages/addon.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/addons-packages/addon.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/addons-packages/addon.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/addons-packages/addon.html#best-practices","title":"Best Practices","text":"
  1. Always check add-on compatibility
  2. Back up configurations before updates
  3. Monitor resource usage
  4. Use appropriate update strategies
  5. Implement proper error handling
  6. Test configurations in safe environment
  7. Handle rate limiting gracefully
  8. Keep add-ons updated
"},{"location":"tools/addons-packages/addon.html#add-on-security","title":"Add-on Security","text":""},{"location":"tools/addons-packages/addon.html#see-also","title":"See Also","text":""},{"location":"tools/addons-packages/package.html","title":"Package Management Tool","text":"

The Package Management tool provides functionality to manage Home Assistant Community Store (HACS) packages through the MCP interface.

"},{"location":"tools/addons-packages/package.html#features","title":"Features","text":""},{"location":"tools/addons-packages/package.html#usage","title":"Usage","text":""},{"location":"tools/addons-packages/package.html#rest-api","title":"REST API","text":"
GET /api/packages\nGET /api/packages/{package_id}\nPOST /api/packages/{package_id}/install\nPOST /api/packages/{package_id}/uninstall\nPOST /api/packages/{package_id}/update\nGET /api/packages/search\nGET /api/packages/categories\nGET /api/packages/repositories\n
"},{"location":"tools/addons-packages/package.html#websocket","title":"WebSocket","text":"
// List packages\n{\n    \"type\": \"get_packages\",\n    \"category\": \"optional_category\"\n}\n\n// Search packages\n{\n    \"type\": \"search_packages\",\n    \"query\": \"search_query\",\n    \"category\": \"optional_category\"\n}\n\n// Install package\n{\n    \"type\": \"install_package\",\n    \"package_id\": \"required_package_id\",\n    \"version\": \"optional_version\"\n}\n
"},{"location":"tools/addons-packages/package.html#package-categories","title":"Package Categories","text":""},{"location":"tools/addons-packages/package.html#examples","title":"Examples","text":""},{"location":"tools/addons-packages/package.html#list-all-packages","title":"List All Packages","text":"
const response = await fetch('http://your-ha-mcp/api/packages', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst packages = await response.json();\n
"},{"location":"tools/addons-packages/package.html#search-packages","title":"Search Packages","text":"
const response = await fetch('http://your-ha-mcp/api/packages/search?q=weather&category=integrations', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst searchResults = await response.json();\n
"},{"location":"tools/addons-packages/package.html#install-package","title":"Install Package","text":"
const response = await fetch('http://your-ha-mcp/api/packages/custom-weather-card/install', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"version\": \"latest\"\n    })\n});\n
"},{"location":"tools/addons-packages/package.html#response-format","title":"Response Format","text":""},{"location":"tools/addons-packages/package.html#package-list-response","title":"Package List Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"packages\": [\n            {\n                \"id\": \"package_id\",\n                \"name\": \"Package Name\",\n                \"category\": \"integrations\",\n                \"description\": \"Package description\",\n                \"version\": \"1.0.0\",\n                \"installed\": true,\n                \"update_available\": false,\n                \"stars\": 150,\n                \"downloads\": 10000\n            }\n        ]\n    }\n}\n
"},{"location":"tools/addons-packages/package.html#package-info-response","title":"Package Info Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"package\": {\n            \"id\": \"package_id\",\n            \"name\": \"Package Name\",\n            \"category\": \"integrations\",\n            \"description\": \"Package description\",\n            \"long_description\": \"Detailed description\",\n            \"version\": \"1.0.0\",\n            \"installed_version\": \"0.9.0\",\n            \"available_version\": \"1.0.0\",\n            \"installed\": true,\n            \"update_available\": true,\n            \"stars\": 150,\n            \"downloads\": 10000,\n            \"repository\": \"https://github.com/author/repo\",\n            \"author\": {\n                \"name\": \"Author Name\",\n                \"url\": \"https://github.com/author\"\n            },\n            \"documentation\": \"https://github.com/author/repo/wiki\",\n            \"dependencies\": [\n                \"dependency1\",\n                \"dependency2\"\n            ]\n        }\n    }\n}\n
"},{"location":"tools/addons-packages/package.html#search-response","title":"Search Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"results\": [\n            {\n                \"id\": \"package_id\",\n                \"name\": \"Package Name\",\n                \"category\": \"integrations\",\n                \"description\": \"Package description\",\n                \"version\": \"1.0.0\",\n                \"score\": 0.95\n            }\n        ],\n        \"total\": 42\n    }\n}\n
"},{"location":"tools/addons-packages/package.html#error-handling","title":"Error Handling","text":""},{"location":"tools/addons-packages/package.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/addons-packages/package.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/addons-packages/package.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/addons-packages/package.html#best-practices","title":"Best Practices","text":"
  1. Check package compatibility
  2. Review package documentation
  3. Verify package dependencies
  4. Back up before updates
  5. Test in safe environment
  6. Monitor resource usage
  7. Keep packages updated
  8. Handle rate limiting gracefully
"},{"location":"tools/addons-packages/package.html#package-security","title":"Package Security","text":""},{"location":"tools/addons-packages/package.html#see-also","title":"See Also","text":""},{"location":"tools/automation/automation-config.html","title":"Automation Configuration Tool","text":"

The Automation Configuration tool provides functionality to create, update, and manage Home Assistant automation configurations.

"},{"location":"tools/automation/automation-config.html#features","title":"Features","text":""},{"location":"tools/automation/automation-config.html#usage","title":"Usage","text":""},{"location":"tools/automation/automation-config.html#rest-api","title":"REST API","text":"
POST /api/automations\nPUT /api/automations/{automation_id}\nDELETE /api/automations/{automation_id}\nPOST /api/automations/{automation_id}/duplicate\nPOST /api/automations/validate\n
"},{"location":"tools/automation/automation-config.html#websocket","title":"WebSocket","text":"
// Create automation\n{\n    \"type\": \"create_automation\",\n    \"automation\": {\n        // Automation configuration\n    }\n}\n\n// Update automation\n{\n    \"type\": \"update_automation\",\n    \"automation_id\": \"required_automation_id\",\n    \"automation\": {\n        // Updated configuration\n    }\n}\n\n// Delete automation\n{\n    \"type\": \"delete_automation\",\n    \"automation_id\": \"required_automation_id\"\n}\n
"},{"location":"tools/automation/automation-config.html#automation-configuration","title":"Automation Configuration","text":""},{"location":"tools/automation/automation-config.html#basic-structure","title":"Basic Structure","text":"
{\n    \"id\": \"morning_routine\",\n    \"alias\": \"Morning Routine\",\n    \"description\": \"Turn on lights and adjust temperature in the morning\",\n    \"trigger\": [\n        {\n            \"platform\": \"time\",\n            \"at\": \"07:00:00\"\n        }\n    ],\n    \"condition\": [\n        {\n            \"condition\": \"time\",\n            \"weekday\": [\"mon\", \"tue\", \"wed\", \"thu\", \"fri\"]\n        }\n    ],\n    \"action\": [\n        {\n            \"service\": \"light.turn_on\",\n            \"target\": {\n                \"entity_id\": \"light.bedroom\"\n            },\n            \"data\": {\n                \"brightness\": 255,\n                \"transition\": 300\n            }\n        }\n    ],\n    \"mode\": \"single\"\n}\n
"},{"location":"tools/automation/automation-config.html#trigger-types","title":"Trigger Types","text":"
// Time-based trigger\n{\n    \"platform\": \"time\",\n    \"at\": \"07:00:00\"\n}\n\n// State-based trigger\n{\n    \"platform\": \"state\",\n    \"entity_id\": \"binary_sensor.motion\",\n    \"to\": \"on\"\n}\n\n// Event-based trigger\n{\n    \"platform\": \"event\",\n    \"event_type\": \"custom_event\"\n}\n\n// Numeric state trigger\n{\n    \"platform\": \"numeric_state\",\n    \"entity_id\": \"sensor.temperature\",\n    \"above\": 25\n}\n
"},{"location":"tools/automation/automation-config.html#condition-types","title":"Condition Types","text":"
// Time condition\n{\n    \"condition\": \"time\",\n    \"after\": \"07:00:00\",\n    \"before\": \"22:00:00\"\n}\n\n// State condition\n{\n    \"condition\": \"state\",\n    \"entity_id\": \"device_tracker.phone\",\n    \"state\": \"home\"\n}\n\n// Numeric state condition\n{\n    \"condition\": \"numeric_state\",\n    \"entity_id\": \"sensor.temperature\",\n    \"below\": 25\n}\n
"},{"location":"tools/automation/automation-config.html#action-types","title":"Action Types","text":"
// Service call action\n{\n    \"service\": \"light.turn_on\",\n    \"target\": {\n        \"entity_id\": \"light.bedroom\"\n    }\n}\n\n// Delay action\n{\n    \"delay\": \"00:00:30\"\n}\n\n// Scene activation\n{\n    \"scene\": \"scene.evening_mode\"\n}\n\n// Conditional action\n{\n    \"choose\": [\n        {\n            \"conditions\": [\n                {\n                    \"condition\": \"state\",\n                    \"entity_id\": \"sun.sun\",\n                    \"state\": \"below_horizon\"\n                }\n            ],\n            \"sequence\": [\n                {\n                    \"service\": \"light.turn_on\",\n                    \"target\": {\n                        \"entity_id\": \"light.living_room\"\n                    }\n                }\n            ]\n        }\n    ]\n}\n
"},{"location":"tools/automation/automation-config.html#examples","title":"Examples","text":""},{"location":"tools/automation/automation-config.html#create-new-automation","title":"Create New Automation","text":"
const response = await fetch('http://your-ha-mcp/api/automations', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"alias\": \"Morning Routine\",\n        \"description\": \"Turn on lights in the morning\",\n        \"trigger\": [\n            {\n                \"platform\": \"time\",\n                \"at\": \"07:00:00\"\n            }\n        ],\n        \"action\": [\n            {\n                \"service\": \"light.turn_on\",\n                \"target\": {\n                    \"entity_id\": \"light.bedroom\"\n                }\n            }\n        ]\n    })\n});\n
"},{"location":"tools/automation/automation-config.html#update-existing-automation","title":"Update Existing Automation","text":"
const response = await fetch('http://your-ha-mcp/api/automations/morning_routine', {\n    method: 'PUT',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"alias\": \"Morning Routine\",\n        \"trigger\": [\n            {\n                \"platform\": \"time\",\n                \"at\": \"07:30:00\"  // Updated time\n            }\n        ],\n        \"action\": [\n            {\n                \"service\": \"light.turn_on\",\n                \"target\": {\n                    \"entity_id\": \"light.bedroom\"\n                }\n            }\n        ]\n    })\n});\n
"},{"location":"tools/automation/automation-config.html#response-format","title":"Response Format","text":""},{"location":"tools/automation/automation-config.html#success-response","title":"Success Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"automation\": {\n            \"id\": \"created_automation_id\",\n            // Full automation configuration\n        }\n    }\n}\n
"},{"location":"tools/automation/automation-config.html#validation-response","title":"Validation Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"valid\": true,\n        \"warnings\": [\n            \"No conditions specified\"\n        ]\n    }\n}\n
"},{"location":"tools/automation/automation-config.html#error-handling","title":"Error Handling","text":""},{"location":"tools/automation/automation-config.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/automation/automation-config.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\",\n    \"validation_errors\": [\n        {\n            \"path\": \"trigger[0].platform\",\n            \"message\": \"Invalid trigger platform\"\n        }\n    ]\n}\n
"},{"location":"tools/automation/automation-config.html#best-practices","title":"Best Practices","text":"
  1. Always validate configurations before saving
  2. Use descriptive aliases and descriptions
  3. Group related automations
  4. Test automations in a safe environment
  5. Document automation dependencies
  6. Use variables for reusable values
  7. Implement proper error handling
  8. Consider automation modes carefully
"},{"location":"tools/automation/automation-config.html#see-also","title":"See Also","text":""},{"location":"tools/automation/automation.html","title":"Automation Management Tool","text":"

The Automation Management tool provides functionality to manage and control Home Assistant automations.

"},{"location":"tools/automation/automation.html#features","title":"Features","text":""},{"location":"tools/automation/automation.html#usage","title":"Usage","text":""},{"location":"tools/automation/automation.html#rest-api","title":"REST API","text":"
GET /api/automations\nGET /api/automations/{automation_id}\nPOST /api/automations/{automation_id}/toggle\nPOST /api/automations/{automation_id}/trigger\nGET /api/automations/{automation_id}/history\n
"},{"location":"tools/automation/automation.html#websocket","title":"WebSocket","text":"
// List automations\n{\n    \"type\": \"get_automations\"\n}\n\n// Toggle automation\n{\n    \"type\": \"toggle_automation\",\n    \"automation_id\": \"required_automation_id\"\n}\n\n// Trigger automation\n{\n    \"type\": \"trigger_automation\",\n    \"automation_id\": \"required_automation_id\",\n    \"variables\": {\n        // Optional variables\n    }\n}\n
"},{"location":"tools/automation/automation.html#examples","title":"Examples","text":""},{"location":"tools/automation/automation.html#list-all-automations","title":"List All Automations","text":"
const response = await fetch('http://your-ha-mcp/api/automations', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst automations = await response.json();\n
"},{"location":"tools/automation/automation.html#toggle-automation-state","title":"Toggle Automation State","text":"
const response = await fetch('http://your-ha-mcp/api/automations/morning_routine/toggle', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\n
"},{"location":"tools/automation/automation.html#trigger-automation-manually","title":"Trigger Automation Manually","text":"
const response = await fetch('http://your-ha-mcp/api/automations/morning_routine/trigger', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"variables\": {\n            \"brightness\": 100,\n            \"temperature\": 22\n        }\n    })\n});\n
"},{"location":"tools/automation/automation.html#response-format","title":"Response Format","text":""},{"location":"tools/automation/automation.html#automation-list-response","title":"Automation List Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"automations\": [\n            {\n                \"id\": \"automation_id\",\n                \"name\": \"Automation Name\",\n                \"enabled\": true,\n                \"last_triggered\": \"2024-02-05T12:00:00Z\",\n                \"trigger_count\": 42\n            }\n        ]\n    }\n}\n
"},{"location":"tools/automation/automation.html#automation-details-response","title":"Automation Details Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"automation\": {\n            \"id\": \"automation_id\",\n            \"name\": \"Automation Name\",\n            \"enabled\": true,\n            \"triggers\": [\n                {\n                    \"platform\": \"time\",\n                    \"at\": \"07:00:00\"\n                }\n            ],\n            \"conditions\": [],\n            \"actions\": [\n                {\n                    \"service\": \"light.turn_on\",\n                    \"target\": {\n                        \"entity_id\": \"light.bedroom\"\n                    }\n                }\n            ],\n            \"mode\": \"single\",\n            \"max\": 10,\n            \"last_triggered\": \"2024-02-05T12:00:00Z\",\n            \"trigger_count\": 42\n        }\n    }\n}\n
"},{"location":"tools/automation/automation.html#automation-history-response","title":"Automation History Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"history\": [\n            {\n                \"timestamp\": \"2024-02-05T12:00:00Z\",\n                \"trigger\": {\n                    \"platform\": \"time\",\n                    \"at\": \"07:00:00\"\n                },\n                \"context\": {\n                    \"user_id\": \"user_123\",\n                    \"variables\": {}\n                },\n                \"result\": \"success\"\n            }\n        ]\n    }\n}\n
"},{"location":"tools/automation/automation.html#error-handling","title":"Error Handling","text":""},{"location":"tools/automation/automation.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/automation/automation.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/automation/automation.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/automation/automation.html#best-practices","title":"Best Practices","text":"
  1. Monitor automation execution history
  2. Use descriptive automation names
  3. Implement proper error handling
  4. Cache automation configurations when possible
  5. Handle rate limiting gracefully
  6. Test automations before enabling
  7. Use variables for flexible automation behavior
"},{"location":"tools/automation/automation.html#see-also","title":"See Also","text":""},{"location":"tools/device-management/control.html","title":"Device Control Tool","text":"

The Device Control tool provides functionality to control various types of devices in your Home Assistant instance.

"},{"location":"tools/device-management/control.html#supported-device-types","title":"Supported Device Types","text":""},{"location":"tools/device-management/control.html#usage","title":"Usage","text":""},{"location":"tools/device-management/control.html#rest-api","title":"REST API","text":"
POST /api/devices/{device_id}/control\n
"},{"location":"tools/device-management/control.html#websocket","title":"WebSocket","text":"
{\n    \"type\": \"control_device\",\n    \"device_id\": \"required_device_id\",\n    \"domain\": \"required_domain\",\n    \"service\": \"required_service\",\n    \"data\": {\n        // Service-specific data\n    }\n}\n
"},{"location":"tools/device-management/control.html#domain-specific-commands","title":"Domain-Specific Commands","text":""},{"location":"tools/device-management/control.html#lights","title":"Lights","text":"
// Turn on/off\nPOST /api/devices/light/{device_id}/control\n{\n    \"service\": \"turn_on\",  // or \"turn_off\"\n}\n\n// Set brightness\n{\n    \"service\": \"turn_on\",\n    \"data\": {\n        \"brightness\": 255  // 0-255\n    }\n}\n\n// Set color\n{\n    \"service\": \"turn_on\",\n    \"data\": {\n        \"rgb_color\": [255, 0, 0]  // Red\n    }\n}\n
"},{"location":"tools/device-management/control.html#covers","title":"Covers","text":"
// Open/close\nPOST /api/devices/cover/{device_id}/control\n{\n    \"service\": \"open_cover\",  // or \"close_cover\"\n}\n\n// Set position\n{\n    \"service\": \"set_cover_position\",\n    \"data\": {\n        \"position\": 50  // 0-100\n    }\n}\n
"},{"location":"tools/device-management/control.html#climate","title":"Climate","text":"
// Set temperature\nPOST /api/devices/climate/{device_id}/control\n{\n    \"service\": \"set_temperature\",\n    \"data\": {\n        \"temperature\": 22.5\n    }\n}\n\n// Set mode\n{\n    \"service\": \"set_hvac_mode\",\n    \"data\": {\n        \"hvac_mode\": \"heat\"  // heat, cool, auto, off\n    }\n}\n
"},{"location":"tools/device-management/control.html#examples","title":"Examples","text":""},{"location":"tools/device-management/control.html#control-light-brightness","title":"Control Light Brightness","text":"
const response = await fetch('http://your-ha-mcp/api/devices/light/living_room/control', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"service\": \"turn_on\",\n        \"data\": {\n            \"brightness\": 128\n        }\n    })\n});\n
"},{"location":"tools/device-management/control.html#control-cover-position","title":"Control Cover Position","text":"
const response = await fetch('http://your-ha-mcp/api/devices/cover/bedroom/control', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"service\": \"set_cover_position\",\n        \"data\": {\n            \"position\": 75\n        }\n    })\n});\n
"},{"location":"tools/device-management/control.html#response-format","title":"Response Format","text":""},{"location":"tools/device-management/control.html#success-response","title":"Success Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"state\": \"on\",\n        \"attributes\": {\n            // Updated device attributes\n        }\n    }\n}\n
"},{"location":"tools/device-management/control.html#error-response","title":"Error Response","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/device-management/control.html#error-handling","title":"Error Handling","text":""},{"location":"tools/device-management/control.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/device-management/control.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/device-management/control.html#best-practices","title":"Best Practices","text":"
  1. Validate device availability before sending commands
  2. Implement proper error handling
  3. Use appropriate retry strategies for failed commands
  4. Cache device capabilities when possible
  5. Handle rate limiting gracefully
"},{"location":"tools/device-management/control.html#see-also","title":"See Also","text":""},{"location":"tools/device-management/list-devices.html","title":"List Devices Tool","text":"

The List Devices tool provides functionality to retrieve and manage device information from your Home Assistant instance.

"},{"location":"tools/device-management/list-devices.html#features","title":"Features","text":""},{"location":"tools/device-management/list-devices.html#usage","title":"Usage","text":""},{"location":"tools/device-management/list-devices.html#rest-api","title":"REST API","text":"
GET /api/devices\nGET /api/devices/{domain}\nGET /api/devices/{device_id}/state\n
"},{"location":"tools/device-management/list-devices.html#websocket","title":"WebSocket","text":"
// List all devices\n{\n    \"type\": \"list_devices\",\n    \"domain\": \"optional_domain\"\n}\n\n// Get device state\n{\n    \"type\": \"get_device_state\",\n    \"device_id\": \"required_device_id\"\n}\n
"},{"location":"tools/device-management/list-devices.html#examples","title":"Examples","text":""},{"location":"tools/device-management/list-devices.html#list-all-devices","title":"List All Devices","text":"
const response = await fetch('http://your-ha-mcp/api/devices', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst devices = await response.json();\n
"},{"location":"tools/device-management/list-devices.html#get-devices-by-domain","title":"Get Devices by Domain","text":"
const response = await fetch('http://your-ha-mcp/api/devices/light', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst lightDevices = await response.json();\n
"},{"location":"tools/device-management/list-devices.html#response-format","title":"Response Format","text":""},{"location":"tools/device-management/list-devices.html#device-list-response","title":"Device List Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"devices\": [\n            {\n                \"id\": \"device_id\",\n                \"name\": \"Device Name\",\n                \"domain\": \"light\",\n                \"state\": \"on\",\n                \"attributes\": {\n                    \"brightness\": 255,\n                    \"color_temp\": 370\n                }\n            }\n        ]\n    }\n}\n
"},{"location":"tools/device-management/list-devices.html#device-state-response","title":"Device State Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"state\": \"on\",\n        \"attributes\": {\n            \"brightness\": 255,\n            \"color_temp\": 370\n        },\n        \"last_changed\": \"2024-02-05T12:00:00Z\",\n        \"last_updated\": \"2024-02-05T12:00:00Z\"\n    }\n}\n
"},{"location":"tools/device-management/list-devices.html#error-handling","title":"Error Handling","text":""},{"location":"tools/device-management/list-devices.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/device-management/list-devices.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/device-management/list-devices.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/device-management/list-devices.html#best-practices","title":"Best Practices","text":"
  1. Cache device lists when possible
  2. Use domain filtering for better performance
  3. Implement proper error handling
  4. Handle rate limiting gracefully
"},{"location":"tools/device-management/list-devices.html#see-also","title":"See Also","text":""},{"location":"tools/events/sse-stats.html","title":"SSE Statistics Tool","text":"

The SSE Statistics tool provides functionality to monitor and analyze Server-Sent Events (SSE) connections and performance in your Home Assistant MCP instance.

"},{"location":"tools/events/sse-stats.html#features","title":"Features","text":""},{"location":"tools/events/sse-stats.html#usage","title":"Usage","text":""},{"location":"tools/events/sse-stats.html#rest-api","title":"REST API","text":"
GET /api/sse/stats\nGET /api/sse/connections\nGET /api/sse/connections/{connection_id}\nGET /api/sse/metrics\nGET /api/sse/history\n
"},{"location":"tools/events/sse-stats.html#websocket","title":"WebSocket","text":"
// Get SSE stats\n{\n    \"type\": \"get_sse_stats\"\n}\n\n// Get connection details\n{\n    \"type\": \"get_sse_connection\",\n    \"connection_id\": \"required_connection_id\"\n}\n\n// Get performance metrics\n{\n    \"type\": \"get_sse_metrics\",\n    \"period\": \"1h|24h|7d|30d\"\n}\n
"},{"location":"tools/events/sse-stats.html#examples","title":"Examples","text":""},{"location":"tools/events/sse-stats.html#get-current-statistics","title":"Get Current Statistics","text":"
const response = await fetch('http://your-ha-mcp/api/sse/stats', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst stats = await response.json();\n
"},{"location":"tools/events/sse-stats.html#get-connection-details","title":"Get Connection Details","text":"
const response = await fetch('http://your-ha-mcp/api/sse/connections/conn_123', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst connection = await response.json();\n
"},{"location":"tools/events/sse-stats.html#get-performance-metrics","title":"Get Performance Metrics","text":"
const response = await fetch('http://your-ha-mcp/api/sse/metrics?period=24h', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst metrics = await response.json();\n
"},{"location":"tools/events/sse-stats.html#response-format","title":"Response Format","text":""},{"location":"tools/events/sse-stats.html#statistics-response","title":"Statistics Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"active_connections\": 42,\n        \"total_events_sent\": 12345,\n        \"events_per_second\": 5.2,\n        \"memory_usage\": 128974848,\n        \"cpu_usage\": 2.5,\n        \"uptime\": \"PT24H\",\n        \"event_backlog\": 0\n    }\n}\n
"},{"location":"tools/events/sse-stats.html#connection-details-response","title":"Connection Details Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"connection\": {\n            \"id\": \"conn_123\",\n            \"client_id\": \"client_456\",\n            \"user_id\": \"user_789\",\n            \"connected_at\": \"2024-02-05T12:00:00Z\",\n            \"last_event_at\": \"2024-02-05T12:05:00Z\",\n            \"events_sent\": 150,\n            \"subscriptions\": [\n                {\n                    \"event_type\": \"state_changed\",\n                    \"entity_id\": \"light.living_room\"\n                }\n            ],\n            \"state\": \"active\",\n            \"ip_address\": \"192.168.1.100\",\n            \"user_agent\": \"Mozilla/5.0 ...\"\n        }\n    }\n}\n
"},{"location":"tools/events/sse-stats.html#performance-metrics-response","title":"Performance Metrics Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"metrics\": {\n            \"connections\": {\n                \"current\": 42,\n                \"max\": 100,\n                \"average\": 35.5\n            },\n            \"events\": {\n                \"total\": 12345,\n                \"rate\": {\n                    \"current\": 5.2,\n                    \"max\": 15.0,\n                    \"average\": 4.8\n                }\n            },\n            \"latency\": {\n                \"p50\": 15,\n                \"p95\": 45,\n                \"p99\": 100\n            },\n            \"resources\": {\n                \"memory\": {\n                    \"current\": 128974848,\n                    \"max\": 536870912\n                },\n                \"cpu\": {\n                    \"current\": 2.5,\n                    \"max\": 10.0,\n                    \"average\": 3.2\n                }\n            }\n        },\n        \"period\": \"24h\",\n        \"timestamp\": \"2024-02-05T12:00:00Z\"\n    }\n}\n
"},{"location":"tools/events/sse-stats.html#error-handling","title":"Error Handling","text":""},{"location":"tools/events/sse-stats.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/events/sse-stats.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/events/sse-stats.html#monitoring-metrics","title":"Monitoring Metrics","text":""},{"location":"tools/events/sse-stats.html#connection-metrics","title":"Connection Metrics","text":""},{"location":"tools/events/sse-stats.html#event-metrics","title":"Event Metrics","text":""},{"location":"tools/events/sse-stats.html#resource-metrics","title":"Resource Metrics","text":""},{"location":"tools/events/sse-stats.html#alert-thresholds","title":"Alert Thresholds","text":""},{"location":"tools/events/sse-stats.html#best-practices","title":"Best Practices","text":"
  1. Monitor connection health
  2. Track resource usage
  3. Set up alerts
  4. Analyze usage patterns
  5. Optimize performance
  6. Plan capacity
  7. Implement failover
  8. Regular maintenance
"},{"location":"tools/events/sse-stats.html#performance-optimization","title":"Performance Optimization","text":""},{"location":"tools/events/sse-stats.html#see-also","title":"See Also","text":""},{"location":"tools/events/subscribe-events.html","title":"Event Subscription Tool","text":"

The Event Subscription tool provides functionality to subscribe to and monitor real-time events from your Home Assistant instance.

"},{"location":"tools/events/subscribe-events.html#features","title":"Features","text":""},{"location":"tools/events/subscribe-events.html#usage","title":"Usage","text":""},{"location":"tools/events/subscribe-events.html#rest-api","title":"REST API","text":"
POST /api/events/subscribe\nDELETE /api/events/unsubscribe\nGET /api/events/subscriptions\nGET /api/events/history\n
"},{"location":"tools/events/subscribe-events.html#websocket","title":"WebSocket","text":"
// Subscribe to events\n{\n    \"type\": \"subscribe_events\",\n    \"event_type\": \"optional_event_type\",\n    \"entity_id\": \"optional_entity_id\",\n    \"domain\": \"optional_domain\"\n}\n\n// Unsubscribe from events\n{\n    \"type\": \"unsubscribe_events\",\n    \"subscription_id\": \"required_subscription_id\"\n}\n
"},{"location":"tools/events/subscribe-events.html#server-sent-events-sse","title":"Server-Sent Events (SSE)","text":"
GET /api/events/stream?event_type=state_changed&entity_id=light.living_room\n
"},{"location":"tools/events/subscribe-events.html#event-types","title":"Event Types","text":""},{"location":"tools/events/subscribe-events.html#examples","title":"Examples","text":""},{"location":"tools/events/subscribe-events.html#subscribe-to-all-state-changes","title":"Subscribe to All State Changes","text":"
const response = await fetch('http://your-ha-mcp/api/events/subscribe', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"event_type\": \"state_changed\"\n    })\n});\n
"},{"location":"tools/events/subscribe-events.html#monitor-specific-entity","title":"Monitor Specific Entity","text":"
const response = await fetch('http://your-ha-mcp/api/events/subscribe', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"event_type\": \"state_changed\",\n        \"entity_id\": \"light.living_room\"\n    })\n});\n
"},{"location":"tools/events/subscribe-events.html#domain-based-monitoring","title":"Domain-Based Monitoring","text":"
const response = await fetch('http://your-ha-mcp/api/events/subscribe', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"event_type\": \"state_changed\",\n        \"domain\": \"light\"\n    })\n});\n
"},{"location":"tools/events/subscribe-events.html#sse-connection-example","title":"SSE Connection Example","text":"
const eventSource = new EventSource(\n    'http://your-ha-mcp/api/events/stream?event_type=state_changed&entity_id=light.living_room',\n    {\n        headers: {\n            'Authorization': 'Bearer your_access_token'\n        }\n    }\n);\n\neventSource.onmessage = (event) => {\n    const data = JSON.parse(event.data);\n    console.log('Event received:', data);\n};\n\neventSource.onerror = (error) => {\n    console.error('SSE error:', error);\n    eventSource.close();\n};\n
"},{"location":"tools/events/subscribe-events.html#response-format","title":"Response Format","text":""},{"location":"tools/events/subscribe-events.html#subscription-response","title":"Subscription Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"subscription_id\": \"sub_123\",\n        \"event_type\": \"state_changed\",\n        \"entity_id\": \"light.living_room\",\n        \"created_at\": \"2024-02-05T12:00:00Z\"\n    }\n}\n
"},{"location":"tools/events/subscribe-events.html#event-message-format","title":"Event Message Format","text":"
{\n    \"event_type\": \"state_changed\",\n    \"entity_id\": \"light.living_room\",\n    \"data\": {\n        \"old_state\": {\n            \"state\": \"off\",\n            \"attributes\": {},\n            \"last_changed\": \"2024-02-05T11:55:00Z\"\n        },\n        \"new_state\": {\n            \"state\": \"on\",\n            \"attributes\": {\n                \"brightness\": 255\n            },\n            \"last_changed\": \"2024-02-05T12:00:00Z\"\n        }\n    },\n    \"origin\": \"LOCAL\",\n    \"time_fired\": \"2024-02-05T12:00:00Z\",\n    \"context\": {\n        \"id\": \"context_123\",\n        \"parent_id\": null,\n        \"user_id\": \"user_123\"\n    }\n}\n
"},{"location":"tools/events/subscribe-events.html#subscriptions-list-response","title":"Subscriptions List Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"subscriptions\": [\n            {\n                \"id\": \"sub_123\",\n                \"event_type\": \"state_changed\",\n                \"entity_id\": \"light.living_room\",\n                \"created_at\": \"2024-02-05T12:00:00Z\",\n                \"last_event\": \"2024-02-05T12:05:00Z\"\n            }\n        ]\n    }\n}\n
"},{"location":"tools/events/subscribe-events.html#error-handling","title":"Error Handling","text":""},{"location":"tools/events/subscribe-events.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/events/subscribe-events.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/events/subscribe-events.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/events/subscribe-events.html#best-practices","title":"Best Practices","text":"
  1. Use specific event types when possible
  2. Implement proper error handling
  3. Handle connection interruptions
  4. Process events asynchronously
  5. Implement backoff strategies
  6. Monitor subscription health
  7. Clean up unused subscriptions
  8. Handle rate limiting gracefully
"},{"location":"tools/events/subscribe-events.html#connection-management","title":"Connection Management","text":""},{"location":"tools/events/subscribe-events.html#see-also","title":"See Also","text":""},{"location":"tools/history-state/history.html","title":"Device History Tool","text":"

The Device History tool allows you to retrieve historical state information for devices in your Home Assistant instance.

"},{"location":"tools/history-state/history.html#features","title":"Features","text":""},{"location":"tools/history-state/history.html#usage","title":"Usage","text":""},{"location":"tools/history-state/history.html#rest-api","title":"REST API","text":"
GET /api/history/{device_id}\nGET /api/history/{device_id}/period/{start_time}\nGET /api/history/{device_id}/period/{start_time}/{end_time}\n
"},{"location":"tools/history-state/history.html#websocket","title":"WebSocket","text":"
{\n    \"type\": \"get_history\",\n    \"device_id\": \"required_device_id\",\n    \"start_time\": \"optional_iso_timestamp\",\n    \"end_time\": \"optional_iso_timestamp\",\n    \"significant_changes_only\": false\n}\n
"},{"location":"tools/history-state/history.html#query-parameters","title":"Query Parameters","text":"Parameter Type Description start_time ISO timestamp Start of the period to fetch history for end_time ISO timestamp End of the period to fetch history for significant_changes_only boolean Only return significant state changes minimal_response boolean Return minimal state information no_attributes boolean Exclude attribute data from response"},{"location":"tools/history-state/history.html#examples","title":"Examples","text":""},{"location":"tools/history-state/history.html#get-recent-history","title":"Get Recent History","text":"
const response = await fetch('http://your-ha-mcp/api/history/light.living_room', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst history = await response.json();\n
"},{"location":"tools/history-state/history.html#get-history-for-specific-period","title":"Get History for Specific Period","text":"
const startTime = '2024-02-01T00:00:00Z';\nconst endTime = '2024-02-02T00:00:00Z';\nconst response = await fetch(\n    `http://your-ha-mcp/api/history/light.living_room/period/${startTime}/${endTime}`, \n    {\n        headers: {\n            'Authorization': 'Bearer your_access_token'\n        }\n    }\n);\nconst history = await response.json();\n
"},{"location":"tools/history-state/history.html#response-format","title":"Response Format","text":""},{"location":"tools/history-state/history.html#history-response","title":"History Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"history\": [\n            {\n                \"state\": \"on\",\n                \"attributes\": {\n                    \"brightness\": 255\n                },\n                \"last_changed\": \"2024-02-05T12:00:00Z\",\n                \"last_updated\": \"2024-02-05T12:00:00Z\"\n            },\n            {\n                \"state\": \"off\",\n                \"last_changed\": \"2024-02-05T13:00:00Z\",\n                \"last_updated\": \"2024-02-05T13:00:00Z\"\n            }\n        ]\n    }\n}\n
"},{"location":"tools/history-state/history.html#aggregated-history-response","title":"Aggregated History Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"aggregates\": {\n            \"daily\": [\n                {\n                    \"date\": \"2024-02-05\",\n                    \"on_time\": \"PT5H30M\",\n                    \"off_time\": \"PT18H30M\",\n                    \"changes\": 10\n                }\n            ]\n        }\n    }\n}\n
"},{"location":"tools/history-state/history.html#error-handling","title":"Error Handling","text":""},{"location":"tools/history-state/history.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/history-state/history.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/history-state/history.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/history-state/history.html#data-retention","title":"Data Retention","text":""},{"location":"tools/history-state/history.html#best-practices","title":"Best Practices","text":"
  1. Use appropriate time ranges to avoid large responses
  2. Enable significant_changes_only for better performance
  3. Use minimal_response when full state data isn't needed
  4. Implement proper error handling
  5. Cache frequently accessed historical data
  6. Handle rate limiting gracefully
"},{"location":"tools/history-state/history.html#see-also","title":"See Also","text":""},{"location":"tools/history-state/scene.html","title":"Scene Management Tool","text":"

The Scene Management tool provides functionality to manage and control scenes in your Home Assistant instance.

"},{"location":"tools/history-state/scene.html#features","title":"Features","text":""},{"location":"tools/history-state/scene.html#usage","title":"Usage","text":""},{"location":"tools/history-state/scene.html#rest-api","title":"REST API","text":"
GET /api/scenes\nGET /api/scenes/{scene_id}\nPOST /api/scenes/{scene_id}/activate\nPOST /api/scenes\nPUT /api/scenes/{scene_id}\nDELETE /api/scenes/{scene_id}\n
"},{"location":"tools/history-state/scene.html#websocket","title":"WebSocket","text":"
// List scenes\n{\n    \"type\": \"get_scenes\"\n}\n\n// Activate scene\n{\n    \"type\": \"activate_scene\",\n    \"scene_id\": \"required_scene_id\"\n}\n\n// Create/Update scene\n{\n    \"type\": \"create_scene\",\n    \"scene\": {\n        \"name\": \"required_scene_name\",\n        \"entities\": {\n            // Entity states\n        }\n    }\n}\n
"},{"location":"tools/history-state/scene.html#scene-configuration","title":"Scene Configuration","text":""},{"location":"tools/history-state/scene.html#scene-definition","title":"Scene Definition","text":"
{\n    \"name\": \"Movie Night\",\n    \"entities\": {\n        \"light.living_room\": {\n            \"state\": \"on\",\n            \"brightness\": 50,\n            \"color_temp\": 2700\n        },\n        \"cover.living_room\": {\n            \"state\": \"closed\"\n        },\n        \"media_player.tv\": {\n            \"state\": \"on\",\n            \"source\": \"HDMI 1\"\n        }\n    }\n}\n
"},{"location":"tools/history-state/scene.html#examples","title":"Examples","text":""},{"location":"tools/history-state/scene.html#list-all-scenes","title":"List All Scenes","text":"
const response = await fetch('http://your-ha-mcp/api/scenes', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst scenes = await response.json();\n
"},{"location":"tools/history-state/scene.html#activate-a-scene","title":"Activate a Scene","text":"
const response = await fetch('http://your-ha-mcp/api/scenes/movie_night/activate', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\n
"},{"location":"tools/history-state/scene.html#create-a-new-scene","title":"Create a New Scene","text":"
const response = await fetch('http://your-ha-mcp/api/scenes', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"name\": \"Movie Night\",\n        \"entities\": {\n            \"light.living_room\": {\n                \"state\": \"on\",\n                \"brightness\": 50\n            },\n            \"cover.living_room\": {\n                \"state\": \"closed\"\n            }\n        }\n    })\n});\n
"},{"location":"tools/history-state/scene.html#response-format","title":"Response Format","text":""},{"location":"tools/history-state/scene.html#scene-list-response","title":"Scene List Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"scenes\": [\n            {\n                \"id\": \"scene_id\",\n                \"name\": \"Scene Name\",\n                \"entities\": {\n                    // Entity configurations\n                }\n            }\n        ]\n    }\n}\n
"},{"location":"tools/history-state/scene.html#scene-activation-response","title":"Scene Activation Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"scene_id\": \"activated_scene_id\",\n        \"status\": \"activated\",\n        \"timestamp\": \"2024-02-05T12:00:00Z\"\n    }\n}\n
"},{"location":"tools/history-state/scene.html#error-handling","title":"Error Handling","text":""},{"location":"tools/history-state/scene.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/history-state/scene.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/history-state/scene.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/history-state/scene.html#best-practices","title":"Best Practices","text":"
  1. Validate entity availability before creating scenes
  2. Use meaningful scene names
  3. Group related entities in scenes
  4. Implement proper error handling
  5. Cache scene configurations when possible
  6. Handle rate limiting gracefully
"},{"location":"tools/history-state/scene.html#scene-transitions","title":"Scene Transitions","text":"

Scenes can include transition settings for smooth state changes:

{\n    \"name\": \"Sunset Mode\",\n    \"entities\": {\n        \"light.living_room\": {\n            \"state\": \"on\",\n            \"brightness\": 128,\n            \"transition\": 5  // 5 seconds\n        }\n    }\n}\n
"},{"location":"tools/history-state/scene.html#see-also","title":"See Also","text":""},{"location":"tools/notifications/notify.html","title":"Notification Tool","text":"

The Notification tool provides functionality to send notifications through various services in your Home Assistant instance.

"},{"location":"tools/notifications/notify.html#features","title":"Features","text":""},{"location":"tools/notifications/notify.html#usage","title":"Usage","text":""},{"location":"tools/notifications/notify.html#rest-api","title":"REST API","text":"
POST /api/notify\nPOST /api/notify/{service_id}\nGET /api/notify/services\nGET /api/notify/history\n
"},{"location":"tools/notifications/notify.html#websocket","title":"WebSocket","text":"
// Send notification\n{\n    \"type\": \"send_notification\",\n    \"service\": \"required_service_id\",\n    \"message\": \"required_message\",\n    \"title\": \"optional_title\",\n    \"data\": {\n        // Service-specific data\n    }\n}\n\n// Get notification services\n{\n    \"type\": \"get_notification_services\"\n}\n
"},{"location":"tools/notifications/notify.html#supported-services","title":"Supported Services","text":""},{"location":"tools/notifications/notify.html#examples","title":"Examples","text":""},{"location":"tools/notifications/notify.html#basic-notification","title":"Basic Notification","text":"
const response = await fetch('http://your-ha-mcp/api/notify/mobile_app', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"message\": \"Motion detected in living room\",\n        \"title\": \"Security Alert\"\n    })\n});\n
"},{"location":"tools/notifications/notify.html#rich-notification","title":"Rich Notification","text":"
const response = await fetch('http://your-ha-mcp/api/notify/mobile_app', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"message\": \"Motion detected in living room\",\n        \"title\": \"Security Alert\",\n        \"data\": {\n            \"image\": \"https://your-camera-snapshot.jpg\",\n            \"actions\": [\n                {\n                    \"action\": \"view_camera\",\n                    \"title\": \"View Camera\"\n                },\n                {\n                    \"action\": \"dismiss\",\n                    \"title\": \"Dismiss\"\n                }\n            ],\n            \"priority\": \"high\",\n            \"ttl\": 3600,\n            \"group\": \"security\"\n        }\n    })\n});\n
"},{"location":"tools/notifications/notify.html#service-specific-example-telegram","title":"Service-Specific Example (Telegram)","text":"
const response = await fetch('http://your-ha-mcp/api/notify/telegram', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"message\": \"Temperature is too high!\",\n        \"title\": \"Climate Alert\",\n        \"data\": {\n            \"parse_mode\": \"markdown\",\n            \"inline_keyboard\": [\n                [\n                    {\n                        \"text\": \"Turn On AC\",\n                        \"callback_data\": \"turn_on_ac\"\n                    }\n                ]\n            ]\n        }\n    })\n});\n
"},{"location":"tools/notifications/notify.html#response-format","title":"Response Format","text":""},{"location":"tools/notifications/notify.html#success-response","title":"Success Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"notification_id\": \"notification_123\",\n        \"status\": \"sent\",\n        \"timestamp\": \"2024-02-05T12:00:00Z\",\n        \"service\": \"mobile_app\"\n    }\n}\n
"},{"location":"tools/notifications/notify.html#services-list-response","title":"Services List Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"services\": [\n            {\n                \"id\": \"mobile_app\",\n                \"name\": \"Mobile App\",\n                \"enabled\": true,\n                \"features\": [\n                    \"actions\",\n                    \"images\",\n                    \"sound\"\n                ]\n            }\n        ]\n    }\n}\n
"},{"location":"tools/notifications/notify.html#notification-history-response","title":"Notification History Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"history\": [\n            {\n                \"id\": \"notification_123\",\n                \"service\": \"mobile_app\",\n                \"message\": \"Motion detected\",\n                \"title\": \"Security Alert\",\n                \"timestamp\": \"2024-02-05T12:00:00Z\",\n                \"status\": \"delivered\"\n            }\n        ]\n    }\n}\n
"},{"location":"tools/notifications/notify.html#error-handling","title":"Error Handling","text":""},{"location":"tools/notifications/notify.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/notifications/notify.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/notifications/notify.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/notifications/notify.html#best-practices","title":"Best Practices","text":"
  1. Use appropriate priority levels
  2. Group related notifications
  3. Include relevant context
  4. Implement proper error handling
  5. Use templates for consistency
  6. Consider time zones
  7. Respect user preferences
  8. Handle rate limiting gracefully
"},{"location":"tools/notifications/notify.html#notification-templates","title":"Notification Templates","text":"
// Template example\n{\n    \"template\": \"security_alert\",\n    \"data\": {\n        \"location\": \"living_room\",\n        \"event_type\": \"motion\",\n        \"timestamp\": \"2024-02-05T12:00:00Z\"\n    }\n}\n
"},{"location":"tools/notifications/notify.html#see-also","title":"See Also","text":""}]} \ No newline at end of file diff --git a/search/search_index.json b/search/search_index.json index 0a0e23d..de36f89 100644 --- a/search/search_index.json +++ b/search/search_index.json @@ -1 +1 @@ -{"config":{"lang":["en"],"separator":"[\\s\\-,:!=\\[\\]()\"/]+|(?!\\b)(?=[A-Z][a-z])|\\.(?!\\d)|&[lg]t;","pipeline":["stopWordFilter"]},"docs":[{"location":"index.html","title":"Advanced Home Assistant MCP","text":"

Welcome to the Advanced Home Assistant Master Control Program documentation.

This documentation provides comprehensive information about setting up, configuring, and using the Advanced Home Assistant MCP system.

"},{"location":"index.html#quick-links","title":"Quick Links","text":""},{"location":"index.html#what-is-mcp-server","title":"What is MCP Server?","text":"

MCP Server is a bridge between Home Assistant and custom automation tools, enabling basic device control and real-time monitoring of your smart home environment. It provides a flexible interface for managing and interacting with your home automation setup.

"},{"location":"index.html#key-features","title":"Key Features","text":""},{"location":"index.html#device-control","title":"\ud83c\udfae Device Control","text":""},{"location":"index.html#security-performance","title":"\ud83d\udee1\ufe0f Security & Performance","text":""},{"location":"index.html#documentation-structure","title":"Documentation Structure","text":""},{"location":"index.html#getting-started","title":"Getting Started","text":""},{"location":"index.html#core-documentation","title":"Core Documentation","text":""},{"location":"index.html#support","title":"Support","text":"

Need help or want to report issues?

"},{"location":"index.html#license","title":"License","text":"

This project is licensed under the MIT License. See the LICENSE file for details.

"},{"location":"api.html","title":"Home Assistant MCP Server API Documentation","text":""},{"location":"api.html#overview","title":"Overview","text":"

This document provides a reference for the MCP Server API, which offers basic device control and state management for Home Assistant.

"},{"location":"api.html#authentication","title":"Authentication","text":"

All API requests require a valid JWT token in the Authorization header:

Authorization: Bearer YOUR_TOKEN\n
"},{"location":"api.html#core-endpoints","title":"Core Endpoints","text":""},{"location":"api.html#device-state-management","title":"Device State Management","text":""},{"location":"api.html#get-device-state","title":"Get Device State","text":"
GET /api/state/{entity_id}\n

Response:

{\n  \"entity_id\": \"light.living_room\",\n  \"state\": \"on\",\n  \"attributes\": {\n    \"brightness\": 128\n  }\n}\n

"},{"location":"api.html#update-device-state","title":"Update Device State","text":"
POST /api/state\nContent-Type: application/json\n\n{\n  \"entity_id\": \"light.living_room\",\n  \"state\": \"on\",\n  \"attributes\": {\n    \"brightness\": 128\n  }\n}\n
"},{"location":"api.html#device-control","title":"Device Control","text":""},{"location":"api.html#execute-device-command","title":"Execute Device Command","text":"
POST /api/control\nContent-Type: application/json\n\n{\n  \"entity_id\": \"light.living_room\",\n  \"command\": \"turn_on\",\n  \"parameters\": {\n    \"brightness\": 50\n  }\n}\n
"},{"location":"api.html#real-time-updates","title":"Real-Time Updates","text":""},{"location":"api.html#websocket-connection","title":"WebSocket Connection","text":"

Connect to real-time updates:

const ws = new WebSocket('ws://localhost:3000/events');\nws.onmessage = (event) => {\n  const deviceUpdate = JSON.parse(event.data);\n  console.log('Device state changed:', deviceUpdate);\n};\n
"},{"location":"api.html#error-handling","title":"Error Handling","text":""},{"location":"api.html#common-error-responses","title":"Common Error Responses","text":"
{\n  \"error\": {\n    \"code\": \"INVALID_REQUEST\",\n    \"message\": \"Invalid request parameters\",\n    \"details\": \"Entity ID not found or invalid command\"\n  }\n}\n
"},{"location":"api.html#rate-limiting","title":"Rate Limiting","text":"

Basic rate limiting is implemented: - Maximum of 100 requests per minute - Excess requests will receive a 429 Too Many Requests response

"},{"location":"api.html#supported-operations","title":"Supported Operations","text":""},{"location":"api.html#supported-commands","title":"Supported Commands","text":""},{"location":"api.html#supported-entities","title":"Supported Entities","text":""},{"location":"api.html#limitations","title":"Limitations","text":""},{"location":"api.html#best-practices","title":"Best Practices","text":"
  1. Always include a valid JWT token
  2. Handle potential errors in your client code
  3. Use WebSocket for real-time updates when possible
  4. Validate entity IDs before sending commands
"},{"location":"api.html#example-client-usage","title":"Example Client Usage","text":"
async function controlDevice(entityId: string, command: string, params?: Record<string, unknown>) {\n  try {\n    const response = await fetch('/api/control', {\n    method: 'POST',\n    headers: {\n        'Content-Type': 'application/json',\n        'Authorization': `Bearer ${token}`\n    },\n    body: JSON.stringify({\n        entity_id: entityId,\n        command,\n        parameters: params\n    })\n  });\n\n    if (!response.ok) {\n      const error = await response.json();\n      throw new Error(error.message);\n    }\n\n    return await response.json();\n} catch (error) {\n    console.error('Device control failed:', error);\n    throw error;\n  }\n}\n\n// Usage example\ncontrolDevice('light.living_room', 'turn_on', { brightness: 50 })\n  .then(result => console.log('Device controlled successfully'))\n  .catch(error => console.error('Control failed', error));\n
"},{"location":"api.html#future-development","title":"Future Development","text":"

Planned improvements: - Enhanced error handling - More comprehensive device support - Improved authentication mechanisms

API is subject to change. Always refer to the latest documentation.

"},{"location":"architecture.html","title":"Architecture Overview \ud83c\udfd7\ufe0f","text":"

This document describes the architecture of the MCP Server, explaining how different components work together to provide a bridge between Home Assistant and custom automation tools.

"},{"location":"architecture.html#system-architecture","title":"System Architecture","text":"
graph TD\n    subgraph \"Client Layer\"\n        WC[Web Clients]\n        MC[Mobile Clients]\n    end\n\n    subgraph \"MCP Server\"\n        API[API Gateway]\n        SSE[SSE Manager]\n        WS[WebSocket Server]\n        CM[Command Manager]\n    end\n\n    subgraph \"Home Assistant\"\n        HA[Home Assistant Core]\n        Dev[Devices & Services]\n    end\n\n    WC --> |HTTP/WS| API\n    MC --> |HTTP/WS| API\n\n    API --> |Events| SSE\n    API --> |Real-time| WS\n\n    API --> HA\n    HA --> API
"},{"location":"architecture.html#core-components","title":"Core Components","text":""},{"location":"architecture.html#api-gateway","title":"API Gateway","text":""},{"location":"architecture.html#sse-manager","title":"SSE Manager","text":""},{"location":"architecture.html#websocket-server","title":"WebSocket Server","text":""},{"location":"architecture.html#command-manager","title":"Command Manager","text":""},{"location":"architecture.html#communication-flow","title":"Communication Flow","text":"
  1. Client sends a request to the MCP Server API
  2. API Gateway authenticates the request
  3. Command Manager processes the request
  4. Request is forwarded to Home Assistant
  5. Response is sent back to the client via API or WebSocket
"},{"location":"architecture.html#key-design-principles","title":"Key Design Principles","text":""},{"location":"architecture.html#limitations","title":"Limitations","text":""},{"location":"architecture.html#future-improvements","title":"Future Improvements","text":"

Architecture is subject to change as the project evolves.

"},{"location":"configuration.html","title":"System Configuration","text":"

This document provides detailed information about configuring the Home Assistant MCP Server.

"},{"location":"configuration.html#configuration-file-structure","title":"Configuration File Structure","text":"

The MCP Server uses environment variables for configuration, with support for different environments (development, test, production):

# .env, .env.development, or .env.test\nPORT=4000\nNODE_ENV=development\nHASS_HOST=http://192.168.178.63:8123\nHASS_TOKEN=your_token_here\nJWT_SECRET=your_secret_key\n
"},{"location":"configuration.html#server-settings","title":"Server Settings","text":""},{"location":"configuration.html#basic-server-configuration","title":"Basic Server Configuration","text":""},{"location":"configuration.html#security-settings","title":"Security Settings","text":""},{"location":"configuration.html#websocket-settings","title":"WebSocket Settings","text":""},{"location":"configuration.html#environment-variables","title":"Environment Variables","text":"

All configuration is managed through environment variables:

# Server\nPORT=4000\nNODE_ENV=development\n\n# Home Assistant\nHASS_HOST=http://your-hass-instance:8123\nHASS_TOKEN=your_token_here\n\n# Security\nJWT_SECRET=your-secret-key\n\n# Logging\nLOG_LEVEL=info\nLOG_DIR=logs\nLOG_MAX_SIZE=20m\nLOG_MAX_DAYS=14d\nLOG_COMPRESS=true\nLOG_REQUESTS=true\n
"},{"location":"configuration.html#advanced-configuration","title":"Advanced Configuration","text":""},{"location":"configuration.html#security-rate-limiting","title":"Security Rate Limiting","text":"

Rate limiting is enabled by default to protect against brute force attacks:

RATE_LIMIT: {\n  windowMs: 15 * 60 * 1000,  // 15 minutes\n  max: 100  // limit each IP to 100 requests per window\n}\n
"},{"location":"configuration.html#logging","title":"Logging","text":"

The server uses Bun's built-in logging capabilities with additional configuration:

LOGGING: {\n  LEVEL: \"info\",  // debug, info, warn, error\n  DIR: \"logs\",\n  MAX_SIZE: \"20m\",\n  MAX_DAYS: \"14d\",\n  COMPRESS: true,\n  TIMESTAMP_FORMAT: \"YYYY-MM-DD HH:mm:ss:ms\",\n  LOG_REQUESTS: true\n}\n

For production deployments, we recommend using system tools like logrotate for log management.

Example logrotate configuration (/etc/logrotate.d/mcp-server):

/var/log/mcp-server.log {\n    daily\n    rotate 7\n    compress\n    delaycompress\n    missingok\n    notifempty\n    create 644 mcp mcp\n}\n

"},{"location":"configuration.html#best-practices","title":"Best Practices","text":"
  1. Always use environment variables for sensitive information
  2. Keep .env files secure and never commit them to version control
  3. Use different environment files for development, test, and production
  4. Enable SSL/TLS in production (preferably via reverse proxy)
  5. Monitor log files for issues
  6. Regularly rotate logs in production
"},{"location":"configuration.html#validation","title":"Validation","text":"

The server validates configuration on startup using Zod schemas: - Required fields are checked (e.g., HASS_TOKEN) - Value types are verified - Enums are validated (e.g., LOG_LEVEL) - Default values are applied when not specified

"},{"location":"configuration.html#troubleshooting","title":"Troubleshooting","text":"

Common configuration issues: 1. Missing required environment variables 2. Invalid environment variable values 3. Permission issues with log directories 4. Rate limiting too restrictive

See the Troubleshooting Guide for solutions.

"},{"location":"contributing.html","title":"Contributing Guide \ud83e\udd1d","text":"

Thank you for your interest in contributing to the MCP Server project!

"},{"location":"contributing.html#getting-started","title":"Getting Started","text":""},{"location":"contributing.html#prerequisites","title":"Prerequisites","text":""},{"location":"contributing.html#development-setup","title":"Development Setup","text":"
  1. Fork the repository
  2. Clone your fork:

    git clone https://github.com/YOUR_USERNAME/homeassistant-mcp.git\ncd homeassistant-mcp\n

  3. Install dependencies:

    bun install\n

  4. Configure environment:

    cp .env.example .env\n# Edit .env with your Home Assistant details\n

"},{"location":"contributing.html#development-workflow","title":"Development Workflow","text":""},{"location":"contributing.html#branch-naming","title":"Branch Naming","text":"

Example:

git checkout -b feature/device-control-improvements\n

"},{"location":"contributing.html#commit-messages","title":"Commit Messages","text":"

Follow simple, clear commit messages:

type: brief description\n\n[optional detailed explanation]\n

Types: - feat: - New feature - fix: - Bug fix - docs: - Documentation - chore: - Maintenance

"},{"location":"contributing.html#code-style","title":"Code Style","text":""},{"location":"contributing.html#testing","title":"Testing","text":"

Run tests before submitting:

# Run all tests\nbun test\n\n# Run specific test\nbun test test/api/control.test.ts\n
"},{"location":"contributing.html#pull-request-process","title":"Pull Request Process","text":"
  1. Ensure tests pass
  2. Update documentation if needed
  3. Provide clear description of changes
"},{"location":"contributing.html#pr-template","title":"PR Template","text":"
## Description\nBrief explanation of the changes\n\n## Type of Change\n- [ ] Bug fix\n- [ ] New feature\n- [ ] Documentation update\n\n## Testing\nDescribe how you tested these changes\n
"},{"location":"contributing.html#reporting-issues","title":"Reporting Issues","text":""},{"location":"contributing.html#code-of-conduct","title":"Code of Conduct","text":""},{"location":"contributing.html#resources","title":"Resources","text":"

Thank you for contributing!

"},{"location":"deployment.html","title":"Deployment Guide","text":"

This documentation is automatically deployed to GitHub Pages using GitHub Actions. Here's how it works and how to manage deployments.

"},{"location":"deployment.html#automatic-deployment","title":"Automatic Deployment","text":"

The documentation is automatically deployed when changes are pushed to the main or master branch. The deployment process:

  1. Triggers on push to main/master
  2. Sets up Python environment
  3. Installs required dependencies
  4. Builds the documentation
  5. Deploys to the gh-pages branch
"},{"location":"deployment.html#github-actions-workflow","title":"GitHub Actions Workflow","text":"

The deployment is handled by the workflow in .github/workflows/deploy-docs.yml. This is the single source of truth for documentation deployment:

name: Deploy MkDocs\non:\n  push:\n    branches:\n      - main\n      - master\n  workflow_dispatch:  # Allow manual trigger\n
"},{"location":"deployment.html#manual-deployment","title":"Manual Deployment","text":"

If needed, you can deploy manually using:

# Create a virtual environment\npython -m venv venv\n\n# Activate the virtual environment\nsource venv/bin/activate\n\n# Install dependencies\npip install -r docs/requirements.txt\n\n# Build the documentation\nmkdocs build\n\n# Deploy to GitHub Pages\nmkdocs gh-deploy --force\n
"},{"location":"deployment.html#best-practices","title":"Best Practices","text":""},{"location":"deployment.html#1-documentation-updates","title":"1. Documentation Updates","text":""},{"location":"deployment.html#2-version-control","title":"2. Version Control","text":""},{"location":"deployment.html#3-content-guidelines","title":"3. Content Guidelines","text":""},{"location":"deployment.html#4-maintenance","title":"4. Maintenance","text":""},{"location":"deployment.html#troubleshooting","title":"Troubleshooting","text":""},{"location":"deployment.html#common-issues","title":"Common Issues","text":"
  1. Failed Deployments
  2. Check GitHub Actions logs
  3. Verify dependencies are up to date
  4. Ensure all required files exist

  5. Broken Links

  6. Run mkdocs build --strict
  7. Use relative paths in markdown
  8. Check case sensitivity

  9. Style Issues

  10. Verify theme configuration
  11. Check CSS customizations
  12. Test on multiple browsers
"},{"location":"deployment.html#configuration-files","title":"Configuration Files","text":""},{"location":"deployment.html#requirementstxt","title":"requirements.txt","text":"

Create a requirements file for documentation dependencies:

mkdocs-material\nmkdocs-minify-plugin\nmkdocs-git-revision-date-plugin\nmkdocs-mkdocstrings\nmkdocs-social-plugin\nmkdocs-redirects\n
"},{"location":"deployment.html#monitoring","title":"Monitoring","text":""},{"location":"deployment.html#workflow-features","title":"Workflow Features","text":""},{"location":"deployment.html#caching","title":"Caching","text":"

The workflow implements caching for Python dependencies to speed up deployments: - Pip cache for Python packages - MkDocs dependencies cache

"},{"location":"deployment.html#deployment-checks","title":"Deployment Checks","text":"

Several checks are performed during deployment: 1. Link validation with mkdocs build --strict 2. Build verification 3. Post-deployment site accessibility check

"},{"location":"deployment.html#manual-triggers","title":"Manual Triggers","text":"

You can manually trigger deployments using the \"workflow_dispatch\" event in GitHub Actions.

"},{"location":"deployment.html#cleanup","title":"Cleanup","text":"

To clean up duplicate workflow files, run:

# Make the script executable\nchmod +x scripts/cleanup-workflows.sh\n\n# Run the cleanup script\n./scripts/cleanup-workflows.sh\n
"},{"location":"roadmap.html","title":"Roadmap for MCP Server","text":"

The following roadmap outlines our planned enhancements and future directions for the Home Assistant MCP Server. This document is a living guide that will be updated as new features are developed.

"},{"location":"roadmap.html#near-term-goals","title":"Near-Term Goals","text":""},{"location":"roadmap.html#mid-term-goals","title":"Mid-Term Goals","text":""},{"location":"roadmap.html#long-term-vision","title":"Long-Term Vision","text":""},{"location":"roadmap.html#how-to-follow-the-roadmap","title":"How to Follow the Roadmap","text":"

This roadmap is intended as a guide and may evolve based on community needs, technological advancements, and strategic priorities.

"},{"location":"security.html","title":"Security Guide","text":"

This document outlines security best practices and configurations for the Home Assistant MCP Server.

"},{"location":"security.html#authentication","title":"Authentication","text":""},{"location":"security.html#jwt-authentication","title":"JWT Authentication","text":"

The server uses JWT (JSON Web Tokens) for API authentication:

Authorization: Bearer YOUR_JWT_TOKEN\n
"},{"location":"security.html#token-configuration","title":"Token Configuration","text":"
security:\n  jwt_secret: YOUR_SECRET_KEY\n  token_expiry: 24h\n  refresh_token_expiry: 7d\n
"},{"location":"security.html#access-control","title":"Access Control","text":""},{"location":"security.html#cors-configuration","title":"CORS Configuration","text":"

Configure allowed origins to prevent unauthorized access:

security:\n  allowed_origins:\n    - http://localhost:3000\n    - https://your-domain.com\n
"},{"location":"security.html#ip-filtering","title":"IP Filtering","text":"

Restrict access by IP address:

security:\n  allowed_ips:\n    - 192.168.1.0/24\n    - 10.0.0.0/8\n
"},{"location":"security.html#ssltls-configuration","title":"SSL/TLS Configuration","text":""},{"location":"security.html#enable-https","title":"Enable HTTPS","text":"
ssl:\n  enabled: true\n  cert_file: /path/to/cert.pem\n  key_file: /path/to/key.pem\n
"},{"location":"security.html#certificate-management","title":"Certificate Management","text":"
  1. Use Let's Encrypt for free SSL certificates
  2. Regularly renew certificates
  3. Monitor certificate expiration
"},{"location":"security.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"security.html#basic-rate-limiting","title":"Basic Rate Limiting","text":"
rate_limit:\n  enabled: true\n  requests_per_minute: 100\n  burst: 20\n
"},{"location":"security.html#advanced-rate-limiting","title":"Advanced Rate Limiting","text":"
rate_limit:\n  rules:\n    - endpoint: /api/control\n      requests_per_minute: 50\n    - endpoint: /api/state\n      requests_per_minute: 200\n
"},{"location":"security.html#data-protection","title":"Data Protection","text":""},{"location":"security.html#sensitive-data","title":"Sensitive Data","text":""},{"location":"security.html#logging-security","title":"Logging Security","text":""},{"location":"security.html#best-practices","title":"Best Practices","text":"
  1. Regular Security Updates
  2. Keep dependencies updated
  3. Monitor security advisories
  4. Apply patches promptly

  5. Password Policies

  6. Enforce strong passwords
  7. Implement password expiration
  8. Use secure password storage

  9. Monitoring

  10. Log security events
  11. Monitor access patterns
  12. Set up alerts for suspicious activity

  13. Network Security

  14. Use VPN for remote access
  15. Implement network segmentation
  16. Configure firewalls properly
"},{"location":"security.html#security-checklist","title":"Security Checklist","text":""},{"location":"security.html#incident-response","title":"Incident Response","text":"
  1. Detection
  2. Monitor security logs
  3. Set up intrusion detection
  4. Configure alerts

  5. Response

  6. Document incident details
  7. Isolate affected systems
  8. Investigate root cause

  9. Recovery

  10. Apply security fixes
  11. Restore from backups
  12. Update security measures
"},{"location":"security.html#additional-resources","title":"Additional Resources","text":""},{"location":"testing.html","title":"Testing Documentation","text":""},{"location":"testing.html#quick-reference","title":"Quick Reference","text":"
# Most Common Commands\nbun test                    # Run all tests\nbun test --watch           # Run tests in watch mode\nbun test --coverage        # Run tests with coverage\nbun test path/to/test.ts   # Run a specific test file\n\n# Additional Options\nDEBUG=true bun test        # Run with debug output\nbun test --pattern \"auth\"  # Run tests matching a pattern\nbun test --timeout 60000   # Run with a custom timeout\n
"},{"location":"testing.html#overview","title":"Overview","text":"

This document describes the testing setup and practices used in the Home Assistant MCP project. We use Bun's test runner for both unit and integration testing, ensuring comprehensive coverage across modules.

"},{"location":"testing.html#test-structure","title":"Test Structure","text":"

Tests are organized in two main locations:

  1. Root Level Integration Tests (/__tests__/):
__tests__/\n\u251c\u2500\u2500 ai/              # AI/ML component tests\n\u251c\u2500\u2500 api/             # API integration tests\n\u251c\u2500\u2500 context/         # Context management tests\n\u251c\u2500\u2500 hass/            # Home Assistant integration tests\n\u251c\u2500\u2500 schemas/         # Schema validation tests\n\u251c\u2500\u2500 security/        # Security integration tests\n\u251c\u2500\u2500 tools/           # Tools and utilities tests\n\u251c\u2500\u2500 websocket/       # WebSocket integration tests\n\u251c\u2500\u2500 helpers.test.ts  # Helper function tests\n\u251c\u2500\u2500 index.test.ts    # Main application tests\n\u2514\u2500\u2500 server.test.ts   # Server integration tests\n
  1. Component Level Unit Tests (src/**/):
src/\n\u251c\u2500\u2500 __tests__/   # Global test setup and utilities\n\u2502   \u2514\u2500\u2500 setup.ts # Global test configuration\n\u251c\u2500\u2500 component/\n\u2502   \u251c\u2500\u2500 __tests__/   # Component-specific unit tests\n\u2502   \u2514\u2500\u2500 component.ts\n
"},{"location":"testing.html#test-configuration","title":"Test Configuration","text":""},{"location":"testing.html#bun-test-configuration-bunfigtoml","title":"Bun Test Configuration (bunfig.toml)","text":"
[test]\npreload = [\"./src/__tests__/setup.ts\"]  # Global test setup\ncoverage = true                         # Enable coverage by default\ntimeout = 30000                         # Test timeout in milliseconds\ntestMatch = [\"**/__tests__/**/*.test.ts\"] # Test file patterns\n
"},{"location":"testing.html#bun-scripts","title":"Bun Scripts","text":"

Available test commands in package.json:

# Run all tests\nbun test\n\n# Watch mode for development\nbun test --watch\n\n# Generate coverage report\nbun test --coverage\n\n# Run linting\nbun run lint\n\n# Format code\nbun run format\n
"},{"location":"testing.html#test-setup","title":"Test Setup","text":""},{"location":"testing.html#global-configuration","title":"Global Configuration","text":"

A global test setup file (src/__tests__/setup.ts) provides: - Environment configuration - Mock utilities - Test helper functions - Global lifecycle hooks

"},{"location":"testing.html#test-environment","title":"Test Environment","text":""},{"location":"testing.html#running-tests","title":"Running Tests","text":"
# Basic test run\nbun test\n\n# Run tests with coverage\nbun test --coverage\n\n# Run a specific test file\nbun test path/to/test.test.ts\n\n# Run tests in watch mode\nbun test --watch\n\n# Run tests with debug output\nDEBUG=true bun test\n\n# Run tests with increased timeout\nbun test --timeout 60000\n\n# Run tests matching a pattern\nbun test --pattern \"auth\"\n
"},{"location":"testing.html#advanced-debugging","title":"Advanced Debugging","text":""},{"location":"testing.html#using-node-inspector","title":"Using Node Inspector","text":"
# Start tests with inspector\nbun test --inspect\n\n# Start tests with inspector and break on first line\nbun test --inspect-brk\n
"},{"location":"testing.html#using-vs-code","title":"Using VS Code","text":"

Create a launch configuration in .vscode/launch.json:

{\n  \"version\": \"0.2.0\",\n  \"configurations\": [\n    {\n      \"type\": \"bun\",\n      \"request\": \"launch\",\n      \"name\": \"Debug Tests\",\n      \"program\": \"${workspaceFolder}/node_modules/bun/bin/bun\",\n      \"args\": [\"test\", \"${file}\"],\n      \"cwd\": \"${workspaceFolder}\",\n      \"env\": { \"DEBUG\": \"true\" }\n    }\n  ]\n}\n
"},{"location":"testing.html#test-isolation","title":"Test Isolation","text":"

To run a single test in isolation:

describe.only(\"specific test suite\", () => {\n  it.only(\"specific test case\", () => {\n    // Only this test will run\n  });\n});\n
"},{"location":"testing.html#writing-tests","title":"Writing Tests","text":""},{"location":"testing.html#test-file-naming","title":"Test File Naming","text":""},{"location":"testing.html#example-test-structure","title":"Example Test Structure","text":"
describe(\"Security Features\", () => {\n  it(\"should validate tokens correctly\", () => {\n    const payload = { userId: \"123\", role: \"user\" };\n    const token = jwt.sign(payload, validSecret, { expiresIn: \"1h\" });\n    const result = TokenManager.validateToken(token, testIp);\n    expect(result.valid).toBe(true);\n  });\n});\n
"},{"location":"testing.html#coverage","title":"Coverage","text":"

The project maintains strict coverage: - Overall coverage: at least 80% - Critical paths: 90%+ - New features: \u226585% coverage

Generate a coverage report with:

bun test --coverage\n
"},{"location":"testing.html#security-middleware-testing","title":"Security Middleware Testing","text":""},{"location":"testing.html#utility-function-testing","title":"Utility Function Testing","text":"

The security middleware now uses a utility-first approach, which allows for more granular and comprehensive testing. Each security function is now independently testable, improving code reliability and maintainability.

"},{"location":"testing.html#key-utility-functions","title":"Key Utility Functions","text":"
  1. Rate Limiting (checkRateLimit)
  2. Tests multiple scenarios:
    • Requests under threshold
    • Requests exceeding threshold
    • Rate limit reset after window expiration
// Example test\nit('should throw when requests exceed threshold', () => {\n  const ip = '127.0.0.2';\n  for (let i = 0; i < 11; i++) {\n    if (i < 10) {\n      expect(() => checkRateLimit(ip, 10)).not.toThrow();\n    } else {\n      expect(() => checkRateLimit(ip, 10)).toThrow('Too many requests from this IP');\n    }\n  }\n});\n
  1. Request Validation (validateRequestHeaders)
  2. Tests content type validation
  3. Checks request size limits
  4. Validates authorization headers
it('should reject invalid content type', () => {\n  const mockRequest = new Request('http://localhost', {\n    method: 'POST',\n    headers: { 'content-type': 'text/plain' }\n  });\n  expect(() => validateRequestHeaders(mockRequest)).toThrow('Content-Type must be application/json');\n});\n
  1. Input Sanitization (sanitizeValue)
  2. Sanitizes HTML tags
  3. Handles nested objects
  4. Preserves non-string values
it('should sanitize HTML tags', () => {\n  const input = '<script>alert(\"xss\")</script>Hello';\n  const sanitized = sanitizeValue(input);\n  expect(sanitized).toBe('&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;Hello');\n});\n
  1. Security Headers (applySecurityHeaders)
  2. Verifies correct security header application
  3. Checks CSP, frame options, and other security headers
it('should apply security headers', () => {\n  const mockRequest = new Request('http://localhost');\n  const headers = applySecurityHeaders(mockRequest);\n  expect(headers['content-security-policy']).toBeDefined();\n  expect(headers['x-frame-options']).toBeDefined();\n});\n
  1. Error Handling (handleError)
  2. Tests error responses in production and development modes
  3. Verifies error message and stack trace inclusion
it('should include error details in development mode', () => {\n  const error = new Error('Test error');\n  const result = handleError(error, 'development');\n  expect(result).toEqual({\n    error: true,\n    message: 'Internal server error',\n    error: 'Test error',\n    stack: expect.any(String)\n  });\n});\n
"},{"location":"testing.html#testing-philosophy","title":"Testing Philosophy","text":""},{"location":"testing.html#best-practices","title":"Best Practices","text":"
  1. Use minimal, focused test cases
  2. Test both successful and failure scenarios
  3. Verify input sanitization and security measures
  4. Mock external dependencies when necessary
"},{"location":"testing.html#running-security-tests","title":"Running Security Tests","text":"
# Run all tests\nbun test\n\n# Run specific security tests\nbun test __tests__/security/\n
"},{"location":"testing.html#continuous-improvement","title":"Continuous Improvement","text":""},{"location":"testing.html#best-practices_1","title":"Best Practices","text":"
  1. Isolation: Each test should be independent and not rely on the state of other tests.
  2. Mocking: Use the provided mock utilities for external dependencies.
  3. Cleanup: Clean up any resources or state modifications in afterEach or afterAll hooks.
  4. Descriptive Names: Use clear, descriptive test names that explain the expected behavior.
  5. Assertions: Make specific, meaningful assertions rather than general ones.
  6. Setup: Use beforeEach for common test setup to avoid repetition.
  7. Error Cases: Test both success and error cases for complete coverage.
"},{"location":"testing.html#coverage_1","title":"Coverage","text":"

The project aims for high test coverage, particularly focusing on: - Security-critical code paths - API endpoints - Data validation - Error handling - Event broadcasting

Run coverage reports using:

bun test --coverage\n

"},{"location":"testing.html#debugging-tests","title":"Debugging Tests","text":"

To debug tests: 1. Set DEBUG=true to enable console output during tests 2. Use the --watch flag for development 3. Add console.log() statements (they're only shown when DEBUG is true) 4. Use the test utilities' debugging helpers

"},{"location":"testing.html#advanced-debugging_1","title":"Advanced Debugging","text":"
  1. Using Node Inspector:

    # Start tests with inspector\nbun test --inspect\n\n# Start tests with inspector and break on first line\nbun test --inspect-brk\n

  2. Using VS Code:

    // .vscode/launch.json\n{\n  \"version\": \"0.2.0\",\n  \"configurations\": [\n    {\n      \"type\": \"bun\",\n      \"request\": \"launch\",\n      \"name\": \"Debug Tests\",\n      \"program\": \"${workspaceFolder}/node_modules/bun/bin/bun\",\n      \"args\": [\"test\", \"${file}\"],\n      \"cwd\": \"${workspaceFolder}\",\n      \"env\": { \"DEBUG\": \"true\" }\n    }\n  ]\n}\n

  3. Test Isolation: To run a single test in isolation:

    describe.only(\"specific test suite\", () => {\n  it.only(\"specific test case\", () => {\n    // Only this test will run\n  });\n});\n

"},{"location":"testing.html#contributing","title":"Contributing","text":"

When contributing new code: 1. Add tests for new features 2. Ensure existing tests pass 3. Maintain or improve coverage 4. Follow the existing test patterns and naming conventions 5. Document any new test utilities or patterns

"},{"location":"testing.html#coverage-requirements","title":"Coverage Requirements","text":"

The project maintains strict coverage requirements:

Coverage reports are generated in multiple formats: - Console summary - HTML report (./coverage/index.html) - LCOV report (./coverage/lcov.info)

To view detailed coverage:

# Generate and open coverage report\nbun test --coverage && open coverage/index.html\n

"},{"location":"troubleshooting.html","title":"Troubleshooting Guide \ud83d\udd27","text":"

This guide helps you diagnose and resolve common issues with MCP Server.

"},{"location":"troubleshooting.html#quick-diagnostics","title":"Quick Diagnostics","text":""},{"location":"troubleshooting.html#health-check","title":"Health Check","text":"

First, verify the server's health:

curl http://localhost:3000/health\n

Expected response:

{\n  \"status\": \"healthy\",\n  \"version\": \"1.0.0\",\n  \"uptime\": 3600,\n  \"homeAssistant\": {\n    \"connected\": true,\n    \"version\": \"2024.1.0\"\n  }\n}\n

"},{"location":"troubleshooting.html#common-issues","title":"Common Issues","text":""},{"location":"troubleshooting.html#1-connection-issues","title":"1. Connection Issues","text":""},{"location":"troubleshooting.html#cannot-connect-to-mcp-server","title":"Cannot Connect to MCP Server","text":"

Symptoms: - Server not responding - Connection refused errors - Timeout errors

Solutions:

  1. Check if the server is running:

    # For Docker installation\ndocker compose ps\n\n# For manual installation\nps aux | grep mcp\n

  2. Verify port availability:

    # Check if port is in use\nnetstat -tuln | grep 3000\n

  3. Check logs:

    # Docker logs\ndocker compose logs mcp\n\n# Manual installation logs\nbun run dev\n

"},{"location":"troubleshooting.html#home-assistant-connection-failed","title":"Home Assistant Connection Failed","text":"

Symptoms: - \"Connection Error\" in health check - Cannot control devices - State updates not working

Solutions:

  1. Verify Home Assistant URL and token in .env:

    HA_URL=http://homeassistant:8123\nHA_TOKEN=your_long_lived_access_token\n

  2. Test Home Assistant connection:

    curl -H \"Authorization: Bearer YOUR_HA_TOKEN\" \\\n     http://your-homeassistant:8123/api/\n

  3. Check network connectivity:

    # For Docker setup\ndocker compose exec mcp ping homeassistant\n

"},{"location":"troubleshooting.html#2-authentication-issues","title":"2. Authentication Issues","text":""},{"location":"troubleshooting.html#invalid-token","title":"Invalid Token","text":"

Symptoms: - 401 Unauthorized responses - \"Invalid token\" errors

Solutions:

  1. Generate a new token:

    curl -X POST http://localhost:3000/auth/token \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"username\": \"your_username\", \"password\": \"your_password\"}'\n

  2. Verify token format:

    // Token should be in format:\nAuthorization: Bearer eyJhbGciOiJIUzI1NiIs...\n

"},{"location":"troubleshooting.html#rate-limiting","title":"Rate Limiting","text":"

Symptoms: - 429 Too Many Requests - \"Rate limit exceeded\" errors

Solutions:

  1. Check current rate limit status:

    curl -I http://localhost:3000/api/state\n

  2. Adjust rate limits in configuration:

    security:\n  rateLimit: 100  # Increase if needed\n  rateLimitWindow: 60000  # Window in milliseconds\n

"},{"location":"troubleshooting.html#3-real-time-updates-issues","title":"3. Real-time Updates Issues","text":""},{"location":"troubleshooting.html#sse-connection-drops","title":"SSE Connection Drops","text":"

Symptoms: - Frequent disconnections - Missing state updates - EventSource errors

Solutions:

  1. Implement proper reconnection logic:

    class SSEClient {\n    constructor() {\n        this.connect();\n    }\n\n    connect() {\n        this.eventSource = new EventSource('/subscribe_events');\n        this.eventSource.onerror = this.handleError.bind(this);\n    }\n\n    handleError(error) {\n        console.error('SSE Error:', error);\n        this.eventSource.close();\n        setTimeout(() => this.connect(), 1000);\n    }\n}\n

  2. Check network stability:

    # Monitor connection stability\nping -c 100 localhost\n

"},{"location":"troubleshooting.html#4-performance-issues","title":"4. Performance Issues","text":""},{"location":"troubleshooting.html#high-latency","title":"High Latency","text":"

Symptoms: - Slow response times - Command execution delays - UI lag

Solutions:

  1. Enable Redis caching:

    REDIS_ENABLED=true\nREDIS_URL=redis://localhost:6379\n

  2. Monitor system resources:

    # Check CPU and memory usage\ndocker stats\n\n# Or for manual installation\ntop -p $(pgrep -f mcp)\n

  3. Optimize database queries and caching:

    // Use batch operations\nconst results = await Promise.all([\n    cache.get('key1'),\n    cache.get('key2')\n]);\n

"},{"location":"troubleshooting.html#5-device-control-issues","title":"5. Device Control Issues","text":""},{"location":"troubleshooting.html#commands-not-executing","title":"Commands Not Executing","text":"

Symptoms: - Commands appear successful but no device response - Inconsistent device states - Error messages from Home Assistant

Solutions:

  1. Verify device availability:

    curl http://localhost:3000/api/state/light.living_room\n

  2. Check command syntax:

    # Test basic command\ncurl -X POST http://localhost:3000/api/command \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"command\": \"Turn on living room lights\"}'\n

  3. Review Home Assistant logs:

    docker compose exec homeassistant journalctl -f\n

"},{"location":"troubleshooting.html#debugging-tools","title":"Debugging Tools","text":""},{"location":"troubleshooting.html#log-analysis","title":"Log Analysis","text":"

Enable debug logging:

LOG_LEVEL=debug\nDEBUG=mcp:*\n
"},{"location":"troubleshooting.html#network-debugging","title":"Network Debugging","text":"

Monitor network traffic:

# TCP dump for API traffic\ntcpdump -i any port 3000 -w debug.pcap\n
"},{"location":"troubleshooting.html#performance-profiling","title":"Performance Profiling","text":"

Enable performance monitoring:

ENABLE_METRICS=true\nMETRICS_PORT=9090\n
"},{"location":"troubleshooting.html#getting-help","title":"Getting Help","text":"

If you're still experiencing issues:

  1. Check the GitHub Issues
  2. Search Discussions
  3. Create a new issue with:
  4. Detailed description
  5. Logs
  6. Configuration (sanitized)
  7. Steps to reproduce
"},{"location":"troubleshooting.html#maintenance","title":"Maintenance","text":""},{"location":"troubleshooting.html#regular-health-checks","title":"Regular Health Checks","text":"

Run periodic health checks:

# Create a cron job\n*/5 * * * * curl -f http://localhost:3000/health || notify-admin\n
"},{"location":"troubleshooting.html#log-rotation","title":"Log Rotation","text":"

Configure log rotation:

logging:\n  maxSize: \"100m\"\n  maxFiles: \"7d\"\n  compress: true\n
"},{"location":"troubleshooting.html#backup-configuration","title":"Backup Configuration","text":"

Regularly backup your configuration:

# Backup script\ntar -czf mcp-backup-$(date +%Y%m%d).tar.gz \\\n    .env \\\n    config/ \\\n    data/\n
"},{"location":"troubleshooting.html#faq","title":"FAQ","text":""},{"location":"troubleshooting.html#general-questions","title":"General Questions","text":""},{"location":"troubleshooting.html#q-what-is-mcp-server","title":"Q: What is MCP Server?","text":"

A: MCP Server is a bridge between Home Assistant and Language Learning Models, enabling natural language control and automation of your smart home devices.

"},{"location":"troubleshooting.html#q-what-are-the-system-requirements","title":"Q: What are the system requirements?","text":"

A: MCP Server requires: - Node.js 16 or higher - Home Assistant instance - 1GB RAM minimum - 1GB disk space

"},{"location":"troubleshooting.html#q-how-do-i-update-mcp-server","title":"Q: How do I update MCP Server?","text":"

A: For Docker installation:

docker compose pull\ndocker compose up -d\n
For manual installation:
git pull\nbun install\nbun run build\n

"},{"location":"troubleshooting.html#integration-questions","title":"Integration Questions","text":""},{"location":"troubleshooting.html#q-can-i-use-mcp-server-with-any-home-assistant-instance","title":"Q: Can I use MCP Server with any Home Assistant instance?","text":"

A: Yes, MCP Server works with any Home Assistant instance that has the REST API enabled and a valid long-lived access token.

"},{"location":"troubleshooting.html#q-does-mcp-server-support-all-home-assistant-integrations","title":"Q: Does MCP Server support all Home Assistant integrations?","text":"

A: MCP Server supports all Home Assistant devices and services that are accessible via the REST API.

"},{"location":"troubleshooting.html#security-questions","title":"Security Questions","text":""},{"location":"troubleshooting.html#q-is-my-home-assistant-token-secure","title":"Q: Is my Home Assistant token secure?","text":"

A: Yes, your Home Assistant token is stored securely and only used for authenticated communication between MCP Server and your Home Assistant instance.

"},{"location":"troubleshooting.html#q-can-i-use-mcp-server-remotely","title":"Q: Can I use MCP Server remotely?","text":"

A: Yes, but we recommend using a secure connection (HTTPS) and proper authentication when exposing MCP Server to the internet.

"},{"location":"troubleshooting.html#troubleshooting-questions","title":"Troubleshooting Questions","text":""},{"location":"troubleshooting.html#q-why-are-my-device-states-not-updating","title":"Q: Why are my device states not updating?","text":"

A: Check: 1. Home Assistant connection 2. WebSocket connection status 3. Device availability in Home Assistant 4. Network connectivity

"},{"location":"troubleshooting.html#q-why-are-my-commands-not-working","title":"Q: Why are my commands not working?","text":"

A: Verify: 1. Command syntax 2. Device availability 3. User permissions 4. Home Assistant API access

"},{"location":"usage.html","title":"Usage Guide","text":"

This guide explains how to use the Home Assistant MCP Server for basic device management and integration.

"},{"location":"usage.html#basic-setup","title":"Basic Setup","text":"
  1. Starting the Server:
  2. Development mode: bun run dev
  3. Production mode: bun run start

  4. Accessing the Server:

  5. Default URL: http://localhost:3000
  6. Ensure Home Assistant credentials are configured in .env
"},{"location":"usage.html#device-control","title":"Device Control","text":""},{"location":"usage.html#rest-api-interactions","title":"REST API Interactions","text":"

Basic device control can be performed via the REST API:

// Turn on a light\nfetch('http://localhost:3000/api/control', {\n  method: 'POST',\n  headers: {\n    'Content-Type': 'application/json',\n    'Authorization': `Bearer ${token}`\n  },\n  body: JSON.stringify({\n    entity_id: 'light.living_room',\n    command: 'turn_on',\n    parameters: { brightness: 50 }\n  })\n});\n
"},{"location":"usage.html#supported-commands","title":"Supported Commands","text":""},{"location":"usage.html#supported-entities","title":"Supported Entities","text":""},{"location":"usage.html#real-time-updates","title":"Real-Time Updates","text":""},{"location":"usage.html#websocket-connection","title":"WebSocket Connection","text":"

Subscribe to real-time device state changes:

const ws = new WebSocket('ws://localhost:3000/events');\nws.onmessage = (event) => {\n  const deviceUpdate = JSON.parse(event.data);\n  console.log('Device state changed:', deviceUpdate);\n};\n
"},{"location":"usage.html#authentication","title":"Authentication","text":"

All API requests require a valid JWT token in the Authorization header.

"},{"location":"usage.html#limitations","title":"Limitations","text":""},{"location":"usage.html#troubleshooting","title":"Troubleshooting","text":"
  1. Verify Home Assistant connection
  2. Check JWT token validity
  3. Ensure correct entity IDs
  4. Review server logs for detailed errors
"},{"location":"usage.html#configuration","title":"Configuration","text":"

Configure the server using environment variables in .env:

HA_URL=http://homeassistant:8123\nHA_TOKEN=your_home_assistant_token\nJWT_SECRET=your_jwt_secret\n
"},{"location":"usage.html#next-steps","title":"Next Steps","text":""},{"location":"api/index.html","title":"API Documentation \ud83d\udcda","text":"

Welcome to the MCP Server API documentation. This guide covers all available endpoints, authentication methods, and integration patterns.

"},{"location":"api/index.html#api-overview","title":"API Overview","text":"

The MCP Server provides several API categories:

  1. Core API - Basic device control and state management
  2. SSE API - Real-time event subscriptions
  3. Scene API - Scene management and automation
  4. Voice API - Natural language command processing
"},{"location":"api/index.html#authentication","title":"Authentication","text":"

All API endpoints require authentication using JWT tokens:

# Include the token in your requests\ncurl -H \"Authorization: Bearer YOUR_JWT_TOKEN\" http://localhost:3000/api/state\n

To obtain a token:

curl -X POST http://localhost:3000/auth/token \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"username\": \"your_username\", \"password\": \"your_password\"}'\n
"},{"location":"api/index.html#core-endpoints","title":"Core Endpoints","text":""},{"location":"api/index.html#device-state","title":"Device State","text":"
GET /api/state\n

Retrieve the current state of all devices:

curl http://localhost:3000/api/state\n

Response:

{\n  \"devices\": [\n    {\n      \"id\": \"light.living_room\",\n      \"state\": \"on\",\n      \"attributes\": {\n        \"brightness\": 255,\n        \"color_temp\": 370\n      }\n    }\n  ]\n}\n

"},{"location":"api/index.html#command-execution","title":"Command Execution","text":"
POST /api/command\n

Execute a natural language command:

curl -X POST http://localhost:3000/api/command \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"command\": \"Turn on the kitchen lights\"}'\n

Response:

{\n  \"success\": true,\n  \"action\": \"turn_on\",\n  \"device\": \"light.kitchen\",\n  \"message\": \"Kitchen lights turned on\"\n}\n

"},{"location":"api/index.html#real-time-events","title":"Real-Time Events","text":""},{"location":"api/index.html#event-subscription","title":"Event Subscription","text":"
GET /subscribe_events\n

Subscribe to device state changes:

const eventSource = new EventSource('http://localhost:3000/subscribe_events?token=YOUR_TOKEN');\n\neventSource.onmessage = (event) => {\n    const data = JSON.parse(event.data);\n    console.log('State changed:', data);\n};\n
"},{"location":"api/index.html#filtered-subscriptions","title":"Filtered Subscriptions","text":"

Subscribe to specific device types:

GET /subscribe_events?domain=light\nGET /subscribe_events?entity_id=light.living_room\n
"},{"location":"api/index.html#scene-management","title":"Scene Management","text":""},{"location":"api/index.html#create-scene","title":"Create Scene","text":"
POST /api/scene\n

Create a new scene:

curl -X POST http://localhost:3000/api/scene \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"Movie Night\",\n    \"actions\": [\n      {\"device\": \"light.living_room\", \"action\": \"dim\", \"value\": 20},\n      {\"device\": \"media_player.tv\", \"action\": \"on\"}\n    ]\n  }'\n
"},{"location":"api/index.html#activate-scene","title":"Activate Scene","text":"
POST /api/scene/activate\n

Activate an existing scene:

curl -X POST http://localhost:3000/api/scene/activate \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"name\": \"Movie Night\"}'\n
"},{"location":"api/index.html#error-handling","title":"Error Handling","text":"

The API uses standard HTTP status codes:

Error responses include detailed messages:

{\n  \"error\": true,\n  \"message\": \"Device not found\",\n  \"code\": \"DEVICE_NOT_FOUND\",\n  \"details\": {\n    \"device_id\": \"light.nonexistent\"\n  }\n}\n
"},{"location":"api/index.html#rate-limiting","title":"Rate Limiting","text":"

API requests are rate-limited to prevent abuse:

X-RateLimit-Limit: 100\nX-RateLimit-Remaining: 99\nX-RateLimit-Reset: 1640995200\n

When exceeded, returns 429 Too Many Requests:

{\n  \"error\": true,\n  \"message\": \"Rate limit exceeded\",\n  \"reset\": 1640995200\n}\n
"},{"location":"api/index.html#websocket-api","title":"WebSocket API","text":"

For bi-directional communication:

const ws = new WebSocket('ws://localhost:3000/ws');\n\nws.onmessage = (event) => {\n    const data = JSON.parse(event.data);\n    console.log('Received:', data);\n};\n\nws.send(JSON.stringify({\n    type: 'command',\n    payload: {\n        command: 'Turn on lights'\n    }\n}));\n
"},{"location":"api/index.html#api-versioning","title":"API Versioning","text":"

The current API version is v1. Include the version in the URL:

/api/v1/state\n/api/v1/command\n
"},{"location":"api/index.html#further-reading","title":"Further Reading","text":""},{"location":"api/index.html#api-reference","title":"API Reference","text":"

The Advanced Home Assistant MCP provides several APIs for integration and automation:

"},{"location":"api/core.html","title":"Core Functions API \ud83d\udd27","text":"

The Core Functions API provides the fundamental operations for interacting with Home Assistant devices and services through MCP Server.

"},{"location":"api/core.html#device-control","title":"Device Control","text":""},{"location":"api/core.html#get-device-state","title":"Get Device State","text":"

Retrieve the current state of devices.

GET /api/state\nGET /api/state/{entity_id}\n

Parameters: - entity_id (optional): Specific device ID to query

# Get all states\ncurl http://localhost:3000/api/state\n\n# Get specific device state\ncurl http://localhost:3000/api/state/light.living_room\n

Response:

{\n  \"entity_id\": \"light.living_room\",\n  \"state\": \"on\",\n  \"attributes\": {\n    \"brightness\": 255,\n    \"color_temp\": 370,\n    \"friendly_name\": \"Living Room Light\"\n  },\n  \"last_changed\": \"2024-01-20T15:30:00Z\"\n}\n

"},{"location":"api/core.html#control-device","title":"Control Device","text":"

Execute device commands.

POST /api/device/control\n

Request body:

{\n  \"entity_id\": \"light.living_room\",\n  \"action\": \"turn_on\",\n  \"parameters\": {\n    \"brightness\": 200,\n    \"color_temp\": 400\n  }\n}\n

Available actions: - turn_on - turn_off - toggle - set_value

Example with curl:

curl -X POST http://localhost:3000/api/device/control \\\n  -H \"Content-Type: application/json\" \\\n  -H \"Authorization: Bearer YOUR_JWT_TOKEN\" \\\n  -d '{\n    \"entity_id\": \"light.living_room\",\n    \"action\": \"turn_on\",\n    \"parameters\": {\n      \"brightness\": 200\n    }\n  }'\n

"},{"location":"api/core.html#natural-language-commands","title":"Natural Language Commands","text":""},{"location":"api/core.html#execute-command","title":"Execute Command","text":"

Process natural language commands.

POST /api/command\n

Request body:

{\n  \"command\": \"Turn on the living room lights and set them to 50% brightness\"\n}\n

Example usage:

curl -X POST http://localhost:3000/api/command \\\n  -H \"Content-Type: application/json\" \\\n  -H \"Authorization: Bearer YOUR_JWT_TOKEN\" \\\n  -d '{\n    \"command\": \"Turn on the living room lights and set them to 50% brightness\"\n  }'\n

Response:

{\n  \"success\": true,\n  \"actions\": [\n    {\n      \"entity_id\": \"light.living_room\",\n      \"action\": \"turn_on\",\n      \"parameters\": {\n        \"brightness\": 127\n      },\n      \"status\": \"completed\"\n    }\n  ],\n  \"message\": \"Command executed successfully\"\n}\n

"},{"location":"api/core.html#scene-management","title":"Scene Management","text":""},{"location":"api/core.html#create-scene","title":"Create Scene","text":"

Define a new scene with multiple actions.

POST /api/scene\n

Request body:

{\n  \"name\": \"Movie Night\",\n  \"description\": \"Perfect lighting for movie watching\",\n  \"actions\": [\n    {\n      \"entity_id\": \"light.living_room\",\n      \"action\": \"turn_on\",\n      \"parameters\": {\n        \"brightness\": 50,\n        \"color_temp\": 500\n      }\n    },\n    {\n      \"entity_id\": \"cover.living_room\",\n      \"action\": \"close\"\n    }\n  ]\n}\n

"},{"location":"api/core.html#activate-scene","title":"Activate Scene","text":"

Trigger a predefined scene.

POST /api/scene/{scene_name}/activate\n

Example:

curl -X POST http://localhost:3000/api/scene/movie_night/activate \\\n  -H \"Authorization: Bearer YOUR_JWT_TOKEN\"\n

"},{"location":"api/core.html#groups","title":"Groups","text":""},{"location":"api/core.html#create-device-group","title":"Create Device Group","text":"

Create a group of devices for collective control.

POST /api/group\n

Request body:

{\n  \"name\": \"Living Room\",\n  \"entities\": [\n    \"light.living_room_main\",\n    \"light.living_room_accent\",\n    \"switch.living_room_fan\"\n  ]\n}\n

"},{"location":"api/core.html#control-group","title":"Control Group","text":"

Control multiple devices in a group.

POST /api/group/{group_name}/control\n

Request body:

{\n  \"action\": \"turn_off\"\n}\n

"},{"location":"api/core.html#system-operations","title":"System Operations","text":""},{"location":"api/core.html#health-check","title":"Health Check","text":"

Check server status and connectivity.

GET /health\n

Response:

{\n  \"status\": \"healthy\",\n  \"version\": \"1.0.0\",\n  \"uptime\": 3600,\n  \"homeAssistant\": {\n    \"connected\": true,\n    \"version\": \"2024.1.0\"\n  }\n}\n

"},{"location":"api/core.html#configuration","title":"Configuration","text":"

Get current server configuration.

GET /api/config\n

Response:

{\n  \"server\": {\n    \"port\": 3000,\n    \"host\": \"0.0.0.0\",\n    \"version\": \"1.0.0\"\n  },\n  \"homeAssistant\": {\n    \"url\": \"http://homeassistant:8123\",\n    \"connected\": true\n  },\n  \"features\": {\n    \"nlp\": true,\n    \"scenes\": true,\n    \"groups\": true\n  }\n}\n

"},{"location":"api/core.html#error-handling","title":"Error Handling","text":"

All endpoints follow standard HTTP status codes and return detailed error messages:

{\n  \"error\": true,\n  \"code\": \"INVALID_ENTITY\",\n  \"message\": \"Device 'light.nonexistent' not found\",\n  \"details\": {\n    \"entity_id\": \"light.nonexistent\",\n    \"available_entities\": [\n      \"light.living_room\",\n      \"light.kitchen\"\n    ]\n  }\n}\n

Common error codes: - INVALID_ENTITY: Device not found - INVALID_ACTION: Unsupported action - INVALID_PARAMETERS: Invalid command parameters - AUTHENTICATION_ERROR: Invalid or missing token - CONNECTION_ERROR: Home Assistant connection issue

"},{"location":"api/core.html#typescript-interfaces","title":"TypeScript Interfaces","text":"
interface DeviceState {\n  entity_id: string;\n  state: string;\n  attributes: Record<string, any>;\n  last_changed: string;\n}\n\ninterface DeviceCommand {\n  entity_id: string;\n  action: 'turn_on' | 'turn_off' | 'toggle' | 'set_value';\n  parameters?: Record<string, any>;\n}\n\ninterface Scene {\n  name: string;\n  description?: string;\n  actions: DeviceCommand[];\n}\n\ninterface Group {\n  name: string;\n  entities: string[];\n}\n
"},{"location":"api/core.html#related-resources","title":"Related Resources","text":""},{"location":"api/sse.html","title":"Server-Sent Events (SSE) API \ud83d\udce1","text":"

The SSE API provides real-time updates about device states and events from your Home Assistant setup. This guide covers how to use and implement SSE connections in your applications.

"},{"location":"api/sse.html#overview","title":"Overview","text":"

Server-Sent Events (SSE) is a standard that enables servers to push real-time updates to clients over HTTP connections. MCP Server uses SSE to provide:

"},{"location":"api/sse.html#basic-usage","title":"Basic Usage","text":""},{"location":"api/sse.html#establishing-a-connection","title":"Establishing a Connection","text":"

Create an EventSource connection to receive updates:

const eventSource = new EventSource('http://localhost:3000/subscribe_events?token=YOUR_JWT_TOKEN');\n\neventSource.onmessage = (event) => {\n    const data = JSON.parse(event.data);\n    console.log('Received update:', data);\n};\n
"},{"location":"api/sse.html#connection-states","title":"Connection States","text":"

Handle different connection states:

eventSource.onopen = () => {\n    console.log('Connection established');\n};\n\neventSource.onerror = (error) => {\n    console.error('Connection error:', error);\n    // Implement reconnection logic if needed\n};\n
"},{"location":"api/sse.html#event-types","title":"Event Types","text":""},{"location":"api/sse.html#device-state-events","title":"Device State Events","text":"

Subscribe to all device state changes:

const stateEvents = new EventSource('http://localhost:3000/subscribe_events?type=state');\n\nstateEvents.onmessage = (event) => {\n    const state = JSON.parse(event.data);\n    console.log('Device state changed:', state);\n};\n

Example state event:

{\n  \"type\": \"state_changed\",\n  \"entity_id\": \"light.living_room\",\n  \"state\": \"on\",\n  \"attributes\": {\n    \"brightness\": 255,\n    \"color_temp\": 370\n  },\n  \"timestamp\": \"2024-01-20T15:30:00Z\"\n}\n

"},{"location":"api/sse.html#filtered-subscriptions","title":"Filtered Subscriptions","text":""},{"location":"api/sse.html#by-domain","title":"By Domain","text":"

Subscribe to specific device types:

// Subscribe to only light events\nconst lightEvents = new EventSource('http://localhost:3000/subscribe_events?domain=light');\n\n// Subscribe to multiple domains\nconst multiEvents = new EventSource('http://localhost:3000/subscribe_events?domain=light,switch,sensor');\n
"},{"location":"api/sse.html#by-entity-id","title":"By Entity ID","text":"

Subscribe to specific devices:

// Single entity\nconst livingRoomLight = new EventSource(\n    'http://localhost:3000/subscribe_events?entity_id=light.living_room'\n);\n\n// Multiple entities\nconst kitchenDevices = new EventSource(\n    'http://localhost:3000/subscribe_events?entity_id=light.kitchen,switch.coffee_maker'\n);\n
"},{"location":"api/sse.html#advanced-usage","title":"Advanced Usage","text":""},{"location":"api/sse.html#connection-management","title":"Connection Management","text":"

Implement robust connection handling:

class SSEManager {\n    constructor(url, options = {}) {\n        this.url = url;\n        this.options = {\n            maxRetries: 3,\n            retryDelay: 1000,\n            ...options\n        };\n        this.retryCount = 0;\n        this.connect();\n    }\n\n    connect() {\n        this.eventSource = new EventSource(this.url);\n\n        this.eventSource.onopen = () => {\n            this.retryCount = 0;\n            console.log('Connected to SSE stream');\n        };\n\n        this.eventSource.onerror = (error) => {\n            this.handleError(error);\n        };\n\n        this.eventSource.onmessage = (event) => {\n            this.handleMessage(event);\n        };\n    }\n\n    handleError(error) {\n        console.error('SSE Error:', error);\n        this.eventSource.close();\n\n        if (this.retryCount < this.options.maxRetries) {\n            this.retryCount++;\n            setTimeout(() => {\n                console.log(`Retrying connection (${this.retryCount}/${this.options.maxRetries})`);\n                this.connect();\n            }, this.options.retryDelay * this.retryCount);\n        }\n    }\n\n    handleMessage(event) {\n        try {\n            const data = JSON.parse(event.data);\n            // Handle the event data\n            console.log('Received:', data);\n        } catch (error) {\n            console.error('Error parsing SSE data:', error);\n        }\n    }\n\n    disconnect() {\n        if (this.eventSource) {\n            this.eventSource.close();\n        }\n    }\n}\n\n// Usage\nconst sseManager = new SSEManager('http://localhost:3000/subscribe_events?token=YOUR_TOKEN');\n
"},{"location":"api/sse.html#event-filtering","title":"Event Filtering","text":"

Filter events on the client side:

class EventFilter {\n    constructor(conditions) {\n        this.conditions = conditions;\n    }\n\n    matches(event) {\n        return Object.entries(this.conditions).every(([key, value]) => {\n            if (Array.isArray(value)) {\n                return value.includes(event[key]);\n            }\n            return event[key] === value;\n        });\n    }\n}\n\n// Usage\nconst filter = new EventFilter({\n    domain: ['light', 'switch'],\n    state: 'on'\n});\n\neventSource.onmessage = (event) => {\n    const data = JSON.parse(event.data);\n    if (filter.matches(data)) {\n        console.log('Matched event:', data);\n    }\n};\n
"},{"location":"api/sse.html#best-practices","title":"Best Practices","text":"
  1. Authentication
  2. Always include authentication tokens
  3. Implement token refresh mechanisms
  4. Handle authentication errors gracefully

  5. Error Handling

  6. Implement progressive retry logic
  7. Log connection issues
  8. Notify users of connection status

  9. Resource Management

  10. Close EventSource connections when not needed
  11. Limit the number of concurrent connections
  12. Use filtered subscriptions when possible

  13. Performance

  14. Process events efficiently
  15. Batch UI updates
  16. Consider debouncing frequent updates
"},{"location":"api/sse.html#common-issues","title":"Common Issues","text":""},{"location":"api/sse.html#connection-drops","title":"Connection Drops","text":"

If the connection drops, the EventSource will automatically attempt to reconnect. You can customize this behavior:

eventSource.addEventListener('error', (error) => {\n    if (eventSource.readyState === EventSource.CLOSED) {\n        // Connection closed, implement custom retry logic\n    }\n});\n
"},{"location":"api/sse.html#memory-leaks","title":"Memory Leaks","text":"

Always clean up EventSource connections:

// In a React component\nuseEffect(() => {\n    const eventSource = new EventSource('http://localhost:3000/subscribe_events');\n\n    return () => {\n        eventSource.close(); // Cleanup on unmount\n    };\n}, []);\n
"},{"location":"api/sse.html#related-resources","title":"Related Resources","text":""},{"location":"config/index.html","title":"Configuration","text":"

This section covers the configuration options available in the Home Assistant MCP Server.

"},{"location":"config/index.html#overview","title":"Overview","text":"

The MCP Server can be configured through various configuration files and environment variables. This section will guide you through the available options and their usage.

"},{"location":"config/index.html#configuration-files","title":"Configuration Files","text":"

The main configuration files are:

  1. .env - Environment variables
  2. config.yaml - Main configuration file
  3. devices.yaml - Device-specific configurations
"},{"location":"config/index.html#environment-variables","title":"Environment Variables","text":"

Key environment variables that can be set:

"},{"location":"config/index.html#next-steps","title":"Next Steps","text":""},{"location":"development/index.html","title":"Development Guide","text":"

Welcome to the development guide for the Home Assistant MCP Server. This section provides comprehensive information for developers who want to contribute to or extend the project.

"},{"location":"development/index.html#development-overview","title":"Development Overview","text":"

The MCP Server is built with modern development practices in mind, focusing on:

"},{"location":"development/index.html#getting-started","title":"Getting Started","text":"
  1. Set up your development environment
  2. Fork the repository
  3. Install dependencies
  4. Run tests
  5. Make your changes
  6. Submit a pull request
"},{"location":"development/index.html#development-topics","title":"Development Topics","text":""},{"location":"development/index.html#best-practices","title":"Best Practices","text":""},{"location":"development/index.html#development-workflow","title":"Development Workflow","text":"
  1. Create a feature branch
  2. Make your changes
  3. Run tests
  4. Update documentation
  5. Submit a pull request
  6. Address review comments
  7. Merge when approved
"},{"location":"development/index.html#next-steps","title":"Next Steps","text":""},{"location":"development/best-practices.html","title":"Development Best Practices","text":"

This guide outlines the best practices for developing tools and features for the Home Assistant MCP.

"},{"location":"development/best-practices.html#code-style","title":"Code Style","text":""},{"location":"development/best-practices.html#typescript","title":"TypeScript","text":"
  1. Use TypeScript for all new code
  2. Enable strict mode
  3. Use explicit types
  4. Avoid any type
  5. Use interfaces over types
  6. Document with JSDoc comments
/** \n * Represents a device in the system.\n * @interface\n */\ninterface Device {\n    /** Unique device identifier */\n    id: string;\n\n    /** Human-readable device name */\n    name: string;\n\n    /** Device state */\n    state: DeviceState;\n}\n
"},{"location":"development/best-practices.html#naming-conventions","title":"Naming Conventions","text":"
  1. Use PascalCase for:
  2. Classes
  3. Interfaces
  4. Types
  5. Enums

  6. Use camelCase for:

  7. Variables
  8. Functions
  9. Methods
  10. Properties

  11. Use UPPER_SNAKE_CASE for:

  12. Constants
  13. Enum values
class DeviceManager {\n    private readonly DEFAULT_TIMEOUT = 5000;\n\n    async getDeviceState(deviceId: string): Promise<DeviceState> {\n        // Implementation\n    }\n}\n
"},{"location":"development/best-practices.html#architecture","title":"Architecture","text":""},{"location":"development/best-practices.html#solid-principles","title":"SOLID Principles","text":"
  1. Single Responsibility
  2. Each class/module has one job
  3. Split complex functionality

  4. Open/Closed

  5. Open for extension
  6. Closed for modification

  7. Liskov Substitution

  8. Subtypes must be substitutable
  9. Use interfaces properly

  10. Interface Segregation

  11. Keep interfaces focused
  12. Split large interfaces

  13. Dependency Inversion

  14. Depend on abstractions
  15. Use dependency injection
"},{"location":"development/best-practices.html#example","title":"Example","text":"
// Bad\nclass DeviceManager {\n    async getState() { /* ... */ }\n    async setState() { /* ... */ }\n    async sendNotification() { /* ... */ }  // Wrong responsibility\n}\n\n// Good\nclass DeviceManager {\n    constructor(\n        private notifier: NotificationService\n    ) {}\n\n    async getState() { /* ... */ }\n    async setState() { /* ... */ }\n}\n\nclass NotificationService {\n    async send() { /* ... */ }\n}\n
"},{"location":"development/best-practices.html#error-handling","title":"Error Handling","text":""},{"location":"development/best-practices.html#best-practices","title":"Best Practices","text":"
  1. Use custom error classes
  2. Include error codes
  3. Provide meaningful messages
  4. Include error context
  5. Handle async errors
  6. Log appropriately
class DeviceError extends Error {\n    constructor(\n        message: string,\n        public code: string,\n        public context: Record<string, any>\n    ) {\n        super(message);\n        this.name = 'DeviceError';\n    }\n}\n\ntry {\n    await device.connect();\n} catch (error) {\n    throw new DeviceError(\n        'Failed to connect to device',\n        'DEVICE_CONNECTION_ERROR',\n        { deviceId: device.id, attempt: 1 }\n    );\n}\n
"},{"location":"development/best-practices.html#testing","title":"Testing","text":""},{"location":"development/best-practices.html#guidelines","title":"Guidelines","text":"
  1. Write unit tests first
  2. Use meaningful descriptions
  3. Test edge cases
  4. Mock external dependencies
  5. Keep tests focused
  6. Use test fixtures
describe('DeviceManager', () => {\n    let manager: DeviceManager;\n    let mockDevice: jest.Mocked<Device>;\n\n    beforeEach(() => {\n        mockDevice = {\n            id: 'test_device',\n            getState: jest.fn()\n        };\n        manager = new DeviceManager(mockDevice);\n    });\n\n    it('should get device state', async () => {\n        mockDevice.getState.mockResolvedValue('on');\n        const state = await manager.getDeviceState();\n        expect(state).toBe('on');\n    });\n});\n
"},{"location":"development/best-practices.html#performance","title":"Performance","text":""},{"location":"development/best-practices.html#optimization","title":"Optimization","text":"
  1. Use caching
  2. Implement pagination
  3. Optimize database queries
  4. Use connection pooling
  5. Implement rate limiting
  6. Batch operations
class DeviceCache {\n    private cache = new Map<string, CacheEntry>();\n    private readonly TTL = 60000;  // 1 minute\n\n    async getDevice(id: string): Promise<Device> {\n        const cached = this.cache.get(id);\n        if (cached && Date.now() - cached.timestamp < this.TTL) {\n            return cached.device;\n        }\n\n        const device = await this.fetchDevice(id);\n        this.cache.set(id, {\n            device,\n            timestamp: Date.now()\n        });\n\n        return device;\n    }\n}\n
"},{"location":"development/best-practices.html#security","title":"Security","text":""},{"location":"development/best-practices.html#guidelines_1","title":"Guidelines","text":"
  1. Validate all input
  2. Use parameterized queries
  3. Implement rate limiting
  4. Use proper authentication
  5. Follow OWASP guidelines
  6. Sanitize output
class InputValidator {\n    static validateDeviceId(id: string): boolean {\n        return /^[a-zA-Z0-9_-]{1,64}$/.test(id);\n    }\n\n    static sanitizeOutput(data: any): any {\n        // Implement output sanitization\n        return data;\n    }\n}\n
"},{"location":"development/best-practices.html#documentation","title":"Documentation","text":""},{"location":"development/best-practices.html#standards","title":"Standards","text":"
  1. Use JSDoc comments
  2. Document interfaces
  3. Include examples
  4. Document errors
  5. Keep docs updated
  6. Use markdown
/**\n * Manages device operations.\n * @class\n */\nclass DeviceManager {\n    /**\n     * Gets the current state of a device.\n     * @param {string} deviceId - The device identifier.\n     * @returns {Promise<DeviceState>} The current device state.\n     * @throws {DeviceError} If device is not found or unavailable.\n     * @example\n     * const state = await deviceManager.getDeviceState('living_room_light');\n     */\n    async getDeviceState(deviceId: string): Promise<DeviceState> {\n        // Implementation\n    }\n}\n
"},{"location":"development/best-practices.html#logging","title":"Logging","text":""},{"location":"development/best-practices.html#best-practices_1","title":"Best Practices","text":"
  1. Use appropriate levels
  2. Include context
  3. Structure log data
  4. Handle sensitive data
  5. Implement rotation
  6. Use correlation IDs
class Logger {\n    info(message: string, context: Record<string, any>) {\n        console.log(JSON.stringify({\n            level: 'info',\n            message,\n            context,\n            timestamp: new Date().toISOString(),\n            correlationId: context.correlationId\n        }));\n    }\n}\n
"},{"location":"development/best-practices.html#version-control","title":"Version Control","text":""},{"location":"development/best-practices.html#guidelines_2","title":"Guidelines","text":"
  1. Use meaningful commits
  2. Follow branching strategy
  3. Write good PR descriptions
  4. Review code thoroughly
  5. Keep changes focused
  6. Use conventional commits
# Good commit messages\ngit commit -m \"feat(device): add support for zigbee devices\"\ngit commit -m \"fix(api): handle timeout errors properly\"\n
"},{"location":"development/best-practices.html#see-also","title":"See Also","text":""},{"location":"development/environment.html","title":"Development Environment Setup","text":"

This guide will help you set up your development environment for the Home Assistant MCP Server.

"},{"location":"development/environment.html#prerequisites","title":"Prerequisites","text":""},{"location":"development/environment.html#required-software","title":"Required Software","text":""},{"location":"development/environment.html#system-requirements","title":"System Requirements","text":""},{"location":"development/environment.html#initial-setup","title":"Initial Setup","text":"
  1. Clone the Repository

    git clone https://github.com/jango-blockchained/homeassistant-mcp.git\ncd homeassistant-mcp\n

  2. Create Virtual Environment

    python -m venv .venv\nsource .venv/bin/activate  # Linux/macOS\n# or\n.venv\\Scripts\\activate  # Windows\n

  3. Install Dependencies

    pip install -r requirements.txt\npip install -r docs/requirements.txt  # for documentation\n

"},{"location":"development/environment.html#development-tools","title":"Development Tools","text":""},{"location":"development/environment.html#code-editor-setup","title":"Code Editor Setup","text":"

We recommend using Visual Studio Code with these extensions: - Python - Docker - YAML - ESLint - Prettier

"},{"location":"development/environment.html#vs-code-settings","title":"VS Code Settings","text":"
{\n  \"python.linting.enabled\": true,\n  \"python.linting.pylintEnabled\": true,\n  \"python.formatting.provider\": \"black\",\n  \"editor.formatOnSave\": true\n}\n
"},{"location":"development/environment.html#configuration","title":"Configuration","text":"
  1. Create Local Config

    cp config.example.yaml config.yaml\n

  2. Set Environment Variables

    cp .env.example .env\n# Edit .env with your settings\n

"},{"location":"development/environment.html#running-tests","title":"Running Tests","text":""},{"location":"development/environment.html#unit-tests","title":"Unit Tests","text":"
pytest tests/unit\n
"},{"location":"development/environment.html#integration-tests","title":"Integration Tests","text":"
pytest tests/integration\n
"},{"location":"development/environment.html#coverage-report","title":"Coverage Report","text":"
pytest --cov=src tests/\n
"},{"location":"development/environment.html#docker-development","title":"Docker Development","text":""},{"location":"development/environment.html#build-container","title":"Build Container","text":"
docker build -t mcp-server-dev -f Dockerfile.dev .\n
"},{"location":"development/environment.html#run-development-container","title":"Run Development Container","text":"
docker run -it --rm \\\n  -v $(pwd):/app \\\n  -p 8123:8123 \\\n  mcp-server-dev\n
"},{"location":"development/environment.html#database-setup","title":"Database Setup","text":""},{"location":"development/environment.html#local-development-database","title":"Local Development Database","text":"
docker run -d \\\n  -p 5432:5432 \\\n  -e POSTGRES_USER=mcp \\\n  -e POSTGRES_PASSWORD=development \\\n  -e POSTGRES_DB=mcp_dev \\\n  postgres:14\n
"},{"location":"development/environment.html#run-migrations","title":"Run Migrations","text":"
alembic upgrade head\n
"},{"location":"development/environment.html#frontend-development","title":"Frontend Development","text":"
  1. Install Node.js Dependencies

    cd frontend\nnpm install\n

  2. Start Development Server

    npm run dev\n

"},{"location":"development/environment.html#documentation","title":"Documentation","text":""},{"location":"development/environment.html#build-documentation","title":"Build Documentation","text":"
mkdocs serve\n
"},{"location":"development/environment.html#view-documentation","title":"View Documentation","text":"

Open http://localhost:8000 in your browser

"},{"location":"development/environment.html#debugging","title":"Debugging","text":""},{"location":"development/environment.html#vs-code-launch-configuration","title":"VS Code Launch Configuration","text":"
{\n  \"version\": \"0.2.0\",\n  \"configurations\": [\n    {\n      \"name\": \"Python: MCP Server\",\n      \"type\": \"python\",\n      \"request\": \"launch\",\n      \"program\": \"src/main.py\",\n      \"console\": \"integratedTerminal\"\n    }\n  ]\n}\n
"},{"location":"development/environment.html#git-hooks","title":"Git Hooks","text":""},{"location":"development/environment.html#install-pre-commit","title":"Install Pre-commit","text":"
pip install pre-commit\npre-commit install\n
"},{"location":"development/environment.html#available-hooks","title":"Available Hooks","text":""},{"location":"development/environment.html#troubleshooting","title":"Troubleshooting","text":"

Common Issues: 1. Port already in use - Check for running processes: lsof -i :8123 - Kill process if needed: kill -9 PID

  1. Database connection issues
  2. Verify PostgreSQL is running
  3. Check connection settings in .env

  4. Virtual environment problems

  5. Delete and recreate: rm -rf .venv && python -m venv .venv
  6. Reinstall dependencies
"},{"location":"development/environment.html#next-steps","title":"Next Steps","text":"
  1. Review the Architecture Guide
  2. Check Contributing Guidelines
  3. Start with Simple Issues
"},{"location":"development/interfaces.html","title":"Interface Documentation","text":"

This document describes the core interfaces used throughout the Home Assistant MCP.

"},{"location":"development/interfaces.html#core-interfaces","title":"Core Interfaces","text":""},{"location":"development/interfaces.html#tool-interface","title":"Tool Interface","text":"
interface Tool {\n    /** Unique identifier for the tool */\n    id: string;\n\n    /** Human-readable name */\n    name: string;\n\n    /** Detailed description */\n    description: string;\n\n    /** Semantic version */\n    version: string;\n\n    /** Tool category */\n    category: ToolCategory;\n\n    /** Execute tool functionality */\n    execute(params: any): Promise<ToolResult>;\n}\n
"},{"location":"development/interfaces.html#tool-result","title":"Tool Result","text":"
interface ToolResult {\n    /** Operation success status */\n    success: boolean;\n\n    /** Response data */\n    data?: any;\n\n    /** Error message if failed */\n    message?: string;\n\n    /** Error code if failed */\n    error_code?: string;\n}\n
"},{"location":"development/interfaces.html#tool-category","title":"Tool Category","text":"
enum ToolCategory {\n    DeviceManagement = 'device_management',\n    HistoryState = 'history_state',\n    Automation = 'automation',\n    AddonsPackages = 'addons_packages',\n    Notifications = 'notifications',\n    Events = 'events',\n    Utility = 'utility'\n}\n
"},{"location":"development/interfaces.html#event-interfaces","title":"Event Interfaces","text":""},{"location":"development/interfaces.html#event-subscription","title":"Event Subscription","text":"
interface EventSubscription {\n    /** Unique subscription ID */\n    id: string;\n\n    /** Event type to subscribe to */\n    event_type: string;\n\n    /** Optional entity ID filter */\n    entity_id?: string;\n\n    /** Optional domain filter */\n    domain?: string;\n\n    /** Subscription creation timestamp */\n    created_at: string;\n\n    /** Last event timestamp */\n    last_event?: string;\n}\n
"},{"location":"development/interfaces.html#event-message","title":"Event Message","text":"
interface EventMessage {\n    /** Event type */\n    event_type: string;\n\n    /** Entity ID if applicable */\n    entity_id?: string;\n\n    /** Event data */\n    data: any;\n\n    /** Event origin */\n    origin: 'LOCAL' | 'REMOTE';\n\n    /** Event timestamp */\n    time_fired: string;\n\n    /** Event context */\n    context: EventContext;\n}\n
"},{"location":"development/interfaces.html#device-interfaces","title":"Device Interfaces","text":""},{"location":"development/interfaces.html#device","title":"Device","text":"
interface Device {\n    /** Device ID */\n    id: string;\n\n    /** Device name */\n    name: string;\n\n    /** Device domain */\n    domain: string;\n\n    /** Current state */\n    state: string;\n\n    /** Device attributes */\n    attributes: Record<string, any>;\n\n    /** Device capabilities */\n    capabilities: DeviceCapabilities;\n}\n
"},{"location":"development/interfaces.html#device-capabilities","title":"Device Capabilities","text":"
interface DeviceCapabilities {\n    /** Supported features */\n    features: string[];\n\n    /** Supported commands */\n    commands: string[];\n\n    /** State attributes */\n    attributes: {\n        /** Attribute name */\n        [key: string]: {\n            /** Attribute type */\n            type: 'string' | 'number' | 'boolean' | 'object';\n            /** Attribute description */\n            description: string;\n            /** Optional value constraints */\n            constraints?: {\n                min?: number;\n                max?: number;\n                enum?: any[];\n            };\n        };\n    };\n}\n
"},{"location":"development/interfaces.html#authentication-interfaces","title":"Authentication Interfaces","text":""},{"location":"development/interfaces.html#auth-token","title":"Auth Token","text":"
interface AuthToken {\n    /** Token value */\n    token: string;\n\n    /** Token type */\n    type: 'bearer' | 'jwt';\n\n    /** Expiration timestamp */\n    expires_at: string;\n\n    /** Token refresh info */\n    refresh?: {\n        token: string;\n        expires_at: string;\n    };\n}\n
"},{"location":"development/interfaces.html#user","title":"User","text":"
interface User {\n    /** User ID */\n    id: string;\n\n    /** Username */\n    username: string;\n\n    /** User type */\n    type: 'admin' | 'user' | 'service';\n\n    /** User permissions */\n    permissions: string[];\n}\n
"},{"location":"development/interfaces.html#error-interfaces","title":"Error Interfaces","text":""},{"location":"development/interfaces.html#tool-error","title":"Tool Error","text":"
interface ToolError extends Error {\n    /** Error code */\n    code: string;\n\n    /** HTTP status code */\n    status: number;\n\n    /** Error details */\n    details?: Record<string, any>;\n}\n
"},{"location":"development/interfaces.html#validation-error","title":"Validation Error","text":"
interface ValidationError {\n    /** Error path */\n    path: string;\n\n    /** Error message */\n    message: string;\n\n    /** Error code */\n    code: string;\n}\n
"},{"location":"development/interfaces.html#configuration-interfaces","title":"Configuration Interfaces","text":""},{"location":"development/interfaces.html#tool-configuration","title":"Tool Configuration","text":"
interface ToolConfig {\n    /** Enable/disable tool */\n    enabled: boolean;\n\n    /** Tool-specific settings */\n    settings: Record<string, any>;\n\n    /** Rate limiting */\n    rate_limit?: {\n        /** Max requests */\n        max: number;\n        /** Time window in seconds */\n        window: number;\n    };\n}\n
"},{"location":"development/interfaces.html#system-configuration","title":"System Configuration","text":"
interface SystemConfig {\n    /** System name */\n    name: string;\n\n    /** Environment */\n    environment: 'development' | 'production';\n\n    /** Log level */\n    log_level: 'debug' | 'info' | 'warn' | 'error';\n\n    /** Tool configurations */\n    tools: Record<string, ToolConfig>;\n}\n
"},{"location":"development/interfaces.html#best-practices","title":"Best Practices","text":"
  1. Use TypeScript for all interfaces
  2. Include JSDoc comments
  3. Use strict typing
  4. Keep interfaces focused
  5. Use consistent naming
  6. Document constraints
  7. Version interfaces
  8. Include examples
"},{"location":"development/interfaces.html#see-also","title":"See Also","text":""},{"location":"development/test-migration-guide.html","title":"Migrating Tests from Jest to Bun","text":"

This guide provides instructions for migrating test files from Jest to Bun's test framework.

"},{"location":"development/test-migration-guide.html#table-of-contents","title":"Table of Contents","text":""},{"location":"development/test-migration-guide.html#basic-setup","title":"Basic Setup","text":"
  1. Remove Jest-related dependencies from package.json:

    {\n  \"devDependencies\": {\n    \"@jest/globals\": \"...\",\n    \"jest\": \"...\",\n    \"ts-jest\": \"...\"\n  }\n}\n

  2. Remove Jest configuration files:

  3. jest.config.js
  4. jest.setup.js

  5. Update test scripts in package.json:

    {\n  \"scripts\": {\n    \"test\": \"bun test\",\n    \"test:watch\": \"bun test --watch\",\n    \"test:coverage\": \"bun test --coverage\"\n  }\n}\n

"},{"location":"development/test-migration-guide.html#import-changes","title":"Import Changes","text":""},{"location":"development/test-migration-guide.html#before-jest","title":"Before (Jest):","text":"
import { jest, describe, it, expect, beforeEach, afterEach } from '@jest/globals';\n
"},{"location":"development/test-migration-guide.html#after-bun","title":"After (Bun):","text":"
import { describe, expect, test, beforeEach, afterEach, mock } from \"bun:test\";\nimport type { Mock } from \"bun:test\";\n

Note: it is replaced with test in Bun.

"},{"location":"development/test-migration-guide.html#api-changes","title":"API Changes","text":""},{"location":"development/test-migration-guide.html#test-structure","title":"Test Structure","text":"
// Jest\ndescribe('Suite', () => {\n  it('should do something', () => {\n    // test\n  });\n});\n\n// Bun\ndescribe('Suite', () => {\n  test('should do something', () => {\n    // test\n  });\n});\n
"},{"location":"development/test-migration-guide.html#assertions","title":"Assertions","text":"

Most Jest assertions work the same in Bun:

// These work the same in both:\nexpect(value).toBe(expected);\nexpect(value).toEqual(expected);\nexpect(value).toBeDefined();\nexpect(value).toBeUndefined();\nexpect(value).toBeTruthy();\nexpect(value).toBeFalsy();\nexpect(array).toContain(item);\nexpect(value).toBeInstanceOf(Class);\nexpect(spy).toHaveBeenCalled();\nexpect(spy).toHaveBeenCalledWith(...args);\n
"},{"location":"development/test-migration-guide.html#mocking","title":"Mocking","text":""},{"location":"development/test-migration-guide.html#function-mocking","title":"Function Mocking","text":""},{"location":"development/test-migration-guide.html#before-jest_1","title":"Before (Jest):","text":"
const mockFn = jest.fn();\nmockFn.mockImplementation(() => 'result');\nmockFn.mockResolvedValue('result');\nmockFn.mockRejectedValue(new Error());\n
"},{"location":"development/test-migration-guide.html#after-bun_1","title":"After (Bun):","text":"
const mockFn = mock(() => 'result');\nconst mockAsyncFn = mock(() => Promise.resolve('result'));\nconst mockErrorFn = mock(() => Promise.reject(new Error()));\n
"},{"location":"development/test-migration-guide.html#module-mocking","title":"Module Mocking","text":""},{"location":"development/test-migration-guide.html#before-jest_2","title":"Before (Jest):","text":"
jest.mock('module-name', () => ({\n  default: jest.fn(),\n  namedExport: jest.fn()\n}));\n
"},{"location":"development/test-migration-guide.html#after-bun_2","title":"After (Bun):","text":"
// Option 1: Using vi.mock (if available)\nvi.mock('module-name', () => ({\n  default: mock(() => {}),\n  namedExport: mock(() => {})\n}));\n\n// Option 2: Using dynamic imports\nconst mockModule = {\n  default: mock(() => {}),\n  namedExport: mock(() => {})\n};\n
"},{"location":"development/test-migration-guide.html#mock-resetclear","title":"Mock Reset/Clear","text":""},{"location":"development/test-migration-guide.html#before-jest_3","title":"Before (Jest):","text":"
jest.clearAllMocks();\nmockFn.mockClear();\njest.resetModules();\n
"},{"location":"development/test-migration-guide.html#after-bun_3","title":"After (Bun):","text":"
mockFn.mockReset();\n// or for specific calls\nmockFn.mock.calls = [];\n
"},{"location":"development/test-migration-guide.html#spy-on-methods","title":"Spy on Methods","text":""},{"location":"development/test-migration-guide.html#before-jest_4","title":"Before (Jest):","text":"
jest.spyOn(object, 'method');\n
"},{"location":"development/test-migration-guide.html#after-bun_4","title":"After (Bun):","text":"
const spy = mock(((...args) => object.method(...args)));\nobject.method = spy;\n
"},{"location":"development/test-migration-guide.html#common-patterns","title":"Common Patterns","text":""},{"location":"development/test-migration-guide.html#async-tests","title":"Async Tests","text":"
// Works the same in both Jest and Bun:\ntest('async test', async () => {\n  const result = await someAsyncFunction();\n  expect(result).toBe(expected);\n});\n
"},{"location":"development/test-migration-guide.html#setup-and-teardown","title":"Setup and Teardown","text":"
describe('Suite', () => {\n  beforeEach(() => {\n    // setup\n  });\n\n  afterEach(() => {\n    // cleanup\n  });\n\n  test('test', () => {\n    // test\n  });\n});\n
"},{"location":"development/test-migration-guide.html#mocking-fetch","title":"Mocking Fetch","text":"
// Before (Jest)\nglobal.fetch = jest.fn(() => Promise.resolve(new Response()));\n\n// After (Bun)\nconst mockFetch = mock(() => Promise.resolve(new Response()));\nglobal.fetch = mockFetch as unknown as typeof fetch;\n
"},{"location":"development/test-migration-guide.html#mocking-websocket","title":"Mocking WebSocket","text":"
// Create a MockWebSocket class implementing WebSocket interface\nclass MockWebSocket implements WebSocket {\n  public static readonly CONNECTING = 0;\n  public static readonly OPEN = 1;\n  public static readonly CLOSING = 2;\n  public static readonly CLOSED = 3;\n\n  public readyState: 0 | 1 | 2 | 3 = MockWebSocket.OPEN;\n  public addEventListener = mock(() => undefined);\n  public removeEventListener = mock(() => undefined);\n  public send = mock(() => undefined);\n  public close = mock(() => undefined);\n  // ... implement other required methods\n}\n\n// Use it in tests\nglobal.WebSocket = MockWebSocket as unknown as typeof WebSocket;\n
"},{"location":"development/test-migration-guide.html#examples","title":"Examples","text":""},{"location":"development/test-migration-guide.html#basic-test","title":"Basic Test","text":"
import { describe, expect, test } from \"bun:test\";\n\ndescribe('formatToolCall', () => {\n  test('should format an object into the correct structure', () => {\n    const testObj = { name: 'test', value: 123 };\n    const result = formatToolCall(testObj);\n\n    expect(result).toEqual({\n      content: [{\n        type: 'text',\n        text: JSON.stringify(testObj, null, 2),\n        isError: false\n      }]\n    });\n  });\n});\n
"},{"location":"development/test-migration-guide.html#async-test-with-mocking","title":"Async Test with Mocking","text":"
import { describe, expect, test, mock } from \"bun:test\";\n\ndescribe('API Client', () => {\n  test('should fetch data', async () => {\n    const mockResponse = { data: 'test' };\n    const mockFetch = mock(() => Promise.resolve(new Response(\n      JSON.stringify(mockResponse),\n      { status: 200, headers: new Headers() }\n    )));\n    global.fetch = mockFetch as unknown as typeof fetch;\n\n    const result = await apiClient.getData();\n    expect(result).toEqual(mockResponse);\n  });\n});\n
"},{"location":"development/test-migration-guide.html#complex-mocking-example","title":"Complex Mocking Example","text":"
import { describe, expect, test, mock } from \"bun:test\";\nimport type { Mock } from \"bun:test\";\n\ninterface MockServices {\n  light: {\n    turn_on: Mock<() => Promise<{ success: boolean }>>;\n    turn_off: Mock<() => Promise<{ success: boolean }>>;\n  };\n}\n\nconst mockServices: MockServices = {\n  light: {\n    turn_on: mock(() => Promise.resolve({ success: true })),\n    turn_off: mock(() => Promise.resolve({ success: true }))\n  }\n};\n\ndescribe('Home Assistant Service', () => {\n  test('should control lights', async () => {\n    const result = await mockServices.light.turn_on();\n    expect(result.success).toBe(true);\n  });\n});\n
"},{"location":"development/test-migration-guide.html#best-practices","title":"Best Practices","text":"
  1. Use TypeScript for better type safety in mocks
  2. Keep mocks as simple as possible
  3. Prefer interface-based mocks over concrete implementations
  4. Use proper type assertions when necessary
  5. Clean up mocks in afterEach blocks
  6. Use descriptive test names
  7. Group related tests using describe blocks
"},{"location":"development/test-migration-guide.html#common-issues-and-solutions","title":"Common Issues and Solutions","text":""},{"location":"development/test-migration-guide.html#issue-type-errors-with-mocks","title":"Issue: Type Errors with Mocks","text":"
// Solution: Use proper typing with Mock type\nimport type { Mock } from \"bun:test\";\nconst mockFn: Mock<() => string> = mock(() => \"result\");\n
"},{"location":"development/test-migration-guide.html#issue-global-object-mocking","title":"Issue: Global Object Mocking","text":"
// Solution: Use type assertions carefully\nglobal.someGlobal = mockImplementation as unknown as typeof someGlobal;\n
"},{"location":"development/test-migration-guide.html#issue-module-mocking","title":"Issue: Module Mocking","text":"
// Solution: Use dynamic imports or vi.mock if available\nconst mockModule = {\n  default: mock(() => mockImplementation)\n};\n
"},{"location":"development/tools.html","title":"Tool Development Guide","text":"

This guide explains how to create new tools for the Home Assistant MCP.

"},{"location":"development/tools.html#tool-structure","title":"Tool Structure","text":"

Each tool should follow this basic structure:

interface Tool {\n    id: string;\n    name: string;\n    description: string;\n    version: string;\n    category: ToolCategory;\n    execute(params: any): Promise<ToolResult>;\n}\n
"},{"location":"development/tools.html#creating-a-new-tool","title":"Creating a New Tool","text":"
  1. Create a new file in the appropriate category directory
  2. Implement the Tool interface
  3. Add API endpoints
  4. Add WebSocket handlers
  5. Add documentation
  6. Add tests
"},{"location":"development/tools.html#example-tool-implementation","title":"Example Tool Implementation","text":"
import { Tool, ToolCategory, ToolResult } from '../interfaces';\n\nexport class MyCustomTool implements Tool {\n    id = 'my_custom_tool';\n    name = 'My Custom Tool';\n    description = 'Description of what the tool does';\n    version = '1.0.0';\n    category = ToolCategory.Utility;\n\n    async execute(params: any): Promise<ToolResult> {\n        // Tool implementation\n        return {\n            success: true,\n            data: {\n                // Tool-specific response data\n            }\n        };\n    }\n}\n
"},{"location":"development/tools.html#tool-categories","title":"Tool Categories","text":""},{"location":"development/tools.html#api-integration","title":"API Integration","text":""},{"location":"development/tools.html#rest-endpoint","title":"REST Endpoint","text":"
import { Router } from 'express';\nimport { MyCustomTool } from './my-custom-tool';\n\nconst router = Router();\nconst tool = new MyCustomTool();\n\nrouter.post('/api/tools/custom', async (req, res) => {\n    try {\n        const result = await tool.execute(req.body);\n        res.json(result);\n    } catch (error) {\n        res.status(500).json({\n            success: false,\n            message: error.message\n        });\n    }\n});\n
"},{"location":"development/tools.html#websocket-handler","title":"WebSocket Handler","text":"
import { WebSocketServer } from 'ws';\nimport { MyCustomTool } from './my-custom-tool';\n\nconst tool = new MyCustomTool();\n\nwss.on('connection', (ws) => {\n    ws.on('message', async (message) => {\n        const { type, params } = JSON.parse(message);\n        if (type === 'my_custom_tool') {\n            const result = await tool.execute(params);\n            ws.send(JSON.stringify(result));\n        }\n    });\n});\n
"},{"location":"development/tools.html#error-handling","title":"Error Handling","text":"
class ToolError extends Error {\n    constructor(\n        message: string,\n        public code: string,\n        public status: number = 500\n    ) {\n        super(message);\n        this.name = 'ToolError';\n    }\n}\n\n// Usage in tool\nasync execute(params: any): Promise<ToolResult> {\n    try {\n        // Tool implementation\n    } catch (error) {\n        throw new ToolError(\n            'Operation failed',\n            'TOOL_ERROR',\n            500\n        );\n    }\n}\n
"},{"location":"development/tools.html#testing","title":"Testing","text":"
import { MyCustomTool } from './my-custom-tool';\n\ndescribe('MyCustomTool', () => {\n    let tool: MyCustomTool;\n\n    beforeEach(() => {\n        tool = new MyCustomTool();\n    });\n\n    it('should execute successfully', async () => {\n        const result = await tool.execute({\n            // Test parameters\n        });\n        expect(result.success).toBe(true);\n    });\n\n    it('should handle errors', async () => {\n        // Error test cases\n    });\n});\n
"},{"location":"development/tools.html#documentation","title":"Documentation","text":"
  1. Create tool documentation in docs/tools/category/tool-name.md
  2. Update tools/tools.md with tool reference
  3. Add tool to navigation in mkdocs.yml
"},{"location":"development/tools.html#documentation-template","title":"Documentation Template","text":"
# Tool Name\n\nDescription of the tool.\n\n## Features\n\n- Feature 1\n- Feature 2\n\n## Usage\n\n### REST API\n\n```typescript\n// API endpoints\n
"},{"location":"development/tools.html#websocket","title":"WebSocket","text":"
// WebSocket usage\n
"},{"location":"development/tools.html#examples","title":"Examples","text":""},{"location":"development/tools.html#example-1","title":"Example 1","text":"
// Usage example\n
"},{"location":"development/tools.html#response-format","title":"Response Format","text":"

{\n    \"success\": true,\n    \"data\": {\n        // Response data structure\n    }\n}\n
```

"},{"location":"development/tools.html#best-practices","title":"Best Practices","text":"
  1. Follow consistent naming conventions
  2. Implement proper error handling
  3. Add comprehensive documentation
  4. Write thorough tests
  5. Use TypeScript for type safety
  6. Follow SOLID principles
  7. Implement rate limiting
  8. Add proper logging
"},{"location":"development/tools.html#see-also","title":"See Also","text":""},{"location":"examples/index.html","title":"Example Projects \ud83d\udcda","text":"

This section contains examples and tutorials for common MCP Server integrations.

"},{"location":"examples/index.html#speech-to-text-integration","title":"Speech-to-Text Integration","text":"

Example of integrating speech recognition with MCP Server:

// From examples/speech-to-text-example.ts\n// Add example code and explanation\n
"},{"location":"examples/index.html#more-examples-coming-soon","title":"More Examples Coming Soon","text":"

...

"},{"location":"getting-started/index.html","title":"Getting Started","text":"

Welcome to the Advanced Home Assistant MCP getting started guide. Follow these steps to begin:

  1. Installation
  2. Configuration
  3. Docker Setup
  4. Quick Start
"},{"location":"getting-started/configuration.html","title":"Configuration","text":""},{"location":"getting-started/configuration.html#basic-configuration","title":"Basic Configuration","text":""},{"location":"getting-started/configuration.html#advanced-settings","title":"Advanced Settings","text":""},{"location":"getting-started/docker.html","title":"Docker Deployment Guide \ud83d\udc33","text":"

Detailed guide for deploying MCP Server with Docker...

"},{"location":"getting-started/installation.html","title":"Installation Guide \ud83d\udee0\ufe0f","text":"

This guide covers different methods to install and set up the MCP Server for Home Assistant. Choose the installation method that best suits your needs.

"},{"location":"getting-started/installation.html#prerequisites","title":"Prerequisites","text":"

Before installing MCP Server, ensure you have:

"},{"location":"getting-started/installation.html#installation-methods","title":"Installation Methods","text":""},{"location":"getting-started/installation.html#1-smithery-installation-recommended","title":"1. \ud83d\udd27 Smithery Installation (Recommended)","text":"

The easiest way to install MCP Server is through Smithery:

"},{"location":"getting-started/installation.html#smithery-configuration","title":"Smithery Configuration","text":"

The project includes a smithery.yaml configuration:

# Add smithery.yaml contents and explanation\n
"},{"location":"getting-started/installation.html#installation-steps","title":"Installation Steps","text":"
npx -y @smithery/cli install @jango-blockchained/advanced-homeassistant-mcp --client claude\n
"},{"location":"getting-started/installation.html#2-docker-installation","title":"2. \ud83d\udc33 Docker Installation","text":"

For a containerized deployment:

# Clone the repository\ngit clone --depth 1 https://github.com/jango-blockchained/advanced-homeassistant-mcp.git\ncd advanced-homeassistant-mcp\n\n# Configure environment variables\ncp .env.example .env\n# Edit .env with your Home Assistant details:\n# - HA_URL: Your Home Assistant URL\n# - HA_TOKEN: Your Long-Lived Access Token\n# - Other configuration options\n\n# Build and start containers\ndocker compose up -d --build\n\n# View logs (optional)\ndocker compose logs -f --tail=50\n
"},{"location":"getting-started/installation.html#3-manual-installation","title":"3. \ud83d\udcbb Manual Installation","text":"

For direct installation on your system:

# Install Bun runtime\ncurl -fsSL https://bun.sh/install | bash\n\n# Clone and install\ngit clone https://github.com/jango-blockchained/advanced-homeassistant-mcp.git\ncd advanced-homeassistant-mcp\nbun install --frozen-lockfile\n\n# Configure environment\ncp .env.example .env\n# Edit .env with your configuration\n\n# Start the server\nbun run dev --watch\n
"},{"location":"getting-started/installation.html#configuration","title":"Configuration","text":""},{"location":"getting-started/installation.html#environment-variables","title":"Environment Variables","text":"

Key configuration options in your .env file:

# Home Assistant Configuration\nHA_URL=http://your-homeassistant:8123\nHA_TOKEN=your_long_lived_access_token\n\n# Server Configuration\nPORT=3000\nHOST=0.0.0.0\nNODE_ENV=production\n\n# Security Settings\nJWT_SECRET=your_secure_jwt_secret\nRATE_LIMIT=100\n
"},{"location":"getting-started/installation.html#client-integration","title":"Client Integration","text":""},{"location":"getting-started/installation.html#cursor-integration","title":"Cursor Integration","text":"

Add to .cursor/config/config.json:

{\n  \"mcpServers\": {\n    \"homeassistant-mcp\": {\n      \"command\": \"bun\",\n      \"args\": [\"run\", \"start\"],\n      \"cwd\": \"${workspaceRoot}\",\n      \"env\": {\n        \"NODE_ENV\": \"development\"\n      }\n    }\n  }\n}\n
"},{"location":"getting-started/installation.html#claude-desktop-integration","title":"Claude Desktop Integration","text":"

Add to your Claude configuration:

{\n  \"mcpServers\": {\n    \"homeassistant-mcp\": {\n      \"command\": \"bun\",\n      \"args\": [\"run\", \"start\", \"--port\", \"8080\"],\n      \"env\": {\n        \"NODE_ENV\": \"production\"\n      }\n    }\n  }\n}\n
"},{"location":"getting-started/installation.html#verification","title":"Verification","text":"

To verify your installation:

  1. Check server status:

    curl http://localhost:3000/health\n

  2. Test Home Assistant connection:

    curl http://localhost:3000/api/state\n

"},{"location":"getting-started/installation.html#troubleshooting","title":"Troubleshooting","text":"

If you encounter issues:

  1. Check the Troubleshooting Guide
  2. Verify your environment variables
  3. Check server logs:
    # For Docker installation\ndocker compose logs -f\n\n# For manual installation\nbun run dev\n
"},{"location":"getting-started/installation.html#next-steps","title":"Next Steps","text":""},{"location":"getting-started/installation.html#support","title":"Support","text":"

Need help? Check our Support Resources or open an issue.

"},{"location":"getting-started/quickstart.html","title":"Quick Start Guide \ud83d\ude80","text":"

This guide will help you get started with MCP Server after installation. We'll cover basic usage, common commands, and simple integrations.

"},{"location":"getting-started/quickstart.html#first-steps","title":"First Steps","text":""},{"location":"getting-started/quickstart.html#1-verify-connection","title":"1. Verify Connection","text":"

After installation, verify your MCP Server is running and connected to Home Assistant:

# Check server health\ncurl http://localhost:3000/health\n\n# Verify Home Assistant connection\ncurl http://localhost:3000/api/state\n
"},{"location":"getting-started/quickstart.html#2-basic-voice-commands","title":"2. Basic Voice Commands","text":"

Try these basic voice commands to test your setup:

# Example using curl for testing\ncurl -X POST http://localhost:3000/api/command \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"command\": \"Turn on the living room lights\"}'\n

Common voice commands: - \"Turn on/off [device name]\" - \"Set [device] to [value]\" - \"What's the temperature in [room]?\" - \"Is [device] on or off?\"

"},{"location":"getting-started/quickstart.html#real-world-examples","title":"Real-World Examples","text":""},{"location":"getting-started/quickstart.html#1-smart-lighting-control","title":"1. Smart Lighting Control","text":"
// Browser example using fetch\nconst response = await fetch('http://localhost:3000/api/command', {\n  method: 'POST',\n  headers: {\n    'Content-Type': 'application/json',\n  },\n  body: JSON.stringify({\n    command: 'Set living room lights to 50% brightness and warm white color'\n  })\n});\n
"},{"location":"getting-started/quickstart.html#2-real-time-updates","title":"2. Real-Time Updates","text":"

Subscribe to device state changes using Server-Sent Events (SSE):

const eventSource = new EventSource('http://localhost:3000/subscribe_events?token=YOUR_TOKEN&domain=light');\n\neventSource.onmessage = (event) => {\n    const data = JSON.parse(event.data);\n    console.log('Device state changed:', data);\n    // Update your UI here\n};\n
"},{"location":"getting-started/quickstart.html#3-scene-automation","title":"3. Scene Automation","text":"

Create and trigger scenes for different activities:

// Create a \"Movie Night\" scene\nconst createScene = async () => {\n  await fetch('http://localhost:3000/api/scene', {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application/json',\n    },\n    body: JSON.stringify({\n      name: 'Movie Night',\n      actions: [\n        { device: 'living_room_lights', action: 'dim', value: 20 },\n        { device: 'tv', action: 'on' },\n        { device: 'soundbar', action: 'on' }\n      ]\n    })\n  });\n};\n\n// Trigger the scene with voice command:\n// \"Hey MCP, activate movie night scene\"\n
"},{"location":"getting-started/quickstart.html#integration-examples","title":"Integration Examples","text":""},{"location":"getting-started/quickstart.html#1-web-dashboard-integration","title":"1. Web Dashboard Integration","text":"
// React component example\nfunction SmartHomeControl() {\n    const [devices, setDevices] = useState([]);\n\n    useEffect(() => {\n        // Subscribe to device updates\n        const events = new EventSource('http://localhost:3000/subscribe_events');\n        events.onmessage = (event) => {\n            const data = JSON.parse(event.data);\n            setDevices(currentDevices => \n                currentDevices.map(device => \n                    device.id === data.id ? {...device, ...data} : device\n                )\n            );\n        };\n\n        return () => events.close();\n    }, []);\n\n    return (\n        <div className=\"dashboard\">\n            {devices.map(device => (\n                <DeviceCard key={device.id} device={device} />\n            ))}\n        </div>\n    );\n}\n
"},{"location":"getting-started/quickstart.html#2-voice-assistant-integration","title":"2. Voice Assistant Integration","text":"
// Example using speech-to-text with MCP\nasync function handleVoiceCommand(audioBlob: Blob) {\n    // First, convert speech to text\n    const text = await speechToText(audioBlob);\n\n    // Then send command to MCP\n    const response = await fetch('http://localhost:3000/api/command', {\n        method: 'POST',\n        headers: {\n            'Content-Type': 'application/json',\n        },\n        body: JSON.stringify({ command: text })\n    });\n\n    return response.json();\n}\n
"},{"location":"getting-started/quickstart.html#best-practices","title":"Best Practices","text":"
  1. Error Handling

    try {\n    const response = await fetch('http://localhost:3000/api/command', {\n        method: 'POST',\n        headers: {\n            'Content-Type': 'application/json',\n        },\n        body: JSON.stringify({ command: 'Turn on lights' })\n    });\n\n    if (!response.ok) {\n        throw new Error(`HTTP error! status: ${response.status}`);\n    }\n\n    const data = await response.json();\n} catch (error) {\n    console.error('Error:', error);\n    // Handle error appropriately\n}\n

  2. Connection Management

    class MCPConnection {\n    constructor() {\n        this.eventSource = null;\n        this.reconnectAttempts = 0;\n    }\n\n    connect() {\n        this.eventSource = new EventSource('http://localhost:3000/subscribe_events');\n        this.eventSource.onerror = this.handleError.bind(this);\n    }\n\n    handleError() {\n        if (this.reconnectAttempts < 3) {\n            setTimeout(() => {\n                this.reconnectAttempts++;\n                this.connect();\n            }, 1000 * this.reconnectAttempts);\n        }\n    }\n}\n

"},{"location":"getting-started/quickstart.html#next-steps","title":"Next Steps","text":""},{"location":"getting-started/quickstart.html#troubleshooting","title":"Troubleshooting","text":"

If you encounter issues: - Verify your authentication token - Check server logs for errors - Ensure Home Assistant is accessible - Review the Troubleshooting Guide

Need more help? Visit our Support Resources.

"},{"location":"tools/index.html","title":"Tools Overview","text":"

The Home Assistant MCP Server provides a variety of tools to help you manage and interact with your home automation system.

"},{"location":"tools/index.html#available-tools","title":"Available Tools","text":""},{"location":"tools/index.html#device-management","title":"Device Management","text":""},{"location":"tools/index.html#history-state","title":"History & State","text":""},{"location":"tools/index.html#automation","title":"Automation","text":""},{"location":"tools/index.html#add-ons-packages","title":"Add-ons & Packages","text":""},{"location":"tools/index.html#notifications","title":"Notifications","text":""},{"location":"tools/index.html#events","title":"Events","text":""},{"location":"tools/index.html#getting-started","title":"Getting Started","text":"

To get started with these tools:

  1. Ensure you have the MCP Server properly installed and configured
  2. Check the specific tool documentation for detailed usage instructions
  3. Use the API endpoints or command-line interface as needed
"},{"location":"tools/index.html#next-steps","title":"Next Steps","text":""},{"location":"tools/addons-packages/addon.html","title":"Add-on Management Tool","text":"

The Add-on Management tool provides functionality to manage Home Assistant add-ons through the MCP interface.

"},{"location":"tools/addons-packages/addon.html#features","title":"Features","text":""},{"location":"tools/addons-packages/addon.html#usage","title":"Usage","text":""},{"location":"tools/addons-packages/addon.html#rest-api","title":"REST API","text":"
GET /api/addons\nGET /api/addons/{addon_slug}\nPOST /api/addons/{addon_slug}/install\nPOST /api/addons/{addon_slug}/uninstall\nPOST /api/addons/{addon_slug}/start\nPOST /api/addons/{addon_slug}/stop\nPOST /api/addons/{addon_slug}/restart\nGET /api/addons/{addon_slug}/logs\nPUT /api/addons/{addon_slug}/config\nGET /api/addons/{addon_slug}/stats\n
"},{"location":"tools/addons-packages/addon.html#websocket","title":"WebSocket","text":"
// List add-ons\n{\n    \"type\": \"get_addons\"\n}\n\n// Get add-on info\n{\n    \"type\": \"get_addon_info\",\n    \"addon_slug\": \"required_addon_slug\"\n}\n\n// Install add-on\n{\n    \"type\": \"install_addon\",\n    \"addon_slug\": \"required_addon_slug\",\n    \"version\": \"optional_version\"\n}\n\n// Control add-on\n{\n    \"type\": \"control_addon\",\n    \"addon_slug\": \"required_addon_slug\",\n    \"action\": \"start|stop|restart\"\n}\n
"},{"location":"tools/addons-packages/addon.html#examples","title":"Examples","text":""},{"location":"tools/addons-packages/addon.html#list-all-add-ons","title":"List All Add-ons","text":"
const response = await fetch('http://your-ha-mcp/api/addons', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst addons = await response.json();\n
"},{"location":"tools/addons-packages/addon.html#install-add-on","title":"Install Add-on","text":"
const response = await fetch('http://your-ha-mcp/api/addons/mosquitto/install', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"version\": \"latest\"\n    })\n});\n
"},{"location":"tools/addons-packages/addon.html#configure-add-on","title":"Configure Add-on","text":"
const response = await fetch('http://your-ha-mcp/api/addons/mosquitto/config', {\n    method: 'PUT',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"logins\": [\n            {\n                \"username\": \"mqtt_user\",\n                \"password\": \"mqtt_password\"\n            }\n        ],\n        \"customize\": {\n            \"active\": true,\n            \"folder\": \"mosquitto\"\n        }\n    })\n});\n
"},{"location":"tools/addons-packages/addon.html#response-format","title":"Response Format","text":""},{"location":"tools/addons-packages/addon.html#add-on-list-response","title":"Add-on List Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"addons\": [\n            {\n                \"slug\": \"addon_slug\",\n                \"name\": \"Add-on Name\",\n                \"version\": \"1.0.0\",\n                \"state\": \"started\",\n                \"repository\": \"core\",\n                \"installed\": true,\n                \"update_available\": false\n            }\n        ]\n    }\n}\n
"},{"location":"tools/addons-packages/addon.html#add-on-info-response","title":"Add-on Info Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"addon\": {\n            \"slug\": \"addon_slug\",\n            \"name\": \"Add-on Name\",\n            \"version\": \"1.0.0\",\n            \"description\": \"Add-on description\",\n            \"long_description\": \"Detailed description\",\n            \"repository\": \"core\",\n            \"installed\": true,\n            \"state\": \"started\",\n            \"webui\": \"http://[HOST]:[PORT:80]\",\n            \"boot\": \"auto\",\n            \"options\": {\n                // Add-on specific options\n            },\n            \"schema\": {\n                // Add-on options schema\n            },\n            \"ports\": {\n                \"80/tcp\": 8080\n            },\n            \"ingress\": true,\n            \"ingress_port\": 8099\n        }\n    }\n}\n
"},{"location":"tools/addons-packages/addon.html#add-on-stats-response","title":"Add-on Stats Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"stats\": {\n            \"cpu_percent\": 2.5,\n            \"memory_usage\": 128974848,\n            \"memory_limit\": 536870912,\n            \"network_rx\": 1234,\n            \"network_tx\": 5678,\n            \"blk_read\": 12345,\n            \"blk_write\": 67890\n        }\n    }\n}\n
"},{"location":"tools/addons-packages/addon.html#error-handling","title":"Error Handling","text":""},{"location":"tools/addons-packages/addon.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/addons-packages/addon.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/addons-packages/addon.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/addons-packages/addon.html#best-practices","title":"Best Practices","text":"
  1. Always check add-on compatibility
  2. Back up configurations before updates
  3. Monitor resource usage
  4. Use appropriate update strategies
  5. Implement proper error handling
  6. Test configurations in safe environment
  7. Handle rate limiting gracefully
  8. Keep add-ons updated
"},{"location":"tools/addons-packages/addon.html#add-on-security","title":"Add-on Security","text":""},{"location":"tools/addons-packages/addon.html#see-also","title":"See Also","text":""},{"location":"tools/addons-packages/package.html","title":"Package Management Tool","text":"

The Package Management tool provides functionality to manage Home Assistant Community Store (HACS) packages through the MCP interface.

"},{"location":"tools/addons-packages/package.html#features","title":"Features","text":""},{"location":"tools/addons-packages/package.html#usage","title":"Usage","text":""},{"location":"tools/addons-packages/package.html#rest-api","title":"REST API","text":"
GET /api/packages\nGET /api/packages/{package_id}\nPOST /api/packages/{package_id}/install\nPOST /api/packages/{package_id}/uninstall\nPOST /api/packages/{package_id}/update\nGET /api/packages/search\nGET /api/packages/categories\nGET /api/packages/repositories\n
"},{"location":"tools/addons-packages/package.html#websocket","title":"WebSocket","text":"
// List packages\n{\n    \"type\": \"get_packages\",\n    \"category\": \"optional_category\"\n}\n\n// Search packages\n{\n    \"type\": \"search_packages\",\n    \"query\": \"search_query\",\n    \"category\": \"optional_category\"\n}\n\n// Install package\n{\n    \"type\": \"install_package\",\n    \"package_id\": \"required_package_id\",\n    \"version\": \"optional_version\"\n}\n
"},{"location":"tools/addons-packages/package.html#package-categories","title":"Package Categories","text":""},{"location":"tools/addons-packages/package.html#examples","title":"Examples","text":""},{"location":"tools/addons-packages/package.html#list-all-packages","title":"List All Packages","text":"
const response = await fetch('http://your-ha-mcp/api/packages', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst packages = await response.json();\n
"},{"location":"tools/addons-packages/package.html#search-packages","title":"Search Packages","text":"
const response = await fetch('http://your-ha-mcp/api/packages/search?q=weather&category=integrations', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst searchResults = await response.json();\n
"},{"location":"tools/addons-packages/package.html#install-package","title":"Install Package","text":"
const response = await fetch('http://your-ha-mcp/api/packages/custom-weather-card/install', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"version\": \"latest\"\n    })\n});\n
"},{"location":"tools/addons-packages/package.html#response-format","title":"Response Format","text":""},{"location":"tools/addons-packages/package.html#package-list-response","title":"Package List Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"packages\": [\n            {\n                \"id\": \"package_id\",\n                \"name\": \"Package Name\",\n                \"category\": \"integrations\",\n                \"description\": \"Package description\",\n                \"version\": \"1.0.0\",\n                \"installed\": true,\n                \"update_available\": false,\n                \"stars\": 150,\n                \"downloads\": 10000\n            }\n        ]\n    }\n}\n
"},{"location":"tools/addons-packages/package.html#package-info-response","title":"Package Info Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"package\": {\n            \"id\": \"package_id\",\n            \"name\": \"Package Name\",\n            \"category\": \"integrations\",\n            \"description\": \"Package description\",\n            \"long_description\": \"Detailed description\",\n            \"version\": \"1.0.0\",\n            \"installed_version\": \"0.9.0\",\n            \"available_version\": \"1.0.0\",\n            \"installed\": true,\n            \"update_available\": true,\n            \"stars\": 150,\n            \"downloads\": 10000,\n            \"repository\": \"https://github.com/author/repo\",\n            \"author\": {\n                \"name\": \"Author Name\",\n                \"url\": \"https://github.com/author\"\n            },\n            \"documentation\": \"https://github.com/author/repo/wiki\",\n            \"dependencies\": [\n                \"dependency1\",\n                \"dependency2\"\n            ]\n        }\n    }\n}\n
"},{"location":"tools/addons-packages/package.html#search-response","title":"Search Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"results\": [\n            {\n                \"id\": \"package_id\",\n                \"name\": \"Package Name\",\n                \"category\": \"integrations\",\n                \"description\": \"Package description\",\n                \"version\": \"1.0.0\",\n                \"score\": 0.95\n            }\n        ],\n        \"total\": 42\n    }\n}\n
"},{"location":"tools/addons-packages/package.html#error-handling","title":"Error Handling","text":""},{"location":"tools/addons-packages/package.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/addons-packages/package.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/addons-packages/package.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/addons-packages/package.html#best-practices","title":"Best Practices","text":"
  1. Check package compatibility
  2. Review package documentation
  3. Verify package dependencies
  4. Back up before updates
  5. Test in safe environment
  6. Monitor resource usage
  7. Keep packages updated
  8. Handle rate limiting gracefully
"},{"location":"tools/addons-packages/package.html#package-security","title":"Package Security","text":""},{"location":"tools/addons-packages/package.html#see-also","title":"See Also","text":""},{"location":"tools/automation/automation-config.html","title":"Automation Configuration Tool","text":"

The Automation Configuration tool provides functionality to create, update, and manage Home Assistant automation configurations.

"},{"location":"tools/automation/automation-config.html#features","title":"Features","text":""},{"location":"tools/automation/automation-config.html#usage","title":"Usage","text":""},{"location":"tools/automation/automation-config.html#rest-api","title":"REST API","text":"
POST /api/automations\nPUT /api/automations/{automation_id}\nDELETE /api/automations/{automation_id}\nPOST /api/automations/{automation_id}/duplicate\nPOST /api/automations/validate\n
"},{"location":"tools/automation/automation-config.html#websocket","title":"WebSocket","text":"
// Create automation\n{\n    \"type\": \"create_automation\",\n    \"automation\": {\n        // Automation configuration\n    }\n}\n\n// Update automation\n{\n    \"type\": \"update_automation\",\n    \"automation_id\": \"required_automation_id\",\n    \"automation\": {\n        // Updated configuration\n    }\n}\n\n// Delete automation\n{\n    \"type\": \"delete_automation\",\n    \"automation_id\": \"required_automation_id\"\n}\n
"},{"location":"tools/automation/automation-config.html#automation-configuration","title":"Automation Configuration","text":""},{"location":"tools/automation/automation-config.html#basic-structure","title":"Basic Structure","text":"
{\n    \"id\": \"morning_routine\",\n    \"alias\": \"Morning Routine\",\n    \"description\": \"Turn on lights and adjust temperature in the morning\",\n    \"trigger\": [\n        {\n            \"platform\": \"time\",\n            \"at\": \"07:00:00\"\n        }\n    ],\n    \"condition\": [\n        {\n            \"condition\": \"time\",\n            \"weekday\": [\"mon\", \"tue\", \"wed\", \"thu\", \"fri\"]\n        }\n    ],\n    \"action\": [\n        {\n            \"service\": \"light.turn_on\",\n            \"target\": {\n                \"entity_id\": \"light.bedroom\"\n            },\n            \"data\": {\n                \"brightness\": 255,\n                \"transition\": 300\n            }\n        }\n    ],\n    \"mode\": \"single\"\n}\n
"},{"location":"tools/automation/automation-config.html#trigger-types","title":"Trigger Types","text":"
// Time-based trigger\n{\n    \"platform\": \"time\",\n    \"at\": \"07:00:00\"\n}\n\n// State-based trigger\n{\n    \"platform\": \"state\",\n    \"entity_id\": \"binary_sensor.motion\",\n    \"to\": \"on\"\n}\n\n// Event-based trigger\n{\n    \"platform\": \"event\",\n    \"event_type\": \"custom_event\"\n}\n\n// Numeric state trigger\n{\n    \"platform\": \"numeric_state\",\n    \"entity_id\": \"sensor.temperature\",\n    \"above\": 25\n}\n
"},{"location":"tools/automation/automation-config.html#condition-types","title":"Condition Types","text":"
// Time condition\n{\n    \"condition\": \"time\",\n    \"after\": \"07:00:00\",\n    \"before\": \"22:00:00\"\n}\n\n// State condition\n{\n    \"condition\": \"state\",\n    \"entity_id\": \"device_tracker.phone\",\n    \"state\": \"home\"\n}\n\n// Numeric state condition\n{\n    \"condition\": \"numeric_state\",\n    \"entity_id\": \"sensor.temperature\",\n    \"below\": 25\n}\n
"},{"location":"tools/automation/automation-config.html#action-types","title":"Action Types","text":"
// Service call action\n{\n    \"service\": \"light.turn_on\",\n    \"target\": {\n        \"entity_id\": \"light.bedroom\"\n    }\n}\n\n// Delay action\n{\n    \"delay\": \"00:00:30\"\n}\n\n// Scene activation\n{\n    \"scene\": \"scene.evening_mode\"\n}\n\n// Conditional action\n{\n    \"choose\": [\n        {\n            \"conditions\": [\n                {\n                    \"condition\": \"state\",\n                    \"entity_id\": \"sun.sun\",\n                    \"state\": \"below_horizon\"\n                }\n            ],\n            \"sequence\": [\n                {\n                    \"service\": \"light.turn_on\",\n                    \"target\": {\n                        \"entity_id\": \"light.living_room\"\n                    }\n                }\n            ]\n        }\n    ]\n}\n
"},{"location":"tools/automation/automation-config.html#examples","title":"Examples","text":""},{"location":"tools/automation/automation-config.html#create-new-automation","title":"Create New Automation","text":"
const response = await fetch('http://your-ha-mcp/api/automations', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"alias\": \"Morning Routine\",\n        \"description\": \"Turn on lights in the morning\",\n        \"trigger\": [\n            {\n                \"platform\": \"time\",\n                \"at\": \"07:00:00\"\n            }\n        ],\n        \"action\": [\n            {\n                \"service\": \"light.turn_on\",\n                \"target\": {\n                    \"entity_id\": \"light.bedroom\"\n                }\n            }\n        ]\n    })\n});\n
"},{"location":"tools/automation/automation-config.html#update-existing-automation","title":"Update Existing Automation","text":"
const response = await fetch('http://your-ha-mcp/api/automations/morning_routine', {\n    method: 'PUT',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"alias\": \"Morning Routine\",\n        \"trigger\": [\n            {\n                \"platform\": \"time\",\n                \"at\": \"07:30:00\"  // Updated time\n            }\n        ],\n        \"action\": [\n            {\n                \"service\": \"light.turn_on\",\n                \"target\": {\n                    \"entity_id\": \"light.bedroom\"\n                }\n            }\n        ]\n    })\n});\n
"},{"location":"tools/automation/automation-config.html#response-format","title":"Response Format","text":""},{"location":"tools/automation/automation-config.html#success-response","title":"Success Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"automation\": {\n            \"id\": \"created_automation_id\",\n            // Full automation configuration\n        }\n    }\n}\n
"},{"location":"tools/automation/automation-config.html#validation-response","title":"Validation Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"valid\": true,\n        \"warnings\": [\n            \"No conditions specified\"\n        ]\n    }\n}\n
"},{"location":"tools/automation/automation-config.html#error-handling","title":"Error Handling","text":""},{"location":"tools/automation/automation-config.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/automation/automation-config.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\",\n    \"validation_errors\": [\n        {\n            \"path\": \"trigger[0].platform\",\n            \"message\": \"Invalid trigger platform\"\n        }\n    ]\n}\n
"},{"location":"tools/automation/automation-config.html#best-practices","title":"Best Practices","text":"
  1. Always validate configurations before saving
  2. Use descriptive aliases and descriptions
  3. Group related automations
  4. Test automations in a safe environment
  5. Document automation dependencies
  6. Use variables for reusable values
  7. Implement proper error handling
  8. Consider automation modes carefully
"},{"location":"tools/automation/automation-config.html#see-also","title":"See Also","text":""},{"location":"tools/automation/automation.html","title":"Automation Management Tool","text":"

The Automation Management tool provides functionality to manage and control Home Assistant automations.

"},{"location":"tools/automation/automation.html#features","title":"Features","text":""},{"location":"tools/automation/automation.html#usage","title":"Usage","text":""},{"location":"tools/automation/automation.html#rest-api","title":"REST API","text":"
GET /api/automations\nGET /api/automations/{automation_id}\nPOST /api/automations/{automation_id}/toggle\nPOST /api/automations/{automation_id}/trigger\nGET /api/automations/{automation_id}/history\n
"},{"location":"tools/automation/automation.html#websocket","title":"WebSocket","text":"
// List automations\n{\n    \"type\": \"get_automations\"\n}\n\n// Toggle automation\n{\n    \"type\": \"toggle_automation\",\n    \"automation_id\": \"required_automation_id\"\n}\n\n// Trigger automation\n{\n    \"type\": \"trigger_automation\",\n    \"automation_id\": \"required_automation_id\",\n    \"variables\": {\n        // Optional variables\n    }\n}\n
"},{"location":"tools/automation/automation.html#examples","title":"Examples","text":""},{"location":"tools/automation/automation.html#list-all-automations","title":"List All Automations","text":"
const response = await fetch('http://your-ha-mcp/api/automations', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst automations = await response.json();\n
"},{"location":"tools/automation/automation.html#toggle-automation-state","title":"Toggle Automation State","text":"
const response = await fetch('http://your-ha-mcp/api/automations/morning_routine/toggle', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\n
"},{"location":"tools/automation/automation.html#trigger-automation-manually","title":"Trigger Automation Manually","text":"
const response = await fetch('http://your-ha-mcp/api/automations/morning_routine/trigger', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"variables\": {\n            \"brightness\": 100,\n            \"temperature\": 22\n        }\n    })\n});\n
"},{"location":"tools/automation/automation.html#response-format","title":"Response Format","text":""},{"location":"tools/automation/automation.html#automation-list-response","title":"Automation List Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"automations\": [\n            {\n                \"id\": \"automation_id\",\n                \"name\": \"Automation Name\",\n                \"enabled\": true,\n                \"last_triggered\": \"2024-02-05T12:00:00Z\",\n                \"trigger_count\": 42\n            }\n        ]\n    }\n}\n
"},{"location":"tools/automation/automation.html#automation-details-response","title":"Automation Details Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"automation\": {\n            \"id\": \"automation_id\",\n            \"name\": \"Automation Name\",\n            \"enabled\": true,\n            \"triggers\": [\n                {\n                    \"platform\": \"time\",\n                    \"at\": \"07:00:00\"\n                }\n            ],\n            \"conditions\": [],\n            \"actions\": [\n                {\n                    \"service\": \"light.turn_on\",\n                    \"target\": {\n                        \"entity_id\": \"light.bedroom\"\n                    }\n                }\n            ],\n            \"mode\": \"single\",\n            \"max\": 10,\n            \"last_triggered\": \"2024-02-05T12:00:00Z\",\n            \"trigger_count\": 42\n        }\n    }\n}\n
"},{"location":"tools/automation/automation.html#automation-history-response","title":"Automation History Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"history\": [\n            {\n                \"timestamp\": \"2024-02-05T12:00:00Z\",\n                \"trigger\": {\n                    \"platform\": \"time\",\n                    \"at\": \"07:00:00\"\n                },\n                \"context\": {\n                    \"user_id\": \"user_123\",\n                    \"variables\": {}\n                },\n                \"result\": \"success\"\n            }\n        ]\n    }\n}\n
"},{"location":"tools/automation/automation.html#error-handling","title":"Error Handling","text":""},{"location":"tools/automation/automation.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/automation/automation.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/automation/automation.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/automation/automation.html#best-practices","title":"Best Practices","text":"
  1. Monitor automation execution history
  2. Use descriptive automation names
  3. Implement proper error handling
  4. Cache automation configurations when possible
  5. Handle rate limiting gracefully
  6. Test automations before enabling
  7. Use variables for flexible automation behavior
"},{"location":"tools/automation/automation.html#see-also","title":"See Also","text":""},{"location":"tools/device-management/control.html","title":"Device Control Tool","text":"

The Device Control tool provides functionality to control various types of devices in your Home Assistant instance.

"},{"location":"tools/device-management/control.html#supported-device-types","title":"Supported Device Types","text":""},{"location":"tools/device-management/control.html#usage","title":"Usage","text":""},{"location":"tools/device-management/control.html#rest-api","title":"REST API","text":"
POST /api/devices/{device_id}/control\n
"},{"location":"tools/device-management/control.html#websocket","title":"WebSocket","text":"
{\n    \"type\": \"control_device\",\n    \"device_id\": \"required_device_id\",\n    \"domain\": \"required_domain\",\n    \"service\": \"required_service\",\n    \"data\": {\n        // Service-specific data\n    }\n}\n
"},{"location":"tools/device-management/control.html#domain-specific-commands","title":"Domain-Specific Commands","text":""},{"location":"tools/device-management/control.html#lights","title":"Lights","text":"
// Turn on/off\nPOST /api/devices/light/{device_id}/control\n{\n    \"service\": \"turn_on\",  // or \"turn_off\"\n}\n\n// Set brightness\n{\n    \"service\": \"turn_on\",\n    \"data\": {\n        \"brightness\": 255  // 0-255\n    }\n}\n\n// Set color\n{\n    \"service\": \"turn_on\",\n    \"data\": {\n        \"rgb_color\": [255, 0, 0]  // Red\n    }\n}\n
"},{"location":"tools/device-management/control.html#covers","title":"Covers","text":"
// Open/close\nPOST /api/devices/cover/{device_id}/control\n{\n    \"service\": \"open_cover\",  // or \"close_cover\"\n}\n\n// Set position\n{\n    \"service\": \"set_cover_position\",\n    \"data\": {\n        \"position\": 50  // 0-100\n    }\n}\n
"},{"location":"tools/device-management/control.html#climate","title":"Climate","text":"
// Set temperature\nPOST /api/devices/climate/{device_id}/control\n{\n    \"service\": \"set_temperature\",\n    \"data\": {\n        \"temperature\": 22.5\n    }\n}\n\n// Set mode\n{\n    \"service\": \"set_hvac_mode\",\n    \"data\": {\n        \"hvac_mode\": \"heat\"  // heat, cool, auto, off\n    }\n}\n
"},{"location":"tools/device-management/control.html#examples","title":"Examples","text":""},{"location":"tools/device-management/control.html#control-light-brightness","title":"Control Light Brightness","text":"
const response = await fetch('http://your-ha-mcp/api/devices/light/living_room/control', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"service\": \"turn_on\",\n        \"data\": {\n            \"brightness\": 128\n        }\n    })\n});\n
"},{"location":"tools/device-management/control.html#control-cover-position","title":"Control Cover Position","text":"
const response = await fetch('http://your-ha-mcp/api/devices/cover/bedroom/control', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"service\": \"set_cover_position\",\n        \"data\": {\n            \"position\": 75\n        }\n    })\n});\n
"},{"location":"tools/device-management/control.html#response-format","title":"Response Format","text":""},{"location":"tools/device-management/control.html#success-response","title":"Success Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"state\": \"on\",\n        \"attributes\": {\n            // Updated device attributes\n        }\n    }\n}\n
"},{"location":"tools/device-management/control.html#error-response","title":"Error Response","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/device-management/control.html#error-handling","title":"Error Handling","text":""},{"location":"tools/device-management/control.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/device-management/control.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/device-management/control.html#best-practices","title":"Best Practices","text":"
  1. Validate device availability before sending commands
  2. Implement proper error handling
  3. Use appropriate retry strategies for failed commands
  4. Cache device capabilities when possible
  5. Handle rate limiting gracefully
"},{"location":"tools/device-management/control.html#see-also","title":"See Also","text":""},{"location":"tools/device-management/list-devices.html","title":"List Devices Tool","text":"

The List Devices tool provides functionality to retrieve and manage device information from your Home Assistant instance.

"},{"location":"tools/device-management/list-devices.html#features","title":"Features","text":""},{"location":"tools/device-management/list-devices.html#usage","title":"Usage","text":""},{"location":"tools/device-management/list-devices.html#rest-api","title":"REST API","text":"
GET /api/devices\nGET /api/devices/{domain}\nGET /api/devices/{device_id}/state\n
"},{"location":"tools/device-management/list-devices.html#websocket","title":"WebSocket","text":"
// List all devices\n{\n    \"type\": \"list_devices\",\n    \"domain\": \"optional_domain\"\n}\n\n// Get device state\n{\n    \"type\": \"get_device_state\",\n    \"device_id\": \"required_device_id\"\n}\n
"},{"location":"tools/device-management/list-devices.html#examples","title":"Examples","text":""},{"location":"tools/device-management/list-devices.html#list-all-devices","title":"List All Devices","text":"
const response = await fetch('http://your-ha-mcp/api/devices', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst devices = await response.json();\n
"},{"location":"tools/device-management/list-devices.html#get-devices-by-domain","title":"Get Devices by Domain","text":"
const response = await fetch('http://your-ha-mcp/api/devices/light', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst lightDevices = await response.json();\n
"},{"location":"tools/device-management/list-devices.html#response-format","title":"Response Format","text":""},{"location":"tools/device-management/list-devices.html#device-list-response","title":"Device List Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"devices\": [\n            {\n                \"id\": \"device_id\",\n                \"name\": \"Device Name\",\n                \"domain\": \"light\",\n                \"state\": \"on\",\n                \"attributes\": {\n                    \"brightness\": 255,\n                    \"color_temp\": 370\n                }\n            }\n        ]\n    }\n}\n
"},{"location":"tools/device-management/list-devices.html#device-state-response","title":"Device State Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"state\": \"on\",\n        \"attributes\": {\n            \"brightness\": 255,\n            \"color_temp\": 370\n        },\n        \"last_changed\": \"2024-02-05T12:00:00Z\",\n        \"last_updated\": \"2024-02-05T12:00:00Z\"\n    }\n}\n
"},{"location":"tools/device-management/list-devices.html#error-handling","title":"Error Handling","text":""},{"location":"tools/device-management/list-devices.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/device-management/list-devices.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/device-management/list-devices.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/device-management/list-devices.html#best-practices","title":"Best Practices","text":"
  1. Cache device lists when possible
  2. Use domain filtering for better performance
  3. Implement proper error handling
  4. Handle rate limiting gracefully
"},{"location":"tools/device-management/list-devices.html#see-also","title":"See Also","text":""},{"location":"tools/events/sse-stats.html","title":"SSE Statistics Tool","text":"

The SSE Statistics tool provides functionality to monitor and analyze Server-Sent Events (SSE) connections and performance in your Home Assistant MCP instance.

"},{"location":"tools/events/sse-stats.html#features","title":"Features","text":""},{"location":"tools/events/sse-stats.html#usage","title":"Usage","text":""},{"location":"tools/events/sse-stats.html#rest-api","title":"REST API","text":"
GET /api/sse/stats\nGET /api/sse/connections\nGET /api/sse/connections/{connection_id}\nGET /api/sse/metrics\nGET /api/sse/history\n
"},{"location":"tools/events/sse-stats.html#websocket","title":"WebSocket","text":"
// Get SSE stats\n{\n    \"type\": \"get_sse_stats\"\n}\n\n// Get connection details\n{\n    \"type\": \"get_sse_connection\",\n    \"connection_id\": \"required_connection_id\"\n}\n\n// Get performance metrics\n{\n    \"type\": \"get_sse_metrics\",\n    \"period\": \"1h|24h|7d|30d\"\n}\n
"},{"location":"tools/events/sse-stats.html#examples","title":"Examples","text":""},{"location":"tools/events/sse-stats.html#get-current-statistics","title":"Get Current Statistics","text":"
const response = await fetch('http://your-ha-mcp/api/sse/stats', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst stats = await response.json();\n
"},{"location":"tools/events/sse-stats.html#get-connection-details","title":"Get Connection Details","text":"
const response = await fetch('http://your-ha-mcp/api/sse/connections/conn_123', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst connection = await response.json();\n
"},{"location":"tools/events/sse-stats.html#get-performance-metrics","title":"Get Performance Metrics","text":"
const response = await fetch('http://your-ha-mcp/api/sse/metrics?period=24h', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst metrics = await response.json();\n
"},{"location":"tools/events/sse-stats.html#response-format","title":"Response Format","text":""},{"location":"tools/events/sse-stats.html#statistics-response","title":"Statistics Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"active_connections\": 42,\n        \"total_events_sent\": 12345,\n        \"events_per_second\": 5.2,\n        \"memory_usage\": 128974848,\n        \"cpu_usage\": 2.5,\n        \"uptime\": \"PT24H\",\n        \"event_backlog\": 0\n    }\n}\n
"},{"location":"tools/events/sse-stats.html#connection-details-response","title":"Connection Details Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"connection\": {\n            \"id\": \"conn_123\",\n            \"client_id\": \"client_456\",\n            \"user_id\": \"user_789\",\n            \"connected_at\": \"2024-02-05T12:00:00Z\",\n            \"last_event_at\": \"2024-02-05T12:05:00Z\",\n            \"events_sent\": 150,\n            \"subscriptions\": [\n                {\n                    \"event_type\": \"state_changed\",\n                    \"entity_id\": \"light.living_room\"\n                }\n            ],\n            \"state\": \"active\",\n            \"ip_address\": \"192.168.1.100\",\n            \"user_agent\": \"Mozilla/5.0 ...\"\n        }\n    }\n}\n
"},{"location":"tools/events/sse-stats.html#performance-metrics-response","title":"Performance Metrics Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"metrics\": {\n            \"connections\": {\n                \"current\": 42,\n                \"max\": 100,\n                \"average\": 35.5\n            },\n            \"events\": {\n                \"total\": 12345,\n                \"rate\": {\n                    \"current\": 5.2,\n                    \"max\": 15.0,\n                    \"average\": 4.8\n                }\n            },\n            \"latency\": {\n                \"p50\": 15,\n                \"p95\": 45,\n                \"p99\": 100\n            },\n            \"resources\": {\n                \"memory\": {\n                    \"current\": 128974848,\n                    \"max\": 536870912\n                },\n                \"cpu\": {\n                    \"current\": 2.5,\n                    \"max\": 10.0,\n                    \"average\": 3.2\n                }\n            }\n        },\n        \"period\": \"24h\",\n        \"timestamp\": \"2024-02-05T12:00:00Z\"\n    }\n}\n
"},{"location":"tools/events/sse-stats.html#error-handling","title":"Error Handling","text":""},{"location":"tools/events/sse-stats.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/events/sse-stats.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/events/sse-stats.html#monitoring-metrics","title":"Monitoring Metrics","text":""},{"location":"tools/events/sse-stats.html#connection-metrics","title":"Connection Metrics","text":""},{"location":"tools/events/sse-stats.html#event-metrics","title":"Event Metrics","text":""},{"location":"tools/events/sse-stats.html#resource-metrics","title":"Resource Metrics","text":""},{"location":"tools/events/sse-stats.html#alert-thresholds","title":"Alert Thresholds","text":""},{"location":"tools/events/sse-stats.html#best-practices","title":"Best Practices","text":"
  1. Monitor connection health
  2. Track resource usage
  3. Set up alerts
  4. Analyze usage patterns
  5. Optimize performance
  6. Plan capacity
  7. Implement failover
  8. Regular maintenance
"},{"location":"tools/events/sse-stats.html#performance-optimization","title":"Performance Optimization","text":""},{"location":"tools/events/sse-stats.html#see-also","title":"See Also","text":""},{"location":"tools/events/subscribe-events.html","title":"Event Subscription Tool","text":"

The Event Subscription tool provides functionality to subscribe to and monitor real-time events from your Home Assistant instance.

"},{"location":"tools/events/subscribe-events.html#features","title":"Features","text":""},{"location":"tools/events/subscribe-events.html#usage","title":"Usage","text":""},{"location":"tools/events/subscribe-events.html#rest-api","title":"REST API","text":"
POST /api/events/subscribe\nDELETE /api/events/unsubscribe\nGET /api/events/subscriptions\nGET /api/events/history\n
"},{"location":"tools/events/subscribe-events.html#websocket","title":"WebSocket","text":"
// Subscribe to events\n{\n    \"type\": \"subscribe_events\",\n    \"event_type\": \"optional_event_type\",\n    \"entity_id\": \"optional_entity_id\",\n    \"domain\": \"optional_domain\"\n}\n\n// Unsubscribe from events\n{\n    \"type\": \"unsubscribe_events\",\n    \"subscription_id\": \"required_subscription_id\"\n}\n
"},{"location":"tools/events/subscribe-events.html#server-sent-events-sse","title":"Server-Sent Events (SSE)","text":"
GET /api/events/stream?event_type=state_changed&entity_id=light.living_room\n
"},{"location":"tools/events/subscribe-events.html#event-types","title":"Event Types","text":""},{"location":"tools/events/subscribe-events.html#examples","title":"Examples","text":""},{"location":"tools/events/subscribe-events.html#subscribe-to-all-state-changes","title":"Subscribe to All State Changes","text":"
const response = await fetch('http://your-ha-mcp/api/events/subscribe', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"event_type\": \"state_changed\"\n    })\n});\n
"},{"location":"tools/events/subscribe-events.html#monitor-specific-entity","title":"Monitor Specific Entity","text":"
const response = await fetch('http://your-ha-mcp/api/events/subscribe', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"event_type\": \"state_changed\",\n        \"entity_id\": \"light.living_room\"\n    })\n});\n
"},{"location":"tools/events/subscribe-events.html#domain-based-monitoring","title":"Domain-Based Monitoring","text":"
const response = await fetch('http://your-ha-mcp/api/events/subscribe', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"event_type\": \"state_changed\",\n        \"domain\": \"light\"\n    })\n});\n
"},{"location":"tools/events/subscribe-events.html#sse-connection-example","title":"SSE Connection Example","text":"
const eventSource = new EventSource(\n    'http://your-ha-mcp/api/events/stream?event_type=state_changed&entity_id=light.living_room',\n    {\n        headers: {\n            'Authorization': 'Bearer your_access_token'\n        }\n    }\n);\n\neventSource.onmessage = (event) => {\n    const data = JSON.parse(event.data);\n    console.log('Event received:', data);\n};\n\neventSource.onerror = (error) => {\n    console.error('SSE error:', error);\n    eventSource.close();\n};\n
"},{"location":"tools/events/subscribe-events.html#response-format","title":"Response Format","text":""},{"location":"tools/events/subscribe-events.html#subscription-response","title":"Subscription Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"subscription_id\": \"sub_123\",\n        \"event_type\": \"state_changed\",\n        \"entity_id\": \"light.living_room\",\n        \"created_at\": \"2024-02-05T12:00:00Z\"\n    }\n}\n
"},{"location":"tools/events/subscribe-events.html#event-message-format","title":"Event Message Format","text":"
{\n    \"event_type\": \"state_changed\",\n    \"entity_id\": \"light.living_room\",\n    \"data\": {\n        \"old_state\": {\n            \"state\": \"off\",\n            \"attributes\": {},\n            \"last_changed\": \"2024-02-05T11:55:00Z\"\n        },\n        \"new_state\": {\n            \"state\": \"on\",\n            \"attributes\": {\n                \"brightness\": 255\n            },\n            \"last_changed\": \"2024-02-05T12:00:00Z\"\n        }\n    },\n    \"origin\": \"LOCAL\",\n    \"time_fired\": \"2024-02-05T12:00:00Z\",\n    \"context\": {\n        \"id\": \"context_123\",\n        \"parent_id\": null,\n        \"user_id\": \"user_123\"\n    }\n}\n
"},{"location":"tools/events/subscribe-events.html#subscriptions-list-response","title":"Subscriptions List Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"subscriptions\": [\n            {\n                \"id\": \"sub_123\",\n                \"event_type\": \"state_changed\",\n                \"entity_id\": \"light.living_room\",\n                \"created_at\": \"2024-02-05T12:00:00Z\",\n                \"last_event\": \"2024-02-05T12:05:00Z\"\n            }\n        ]\n    }\n}\n
"},{"location":"tools/events/subscribe-events.html#error-handling","title":"Error Handling","text":""},{"location":"tools/events/subscribe-events.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/events/subscribe-events.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/events/subscribe-events.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/events/subscribe-events.html#best-practices","title":"Best Practices","text":"
  1. Use specific event types when possible
  2. Implement proper error handling
  3. Handle connection interruptions
  4. Process events asynchronously
  5. Implement backoff strategies
  6. Monitor subscription health
  7. Clean up unused subscriptions
  8. Handle rate limiting gracefully
"},{"location":"tools/events/subscribe-events.html#connection-management","title":"Connection Management","text":""},{"location":"tools/events/subscribe-events.html#see-also","title":"See Also","text":""},{"location":"tools/history-state/history.html","title":"Device History Tool","text":"

The Device History tool allows you to retrieve historical state information for devices in your Home Assistant instance.

"},{"location":"tools/history-state/history.html#features","title":"Features","text":""},{"location":"tools/history-state/history.html#usage","title":"Usage","text":""},{"location":"tools/history-state/history.html#rest-api","title":"REST API","text":"
GET /api/history/{device_id}\nGET /api/history/{device_id}/period/{start_time}\nGET /api/history/{device_id}/period/{start_time}/{end_time}\n
"},{"location":"tools/history-state/history.html#websocket","title":"WebSocket","text":"
{\n    \"type\": \"get_history\",\n    \"device_id\": \"required_device_id\",\n    \"start_time\": \"optional_iso_timestamp\",\n    \"end_time\": \"optional_iso_timestamp\",\n    \"significant_changes_only\": false\n}\n
"},{"location":"tools/history-state/history.html#query-parameters","title":"Query Parameters","text":"Parameter Type Description start_time ISO timestamp Start of the period to fetch history for end_time ISO timestamp End of the period to fetch history for significant_changes_only boolean Only return significant state changes minimal_response boolean Return minimal state information no_attributes boolean Exclude attribute data from response"},{"location":"tools/history-state/history.html#examples","title":"Examples","text":""},{"location":"tools/history-state/history.html#get-recent-history","title":"Get Recent History","text":"
const response = await fetch('http://your-ha-mcp/api/history/light.living_room', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst history = await response.json();\n
"},{"location":"tools/history-state/history.html#get-history-for-specific-period","title":"Get History for Specific Period","text":"
const startTime = '2024-02-01T00:00:00Z';\nconst endTime = '2024-02-02T00:00:00Z';\nconst response = await fetch(\n    `http://your-ha-mcp/api/history/light.living_room/period/${startTime}/${endTime}`, \n    {\n        headers: {\n            'Authorization': 'Bearer your_access_token'\n        }\n    }\n);\nconst history = await response.json();\n
"},{"location":"tools/history-state/history.html#response-format","title":"Response Format","text":""},{"location":"tools/history-state/history.html#history-response","title":"History Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"history\": [\n            {\n                \"state\": \"on\",\n                \"attributes\": {\n                    \"brightness\": 255\n                },\n                \"last_changed\": \"2024-02-05T12:00:00Z\",\n                \"last_updated\": \"2024-02-05T12:00:00Z\"\n            },\n            {\n                \"state\": \"off\",\n                \"last_changed\": \"2024-02-05T13:00:00Z\",\n                \"last_updated\": \"2024-02-05T13:00:00Z\"\n            }\n        ]\n    }\n}\n
"},{"location":"tools/history-state/history.html#aggregated-history-response","title":"Aggregated History Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"aggregates\": {\n            \"daily\": [\n                {\n                    \"date\": \"2024-02-05\",\n                    \"on_time\": \"PT5H30M\",\n                    \"off_time\": \"PT18H30M\",\n                    \"changes\": 10\n                }\n            ]\n        }\n    }\n}\n
"},{"location":"tools/history-state/history.html#error-handling","title":"Error Handling","text":""},{"location":"tools/history-state/history.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/history-state/history.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/history-state/history.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/history-state/history.html#data-retention","title":"Data Retention","text":""},{"location":"tools/history-state/history.html#best-practices","title":"Best Practices","text":"
  1. Use appropriate time ranges to avoid large responses
  2. Enable significant_changes_only for better performance
  3. Use minimal_response when full state data isn't needed
  4. Implement proper error handling
  5. Cache frequently accessed historical data
  6. Handle rate limiting gracefully
"},{"location":"tools/history-state/history.html#see-also","title":"See Also","text":""},{"location":"tools/history-state/scene.html","title":"Scene Management Tool","text":"

The Scene Management tool provides functionality to manage and control scenes in your Home Assistant instance.

"},{"location":"tools/history-state/scene.html#features","title":"Features","text":""},{"location":"tools/history-state/scene.html#usage","title":"Usage","text":""},{"location":"tools/history-state/scene.html#rest-api","title":"REST API","text":"
GET /api/scenes\nGET /api/scenes/{scene_id}\nPOST /api/scenes/{scene_id}/activate\nPOST /api/scenes\nPUT /api/scenes/{scene_id}\nDELETE /api/scenes/{scene_id}\n
"},{"location":"tools/history-state/scene.html#websocket","title":"WebSocket","text":"
// List scenes\n{\n    \"type\": \"get_scenes\"\n}\n\n// Activate scene\n{\n    \"type\": \"activate_scene\",\n    \"scene_id\": \"required_scene_id\"\n}\n\n// Create/Update scene\n{\n    \"type\": \"create_scene\",\n    \"scene\": {\n        \"name\": \"required_scene_name\",\n        \"entities\": {\n            // Entity states\n        }\n    }\n}\n
"},{"location":"tools/history-state/scene.html#scene-configuration","title":"Scene Configuration","text":""},{"location":"tools/history-state/scene.html#scene-definition","title":"Scene Definition","text":"
{\n    \"name\": \"Movie Night\",\n    \"entities\": {\n        \"light.living_room\": {\n            \"state\": \"on\",\n            \"brightness\": 50,\n            \"color_temp\": 2700\n        },\n        \"cover.living_room\": {\n            \"state\": \"closed\"\n        },\n        \"media_player.tv\": {\n            \"state\": \"on\",\n            \"source\": \"HDMI 1\"\n        }\n    }\n}\n
"},{"location":"tools/history-state/scene.html#examples","title":"Examples","text":""},{"location":"tools/history-state/scene.html#list-all-scenes","title":"List All Scenes","text":"
const response = await fetch('http://your-ha-mcp/api/scenes', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst scenes = await response.json();\n
"},{"location":"tools/history-state/scene.html#activate-a-scene","title":"Activate a Scene","text":"
const response = await fetch('http://your-ha-mcp/api/scenes/movie_night/activate', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\n
"},{"location":"tools/history-state/scene.html#create-a-new-scene","title":"Create a New Scene","text":"
const response = await fetch('http://your-ha-mcp/api/scenes', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"name\": \"Movie Night\",\n        \"entities\": {\n            \"light.living_room\": {\n                \"state\": \"on\",\n                \"brightness\": 50\n            },\n            \"cover.living_room\": {\n                \"state\": \"closed\"\n            }\n        }\n    })\n});\n
"},{"location":"tools/history-state/scene.html#response-format","title":"Response Format","text":""},{"location":"tools/history-state/scene.html#scene-list-response","title":"Scene List Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"scenes\": [\n            {\n                \"id\": \"scene_id\",\n                \"name\": \"Scene Name\",\n                \"entities\": {\n                    // Entity configurations\n                }\n            }\n        ]\n    }\n}\n
"},{"location":"tools/history-state/scene.html#scene-activation-response","title":"Scene Activation Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"scene_id\": \"activated_scene_id\",\n        \"status\": \"activated\",\n        \"timestamp\": \"2024-02-05T12:00:00Z\"\n    }\n}\n
"},{"location":"tools/history-state/scene.html#error-handling","title":"Error Handling","text":""},{"location":"tools/history-state/scene.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/history-state/scene.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/history-state/scene.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/history-state/scene.html#best-practices","title":"Best Practices","text":"
  1. Validate entity availability before creating scenes
  2. Use meaningful scene names
  3. Group related entities in scenes
  4. Implement proper error handling
  5. Cache scene configurations when possible
  6. Handle rate limiting gracefully
"},{"location":"tools/history-state/scene.html#scene-transitions","title":"Scene Transitions","text":"

Scenes can include transition settings for smooth state changes:

{\n    \"name\": \"Sunset Mode\",\n    \"entities\": {\n        \"light.living_room\": {\n            \"state\": \"on\",\n            \"brightness\": 128,\n            \"transition\": 5  // 5 seconds\n        }\n    }\n}\n
"},{"location":"tools/history-state/scene.html#see-also","title":"See Also","text":""},{"location":"tools/notifications/notify.html","title":"Notification Tool","text":"

The Notification tool provides functionality to send notifications through various services in your Home Assistant instance.

"},{"location":"tools/notifications/notify.html#features","title":"Features","text":""},{"location":"tools/notifications/notify.html#usage","title":"Usage","text":""},{"location":"tools/notifications/notify.html#rest-api","title":"REST API","text":"
POST /api/notify\nPOST /api/notify/{service_id}\nGET /api/notify/services\nGET /api/notify/history\n
"},{"location":"tools/notifications/notify.html#websocket","title":"WebSocket","text":"
// Send notification\n{\n    \"type\": \"send_notification\",\n    \"service\": \"required_service_id\",\n    \"message\": \"required_message\",\n    \"title\": \"optional_title\",\n    \"data\": {\n        // Service-specific data\n    }\n}\n\n// Get notification services\n{\n    \"type\": \"get_notification_services\"\n}\n
"},{"location":"tools/notifications/notify.html#supported-services","title":"Supported Services","text":""},{"location":"tools/notifications/notify.html#examples","title":"Examples","text":""},{"location":"tools/notifications/notify.html#basic-notification","title":"Basic Notification","text":"
const response = await fetch('http://your-ha-mcp/api/notify/mobile_app', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"message\": \"Motion detected in living room\",\n        \"title\": \"Security Alert\"\n    })\n});\n
"},{"location":"tools/notifications/notify.html#rich-notification","title":"Rich Notification","text":"
const response = await fetch('http://your-ha-mcp/api/notify/mobile_app', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"message\": \"Motion detected in living room\",\n        \"title\": \"Security Alert\",\n        \"data\": {\n            \"image\": \"https://your-camera-snapshot.jpg\",\n            \"actions\": [\n                {\n                    \"action\": \"view_camera\",\n                    \"title\": \"View Camera\"\n                },\n                {\n                    \"action\": \"dismiss\",\n                    \"title\": \"Dismiss\"\n                }\n            ],\n            \"priority\": \"high\",\n            \"ttl\": 3600,\n            \"group\": \"security\"\n        }\n    })\n});\n
"},{"location":"tools/notifications/notify.html#service-specific-example-telegram","title":"Service-Specific Example (Telegram)","text":"
const response = await fetch('http://your-ha-mcp/api/notify/telegram', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"message\": \"Temperature is too high!\",\n        \"title\": \"Climate Alert\",\n        \"data\": {\n            \"parse_mode\": \"markdown\",\n            \"inline_keyboard\": [\n                [\n                    {\n                        \"text\": \"Turn On AC\",\n                        \"callback_data\": \"turn_on_ac\"\n                    }\n                ]\n            ]\n        }\n    })\n});\n
"},{"location":"tools/notifications/notify.html#response-format","title":"Response Format","text":""},{"location":"tools/notifications/notify.html#success-response","title":"Success Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"notification_id\": \"notification_123\",\n        \"status\": \"sent\",\n        \"timestamp\": \"2024-02-05T12:00:00Z\",\n        \"service\": \"mobile_app\"\n    }\n}\n
"},{"location":"tools/notifications/notify.html#services-list-response","title":"Services List Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"services\": [\n            {\n                \"id\": \"mobile_app\",\n                \"name\": \"Mobile App\",\n                \"enabled\": true,\n                \"features\": [\n                    \"actions\",\n                    \"images\",\n                    \"sound\"\n                ]\n            }\n        ]\n    }\n}\n
"},{"location":"tools/notifications/notify.html#notification-history-response","title":"Notification History Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"history\": [\n            {\n                \"id\": \"notification_123\",\n                \"service\": \"mobile_app\",\n                \"message\": \"Motion detected\",\n                \"title\": \"Security Alert\",\n                \"timestamp\": \"2024-02-05T12:00:00Z\",\n                \"status\": \"delivered\"\n            }\n        ]\n    }\n}\n
"},{"location":"tools/notifications/notify.html#error-handling","title":"Error Handling","text":""},{"location":"tools/notifications/notify.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/notifications/notify.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/notifications/notify.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/notifications/notify.html#best-practices","title":"Best Practices","text":"
  1. Use appropriate priority levels
  2. Group related notifications
  3. Include relevant context
  4. Implement proper error handling
  5. Use templates for consistency
  6. Consider time zones
  7. Respect user preferences
  8. Handle rate limiting gracefully
"},{"location":"tools/notifications/notify.html#notification-templates","title":"Notification Templates","text":"
// Template example\n{\n    \"template\": \"security_alert\",\n    \"data\": {\n        \"location\": \"living_room\",\n        \"event_type\": \"motion\",\n        \"timestamp\": \"2024-02-05T12:00:00Z\"\n    }\n}\n
"},{"location":"tools/notifications/notify.html#see-also","title":"See Also","text":""}]} \ No newline at end of file +{"config":{"lang":["en"],"separator":"[\\s\\-,:!=\\[\\]()\"/]+|(?!\\b)(?=[A-Z][a-z])|\\.(?!\\d)|&[lg]t;","pipeline":["stopWordFilter"]},"docs":[{"location":"index.html","title":"Advanced Home Assistant MCP","text":"

Welcome to the Advanced Home Assistant Master Control Program documentation.

This documentation provides comprehensive information about setting up, configuring, and using the Advanced Home Assistant MCP system.

"},{"location":"index.html#quick-links","title":"Quick Links","text":""},{"location":"index.html#what-is-mcp-server","title":"What is MCP Server?","text":"

MCP Server is a bridge between Home Assistant and custom automation tools, enabling basic device control and real-time monitoring of your smart home environment. It provides a flexible interface for managing and interacting with your home automation setup.

"},{"location":"index.html#key-features","title":"Key Features","text":""},{"location":"index.html#device-control","title":"\ud83c\udfae Device Control","text":""},{"location":"index.html#security-performance","title":"\ud83d\udee1\ufe0f Security & Performance","text":""},{"location":"index.html#documentation-structure","title":"Documentation Structure","text":""},{"location":"index.html#getting-started","title":"Getting Started","text":""},{"location":"index.html#core-documentation","title":"Core Documentation","text":""},{"location":"index.html#support","title":"Support","text":"

Need help or want to report issues?

"},{"location":"index.html#license","title":"License","text":"

This project is licensed under the MIT License. See the LICENSE file for details.

"},{"location":"api.html","title":"Home Assistant MCP Server API Documentation","text":""},{"location":"api.html#overview","title":"Overview","text":"

This document provides a reference for the MCP Server API, which offers basic device control and state management for Home Assistant.

"},{"location":"api.html#authentication","title":"Authentication","text":"

All API requests require a valid JWT token in the Authorization header:

Authorization: Bearer YOUR_TOKEN\n
"},{"location":"api.html#core-endpoints","title":"Core Endpoints","text":""},{"location":"api.html#device-state-management","title":"Device State Management","text":""},{"location":"api.html#get-device-state","title":"Get Device State","text":"
GET /api/state/{entity_id}\n

Response:

{\n  \"entity_id\": \"light.living_room\",\n  \"state\": \"on\",\n  \"attributes\": {\n    \"brightness\": 128\n  }\n}\n

"},{"location":"api.html#update-device-state","title":"Update Device State","text":"
POST /api/state\nContent-Type: application/json\n\n{\n  \"entity_id\": \"light.living_room\",\n  \"state\": \"on\",\n  \"attributes\": {\n    \"brightness\": 128\n  }\n}\n
"},{"location":"api.html#device-control","title":"Device Control","text":""},{"location":"api.html#execute-device-command","title":"Execute Device Command","text":"
POST /api/control\nContent-Type: application/json\n\n{\n  \"entity_id\": \"light.living_room\",\n  \"command\": \"turn_on\",\n  \"parameters\": {\n    \"brightness\": 50\n  }\n}\n
"},{"location":"api.html#real-time-updates","title":"Real-Time Updates","text":""},{"location":"api.html#websocket-connection","title":"WebSocket Connection","text":"

Connect to real-time updates:

const ws = new WebSocket('ws://localhost:3000/events');\nws.onmessage = (event) => {\n  const deviceUpdate = JSON.parse(event.data);\n  console.log('Device state changed:', deviceUpdate);\n};\n
"},{"location":"api.html#error-handling","title":"Error Handling","text":""},{"location":"api.html#common-error-responses","title":"Common Error Responses","text":"
{\n  \"error\": {\n    \"code\": \"INVALID_REQUEST\",\n    \"message\": \"Invalid request parameters\",\n    \"details\": \"Entity ID not found or invalid command\"\n  }\n}\n
"},{"location":"api.html#rate-limiting","title":"Rate Limiting","text":"

Basic rate limiting is implemented: - Maximum of 100 requests per minute - Excess requests will receive a 429 Too Many Requests response

"},{"location":"api.html#supported-operations","title":"Supported Operations","text":""},{"location":"api.html#supported-commands","title":"Supported Commands","text":""},{"location":"api.html#supported-entities","title":"Supported Entities","text":""},{"location":"api.html#limitations","title":"Limitations","text":""},{"location":"api.html#best-practices","title":"Best Practices","text":"
  1. Always include a valid JWT token
  2. Handle potential errors in your client code
  3. Use WebSocket for real-time updates when possible
  4. Validate entity IDs before sending commands
"},{"location":"api.html#example-client-usage","title":"Example Client Usage","text":"
async function controlDevice(entityId: string, command: string, params?: Record<string, unknown>) {\n  try {\n    const response = await fetch('/api/control', {\n    method: 'POST',\n    headers: {\n        'Content-Type': 'application/json',\n        'Authorization': `Bearer ${token}`\n    },\n    body: JSON.stringify({\n        entity_id: entityId,\n        command,\n        parameters: params\n    })\n  });\n\n    if (!response.ok) {\n      const error = await response.json();\n      throw new Error(error.message);\n    }\n\n    return await response.json();\n} catch (error) {\n    console.error('Device control failed:', error);\n    throw error;\n  }\n}\n\n// Usage example\ncontrolDevice('light.living_room', 'turn_on', { brightness: 50 })\n  .then(result => console.log('Device controlled successfully'))\n  .catch(error => console.error('Control failed', error));\n
"},{"location":"api.html#future-development","title":"Future Development","text":"

Planned improvements: - Enhanced error handling - More comprehensive device support - Improved authentication mechanisms

API is subject to change. Always refer to the latest documentation.

"},{"location":"architecture.html","title":"Architecture Overview \ud83c\udfd7\ufe0f","text":"

This document describes the architecture of the MCP Server, explaining how different components work together to provide a bridge between Home Assistant and custom automation tools.

"},{"location":"architecture.html#system-architecture","title":"System Architecture","text":"
graph TD\n    subgraph \"Client Layer\"\n        WC[Web Clients]\n        MC[Mobile Clients]\n    end\n\n    subgraph \"MCP Server\"\n        API[API Gateway]\n        SSE[SSE Manager]\n        WS[WebSocket Server]\n        CM[Command Manager]\n    end\n\n    subgraph \"Home Assistant\"\n        HA[Home Assistant Core]\n        Dev[Devices & Services]\n    end\n\n    WC --> |HTTP/WS| API\n    MC --> |HTTP/WS| API\n\n    API --> |Events| SSE\n    API --> |Real-time| WS\n\n    API --> HA\n    HA --> API
"},{"location":"architecture.html#core-components","title":"Core Components","text":""},{"location":"architecture.html#api-gateway","title":"API Gateway","text":""},{"location":"architecture.html#sse-manager","title":"SSE Manager","text":""},{"location":"architecture.html#websocket-server","title":"WebSocket Server","text":""},{"location":"architecture.html#command-manager","title":"Command Manager","text":""},{"location":"architecture.html#communication-flow","title":"Communication Flow","text":"
  1. Client sends a request to the MCP Server API
  2. API Gateway authenticates the request
  3. Command Manager processes the request
  4. Request is forwarded to Home Assistant
  5. Response is sent back to the client via API or WebSocket
"},{"location":"architecture.html#key-design-principles","title":"Key Design Principles","text":""},{"location":"architecture.html#limitations","title":"Limitations","text":""},{"location":"architecture.html#future-improvements","title":"Future Improvements","text":"

Architecture is subject to change as the project evolves.

"},{"location":"configuration.html","title":"System Configuration","text":"

This document provides detailed information about configuring the Home Assistant MCP Server.

"},{"location":"configuration.html#configuration-file-structure","title":"Configuration File Structure","text":"

The MCP Server uses environment variables for configuration, with support for different environments (development, test, production):

# .env, .env.development, or .env.test\nPORT=4000\nNODE_ENV=development\nHASS_HOST=http://192.168.178.63:8123\nHASS_TOKEN=your_token_here\nJWT_SECRET=your_secret_key\n
"},{"location":"configuration.html#server-settings","title":"Server Settings","text":""},{"location":"configuration.html#basic-server-configuration","title":"Basic Server Configuration","text":""},{"location":"configuration.html#security-settings","title":"Security Settings","text":""},{"location":"configuration.html#websocket-settings","title":"WebSocket Settings","text":""},{"location":"configuration.html#speech-features-optional","title":"Speech Features (Optional)","text":""},{"location":"configuration.html#environment-variables","title":"Environment Variables","text":"

All configuration is managed through environment variables:

# Server\nPORT=4000\nNODE_ENV=development\n\n# Home Assistant\nHASS_HOST=http://your-hass-instance:8123\nHASS_TOKEN=your_token_here\n\n# Security\nJWT_SECRET=your-secret-key\n\n# Logging\nLOG_LEVEL=info\nLOG_DIR=logs\nLOG_MAX_SIZE=20m\nLOG_MAX_DAYS=14d\nLOG_COMPRESS=true\nLOG_REQUESTS=true\n\n# Speech Features (Optional)\nENABLE_SPEECH_FEATURES=false\nENABLE_WAKE_WORD=false\nENABLE_SPEECH_TO_TEXT=false\nWHISPER_MODEL_PATH=/models\nWHISPER_MODEL_TYPE=base\n
"},{"location":"configuration.html#advanced-configuration","title":"Advanced Configuration","text":""},{"location":"configuration.html#security-rate-limiting","title":"Security Rate Limiting","text":"

Rate limiting is enabled by default to protect against brute force attacks:

RATE_LIMIT: {\n  windowMs: 15 * 60 * 1000,  // 15 minutes\n  max: 100  // limit each IP to 100 requests per window\n}\n
"},{"location":"configuration.html#logging","title":"Logging","text":"

The server uses Bun's built-in logging capabilities with additional configuration:

LOGGING: {\n  LEVEL: \"info\",  // debug, info, warn, error\n  DIR: \"logs\",\n  MAX_SIZE: \"20m\",\n  MAX_DAYS: \"14d\",\n  COMPRESS: true,\n  TIMESTAMP_FORMAT: \"YYYY-MM-DD HH:mm:ss:ms\",\n  LOG_REQUESTS: true\n}\n
"},{"location":"configuration.html#speech-to-text-configuration","title":"Speech-to-Text Configuration","text":"

When speech features are enabled, you can configure the following options:

SPEECH: {\n  ENABLED: false,  // Master switch for all speech features\n  WAKE_WORD_ENABLED: false,  // Enable wake word detection\n  SPEECH_TO_TEXT_ENABLED: false,  // Enable speech-to-text\n  WHISPER_MODEL_PATH: \"/models\",  // Path to Whisper models\n  WHISPER_MODEL_TYPE: \"base\",  // Model type to use\n}\n

Available Whisper models: - tiny.en: Fastest, lowest accuracy - base.en: Good balance of speed and accuracy - small.en: Better accuracy, slower - medium.en: High accuracy, much slower - large-v2: Best accuracy, very slow

For production deployments, we recommend using system tools like logrotate for log management.

Example logrotate configuration (/etc/logrotate.d/mcp-server):

/var/log/mcp-server.log {\n    daily\n    rotate 7\n    compress\n    delaycompress\n    missingok\n    notifempty\n    create 644 mcp mcp\n}\n

"},{"location":"configuration.html#best-practices","title":"Best Practices","text":"
  1. Always use environment variables for sensitive information
  2. Keep .env files secure and never commit them to version control
  3. Use different environment files for development, test, and production
  4. Enable SSL/TLS in production (preferably via reverse proxy)
  5. Monitor log files for issues
  6. Regularly rotate logs in production
  7. Start with smaller Whisper models and upgrade if needed
  8. Consider GPU acceleration for larger Whisper models
"},{"location":"configuration.html#validation","title":"Validation","text":"

The server validates configuration on startup using Zod schemas: - Required fields are checked (e.g., HASS_TOKEN) - Value types are verified - Enums are validated (e.g., LOG_LEVEL, WHISPER_MODEL_TYPE) - Default values are applied when not specified

"},{"location":"configuration.html#troubleshooting","title":"Troubleshooting","text":"

Common configuration issues: 1. Missing required environment variables 2. Invalid environment variable values 3. Permission issues with log directories 4. Rate limiting too restrictive 5. Speech model loading failures 6. Docker not available for speech features 7. Insufficient system resources for larger models

See the Troubleshooting Guide for solutions.

"},{"location":"configuration.html#configuration-guide","title":"Configuration Guide","text":"

This document describes all available configuration options for the Home Assistant MCP Server.

"},{"location":"configuration.html#environment-variables_1","title":"Environment Variables","text":""},{"location":"configuration.html#required-settings","title":"Required Settings","text":"
# Server Configuration\nPORT=3000                      # Server port\nHOST=localhost                 # Server host\n\n# Home Assistant\nHASS_URL=http://localhost:8123 # Home Assistant URL\nHASS_TOKEN=your_token         # Long-lived access token\n\n# Security\nJWT_SECRET=your_secret        # JWT signing secret\n
"},{"location":"configuration.html#optional-settings","title":"Optional Settings","text":"
# Rate Limiting\nRATE_LIMIT_WINDOW=60000       # Time window in ms (default: 60000)\nRATE_LIMIT_MAX=100           # Max requests per window (default: 100)\n\n# Logging\nLOG_LEVEL=info               # debug, info, warn, error (default: info)\nLOG_DIR=logs                 # Log directory (default: logs)\nLOG_MAX_SIZE=10m            # Max log file size (default: 10m)\nLOG_MAX_FILES=5             # Max number of log files (default: 5)\n\n# WebSocket/SSE\nWS_HEARTBEAT=30000          # WebSocket heartbeat interval in ms (default: 30000)\nSSE_RETRY=3000             # SSE retry interval in ms (default: 3000)\n\n# Speech Features\nENABLE_SPEECH_FEATURES=false # Enable speech processing (default: false)\nENABLE_WAKE_WORD=false      # Enable wake word detection (default: false)\nENABLE_SPEECH_TO_TEXT=false # Enable speech-to-text (default: false)\n\n# Speech Model Configuration\nWHISPER_MODEL_PATH=/models  # Path to whisper models (default: /models)\nWHISPER_MODEL_TYPE=base     # Model type: tiny|base|small|medium|large-v2 (default: base)\nWHISPER_LANGUAGE=en        # Primary language (default: en)\nWHISPER_TASK=transcribe    # Task type: transcribe|translate (default: transcribe)\nWHISPER_DEVICE=cuda        # Processing device: cpu|cuda (default: cuda if available, else cpu)\n\n# Wake Word Configuration\nWAKE_WORDS=hey jarvis,ok google,alexa  # Comma-separated wake words (default: hey jarvis)\nWAKE_WORD_SENSITIVITY=0.5   # Detection sensitivity 0-1 (default: 0.5)\n
"},{"location":"configuration.html#speech-features","title":"Speech Features","text":""},{"location":"configuration.html#model-selection","title":"Model Selection","text":"

Choose a model based on your needs:

Model Size Memory Required Speed Accuracy tiny.en 75MB 1GB Fast Basic base.en 150MB 2GB Good Good small.en 500MB 4GB Med Better medium.en 1.5GB 8GB Slow High large-v2 3GB 16GB Slow Best"},{"location":"configuration.html#gpu-acceleration","title":"GPU Acceleration","text":"

When WHISPER_DEVICE=cuda: - NVIDIA GPU with CUDA support required - Significantly faster processing - Higher memory requirements

"},{"location":"configuration.html#wake-word-detection","title":"Wake Word Detection","text":""},{"location":"configuration.html#best-practices_1","title":"Best Practices","text":"
  1. Model Selection:
  2. Start with base.en model
  3. Upgrade if better accuracy needed
  4. Downgrade if performance issues

  5. Resource Management:

  6. Monitor memory usage
  7. Use GPU acceleration when available
  8. Consider model size vs available resources

  9. Wake Word Configuration:

  10. Use distinct wake words
  11. Adjust sensitivity based on environment
  12. Limit number of wake words for better performance
"},{"location":"contributing.html","title":"Contributing Guide \ud83e\udd1d","text":"

Thank you for your interest in contributing to the MCP Server project!

"},{"location":"contributing.html#getting-started","title":"Getting Started","text":""},{"location":"contributing.html#prerequisites","title":"Prerequisites","text":""},{"location":"contributing.html#development-setup","title":"Development Setup","text":"
  1. Fork the repository
  2. Clone your fork:

    git clone https://github.com/YOUR_USERNAME/homeassistant-mcp.git\ncd homeassistant-mcp\n

  3. Install dependencies:

    bun install\n

  4. Configure environment:

    cp .env.example .env\n# Edit .env with your Home Assistant details\n

"},{"location":"contributing.html#development-workflow","title":"Development Workflow","text":""},{"location":"contributing.html#branch-naming","title":"Branch Naming","text":"

Example:

git checkout -b feature/device-control-improvements\n

"},{"location":"contributing.html#commit-messages","title":"Commit Messages","text":"

Follow simple, clear commit messages:

type: brief description\n\n[optional detailed explanation]\n

Types: - feat: - New feature - fix: - Bug fix - docs: - Documentation - chore: - Maintenance

"},{"location":"contributing.html#code-style","title":"Code Style","text":""},{"location":"contributing.html#testing","title":"Testing","text":"

Run tests before submitting:

# Run all tests\nbun test\n\n# Run specific test\nbun test test/api/control.test.ts\n
"},{"location":"contributing.html#pull-request-process","title":"Pull Request Process","text":"
  1. Ensure tests pass
  2. Update documentation if needed
  3. Provide clear description of changes
"},{"location":"contributing.html#pr-template","title":"PR Template","text":"
## Description\nBrief explanation of the changes\n\n## Type of Change\n- [ ] Bug fix\n- [ ] New feature\n- [ ] Documentation update\n\n## Testing\nDescribe how you tested these changes\n
"},{"location":"contributing.html#reporting-issues","title":"Reporting Issues","text":""},{"location":"contributing.html#code-of-conduct","title":"Code of Conduct","text":""},{"location":"contributing.html#resources","title":"Resources","text":"

Thank you for contributing!

"},{"location":"deployment.html","title":"Deployment Guide","text":"

This documentation is automatically deployed to GitHub Pages using GitHub Actions. Here's how it works and how to manage deployments.

"},{"location":"deployment.html#automatic-deployment","title":"Automatic Deployment","text":"

The documentation is automatically deployed when changes are pushed to the main or master branch. The deployment process:

  1. Triggers on push to main/master
  2. Sets up Python environment
  3. Installs required dependencies
  4. Builds the documentation
  5. Deploys to the gh-pages branch
"},{"location":"deployment.html#github-actions-workflow","title":"GitHub Actions Workflow","text":"

The deployment is handled by the workflow in .github/workflows/deploy-docs.yml. This is the single source of truth for documentation deployment:

name: Deploy MkDocs\non:\n  push:\n    branches:\n      - main\n      - master\n  workflow_dispatch:  # Allow manual trigger\n
"},{"location":"deployment.html#manual-deployment","title":"Manual Deployment","text":"

If needed, you can deploy manually using:

# Create a virtual environment\npython -m venv venv\n\n# Activate the virtual environment\nsource venv/bin/activate\n\n# Install dependencies\npip install -r docs/requirements.txt\n\n# Build the documentation\nmkdocs build\n\n# Deploy to GitHub Pages\nmkdocs gh-deploy --force\n
"},{"location":"deployment.html#best-practices","title":"Best Practices","text":""},{"location":"deployment.html#1-documentation-updates","title":"1. Documentation Updates","text":""},{"location":"deployment.html#2-version-control","title":"2. Version Control","text":""},{"location":"deployment.html#3-content-guidelines","title":"3. Content Guidelines","text":""},{"location":"deployment.html#4-maintenance","title":"4. Maintenance","text":""},{"location":"deployment.html#troubleshooting","title":"Troubleshooting","text":""},{"location":"deployment.html#common-issues","title":"Common Issues","text":"
  1. Failed Deployments
  2. Check GitHub Actions logs
  3. Verify dependencies are up to date
  4. Ensure all required files exist

  5. Broken Links

  6. Run mkdocs build --strict
  7. Use relative paths in markdown
  8. Check case sensitivity

  9. Style Issues

  10. Verify theme configuration
  11. Check CSS customizations
  12. Test on multiple browsers
"},{"location":"deployment.html#configuration-files","title":"Configuration Files","text":""},{"location":"deployment.html#requirementstxt","title":"requirements.txt","text":"

Create a requirements file for documentation dependencies:

mkdocs-material\nmkdocs-minify-plugin\nmkdocs-git-revision-date-plugin\nmkdocs-mkdocstrings\nmkdocs-social-plugin\nmkdocs-redirects\n
"},{"location":"deployment.html#monitoring","title":"Monitoring","text":""},{"location":"deployment.html#workflow-features","title":"Workflow Features","text":""},{"location":"deployment.html#caching","title":"Caching","text":"

The workflow implements caching for Python dependencies to speed up deployments: - Pip cache for Python packages - MkDocs dependencies cache

"},{"location":"deployment.html#deployment-checks","title":"Deployment Checks","text":"

Several checks are performed during deployment: 1. Link validation with mkdocs build --strict 2. Build verification 3. Post-deployment site accessibility check

"},{"location":"deployment.html#manual-triggers","title":"Manual Triggers","text":"

You can manually trigger deployments using the \"workflow_dispatch\" event in GitHub Actions.

"},{"location":"deployment.html#cleanup","title":"Cleanup","text":"

To clean up duplicate workflow files, run:

# Make the script executable\nchmod +x scripts/cleanup-workflows.sh\n\n# Run the cleanup script\n./scripts/cleanup-workflows.sh\n
"},{"location":"roadmap.html","title":"Roadmap for MCP Server","text":"

The following roadmap outlines our planned enhancements and future directions for the Home Assistant MCP Server. This document is a living guide that will be updated as new features are developed.

"},{"location":"roadmap.html#near-term-goals","title":"Near-Term Goals","text":""},{"location":"roadmap.html#mid-term-goals","title":"Mid-Term Goals","text":""},{"location":"roadmap.html#long-term-vision","title":"Long-Term Vision","text":""},{"location":"roadmap.html#how-to-follow-the-roadmap","title":"How to Follow the Roadmap","text":"

This roadmap is intended as a guide and may evolve based on community needs, technological advancements, and strategic priorities.

"},{"location":"security.html","title":"Security Guide","text":"

This document outlines security best practices and configurations for the Home Assistant MCP Server.

"},{"location":"security.html#authentication","title":"Authentication","text":""},{"location":"security.html#jwt-authentication","title":"JWT Authentication","text":"

The server uses JWT (JSON Web Tokens) for API authentication:

Authorization: Bearer YOUR_JWT_TOKEN\n
"},{"location":"security.html#token-configuration","title":"Token Configuration","text":"
security:\n  jwt_secret: YOUR_SECRET_KEY\n  token_expiry: 24h\n  refresh_token_expiry: 7d\n
"},{"location":"security.html#access-control","title":"Access Control","text":""},{"location":"security.html#cors-configuration","title":"CORS Configuration","text":"

Configure allowed origins to prevent unauthorized access:

security:\n  allowed_origins:\n    - http://localhost:3000\n    - https://your-domain.com\n
"},{"location":"security.html#ip-filtering","title":"IP Filtering","text":"

Restrict access by IP address:

security:\n  allowed_ips:\n    - 192.168.1.0/24\n    - 10.0.0.0/8\n
"},{"location":"security.html#ssltls-configuration","title":"SSL/TLS Configuration","text":""},{"location":"security.html#enable-https","title":"Enable HTTPS","text":"
ssl:\n  enabled: true\n  cert_file: /path/to/cert.pem\n  key_file: /path/to/key.pem\n
"},{"location":"security.html#certificate-management","title":"Certificate Management","text":"
  1. Use Let's Encrypt for free SSL certificates
  2. Regularly renew certificates
  3. Monitor certificate expiration
"},{"location":"security.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"security.html#basic-rate-limiting","title":"Basic Rate Limiting","text":"
rate_limit:\n  enabled: true\n  requests_per_minute: 100\n  burst: 20\n
"},{"location":"security.html#advanced-rate-limiting","title":"Advanced Rate Limiting","text":"
rate_limit:\n  rules:\n    - endpoint: /api/control\n      requests_per_minute: 50\n    - endpoint: /api/state\n      requests_per_minute: 200\n
"},{"location":"security.html#data-protection","title":"Data Protection","text":""},{"location":"security.html#sensitive-data","title":"Sensitive Data","text":""},{"location":"security.html#logging-security","title":"Logging Security","text":""},{"location":"security.html#best-practices","title":"Best Practices","text":"
  1. Regular Security Updates
  2. Keep dependencies updated
  3. Monitor security advisories
  4. Apply patches promptly

  5. Password Policies

  6. Enforce strong passwords
  7. Implement password expiration
  8. Use secure password storage

  9. Monitoring

  10. Log security events
  11. Monitor access patterns
  12. Set up alerts for suspicious activity

  13. Network Security

  14. Use VPN for remote access
  15. Implement network segmentation
  16. Configure firewalls properly
"},{"location":"security.html#security-checklist","title":"Security Checklist","text":""},{"location":"security.html#incident-response","title":"Incident Response","text":"
  1. Detection
  2. Monitor security logs
  3. Set up intrusion detection
  4. Configure alerts

  5. Response

  6. Document incident details
  7. Isolate affected systems
  8. Investigate root cause

  9. Recovery

  10. Apply security fixes
  11. Restore from backups
  12. Update security measures
"},{"location":"security.html#additional-resources","title":"Additional Resources","text":""},{"location":"testing.html","title":"Testing Documentation","text":""},{"location":"testing.html#quick-reference","title":"Quick Reference","text":"
# Most Common Commands\nbun test                    # Run all tests\nbun test --watch           # Run tests in watch mode\nbun test --coverage        # Run tests with coverage\nbun test path/to/test.ts   # Run a specific test file\n\n# Additional Options\nDEBUG=true bun test        # Run with debug output\nbun test --pattern \"auth\"  # Run tests matching a pattern\nbun test --timeout 60000   # Run with a custom timeout\n
"},{"location":"testing.html#overview","title":"Overview","text":"

This document describes the testing setup and practices used in the Home Assistant MCP project. We use Bun's test runner for both unit and integration testing, ensuring comprehensive coverage across modules.

"},{"location":"testing.html#test-structure","title":"Test Structure","text":"

Tests are organized in two main locations:

  1. Root Level Integration Tests (/__tests__/):
__tests__/\n\u251c\u2500\u2500 ai/              # AI/ML component tests\n\u251c\u2500\u2500 api/             # API integration tests\n\u251c\u2500\u2500 context/         # Context management tests\n\u251c\u2500\u2500 hass/            # Home Assistant integration tests\n\u251c\u2500\u2500 schemas/         # Schema validation tests\n\u251c\u2500\u2500 security/        # Security integration tests\n\u251c\u2500\u2500 tools/           # Tools and utilities tests\n\u251c\u2500\u2500 websocket/       # WebSocket integration tests\n\u251c\u2500\u2500 helpers.test.ts  # Helper function tests\n\u251c\u2500\u2500 index.test.ts    # Main application tests\n\u2514\u2500\u2500 server.test.ts   # Server integration tests\n
  1. Component Level Unit Tests (src/**/):
src/\n\u251c\u2500\u2500 __tests__/   # Global test setup and utilities\n\u2502   \u2514\u2500\u2500 setup.ts # Global test configuration\n\u251c\u2500\u2500 component/\n\u2502   \u251c\u2500\u2500 __tests__/   # Component-specific unit tests\n\u2502   \u2514\u2500\u2500 component.ts\n
"},{"location":"testing.html#test-configuration","title":"Test Configuration","text":""},{"location":"testing.html#bun-test-configuration-bunfigtoml","title":"Bun Test Configuration (bunfig.toml)","text":"
[test]\npreload = [\"./src/__tests__/setup.ts\"]  # Global test setup\ncoverage = true                         # Enable coverage by default\ntimeout = 30000                         # Test timeout in milliseconds\ntestMatch = [\"**/__tests__/**/*.test.ts\"] # Test file patterns\n
"},{"location":"testing.html#bun-scripts","title":"Bun Scripts","text":"

Available test commands in package.json:

# Run all tests\nbun test\n\n# Watch mode for development\nbun test --watch\n\n# Generate coverage report\nbun test --coverage\n\n# Run linting\nbun run lint\n\n# Format code\nbun run format\n
"},{"location":"testing.html#test-setup","title":"Test Setup","text":""},{"location":"testing.html#global-configuration","title":"Global Configuration","text":"

A global test setup file (src/__tests__/setup.ts) provides: - Environment configuration - Mock utilities - Test helper functions - Global lifecycle hooks

"},{"location":"testing.html#test-environment","title":"Test Environment","text":""},{"location":"testing.html#running-tests","title":"Running Tests","text":"
# Basic test run\nbun test\n\n# Run tests with coverage\nbun test --coverage\n\n# Run a specific test file\nbun test path/to/test.test.ts\n\n# Run tests in watch mode\nbun test --watch\n\n# Run tests with debug output\nDEBUG=true bun test\n\n# Run tests with increased timeout\nbun test --timeout 60000\n\n# Run tests matching a pattern\nbun test --pattern \"auth\"\n
"},{"location":"testing.html#advanced-debugging","title":"Advanced Debugging","text":""},{"location":"testing.html#using-node-inspector","title":"Using Node Inspector","text":"
# Start tests with inspector\nbun test --inspect\n\n# Start tests with inspector and break on first line\nbun test --inspect-brk\n
"},{"location":"testing.html#using-vs-code","title":"Using VS Code","text":"

Create a launch configuration in .vscode/launch.json:

{\n  \"version\": \"0.2.0\",\n  \"configurations\": [\n    {\n      \"type\": \"bun\",\n      \"request\": \"launch\",\n      \"name\": \"Debug Tests\",\n      \"program\": \"${workspaceFolder}/node_modules/bun/bin/bun\",\n      \"args\": [\"test\", \"${file}\"],\n      \"cwd\": \"${workspaceFolder}\",\n      \"env\": { \"DEBUG\": \"true\" }\n    }\n  ]\n}\n
"},{"location":"testing.html#test-isolation","title":"Test Isolation","text":"

To run a single test in isolation:

describe.only(\"specific test suite\", () => {\n  it.only(\"specific test case\", () => {\n    // Only this test will run\n  });\n});\n
"},{"location":"testing.html#writing-tests","title":"Writing Tests","text":""},{"location":"testing.html#test-file-naming","title":"Test File Naming","text":""},{"location":"testing.html#example-test-structure","title":"Example Test Structure","text":"
describe(\"Security Features\", () => {\n  it(\"should validate tokens correctly\", () => {\n    const payload = { userId: \"123\", role: \"user\" };\n    const token = jwt.sign(payload, validSecret, { expiresIn: \"1h\" });\n    const result = TokenManager.validateToken(token, testIp);\n    expect(result.valid).toBe(true);\n  });\n});\n
"},{"location":"testing.html#coverage","title":"Coverage","text":"

The project maintains strict coverage: - Overall coverage: at least 80% - Critical paths: 90%+ - New features: \u226585% coverage

Generate a coverage report with:

bun test --coverage\n
"},{"location":"testing.html#security-middleware-testing","title":"Security Middleware Testing","text":""},{"location":"testing.html#utility-function-testing","title":"Utility Function Testing","text":"

The security middleware now uses a utility-first approach, which allows for more granular and comprehensive testing. Each security function is now independently testable, improving code reliability and maintainability.

"},{"location":"testing.html#key-utility-functions","title":"Key Utility Functions","text":"
  1. Rate Limiting (checkRateLimit)
  2. Tests multiple scenarios:
    • Requests under threshold
    • Requests exceeding threshold
    • Rate limit reset after window expiration
// Example test\nit('should throw when requests exceed threshold', () => {\n  const ip = '127.0.0.2';\n  for (let i = 0; i < 11; i++) {\n    if (i < 10) {\n      expect(() => checkRateLimit(ip, 10)).not.toThrow();\n    } else {\n      expect(() => checkRateLimit(ip, 10)).toThrow('Too many requests from this IP');\n    }\n  }\n});\n
  1. Request Validation (validateRequestHeaders)
  2. Tests content type validation
  3. Checks request size limits
  4. Validates authorization headers
it('should reject invalid content type', () => {\n  const mockRequest = new Request('http://localhost', {\n    method: 'POST',\n    headers: { 'content-type': 'text/plain' }\n  });\n  expect(() => validateRequestHeaders(mockRequest)).toThrow('Content-Type must be application/json');\n});\n
  1. Input Sanitization (sanitizeValue)
  2. Sanitizes HTML tags
  3. Handles nested objects
  4. Preserves non-string values
it('should sanitize HTML tags', () => {\n  const input = '<script>alert(\"xss\")</script>Hello';\n  const sanitized = sanitizeValue(input);\n  expect(sanitized).toBe('&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;Hello');\n});\n
  1. Security Headers (applySecurityHeaders)
  2. Verifies correct security header application
  3. Checks CSP, frame options, and other security headers
it('should apply security headers', () => {\n  const mockRequest = new Request('http://localhost');\n  const headers = applySecurityHeaders(mockRequest);\n  expect(headers['content-security-policy']).toBeDefined();\n  expect(headers['x-frame-options']).toBeDefined();\n});\n
  1. Error Handling (handleError)
  2. Tests error responses in production and development modes
  3. Verifies error message and stack trace inclusion
it('should include error details in development mode', () => {\n  const error = new Error('Test error');\n  const result = handleError(error, 'development');\n  expect(result).toEqual({\n    error: true,\n    message: 'Internal server error',\n    error: 'Test error',\n    stack: expect.any(String)\n  });\n});\n
"},{"location":"testing.html#testing-philosophy","title":"Testing Philosophy","text":""},{"location":"testing.html#best-practices","title":"Best Practices","text":"
  1. Use minimal, focused test cases
  2. Test both successful and failure scenarios
  3. Verify input sanitization and security measures
  4. Mock external dependencies when necessary
"},{"location":"testing.html#running-security-tests","title":"Running Security Tests","text":"
# Run all tests\nbun test\n\n# Run specific security tests\nbun test __tests__/security/\n
"},{"location":"testing.html#continuous-improvement","title":"Continuous Improvement","text":""},{"location":"testing.html#best-practices_1","title":"Best Practices","text":"
  1. Isolation: Each test should be independent and not rely on the state of other tests.
  2. Mocking: Use the provided mock utilities for external dependencies.
  3. Cleanup: Clean up any resources or state modifications in afterEach or afterAll hooks.
  4. Descriptive Names: Use clear, descriptive test names that explain the expected behavior.
  5. Assertions: Make specific, meaningful assertions rather than general ones.
  6. Setup: Use beforeEach for common test setup to avoid repetition.
  7. Error Cases: Test both success and error cases for complete coverage.
"},{"location":"testing.html#coverage_1","title":"Coverage","text":"

The project aims for high test coverage, particularly focusing on: - Security-critical code paths - API endpoints - Data validation - Error handling - Event broadcasting

Run coverage reports using:

bun test --coverage\n

"},{"location":"testing.html#debugging-tests","title":"Debugging Tests","text":"

To debug tests: 1. Set DEBUG=true to enable console output during tests 2. Use the --watch flag for development 3. Add console.log() statements (they're only shown when DEBUG is true) 4. Use the test utilities' debugging helpers

"},{"location":"testing.html#advanced-debugging_1","title":"Advanced Debugging","text":"
  1. Using Node Inspector:

    # Start tests with inspector\nbun test --inspect\n\n# Start tests with inspector and break on first line\nbun test --inspect-brk\n

  2. Using VS Code:

    // .vscode/launch.json\n{\n  \"version\": \"0.2.0\",\n  \"configurations\": [\n    {\n      \"type\": \"bun\",\n      \"request\": \"launch\",\n      \"name\": \"Debug Tests\",\n      \"program\": \"${workspaceFolder}/node_modules/bun/bin/bun\",\n      \"args\": [\"test\", \"${file}\"],\n      \"cwd\": \"${workspaceFolder}\",\n      \"env\": { \"DEBUG\": \"true\" }\n    }\n  ]\n}\n

  3. Test Isolation: To run a single test in isolation:

    describe.only(\"specific test suite\", () => {\n  it.only(\"specific test case\", () => {\n    // Only this test will run\n  });\n});\n

"},{"location":"testing.html#contributing","title":"Contributing","text":"

When contributing new code: 1. Add tests for new features 2. Ensure existing tests pass 3. Maintain or improve coverage 4. Follow the existing test patterns and naming conventions 5. Document any new test utilities or patterns

"},{"location":"testing.html#coverage-requirements","title":"Coverage Requirements","text":"

The project maintains strict coverage requirements:

Coverage reports are generated in multiple formats: - Console summary - HTML report (./coverage/index.html) - LCOV report (./coverage/lcov.info)

To view detailed coverage:

# Generate and open coverage report\nbun test --coverage && open coverage/index.html\n

"},{"location":"troubleshooting.html","title":"Troubleshooting Guide \ud83d\udd27","text":"

This guide helps you diagnose and resolve common issues with MCP Server.

"},{"location":"troubleshooting.html#quick-diagnostics","title":"Quick Diagnostics","text":""},{"location":"troubleshooting.html#health-check","title":"Health Check","text":"

First, verify the server's health:

curl http://localhost:3000/health\n

Expected response:

{\n  \"status\": \"healthy\",\n  \"version\": \"1.0.0\",\n  \"uptime\": 3600,\n  \"homeAssistant\": {\n    \"connected\": true,\n    \"version\": \"2024.1.0\"\n  }\n}\n

"},{"location":"troubleshooting.html#common-issues","title":"Common Issues","text":""},{"location":"troubleshooting.html#1-connection-issues","title":"1. Connection Issues","text":""},{"location":"troubleshooting.html#cannot-connect-to-mcp-server","title":"Cannot Connect to MCP Server","text":"

Symptoms: - Server not responding - Connection refused errors - Timeout errors

Solutions:

  1. Check if the server is running:

    # For Docker installation\ndocker compose ps\n\n# For manual installation\nps aux | grep mcp\n

  2. Verify port availability:

    # Check if port is in use\nnetstat -tuln | grep 3000\n

  3. Check logs:

    # Docker logs\ndocker compose logs mcp\n\n# Manual installation logs\nbun run dev\n

"},{"location":"troubleshooting.html#home-assistant-connection-failed","title":"Home Assistant Connection Failed","text":"

Symptoms: - \"Connection Error\" in health check - Cannot control devices - State updates not working

Solutions:

  1. Verify Home Assistant URL and token in .env:

    HA_URL=http://homeassistant:8123\nHA_TOKEN=your_long_lived_access_token\n

  2. Test Home Assistant connection:

    curl -H \"Authorization: Bearer YOUR_HA_TOKEN\" \\\n     http://your-homeassistant:8123/api/\n

  3. Check network connectivity:

    # For Docker setup\ndocker compose exec mcp ping homeassistant\n

"},{"location":"troubleshooting.html#2-authentication-issues","title":"2. Authentication Issues","text":""},{"location":"troubleshooting.html#invalid-token","title":"Invalid Token","text":"

Symptoms: - 401 Unauthorized responses - \"Invalid token\" errors

Solutions:

  1. Generate a new token:

    curl -X POST http://localhost:3000/auth/token \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"username\": \"your_username\", \"password\": \"your_password\"}'\n

  2. Verify token format:

    // Token should be in format:\nAuthorization: Bearer eyJhbGciOiJIUzI1NiIs...\n

"},{"location":"troubleshooting.html#rate-limiting","title":"Rate Limiting","text":"

Symptoms: - 429 Too Many Requests - \"Rate limit exceeded\" errors

Solutions:

  1. Check current rate limit status:

    curl -I http://localhost:3000/api/state\n

  2. Adjust rate limits in configuration:

    security:\n  rateLimit: 100  # Increase if needed\n  rateLimitWindow: 60000  # Window in milliseconds\n

"},{"location":"troubleshooting.html#3-real-time-updates-issues","title":"3. Real-time Updates Issues","text":""},{"location":"troubleshooting.html#sse-connection-drops","title":"SSE Connection Drops","text":"

Symptoms: - Frequent disconnections - Missing state updates - EventSource errors

Solutions:

  1. Implement proper reconnection logic:

    class SSEClient {\n    constructor() {\n        this.connect();\n    }\n\n    connect() {\n        this.eventSource = new EventSource('/subscribe_events');\n        this.eventSource.onerror = this.handleError.bind(this);\n    }\n\n    handleError(error) {\n        console.error('SSE Error:', error);\n        this.eventSource.close();\n        setTimeout(() => this.connect(), 1000);\n    }\n}\n

  2. Check network stability:

    # Monitor connection stability\nping -c 100 localhost\n

"},{"location":"troubleshooting.html#4-performance-issues","title":"4. Performance Issues","text":""},{"location":"troubleshooting.html#high-latency","title":"High Latency","text":"

Symptoms: - Slow response times - Command execution delays - UI lag

Solutions:

  1. Enable Redis caching:

    REDIS_ENABLED=true\nREDIS_URL=redis://localhost:6379\n

  2. Monitor system resources:

    # Check CPU and memory usage\ndocker stats\n\n# Or for manual installation\ntop -p $(pgrep -f mcp)\n

  3. Optimize database queries and caching:

    // Use batch operations\nconst results = await Promise.all([\n    cache.get('key1'),\n    cache.get('key2')\n]);\n

"},{"location":"troubleshooting.html#5-device-control-issues","title":"5. Device Control Issues","text":""},{"location":"troubleshooting.html#commands-not-executing","title":"Commands Not Executing","text":"

Symptoms: - Commands appear successful but no device response - Inconsistent device states - Error messages from Home Assistant

Solutions:

  1. Verify device availability:

    curl http://localhost:3000/api/state/light.living_room\n

  2. Check command syntax:

    # Test basic command\ncurl -X POST http://localhost:3000/api/command \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"command\": \"Turn on living room lights\"}'\n

  3. Review Home Assistant logs:

    docker compose exec homeassistant journalctl -f\n

"},{"location":"troubleshooting.html#debugging-tools","title":"Debugging Tools","text":""},{"location":"troubleshooting.html#log-analysis","title":"Log Analysis","text":"

Enable debug logging:

LOG_LEVEL=debug\nDEBUG=mcp:*\n
"},{"location":"troubleshooting.html#network-debugging","title":"Network Debugging","text":"

Monitor network traffic:

# TCP dump for API traffic\ntcpdump -i any port 3000 -w debug.pcap\n
"},{"location":"troubleshooting.html#performance-profiling","title":"Performance Profiling","text":"

Enable performance monitoring:

ENABLE_METRICS=true\nMETRICS_PORT=9090\n
"},{"location":"troubleshooting.html#getting-help","title":"Getting Help","text":"

If you're still experiencing issues:

  1. Check the GitHub Issues
  2. Search Discussions
  3. Create a new issue with:
  4. Detailed description
  5. Logs
  6. Configuration (sanitized)
  7. Steps to reproduce
"},{"location":"troubleshooting.html#maintenance","title":"Maintenance","text":""},{"location":"troubleshooting.html#regular-health-checks","title":"Regular Health Checks","text":"

Run periodic health checks:

# Create a cron job\n*/5 * * * * curl -f http://localhost:3000/health || notify-admin\n
"},{"location":"troubleshooting.html#log-rotation","title":"Log Rotation","text":"

Configure log rotation:

logging:\n  maxSize: \"100m\"\n  maxFiles: \"7d\"\n  compress: true\n
"},{"location":"troubleshooting.html#backup-configuration","title":"Backup Configuration","text":"

Regularly backup your configuration:

# Backup script\ntar -czf mcp-backup-$(date +%Y%m%d).tar.gz \\\n    .env \\\n    config/ \\\n    data/\n
"},{"location":"troubleshooting.html#faq","title":"FAQ","text":""},{"location":"troubleshooting.html#general-questions","title":"General Questions","text":""},{"location":"troubleshooting.html#q-what-is-mcp-server","title":"Q: What is MCP Server?","text":"

A: MCP Server is a bridge between Home Assistant and Language Learning Models, enabling natural language control and automation of your smart home devices.

"},{"location":"troubleshooting.html#q-what-are-the-system-requirements","title":"Q: What are the system requirements?","text":"

A: MCP Server requires: - Node.js 16 or higher - Home Assistant instance - 1GB RAM minimum - 1GB disk space

"},{"location":"troubleshooting.html#q-how-do-i-update-mcp-server","title":"Q: How do I update MCP Server?","text":"

A: For Docker installation:

docker compose pull\ndocker compose up -d\n
For manual installation:
git pull\nbun install\nbun run build\n

"},{"location":"troubleshooting.html#integration-questions","title":"Integration Questions","text":""},{"location":"troubleshooting.html#q-can-i-use-mcp-server-with-any-home-assistant-instance","title":"Q: Can I use MCP Server with any Home Assistant instance?","text":"

A: Yes, MCP Server works with any Home Assistant instance that has the REST API enabled and a valid long-lived access token.

"},{"location":"troubleshooting.html#q-does-mcp-server-support-all-home-assistant-integrations","title":"Q: Does MCP Server support all Home Assistant integrations?","text":"

A: MCP Server supports all Home Assistant devices and services that are accessible via the REST API.

"},{"location":"troubleshooting.html#security-questions","title":"Security Questions","text":""},{"location":"troubleshooting.html#q-is-my-home-assistant-token-secure","title":"Q: Is my Home Assistant token secure?","text":"

A: Yes, your Home Assistant token is stored securely and only used for authenticated communication between MCP Server and your Home Assistant instance.

"},{"location":"troubleshooting.html#q-can-i-use-mcp-server-remotely","title":"Q: Can I use MCP Server remotely?","text":"

A: Yes, but we recommend using a secure connection (HTTPS) and proper authentication when exposing MCP Server to the internet.

"},{"location":"troubleshooting.html#troubleshooting-questions","title":"Troubleshooting Questions","text":""},{"location":"troubleshooting.html#q-why-are-my-device-states-not-updating","title":"Q: Why are my device states not updating?","text":"

A: Check: 1. Home Assistant connection 2. WebSocket connection status 3. Device availability in Home Assistant 4. Network connectivity

"},{"location":"troubleshooting.html#q-why-are-my-commands-not-working","title":"Q: Why are my commands not working?","text":"

A: Verify: 1. Command syntax 2. Device availability 3. User permissions 4. Home Assistant API access

"},{"location":"usage.html","title":"Usage Guide","text":"

This guide explains how to use the Home Assistant MCP Server for basic device management and integration.

"},{"location":"usage.html#basic-setup","title":"Basic Setup","text":"
  1. Starting the Server:
  2. Development mode: bun run dev
  3. Production mode: bun run start

  4. Accessing the Server:

  5. Default URL: http://localhost:3000
  6. Ensure Home Assistant credentials are configured in .env
"},{"location":"usage.html#device-control","title":"Device Control","text":""},{"location":"usage.html#rest-api-interactions","title":"REST API Interactions","text":"

Basic device control can be performed via the REST API:

// Turn on a light\nfetch('http://localhost:3000/api/control', {\n  method: 'POST',\n  headers: {\n    'Content-Type': 'application/json',\n    'Authorization': `Bearer ${token}`\n  },\n  body: JSON.stringify({\n    entity_id: 'light.living_room',\n    command: 'turn_on',\n    parameters: { brightness: 50 }\n  })\n});\n
"},{"location":"usage.html#supported-commands","title":"Supported Commands","text":""},{"location":"usage.html#supported-entities","title":"Supported Entities","text":""},{"location":"usage.html#real-time-updates","title":"Real-Time Updates","text":""},{"location":"usage.html#websocket-connection","title":"WebSocket Connection","text":"

Subscribe to real-time device state changes:

const ws = new WebSocket('ws://localhost:3000/events');\nws.onmessage = (event) => {\n  const deviceUpdate = JSON.parse(event.data);\n  console.log('Device state changed:', deviceUpdate);\n};\n
"},{"location":"usage.html#authentication","title":"Authentication","text":"

All API requests require a valid JWT token in the Authorization header.

"},{"location":"usage.html#limitations","title":"Limitations","text":""},{"location":"usage.html#troubleshooting","title":"Troubleshooting","text":"
  1. Verify Home Assistant connection
  2. Check JWT token validity
  3. Ensure correct entity IDs
  4. Review server logs for detailed errors
"},{"location":"usage.html#configuration","title":"Configuration","text":"

Configure the server using environment variables in .env:

HA_URL=http://homeassistant:8123\nHA_TOKEN=your_home_assistant_token\nJWT_SECRET=your_jwt_secret\n
"},{"location":"usage.html#next-steps","title":"Next Steps","text":""},{"location":"api/index.html","title":"API Documentation \ud83d\udcda","text":"

Welcome to the MCP Server API documentation. This guide covers all available endpoints, authentication methods, and integration patterns.

"},{"location":"api/index.html#api-overview","title":"API Overview","text":"

The MCP Server provides several API categories:

  1. Core API - Basic device control and state management
  2. SSE API - Real-time event subscriptions
  3. Scene API - Scene management and automation
  4. Voice API - Natural language command processing
"},{"location":"api/index.html#authentication","title":"Authentication","text":"

All API endpoints require authentication using JWT tokens:

# Include the token in your requests\ncurl -H \"Authorization: Bearer YOUR_JWT_TOKEN\" http://localhost:3000/api/state\n

To obtain a token:

curl -X POST http://localhost:3000/auth/token \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"username\": \"your_username\", \"password\": \"your_password\"}'\n
"},{"location":"api/index.html#core-endpoints","title":"Core Endpoints","text":""},{"location":"api/index.html#device-state","title":"Device State","text":"
GET /api/state\n

Retrieve the current state of all devices:

curl http://localhost:3000/api/state\n

Response:

{\n  \"devices\": [\n    {\n      \"id\": \"light.living_room\",\n      \"state\": \"on\",\n      \"attributes\": {\n        \"brightness\": 255,\n        \"color_temp\": 370\n      }\n    }\n  ]\n}\n

"},{"location":"api/index.html#command-execution","title":"Command Execution","text":"
POST /api/command\n

Execute a natural language command:

curl -X POST http://localhost:3000/api/command \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"command\": \"Turn on the kitchen lights\"}'\n

Response:

{\n  \"success\": true,\n  \"action\": \"turn_on\",\n  \"device\": \"light.kitchen\",\n  \"message\": \"Kitchen lights turned on\"\n}\n

"},{"location":"api/index.html#real-time-events","title":"Real-Time Events","text":""},{"location":"api/index.html#event-subscription","title":"Event Subscription","text":"
GET /subscribe_events\n

Subscribe to device state changes:

const eventSource = new EventSource('http://localhost:3000/subscribe_events?token=YOUR_TOKEN');\n\neventSource.onmessage = (event) => {\n    const data = JSON.parse(event.data);\n    console.log('State changed:', data);\n};\n
"},{"location":"api/index.html#filtered-subscriptions","title":"Filtered Subscriptions","text":"

Subscribe to specific device types:

GET /subscribe_events?domain=light\nGET /subscribe_events?entity_id=light.living_room\n
"},{"location":"api/index.html#scene-management","title":"Scene Management","text":""},{"location":"api/index.html#create-scene","title":"Create Scene","text":"
POST /api/scene\n

Create a new scene:

curl -X POST http://localhost:3000/api/scene \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"Movie Night\",\n    \"actions\": [\n      {\"device\": \"light.living_room\", \"action\": \"dim\", \"value\": 20},\n      {\"device\": \"media_player.tv\", \"action\": \"on\"}\n    ]\n  }'\n
"},{"location":"api/index.html#activate-scene","title":"Activate Scene","text":"
POST /api/scene/activate\n

Activate an existing scene:

curl -X POST http://localhost:3000/api/scene/activate \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"name\": \"Movie Night\"}'\n
"},{"location":"api/index.html#error-handling","title":"Error Handling","text":"

The API uses standard HTTP status codes:

Error responses include detailed messages:

{\n  \"error\": true,\n  \"message\": \"Device not found\",\n  \"code\": \"DEVICE_NOT_FOUND\",\n  \"details\": {\n    \"device_id\": \"light.nonexistent\"\n  }\n}\n
"},{"location":"api/index.html#rate-limiting","title":"Rate Limiting","text":"

API requests are rate-limited to prevent abuse:

X-RateLimit-Limit: 100\nX-RateLimit-Remaining: 99\nX-RateLimit-Reset: 1640995200\n

When exceeded, returns 429 Too Many Requests:

{\n  \"error\": true,\n  \"message\": \"Rate limit exceeded\",\n  \"reset\": 1640995200\n}\n
"},{"location":"api/index.html#websocket-api","title":"WebSocket API","text":"

For bi-directional communication:

const ws = new WebSocket('ws://localhost:3000/ws');\n\nws.onmessage = (event) => {\n    const data = JSON.parse(event.data);\n    console.log('Received:', data);\n};\n\nws.send(JSON.stringify({\n    type: 'command',\n    payload: {\n        command: 'Turn on lights'\n    }\n}));\n
"},{"location":"api/index.html#api-versioning","title":"API Versioning","text":"

The current API version is v1. Include the version in the URL:

/api/v1/state\n/api/v1/command\n
"},{"location":"api/index.html#further-reading","title":"Further Reading","text":""},{"location":"api/index.html#api-reference","title":"API Reference","text":"

The Advanced Home Assistant MCP provides several APIs for integration and automation:

"},{"location":"api/core.html","title":"Core Functions API \ud83d\udd27","text":"

The Core Functions API provides the fundamental operations for interacting with Home Assistant devices and services through MCP Server.

"},{"location":"api/core.html#device-control","title":"Device Control","text":""},{"location":"api/core.html#get-device-state","title":"Get Device State","text":"

Retrieve the current state of devices.

GET /api/state\nGET /api/state/{entity_id}\n

Parameters: - entity_id (optional): Specific device ID to query

# Get all states\ncurl http://localhost:3000/api/state\n\n# Get specific device state\ncurl http://localhost:3000/api/state/light.living_room\n

Response:

{\n  \"entity_id\": \"light.living_room\",\n  \"state\": \"on\",\n  \"attributes\": {\n    \"brightness\": 255,\n    \"color_temp\": 370,\n    \"friendly_name\": \"Living Room Light\"\n  },\n  \"last_changed\": \"2024-01-20T15:30:00Z\"\n}\n

"},{"location":"api/core.html#control-device","title":"Control Device","text":"

Execute device commands.

POST /api/device/control\n

Request body:

{\n  \"entity_id\": \"light.living_room\",\n  \"action\": \"turn_on\",\n  \"parameters\": {\n    \"brightness\": 200,\n    \"color_temp\": 400\n  }\n}\n

Available actions: - turn_on - turn_off - toggle - set_value

Example with curl:

curl -X POST http://localhost:3000/api/device/control \\\n  -H \"Content-Type: application/json\" \\\n  -H \"Authorization: Bearer YOUR_JWT_TOKEN\" \\\n  -d '{\n    \"entity_id\": \"light.living_room\",\n    \"action\": \"turn_on\",\n    \"parameters\": {\n      \"brightness\": 200\n    }\n  }'\n

"},{"location":"api/core.html#natural-language-commands","title":"Natural Language Commands","text":""},{"location":"api/core.html#execute-command","title":"Execute Command","text":"

Process natural language commands.

POST /api/command\n

Request body:

{\n  \"command\": \"Turn on the living room lights and set them to 50% brightness\"\n}\n

Example usage:

curl -X POST http://localhost:3000/api/command \\\n  -H \"Content-Type: application/json\" \\\n  -H \"Authorization: Bearer YOUR_JWT_TOKEN\" \\\n  -d '{\n    \"command\": \"Turn on the living room lights and set them to 50% brightness\"\n  }'\n

Response:

{\n  \"success\": true,\n  \"actions\": [\n    {\n      \"entity_id\": \"light.living_room\",\n      \"action\": \"turn_on\",\n      \"parameters\": {\n        \"brightness\": 127\n      },\n      \"status\": \"completed\"\n    }\n  ],\n  \"message\": \"Command executed successfully\"\n}\n

"},{"location":"api/core.html#scene-management","title":"Scene Management","text":""},{"location":"api/core.html#create-scene","title":"Create Scene","text":"

Define a new scene with multiple actions.

POST /api/scene\n

Request body:

{\n  \"name\": \"Movie Night\",\n  \"description\": \"Perfect lighting for movie watching\",\n  \"actions\": [\n    {\n      \"entity_id\": \"light.living_room\",\n      \"action\": \"turn_on\",\n      \"parameters\": {\n        \"brightness\": 50,\n        \"color_temp\": 500\n      }\n    },\n    {\n      \"entity_id\": \"cover.living_room\",\n      \"action\": \"close\"\n    }\n  ]\n}\n

"},{"location":"api/core.html#activate-scene","title":"Activate Scene","text":"

Trigger a predefined scene.

POST /api/scene/{scene_name}/activate\n

Example:

curl -X POST http://localhost:3000/api/scene/movie_night/activate \\\n  -H \"Authorization: Bearer YOUR_JWT_TOKEN\"\n

"},{"location":"api/core.html#groups","title":"Groups","text":""},{"location":"api/core.html#create-device-group","title":"Create Device Group","text":"

Create a group of devices for collective control.

POST /api/group\n

Request body:

{\n  \"name\": \"Living Room\",\n  \"entities\": [\n    \"light.living_room_main\",\n    \"light.living_room_accent\",\n    \"switch.living_room_fan\"\n  ]\n}\n

"},{"location":"api/core.html#control-group","title":"Control Group","text":"

Control multiple devices in a group.

POST /api/group/{group_name}/control\n

Request body:

{\n  \"action\": \"turn_off\"\n}\n

"},{"location":"api/core.html#system-operations","title":"System Operations","text":""},{"location":"api/core.html#health-check","title":"Health Check","text":"

Check server status and connectivity.

GET /health\n

Response:

{\n  \"status\": \"healthy\",\n  \"version\": \"1.0.0\",\n  \"uptime\": 3600,\n  \"homeAssistant\": {\n    \"connected\": true,\n    \"version\": \"2024.1.0\"\n  }\n}\n

"},{"location":"api/core.html#configuration","title":"Configuration","text":"

Get current server configuration.

GET /api/config\n

Response:

{\n  \"server\": {\n    \"port\": 3000,\n    \"host\": \"0.0.0.0\",\n    \"version\": \"1.0.0\"\n  },\n  \"homeAssistant\": {\n    \"url\": \"http://homeassistant:8123\",\n    \"connected\": true\n  },\n  \"features\": {\n    \"nlp\": true,\n    \"scenes\": true,\n    \"groups\": true\n  }\n}\n

"},{"location":"api/core.html#error-handling","title":"Error Handling","text":"

All endpoints follow standard HTTP status codes and return detailed error messages:

{\n  \"error\": true,\n  \"code\": \"INVALID_ENTITY\",\n  \"message\": \"Device 'light.nonexistent' not found\",\n  \"details\": {\n    \"entity_id\": \"light.nonexistent\",\n    \"available_entities\": [\n      \"light.living_room\",\n      \"light.kitchen\"\n    ]\n  }\n}\n

Common error codes: - INVALID_ENTITY: Device not found - INVALID_ACTION: Unsupported action - INVALID_PARAMETERS: Invalid command parameters - AUTHENTICATION_ERROR: Invalid or missing token - CONNECTION_ERROR: Home Assistant connection issue

"},{"location":"api/core.html#typescript-interfaces","title":"TypeScript Interfaces","text":"
interface DeviceState {\n  entity_id: string;\n  state: string;\n  attributes: Record<string, any>;\n  last_changed: string;\n}\n\ninterface DeviceCommand {\n  entity_id: string;\n  action: 'turn_on' | 'turn_off' | 'toggle' | 'set_value';\n  parameters?: Record<string, any>;\n}\n\ninterface Scene {\n  name: string;\n  description?: string;\n  actions: DeviceCommand[];\n}\n\ninterface Group {\n  name: string;\n  entities: string[];\n}\n
"},{"location":"api/core.html#related-resources","title":"Related Resources","text":""},{"location":"api/sse.html","title":"Server-Sent Events (SSE) API \ud83d\udce1","text":"

The SSE API provides real-time updates about device states and events from your Home Assistant setup. This guide covers how to use and implement SSE connections in your applications.

"},{"location":"api/sse.html#overview","title":"Overview","text":"

Server-Sent Events (SSE) is a standard that enables servers to push real-time updates to clients over HTTP connections. MCP Server uses SSE to provide:

"},{"location":"api/sse.html#basic-usage","title":"Basic Usage","text":""},{"location":"api/sse.html#establishing-a-connection","title":"Establishing a Connection","text":"

Create an EventSource connection to receive updates:

const eventSource = new EventSource('http://localhost:3000/subscribe_events?token=YOUR_JWT_TOKEN');\n\neventSource.onmessage = (event) => {\n    const data = JSON.parse(event.data);\n    console.log('Received update:', data);\n};\n
"},{"location":"api/sse.html#connection-states","title":"Connection States","text":"

Handle different connection states:

eventSource.onopen = () => {\n    console.log('Connection established');\n};\n\neventSource.onerror = (error) => {\n    console.error('Connection error:', error);\n    // Implement reconnection logic if needed\n};\n
"},{"location":"api/sse.html#event-types","title":"Event Types","text":""},{"location":"api/sse.html#device-state-events","title":"Device State Events","text":"

Subscribe to all device state changes:

const stateEvents = new EventSource('http://localhost:3000/subscribe_events?type=state');\n\nstateEvents.onmessage = (event) => {\n    const state = JSON.parse(event.data);\n    console.log('Device state changed:', state);\n};\n

Example state event:

{\n  \"type\": \"state_changed\",\n  \"entity_id\": \"light.living_room\",\n  \"state\": \"on\",\n  \"attributes\": {\n    \"brightness\": 255,\n    \"color_temp\": 370\n  },\n  \"timestamp\": \"2024-01-20T15:30:00Z\"\n}\n

"},{"location":"api/sse.html#filtered-subscriptions","title":"Filtered Subscriptions","text":""},{"location":"api/sse.html#by-domain","title":"By Domain","text":"

Subscribe to specific device types:

// Subscribe to only light events\nconst lightEvents = new EventSource('http://localhost:3000/subscribe_events?domain=light');\n\n// Subscribe to multiple domains\nconst multiEvents = new EventSource('http://localhost:3000/subscribe_events?domain=light,switch,sensor');\n
"},{"location":"api/sse.html#by-entity-id","title":"By Entity ID","text":"

Subscribe to specific devices:

// Single entity\nconst livingRoomLight = new EventSource(\n    'http://localhost:3000/subscribe_events?entity_id=light.living_room'\n);\n\n// Multiple entities\nconst kitchenDevices = new EventSource(\n    'http://localhost:3000/subscribe_events?entity_id=light.kitchen,switch.coffee_maker'\n);\n
"},{"location":"api/sse.html#advanced-usage","title":"Advanced Usage","text":""},{"location":"api/sse.html#connection-management","title":"Connection Management","text":"

Implement robust connection handling:

class SSEManager {\n    constructor(url, options = {}) {\n        this.url = url;\n        this.options = {\n            maxRetries: 3,\n            retryDelay: 1000,\n            ...options\n        };\n        this.retryCount = 0;\n        this.connect();\n    }\n\n    connect() {\n        this.eventSource = new EventSource(this.url);\n\n        this.eventSource.onopen = () => {\n            this.retryCount = 0;\n            console.log('Connected to SSE stream');\n        };\n\n        this.eventSource.onerror = (error) => {\n            this.handleError(error);\n        };\n\n        this.eventSource.onmessage = (event) => {\n            this.handleMessage(event);\n        };\n    }\n\n    handleError(error) {\n        console.error('SSE Error:', error);\n        this.eventSource.close();\n\n        if (this.retryCount < this.options.maxRetries) {\n            this.retryCount++;\n            setTimeout(() => {\n                console.log(`Retrying connection (${this.retryCount}/${this.options.maxRetries})`);\n                this.connect();\n            }, this.options.retryDelay * this.retryCount);\n        }\n    }\n\n    handleMessage(event) {\n        try {\n            const data = JSON.parse(event.data);\n            // Handle the event data\n            console.log('Received:', data);\n        } catch (error) {\n            console.error('Error parsing SSE data:', error);\n        }\n    }\n\n    disconnect() {\n        if (this.eventSource) {\n            this.eventSource.close();\n        }\n    }\n}\n\n// Usage\nconst sseManager = new SSEManager('http://localhost:3000/subscribe_events?token=YOUR_TOKEN');\n
"},{"location":"api/sse.html#event-filtering","title":"Event Filtering","text":"

Filter events on the client side:

class EventFilter {\n    constructor(conditions) {\n        this.conditions = conditions;\n    }\n\n    matches(event) {\n        return Object.entries(this.conditions).every(([key, value]) => {\n            if (Array.isArray(value)) {\n                return value.includes(event[key]);\n            }\n            return event[key] === value;\n        });\n    }\n}\n\n// Usage\nconst filter = new EventFilter({\n    domain: ['light', 'switch'],\n    state: 'on'\n});\n\neventSource.onmessage = (event) => {\n    const data = JSON.parse(event.data);\n    if (filter.matches(data)) {\n        console.log('Matched event:', data);\n    }\n};\n
"},{"location":"api/sse.html#best-practices","title":"Best Practices","text":"
  1. Authentication
  2. Always include authentication tokens
  3. Implement token refresh mechanisms
  4. Handle authentication errors gracefully

  5. Error Handling

  6. Implement progressive retry logic
  7. Log connection issues
  8. Notify users of connection status

  9. Resource Management

  10. Close EventSource connections when not needed
  11. Limit the number of concurrent connections
  12. Use filtered subscriptions when possible

  13. Performance

  14. Process events efficiently
  15. Batch UI updates
  16. Consider debouncing frequent updates
"},{"location":"api/sse.html#common-issues","title":"Common Issues","text":""},{"location":"api/sse.html#connection-drops","title":"Connection Drops","text":"

If the connection drops, the EventSource will automatically attempt to reconnect. You can customize this behavior:

eventSource.addEventListener('error', (error) => {\n    if (eventSource.readyState === EventSource.CLOSED) {\n        // Connection closed, implement custom retry logic\n    }\n});\n
"},{"location":"api/sse.html#memory-leaks","title":"Memory Leaks","text":"

Always clean up EventSource connections:

// In a React component\nuseEffect(() => {\n    const eventSource = new EventSource('http://localhost:3000/subscribe_events');\n\n    return () => {\n        eventSource.close(); // Cleanup on unmount\n    };\n}, []);\n
"},{"location":"api/sse.html#related-resources","title":"Related Resources","text":""},{"location":"config/index.html","title":"Configuration","text":"

This section covers the configuration options available in the Home Assistant MCP Server.

"},{"location":"config/index.html#overview","title":"Overview","text":"

The MCP Server can be configured through various configuration files and environment variables. This section will guide you through the available options and their usage.

"},{"location":"config/index.html#configuration-files","title":"Configuration Files","text":"

The main configuration files are:

  1. .env - Environment variables
  2. config.yaml - Main configuration file
  3. devices.yaml - Device-specific configurations
"},{"location":"config/index.html#environment-variables","title":"Environment Variables","text":"

Key environment variables that can be set:

"},{"location":"config/index.html#next-steps","title":"Next Steps","text":""},{"location":"development/index.html","title":"Development Guide","text":"

Welcome to the development guide for the Home Assistant MCP Server. This section provides comprehensive information for developers who want to contribute to or extend the project.

"},{"location":"development/index.html#development-overview","title":"Development Overview","text":"

The MCP Server is built with modern development practices in mind, focusing on:

"},{"location":"development/index.html#getting-started","title":"Getting Started","text":"
  1. Set up your development environment
  2. Fork the repository
  3. Install dependencies
  4. Run tests
  5. Make your changes
  6. Submit a pull request
"},{"location":"development/index.html#development-topics","title":"Development Topics","text":""},{"location":"development/index.html#best-practices","title":"Best Practices","text":""},{"location":"development/index.html#development-workflow","title":"Development Workflow","text":"
  1. Create a feature branch
  2. Make your changes
  3. Run tests
  4. Update documentation
  5. Submit a pull request
  6. Address review comments
  7. Merge when approved
"},{"location":"development/index.html#next-steps","title":"Next Steps","text":""},{"location":"development/best-practices.html","title":"Development Best Practices","text":"

This guide outlines the best practices for developing tools and features for the Home Assistant MCP.

"},{"location":"development/best-practices.html#code-style","title":"Code Style","text":""},{"location":"development/best-practices.html#typescript","title":"TypeScript","text":"
  1. Use TypeScript for all new code
  2. Enable strict mode
  3. Use explicit types
  4. Avoid any type
  5. Use interfaces over types
  6. Document with JSDoc comments
/** \n * Represents a device in the system.\n * @interface\n */\ninterface Device {\n    /** Unique device identifier */\n    id: string;\n\n    /** Human-readable device name */\n    name: string;\n\n    /** Device state */\n    state: DeviceState;\n}\n
"},{"location":"development/best-practices.html#naming-conventions","title":"Naming Conventions","text":"
  1. Use PascalCase for:
  2. Classes
  3. Interfaces
  4. Types
  5. Enums

  6. Use camelCase for:

  7. Variables
  8. Functions
  9. Methods
  10. Properties

  11. Use UPPER_SNAKE_CASE for:

  12. Constants
  13. Enum values
class DeviceManager {\n    private readonly DEFAULT_TIMEOUT = 5000;\n\n    async getDeviceState(deviceId: string): Promise<DeviceState> {\n        // Implementation\n    }\n}\n
"},{"location":"development/best-practices.html#architecture","title":"Architecture","text":""},{"location":"development/best-practices.html#solid-principles","title":"SOLID Principles","text":"
  1. Single Responsibility
  2. Each class/module has one job
  3. Split complex functionality

  4. Open/Closed

  5. Open for extension
  6. Closed for modification

  7. Liskov Substitution

  8. Subtypes must be substitutable
  9. Use interfaces properly

  10. Interface Segregation

  11. Keep interfaces focused
  12. Split large interfaces

  13. Dependency Inversion

  14. Depend on abstractions
  15. Use dependency injection
"},{"location":"development/best-practices.html#example","title":"Example","text":"
// Bad\nclass DeviceManager {\n    async getState() { /* ... */ }\n    async setState() { /* ... */ }\n    async sendNotification() { /* ... */ }  // Wrong responsibility\n}\n\n// Good\nclass DeviceManager {\n    constructor(\n        private notifier: NotificationService\n    ) {}\n\n    async getState() { /* ... */ }\n    async setState() { /* ... */ }\n}\n\nclass NotificationService {\n    async send() { /* ... */ }\n}\n
"},{"location":"development/best-practices.html#error-handling","title":"Error Handling","text":""},{"location":"development/best-practices.html#best-practices","title":"Best Practices","text":"
  1. Use custom error classes
  2. Include error codes
  3. Provide meaningful messages
  4. Include error context
  5. Handle async errors
  6. Log appropriately
class DeviceError extends Error {\n    constructor(\n        message: string,\n        public code: string,\n        public context: Record<string, any>\n    ) {\n        super(message);\n        this.name = 'DeviceError';\n    }\n}\n\ntry {\n    await device.connect();\n} catch (error) {\n    throw new DeviceError(\n        'Failed to connect to device',\n        'DEVICE_CONNECTION_ERROR',\n        { deviceId: device.id, attempt: 1 }\n    );\n}\n
"},{"location":"development/best-practices.html#testing","title":"Testing","text":""},{"location":"development/best-practices.html#guidelines","title":"Guidelines","text":"
  1. Write unit tests first
  2. Use meaningful descriptions
  3. Test edge cases
  4. Mock external dependencies
  5. Keep tests focused
  6. Use test fixtures
describe('DeviceManager', () => {\n    let manager: DeviceManager;\n    let mockDevice: jest.Mocked<Device>;\n\n    beforeEach(() => {\n        mockDevice = {\n            id: 'test_device',\n            getState: jest.fn()\n        };\n        manager = new DeviceManager(mockDevice);\n    });\n\n    it('should get device state', async () => {\n        mockDevice.getState.mockResolvedValue('on');\n        const state = await manager.getDeviceState();\n        expect(state).toBe('on');\n    });\n});\n
"},{"location":"development/best-practices.html#performance","title":"Performance","text":""},{"location":"development/best-practices.html#optimization","title":"Optimization","text":"
  1. Use caching
  2. Implement pagination
  3. Optimize database queries
  4. Use connection pooling
  5. Implement rate limiting
  6. Batch operations
class DeviceCache {\n    private cache = new Map<string, CacheEntry>();\n    private readonly TTL = 60000;  // 1 minute\n\n    async getDevice(id: string): Promise<Device> {\n        const cached = this.cache.get(id);\n        if (cached && Date.now() - cached.timestamp < this.TTL) {\n            return cached.device;\n        }\n\n        const device = await this.fetchDevice(id);\n        this.cache.set(id, {\n            device,\n            timestamp: Date.now()\n        });\n\n        return device;\n    }\n}\n
"},{"location":"development/best-practices.html#security","title":"Security","text":""},{"location":"development/best-practices.html#guidelines_1","title":"Guidelines","text":"
  1. Validate all input
  2. Use parameterized queries
  3. Implement rate limiting
  4. Use proper authentication
  5. Follow OWASP guidelines
  6. Sanitize output
class InputValidator {\n    static validateDeviceId(id: string): boolean {\n        return /^[a-zA-Z0-9_-]{1,64}$/.test(id);\n    }\n\n    static sanitizeOutput(data: any): any {\n        // Implement output sanitization\n        return data;\n    }\n}\n
"},{"location":"development/best-practices.html#documentation","title":"Documentation","text":""},{"location":"development/best-practices.html#standards","title":"Standards","text":"
  1. Use JSDoc comments
  2. Document interfaces
  3. Include examples
  4. Document errors
  5. Keep docs updated
  6. Use markdown
/**\n * Manages device operations.\n * @class\n */\nclass DeviceManager {\n    /**\n     * Gets the current state of a device.\n     * @param {string} deviceId - The device identifier.\n     * @returns {Promise<DeviceState>} The current device state.\n     * @throws {DeviceError} If device is not found or unavailable.\n     * @example\n     * const state = await deviceManager.getDeviceState('living_room_light');\n     */\n    async getDeviceState(deviceId: string): Promise<DeviceState> {\n        // Implementation\n    }\n}\n
"},{"location":"development/best-practices.html#logging","title":"Logging","text":""},{"location":"development/best-practices.html#best-practices_1","title":"Best Practices","text":"
  1. Use appropriate levels
  2. Include context
  3. Structure log data
  4. Handle sensitive data
  5. Implement rotation
  6. Use correlation IDs
class Logger {\n    info(message: string, context: Record<string, any>) {\n        console.log(JSON.stringify({\n            level: 'info',\n            message,\n            context,\n            timestamp: new Date().toISOString(),\n            correlationId: context.correlationId\n        }));\n    }\n}\n
"},{"location":"development/best-practices.html#version-control","title":"Version Control","text":""},{"location":"development/best-practices.html#guidelines_2","title":"Guidelines","text":"
  1. Use meaningful commits
  2. Follow branching strategy
  3. Write good PR descriptions
  4. Review code thoroughly
  5. Keep changes focused
  6. Use conventional commits
# Good commit messages\ngit commit -m \"feat(device): add support for zigbee devices\"\ngit commit -m \"fix(api): handle timeout errors properly\"\n
"},{"location":"development/best-practices.html#see-also","title":"See Also","text":""},{"location":"development/environment.html","title":"Development Environment Setup","text":"

This guide will help you set up your development environment for the Home Assistant MCP Server.

"},{"location":"development/environment.html#prerequisites","title":"Prerequisites","text":""},{"location":"development/environment.html#required-software","title":"Required Software","text":""},{"location":"development/environment.html#system-requirements","title":"System Requirements","text":""},{"location":"development/environment.html#initial-setup","title":"Initial Setup","text":"
  1. Clone the Repository

    git clone https://github.com/jango-blockchained/homeassistant-mcp.git\ncd homeassistant-mcp\n

  2. Create Virtual Environment

    python -m venv .venv\nsource .venv/bin/activate  # Linux/macOS\n# or\n.venv\\Scripts\\activate  # Windows\n

  3. Install Dependencies

    pip install -r requirements.txt\npip install -r docs/requirements.txt  # for documentation\n

"},{"location":"development/environment.html#development-tools","title":"Development Tools","text":""},{"location":"development/environment.html#code-editor-setup","title":"Code Editor Setup","text":"

We recommend using Visual Studio Code with these extensions: - Python - Docker - YAML - ESLint - Prettier

"},{"location":"development/environment.html#vs-code-settings","title":"VS Code Settings","text":"
{\n  \"python.linting.enabled\": true,\n  \"python.linting.pylintEnabled\": true,\n  \"python.formatting.provider\": \"black\",\n  \"editor.formatOnSave\": true\n}\n
"},{"location":"development/environment.html#configuration","title":"Configuration","text":"
  1. Create Local Config

    cp config.example.yaml config.yaml\n

  2. Set Environment Variables

    cp .env.example .env\n# Edit .env with your settings\n

"},{"location":"development/environment.html#running-tests","title":"Running Tests","text":""},{"location":"development/environment.html#unit-tests","title":"Unit Tests","text":"
pytest tests/unit\n
"},{"location":"development/environment.html#integration-tests","title":"Integration Tests","text":"
pytest tests/integration\n
"},{"location":"development/environment.html#coverage-report","title":"Coverage Report","text":"
pytest --cov=src tests/\n
"},{"location":"development/environment.html#docker-development","title":"Docker Development","text":""},{"location":"development/environment.html#build-container","title":"Build Container","text":"
docker build -t mcp-server-dev -f Dockerfile.dev .\n
"},{"location":"development/environment.html#run-development-container","title":"Run Development Container","text":"
docker run -it --rm \\\n  -v $(pwd):/app \\\n  -p 8123:8123 \\\n  mcp-server-dev\n
"},{"location":"development/environment.html#database-setup","title":"Database Setup","text":""},{"location":"development/environment.html#local-development-database","title":"Local Development Database","text":"
docker run -d \\\n  -p 5432:5432 \\\n  -e POSTGRES_USER=mcp \\\n  -e POSTGRES_PASSWORD=development \\\n  -e POSTGRES_DB=mcp_dev \\\n  postgres:14\n
"},{"location":"development/environment.html#run-migrations","title":"Run Migrations","text":"
alembic upgrade head\n
"},{"location":"development/environment.html#frontend-development","title":"Frontend Development","text":"
  1. Install Node.js Dependencies

    cd frontend\nnpm install\n

  2. Start Development Server

    npm run dev\n

"},{"location":"development/environment.html#documentation","title":"Documentation","text":""},{"location":"development/environment.html#build-documentation","title":"Build Documentation","text":"
mkdocs serve\n
"},{"location":"development/environment.html#view-documentation","title":"View Documentation","text":"

Open http://localhost:8000 in your browser

"},{"location":"development/environment.html#debugging","title":"Debugging","text":""},{"location":"development/environment.html#vs-code-launch-configuration","title":"VS Code Launch Configuration","text":"
{\n  \"version\": \"0.2.0\",\n  \"configurations\": [\n    {\n      \"name\": \"Python: MCP Server\",\n      \"type\": \"python\",\n      \"request\": \"launch\",\n      \"program\": \"src/main.py\",\n      \"console\": \"integratedTerminal\"\n    }\n  ]\n}\n
"},{"location":"development/environment.html#git-hooks","title":"Git Hooks","text":""},{"location":"development/environment.html#install-pre-commit","title":"Install Pre-commit","text":"
pip install pre-commit\npre-commit install\n
"},{"location":"development/environment.html#available-hooks","title":"Available Hooks","text":""},{"location":"development/environment.html#troubleshooting","title":"Troubleshooting","text":"

Common Issues: 1. Port already in use - Check for running processes: lsof -i :8123 - Kill process if needed: kill -9 PID

  1. Database connection issues
  2. Verify PostgreSQL is running
  3. Check connection settings in .env

  4. Virtual environment problems

  5. Delete and recreate: rm -rf .venv && python -m venv .venv
  6. Reinstall dependencies
"},{"location":"development/environment.html#next-steps","title":"Next Steps","text":"
  1. Review the Architecture Guide
  2. Check Contributing Guidelines
  3. Start with Simple Issues
"},{"location":"development/interfaces.html","title":"Interface Documentation","text":"

This document describes the core interfaces used throughout the Home Assistant MCP.

"},{"location":"development/interfaces.html#core-interfaces","title":"Core Interfaces","text":""},{"location":"development/interfaces.html#tool-interface","title":"Tool Interface","text":"
interface Tool {\n    /** Unique identifier for the tool */\n    id: string;\n\n    /** Human-readable name */\n    name: string;\n\n    /** Detailed description */\n    description: string;\n\n    /** Semantic version */\n    version: string;\n\n    /** Tool category */\n    category: ToolCategory;\n\n    /** Execute tool functionality */\n    execute(params: any): Promise<ToolResult>;\n}\n
"},{"location":"development/interfaces.html#tool-result","title":"Tool Result","text":"
interface ToolResult {\n    /** Operation success status */\n    success: boolean;\n\n    /** Response data */\n    data?: any;\n\n    /** Error message if failed */\n    message?: string;\n\n    /** Error code if failed */\n    error_code?: string;\n}\n
"},{"location":"development/interfaces.html#tool-category","title":"Tool Category","text":"
enum ToolCategory {\n    DeviceManagement = 'device_management',\n    HistoryState = 'history_state',\n    Automation = 'automation',\n    AddonsPackages = 'addons_packages',\n    Notifications = 'notifications',\n    Events = 'events',\n    Utility = 'utility'\n}\n
"},{"location":"development/interfaces.html#event-interfaces","title":"Event Interfaces","text":""},{"location":"development/interfaces.html#event-subscription","title":"Event Subscription","text":"
interface EventSubscription {\n    /** Unique subscription ID */\n    id: string;\n\n    /** Event type to subscribe to */\n    event_type: string;\n\n    /** Optional entity ID filter */\n    entity_id?: string;\n\n    /** Optional domain filter */\n    domain?: string;\n\n    /** Subscription creation timestamp */\n    created_at: string;\n\n    /** Last event timestamp */\n    last_event?: string;\n}\n
"},{"location":"development/interfaces.html#event-message","title":"Event Message","text":"
interface EventMessage {\n    /** Event type */\n    event_type: string;\n\n    /** Entity ID if applicable */\n    entity_id?: string;\n\n    /** Event data */\n    data: any;\n\n    /** Event origin */\n    origin: 'LOCAL' | 'REMOTE';\n\n    /** Event timestamp */\n    time_fired: string;\n\n    /** Event context */\n    context: EventContext;\n}\n
"},{"location":"development/interfaces.html#device-interfaces","title":"Device Interfaces","text":""},{"location":"development/interfaces.html#device","title":"Device","text":"
interface Device {\n    /** Device ID */\n    id: string;\n\n    /** Device name */\n    name: string;\n\n    /** Device domain */\n    domain: string;\n\n    /** Current state */\n    state: string;\n\n    /** Device attributes */\n    attributes: Record<string, any>;\n\n    /** Device capabilities */\n    capabilities: DeviceCapabilities;\n}\n
"},{"location":"development/interfaces.html#device-capabilities","title":"Device Capabilities","text":"
interface DeviceCapabilities {\n    /** Supported features */\n    features: string[];\n\n    /** Supported commands */\n    commands: string[];\n\n    /** State attributes */\n    attributes: {\n        /** Attribute name */\n        [key: string]: {\n            /** Attribute type */\n            type: 'string' | 'number' | 'boolean' | 'object';\n            /** Attribute description */\n            description: string;\n            /** Optional value constraints */\n            constraints?: {\n                min?: number;\n                max?: number;\n                enum?: any[];\n            };\n        };\n    };\n}\n
"},{"location":"development/interfaces.html#authentication-interfaces","title":"Authentication Interfaces","text":""},{"location":"development/interfaces.html#auth-token","title":"Auth Token","text":"
interface AuthToken {\n    /** Token value */\n    token: string;\n\n    /** Token type */\n    type: 'bearer' | 'jwt';\n\n    /** Expiration timestamp */\n    expires_at: string;\n\n    /** Token refresh info */\n    refresh?: {\n        token: string;\n        expires_at: string;\n    };\n}\n
"},{"location":"development/interfaces.html#user","title":"User","text":"
interface User {\n    /** User ID */\n    id: string;\n\n    /** Username */\n    username: string;\n\n    /** User type */\n    type: 'admin' | 'user' | 'service';\n\n    /** User permissions */\n    permissions: string[];\n}\n
"},{"location":"development/interfaces.html#error-interfaces","title":"Error Interfaces","text":""},{"location":"development/interfaces.html#tool-error","title":"Tool Error","text":"
interface ToolError extends Error {\n    /** Error code */\n    code: string;\n\n    /** HTTP status code */\n    status: number;\n\n    /** Error details */\n    details?: Record<string, any>;\n}\n
"},{"location":"development/interfaces.html#validation-error","title":"Validation Error","text":"
interface ValidationError {\n    /** Error path */\n    path: string;\n\n    /** Error message */\n    message: string;\n\n    /** Error code */\n    code: string;\n}\n
"},{"location":"development/interfaces.html#configuration-interfaces","title":"Configuration Interfaces","text":""},{"location":"development/interfaces.html#tool-configuration","title":"Tool Configuration","text":"
interface ToolConfig {\n    /** Enable/disable tool */\n    enabled: boolean;\n\n    /** Tool-specific settings */\n    settings: Record<string, any>;\n\n    /** Rate limiting */\n    rate_limit?: {\n        /** Max requests */\n        max: number;\n        /** Time window in seconds */\n        window: number;\n    };\n}\n
"},{"location":"development/interfaces.html#system-configuration","title":"System Configuration","text":"
interface SystemConfig {\n    /** System name */\n    name: string;\n\n    /** Environment */\n    environment: 'development' | 'production';\n\n    /** Log level */\n    log_level: 'debug' | 'info' | 'warn' | 'error';\n\n    /** Tool configurations */\n    tools: Record<string, ToolConfig>;\n}\n
"},{"location":"development/interfaces.html#best-practices","title":"Best Practices","text":"
  1. Use TypeScript for all interfaces
  2. Include JSDoc comments
  3. Use strict typing
  4. Keep interfaces focused
  5. Use consistent naming
  6. Document constraints
  7. Version interfaces
  8. Include examples
"},{"location":"development/interfaces.html#see-also","title":"See Also","text":""},{"location":"development/test-migration-guide.html","title":"Migrating Tests from Jest to Bun","text":"

This guide provides instructions for migrating test files from Jest to Bun's test framework.

"},{"location":"development/test-migration-guide.html#table-of-contents","title":"Table of Contents","text":""},{"location":"development/test-migration-guide.html#basic-setup","title":"Basic Setup","text":"
  1. Remove Jest-related dependencies from package.json:

    {\n  \"devDependencies\": {\n    \"@jest/globals\": \"...\",\n    \"jest\": \"...\",\n    \"ts-jest\": \"...\"\n  }\n}\n

  2. Remove Jest configuration files:

  3. jest.config.js
  4. jest.setup.js

  5. Update test scripts in package.json:

    {\n  \"scripts\": {\n    \"test\": \"bun test\",\n    \"test:watch\": \"bun test --watch\",\n    \"test:coverage\": \"bun test --coverage\"\n  }\n}\n

"},{"location":"development/test-migration-guide.html#import-changes","title":"Import Changes","text":""},{"location":"development/test-migration-guide.html#before-jest","title":"Before (Jest):","text":"
import { jest, describe, it, expect, beforeEach, afterEach } from '@jest/globals';\n
"},{"location":"development/test-migration-guide.html#after-bun","title":"After (Bun):","text":"
import { describe, expect, test, beforeEach, afterEach, mock } from \"bun:test\";\nimport type { Mock } from \"bun:test\";\n

Note: it is replaced with test in Bun.

"},{"location":"development/test-migration-guide.html#api-changes","title":"API Changes","text":""},{"location":"development/test-migration-guide.html#test-structure","title":"Test Structure","text":"
// Jest\ndescribe('Suite', () => {\n  it('should do something', () => {\n    // test\n  });\n});\n\n// Bun\ndescribe('Suite', () => {\n  test('should do something', () => {\n    // test\n  });\n});\n
"},{"location":"development/test-migration-guide.html#assertions","title":"Assertions","text":"

Most Jest assertions work the same in Bun:

// These work the same in both:\nexpect(value).toBe(expected);\nexpect(value).toEqual(expected);\nexpect(value).toBeDefined();\nexpect(value).toBeUndefined();\nexpect(value).toBeTruthy();\nexpect(value).toBeFalsy();\nexpect(array).toContain(item);\nexpect(value).toBeInstanceOf(Class);\nexpect(spy).toHaveBeenCalled();\nexpect(spy).toHaveBeenCalledWith(...args);\n
"},{"location":"development/test-migration-guide.html#mocking","title":"Mocking","text":""},{"location":"development/test-migration-guide.html#function-mocking","title":"Function Mocking","text":""},{"location":"development/test-migration-guide.html#before-jest_1","title":"Before (Jest):","text":"
const mockFn = jest.fn();\nmockFn.mockImplementation(() => 'result');\nmockFn.mockResolvedValue('result');\nmockFn.mockRejectedValue(new Error());\n
"},{"location":"development/test-migration-guide.html#after-bun_1","title":"After (Bun):","text":"
const mockFn = mock(() => 'result');\nconst mockAsyncFn = mock(() => Promise.resolve('result'));\nconst mockErrorFn = mock(() => Promise.reject(new Error()));\n
"},{"location":"development/test-migration-guide.html#module-mocking","title":"Module Mocking","text":""},{"location":"development/test-migration-guide.html#before-jest_2","title":"Before (Jest):","text":"
jest.mock('module-name', () => ({\n  default: jest.fn(),\n  namedExport: jest.fn()\n}));\n
"},{"location":"development/test-migration-guide.html#after-bun_2","title":"After (Bun):","text":"
// Option 1: Using vi.mock (if available)\nvi.mock('module-name', () => ({\n  default: mock(() => {}),\n  namedExport: mock(() => {})\n}));\n\n// Option 2: Using dynamic imports\nconst mockModule = {\n  default: mock(() => {}),\n  namedExport: mock(() => {})\n};\n
"},{"location":"development/test-migration-guide.html#mock-resetclear","title":"Mock Reset/Clear","text":""},{"location":"development/test-migration-guide.html#before-jest_3","title":"Before (Jest):","text":"
jest.clearAllMocks();\nmockFn.mockClear();\njest.resetModules();\n
"},{"location":"development/test-migration-guide.html#after-bun_3","title":"After (Bun):","text":"
mockFn.mockReset();\n// or for specific calls\nmockFn.mock.calls = [];\n
"},{"location":"development/test-migration-guide.html#spy-on-methods","title":"Spy on Methods","text":""},{"location":"development/test-migration-guide.html#before-jest_4","title":"Before (Jest):","text":"
jest.spyOn(object, 'method');\n
"},{"location":"development/test-migration-guide.html#after-bun_4","title":"After (Bun):","text":"
const spy = mock(((...args) => object.method(...args)));\nobject.method = spy;\n
"},{"location":"development/test-migration-guide.html#common-patterns","title":"Common Patterns","text":""},{"location":"development/test-migration-guide.html#async-tests","title":"Async Tests","text":"
// Works the same in both Jest and Bun:\ntest('async test', async () => {\n  const result = await someAsyncFunction();\n  expect(result).toBe(expected);\n});\n
"},{"location":"development/test-migration-guide.html#setup-and-teardown","title":"Setup and Teardown","text":"
describe('Suite', () => {\n  beforeEach(() => {\n    // setup\n  });\n\n  afterEach(() => {\n    // cleanup\n  });\n\n  test('test', () => {\n    // test\n  });\n});\n
"},{"location":"development/test-migration-guide.html#mocking-fetch","title":"Mocking Fetch","text":"
// Before (Jest)\nglobal.fetch = jest.fn(() => Promise.resolve(new Response()));\n\n// After (Bun)\nconst mockFetch = mock(() => Promise.resolve(new Response()));\nglobal.fetch = mockFetch as unknown as typeof fetch;\n
"},{"location":"development/test-migration-guide.html#mocking-websocket","title":"Mocking WebSocket","text":"
// Create a MockWebSocket class implementing WebSocket interface\nclass MockWebSocket implements WebSocket {\n  public static readonly CONNECTING = 0;\n  public static readonly OPEN = 1;\n  public static readonly CLOSING = 2;\n  public static readonly CLOSED = 3;\n\n  public readyState: 0 | 1 | 2 | 3 = MockWebSocket.OPEN;\n  public addEventListener = mock(() => undefined);\n  public removeEventListener = mock(() => undefined);\n  public send = mock(() => undefined);\n  public close = mock(() => undefined);\n  // ... implement other required methods\n}\n\n// Use it in tests\nglobal.WebSocket = MockWebSocket as unknown as typeof WebSocket;\n
"},{"location":"development/test-migration-guide.html#examples","title":"Examples","text":""},{"location":"development/test-migration-guide.html#basic-test","title":"Basic Test","text":"
import { describe, expect, test } from \"bun:test\";\n\ndescribe('formatToolCall', () => {\n  test('should format an object into the correct structure', () => {\n    const testObj = { name: 'test', value: 123 };\n    const result = formatToolCall(testObj);\n\n    expect(result).toEqual({\n      content: [{\n        type: 'text',\n        text: JSON.stringify(testObj, null, 2),\n        isError: false\n      }]\n    });\n  });\n});\n
"},{"location":"development/test-migration-guide.html#async-test-with-mocking","title":"Async Test with Mocking","text":"
import { describe, expect, test, mock } from \"bun:test\";\n\ndescribe('API Client', () => {\n  test('should fetch data', async () => {\n    const mockResponse = { data: 'test' };\n    const mockFetch = mock(() => Promise.resolve(new Response(\n      JSON.stringify(mockResponse),\n      { status: 200, headers: new Headers() }\n    )));\n    global.fetch = mockFetch as unknown as typeof fetch;\n\n    const result = await apiClient.getData();\n    expect(result).toEqual(mockResponse);\n  });\n});\n
"},{"location":"development/test-migration-guide.html#complex-mocking-example","title":"Complex Mocking Example","text":"
import { describe, expect, test, mock } from \"bun:test\";\nimport type { Mock } from \"bun:test\";\n\ninterface MockServices {\n  light: {\n    turn_on: Mock<() => Promise<{ success: boolean }>>;\n    turn_off: Mock<() => Promise<{ success: boolean }>>;\n  };\n}\n\nconst mockServices: MockServices = {\n  light: {\n    turn_on: mock(() => Promise.resolve({ success: true })),\n    turn_off: mock(() => Promise.resolve({ success: true }))\n  }\n};\n\ndescribe('Home Assistant Service', () => {\n  test('should control lights', async () => {\n    const result = await mockServices.light.turn_on();\n    expect(result.success).toBe(true);\n  });\n});\n
"},{"location":"development/test-migration-guide.html#best-practices","title":"Best Practices","text":"
  1. Use TypeScript for better type safety in mocks
  2. Keep mocks as simple as possible
  3. Prefer interface-based mocks over concrete implementations
  4. Use proper type assertions when necessary
  5. Clean up mocks in afterEach blocks
  6. Use descriptive test names
  7. Group related tests using describe blocks
"},{"location":"development/test-migration-guide.html#common-issues-and-solutions","title":"Common Issues and Solutions","text":""},{"location":"development/test-migration-guide.html#issue-type-errors-with-mocks","title":"Issue: Type Errors with Mocks","text":"
// Solution: Use proper typing with Mock type\nimport type { Mock } from \"bun:test\";\nconst mockFn: Mock<() => string> = mock(() => \"result\");\n
"},{"location":"development/test-migration-guide.html#issue-global-object-mocking","title":"Issue: Global Object Mocking","text":"
// Solution: Use type assertions carefully\nglobal.someGlobal = mockImplementation as unknown as typeof someGlobal;\n
"},{"location":"development/test-migration-guide.html#issue-module-mocking","title":"Issue: Module Mocking","text":"
// Solution: Use dynamic imports or vi.mock if available\nconst mockModule = {\n  default: mock(() => mockImplementation)\n};\n
"},{"location":"development/tools.html","title":"Tool Development Guide","text":"

This guide explains how to create new tools for the Home Assistant MCP.

"},{"location":"development/tools.html#tool-structure","title":"Tool Structure","text":"

Each tool should follow this basic structure:

interface Tool {\n    id: string;\n    name: string;\n    description: string;\n    version: string;\n    category: ToolCategory;\n    execute(params: any): Promise<ToolResult>;\n}\n
"},{"location":"development/tools.html#creating-a-new-tool","title":"Creating a New Tool","text":"
  1. Create a new file in the appropriate category directory
  2. Implement the Tool interface
  3. Add API endpoints
  4. Add WebSocket handlers
  5. Add documentation
  6. Add tests
"},{"location":"development/tools.html#example-tool-implementation","title":"Example Tool Implementation","text":"
import { Tool, ToolCategory, ToolResult } from '../interfaces';\n\nexport class MyCustomTool implements Tool {\n    id = 'my_custom_tool';\n    name = 'My Custom Tool';\n    description = 'Description of what the tool does';\n    version = '1.0.0';\n    category = ToolCategory.Utility;\n\n    async execute(params: any): Promise<ToolResult> {\n        // Tool implementation\n        return {\n            success: true,\n            data: {\n                // Tool-specific response data\n            }\n        };\n    }\n}\n
"},{"location":"development/tools.html#tool-categories","title":"Tool Categories","text":""},{"location":"development/tools.html#api-integration","title":"API Integration","text":""},{"location":"development/tools.html#rest-endpoint","title":"REST Endpoint","text":"
import { Router } from 'express';\nimport { MyCustomTool } from './my-custom-tool';\n\nconst router = Router();\nconst tool = new MyCustomTool();\n\nrouter.post('/api/tools/custom', async (req, res) => {\n    try {\n        const result = await tool.execute(req.body);\n        res.json(result);\n    } catch (error) {\n        res.status(500).json({\n            success: false,\n            message: error.message\n        });\n    }\n});\n
"},{"location":"development/tools.html#websocket-handler","title":"WebSocket Handler","text":"
import { WebSocketServer } from 'ws';\nimport { MyCustomTool } from './my-custom-tool';\n\nconst tool = new MyCustomTool();\n\nwss.on('connection', (ws) => {\n    ws.on('message', async (message) => {\n        const { type, params } = JSON.parse(message);\n        if (type === 'my_custom_tool') {\n            const result = await tool.execute(params);\n            ws.send(JSON.stringify(result));\n        }\n    });\n});\n
"},{"location":"development/tools.html#error-handling","title":"Error Handling","text":"
class ToolError extends Error {\n    constructor(\n        message: string,\n        public code: string,\n        public status: number = 500\n    ) {\n        super(message);\n        this.name = 'ToolError';\n    }\n}\n\n// Usage in tool\nasync execute(params: any): Promise<ToolResult> {\n    try {\n        // Tool implementation\n    } catch (error) {\n        throw new ToolError(\n            'Operation failed',\n            'TOOL_ERROR',\n            500\n        );\n    }\n}\n
"},{"location":"development/tools.html#testing","title":"Testing","text":"
import { MyCustomTool } from './my-custom-tool';\n\ndescribe('MyCustomTool', () => {\n    let tool: MyCustomTool;\n\n    beforeEach(() => {\n        tool = new MyCustomTool();\n    });\n\n    it('should execute successfully', async () => {\n        const result = await tool.execute({\n            // Test parameters\n        });\n        expect(result.success).toBe(true);\n    });\n\n    it('should handle errors', async () => {\n        // Error test cases\n    });\n});\n
"},{"location":"development/tools.html#documentation","title":"Documentation","text":"
  1. Create tool documentation in docs/tools/category/tool-name.md
  2. Update tools/tools.md with tool reference
  3. Add tool to navigation in mkdocs.yml
"},{"location":"development/tools.html#documentation-template","title":"Documentation Template","text":"
# Tool Name\n\nDescription of the tool.\n\n## Features\n\n- Feature 1\n- Feature 2\n\n## Usage\n\n### REST API\n\n```typescript\n// API endpoints\n
"},{"location":"development/tools.html#websocket","title":"WebSocket","text":"
// WebSocket usage\n
"},{"location":"development/tools.html#examples","title":"Examples","text":""},{"location":"development/tools.html#example-1","title":"Example 1","text":"
// Usage example\n
"},{"location":"development/tools.html#response-format","title":"Response Format","text":"

{\n    \"success\": true,\n    \"data\": {\n        // Response data structure\n    }\n}\n
```

"},{"location":"development/tools.html#best-practices","title":"Best Practices","text":"
  1. Follow consistent naming conventions
  2. Implement proper error handling
  3. Add comprehensive documentation
  4. Write thorough tests
  5. Use TypeScript for type safety
  6. Follow SOLID principles
  7. Implement rate limiting
  8. Add proper logging
"},{"location":"development/tools.html#see-also","title":"See Also","text":""},{"location":"examples/index.html","title":"Example Projects \ud83d\udcda","text":"

This section contains examples and tutorials for common MCP Server integrations.

"},{"location":"examples/index.html#speech-to-text-integration","title":"Speech-to-Text Integration","text":"

Example of integrating speech recognition with MCP Server:

// From examples/speech-to-text-example.ts\n// Add example code and explanation\n
"},{"location":"examples/index.html#more-examples-coming-soon","title":"More Examples Coming Soon","text":"

...

"},{"location":"features/speech.html","title":"Speech Features","text":"

The Home Assistant MCP Server includes powerful speech processing capabilities powered by fast-whisper and custom wake word detection. This guide explains how to set up and use these features effectively.

"},{"location":"features/speech.html#overview","title":"Overview","text":"

The speech processing system consists of two main components: 1. Wake Word Detection - Listens for specific trigger phrases 2. Speech-to-Text - Transcribes spoken commands using fast-whisper

"},{"location":"features/speech.html#setup","title":"Setup","text":""},{"location":"features/speech.html#prerequisites","title":"Prerequisites","text":"
  1. Docker environment:

    docker --version  # Should be 20.10.0 or higher\n

  2. For GPU acceleration:

  3. NVIDIA GPU with CUDA support
  4. NVIDIA Container Toolkit installed
  5. NVIDIA drivers 450.80.02 or higher
"},{"location":"features/speech.html#installation","title":"Installation","text":"
  1. Enable speech features in your .env:

    ENABLE_SPEECH_FEATURES=true\nENABLE_WAKE_WORD=true\nENABLE_SPEECH_TO_TEXT=true\n

  2. Configure model settings:

    WHISPER_MODEL_PATH=/models\nWHISPER_MODEL_TYPE=base\nWHISPER_LANGUAGE=en\nWHISPER_TASK=transcribe\nWHISPER_DEVICE=cuda  # or cpu\n

  3. Start the services:

    docker-compose up -d\n

"},{"location":"features/speech.html#usage","title":"Usage","text":""},{"location":"features/speech.html#wake-word-detection","title":"Wake Word Detection","text":"

The wake word detector continuously listens for configured trigger phrases. Default wake words: - \"hey jarvis\" - \"ok google\" - \"alexa\"

Custom wake words can be configured:

WAKE_WORDS=computer,jarvis,assistant\n

When a wake word is detected: 1. The system starts recording audio 2. Audio is processed through the speech-to-text pipeline 3. The resulting command is processed by the server

"},{"location":"features/speech.html#speech-to-text","title":"Speech-to-Text","text":""},{"location":"features/speech.html#automatic-transcription","title":"Automatic Transcription","text":"

After wake word detection: 1. Audio is automatically captured (default: 5 seconds) 2. The audio is transcribed using the configured whisper model 3. The transcribed text is processed as a command

"},{"location":"features/speech.html#manual-transcription","title":"Manual Transcription","text":"

You can also manually transcribe audio using the API:

// Using the TypeScript client\nimport { SpeechService } from '@ha-mcp/client';\n\nconst speech = new SpeechService();\n\n// Transcribe from audio buffer\nconst buffer = await getAudioBuffer();\nconst text = await speech.transcribe(buffer);\n\n// Transcribe from file\nconst text = await speech.transcribeFile('command.wav');\n
// Using the REST API\nPOST /api/speech/transcribe\nContent-Type: multipart/form-data\n\nfile: <audio file>\n
"},{"location":"features/speech.html#event-handling","title":"Event Handling","text":"

The system emits various events during speech processing:

speech.on('wakeWord', (word: string) => {\n  console.log(`Wake word detected: ${word}`);\n});\n\nspeech.on('listening', () => {\n  console.log('Listening for command...');\n});\n\nspeech.on('transcribing', () => {\n  console.log('Processing speech...');\n});\n\nspeech.on('transcribed', (text: string) => {\n  console.log(`Transcribed text: ${text}`);\n});\n\nspeech.on('error', (error: Error) => {\n  console.error('Speech processing error:', error);\n});\n
"},{"location":"features/speech.html#performance-optimization","title":"Performance Optimization","text":""},{"location":"features/speech.html#model-selection","title":"Model Selection","text":"

Choose an appropriate model based on your needs:

  1. Resource-constrained environments:
  2. Use tiny.en or base.en
  3. Run on CPU if GPU unavailable
  4. Limit concurrent processing

  5. High-accuracy requirements:

  6. Use small.en or medium.en
  7. Enable GPU acceleration
  8. Increase audio quality

  9. Production environments:

  10. Use base.en or small.en
  11. Enable GPU acceleration
  12. Configure appropriate timeouts
"},{"location":"features/speech.html#gpu-acceleration","title":"GPU Acceleration","text":"

When using GPU acceleration:

  1. Monitor GPU memory usage:

    nvidia-smi -l 1\n

  2. Adjust model size if needed:

    WHISPER_MODEL_TYPE=small  # Decrease if GPU memory limited\n

  3. Configure processing device:

    WHISPER_DEVICE=cuda      # Use GPU\nWHISPER_DEVICE=cpu      # Use CPU if GPU unavailable\n

"},{"location":"features/speech.html#troubleshooting","title":"Troubleshooting","text":""},{"location":"features/speech.html#common-issues","title":"Common Issues","text":"
  1. Wake word detection not working:
  2. Check microphone permissions
  3. Adjust WAKE_WORD_SENSITIVITY
  4. Verify wake words configuration

  5. Poor transcription quality:

  6. Check audio input quality
  7. Try a larger model
  8. Verify language settings

  9. Performance issues:

  10. Monitor resource usage
  11. Consider smaller model
  12. Check GPU acceleration status
"},{"location":"features/speech.html#logging","title":"Logging","text":"

Enable debug logging for detailed information:

LOG_LEVEL=debug\n

Speech-specific logs will be tagged with [SPEECH] prefix.

"},{"location":"features/speech.html#security-considerations","title":"Security Considerations","text":"
  1. Audio Privacy:
  2. Audio is processed locally
  3. No data sent to external services
  4. Temporary files automatically cleaned

  5. Access Control:

  6. Speech endpoints require authentication
  7. Rate limiting applies to transcription
  8. Configurable command restrictions

  9. Resource Protection:

  10. Timeouts prevent hanging
  11. Memory limits enforced
  12. Graceful error handling
"},{"location":"getting-started/index.html","title":"Getting Started","text":"

Welcome to the Advanced Home Assistant MCP getting started guide. Follow these steps to begin:

  1. Installation
  2. Configuration
  3. Docker Setup
  4. Quick Start
"},{"location":"getting-started/configuration.html","title":"Configuration","text":""},{"location":"getting-started/configuration.html#basic-configuration","title":"Basic Configuration","text":""},{"location":"getting-started/configuration.html#advanced-settings","title":"Advanced Settings","text":""},{"location":"getting-started/docker.html","title":"Docker Deployment Guide \ud83d\udc33","text":"

Detailed guide for deploying MCP Server with Docker...

"},{"location":"getting-started/installation.html","title":"Installation Guide \ud83d\udee0\ufe0f","text":"

This guide covers different methods to install and set up the MCP Server for Home Assistant. Choose the installation method that best suits your needs.

"},{"location":"getting-started/installation.html#prerequisites","title":"Prerequisites","text":"

Before installing MCP Server, ensure you have:

"},{"location":"getting-started/installation.html#installation-methods","title":"Installation Methods","text":""},{"location":"getting-started/installation.html#1-smithery-installation-recommended","title":"1. \ud83d\udd27 Smithery Installation (Recommended)","text":"

The easiest way to install MCP Server is through Smithery:

"},{"location":"getting-started/installation.html#smithery-configuration","title":"Smithery Configuration","text":"

The project includes a smithery.yaml configuration:

# Add smithery.yaml contents and explanation\n
"},{"location":"getting-started/installation.html#installation-steps","title":"Installation Steps","text":"
npx -y @smithery/cli install @jango-blockchained/advanced-homeassistant-mcp --client claude\n
"},{"location":"getting-started/installation.html#2-docker-installation","title":"2. \ud83d\udc33 Docker Installation","text":"

For a containerized deployment:

# Clone the repository\ngit clone --depth 1 https://github.com/jango-blockchained/advanced-homeassistant-mcp.git\ncd advanced-homeassistant-mcp\n\n# Configure environment variables\ncp .env.example .env\n# Edit .env with your Home Assistant details:\n# - HA_URL: Your Home Assistant URL\n# - HA_TOKEN: Your Long-Lived Access Token\n# - Other configuration options\n\n# Build and start containers\ndocker compose up -d --build\n\n# View logs (optional)\ndocker compose logs -f --tail=50\n
"},{"location":"getting-started/installation.html#3-manual-installation","title":"3. \ud83d\udcbb Manual Installation","text":"

For direct installation on your system:

# Install Bun runtime\ncurl -fsSL https://bun.sh/install | bash\n\n# Clone and install\ngit clone https://github.com/jango-blockchained/advanced-homeassistant-mcp.git\ncd advanced-homeassistant-mcp\nbun install --frozen-lockfile\n\n# Configure environment\ncp .env.example .env\n# Edit .env with your configuration\n\n# Start the server\nbun run dev --watch\n
"},{"location":"getting-started/installation.html#configuration","title":"Configuration","text":""},{"location":"getting-started/installation.html#environment-variables","title":"Environment Variables","text":"

Key configuration options in your .env file:

# Home Assistant Configuration\nHA_URL=http://your-homeassistant:8123\nHA_TOKEN=your_long_lived_access_token\n\n# Server Configuration\nPORT=3000\nHOST=0.0.0.0\nNODE_ENV=production\n\n# Security Settings\nJWT_SECRET=your_secure_jwt_secret\nRATE_LIMIT=100\n
"},{"location":"getting-started/installation.html#client-integration","title":"Client Integration","text":""},{"location":"getting-started/installation.html#cursor-integration","title":"Cursor Integration","text":"

Add to .cursor/config/config.json:

{\n  \"mcpServers\": {\n    \"homeassistant-mcp\": {\n      \"command\": \"bun\",\n      \"args\": [\"run\", \"start\"],\n      \"cwd\": \"${workspaceRoot}\",\n      \"env\": {\n        \"NODE_ENV\": \"development\"\n      }\n    }\n  }\n}\n
"},{"location":"getting-started/installation.html#claude-desktop-integration","title":"Claude Desktop Integration","text":"

Add to your Claude configuration:

{\n  \"mcpServers\": {\n    \"homeassistant-mcp\": {\n      \"command\": \"bun\",\n      \"args\": [\"run\", \"start\", \"--port\", \"8080\"],\n      \"env\": {\n        \"NODE_ENV\": \"production\"\n      }\n    }\n  }\n}\n
"},{"location":"getting-started/installation.html#verification","title":"Verification","text":"

To verify your installation:

  1. Check server status:

    curl http://localhost:3000/health\n

  2. Test Home Assistant connection:

    curl http://localhost:3000/api/state\n

"},{"location":"getting-started/installation.html#troubleshooting","title":"Troubleshooting","text":"

If you encounter issues:

  1. Check the Troubleshooting Guide
  2. Verify your environment variables
  3. Check server logs:
    # For Docker installation\ndocker compose logs -f\n\n# For manual installation\nbun run dev\n
"},{"location":"getting-started/installation.html#next-steps","title":"Next Steps","text":""},{"location":"getting-started/installation.html#support","title":"Support","text":"

Need help? Check our Support Resources or open an issue.

"},{"location":"getting-started/quickstart.html","title":"Quick Start Guide \ud83d\ude80","text":"

This guide will help you get started with MCP Server after installation. We'll cover basic usage, common commands, and simple integrations.

"},{"location":"getting-started/quickstart.html#first-steps","title":"First Steps","text":""},{"location":"getting-started/quickstart.html#1-verify-connection","title":"1. Verify Connection","text":"

After installation, verify your MCP Server is running and connected to Home Assistant:

# Check server health\ncurl http://localhost:3000/health\n\n# Verify Home Assistant connection\ncurl http://localhost:3000/api/state\n
"},{"location":"getting-started/quickstart.html#2-basic-voice-commands","title":"2. Basic Voice Commands","text":"

Try these basic voice commands to test your setup:

# Example using curl for testing\ncurl -X POST http://localhost:3000/api/command \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"command\": \"Turn on the living room lights\"}'\n

Common voice commands: - \"Turn on/off [device name]\" - \"Set [device] to [value]\" - \"What's the temperature in [room]?\" - \"Is [device] on or off?\"

"},{"location":"getting-started/quickstart.html#real-world-examples","title":"Real-World Examples","text":""},{"location":"getting-started/quickstart.html#1-smart-lighting-control","title":"1. Smart Lighting Control","text":"
// Browser example using fetch\nconst response = await fetch('http://localhost:3000/api/command', {\n  method: 'POST',\n  headers: {\n    'Content-Type': 'application/json',\n  },\n  body: JSON.stringify({\n    command: 'Set living room lights to 50% brightness and warm white color'\n  })\n});\n
"},{"location":"getting-started/quickstart.html#2-real-time-updates","title":"2. Real-Time Updates","text":"

Subscribe to device state changes using Server-Sent Events (SSE):

const eventSource = new EventSource('http://localhost:3000/subscribe_events?token=YOUR_TOKEN&domain=light');\n\neventSource.onmessage = (event) => {\n    const data = JSON.parse(event.data);\n    console.log('Device state changed:', data);\n    // Update your UI here\n};\n
"},{"location":"getting-started/quickstart.html#3-scene-automation","title":"3. Scene Automation","text":"

Create and trigger scenes for different activities:

// Create a \"Movie Night\" scene\nconst createScene = async () => {\n  await fetch('http://localhost:3000/api/scene', {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application/json',\n    },\n    body: JSON.stringify({\n      name: 'Movie Night',\n      actions: [\n        { device: 'living_room_lights', action: 'dim', value: 20 },\n        { device: 'tv', action: 'on' },\n        { device: 'soundbar', action: 'on' }\n      ]\n    })\n  });\n};\n\n// Trigger the scene with voice command:\n// \"Hey MCP, activate movie night scene\"\n
"},{"location":"getting-started/quickstart.html#integration-examples","title":"Integration Examples","text":""},{"location":"getting-started/quickstart.html#1-web-dashboard-integration","title":"1. Web Dashboard Integration","text":"
// React component example\nfunction SmartHomeControl() {\n    const [devices, setDevices] = useState([]);\n\n    useEffect(() => {\n        // Subscribe to device updates\n        const events = new EventSource('http://localhost:3000/subscribe_events');\n        events.onmessage = (event) => {\n            const data = JSON.parse(event.data);\n            setDevices(currentDevices => \n                currentDevices.map(device => \n                    device.id === data.id ? {...device, ...data} : device\n                )\n            );\n        };\n\n        return () => events.close();\n    }, []);\n\n    return (\n        <div className=\"dashboard\">\n            {devices.map(device => (\n                <DeviceCard key={device.id} device={device} />\n            ))}\n        </div>\n    );\n}\n
"},{"location":"getting-started/quickstart.html#2-voice-assistant-integration","title":"2. Voice Assistant Integration","text":"
// Example using speech-to-text with MCP\nasync function handleVoiceCommand(audioBlob: Blob) {\n    // First, convert speech to text\n    const text = await speechToText(audioBlob);\n\n    // Then send command to MCP\n    const response = await fetch('http://localhost:3000/api/command', {\n        method: 'POST',\n        headers: {\n            'Content-Type': 'application/json',\n        },\n        body: JSON.stringify({ command: text })\n    });\n\n    return response.json();\n}\n
"},{"location":"getting-started/quickstart.html#best-practices","title":"Best Practices","text":"
  1. Error Handling

    try {\n    const response = await fetch('http://localhost:3000/api/command', {\n        method: 'POST',\n        headers: {\n            'Content-Type': 'application/json',\n        },\n        body: JSON.stringify({ command: 'Turn on lights' })\n    });\n\n    if (!response.ok) {\n        throw new Error(`HTTP error! status: ${response.status}`);\n    }\n\n    const data = await response.json();\n} catch (error) {\n    console.error('Error:', error);\n    // Handle error appropriately\n}\n

  2. Connection Management

    class MCPConnection {\n    constructor() {\n        this.eventSource = null;\n        this.reconnectAttempts = 0;\n    }\n\n    connect() {\n        this.eventSource = new EventSource('http://localhost:3000/subscribe_events');\n        this.eventSource.onerror = this.handleError.bind(this);\n    }\n\n    handleError() {\n        if (this.reconnectAttempts < 3) {\n            setTimeout(() => {\n                this.reconnectAttempts++;\n                this.connect();\n            }, 1000 * this.reconnectAttempts);\n        }\n    }\n}\n

"},{"location":"getting-started/quickstart.html#next-steps","title":"Next Steps","text":""},{"location":"getting-started/quickstart.html#troubleshooting","title":"Troubleshooting","text":"

If you encounter issues: - Verify your authentication token - Check server logs for errors - Ensure Home Assistant is accessible - Review the Troubleshooting Guide

Need more help? Visit our Support Resources.

"},{"location":"tools/index.html","title":"Tools Overview","text":"

The Home Assistant MCP Server provides a variety of tools to help you manage and interact with your home automation system.

"},{"location":"tools/index.html#available-tools","title":"Available Tools","text":""},{"location":"tools/index.html#device-management","title":"Device Management","text":""},{"location":"tools/index.html#history-state","title":"History & State","text":""},{"location":"tools/index.html#automation","title":"Automation","text":""},{"location":"tools/index.html#add-ons-packages","title":"Add-ons & Packages","text":""},{"location":"tools/index.html#notifications","title":"Notifications","text":""},{"location":"tools/index.html#events","title":"Events","text":""},{"location":"tools/index.html#getting-started","title":"Getting Started","text":"

To get started with these tools:

  1. Ensure you have the MCP Server properly installed and configured
  2. Check the specific tool documentation for detailed usage instructions
  3. Use the API endpoints or command-line interface as needed
"},{"location":"tools/index.html#next-steps","title":"Next Steps","text":""},{"location":"tools/addons-packages/addon.html","title":"Add-on Management Tool","text":"

The Add-on Management tool provides functionality to manage Home Assistant add-ons through the MCP interface.

"},{"location":"tools/addons-packages/addon.html#features","title":"Features","text":""},{"location":"tools/addons-packages/addon.html#usage","title":"Usage","text":""},{"location":"tools/addons-packages/addon.html#rest-api","title":"REST API","text":"
GET /api/addons\nGET /api/addons/{addon_slug}\nPOST /api/addons/{addon_slug}/install\nPOST /api/addons/{addon_slug}/uninstall\nPOST /api/addons/{addon_slug}/start\nPOST /api/addons/{addon_slug}/stop\nPOST /api/addons/{addon_slug}/restart\nGET /api/addons/{addon_slug}/logs\nPUT /api/addons/{addon_slug}/config\nGET /api/addons/{addon_slug}/stats\n
"},{"location":"tools/addons-packages/addon.html#websocket","title":"WebSocket","text":"
// List add-ons\n{\n    \"type\": \"get_addons\"\n}\n\n// Get add-on info\n{\n    \"type\": \"get_addon_info\",\n    \"addon_slug\": \"required_addon_slug\"\n}\n\n// Install add-on\n{\n    \"type\": \"install_addon\",\n    \"addon_slug\": \"required_addon_slug\",\n    \"version\": \"optional_version\"\n}\n\n// Control add-on\n{\n    \"type\": \"control_addon\",\n    \"addon_slug\": \"required_addon_slug\",\n    \"action\": \"start|stop|restart\"\n}\n
"},{"location":"tools/addons-packages/addon.html#examples","title":"Examples","text":""},{"location":"tools/addons-packages/addon.html#list-all-add-ons","title":"List All Add-ons","text":"
const response = await fetch('http://your-ha-mcp/api/addons', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst addons = await response.json();\n
"},{"location":"tools/addons-packages/addon.html#install-add-on","title":"Install Add-on","text":"
const response = await fetch('http://your-ha-mcp/api/addons/mosquitto/install', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"version\": \"latest\"\n    })\n});\n
"},{"location":"tools/addons-packages/addon.html#configure-add-on","title":"Configure Add-on","text":"
const response = await fetch('http://your-ha-mcp/api/addons/mosquitto/config', {\n    method: 'PUT',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"logins\": [\n            {\n                \"username\": \"mqtt_user\",\n                \"password\": \"mqtt_password\"\n            }\n        ],\n        \"customize\": {\n            \"active\": true,\n            \"folder\": \"mosquitto\"\n        }\n    })\n});\n
"},{"location":"tools/addons-packages/addon.html#response-format","title":"Response Format","text":""},{"location":"tools/addons-packages/addon.html#add-on-list-response","title":"Add-on List Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"addons\": [\n            {\n                \"slug\": \"addon_slug\",\n                \"name\": \"Add-on Name\",\n                \"version\": \"1.0.0\",\n                \"state\": \"started\",\n                \"repository\": \"core\",\n                \"installed\": true,\n                \"update_available\": false\n            }\n        ]\n    }\n}\n
"},{"location":"tools/addons-packages/addon.html#add-on-info-response","title":"Add-on Info Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"addon\": {\n            \"slug\": \"addon_slug\",\n            \"name\": \"Add-on Name\",\n            \"version\": \"1.0.0\",\n            \"description\": \"Add-on description\",\n            \"long_description\": \"Detailed description\",\n            \"repository\": \"core\",\n            \"installed\": true,\n            \"state\": \"started\",\n            \"webui\": \"http://[HOST]:[PORT:80]\",\n            \"boot\": \"auto\",\n            \"options\": {\n                // Add-on specific options\n            },\n            \"schema\": {\n                // Add-on options schema\n            },\n            \"ports\": {\n                \"80/tcp\": 8080\n            },\n            \"ingress\": true,\n            \"ingress_port\": 8099\n        }\n    }\n}\n
"},{"location":"tools/addons-packages/addon.html#add-on-stats-response","title":"Add-on Stats Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"stats\": {\n            \"cpu_percent\": 2.5,\n            \"memory_usage\": 128974848,\n            \"memory_limit\": 536870912,\n            \"network_rx\": 1234,\n            \"network_tx\": 5678,\n            \"blk_read\": 12345,\n            \"blk_write\": 67890\n        }\n    }\n}\n
"},{"location":"tools/addons-packages/addon.html#error-handling","title":"Error Handling","text":""},{"location":"tools/addons-packages/addon.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/addons-packages/addon.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/addons-packages/addon.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/addons-packages/addon.html#best-practices","title":"Best Practices","text":"
  1. Always check add-on compatibility
  2. Back up configurations before updates
  3. Monitor resource usage
  4. Use appropriate update strategies
  5. Implement proper error handling
  6. Test configurations in safe environment
  7. Handle rate limiting gracefully
  8. Keep add-ons updated
"},{"location":"tools/addons-packages/addon.html#add-on-security","title":"Add-on Security","text":""},{"location":"tools/addons-packages/addon.html#see-also","title":"See Also","text":""},{"location":"tools/addons-packages/package.html","title":"Package Management Tool","text":"

The Package Management tool provides functionality to manage Home Assistant Community Store (HACS) packages through the MCP interface.

"},{"location":"tools/addons-packages/package.html#features","title":"Features","text":""},{"location":"tools/addons-packages/package.html#usage","title":"Usage","text":""},{"location":"tools/addons-packages/package.html#rest-api","title":"REST API","text":"
GET /api/packages\nGET /api/packages/{package_id}\nPOST /api/packages/{package_id}/install\nPOST /api/packages/{package_id}/uninstall\nPOST /api/packages/{package_id}/update\nGET /api/packages/search\nGET /api/packages/categories\nGET /api/packages/repositories\n
"},{"location":"tools/addons-packages/package.html#websocket","title":"WebSocket","text":"
// List packages\n{\n    \"type\": \"get_packages\",\n    \"category\": \"optional_category\"\n}\n\n// Search packages\n{\n    \"type\": \"search_packages\",\n    \"query\": \"search_query\",\n    \"category\": \"optional_category\"\n}\n\n// Install package\n{\n    \"type\": \"install_package\",\n    \"package_id\": \"required_package_id\",\n    \"version\": \"optional_version\"\n}\n
"},{"location":"tools/addons-packages/package.html#package-categories","title":"Package Categories","text":""},{"location":"tools/addons-packages/package.html#examples","title":"Examples","text":""},{"location":"tools/addons-packages/package.html#list-all-packages","title":"List All Packages","text":"
const response = await fetch('http://your-ha-mcp/api/packages', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst packages = await response.json();\n
"},{"location":"tools/addons-packages/package.html#search-packages","title":"Search Packages","text":"
const response = await fetch('http://your-ha-mcp/api/packages/search?q=weather&category=integrations', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst searchResults = await response.json();\n
"},{"location":"tools/addons-packages/package.html#install-package","title":"Install Package","text":"
const response = await fetch('http://your-ha-mcp/api/packages/custom-weather-card/install', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"version\": \"latest\"\n    })\n});\n
"},{"location":"tools/addons-packages/package.html#response-format","title":"Response Format","text":""},{"location":"tools/addons-packages/package.html#package-list-response","title":"Package List Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"packages\": [\n            {\n                \"id\": \"package_id\",\n                \"name\": \"Package Name\",\n                \"category\": \"integrations\",\n                \"description\": \"Package description\",\n                \"version\": \"1.0.0\",\n                \"installed\": true,\n                \"update_available\": false,\n                \"stars\": 150,\n                \"downloads\": 10000\n            }\n        ]\n    }\n}\n
"},{"location":"tools/addons-packages/package.html#package-info-response","title":"Package Info Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"package\": {\n            \"id\": \"package_id\",\n            \"name\": \"Package Name\",\n            \"category\": \"integrations\",\n            \"description\": \"Package description\",\n            \"long_description\": \"Detailed description\",\n            \"version\": \"1.0.0\",\n            \"installed_version\": \"0.9.0\",\n            \"available_version\": \"1.0.0\",\n            \"installed\": true,\n            \"update_available\": true,\n            \"stars\": 150,\n            \"downloads\": 10000,\n            \"repository\": \"https://github.com/author/repo\",\n            \"author\": {\n                \"name\": \"Author Name\",\n                \"url\": \"https://github.com/author\"\n            },\n            \"documentation\": \"https://github.com/author/repo/wiki\",\n            \"dependencies\": [\n                \"dependency1\",\n                \"dependency2\"\n            ]\n        }\n    }\n}\n
"},{"location":"tools/addons-packages/package.html#search-response","title":"Search Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"results\": [\n            {\n                \"id\": \"package_id\",\n                \"name\": \"Package Name\",\n                \"category\": \"integrations\",\n                \"description\": \"Package description\",\n                \"version\": \"1.0.0\",\n                \"score\": 0.95\n            }\n        ],\n        \"total\": 42\n    }\n}\n
"},{"location":"tools/addons-packages/package.html#error-handling","title":"Error Handling","text":""},{"location":"tools/addons-packages/package.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/addons-packages/package.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/addons-packages/package.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/addons-packages/package.html#best-practices","title":"Best Practices","text":"
  1. Check package compatibility
  2. Review package documentation
  3. Verify package dependencies
  4. Back up before updates
  5. Test in safe environment
  6. Monitor resource usage
  7. Keep packages updated
  8. Handle rate limiting gracefully
"},{"location":"tools/addons-packages/package.html#package-security","title":"Package Security","text":""},{"location":"tools/addons-packages/package.html#see-also","title":"See Also","text":""},{"location":"tools/automation/automation-config.html","title":"Automation Configuration Tool","text":"

The Automation Configuration tool provides functionality to create, update, and manage Home Assistant automation configurations.

"},{"location":"tools/automation/automation-config.html#features","title":"Features","text":""},{"location":"tools/automation/automation-config.html#usage","title":"Usage","text":""},{"location":"tools/automation/automation-config.html#rest-api","title":"REST API","text":"
POST /api/automations\nPUT /api/automations/{automation_id}\nDELETE /api/automations/{automation_id}\nPOST /api/automations/{automation_id}/duplicate\nPOST /api/automations/validate\n
"},{"location":"tools/automation/automation-config.html#websocket","title":"WebSocket","text":"
// Create automation\n{\n    \"type\": \"create_automation\",\n    \"automation\": {\n        // Automation configuration\n    }\n}\n\n// Update automation\n{\n    \"type\": \"update_automation\",\n    \"automation_id\": \"required_automation_id\",\n    \"automation\": {\n        // Updated configuration\n    }\n}\n\n// Delete automation\n{\n    \"type\": \"delete_automation\",\n    \"automation_id\": \"required_automation_id\"\n}\n
"},{"location":"tools/automation/automation-config.html#automation-configuration","title":"Automation Configuration","text":""},{"location":"tools/automation/automation-config.html#basic-structure","title":"Basic Structure","text":"
{\n    \"id\": \"morning_routine\",\n    \"alias\": \"Morning Routine\",\n    \"description\": \"Turn on lights and adjust temperature in the morning\",\n    \"trigger\": [\n        {\n            \"platform\": \"time\",\n            \"at\": \"07:00:00\"\n        }\n    ],\n    \"condition\": [\n        {\n            \"condition\": \"time\",\n            \"weekday\": [\"mon\", \"tue\", \"wed\", \"thu\", \"fri\"]\n        }\n    ],\n    \"action\": [\n        {\n            \"service\": \"light.turn_on\",\n            \"target\": {\n                \"entity_id\": \"light.bedroom\"\n            },\n            \"data\": {\n                \"brightness\": 255,\n                \"transition\": 300\n            }\n        }\n    ],\n    \"mode\": \"single\"\n}\n
"},{"location":"tools/automation/automation-config.html#trigger-types","title":"Trigger Types","text":"
// Time-based trigger\n{\n    \"platform\": \"time\",\n    \"at\": \"07:00:00\"\n}\n\n// State-based trigger\n{\n    \"platform\": \"state\",\n    \"entity_id\": \"binary_sensor.motion\",\n    \"to\": \"on\"\n}\n\n// Event-based trigger\n{\n    \"platform\": \"event\",\n    \"event_type\": \"custom_event\"\n}\n\n// Numeric state trigger\n{\n    \"platform\": \"numeric_state\",\n    \"entity_id\": \"sensor.temperature\",\n    \"above\": 25\n}\n
"},{"location":"tools/automation/automation-config.html#condition-types","title":"Condition Types","text":"
// Time condition\n{\n    \"condition\": \"time\",\n    \"after\": \"07:00:00\",\n    \"before\": \"22:00:00\"\n}\n\n// State condition\n{\n    \"condition\": \"state\",\n    \"entity_id\": \"device_tracker.phone\",\n    \"state\": \"home\"\n}\n\n// Numeric state condition\n{\n    \"condition\": \"numeric_state\",\n    \"entity_id\": \"sensor.temperature\",\n    \"below\": 25\n}\n
"},{"location":"tools/automation/automation-config.html#action-types","title":"Action Types","text":"
// Service call action\n{\n    \"service\": \"light.turn_on\",\n    \"target\": {\n        \"entity_id\": \"light.bedroom\"\n    }\n}\n\n// Delay action\n{\n    \"delay\": \"00:00:30\"\n}\n\n// Scene activation\n{\n    \"scene\": \"scene.evening_mode\"\n}\n\n// Conditional action\n{\n    \"choose\": [\n        {\n            \"conditions\": [\n                {\n                    \"condition\": \"state\",\n                    \"entity_id\": \"sun.sun\",\n                    \"state\": \"below_horizon\"\n                }\n            ],\n            \"sequence\": [\n                {\n                    \"service\": \"light.turn_on\",\n                    \"target\": {\n                        \"entity_id\": \"light.living_room\"\n                    }\n                }\n            ]\n        }\n    ]\n}\n
"},{"location":"tools/automation/automation-config.html#examples","title":"Examples","text":""},{"location":"tools/automation/automation-config.html#create-new-automation","title":"Create New Automation","text":"
const response = await fetch('http://your-ha-mcp/api/automations', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"alias\": \"Morning Routine\",\n        \"description\": \"Turn on lights in the morning\",\n        \"trigger\": [\n            {\n                \"platform\": \"time\",\n                \"at\": \"07:00:00\"\n            }\n        ],\n        \"action\": [\n            {\n                \"service\": \"light.turn_on\",\n                \"target\": {\n                    \"entity_id\": \"light.bedroom\"\n                }\n            }\n        ]\n    })\n});\n
"},{"location":"tools/automation/automation-config.html#update-existing-automation","title":"Update Existing Automation","text":"
const response = await fetch('http://your-ha-mcp/api/automations/morning_routine', {\n    method: 'PUT',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"alias\": \"Morning Routine\",\n        \"trigger\": [\n            {\n                \"platform\": \"time\",\n                \"at\": \"07:30:00\"  // Updated time\n            }\n        ],\n        \"action\": [\n            {\n                \"service\": \"light.turn_on\",\n                \"target\": {\n                    \"entity_id\": \"light.bedroom\"\n                }\n            }\n        ]\n    })\n});\n
"},{"location":"tools/automation/automation-config.html#response-format","title":"Response Format","text":""},{"location":"tools/automation/automation-config.html#success-response","title":"Success Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"automation\": {\n            \"id\": \"created_automation_id\",\n            // Full automation configuration\n        }\n    }\n}\n
"},{"location":"tools/automation/automation-config.html#validation-response","title":"Validation Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"valid\": true,\n        \"warnings\": [\n            \"No conditions specified\"\n        ]\n    }\n}\n
"},{"location":"tools/automation/automation-config.html#error-handling","title":"Error Handling","text":""},{"location":"tools/automation/automation-config.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/automation/automation-config.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\",\n    \"validation_errors\": [\n        {\n            \"path\": \"trigger[0].platform\",\n            \"message\": \"Invalid trigger platform\"\n        }\n    ]\n}\n
"},{"location":"tools/automation/automation-config.html#best-practices","title":"Best Practices","text":"
  1. Always validate configurations before saving
  2. Use descriptive aliases and descriptions
  3. Group related automations
  4. Test automations in a safe environment
  5. Document automation dependencies
  6. Use variables for reusable values
  7. Implement proper error handling
  8. Consider automation modes carefully
"},{"location":"tools/automation/automation-config.html#see-also","title":"See Also","text":""},{"location":"tools/automation/automation.html","title":"Automation Management Tool","text":"

The Automation Management tool provides functionality to manage and control Home Assistant automations.

"},{"location":"tools/automation/automation.html#features","title":"Features","text":""},{"location":"tools/automation/automation.html#usage","title":"Usage","text":""},{"location":"tools/automation/automation.html#rest-api","title":"REST API","text":"
GET /api/automations\nGET /api/automations/{automation_id}\nPOST /api/automations/{automation_id}/toggle\nPOST /api/automations/{automation_id}/trigger\nGET /api/automations/{automation_id}/history\n
"},{"location":"tools/automation/automation.html#websocket","title":"WebSocket","text":"
// List automations\n{\n    \"type\": \"get_automations\"\n}\n\n// Toggle automation\n{\n    \"type\": \"toggle_automation\",\n    \"automation_id\": \"required_automation_id\"\n}\n\n// Trigger automation\n{\n    \"type\": \"trigger_automation\",\n    \"automation_id\": \"required_automation_id\",\n    \"variables\": {\n        // Optional variables\n    }\n}\n
"},{"location":"tools/automation/automation.html#examples","title":"Examples","text":""},{"location":"tools/automation/automation.html#list-all-automations","title":"List All Automations","text":"
const response = await fetch('http://your-ha-mcp/api/automations', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst automations = await response.json();\n
"},{"location":"tools/automation/automation.html#toggle-automation-state","title":"Toggle Automation State","text":"
const response = await fetch('http://your-ha-mcp/api/automations/morning_routine/toggle', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\n
"},{"location":"tools/automation/automation.html#trigger-automation-manually","title":"Trigger Automation Manually","text":"
const response = await fetch('http://your-ha-mcp/api/automations/morning_routine/trigger', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"variables\": {\n            \"brightness\": 100,\n            \"temperature\": 22\n        }\n    })\n});\n
"},{"location":"tools/automation/automation.html#response-format","title":"Response Format","text":""},{"location":"tools/automation/automation.html#automation-list-response","title":"Automation List Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"automations\": [\n            {\n                \"id\": \"automation_id\",\n                \"name\": \"Automation Name\",\n                \"enabled\": true,\n                \"last_triggered\": \"2024-02-05T12:00:00Z\",\n                \"trigger_count\": 42\n            }\n        ]\n    }\n}\n
"},{"location":"tools/automation/automation.html#automation-details-response","title":"Automation Details Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"automation\": {\n            \"id\": \"automation_id\",\n            \"name\": \"Automation Name\",\n            \"enabled\": true,\n            \"triggers\": [\n                {\n                    \"platform\": \"time\",\n                    \"at\": \"07:00:00\"\n                }\n            ],\n            \"conditions\": [],\n            \"actions\": [\n                {\n                    \"service\": \"light.turn_on\",\n                    \"target\": {\n                        \"entity_id\": \"light.bedroom\"\n                    }\n                }\n            ],\n            \"mode\": \"single\",\n            \"max\": 10,\n            \"last_triggered\": \"2024-02-05T12:00:00Z\",\n            \"trigger_count\": 42\n        }\n    }\n}\n
"},{"location":"tools/automation/automation.html#automation-history-response","title":"Automation History Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"history\": [\n            {\n                \"timestamp\": \"2024-02-05T12:00:00Z\",\n                \"trigger\": {\n                    \"platform\": \"time\",\n                    \"at\": \"07:00:00\"\n                },\n                \"context\": {\n                    \"user_id\": \"user_123\",\n                    \"variables\": {}\n                },\n                \"result\": \"success\"\n            }\n        ]\n    }\n}\n
"},{"location":"tools/automation/automation.html#error-handling","title":"Error Handling","text":""},{"location":"tools/automation/automation.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/automation/automation.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/automation/automation.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/automation/automation.html#best-practices","title":"Best Practices","text":"
  1. Monitor automation execution history
  2. Use descriptive automation names
  3. Implement proper error handling
  4. Cache automation configurations when possible
  5. Handle rate limiting gracefully
  6. Test automations before enabling
  7. Use variables for flexible automation behavior
"},{"location":"tools/automation/automation.html#see-also","title":"See Also","text":""},{"location":"tools/device-management/control.html","title":"Device Control Tool","text":"

The Device Control tool provides functionality to control various types of devices in your Home Assistant instance.

"},{"location":"tools/device-management/control.html#supported-device-types","title":"Supported Device Types","text":""},{"location":"tools/device-management/control.html#usage","title":"Usage","text":""},{"location":"tools/device-management/control.html#rest-api","title":"REST API","text":"
POST /api/devices/{device_id}/control\n
"},{"location":"tools/device-management/control.html#websocket","title":"WebSocket","text":"
{\n    \"type\": \"control_device\",\n    \"device_id\": \"required_device_id\",\n    \"domain\": \"required_domain\",\n    \"service\": \"required_service\",\n    \"data\": {\n        // Service-specific data\n    }\n}\n
"},{"location":"tools/device-management/control.html#domain-specific-commands","title":"Domain-Specific Commands","text":""},{"location":"tools/device-management/control.html#lights","title":"Lights","text":"
// Turn on/off\nPOST /api/devices/light/{device_id}/control\n{\n    \"service\": \"turn_on\",  // or \"turn_off\"\n}\n\n// Set brightness\n{\n    \"service\": \"turn_on\",\n    \"data\": {\n        \"brightness\": 255  // 0-255\n    }\n}\n\n// Set color\n{\n    \"service\": \"turn_on\",\n    \"data\": {\n        \"rgb_color\": [255, 0, 0]  // Red\n    }\n}\n
"},{"location":"tools/device-management/control.html#covers","title":"Covers","text":"
// Open/close\nPOST /api/devices/cover/{device_id}/control\n{\n    \"service\": \"open_cover\",  // or \"close_cover\"\n}\n\n// Set position\n{\n    \"service\": \"set_cover_position\",\n    \"data\": {\n        \"position\": 50  // 0-100\n    }\n}\n
"},{"location":"tools/device-management/control.html#climate","title":"Climate","text":"
// Set temperature\nPOST /api/devices/climate/{device_id}/control\n{\n    \"service\": \"set_temperature\",\n    \"data\": {\n        \"temperature\": 22.5\n    }\n}\n\n// Set mode\n{\n    \"service\": \"set_hvac_mode\",\n    \"data\": {\n        \"hvac_mode\": \"heat\"  // heat, cool, auto, off\n    }\n}\n
"},{"location":"tools/device-management/control.html#examples","title":"Examples","text":""},{"location":"tools/device-management/control.html#control-light-brightness","title":"Control Light Brightness","text":"
const response = await fetch('http://your-ha-mcp/api/devices/light/living_room/control', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"service\": \"turn_on\",\n        \"data\": {\n            \"brightness\": 128\n        }\n    })\n});\n
"},{"location":"tools/device-management/control.html#control-cover-position","title":"Control Cover Position","text":"
const response = await fetch('http://your-ha-mcp/api/devices/cover/bedroom/control', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"service\": \"set_cover_position\",\n        \"data\": {\n            \"position\": 75\n        }\n    })\n});\n
"},{"location":"tools/device-management/control.html#response-format","title":"Response Format","text":""},{"location":"tools/device-management/control.html#success-response","title":"Success Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"state\": \"on\",\n        \"attributes\": {\n            // Updated device attributes\n        }\n    }\n}\n
"},{"location":"tools/device-management/control.html#error-response","title":"Error Response","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/device-management/control.html#error-handling","title":"Error Handling","text":""},{"location":"tools/device-management/control.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/device-management/control.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/device-management/control.html#best-practices","title":"Best Practices","text":"
  1. Validate device availability before sending commands
  2. Implement proper error handling
  3. Use appropriate retry strategies for failed commands
  4. Cache device capabilities when possible
  5. Handle rate limiting gracefully
"},{"location":"tools/device-management/control.html#see-also","title":"See Also","text":""},{"location":"tools/device-management/list-devices.html","title":"List Devices Tool","text":"

The List Devices tool provides functionality to retrieve and manage device information from your Home Assistant instance.

"},{"location":"tools/device-management/list-devices.html#features","title":"Features","text":""},{"location":"tools/device-management/list-devices.html#usage","title":"Usage","text":""},{"location":"tools/device-management/list-devices.html#rest-api","title":"REST API","text":"
GET /api/devices\nGET /api/devices/{domain}\nGET /api/devices/{device_id}/state\n
"},{"location":"tools/device-management/list-devices.html#websocket","title":"WebSocket","text":"
// List all devices\n{\n    \"type\": \"list_devices\",\n    \"domain\": \"optional_domain\"\n}\n\n// Get device state\n{\n    \"type\": \"get_device_state\",\n    \"device_id\": \"required_device_id\"\n}\n
"},{"location":"tools/device-management/list-devices.html#examples","title":"Examples","text":""},{"location":"tools/device-management/list-devices.html#list-all-devices","title":"List All Devices","text":"
const response = await fetch('http://your-ha-mcp/api/devices', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst devices = await response.json();\n
"},{"location":"tools/device-management/list-devices.html#get-devices-by-domain","title":"Get Devices by Domain","text":"
const response = await fetch('http://your-ha-mcp/api/devices/light', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst lightDevices = await response.json();\n
"},{"location":"tools/device-management/list-devices.html#response-format","title":"Response Format","text":""},{"location":"tools/device-management/list-devices.html#device-list-response","title":"Device List Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"devices\": [\n            {\n                \"id\": \"device_id\",\n                \"name\": \"Device Name\",\n                \"domain\": \"light\",\n                \"state\": \"on\",\n                \"attributes\": {\n                    \"brightness\": 255,\n                    \"color_temp\": 370\n                }\n            }\n        ]\n    }\n}\n
"},{"location":"tools/device-management/list-devices.html#device-state-response","title":"Device State Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"state\": \"on\",\n        \"attributes\": {\n            \"brightness\": 255,\n            \"color_temp\": 370\n        },\n        \"last_changed\": \"2024-02-05T12:00:00Z\",\n        \"last_updated\": \"2024-02-05T12:00:00Z\"\n    }\n}\n
"},{"location":"tools/device-management/list-devices.html#error-handling","title":"Error Handling","text":""},{"location":"tools/device-management/list-devices.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/device-management/list-devices.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/device-management/list-devices.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/device-management/list-devices.html#best-practices","title":"Best Practices","text":"
  1. Cache device lists when possible
  2. Use domain filtering for better performance
  3. Implement proper error handling
  4. Handle rate limiting gracefully
"},{"location":"tools/device-management/list-devices.html#see-also","title":"See Also","text":""},{"location":"tools/events/sse-stats.html","title":"SSE Statistics Tool","text":"

The SSE Statistics tool provides functionality to monitor and analyze Server-Sent Events (SSE) connections and performance in your Home Assistant MCP instance.

"},{"location":"tools/events/sse-stats.html#features","title":"Features","text":""},{"location":"tools/events/sse-stats.html#usage","title":"Usage","text":""},{"location":"tools/events/sse-stats.html#rest-api","title":"REST API","text":"
GET /api/sse/stats\nGET /api/sse/connections\nGET /api/sse/connections/{connection_id}\nGET /api/sse/metrics\nGET /api/sse/history\n
"},{"location":"tools/events/sse-stats.html#websocket","title":"WebSocket","text":"
// Get SSE stats\n{\n    \"type\": \"get_sse_stats\"\n}\n\n// Get connection details\n{\n    \"type\": \"get_sse_connection\",\n    \"connection_id\": \"required_connection_id\"\n}\n\n// Get performance metrics\n{\n    \"type\": \"get_sse_metrics\",\n    \"period\": \"1h|24h|7d|30d\"\n}\n
"},{"location":"tools/events/sse-stats.html#examples","title":"Examples","text":""},{"location":"tools/events/sse-stats.html#get-current-statistics","title":"Get Current Statistics","text":"
const response = await fetch('http://your-ha-mcp/api/sse/stats', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst stats = await response.json();\n
"},{"location":"tools/events/sse-stats.html#get-connection-details","title":"Get Connection Details","text":"
const response = await fetch('http://your-ha-mcp/api/sse/connections/conn_123', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst connection = await response.json();\n
"},{"location":"tools/events/sse-stats.html#get-performance-metrics","title":"Get Performance Metrics","text":"
const response = await fetch('http://your-ha-mcp/api/sse/metrics?period=24h', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst metrics = await response.json();\n
"},{"location":"tools/events/sse-stats.html#response-format","title":"Response Format","text":""},{"location":"tools/events/sse-stats.html#statistics-response","title":"Statistics Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"active_connections\": 42,\n        \"total_events_sent\": 12345,\n        \"events_per_second\": 5.2,\n        \"memory_usage\": 128974848,\n        \"cpu_usage\": 2.5,\n        \"uptime\": \"PT24H\",\n        \"event_backlog\": 0\n    }\n}\n
"},{"location":"tools/events/sse-stats.html#connection-details-response","title":"Connection Details Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"connection\": {\n            \"id\": \"conn_123\",\n            \"client_id\": \"client_456\",\n            \"user_id\": \"user_789\",\n            \"connected_at\": \"2024-02-05T12:00:00Z\",\n            \"last_event_at\": \"2024-02-05T12:05:00Z\",\n            \"events_sent\": 150,\n            \"subscriptions\": [\n                {\n                    \"event_type\": \"state_changed\",\n                    \"entity_id\": \"light.living_room\"\n                }\n            ],\n            \"state\": \"active\",\n            \"ip_address\": \"192.168.1.100\",\n            \"user_agent\": \"Mozilla/5.0 ...\"\n        }\n    }\n}\n
"},{"location":"tools/events/sse-stats.html#performance-metrics-response","title":"Performance Metrics Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"metrics\": {\n            \"connections\": {\n                \"current\": 42,\n                \"max\": 100,\n                \"average\": 35.5\n            },\n            \"events\": {\n                \"total\": 12345,\n                \"rate\": {\n                    \"current\": 5.2,\n                    \"max\": 15.0,\n                    \"average\": 4.8\n                }\n            },\n            \"latency\": {\n                \"p50\": 15,\n                \"p95\": 45,\n                \"p99\": 100\n            },\n            \"resources\": {\n                \"memory\": {\n                    \"current\": 128974848,\n                    \"max\": 536870912\n                },\n                \"cpu\": {\n                    \"current\": 2.5,\n                    \"max\": 10.0,\n                    \"average\": 3.2\n                }\n            }\n        },\n        \"period\": \"24h\",\n        \"timestamp\": \"2024-02-05T12:00:00Z\"\n    }\n}\n
"},{"location":"tools/events/sse-stats.html#error-handling","title":"Error Handling","text":""},{"location":"tools/events/sse-stats.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/events/sse-stats.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/events/sse-stats.html#monitoring-metrics","title":"Monitoring Metrics","text":""},{"location":"tools/events/sse-stats.html#connection-metrics","title":"Connection Metrics","text":""},{"location":"tools/events/sse-stats.html#event-metrics","title":"Event Metrics","text":""},{"location":"tools/events/sse-stats.html#resource-metrics","title":"Resource Metrics","text":""},{"location":"tools/events/sse-stats.html#alert-thresholds","title":"Alert Thresholds","text":""},{"location":"tools/events/sse-stats.html#best-practices","title":"Best Practices","text":"
  1. Monitor connection health
  2. Track resource usage
  3. Set up alerts
  4. Analyze usage patterns
  5. Optimize performance
  6. Plan capacity
  7. Implement failover
  8. Regular maintenance
"},{"location":"tools/events/sse-stats.html#performance-optimization","title":"Performance Optimization","text":""},{"location":"tools/events/sse-stats.html#see-also","title":"See Also","text":""},{"location":"tools/events/subscribe-events.html","title":"Event Subscription Tool","text":"

The Event Subscription tool provides functionality to subscribe to and monitor real-time events from your Home Assistant instance.

"},{"location":"tools/events/subscribe-events.html#features","title":"Features","text":""},{"location":"tools/events/subscribe-events.html#usage","title":"Usage","text":""},{"location":"tools/events/subscribe-events.html#rest-api","title":"REST API","text":"
POST /api/events/subscribe\nDELETE /api/events/unsubscribe\nGET /api/events/subscriptions\nGET /api/events/history\n
"},{"location":"tools/events/subscribe-events.html#websocket","title":"WebSocket","text":"
// Subscribe to events\n{\n    \"type\": \"subscribe_events\",\n    \"event_type\": \"optional_event_type\",\n    \"entity_id\": \"optional_entity_id\",\n    \"domain\": \"optional_domain\"\n}\n\n// Unsubscribe from events\n{\n    \"type\": \"unsubscribe_events\",\n    \"subscription_id\": \"required_subscription_id\"\n}\n
"},{"location":"tools/events/subscribe-events.html#server-sent-events-sse","title":"Server-Sent Events (SSE)","text":"
GET /api/events/stream?event_type=state_changed&entity_id=light.living_room\n
"},{"location":"tools/events/subscribe-events.html#event-types","title":"Event Types","text":""},{"location":"tools/events/subscribe-events.html#examples","title":"Examples","text":""},{"location":"tools/events/subscribe-events.html#subscribe-to-all-state-changes","title":"Subscribe to All State Changes","text":"
const response = await fetch('http://your-ha-mcp/api/events/subscribe', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"event_type\": \"state_changed\"\n    })\n});\n
"},{"location":"tools/events/subscribe-events.html#monitor-specific-entity","title":"Monitor Specific Entity","text":"
const response = await fetch('http://your-ha-mcp/api/events/subscribe', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"event_type\": \"state_changed\",\n        \"entity_id\": \"light.living_room\"\n    })\n});\n
"},{"location":"tools/events/subscribe-events.html#domain-based-monitoring","title":"Domain-Based Monitoring","text":"
const response = await fetch('http://your-ha-mcp/api/events/subscribe', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"event_type\": \"state_changed\",\n        \"domain\": \"light\"\n    })\n});\n
"},{"location":"tools/events/subscribe-events.html#sse-connection-example","title":"SSE Connection Example","text":"
const eventSource = new EventSource(\n    'http://your-ha-mcp/api/events/stream?event_type=state_changed&entity_id=light.living_room',\n    {\n        headers: {\n            'Authorization': 'Bearer your_access_token'\n        }\n    }\n);\n\neventSource.onmessage = (event) => {\n    const data = JSON.parse(event.data);\n    console.log('Event received:', data);\n};\n\neventSource.onerror = (error) => {\n    console.error('SSE error:', error);\n    eventSource.close();\n};\n
"},{"location":"tools/events/subscribe-events.html#response-format","title":"Response Format","text":""},{"location":"tools/events/subscribe-events.html#subscription-response","title":"Subscription Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"subscription_id\": \"sub_123\",\n        \"event_type\": \"state_changed\",\n        \"entity_id\": \"light.living_room\",\n        \"created_at\": \"2024-02-05T12:00:00Z\"\n    }\n}\n
"},{"location":"tools/events/subscribe-events.html#event-message-format","title":"Event Message Format","text":"
{\n    \"event_type\": \"state_changed\",\n    \"entity_id\": \"light.living_room\",\n    \"data\": {\n        \"old_state\": {\n            \"state\": \"off\",\n            \"attributes\": {},\n            \"last_changed\": \"2024-02-05T11:55:00Z\"\n        },\n        \"new_state\": {\n            \"state\": \"on\",\n            \"attributes\": {\n                \"brightness\": 255\n            },\n            \"last_changed\": \"2024-02-05T12:00:00Z\"\n        }\n    },\n    \"origin\": \"LOCAL\",\n    \"time_fired\": \"2024-02-05T12:00:00Z\",\n    \"context\": {\n        \"id\": \"context_123\",\n        \"parent_id\": null,\n        \"user_id\": \"user_123\"\n    }\n}\n
"},{"location":"tools/events/subscribe-events.html#subscriptions-list-response","title":"Subscriptions List Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"subscriptions\": [\n            {\n                \"id\": \"sub_123\",\n                \"event_type\": \"state_changed\",\n                \"entity_id\": \"light.living_room\",\n                \"created_at\": \"2024-02-05T12:00:00Z\",\n                \"last_event\": \"2024-02-05T12:05:00Z\"\n            }\n        ]\n    }\n}\n
"},{"location":"tools/events/subscribe-events.html#error-handling","title":"Error Handling","text":""},{"location":"tools/events/subscribe-events.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/events/subscribe-events.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/events/subscribe-events.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/events/subscribe-events.html#best-practices","title":"Best Practices","text":"
  1. Use specific event types when possible
  2. Implement proper error handling
  3. Handle connection interruptions
  4. Process events asynchronously
  5. Implement backoff strategies
  6. Monitor subscription health
  7. Clean up unused subscriptions
  8. Handle rate limiting gracefully
"},{"location":"tools/events/subscribe-events.html#connection-management","title":"Connection Management","text":""},{"location":"tools/events/subscribe-events.html#see-also","title":"See Also","text":""},{"location":"tools/history-state/history.html","title":"Device History Tool","text":"

The Device History tool allows you to retrieve historical state information for devices in your Home Assistant instance.

"},{"location":"tools/history-state/history.html#features","title":"Features","text":""},{"location":"tools/history-state/history.html#usage","title":"Usage","text":""},{"location":"tools/history-state/history.html#rest-api","title":"REST API","text":"
GET /api/history/{device_id}\nGET /api/history/{device_id}/period/{start_time}\nGET /api/history/{device_id}/period/{start_time}/{end_time}\n
"},{"location":"tools/history-state/history.html#websocket","title":"WebSocket","text":"
{\n    \"type\": \"get_history\",\n    \"device_id\": \"required_device_id\",\n    \"start_time\": \"optional_iso_timestamp\",\n    \"end_time\": \"optional_iso_timestamp\",\n    \"significant_changes_only\": false\n}\n
"},{"location":"tools/history-state/history.html#query-parameters","title":"Query Parameters","text":"Parameter Type Description start_time ISO timestamp Start of the period to fetch history for end_time ISO timestamp End of the period to fetch history for significant_changes_only boolean Only return significant state changes minimal_response boolean Return minimal state information no_attributes boolean Exclude attribute data from response"},{"location":"tools/history-state/history.html#examples","title":"Examples","text":""},{"location":"tools/history-state/history.html#get-recent-history","title":"Get Recent History","text":"
const response = await fetch('http://your-ha-mcp/api/history/light.living_room', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst history = await response.json();\n
"},{"location":"tools/history-state/history.html#get-history-for-specific-period","title":"Get History for Specific Period","text":"
const startTime = '2024-02-01T00:00:00Z';\nconst endTime = '2024-02-02T00:00:00Z';\nconst response = await fetch(\n    `http://your-ha-mcp/api/history/light.living_room/period/${startTime}/${endTime}`, \n    {\n        headers: {\n            'Authorization': 'Bearer your_access_token'\n        }\n    }\n);\nconst history = await response.json();\n
"},{"location":"tools/history-state/history.html#response-format","title":"Response Format","text":""},{"location":"tools/history-state/history.html#history-response","title":"History Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"history\": [\n            {\n                \"state\": \"on\",\n                \"attributes\": {\n                    \"brightness\": 255\n                },\n                \"last_changed\": \"2024-02-05T12:00:00Z\",\n                \"last_updated\": \"2024-02-05T12:00:00Z\"\n            },\n            {\n                \"state\": \"off\",\n                \"last_changed\": \"2024-02-05T13:00:00Z\",\n                \"last_updated\": \"2024-02-05T13:00:00Z\"\n            }\n        ]\n    }\n}\n
"},{"location":"tools/history-state/history.html#aggregated-history-response","title":"Aggregated History Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"aggregates\": {\n            \"daily\": [\n                {\n                    \"date\": \"2024-02-05\",\n                    \"on_time\": \"PT5H30M\",\n                    \"off_time\": \"PT18H30M\",\n                    \"changes\": 10\n                }\n            ]\n        }\n    }\n}\n
"},{"location":"tools/history-state/history.html#error-handling","title":"Error Handling","text":""},{"location":"tools/history-state/history.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/history-state/history.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/history-state/history.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/history-state/history.html#data-retention","title":"Data Retention","text":""},{"location":"tools/history-state/history.html#best-practices","title":"Best Practices","text":"
  1. Use appropriate time ranges to avoid large responses
  2. Enable significant_changes_only for better performance
  3. Use minimal_response when full state data isn't needed
  4. Implement proper error handling
  5. Cache frequently accessed historical data
  6. Handle rate limiting gracefully
"},{"location":"tools/history-state/history.html#see-also","title":"See Also","text":""},{"location":"tools/history-state/scene.html","title":"Scene Management Tool","text":"

The Scene Management tool provides functionality to manage and control scenes in your Home Assistant instance.

"},{"location":"tools/history-state/scene.html#features","title":"Features","text":""},{"location":"tools/history-state/scene.html#usage","title":"Usage","text":""},{"location":"tools/history-state/scene.html#rest-api","title":"REST API","text":"
GET /api/scenes\nGET /api/scenes/{scene_id}\nPOST /api/scenes/{scene_id}/activate\nPOST /api/scenes\nPUT /api/scenes/{scene_id}\nDELETE /api/scenes/{scene_id}\n
"},{"location":"tools/history-state/scene.html#websocket","title":"WebSocket","text":"
// List scenes\n{\n    \"type\": \"get_scenes\"\n}\n\n// Activate scene\n{\n    \"type\": \"activate_scene\",\n    \"scene_id\": \"required_scene_id\"\n}\n\n// Create/Update scene\n{\n    \"type\": \"create_scene\",\n    \"scene\": {\n        \"name\": \"required_scene_name\",\n        \"entities\": {\n            // Entity states\n        }\n    }\n}\n
"},{"location":"tools/history-state/scene.html#scene-configuration","title":"Scene Configuration","text":""},{"location":"tools/history-state/scene.html#scene-definition","title":"Scene Definition","text":"
{\n    \"name\": \"Movie Night\",\n    \"entities\": {\n        \"light.living_room\": {\n            \"state\": \"on\",\n            \"brightness\": 50,\n            \"color_temp\": 2700\n        },\n        \"cover.living_room\": {\n            \"state\": \"closed\"\n        },\n        \"media_player.tv\": {\n            \"state\": \"on\",\n            \"source\": \"HDMI 1\"\n        }\n    }\n}\n
"},{"location":"tools/history-state/scene.html#examples","title":"Examples","text":""},{"location":"tools/history-state/scene.html#list-all-scenes","title":"List All Scenes","text":"
const response = await fetch('http://your-ha-mcp/api/scenes', {\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\nconst scenes = await response.json();\n
"},{"location":"tools/history-state/scene.html#activate-a-scene","title":"Activate a Scene","text":"
const response = await fetch('http://your-ha-mcp/api/scenes/movie_night/activate', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token'\n    }\n});\n
"},{"location":"tools/history-state/scene.html#create-a-new-scene","title":"Create a New Scene","text":"
const response = await fetch('http://your-ha-mcp/api/scenes', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"name\": \"Movie Night\",\n        \"entities\": {\n            \"light.living_room\": {\n                \"state\": \"on\",\n                \"brightness\": 50\n            },\n            \"cover.living_room\": {\n                \"state\": \"closed\"\n            }\n        }\n    })\n});\n
"},{"location":"tools/history-state/scene.html#response-format","title":"Response Format","text":""},{"location":"tools/history-state/scene.html#scene-list-response","title":"Scene List Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"scenes\": [\n            {\n                \"id\": \"scene_id\",\n                \"name\": \"Scene Name\",\n                \"entities\": {\n                    // Entity configurations\n                }\n            }\n        ]\n    }\n}\n
"},{"location":"tools/history-state/scene.html#scene-activation-response","title":"Scene Activation Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"scene_id\": \"activated_scene_id\",\n        \"status\": \"activated\",\n        \"timestamp\": \"2024-02-05T12:00:00Z\"\n    }\n}\n
"},{"location":"tools/history-state/scene.html#error-handling","title":"Error Handling","text":""},{"location":"tools/history-state/scene.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/history-state/scene.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/history-state/scene.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/history-state/scene.html#best-practices","title":"Best Practices","text":"
  1. Validate entity availability before creating scenes
  2. Use meaningful scene names
  3. Group related entities in scenes
  4. Implement proper error handling
  5. Cache scene configurations when possible
  6. Handle rate limiting gracefully
"},{"location":"tools/history-state/scene.html#scene-transitions","title":"Scene Transitions","text":"

Scenes can include transition settings for smooth state changes:

{\n    \"name\": \"Sunset Mode\",\n    \"entities\": {\n        \"light.living_room\": {\n            \"state\": \"on\",\n            \"brightness\": 128,\n            \"transition\": 5  // 5 seconds\n        }\n    }\n}\n
"},{"location":"tools/history-state/scene.html#see-also","title":"See Also","text":""},{"location":"tools/notifications/notify.html","title":"Notification Tool","text":"

The Notification tool provides functionality to send notifications through various services in your Home Assistant instance.

"},{"location":"tools/notifications/notify.html#features","title":"Features","text":""},{"location":"tools/notifications/notify.html#usage","title":"Usage","text":""},{"location":"tools/notifications/notify.html#rest-api","title":"REST API","text":"
POST /api/notify\nPOST /api/notify/{service_id}\nGET /api/notify/services\nGET /api/notify/history\n
"},{"location":"tools/notifications/notify.html#websocket","title":"WebSocket","text":"
// Send notification\n{\n    \"type\": \"send_notification\",\n    \"service\": \"required_service_id\",\n    \"message\": \"required_message\",\n    \"title\": \"optional_title\",\n    \"data\": {\n        // Service-specific data\n    }\n}\n\n// Get notification services\n{\n    \"type\": \"get_notification_services\"\n}\n
"},{"location":"tools/notifications/notify.html#supported-services","title":"Supported Services","text":""},{"location":"tools/notifications/notify.html#examples","title":"Examples","text":""},{"location":"tools/notifications/notify.html#basic-notification","title":"Basic Notification","text":"
const response = await fetch('http://your-ha-mcp/api/notify/mobile_app', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"message\": \"Motion detected in living room\",\n        \"title\": \"Security Alert\"\n    })\n});\n
"},{"location":"tools/notifications/notify.html#rich-notification","title":"Rich Notification","text":"
const response = await fetch('http://your-ha-mcp/api/notify/mobile_app', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"message\": \"Motion detected in living room\",\n        \"title\": \"Security Alert\",\n        \"data\": {\n            \"image\": \"https://your-camera-snapshot.jpg\",\n            \"actions\": [\n                {\n                    \"action\": \"view_camera\",\n                    \"title\": \"View Camera\"\n                },\n                {\n                    \"action\": \"dismiss\",\n                    \"title\": \"Dismiss\"\n                }\n            ],\n            \"priority\": \"high\",\n            \"ttl\": 3600,\n            \"group\": \"security\"\n        }\n    })\n});\n
"},{"location":"tools/notifications/notify.html#service-specific-example-telegram","title":"Service-Specific Example (Telegram)","text":"
const response = await fetch('http://your-ha-mcp/api/notify/telegram', {\n    method: 'POST',\n    headers: {\n        'Authorization': 'Bearer your_access_token',\n        'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({\n        \"message\": \"Temperature is too high!\",\n        \"title\": \"Climate Alert\",\n        \"data\": {\n            \"parse_mode\": \"markdown\",\n            \"inline_keyboard\": [\n                [\n                    {\n                        \"text\": \"Turn On AC\",\n                        \"callback_data\": \"turn_on_ac\"\n                    }\n                ]\n            ]\n        }\n    })\n});\n
"},{"location":"tools/notifications/notify.html#response-format","title":"Response Format","text":""},{"location":"tools/notifications/notify.html#success-response","title":"Success Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"notification_id\": \"notification_123\",\n        \"status\": \"sent\",\n        \"timestamp\": \"2024-02-05T12:00:00Z\",\n        \"service\": \"mobile_app\"\n    }\n}\n
"},{"location":"tools/notifications/notify.html#services-list-response","title":"Services List Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"services\": [\n            {\n                \"id\": \"mobile_app\",\n                \"name\": \"Mobile App\",\n                \"enabled\": true,\n                \"features\": [\n                    \"actions\",\n                    \"images\",\n                    \"sound\"\n                ]\n            }\n        ]\n    }\n}\n
"},{"location":"tools/notifications/notify.html#notification-history-response","title":"Notification History Response","text":"
{\n    \"success\": true,\n    \"data\": {\n        \"history\": [\n            {\n                \"id\": \"notification_123\",\n                \"service\": \"mobile_app\",\n                \"message\": \"Motion detected\",\n                \"title\": \"Security Alert\",\n                \"timestamp\": \"2024-02-05T12:00:00Z\",\n                \"status\": \"delivered\"\n            }\n        ]\n    }\n}\n
"},{"location":"tools/notifications/notify.html#error-handling","title":"Error Handling","text":""},{"location":"tools/notifications/notify.html#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/notifications/notify.html#error-response-format","title":"Error Response Format","text":"
{\n    \"success\": false,\n    \"message\": \"Error description\",\n    \"error_code\": \"ERROR_CODE\"\n}\n
"},{"location":"tools/notifications/notify.html#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/notifications/notify.html#best-practices","title":"Best Practices","text":"
  1. Use appropriate priority levels
  2. Group related notifications
  3. Include relevant context
  4. Implement proper error handling
  5. Use templates for consistency
  6. Consider time zones
  7. Respect user preferences
  8. Handle rate limiting gracefully
"},{"location":"tools/notifications/notify.html#notification-templates","title":"Notification Templates","text":"
// Template example\n{\n    \"template\": \"security_alert\",\n    \"data\": {\n        \"location\": \"living_room\",\n        \"event_type\": \"motion\",\n        \"timestamp\": \"2024-02-05T12:00:00Z\"\n    }\n}\n
"},{"location":"tools/notifications/notify.html#see-also","title":"See Also","text":""}]} \ No newline at end of file diff --git a/sitemap.xml b/sitemap.xml index 20e7276..b84d3d9 100644 --- a/sitemap.xml +++ b/sitemap.xml @@ -88,6 +88,10 @@ https://jango-blockchained.github.io/advanced-homeassistant-mcp/examples/index.html 2025-02-06 + + https://jango-blockchained.github.io/advanced-homeassistant-mcp/features/speech.html + 2025-02-06 + https://jango-blockchained.github.io/advanced-homeassistant-mcp/getting-started/index.html 2025-02-06 diff --git a/sitemap.xml.gz b/sitemap.xml.gz index fe29794962ff7c9fd646cd6e3bff50874a3bf27f..1e894b987f02f4c25c3b64002c4119316d10909d 100644 GIT binary patch delta 540 zcmV+%0^|Lf1gQj&7=KHS+b|43_j8KCd)b))E!rZkH+E^q6;(?<0@&4sD#LWdV1x$zPx!zVANDh5S-JyDW{cgTgFUO~S$&r9JayZeU z>Y2xHO>@0oYYGg59jV6LHRO5`sCg)xZT+=6K5b-82A18t_J0xGak4^U=7&uknpRY2 z*V~Z5*InSgv~|G7`io5tyy$3G0TS!v z%V@nM2%T^Qu7Bjfcb#+$q&Mz3V`(E$kEj>2knKQi-B4cEB>82<&LdJ?)-+$PhYLg; zr=qbI%vN%t8MAd99FTrqNSBZ?>8;Cu#{fe<*;P1pDvD+Z-O@Fht^^M&phk>JoeMWR zj8e!oXMz*hX^fF^a|Cd`PRI^;>V%AFGK1Ib&yT1pn194RB6~3ac`cD3yBJsG-Jd16 z^DHQxKBj!C`GqZj)_Y83M(fTph&<#q0Y5gXkqhH6KdpCLvt+c@acc&aenxt4GuR{% zF?Tid-!Y8qf{t>=ENaqBF5P2dn#SBIEAuK?OG_??7R;j1jNFR`^L_R${Fc@OOb(Lj ew49K`DHXUmt39NDbnpBj;Nvf9uD&|T8UO$UqX`MSQ?ku*~i=CwgVlw zMMzF>8e5U|lk5EL^zeEgJ-uw?nFFk=<$pOubf-BANto|8^=LYA zUEE+p0^jt3htf3xTkEejIq+t{5iC(4wu#N?rZyxG_h#TR9@;tH+whinM1R`v_V3MZ zZ+0JK%hR{=w7-G=2b!INQn2g>`8bYC2AzZs(>e4dTb7Dci^w^2h2@awB=j&ve2kD- zCtpVEMIdy-5r4Rn13z@qF_7N6