From f2738de8a872d65c10c51a3513e860dde63a4596 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Thu, 6 Feb 2025 03:12:07 +0000 Subject: [PATCH] Deployed 81d6dea with MkDocs version: 1.6.1 --- .nojekyll | 0 404.html | 1734 +--------- api.html | 73 + api/core.html | 158 + api/core/index.html | 2443 -------------- api/index.html | 2401 +------------ api/sse.html | 146 + api/sse/index.html | 2429 ------------- architecture.html | 26 + architecture/index.html | 2108 ------------ assets/_mkdocstrings.css | 143 - config/index.html | 1 + configuration.html | 32 + contributing.html | 25 + contributing/index.html | 2207 ------------ deployment.html | 33 + development/best-practices.html | 140 + development/best-practices/index.html | 2619 --------------- development/development/index.html | 2297 ------------- development/environment.html | 51 + development/index.html | 1 + development/interfaces.html | 200 ++ development/interfaces/index.html | 2536 -------------- development/test-migration-guide.html | 177 + development/test-migration-guide/index.html | 2437 -------------- development/tools.html | 125 + development/tools/index.html | 2382 ------------- examples/index.html | 1884 +---------- getting-started/configuration.html | 1 + getting-started/configuration/index.html | 1875 ----------- getting-started/docker.html | 1 + getting-started/docker/index.html | 1799 ---------- getting-started/index.html | 1915 +---------- getting-started/installation.html | 75 + getting-started/installation/index.html | 2308 ------------- getting-started/quickstart.html | 128 + getting-started/quickstart/index.html | 2286 ------------- index.html | 2059 +----------- javascripts/extra.js | 62 + javascripts/mathjax.js | 12 + objects.inv | Bin 149 -> 0 bytes requirements.txt | 42 + roadmap.html | 1 + roadmap/index.html | 1968 ----------- search/search_index.js | 1 + search/search_index.json | 2 +- security.html | 28 + sitemap.xml | 156 +- sitemap.xml.gz | Bin 506 -> 538 bytes stylesheets/extra.css | 164 + testing.html | 173 + testing/index.html | 2835 ---------------- tools/addons-packages/addon.html | 133 + tools/addons-packages/addon/index.html | 2434 -------------- tools/addons-packages/package.html | 118 + tools/addons-packages/package/index.html | 2448 -------------- tools/automation/automation-config.html | 221 ++ tools/automation/automation-config/index.html | 2538 -------------- tools/automation/automation.html | 117 + tools/automation/automation/index.html | 2387 ------------- tools/device-management/control.html | 101 + tools/device-management/control/index.html | 2400 ------------- tools/device-management/list-devices.html | 61 + .../device-management/list-devices/index.html | 2285 ------------- tools/events/sse-stats.html | 117 + tools/events/sse-stats/index.html | 2531 -------------- tools/events/subscribe-events.html | 122 + tools/events/subscribe-events/index.html | 2495 -------------- tools/history-state/history.html | 68 + tools/history-state/history/index.html | 2376 ------------- tools/history-state/scene.html | 113 + tools/history-state/scene/index.html | 2434 -------------- tools/index.html | 1 + tools/notifications/notify.html | 135 + tools/notifications/notify/index.html | 2458 -------------- tools/tools/index.html | 2238 ------------ troubleshooting.html | 96 + troubleshooting/index.html | 2992 ----------------- usage.html | 22 + usage/index.html | 2158 ------------ 80 files changed, 3480 insertions(+), 78818 deletions(-) create mode 100644 .nojekyll create mode 100644 api.html create mode 100644 api/core.html delete mode 100644 api/core/index.html create mode 100644 api/sse.html delete mode 100644 api/sse/index.html create mode 100644 architecture.html delete mode 100644 architecture/index.html create mode 100644 config/index.html create mode 100644 configuration.html create mode 100644 contributing.html delete mode 100644 contributing/index.html create mode 100644 deployment.html create mode 100644 development/best-practices.html delete mode 100644 development/best-practices/index.html delete mode 100644 development/development/index.html create mode 100644 development/environment.html create mode 100644 development/index.html create mode 100644 development/interfaces.html delete mode 100644 development/interfaces/index.html create mode 100644 development/test-migration-guide.html delete mode 100644 development/test-migration-guide/index.html create mode 100644 development/tools.html delete mode 100644 development/tools/index.html create mode 100644 getting-started/configuration.html delete mode 100644 getting-started/configuration/index.html create mode 100644 getting-started/docker.html delete mode 100644 getting-started/docker/index.html create mode 100644 getting-started/installation.html delete mode 100644 getting-started/installation/index.html create mode 100644 getting-started/quickstart.html delete mode 100644 getting-started/quickstart/index.html create mode 100644 javascripts/extra.js create mode 100644 javascripts/mathjax.js delete mode 100644 objects.inv create mode 100644 requirements.txt create mode 100644 roadmap.html delete mode 100644 roadmap/index.html create mode 100644 search/search_index.js create mode 100644 security.html create mode 100644 stylesheets/extra.css create mode 100644 testing.html delete mode 100644 testing/index.html create mode 100644 tools/addons-packages/addon.html delete mode 100644 tools/addons-packages/addon/index.html create mode 100644 tools/addons-packages/package.html delete mode 100644 tools/addons-packages/package/index.html create mode 100644 tools/automation/automation-config.html delete mode 100644 tools/automation/automation-config/index.html create mode 100644 tools/automation/automation.html delete mode 100644 tools/automation/automation/index.html create mode 100644 tools/device-management/control.html delete mode 100644 tools/device-management/control/index.html create mode 100644 tools/device-management/list-devices.html delete mode 100644 tools/device-management/list-devices/index.html create mode 100644 tools/events/sse-stats.html delete mode 100644 tools/events/sse-stats/index.html create mode 100644 tools/events/subscribe-events.html delete mode 100644 tools/events/subscribe-events/index.html create mode 100644 tools/history-state/history.html delete mode 100644 tools/history-state/history/index.html create mode 100644 tools/history-state/scene.html delete mode 100644 tools/history-state/scene/index.html create mode 100644 tools/index.html create mode 100644 tools/notifications/notify.html delete mode 100644 tools/notifications/notify/index.html delete mode 100644 tools/tools/index.html create mode 100644 troubleshooting.html delete mode 100644 troubleshooting/index.html create mode 100644 usage.html delete mode 100644 usage/index.html diff --git a/.nojekyll b/.nojekyll new file mode 100644 index 0000000..e69de29 diff --git a/404.html b/404.html index bf07461..bf63eb6 100644 --- a/404.html +++ b/404.html @@ -1,1733 +1 @@ - - - - - - - - - - - - - - - - - - - Advanced Home Assistant MCP - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
-
- -
- - - - - - -
- - -
- -
- - - - - - -
-
- - - -
-
-
- - - - - -
-
-
- - - -
-
-
- - - -
-
-
- - - -
-
- -

404 - Not found

- -
-
- - - -
- - - -
- - - -
-
-
-
- - - - - - - - - - - - \ No newline at end of file + MCP Server for Home Assistant

404 - Not found

\ No newline at end of file diff --git a/api.html b/api.html new file mode 100644 index 0000000..b096553 --- /dev/null +++ b/api.html @@ -0,0 +1,73 @@ + API Documentation - MCP Server for Home Assistant
Skip to content

Home Assistant MCP Server API Documentation

Overview

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

Authentication

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

Authorization: Bearer YOUR_TOKEN
+

Core Endpoints

Device State Management

Get Device State

GET /api/state/{entity_id}
+

Response:

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

Update Device State

POST /api/state
+Content-Type: application/json
+
+{
+  "entity_id": "light.living_room",
+  "state": "on",
+  "attributes": {
+    "brightness": 128
+  }
+}
+

Device Control

Execute Device Command

POST /api/control
+Content-Type: application/json
+
+{
+  "entity_id": "light.living_room",
+  "command": "turn_on",
+  "parameters": {
+    "brightness": 50
+  }
+}
+

Real-Time Updates

WebSocket Connection

Connect to real-time updates:

const ws = new WebSocket('ws://localhost:3000/events');
+ws.onmessage = (event) => {
+  const deviceUpdate = JSON.parse(event.data);
+  console.log('Device state changed:', deviceUpdate);
+};
+

Error Handling

Common Error Responses

{
+  "error": {
+    "code": "INVALID_REQUEST",
+    "message": "Invalid request parameters",
+    "details": "Entity ID not found or invalid command"
+  }
+}
+

Rate Limiting

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

Supported Operations

Supported Commands

  • turn_on
  • turn_off
  • toggle
  • set_brightness
  • set_color

Supported Entities

  • Lights
  • Switches
  • Climate controls
  • Media players

Limitations

  • Limited to basic device control
  • No advanced automation
  • Minimal error handling
  • Basic authentication

Best Practices

  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

Example Client Usage

async function controlDevice(entityId: string, command: string, params?: Record<string, unknown>) {
+  try {
+    const response = await fetch('/api/control', {
+    method: 'POST',
+    headers: {
+        'Content-Type': 'application/json',
+        'Authorization': `Bearer ${token}`
+    },
+    body: JSON.stringify({
+        entity_id: entityId,
+        command,
+        parameters: params
+    })
+  });
+
+    if (!response.ok) {
+      const error = await response.json();
+      throw new Error(error.message);
+    }
+
+    return await response.json();
+} catch (error) {
+    console.error('Device control failed:', error);
+    throw error;
+  }
+}
+
+// Usage example
+controlDevice('light.living_room', 'turn_on', { brightness: 50 })
+  .then(result => console.log('Device controlled successfully'))
+  .catch(error => console.error('Control failed', error));
+

Future Development

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

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

\ No newline at end of file diff --git a/api/core.html b/api/core.html new file mode 100644 index 0000000..0ae129a --- /dev/null +++ b/api/core.html @@ -0,0 +1,158 @@ + Core Functions - MCP Server for Home Assistant
Skip to content

Core Functions API 🔧

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

Device Control

Get Device State

Retrieve the current state of devices.

GET /api/state
+GET /api/state/{entity_id}
+

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

# Get all states
+curl http://localhost:3000/api/state
+
+# Get specific device state
+curl http://localhost:3000/api/state/light.living_room
+

Response:

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

Control Device

Execute device commands.

POST /api/device/control
+

Request body:

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

Available actions: - turn_on - turn_off - toggle - set_value

Example with curl:

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

Natural Language Commands

Execute Command

Process natural language commands.

POST /api/command
+

Request body:

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

Example usage:

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

Response:

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

Scene Management

Create Scene

Define a new scene with multiple actions.

POST /api/scene
+

Request body:

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

Activate Scene

Trigger a predefined scene.

POST /api/scene/{scene_name}/activate
+

Example:

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

Groups

Create Device Group

Create a group of devices for collective control.

POST /api/group
+

Request body:

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

Control Group

Control multiple devices in a group.

POST /api/group/{group_name}/control
+

Request body:

{
+  "action": "turn_off"
+}
+

System Operations

Health Check

Check server status and connectivity.

GET /health
+

Response:

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

Configuration

Get current server configuration.

GET /api/config
+

Response:

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

Error Handling

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

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

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

TypeScript Interfaces

interface DeviceState {
+  entity_id: string;
+  state: string;
+  attributes: Record<string, any>;
+  last_changed: string;
+}
+
+interface DeviceCommand {
+  entity_id: string;
+  action: 'turn_on' | 'turn_off' | 'toggle' | 'set_value';
+  parameters?: Record<string, any>;
+}
+
+interface Scene {
+  name: string;
+  description?: string;
+  actions: DeviceCommand[];
+}
+
+interface Group {
+  name: string;
+  entities: string[];
+}
+
\ No newline at end of file diff --git a/api/core/index.html b/api/core/index.html deleted file mode 100644 index f1d9a8d..0000000 --- a/api/core/index.html +++ /dev/null @@ -1,2443 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - Core Functions - Advanced Home Assistant MCP - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - Skip to content - - -
-
- -
- - - - - - -
- - -
- -
- - - - - - -
-
- - - -
-
-
- - - - - -
-
-
- - - - - - - -
-
- - - - - - - - -

Core Functions API 🔧

-

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

-

Device Control

-

Get Device State

-

Retrieve the current state of devices.

-
GET /api/state
-GET /api/state/{entity_id}
-
-

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

-
# Get all states
-curl http://localhost:3000/api/state
-
-# Get specific device state
-curl http://localhost:3000/api/state/light.living_room
-
-

Response: -

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

-

Control Device

-

Execute device commands.

-
POST /api/device/control
-
-

Request body: -

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

-

Available actions: -- turn_on -- turn_off -- toggle -- set_value

-

Example with curl: -

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

-

Natural Language Commands

-

Execute Command

-

Process natural language commands.

-
POST /api/command
-
-

Request body: -

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

-

Example usage: -

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

-

Response: -

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

-

Scene Management

-

Create Scene

-

Define a new scene with multiple actions.

-
POST /api/scene
-
-

Request body: -

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

-

Activate Scene

-

Trigger a predefined scene.

-
POST /api/scene/{scene_name}/activate
-
-

Example: -

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

-

Groups

-

Create Device Group

-

Create a group of devices for collective control.

-
POST /api/group
-
-

Request body: -

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

-

Control Group

-

Control multiple devices in a group.

-
POST /api/group/{group_name}/control
-
-

Request body: -

{
-  "action": "turn_off"
-}
-

-

System Operations

-

Health Check

-

Check server status and connectivity.

-
GET /health
-
-

Response: -

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

-

Configuration

-

Get current server configuration.

-
GET /api/config
-
-

Response: -

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

-

Error Handling

-

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

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

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

-

TypeScript Interfaces

-
interface DeviceState {
-  entity_id: string;
-  state: string;
-  attributes: Record<string, any>;
-  last_changed: string;
-}
-
-interface DeviceCommand {
-  entity_id: string;
-  action: 'turn_on' | 'turn_off' | 'toggle' | 'set_value';
-  parameters?: Record<string, any>;
-}
-
-interface Scene {
-  name: string;
-  description?: string;
-  actions: DeviceCommand[];
-}
-
-interface Group {
-  name: string;
-  entities: string[];
-}
-
- - - - - - - - - - - - - - - - - - - - - - - - -
-
- - - -
- - - -
- - - -
-
-
-
- - - - - - - - - - - - \ No newline at end of file diff --git a/api/index.html b/api/index.html index 70a3894..72516be 100644 --- a/api/index.html +++ b/api/index.html @@ -1,2317 +1,84 @@ - - - - - - - - - - - - - - - - - - - - - - - - - API Overview - Advanced Home Assistant MCP - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - Skip to content - - -
-
- -
- - - - - - -
- - -
- -
- - - - - - -
-
- - - -
-
-
- - - - - -
-
-
- - - - - - - -
-
- - - - - - - - -

API Documentation 📚

-

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

-

API Overview

-

The MCP Server provides several API categories:

-
    -
  1. Core API - Basic device control and state management
  2. -
  3. SSE API - Real-time event subscriptions
  4. -
  5. Scene API - Scene management and automation
  6. -
  7. Voice API - Natural language command processing
  8. -
-

Authentication

-

All API endpoints require authentication using JWT tokens:

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

To obtain a token:

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

Core Endpoints

-

Device State

-
GET /api/state
-
-

Retrieve the current state of all devices:

-
curl http://localhost:3000/api/state
-
-

Response: -

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

-

Command Execution

-
POST /api/command
-
-

Execute a natural language command:

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

Response: -

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

-

Real-Time Events

-

Event Subscription

-
GET /subscribe_events
-
-

Subscribe to device state changes:

-
const eventSource = new EventSource('http://localhost:3000/subscribe_events?token=YOUR_TOKEN');
-
-eventSource.onmessage = (event) => {
-    const data = JSON.parse(event.data);
-    console.log('State changed:', data);
-};
-
-

Filtered Subscriptions

-

Subscribe to specific device types:

-
GET /subscribe_events?domain=light
-GET /subscribe_events?entity_id=light.living_room
-
-

Scene Management

-

Create Scene

-
POST /api/scene
-
-

Create a new scene:

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

Activate Scene

-
POST /api/scene/activate
-
-

Activate an existing scene:

-
curl -X POST http://localhost:3000/api/scene/activate \
-  -H "Content-Type: application/json" \
-  -d '{"name": "Movie Night"}'
-
-

Error Handling

-

The API uses standard HTTP status codes:

-
    -
  • 200 - Success
  • -
  • 400 - Bad Request
  • -
  • 401 - Unauthorized
  • -
  • 404 - Not Found
  • -
  • 500 - Server Error
  • -
-

Error responses include detailed messages:

-
{
-  "error": true,
-  "message": "Device not found",
-  "code": "DEVICE_NOT_FOUND",
-  "details": {
-    "device_id": "light.nonexistent"
-  }
-}
-
-

Rate Limiting

-

API requests are rate-limited to prevent abuse:

-
X-RateLimit-Limit: 100
-X-RateLimit-Remaining: 99
-X-RateLimit-Reset: 1640995200
-
-

When exceeded, returns 429 Too Many Requests:

-
{
-  "error": true,
-  "message": "Rate limit exceeded",
-  "reset": 1640995200
-}
-
-

WebSocket API

-

For bi-directional communication:

-
const ws = new WebSocket('ws://localhost:3000/ws');
-
-ws.onmessage = (event) => {
-    const data = JSON.parse(event.data);
-    console.log('Received:', data);
-};
-
-ws.send(JSON.stringify({
-    type: 'command',
-    payload: {
-        command: 'Turn on lights'
-    }
-}));
-
-

API Versioning

-

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

-
/api/v1/state
-/api/v1/command
-
-

Further Reading

- - - - - - - - - - - - - - - - - - - - - - - -
-
- - - -
- - - -
- - - -
-
-
-
- - - - - - - - - - - - \ No newline at end of file + API Overview - MCP Server for Home Assistant
Skip to content

API Documentation 📚

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

API Overview

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

Authentication

All API endpoints require authentication using JWT tokens:

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

To obtain a token:

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

Core Endpoints

Device State

GET /api/state
+

Retrieve the current state of all devices:

curl http://localhost:3000/api/state
+

Response:

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

Command Execution

POST /api/command
+

Execute a natural language command:

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

Response:

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

Real-Time Events

Event Subscription

GET /subscribe_events
+

Subscribe to device state changes:

const eventSource = new EventSource('http://localhost:3000/subscribe_events?token=YOUR_TOKEN');
+
+eventSource.onmessage = (event) => {
+    const data = JSON.parse(event.data);
+    console.log('State changed:', data);
+};
+

Filtered Subscriptions

Subscribe to specific device types:

GET /subscribe_events?domain=light
+GET /subscribe_events?entity_id=light.living_room
+

Scene Management

Create Scene

POST /api/scene
+

Create a new scene:

curl -X POST http://localhost:3000/api/scene \
+  -H "Content-Type: application/json" \
+  -d '{
+    "name": "Movie Night",
+    "actions": [
+      {"device": "light.living_room", "action": "dim", "value": 20},
+      {"device": "media_player.tv", "action": "on"}
+    ]
+  }'
+

Activate Scene

POST /api/scene/activate
+

Activate an existing scene:

curl -X POST http://localhost:3000/api/scene/activate \
+  -H "Content-Type: application/json" \
+  -d '{"name": "Movie Night"}'
+

Error Handling

The API uses standard HTTP status codes:

  • 200 - Success
  • 400 - Bad Request
  • 401 - Unauthorized
  • 404 - Not Found
  • 500 - Server Error

Error responses include detailed messages:

{
+  "error": true,
+  "message": "Device not found",
+  "code": "DEVICE_NOT_FOUND",
+  "details": {
+    "device_id": "light.nonexistent"
+  }
+}
+

Rate Limiting

API requests are rate-limited to prevent abuse:

X-RateLimit-Limit: 100
+X-RateLimit-Remaining: 99
+X-RateLimit-Reset: 1640995200
+

When exceeded, returns 429 Too Many Requests:

{
+  "error": true,
+  "message": "Rate limit exceeded",
+  "reset": 1640995200
+}
+

WebSocket API

For bi-directional communication:

const ws = new WebSocket('ws://localhost:3000/ws');
+
+ws.onmessage = (event) => {
+    const data = JSON.parse(event.data);
+    console.log('Received:', data);
+};
+
+ws.send(JSON.stringify({
+    type: 'command',
+    payload: {
+        command: 'Turn on lights'
+    }
+}));
+

API Versioning

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

/api/v1/state
+/api/v1/command
+

Further Reading

API Reference

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

\ No newline at end of file diff --git a/api/sse.html b/api/sse.html new file mode 100644 index 0000000..57f89b6 --- /dev/null +++ b/api/sse.html @@ -0,0 +1,146 @@ + SSE API - MCP Server for Home Assistant
Skip to content

Server-Sent Events (SSE) API 📡

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.

Overview

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:

  • Real-time device state updates
  • Event notifications
  • System status changes
  • Command execution results

Basic Usage

Establishing a Connection

Create an EventSource connection to receive updates:

const eventSource = new EventSource('http://localhost:3000/subscribe_events?token=YOUR_JWT_TOKEN');
+
+eventSource.onmessage = (event) => {
+    const data = JSON.parse(event.data);
+    console.log('Received update:', data);
+};
+

Connection States

Handle different connection states:

eventSource.onopen = () => {
+    console.log('Connection established');
+};
+
+eventSource.onerror = (error) => {
+    console.error('Connection error:', error);
+    // Implement reconnection logic if needed
+};
+

Event Types

Device State Events

Subscribe to all device state changes:

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

Example state event:

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

Filtered Subscriptions

By Domain

Subscribe to specific device types:

// Subscribe to only light events
+const lightEvents = new EventSource('http://localhost:3000/subscribe_events?domain=light');
+
+// Subscribe to multiple domains
+const multiEvents = new EventSource('http://localhost:3000/subscribe_events?domain=light,switch,sensor');
+

By Entity ID

Subscribe to specific devices:

// Single entity
+const livingRoomLight = new EventSource(
+    'http://localhost:3000/subscribe_events?entity_id=light.living_room'
+);
+
+// Multiple entities
+const kitchenDevices = new EventSource(
+    'http://localhost:3000/subscribe_events?entity_id=light.kitchen,switch.coffee_maker'
+);
+

Advanced Usage

Connection Management

Implement robust connection handling:

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

Event Filtering

Filter events on the client side:

class EventFilter {
+    constructor(conditions) {
+        this.conditions = conditions;
+    }
+
+    matches(event) {
+        return Object.entries(this.conditions).every(([key, value]) => {
+            if (Array.isArray(value)) {
+                return value.includes(event[key]);
+            }
+            return event[key] === value;
+        });
+    }
+}
+
+// Usage
+const filter = new EventFilter({
+    domain: ['light', 'switch'],
+    state: 'on'
+});
+
+eventSource.onmessage = (event) => {
+    const data = JSON.parse(event.data);
+    if (filter.matches(data)) {
+        console.log('Matched event:', data);
+    }
+};
+

Best Practices

  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

Common Issues

Connection Drops

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

eventSource.addEventListener('error', (error) => {
+    if (eventSource.readyState === EventSource.CLOSED) {
+        // Connection closed, implement custom retry logic
+    }
+});
+

Memory Leaks

Always clean up EventSource connections:

// In a React component
+useEffect(() => {
+    const eventSource = new EventSource('http://localhost:3000/subscribe_events');
+
+    return () => {
+        eventSource.close(); // Cleanup on unmount
+    };
+}, []);
+
\ No newline at end of file diff --git a/api/sse/index.html b/api/sse/index.html deleted file mode 100644 index c61979a..0000000 --- a/api/sse/index.html +++ /dev/null @@ -1,2429 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - SSE API - Advanced Home Assistant MCP - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - Skip to content - - -
-
- -
- - - - - - -
- - -
- -
- - - - - - -
-
- - - -
-
-
- - - - - -
-
-
- - - - - - - -
-
- - - - - - - - -

Server-Sent Events (SSE) API 📡

-

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.

-

Overview

-

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:

-
    -
  • Real-time device state updates
  • -
  • Event notifications
  • -
  • System status changes
  • -
  • Command execution results
  • -
-

Basic Usage

-

Establishing a Connection

-

Create an EventSource connection to receive updates:

-
const eventSource = new EventSource('http://localhost:3000/subscribe_events?token=YOUR_JWT_TOKEN');
-
-eventSource.onmessage = (event) => {
-    const data = JSON.parse(event.data);
-    console.log('Received update:', data);
-};
-
-

Connection States

-

Handle different connection states:

-
eventSource.onopen = () => {
-    console.log('Connection established');
-};
-
-eventSource.onerror = (error) => {
-    console.error('Connection error:', error);
-    // Implement reconnection logic if needed
-};
-
-

Event Types

-

Device State Events

-

Subscribe to all device state changes:

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

Example state event: -

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

-

Filtered Subscriptions

-

By Domain

-

Subscribe to specific device types:

-
// Subscribe to only light events
-const lightEvents = new EventSource('http://localhost:3000/subscribe_events?domain=light');
-
-// Subscribe to multiple domains
-const multiEvents = new EventSource('http://localhost:3000/subscribe_events?domain=light,switch,sensor');
-
-

By Entity ID

-

Subscribe to specific devices:

-
// Single entity
-const livingRoomLight = new EventSource(
-    'http://localhost:3000/subscribe_events?entity_id=light.living_room'
-);
-
-// Multiple entities
-const kitchenDevices = new EventSource(
-    'http://localhost:3000/subscribe_events?entity_id=light.kitchen,switch.coffee_maker'
-);
-
-

Advanced Usage

-

Connection Management

-

Implement robust connection handling:

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

Event Filtering

-

Filter events on the client side:

-
class EventFilter {
-    constructor(conditions) {
-        this.conditions = conditions;
-    }
-
-    matches(event) {
-        return Object.entries(this.conditions).every(([key, value]) => {
-            if (Array.isArray(value)) {
-                return value.includes(event[key]);
-            }
-            return event[key] === value;
-        });
-    }
-}
-
-// Usage
-const filter = new EventFilter({
-    domain: ['light', 'switch'],
-    state: 'on'
-});
-
-eventSource.onmessage = (event) => {
-    const data = JSON.parse(event.data);
-    if (filter.matches(data)) {
-        console.log('Matched event:', data);
-    }
-};
-
-

Best Practices

-
    -
  1. Authentication
  2. -
  3. Always include authentication tokens
  4. -
  5. Implement token refresh mechanisms
  6. -
  7. -

    Handle authentication errors gracefully

    -
  8. -
  9. -

    Error Handling

    -
  10. -
  11. Implement progressive retry logic
  12. -
  13. Log connection issues
  14. -
  15. -

    Notify users of connection status

    -
  16. -
  17. -

    Resource Management

    -
  18. -
  19. Close EventSource connections when not needed
  20. -
  21. Limit the number of concurrent connections
  22. -
  23. -

    Use filtered subscriptions when possible

    -
  24. -
  25. -

    Performance

    -
  26. -
  27. Process events efficiently
  28. -
  29. Batch UI updates
  30. -
  31. Consider debouncing frequent updates
  32. -
-

Common Issues

-

Connection Drops

-

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

-
eventSource.addEventListener('error', (error) => {
-    if (eventSource.readyState === EventSource.CLOSED) {
-        // Connection closed, implement custom retry logic
-    }
-});
-
-

Memory Leaks

-

Always clean up EventSource connections:

-
// In a React component
-useEffect(() => {
-    const eventSource = new EventSource('http://localhost:3000/subscribe_events');
-
-    return () => {
-        eventSource.close(); // Cleanup on unmount
-    };
-}, []);
-
- - - - - - - - - - - - - - - - - - - - - - - - -
-
- - - -
- - - -
- - - -
-
-
-
- - - - - - - - - - - - \ No newline at end of file diff --git a/architecture.html b/architecture.html new file mode 100644 index 0000000..3005b49 --- /dev/null +++ b/architecture.html @@ -0,0 +1,26 @@ + Architecture - MCP Server for Home Assistant
Skip to content

Architecture Overview 🏗️

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.

System Architecture

graph TD
+    subgraph "Client Layer"
+        WC[Web Clients]
+        MC[Mobile Clients]
+    end
+
+    subgraph "MCP Server"
+        API[API Gateway]
+        SSE[SSE Manager]
+        WS[WebSocket Server]
+        CM[Command Manager]
+    end
+
+    subgraph "Home Assistant"
+        HA[Home Assistant Core]
+        Dev[Devices & Services]
+    end
+
+    WC --> |HTTP/WS| API
+    MC --> |HTTP/WS| API
+
+    API --> |Events| SSE
+    API --> |Real-time| WS
+
+    API --> HA
+    HA --> API

Core Components

API Gateway

  • Handles incoming HTTP and WebSocket requests
  • Provides endpoints for device management
  • Implements basic authentication and request validation

SSE Manager

  • Manages Server-Sent Events for real-time updates
  • Broadcasts device state changes to connected clients

WebSocket Server

  • Provides real-time, bidirectional communication
  • Supports basic device control and state monitoring

Command Manager

  • Processes device control requests
  • Translates API commands to Home Assistant compatible formats

Communication Flow

  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

Key Design Principles

  • Simplicity: Lightweight, focused design
  • Flexibility: Easily extendable architecture
  • Performance: Efficient request handling
  • Security: Basic authentication and validation

Limitations

  • Basic device control capabilities
  • Limited advanced automation features
  • Minimal third-party integrations

Future Improvements

  • Enhanced error handling
  • More robust authentication
  • Expanded device type support

Architecture is subject to change as the project evolves.

\ No newline at end of file diff --git a/architecture/index.html b/architecture/index.html deleted file mode 100644 index 47dc6e2..0000000 --- a/architecture/index.html +++ /dev/null @@ -1,2108 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - Architecture - Advanced Home Assistant MCP - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - Skip to content - - -
-
- -
- - - - - - -
- - -
- -
- - - - - - -
-
- - - -
-
-
- - - - - -
-
-
- - - - - - - -
-
- - - - - - - - -

Architecture Overview 🏗️

-

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.

-

System Architecture

-
graph TD
-    subgraph "Client Layer"
-        WC[Web Clients]
-        MC[Mobile Clients]
-    end
-
-    subgraph "MCP Server"
-        API[API Gateway]
-        SSE[SSE Manager]
-        WS[WebSocket Server]
-        CM[Command Manager]
-    end
-
-    subgraph "Home Assistant"
-        HA[Home Assistant Core]
-        Dev[Devices & Services]
-    end
-
-    WC --> |HTTP/WS| API
-    MC --> |HTTP/WS| API
-
-    API --> |Events| SSE
-    API --> |Real-time| WS
-
-    API --> HA
-    HA --> API
-
-

Core Components

-

API Gateway

-
    -
  • Handles incoming HTTP and WebSocket requests
  • -
  • Provides endpoints for device management
  • -
  • Implements basic authentication and request validation
  • -
-

SSE Manager

-
    -
  • Manages Server-Sent Events for real-time updates
  • -
  • Broadcasts device state changes to connected clients
  • -
-

WebSocket Server

-
    -
  • Provides real-time, bidirectional communication
  • -
  • Supports basic device control and state monitoring
  • -
-

Command Manager

-
    -
  • Processes device control requests
  • -
  • Translates API commands to Home Assistant compatible formats
  • -
-

Communication Flow

-
    -
  1. Client sends a request to the MCP Server API
  2. -
  3. API Gateway authenticates the request
  4. -
  5. Command Manager processes the request
  6. -
  7. Request is forwarded to Home Assistant
  8. -
  9. Response is sent back to the client via API or WebSocket
  10. -
-

Key Design Principles

-
    -
  • Simplicity: Lightweight, focused design
  • -
  • Flexibility: Easily extendable architecture
  • -
  • Performance: Efficient request handling
  • -
  • Security: Basic authentication and validation
  • -
-

Limitations

-
    -
  • Basic device control capabilities
  • -
  • Limited advanced automation features
  • -
  • Minimal third-party integrations
  • -
-

Future Improvements

-
    -
  • Enhanced error handling
  • -
  • More robust authentication
  • -
  • Expanded device type support
  • -
-

Architecture is subject to change as the project evolves.

- - - - - - - - - - - - - - - - - - - - - - -
-
- - - -
- - - -
- - - -
-
-
-
- - - - - - - - - - - - \ No newline at end of file diff --git a/assets/_mkdocstrings.css b/assets/_mkdocstrings.css index b500381..e69de29 100644 --- a/assets/_mkdocstrings.css +++ b/assets/_mkdocstrings.css @@ -1,143 +0,0 @@ - -/* Avoid breaking parameter names, etc. in table cells. */ -.doc-contents td code { - word-break: normal !important; -} - -/* No line break before first paragraph of descriptions. */ -.doc-md-description, -.doc-md-description>p:first-child { - display: inline; -} - -/* Max width for docstring sections tables. */ -.doc .md-typeset__table, -.doc .md-typeset__table table { - display: table !important; - width: 100%; -} - -.doc .md-typeset__table tr { - display: table-row; -} - -/* Defaults in Spacy table style. */ -.doc-param-default { - float: right; -} - -/* Parameter headings must be inline, not blocks. */ -.doc-heading-parameter { - display: inline; -} - -/* Prefer space on the right, not the left of parameter permalinks. */ -.doc-heading-parameter .headerlink { - margin-left: 0 !important; - margin-right: 0.2rem; -} - -/* Backward-compatibility: docstring section titles in bold. */ -.doc-section-title { - font-weight: bold; -} - -/* Symbols in Navigation and ToC. */ -:root, :host, -[data-md-color-scheme="default"] { - --doc-symbol-parameter-fg-color: #df50af; - --doc-symbol-attribute-fg-color: #953800; - --doc-symbol-function-fg-color: #8250df; - --doc-symbol-method-fg-color: #8250df; - --doc-symbol-class-fg-color: #0550ae; - --doc-symbol-module-fg-color: #5cad0f; - - --doc-symbol-parameter-bg-color: #df50af1a; - --doc-symbol-attribute-bg-color: #9538001a; - --doc-symbol-function-bg-color: #8250df1a; - --doc-symbol-method-bg-color: #8250df1a; - --doc-symbol-class-bg-color: #0550ae1a; - --doc-symbol-module-bg-color: #5cad0f1a; -} - -[data-md-color-scheme="slate"] { - --doc-symbol-parameter-fg-color: #ffa8cc; - --doc-symbol-attribute-fg-color: #ffa657; - --doc-symbol-function-fg-color: #d2a8ff; - --doc-symbol-method-fg-color: #d2a8ff; - --doc-symbol-class-fg-color: #79c0ff; - --doc-symbol-module-fg-color: #baff79; - - --doc-symbol-parameter-bg-color: #ffa8cc1a; - --doc-symbol-attribute-bg-color: #ffa6571a; - --doc-symbol-function-bg-color: #d2a8ff1a; - --doc-symbol-method-bg-color: #d2a8ff1a; - --doc-symbol-class-bg-color: #79c0ff1a; - --doc-symbol-module-bg-color: #baff791a; -} - -code.doc-symbol { - border-radius: .1rem; - font-size: .85em; - padding: 0 .3em; - font-weight: bold; -} - -code.doc-symbol-parameter { - color: var(--doc-symbol-parameter-fg-color); - background-color: var(--doc-symbol-parameter-bg-color); -} - -code.doc-symbol-parameter::after { - content: "param"; -} - -code.doc-symbol-attribute { - color: var(--doc-symbol-attribute-fg-color); - background-color: var(--doc-symbol-attribute-bg-color); -} - -code.doc-symbol-attribute::after { - content: "attr"; -} - -code.doc-symbol-function { - color: var(--doc-symbol-function-fg-color); - background-color: var(--doc-symbol-function-bg-color); -} - -code.doc-symbol-function::after { - content: "func"; -} - -code.doc-symbol-method { - color: var(--doc-symbol-method-fg-color); - background-color: var(--doc-symbol-method-bg-color); -} - -code.doc-symbol-method::after { - content: "meth"; -} - -code.doc-symbol-class { - color: var(--doc-symbol-class-fg-color); - background-color: var(--doc-symbol-class-bg-color); -} - -code.doc-symbol-class::after { - content: "class"; -} - -code.doc-symbol-module { - color: var(--doc-symbol-module-fg-color); - background-color: var(--doc-symbol-module-bg-color); -} - -code.doc-symbol-module::after { - content: "mod"; -} - -.doc-signature .autorefs { - color: inherit; - border-bottom: 1px dotted currentcolor; -} diff --git a/config/index.html b/config/index.html new file mode 100644 index 0000000..dc8fc23 --- /dev/null +++ b/config/index.html @@ -0,0 +1 @@ + Overview - MCP Server for Home Assistant
Skip to content

Configuration

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

Overview

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.

Configuration Files

The main configuration files are:

  1. .env - Environment variables
  2. config.yaml - Main configuration file
  3. devices.yaml - Device-specific configurations

Environment Variables

Key environment variables that can be set:

  • MCP_HOST - Host address (default: 0.0.0.0)
  • MCP_PORT - Port number (default: 8123)
  • MCP_LOG_LEVEL - Logging level (default: INFO)
  • MCP_CONFIG_DIR - Configuration directory path

Next Steps

\ No newline at end of file diff --git a/configuration.html b/configuration.html new file mode 100644 index 0000000..5b96fd8 --- /dev/null +++ b/configuration.html @@ -0,0 +1,32 @@ + 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 a hierarchical configuration structure:

server:
+  host: 0.0.0.0
+  port: 8123
+  log_level: INFO
+
+security:
+  jwt_secret: YOUR_SECRET_KEY
+  allowed_origins:
+    - http://localhost:3000
+    - https://your-domain.com
+
+devices:
+  scan_interval: 30
+  default_timeout: 10
+

Server Settings

Basic Server Configuration

  • host: Server binding address (default: 0.0.0.0)
  • port: Server port number (default: 8123)
  • log_level: Logging level (INFO, DEBUG, WARNING, ERROR)

Security Settings

  • jwt_secret: Secret key for JWT token generation
  • allowed_origins: CORS allowed origins list
  • ssl_cert: Path to SSL certificate (optional)
  • ssl_key: Path to SSL private key (optional)

Device Management

  • scan_interval: Device state scan interval in seconds
  • default_timeout: Default device command timeout
  • retry_attempts: Number of retry attempts for failed commands

Environment Variables

Environment variables override configuration file settings:

MCP_HOST=0.0.0.0
+MCP_PORT=8123
+MCP_LOG_LEVEL=INFO
+MCP_JWT_SECRET=your-secret-key
+

Advanced Configuration

Rate Limiting

rate_limit:
+  enabled: true
+  requests_per_minute: 100
+  burst: 20
+

Caching

cache:
+  enabled: true
+  ttl: 300  # seconds
+  max_size: 1000  # entries
+

Logging

logging:
+  file: /var/log/mcp-server.log
+  max_size: 10MB
+  backup_count: 5
+  format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
+

Best Practices

  1. Always use environment variables for sensitive information
  2. Keep configuration files in a secure location
  3. Regularly backup your configuration
  4. Use SSL in production environments
  5. Monitor log files for issues

Validation

The server validates configuration on startup: - Required fields are checked - Value types are verified - Ranges are validated - Security settings are assessed

Troubleshooting

Common configuration issues: 1. Permission denied accessing files 2. Invalid YAML syntax 3. Missing required fields 4. Type mismatches in values

See the Troubleshooting Guide for solutions.

\ No newline at end of file diff --git a/contributing.html b/contributing.html new file mode 100644 index 0000000..f78b1ab --- /dev/null +++ b/contributing.html @@ -0,0 +1,25 @@ + Contributing - MCP Server for Home Assistant
Skip to content

Contributing Guide 🤝

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

Getting Started

Prerequisites

  • Bun >= 1.0.26
  • Home Assistant instance
  • Basic understanding of TypeScript

Development Setup

  1. Fork the repository
  2. Clone your fork:

    git clone https://github.com/YOUR_USERNAME/homeassistant-mcp.git
    +cd homeassistant-mcp
    +

  3. Install dependencies:

    bun install
    +

  4. Configure environment:

    cp .env.example .env
    +# Edit .env with your Home Assistant details
    +

Development Workflow

Branch Naming

  • feature/ - New features
  • fix/ - Bug fixes
  • docs/ - Documentation updates

Example:

git checkout -b feature/device-control-improvements
+

Commit Messages

Follow simple, clear commit messages:

type: brief description
+
+[optional detailed explanation]
+

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

Code Style

  • Use TypeScript
  • Follow existing code structure
  • Keep changes focused and minimal

Testing

Run tests before submitting:

# Run all tests
+bun test
+
+# Run specific test
+bun test test/api/control.test.ts
+

Pull Request Process

  1. Ensure tests pass
  2. Update documentation if needed
  3. Provide clear description of changes

PR Template

## Description
+Brief explanation of the changes
+
+## Type of Change
+- [ ] Bug fix
+- [ ] New feature
+- [ ] Documentation update
+
+## Testing
+Describe how you tested these changes
+

Reporting Issues

  • Use GitHub Issues
  • Provide clear, reproducible steps
  • Include environment details

Code of Conduct

  • Be respectful
  • Focus on constructive feedback
  • Help maintain a positive environment

Resources

Thank you for contributing!

\ No newline at end of file diff --git a/contributing/index.html b/contributing/index.html deleted file mode 100644 index df9365f..0000000 --- a/contributing/index.html +++ /dev/null @@ -1,2207 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - Contributing - Advanced Home Assistant MCP - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - Skip to content - - -
-
- -
- - - - - - -
- - -
- -
- - - - - - -
-
- - - -
-
-
- - - - - -
-
-
- - - -
-
-
- - - -
-
-
- - - -
-
- - - - - - - - -

Contributing Guide 🤝

-

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

-

Getting Started

-

Prerequisites

-
    -
  • Bun >= 1.0.26
  • -
  • Home Assistant instance
  • -
  • Basic understanding of TypeScript
  • -
-

Development Setup

-
    -
  1. Fork the repository
  2. -
  3. -

    Clone your fork: -

    git clone https://github.com/YOUR_USERNAME/homeassistant-mcp.git
    -cd homeassistant-mcp
    -

    -
  4. -
  5. -

    Install dependencies: -

    bun install
    -

    -
  6. -
  7. -

    Configure environment: -

    cp .env.example .env
    -# Edit .env with your Home Assistant details
    -

    -
  8. -
-

Development Workflow

-

Branch Naming

-
    -
  • feature/ - New features
  • -
  • fix/ - Bug fixes
  • -
  • docs/ - Documentation updates
  • -
-

Example: -

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

-

Commit Messages

-

Follow simple, clear commit messages:

-
type: brief description
-
-[optional detailed explanation]
-
-

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

-

Code Style

-
    -
  • Use TypeScript
  • -
  • Follow existing code structure
  • -
  • Keep changes focused and minimal
  • -
-

Testing

-

Run tests before submitting:

-
# Run all tests
-bun test
-
-# Run specific test
-bun test test/api/control.test.ts
-
-

Pull Request Process

-
    -
  1. Ensure tests pass
  2. -
  3. Update documentation if needed
  4. -
  5. Provide clear description of changes
  6. -
-

PR Template

-
## Description
-Brief explanation of the changes
-
-## Type of Change
-- [ ] Bug fix
-- [ ] New feature
-- [ ] Documentation update
-
-## Testing
-Describe how you tested these changes
-
-

Reporting Issues

-
    -
  • Use GitHub Issues
  • -
  • Provide clear, reproducible steps
  • -
  • Include environment details
  • -
-

Code of Conduct

-
    -
  • Be respectful
  • -
  • Focus on constructive feedback
  • -
  • Help maintain a positive environment
  • -
-

Resources

- -

Thank you for contributing!

- - - - - - - - - - - - - - - - - - - - - - -
-
- - - -
- - - -
- - - -
-
-
-
- - - - - - - - - - - - \ No newline at end of file diff --git a/deployment.html b/deployment.html new file mode 100644 index 0000000..9a4a43e --- /dev/null +++ b/deployment.html @@ -0,0 +1,33 @@ + Deployment - MCP Server for Home Assistant
Skip to content

Deployment Guide

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

Automatic Deployment

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

GitHub Actions Workflow

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
+on:
+  push:
+    branches:
+      - main
+      - master
+  workflow_dispatch:  # Allow manual trigger
+

Manual Deployment

If needed, you can deploy manually using:

# Create a virtual environment
+python -m venv venv
+
+# Activate the virtual environment
+source venv/bin/activate
+
+# Install dependencies
+pip install -r docs/requirements.txt
+
+# Build the documentation
+mkdocs build
+
+# Deploy to GitHub Pages
+mkdocs gh-deploy --force
+

Best Practices

1. Documentation Updates

  • Test locally before pushing: mkdocs serve
  • Verify all links work
  • Ensure images are optimized
  • Check mobile responsiveness

2. Version Control

  • Keep documentation in sync with code versions
  • Use meaningful commit messages
  • Tag important documentation versions

3. Content Guidelines

  • Use consistent formatting
  • Keep navigation structure logical
  • Include examples where appropriate
  • Maintain up-to-date screenshots

4. Maintenance

  • Regularly review and update content
  • Check for broken links
  • Update dependencies
  • Monitor GitHub Actions logs

Troubleshooting

Common Issues

  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

Configuration Files

requirements.txt

Create a requirements file for documentation dependencies:

mkdocs-material
+mkdocs-minify-plugin
+mkdocs-git-revision-date-plugin
+mkdocs-mkdocstrings
+mkdocs-social-plugin
+mkdocs-redirects
+

Monitoring

Workflow Features

Caching

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

Deployment Checks

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

Manual Triggers

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

Cleanup

To clean up duplicate workflow files, run:

# Make the script executable
+chmod +x scripts/cleanup-workflows.sh
+
+# Run the cleanup script
+./scripts/cleanup-workflows.sh
+
\ No newline at end of file diff --git a/development/best-practices.html b/development/best-practices.html new file mode 100644 index 0000000..a3b7fb8 --- /dev/null +++ b/development/best-practices.html @@ -0,0 +1,140 @@ + Best Practices - MCP Server for Home Assistant
Skip to content

Development Best Practices

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

Code Style

TypeScript

  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
/** 
+ * Represents a device in the system.
+ * @interface
+ */
+interface Device {
+    /** Unique device identifier */
+    id: string;
+
+    /** Human-readable device name */
+    name: string;
+
+    /** Device state */
+    state: DeviceState;
+}
+

Naming Conventions

  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 {
+    private readonly DEFAULT_TIMEOUT = 5000;
+
+    async getDeviceState(deviceId: string): Promise<DeviceState> {
+        // Implementation
+    }
+}
+

Architecture

SOLID Principles

  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

Example

// Bad
+class DeviceManager {
+    async getState() { /* ... */ }
+    async setState() { /* ... */ }
+    async sendNotification() { /* ... */ }  // Wrong responsibility
+}
+
+// Good
+class DeviceManager {
+    constructor(
+        private notifier: NotificationService
+    ) {}
+
+    async getState() { /* ... */ }
+    async setState() { /* ... */ }
+}
+
+class NotificationService {
+    async send() { /* ... */ }
+}
+

Error Handling

Best Practices

  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 {
+    constructor(
+        message: string,
+        public code: string,
+        public context: Record<string, any>
+    ) {
+        super(message);
+        this.name = 'DeviceError';
+    }
+}
+
+try {
+    await device.connect();
+} catch (error) {
+    throw new DeviceError(
+        'Failed to connect to device',
+        'DEVICE_CONNECTION_ERROR',
+        { deviceId: device.id, attempt: 1 }
+    );
+}
+

Testing

Guidelines

  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', () => {
+    let manager: DeviceManager;
+    let mockDevice: jest.Mocked<Device>;
+
+    beforeEach(() => {
+        mockDevice = {
+            id: 'test_device',
+            getState: jest.fn()
+        };
+        manager = new DeviceManager(mockDevice);
+    });
+
+    it('should get device state', async () => {
+        mockDevice.getState.mockResolvedValue('on');
+        const state = await manager.getDeviceState();
+        expect(state).toBe('on');
+    });
+});
+

Performance

Optimization

  1. Use caching
  2. Implement pagination
  3. Optimize database queries
  4. Use connection pooling
  5. Implement rate limiting
  6. Batch operations
class DeviceCache {
+    private cache = new Map<string, CacheEntry>();
+    private readonly TTL = 60000;  // 1 minute
+
+    async getDevice(id: string): Promise<Device> {
+        const cached = this.cache.get(id);
+        if (cached && Date.now() - cached.timestamp < this.TTL) {
+            return cached.device;
+        }
+
+        const device = await this.fetchDevice(id);
+        this.cache.set(id, {
+            device,
+            timestamp: Date.now()
+        });
+
+        return device;
+    }
+}
+

Security

Guidelines

  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 {
+    static validateDeviceId(id: string): boolean {
+        return /^[a-zA-Z0-9_-]{1,64}$/.test(id);
+    }
+
+    static sanitizeOutput(data: any): any {
+        // Implement output sanitization
+        return data;
+    }
+}
+

Documentation

Standards

  1. Use JSDoc comments
  2. Document interfaces
  3. Include examples
  4. Document errors
  5. Keep docs updated
  6. Use markdown
/**
+ * Manages device operations.
+ * @class
+ */
+class DeviceManager {
+    /**
+     * Gets the current state of a device.
+     * @param {string} deviceId - The device identifier.
+     * @returns {Promise<DeviceState>} The current device state.
+     * @throws {DeviceError} If device is not found or unavailable.
+     * @example
+     * const state = await deviceManager.getDeviceState('living_room_light');
+     */
+    async getDeviceState(deviceId: string): Promise<DeviceState> {
+        // Implementation
+    }
+}
+

Logging

Best Practices

  1. Use appropriate levels
  2. Include context
  3. Structure log data
  4. Handle sensitive data
  5. Implement rotation
  6. Use correlation IDs
class Logger {
+    info(message: string, context: Record<string, any>) {
+        console.log(JSON.stringify({
+            level: 'info',
+            message,
+            context,
+            timestamp: new Date().toISOString(),
+            correlationId: context.correlationId
+        }));
+    }
+}
+

Version Control

Guidelines

  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
+git commit -m "feat(device): add support for zigbee devices"
+git commit -m "fix(api): handle timeout errors properly"
+

See Also

\ No newline at end of file diff --git a/development/best-practices/index.html b/development/best-practices/index.html deleted file mode 100644 index d0259a8..0000000 --- a/development/best-practices/index.html +++ /dev/null @@ -1,2619 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - Best Practices - Advanced Home Assistant MCP - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - Skip to content - - -
-
- -
- - - - - - -
- - -
- -
- - - - - - -
-
- - - -
-
-
- - - - - -
-
-
- - - -
-
-
- - - -
-
-
- - - -
-
- - - - - - - - -

Development Best Practices

-

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

-

Code Style

-

TypeScript

-
    -
  1. Use TypeScript for all new code
  2. -
  3. Enable strict mode
  4. -
  5. Use explicit types
  6. -
  7. Avoid any type
  8. -
  9. Use interfaces over types
  10. -
  11. Document with JSDoc comments
  12. -
-
/** 
- * Represents a device in the system.
- * @interface
- */
-interface Device {
-    /** Unique device identifier */
-    id: string;
-
-    /** Human-readable device name */
-    name: string;
-
-    /** Device state */
-    state: DeviceState;
-}
-
-

Naming Conventions

-
    -
  1. Use PascalCase for:
  2. -
  3. Classes
  4. -
  5. Interfaces
  6. -
  7. Types
  8. -
  9. -

    Enums

    -
  10. -
  11. -

    Use camelCase for:

    -
  12. -
  13. Variables
  14. -
  15. Functions
  16. -
  17. Methods
  18. -
  19. -

    Properties

    -
  20. -
  21. -

    Use UPPER_SNAKE_CASE for:

    -
  22. -
  23. Constants
  24. -
  25. Enum values
  26. -
-
class DeviceManager {
-    private readonly DEFAULT_TIMEOUT = 5000;
-
-    async getDeviceState(deviceId: string): Promise<DeviceState> {
-        // Implementation
-    }
-}
-
-

Architecture

-

SOLID Principles

-
    -
  1. Single Responsibility
  2. -
  3. Each class/module has one job
  4. -
  5. -

    Split complex functionality

    -
  6. -
  7. -

    Open/Closed

    -
  8. -
  9. Open for extension
  10. -
  11. -

    Closed for modification

    -
  12. -
  13. -

    Liskov Substitution

    -
  14. -
  15. Subtypes must be substitutable
  16. -
  17. -

    Use interfaces properly

    -
  18. -
  19. -

    Interface Segregation

    -
  20. -
  21. Keep interfaces focused
  22. -
  23. -

    Split large interfaces

    -
  24. -
  25. -

    Dependency Inversion

    -
  26. -
  27. Depend on abstractions
  28. -
  29. Use dependency injection
  30. -
-

Example

-
// Bad
-class DeviceManager {
-    async getState() { /* ... */ }
-    async setState() { /* ... */ }
-    async sendNotification() { /* ... */ }  // Wrong responsibility
-}
-
-// Good
-class DeviceManager {
-    constructor(
-        private notifier: NotificationService
-    ) {}
-
-    async getState() { /* ... */ }
-    async setState() { /* ... */ }
-}
-
-class NotificationService {
-    async send() { /* ... */ }
-}
-
-

Error Handling

-

Best Practices

-
    -
  1. Use custom error classes
  2. -
  3. Include error codes
  4. -
  5. Provide meaningful messages
  6. -
  7. Include error context
  8. -
  9. Handle async errors
  10. -
  11. Log appropriately
  12. -
-
class DeviceError extends Error {
-    constructor(
-        message: string,
-        public code: string,
-        public context: Record<string, any>
-    ) {
-        super(message);
-        this.name = 'DeviceError';
-    }
-}
-
-try {
-    await device.connect();
-} catch (error) {
-    throw new DeviceError(
-        'Failed to connect to device',
-        'DEVICE_CONNECTION_ERROR',
-        { deviceId: device.id, attempt: 1 }
-    );
-}
-
-

Testing

-

Guidelines

-
    -
  1. Write unit tests first
  2. -
  3. Use meaningful descriptions
  4. -
  5. Test edge cases
  6. -
  7. Mock external dependencies
  8. -
  9. Keep tests focused
  10. -
  11. Use test fixtures
  12. -
-
describe('DeviceManager', () => {
-    let manager: DeviceManager;
-    let mockDevice: jest.Mocked<Device>;
-
-    beforeEach(() => {
-        mockDevice = {
-            id: 'test_device',
-            getState: jest.fn()
-        };
-        manager = new DeviceManager(mockDevice);
-    });
-
-    it('should get device state', async () => {
-        mockDevice.getState.mockResolvedValue('on');
-        const state = await manager.getDeviceState();
-        expect(state).toBe('on');
-    });
-});
-
-

Performance

-

Optimization

-
    -
  1. Use caching
  2. -
  3. Implement pagination
  4. -
  5. Optimize database queries
  6. -
  7. Use connection pooling
  8. -
  9. Implement rate limiting
  10. -
  11. Batch operations
  12. -
-
class DeviceCache {
-    private cache = new Map<string, CacheEntry>();
-    private readonly TTL = 60000;  // 1 minute
-
-    async getDevice(id: string): Promise<Device> {
-        const cached = this.cache.get(id);
-        if (cached && Date.now() - cached.timestamp < this.TTL) {
-            return cached.device;
-        }
-
-        const device = await this.fetchDevice(id);
-        this.cache.set(id, {
-            device,
-            timestamp: Date.now()
-        });
-
-        return device;
-    }
-}
-
-

Security

-

Guidelines

-
    -
  1. Validate all input
  2. -
  3. Use parameterized queries
  4. -
  5. Implement rate limiting
  6. -
  7. Use proper authentication
  8. -
  9. Follow OWASP guidelines
  10. -
  11. Sanitize output
  12. -
-
class InputValidator {
-    static validateDeviceId(id: string): boolean {
-        return /^[a-zA-Z0-9_-]{1,64}$/.test(id);
-    }
-
-    static sanitizeOutput(data: any): any {
-        // Implement output sanitization
-        return data;
-    }
-}
-
-

Documentation

-

Standards

-
    -
  1. Use JSDoc comments
  2. -
  3. Document interfaces
  4. -
  5. Include examples
  6. -
  7. Document errors
  8. -
  9. Keep docs updated
  10. -
  11. Use markdown
  12. -
-
/**
- * Manages device operations.
- * @class
- */
-class DeviceManager {
-    /**
-     * Gets the current state of a device.
-     * @param {string} deviceId - The device identifier.
-     * @returns {Promise<DeviceState>} The current device state.
-     * @throws {DeviceError} If device is not found or unavailable.
-     * @example
-     * const state = await deviceManager.getDeviceState('living_room_light');
-     */
-    async getDeviceState(deviceId: string): Promise<DeviceState> {
-        // Implementation
-    }
-}
-
-

Logging

-

Best Practices

-
    -
  1. Use appropriate levels
  2. -
  3. Include context
  4. -
  5. Structure log data
  6. -
  7. Handle sensitive data
  8. -
  9. Implement rotation
  10. -
  11. Use correlation IDs
  12. -
-
class Logger {
-    info(message: string, context: Record<string, any>) {
-        console.log(JSON.stringify({
-            level: 'info',
-            message,
-            context,
-            timestamp: new Date().toISOString(),
-            correlationId: context.correlationId
-        }));
-    }
-}
-
-

Version Control

-

Guidelines

-
    -
  1. Use meaningful commits
  2. -
  3. Follow branching strategy
  4. -
  5. Write good PR descriptions
  6. -
  7. Review code thoroughly
  8. -
  9. Keep changes focused
  10. -
  11. Use conventional commits
  12. -
-
# Good commit messages
-git commit -m "feat(device): add support for zigbee devices"
-git commit -m "fix(api): handle timeout errors properly"
-
-

See Also

- - - - - - - - - - - - - - - - - - - - - - - -
-
- - - -
- - - -
- - - -
-
-
-
- - - - - - - - - - - - \ No newline at end of file diff --git a/development/development/index.html b/development/development/index.html deleted file mode 100644 index 24f0cac..0000000 --- a/development/development/index.html +++ /dev/null @@ -1,2297 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - Overview - Advanced Home Assistant MCP - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - Skip to content - - -
-
- -
- - - - - - -
- - -
- -
- - - - - - -
-
- - - -
-
-
- - - - - -
-
-
- - - - - - - -
-
- - - - - - - - -

Development Guide

-

This guide provides information for developers who want to contribute to or extend the Home Assistant MCP.

-

Project Structure

-
homeassistant-mcp/
-├── src/
-│   ├── __tests__/        # Test files
-│   ├── __mocks__/       # Mock files
-│   ├── api/           # API endpoints and route handlers
-│   ├── config/        # Configuration management
-│   ├── hass/         # Home Assistant integration
-│   ├── interfaces/    # TypeScript interfaces
-│   ├── mcp/          # MCP core functionality
-│   ├── middleware/    # Express middleware
-│   ├── routes/       # Route definitions
-│   ├── security/     # Security utilities
-│   ├── sse/          # Server-Sent Events handling
-│   ├── tools/        # Tool implementations
-│   ├── types/        # TypeScript type definitions
-│   └── utils/        # Utility functions
-├── __tests__/        # Test files
-├── docs/            # Documentation
-├── dist/           # Compiled JavaScript
-└── scripts/        # Build and utility scripts
-
-

Development Setup

-
    -
  1. -

    Install dependencies: -

    npm install
    -

    -
  2. -
  3. -

    Set up development environment: -

    cp .env.example .env.development
    -

    -
  4. -
  5. -

    Start development server: -

    npm run dev
    -

    -
  6. -
-

Code Style

-

We follow these coding standards:

-
    -
  1. TypeScript best practices
  2. -
  3. Use strict type checking
  4. -
  5. Avoid any types
  6. -
  7. -

    Document complex types

    -
  8. -
  9. -

    ESLint rules

    -
  10. -
  11. Run npm run lint to check
  12. -
  13. -

    Run npm run lint:fix to auto-fix

    -
  14. -
  15. -

    Code formatting

    -
  16. -
  17. Use Prettier
  18. -
  19. Run npm run format to format code
  20. -
-

Testing

-
    -
  1. -

    Unit tests: -

    npm run test
    -

    -
  2. -
  3. -

    Integration tests: -

    npm run test:integration
    -

    -
  4. -
  5. -

    Coverage report: -

    npm run test:coverage
    -

    -
  6. -
-

Creating New Tools

-
    -
  1. -

    Create a new file in src/tools/: -

    import { z } from 'zod';
    -import { Tool } from '../types';
    -
    -export const myTool: Tool = {
    -  name: 'my_tool',
    -  description: 'Description of my tool',
    -  parameters: z.object({
    -    // Define parameters
    -  }),
    -  execute: async (params) => {
    -    // Implement tool logic
    -  }
    -};
    -

    -
  2. -
  3. -

    Add to src/tools/index.ts

    -
  4. -
  5. Create tests in __tests__/tools/
  6. -
  7. Add documentation in docs/tools/
  8. -
-

Contributing

-
    -
  1. Fork the repository
  2. -
  3. Create a feature branch
  4. -
  5. Make your changes
  6. -
  7. Write/update tests
  8. -
  9. Update documentation
  10. -
  11. Submit a pull request
  12. -
-

Pull Request Process

-
    -
  1. Ensure all tests pass
  2. -
  3. Update documentation
  4. -
  5. Update CHANGELOG.md
  6. -
  7. Get review from maintainers
  8. -
-

Building

-
    -
  1. -

    Development build: -

    npm run build:dev
    -

    -
  2. -
  3. -

    Production build: -

    npm run build
    -

    -
  4. -
-

Documentation

-
    -
  1. Update documentation for changes
  2. -
  3. Follow documentation structure
  4. -
  5. Include examples
  6. -
  7. Update type definitions
  8. -
-

Debugging

-
    -
  1. -

    Development debugging: -

    npm run dev:debug
    -

    -
  2. -
  3. -

    Test debugging: -

    npm run test:debug
    -

    -
  4. -
  5. -

    VSCode launch configurations provided

    -
  6. -
-

Performance

-
    -
  1. Follow performance best practices
  2. -
  3. Use caching where appropriate
  4. -
  5. Implement rate limiting
  6. -
  7. Monitor memory usage
  8. -
-

Security

-
    -
  1. Follow security best practices
  2. -
  3. Validate all inputs
  4. -
  5. Use proper authentication
  6. -
  7. Handle errors securely
  8. -
-

Deployment

-
    -
  1. -

    Build for production: -

    npm run build
    -

    -
  2. -
  3. -

    Start production server: -

    npm start
    -

    -
  4. -
  5. -

    Docker deployment: -

    docker-compose up -d
    -

    -
  6. -
-

Support

-

Need development help? -1. Check documentation -2. Search issues -3. Create new issue -4. Join discussions

- - - - - - - - - - - - - - - - - - - - - - -
-
- - - -
- - - -
- - - -
-
-
-
- - - - - - - - - - - - \ No newline at end of file diff --git a/development/environment.html b/development/environment.html new file mode 100644 index 0000000..a4a65f2 --- /dev/null +++ b/development/environment.html @@ -0,0 +1,51 @@ + Environment Setup - MCP Server for Home Assistant
Skip to content

Development Environment Setup

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

Prerequisites

Required Software

  • Python 3.10 or higher
  • pip (Python package manager)
  • git
  • Docker (optional, for containerized development)
  • Node.js 18+ (for frontend development)

System Requirements

  • 4GB RAM minimum
  • 2 CPU cores minimum
  • 10GB free disk space

Initial Setup

  1. Clone the Repository

    git clone https://github.com/jango-blockchained/homeassistant-mcp.git
    +cd homeassistant-mcp
    +

  2. Create Virtual Environment

    python -m venv .venv
    +source .venv/bin/activate  # Linux/macOS
    +# or
    +.venv\Scripts\activate  # Windows
    +

  3. Install Dependencies

    pip install -r requirements.txt
    +pip install -r docs/requirements.txt  # for documentation
    +

Development Tools

Code Editor Setup

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

VS Code Settings

{
+  "python.linting.enabled": true,
+  "python.linting.pylintEnabled": true,
+  "python.formatting.provider": "black",
+  "editor.formatOnSave": true
+}
+

Configuration

  1. Create Local Config

    cp config.example.yaml config.yaml
    +

  2. Set Environment Variables

    cp .env.example .env
    +# Edit .env with your settings
    +

Running Tests

Unit Tests

pytest tests/unit
+

Integration Tests

pytest tests/integration
+

Coverage Report

pytest --cov=src tests/
+

Docker Development

Build Container

docker build -t mcp-server-dev -f Dockerfile.dev .
+

Run Development Container

docker run -it --rm \
+  -v $(pwd):/app \
+  -p 8123:8123 \
+  mcp-server-dev
+

Database Setup

Local Development Database

docker run -d \
+  -p 5432:5432 \
+  -e POSTGRES_USER=mcp \
+  -e POSTGRES_PASSWORD=development \
+  -e POSTGRES_DB=mcp_dev \
+  postgres:14
+

Run Migrations

alembic upgrade head
+

Frontend Development

  1. Install Node.js Dependencies

    cd frontend
    +npm install
    +

  2. Start Development Server

    npm run dev
    +

Documentation

Build Documentation

mkdocs serve
+

View Documentation

Open http://localhost:8000 in your browser

Debugging

VS Code Launch Configuration

{
+  "version": "0.2.0",
+  "configurations": [
+    {
+      "name": "Python: MCP Server",
+      "type": "python",
+      "request": "launch",
+      "program": "src/main.py",
+      "console": "integratedTerminal"
+    }
+  ]
+}
+

Git Hooks

Install Pre-commit

pip install pre-commit
+pre-commit install
+

Available Hooks

  • black (code formatting)
  • flake8 (linting)
  • isort (import sorting)
  • mypy (type checking)

Troubleshooting

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

Next Steps

  1. Review the Architecture Guide
  2. Check Contributing Guidelines
  3. Start with Simple Issues
\ No newline at end of file diff --git a/development/index.html b/development/index.html new file mode 100644 index 0000000..f2b2cb1 --- /dev/null +++ b/development/index.html @@ -0,0 +1 @@ + Overview - MCP Server for Home Assistant
Skip to content

Development Guide

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.

Development Overview

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

  • Clean, maintainable code
  • Comprehensive testing
  • Clear documentation
  • Modular architecture

Getting Started

  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

Development Topics

Best Practices

  • Follow the coding style guide
  • Write comprehensive tests
  • Document your changes
  • Keep commits atomic
  • Use meaningful commit messages

Development Workflow

  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

Next Steps

\ No newline at end of file diff --git a/development/interfaces.html b/development/interfaces.html new file mode 100644 index 0000000..8abe277 --- /dev/null +++ b/development/interfaces.html @@ -0,0 +1,200 @@ + Interfaces - MCP Server for Home Assistant
Skip to content

Interface Documentation

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

Core Interfaces

Tool Interface

interface Tool {
+    /** Unique identifier for the tool */
+    id: string;
+
+    /** Human-readable name */
+    name: string;
+
+    /** Detailed description */
+    description: string;
+
+    /** Semantic version */
+    version: string;
+
+    /** Tool category */
+    category: ToolCategory;
+
+    /** Execute tool functionality */
+    execute(params: any): Promise<ToolResult>;
+}
+

Tool Result

interface ToolResult {
+    /** Operation success status */
+    success: boolean;
+
+    /** Response data */
+    data?: any;
+
+    /** Error message if failed */
+    message?: string;
+
+    /** Error code if failed */
+    error_code?: string;
+}
+

Tool Category

enum ToolCategory {
+    DeviceManagement = 'device_management',
+    HistoryState = 'history_state',
+    Automation = 'automation',
+    AddonsPackages = 'addons_packages',
+    Notifications = 'notifications',
+    Events = 'events',
+    Utility = 'utility'
+}
+

Event Interfaces

Event Subscription

interface EventSubscription {
+    /** Unique subscription ID */
+    id: string;
+
+    /** Event type to subscribe to */
+    event_type: string;
+
+    /** Optional entity ID filter */
+    entity_id?: string;
+
+    /** Optional domain filter */
+    domain?: string;
+
+    /** Subscription creation timestamp */
+    created_at: string;
+
+    /** Last event timestamp */
+    last_event?: string;
+}
+

Event Message

interface EventMessage {
+    /** Event type */
+    event_type: string;
+
+    /** Entity ID if applicable */
+    entity_id?: string;
+
+    /** Event data */
+    data: any;
+
+    /** Event origin */
+    origin: 'LOCAL' | 'REMOTE';
+
+    /** Event timestamp */
+    time_fired: string;
+
+    /** Event context */
+    context: EventContext;
+}
+

Device Interfaces

Device

interface Device {
+    /** Device ID */
+    id: string;
+
+    /** Device name */
+    name: string;
+
+    /** Device domain */
+    domain: string;
+
+    /** Current state */
+    state: string;
+
+    /** Device attributes */
+    attributes: Record<string, any>;
+
+    /** Device capabilities */
+    capabilities: DeviceCapabilities;
+}
+

Device Capabilities

interface DeviceCapabilities {
+    /** Supported features */
+    features: string[];
+
+    /** Supported commands */
+    commands: string[];
+
+    /** State attributes */
+    attributes: {
+        /** Attribute name */
+        [key: string]: {
+            /** Attribute type */
+            type: 'string' | 'number' | 'boolean' | 'object';
+            /** Attribute description */
+            description: string;
+            /** Optional value constraints */
+            constraints?: {
+                min?: number;
+                max?: number;
+                enum?: any[];
+            };
+        };
+    };
+}
+

Authentication Interfaces

Auth Token

interface AuthToken {
+    /** Token value */
+    token: string;
+
+    /** Token type */
+    type: 'bearer' | 'jwt';
+
+    /** Expiration timestamp */
+    expires_at: string;
+
+    /** Token refresh info */
+    refresh?: {
+        token: string;
+        expires_at: string;
+    };
+}
+

User

interface User {
+    /** User ID */
+    id: string;
+
+    /** Username */
+    username: string;
+
+    /** User type */
+    type: 'admin' | 'user' | 'service';
+
+    /** User permissions */
+    permissions: string[];
+}
+

Error Interfaces

Tool Error

interface ToolError extends Error {
+    /** Error code */
+    code: string;
+
+    /** HTTP status code */
+    status: number;
+
+    /** Error details */
+    details?: Record<string, any>;
+}
+

Validation Error

interface ValidationError {
+    /** Error path */
+    path: string;
+
+    /** Error message */
+    message: string;
+
+    /** Error code */
+    code: string;
+}
+

Configuration Interfaces

Tool Configuration

interface ToolConfig {
+    /** Enable/disable tool */
+    enabled: boolean;
+
+    /** Tool-specific settings */
+    settings: Record<string, any>;
+
+    /** Rate limiting */
+    rate_limit?: {
+        /** Max requests */
+        max: number;
+        /** Time window in seconds */
+        window: number;
+    };
+}
+

System Configuration

interface SystemConfig {
+    /** System name */
+    name: string;
+
+    /** Environment */
+    environment: 'development' | 'production';
+
+    /** Log level */
+    log_level: 'debug' | 'info' | 'warn' | 'error';
+
+    /** Tool configurations */
+    tools: Record<string, ToolConfig>;
+}
+

Best Practices

  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

See Also

\ No newline at end of file diff --git a/development/interfaces/index.html b/development/interfaces/index.html deleted file mode 100644 index 3be3fcf..0000000 --- a/development/interfaces/index.html +++ /dev/null @@ -1,2536 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - Interfaces - Advanced Home Assistant MCP - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - Skip to content - - -
-
- -
- - - - - - -
- - -
- -
- - - - - - -
-
- - - -
-
-
- - - - - -
-
-
- - - - - - - -
-
- - - - - - - - -

Interface Documentation

-

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

-

Core Interfaces

-

Tool Interface

-
interface Tool {
-    /** Unique identifier for the tool */
-    id: string;
-
-    /** Human-readable name */
-    name: string;
-
-    /** Detailed description */
-    description: string;
-
-    /** Semantic version */
-    version: string;
-
-    /** Tool category */
-    category: ToolCategory;
-
-    /** Execute tool functionality */
-    execute(params: any): Promise<ToolResult>;
-}
-
-

Tool Result

-
interface ToolResult {
-    /** Operation success status */
-    success: boolean;
-
-    /** Response data */
-    data?: any;
-
-    /** Error message if failed */
-    message?: string;
-
-    /** Error code if failed */
-    error_code?: string;
-}
-
-

Tool Category

-
enum ToolCategory {
-    DeviceManagement = 'device_management',
-    HistoryState = 'history_state',
-    Automation = 'automation',
-    AddonsPackages = 'addons_packages',
-    Notifications = 'notifications',
-    Events = 'events',
-    Utility = 'utility'
-}
-
-

Event Interfaces

-

Event Subscription

-
interface EventSubscription {
-    /** Unique subscription ID */
-    id: string;
-
-    /** Event type to subscribe to */
-    event_type: string;
-
-    /** Optional entity ID filter */
-    entity_id?: string;
-
-    /** Optional domain filter */
-    domain?: string;
-
-    /** Subscription creation timestamp */
-    created_at: string;
-
-    /** Last event timestamp */
-    last_event?: string;
-}
-
-

Event Message

-
interface EventMessage {
-    /** Event type */
-    event_type: string;
-
-    /** Entity ID if applicable */
-    entity_id?: string;
-
-    /** Event data */
-    data: any;
-
-    /** Event origin */
-    origin: 'LOCAL' | 'REMOTE';
-
-    /** Event timestamp */
-    time_fired: string;
-
-    /** Event context */
-    context: EventContext;
-}
-
-

Device Interfaces

-

Device

-
interface Device {
-    /** Device ID */
-    id: string;
-
-    /** Device name */
-    name: string;
-
-    /** Device domain */
-    domain: string;
-
-    /** Current state */
-    state: string;
-
-    /** Device attributes */
-    attributes: Record<string, any>;
-
-    /** Device capabilities */
-    capabilities: DeviceCapabilities;
-}
-
-

Device Capabilities

-
interface DeviceCapabilities {
-    /** Supported features */
-    features: string[];
-
-    /** Supported commands */
-    commands: string[];
-
-    /** State attributes */
-    attributes: {
-        /** Attribute name */
-        [key: string]: {
-            /** Attribute type */
-            type: 'string' | 'number' | 'boolean' | 'object';
-            /** Attribute description */
-            description: string;
-            /** Optional value constraints */
-            constraints?: {
-                min?: number;
-                max?: number;
-                enum?: any[];
-            };
-        };
-    };
-}
-
-

Authentication Interfaces

-

Auth Token

-
interface AuthToken {
-    /** Token value */
-    token: string;
-
-    /** Token type */
-    type: 'bearer' | 'jwt';
-
-    /** Expiration timestamp */
-    expires_at: string;
-
-    /** Token refresh info */
-    refresh?: {
-        token: string;
-        expires_at: string;
-    };
-}
-
-

User

-
interface User {
-    /** User ID */
-    id: string;
-
-    /** Username */
-    username: string;
-
-    /** User type */
-    type: 'admin' | 'user' | 'service';
-
-    /** User permissions */
-    permissions: string[];
-}
-
-

Error Interfaces

-

Tool Error

-
interface ToolError extends Error {
-    /** Error code */
-    code: string;
-
-    /** HTTP status code */
-    status: number;
-
-    /** Error details */
-    details?: Record<string, any>;
-}
-
-

Validation Error

-
interface ValidationError {
-    /** Error path */
-    path: string;
-
-    /** Error message */
-    message: string;
-
-    /** Error code */
-    code: string;
-}
-
-

Configuration Interfaces

-

Tool Configuration

-
interface ToolConfig {
-    /** Enable/disable tool */
-    enabled: boolean;
-
-    /** Tool-specific settings */
-    settings: Record<string, any>;
-
-    /** Rate limiting */
-    rate_limit?: {
-        /** Max requests */
-        max: number;
-        /** Time window in seconds */
-        window: number;
-    };
-}
-
-

System Configuration

-
interface SystemConfig {
-    /** System name */
-    name: string;
-
-    /** Environment */
-    environment: 'development' | 'production';
-
-    /** Log level */
-    log_level: 'debug' | 'info' | 'warn' | 'error';
-
-    /** Tool configurations */
-    tools: Record<string, ToolConfig>;
-}
-
-

Best Practices

-
    -
  1. Use TypeScript for all interfaces
  2. -
  3. Include JSDoc comments
  4. -
  5. Use strict typing
  6. -
  7. Keep interfaces focused
  8. -
  9. Use consistent naming
  10. -
  11. Document constraints
  12. -
  13. Version interfaces
  14. -
  15. Include examples
  16. -
-

See Also

- - - - - - - - - - - - - - - - - - - - - - - -
-
- - - -
- - - -
- - - -
-
-
-
- - - - - - - - - - - - \ No newline at end of file diff --git a/development/test-migration-guide.html b/development/test-migration-guide.html new file mode 100644 index 0000000..f141fb8 --- /dev/null +++ b/development/test-migration-guide.html @@ -0,0 +1,177 @@ + Test Migration Guide - MCP Server for Home Assistant
Skip to content

Migrating Tests from Jest to Bun

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

Table of Contents

Basic Setup

  1. Remove Jest-related dependencies from package.json:

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

  2. Remove Jest configuration files:

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

  5. Update test scripts in package.json:

    {
    +  "scripts": {
    +    "test": "bun test",
    +    "test:watch": "bun test --watch",
    +    "test:coverage": "bun test --coverage"
    +  }
    +}
    +

Import Changes

Before (Jest):

import { jest, describe, it, expect, beforeEach, afterEach } from '@jest/globals';
+

After (Bun):

import { describe, expect, test, beforeEach, afterEach, mock } from "bun:test";
+import type { Mock } from "bun:test";
+

Note: it is replaced with test in Bun.

API Changes

Test Structure

// Jest
+describe('Suite', () => {
+  it('should do something', () => {
+    // test
+  });
+});
+
+// Bun
+describe('Suite', () => {
+  test('should do something', () => {
+    // test
+  });
+});
+

Assertions

Most Jest assertions work the same in Bun:

// These work the same in both:
+expect(value).toBe(expected);
+expect(value).toEqual(expected);
+expect(value).toBeDefined();
+expect(value).toBeUndefined();
+expect(value).toBeTruthy();
+expect(value).toBeFalsy();
+expect(array).toContain(item);
+expect(value).toBeInstanceOf(Class);
+expect(spy).toHaveBeenCalled();
+expect(spy).toHaveBeenCalledWith(...args);
+

Mocking

Function Mocking

Before (Jest):

const mockFn = jest.fn();
+mockFn.mockImplementation(() => 'result');
+mockFn.mockResolvedValue('result');
+mockFn.mockRejectedValue(new Error());
+

After (Bun):

const mockFn = mock(() => 'result');
+const mockAsyncFn = mock(() => Promise.resolve('result'));
+const mockErrorFn = mock(() => Promise.reject(new Error()));
+

Module Mocking

Before (Jest):

jest.mock('module-name', () => ({
+  default: jest.fn(),
+  namedExport: jest.fn()
+}));
+

After (Bun):

// Option 1: Using vi.mock (if available)
+vi.mock('module-name', () => ({
+  default: mock(() => {}),
+  namedExport: mock(() => {})
+}));
+
+// Option 2: Using dynamic imports
+const mockModule = {
+  default: mock(() => {}),
+  namedExport: mock(() => {})
+};
+

Mock Reset/Clear

Before (Jest):

jest.clearAllMocks();
+mockFn.mockClear();
+jest.resetModules();
+

After (Bun):

mockFn.mockReset();
+// or for specific calls
+mockFn.mock.calls = [];
+

Spy on Methods

Before (Jest):

jest.spyOn(object, 'method');
+

After (Bun):

const spy = mock(((...args) => object.method(...args)));
+object.method = spy;
+

Common Patterns

Async Tests

// Works the same in both Jest and Bun:
+test('async test', async () => {
+  const result = await someAsyncFunction();
+  expect(result).toBe(expected);
+});
+

Setup and Teardown

describe('Suite', () => {
+  beforeEach(() => {
+    // setup
+  });
+
+  afterEach(() => {
+    // cleanup
+  });
+
+  test('test', () => {
+    // test
+  });
+});
+

Mocking Fetch

// Before (Jest)
+global.fetch = jest.fn(() => Promise.resolve(new Response()));
+
+// After (Bun)
+const mockFetch = mock(() => Promise.resolve(new Response()));
+global.fetch = mockFetch as unknown as typeof fetch;
+

Mocking WebSocket

// Create a MockWebSocket class implementing WebSocket interface
+class MockWebSocket implements WebSocket {
+  public static readonly CONNECTING = 0;
+  public static readonly OPEN = 1;
+  public static readonly CLOSING = 2;
+  public static readonly CLOSED = 3;
+
+  public readyState: 0 | 1 | 2 | 3 = MockWebSocket.OPEN;
+  public addEventListener = mock(() => undefined);
+  public removeEventListener = mock(() => undefined);
+  public send = mock(() => undefined);
+  public close = mock(() => undefined);
+  // ... implement other required methods
+}
+
+// Use it in tests
+global.WebSocket = MockWebSocket as unknown as typeof WebSocket;
+

Examples

Basic Test

import { describe, expect, test } from "bun:test";
+
+describe('formatToolCall', () => {
+  test('should format an object into the correct structure', () => {
+    const testObj = { name: 'test', value: 123 };
+    const result = formatToolCall(testObj);
+
+    expect(result).toEqual({
+      content: [{
+        type: 'text',
+        text: JSON.stringify(testObj, null, 2),
+        isError: false
+      }]
+    });
+  });
+});
+

Async Test with Mocking

import { describe, expect, test, mock } from "bun:test";
+
+describe('API Client', () => {
+  test('should fetch data', async () => {
+    const mockResponse = { data: 'test' };
+    const mockFetch = mock(() => Promise.resolve(new Response(
+      JSON.stringify(mockResponse),
+      { status: 200, headers: new Headers() }
+    )));
+    global.fetch = mockFetch as unknown as typeof fetch;
+
+    const result = await apiClient.getData();
+    expect(result).toEqual(mockResponse);
+  });
+});
+

Complex Mocking Example

import { describe, expect, test, mock } from "bun:test";
+import type { Mock } from "bun:test";
+
+interface MockServices {
+  light: {
+    turn_on: Mock<() => Promise<{ success: boolean }>>;
+    turn_off: Mock<() => Promise<{ success: boolean }>>;
+  };
+}
+
+const mockServices: MockServices = {
+  light: {
+    turn_on: mock(() => Promise.resolve({ success: true })),
+    turn_off: mock(() => Promise.resolve({ success: true }))
+  }
+};
+
+describe('Home Assistant Service', () => {
+  test('should control lights', async () => {
+    const result = await mockServices.light.turn_on();
+    expect(result.success).toBe(true);
+  });
+});
+

Best Practices

  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

Common Issues and Solutions

Issue: Type Errors with Mocks

// Solution: Use proper typing with Mock type
+import type { Mock } from "bun:test";
+const mockFn: Mock<() => string> = mock(() => "result");
+

Issue: Global Object Mocking

// Solution: Use type assertions carefully
+global.someGlobal = mockImplementation as unknown as typeof someGlobal;
+

Issue: Module Mocking

// Solution: Use dynamic imports or vi.mock if available
+const mockModule = {
+  default: mock(() => mockImplementation)
+};
+
\ No newline at end of file diff --git a/development/test-migration-guide/index.html b/development/test-migration-guide/index.html deleted file mode 100644 index 83a1423..0000000 --- a/development/test-migration-guide/index.html +++ /dev/null @@ -1,2437 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - Migrating Tests from Jest to Bun - Advanced Home Assistant MCP - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - Skip to content - - -
-
- -
- - - - - - -
- - -
- -
- - - - - - -
-
- - - -
-
-
- - - - - -
-
-
- - - - - - - -
-
- - - - - - - - -

Migrating Tests from Jest to Bun

-

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

-

Table of Contents

- -

Basic Setup

-
    -
  1. -

    Remove Jest-related dependencies from package.json: -

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

    -
  2. -
  3. -

    Remove Jest configuration files:

    -
  4. -
  5. jest.config.js
  6. -
  7. -

    jest.setup.js

    -
  8. -
  9. -

    Update test scripts in package.json: -

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

    -
  10. -
-

Import Changes

-

Before (Jest):

-
import { jest, describe, it, expect, beforeEach, afterEach } from '@jest/globals';
-
-

After (Bun):

-
import { describe, expect, test, beforeEach, afterEach, mock } from "bun:test";
-import type { Mock } from "bun:test";
-
-

Note: it is replaced with test in Bun.

-

API Changes

-

Test Structure

-
// Jest
-describe('Suite', () => {
-  it('should do something', () => {
-    // test
-  });
-});
-
-// Bun
-describe('Suite', () => {
-  test('should do something', () => {
-    // test
-  });
-});
-
-

Assertions

-

Most Jest assertions work the same in Bun:

-
// These work the same in both:
-expect(value).toBe(expected);
-expect(value).toEqual(expected);
-expect(value).toBeDefined();
-expect(value).toBeUndefined();
-expect(value).toBeTruthy();
-expect(value).toBeFalsy();
-expect(array).toContain(item);
-expect(value).toBeInstanceOf(Class);
-expect(spy).toHaveBeenCalled();
-expect(spy).toHaveBeenCalledWith(...args);
-
-

Mocking

-

Function Mocking

-

Before (Jest):

-
const mockFn = jest.fn();
-mockFn.mockImplementation(() => 'result');
-mockFn.mockResolvedValue('result');
-mockFn.mockRejectedValue(new Error());
-
-

After (Bun):

-
const mockFn = mock(() => 'result');
-const mockAsyncFn = mock(() => Promise.resolve('result'));
-const mockErrorFn = mock(() => Promise.reject(new Error()));
-
-

Module Mocking

-

Before (Jest):

-
jest.mock('module-name', () => ({
-  default: jest.fn(),
-  namedExport: jest.fn()
-}));
-
-

After (Bun):

-
// Option 1: Using vi.mock (if available)
-vi.mock('module-name', () => ({
-  default: mock(() => {}),
-  namedExport: mock(() => {})
-}));
-
-// Option 2: Using dynamic imports
-const mockModule = {
-  default: mock(() => {}),
-  namedExport: mock(() => {})
-};
-
-

Mock Reset/Clear

-

Before (Jest):

-
jest.clearAllMocks();
-mockFn.mockClear();
-jest.resetModules();
-
-

After (Bun):

-
mockFn.mockReset();
-// or for specific calls
-mockFn.mock.calls = [];
-
-

Spy on Methods

-

Before (Jest):

-
jest.spyOn(object, 'method');
-
-

After (Bun):

-
const spy = mock(((...args) => object.method(...args)));
-object.method = spy;
-
-

Common Patterns

-

Async Tests

-
// Works the same in both Jest and Bun:
-test('async test', async () => {
-  const result = await someAsyncFunction();
-  expect(result).toBe(expected);
-});
-
-

Setup and Teardown

-
describe('Suite', () => {
-  beforeEach(() => {
-    // setup
-  });
-
-  afterEach(() => {
-    // cleanup
-  });
-
-  test('test', () => {
-    // test
-  });
-});
-
-

Mocking Fetch

-
// Before (Jest)
-global.fetch = jest.fn(() => Promise.resolve(new Response()));
-
-// After (Bun)
-const mockFetch = mock(() => Promise.resolve(new Response()));
-global.fetch = mockFetch as unknown as typeof fetch;
-
-

Mocking WebSocket

-
// Create a MockWebSocket class implementing WebSocket interface
-class MockWebSocket implements WebSocket {
-  public static readonly CONNECTING = 0;
-  public static readonly OPEN = 1;
-  public static readonly CLOSING = 2;
-  public static readonly CLOSED = 3;
-
-  public readyState: 0 | 1 | 2 | 3 = MockWebSocket.OPEN;
-  public addEventListener = mock(() => undefined);
-  public removeEventListener = mock(() => undefined);
-  public send = mock(() => undefined);
-  public close = mock(() => undefined);
-  // ... implement other required methods
-}
-
-// Use it in tests
-global.WebSocket = MockWebSocket as unknown as typeof WebSocket;
-
-

Examples

-

Basic Test

-
import { describe, expect, test } from "bun:test";
-
-describe('formatToolCall', () => {
-  test('should format an object into the correct structure', () => {
-    const testObj = { name: 'test', value: 123 };
-    const result = formatToolCall(testObj);
-
-    expect(result).toEqual({
-      content: [{
-        type: 'text',
-        text: JSON.stringify(testObj, null, 2),
-        isError: false
-      }]
-    });
-  });
-});
-
-

Async Test with Mocking

-
import { describe, expect, test, mock } from "bun:test";
-
-describe('API Client', () => {
-  test('should fetch data', async () => {
-    const mockResponse = { data: 'test' };
-    const mockFetch = mock(() => Promise.resolve(new Response(
-      JSON.stringify(mockResponse),
-      { status: 200, headers: new Headers() }
-    )));
-    global.fetch = mockFetch as unknown as typeof fetch;
-
-    const result = await apiClient.getData();
-    expect(result).toEqual(mockResponse);
-  });
-});
-
-

Complex Mocking Example

-
import { describe, expect, test, mock } from "bun:test";
-import type { Mock } from "bun:test";
-
-interface MockServices {
-  light: {
-    turn_on: Mock<() => Promise<{ success: boolean }>>;
-    turn_off: Mock<() => Promise<{ success: boolean }>>;
-  };
-}
-
-const mockServices: MockServices = {
-  light: {
-    turn_on: mock(() => Promise.resolve({ success: true })),
-    turn_off: mock(() => Promise.resolve({ success: true }))
-  }
-};
-
-describe('Home Assistant Service', () => {
-  test('should control lights', async () => {
-    const result = await mockServices.light.turn_on();
-    expect(result.success).toBe(true);
-  });
-});
-
-

Best Practices

-
    -
  1. Use TypeScript for better type safety in mocks
  2. -
  3. Keep mocks as simple as possible
  4. -
  5. Prefer interface-based mocks over concrete implementations
  6. -
  7. Use proper type assertions when necessary
  8. -
  9. Clean up mocks in afterEach blocks
  10. -
  11. Use descriptive test names
  12. -
  13. Group related tests using describe blocks
  14. -
-

Common Issues and Solutions

-

Issue: Type Errors with Mocks

-
// Solution: Use proper typing with Mock type
-import type { Mock } from "bun:test";
-const mockFn: Mock<() => string> = mock(() => "result");
-
-

Issue: Global Object Mocking

-
// Solution: Use type assertions carefully
-global.someGlobal = mockImplementation as unknown as typeof someGlobal;
-
-

Issue: Module Mocking

-
// Solution: Use dynamic imports or vi.mock if available
-const mockModule = {
-  default: mock(() => mockImplementation)
-};
-
- - - - - - - - - - - - - - - - - - - - - - -
-
- - - -
- - - -
- - - -
-
-
-
- - - - - - - - - - - - \ No newline at end of file diff --git a/development/tools.html b/development/tools.html new file mode 100644 index 0000000..82c34d9 --- /dev/null +++ b/development/tools.html @@ -0,0 +1,125 @@ + Tool Development - MCP Server for Home Assistant
Skip to content

Tool Development Guide

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

Tool Structure

Each tool should follow this basic structure:

interface Tool {
+    id: string;
+    name: string;
+    description: string;
+    version: string;
+    category: ToolCategory;
+    execute(params: any): Promise<ToolResult>;
+}
+

Creating a New Tool

  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

Example Tool Implementation

import { Tool, ToolCategory, ToolResult } from '../interfaces';
+
+export class MyCustomTool implements Tool {
+    id = 'my_custom_tool';
+    name = 'My Custom Tool';
+    description = 'Description of what the tool does';
+    version = '1.0.0';
+    category = ToolCategory.Utility;
+
+    async execute(params: any): Promise<ToolResult> {
+        // Tool implementation
+        return {
+            success: true,
+            data: {
+                // Tool-specific response data
+            }
+        };
+    }
+}
+

Tool Categories

  • Device Management
  • History & State
  • Automation
  • Add-ons & Packages
  • Notifications
  • Events
  • Utility

API Integration

REST Endpoint

import { Router } from 'express';
+import { MyCustomTool } from './my-custom-tool';
+
+const router = Router();
+const tool = new MyCustomTool();
+
+router.post('/api/tools/custom', async (req, res) => {
+    try {
+        const result = await tool.execute(req.body);
+        res.json(result);
+    } catch (error) {
+        res.status(500).json({
+            success: false,
+            message: error.message
+        });
+    }
+});
+

WebSocket Handler

import { WebSocketServer } from 'ws';
+import { MyCustomTool } from './my-custom-tool';
+
+const tool = new MyCustomTool();
+
+wss.on('connection', (ws) => {
+    ws.on('message', async (message) => {
+        const { type, params } = JSON.parse(message);
+        if (type === 'my_custom_tool') {
+            const result = await tool.execute(params);
+            ws.send(JSON.stringify(result));
+        }
+    });
+});
+

Error Handling

class ToolError extends Error {
+    constructor(
+        message: string,
+        public code: string,
+        public status: number = 500
+    ) {
+        super(message);
+        this.name = 'ToolError';
+    }
+}
+
+// Usage in tool
+async execute(params: any): Promise<ToolResult> {
+    try {
+        // Tool implementation
+    } catch (error) {
+        throw new ToolError(
+            'Operation failed',
+            'TOOL_ERROR',
+            500
+        );
+    }
+}
+

Testing

import { MyCustomTool } from './my-custom-tool';
+
+describe('MyCustomTool', () => {
+    let tool: MyCustomTool;
+
+    beforeEach(() => {
+        tool = new MyCustomTool();
+    });
+
+    it('should execute successfully', async () => {
+        const result = await tool.execute({
+            // Test parameters
+        });
+        expect(result.success).toBe(true);
+    });
+
+    it('should handle errors', async () => {
+        // Error test cases
+    });
+});
+

Documentation

  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

Documentation Template

# Tool Name
+
+Description of the tool.
+
+## Features
+
+- Feature 1
+- Feature 2
+
+## Usage
+
+### REST API
+
+```typescript
+// API endpoints
+

WebSocket

// WebSocket usage
+

Examples

Example 1

// Usage example
+

Response Format

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

Best Practices

  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

See Also

\ No newline at end of file diff --git a/development/tools/index.html b/development/tools/index.html deleted file mode 100644 index 6f66f1c..0000000 --- a/development/tools/index.html +++ /dev/null @@ -1,2382 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - Tool Development - Advanced Home Assistant MCP - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - Skip to content - - -
-
- -
- - - - - - -
- - -
- -
- - - - - - -
-
- - - -
-
-
- - - - - -
-
-
- - - - - - - -
-
- - - - - - - - -

Tool Development Guide

-

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

-

Tool Structure

-

Each tool should follow this basic structure:

-
interface Tool {
-    id: string;
-    name: string;
-    description: string;
-    version: string;
-    category: ToolCategory;
-    execute(params: any): Promise<ToolResult>;
-}
-
-

Creating a New Tool

-
    -
  1. Create a new file in the appropriate category directory
  2. -
  3. Implement the Tool interface
  4. -
  5. Add API endpoints
  6. -
  7. Add WebSocket handlers
  8. -
  9. Add documentation
  10. -
  11. Add tests
  12. -
-

Example Tool Implementation

-
import { Tool, ToolCategory, ToolResult } from '../interfaces';
-
-export class MyCustomTool implements Tool {
-    id = 'my_custom_tool';
-    name = 'My Custom Tool';
-    description = 'Description of what the tool does';
-    version = '1.0.0';
-    category = ToolCategory.Utility;
-
-    async execute(params: any): Promise<ToolResult> {
-        // Tool implementation
-        return {
-            success: true,
-            data: {
-                // Tool-specific response data
-            }
-        };
-    }
-}
-
-

Tool Categories

-
    -
  • Device Management
  • -
  • History & State
  • -
  • Automation
  • -
  • Add-ons & Packages
  • -
  • Notifications
  • -
  • Events
  • -
  • Utility
  • -
-

API Integration

-

REST Endpoint

-
import { Router } from 'express';
-import { MyCustomTool } from './my-custom-tool';
-
-const router = Router();
-const tool = new MyCustomTool();
-
-router.post('/api/tools/custom', async (req, res) => {
-    try {
-        const result = await tool.execute(req.body);
-        res.json(result);
-    } catch (error) {
-        res.status(500).json({
-            success: false,
-            message: error.message
-        });
-    }
-});
-
-

WebSocket Handler

-
import { WebSocketServer } from 'ws';
-import { MyCustomTool } from './my-custom-tool';
-
-const tool = new MyCustomTool();
-
-wss.on('connection', (ws) => {
-    ws.on('message', async (message) => {
-        const { type, params } = JSON.parse(message);
-        if (type === 'my_custom_tool') {
-            const result = await tool.execute(params);
-            ws.send(JSON.stringify(result));
-        }
-    });
-});
-
-

Error Handling

-
class ToolError extends Error {
-    constructor(
-        message: string,
-        public code: string,
-        public status: number = 500
-    ) {
-        super(message);
-        this.name = 'ToolError';
-    }
-}
-
-// Usage in tool
-async execute(params: any): Promise<ToolResult> {
-    try {
-        // Tool implementation
-    } catch (error) {
-        throw new ToolError(
-            'Operation failed',
-            'TOOL_ERROR',
-            500
-        );
-    }
-}
-
-

Testing

-
import { MyCustomTool } from './my-custom-tool';
-
-describe('MyCustomTool', () => {
-    let tool: MyCustomTool;
-
-    beforeEach(() => {
-        tool = new MyCustomTool();
-    });
-
-    it('should execute successfully', async () => {
-        const result = await tool.execute({
-            // Test parameters
-        });
-        expect(result.success).toBe(true);
-    });
-
-    it('should handle errors', async () => {
-        // Error test cases
-    });
-});
-
-

Documentation

-
    -
  1. Create tool documentation in docs/tools/category/tool-name.md
  2. -
  3. Update tools/tools.md with tool reference
  4. -
  5. Add tool to navigation in mkdocs.yml
  6. -
-

Documentation Template

-
# Tool Name
-
-Description of the tool.
-
-## Features
-
-- Feature 1
-- Feature 2
-
-## Usage
-
-### REST API
-
-```typescript
-// API endpoints
-
-

WebSocket

-
// WebSocket usage
-
-

Examples

-

Example 1

-
// Usage example
-
-

Response Format

-

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

-

Best Practices

-
    -
  1. Follow consistent naming conventions
  2. -
  3. Implement proper error handling
  4. -
  5. Add comprehensive documentation
  6. -
  7. Write thorough tests
  8. -
  9. Use TypeScript for type safety
  10. -
  11. Follow SOLID principles
  12. -
  13. Implement rate limiting
  14. -
  15. Add proper logging
  16. -
-

See Also

- - - - - - - - - - - - - - - - - - - - - - - -
-
- - - -
- - - -
- - - -
-
-
-
- - - - - - - - - - - - \ No newline at end of file diff --git a/examples/index.html b/examples/index.html index 3c6f181..3e96e6b 100644 --- a/examples/index.html +++ b/examples/index.html @@ -1,1881 +1,3 @@ - - - - - - - - - - - - - - - - - - - - - - - - - Examples - Advanced Home Assistant MCP - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - Skip to content - - -
-
- -
- - - - - - -
- - -
- -
- - - - - - -
-
- - - -
-
-
- - - - - -
-
-
- - - -
-
-
- - - -
-
-
- - - -
-
- - - - - - - - -

Example Projects 📚

-

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

-

Speech-to-Text Integration

-

Example of integrating speech recognition with MCP Server:

-
// From examples/speech-to-text-example.ts
-// Add example code and explanation
-
-

More Examples Coming Soon

-

...

- - - - - - - - - - - - - - - - - - - - - - -
-
- - - -
- - - -
- - - -
-
-
-
- - - - - - - - - - - - \ No newline at end of file + Examples - MCP Server for Home Assistant
Skip to content

Example Projects 📚

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

Speech-to-Text Integration

Example of integrating speech recognition with MCP Server:

// From examples/speech-to-text-example.ts
+// Add example code and explanation
+

More Examples Coming Soon

...

\ No newline at end of file diff --git a/getting-started/configuration.html b/getting-started/configuration.html new file mode 100644 index 0000000..4727b2f --- /dev/null +++ b/getting-started/configuration.html @@ -0,0 +1 @@ + Configuration - MCP Server for Home Assistant
Skip to content

Configuration

Basic Configuration

Advanced Settings

\ No newline at end of file diff --git a/getting-started/configuration/index.html b/getting-started/configuration/index.html deleted file mode 100644 index ea94fce..0000000 --- a/getting-started/configuration/index.html +++ /dev/null @@ -1,1875 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - Configuration - Advanced Home Assistant MCP - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - Skip to content - - -
-
- -
- - - - - - -
- - -
- -
- - - - - - -
-
- - - -
-
-
- - - - - -
-
-
- - - -
-
-
- - - -
-
-
- - - -
-
- - - - - - - - -

Configuration

-

Basic Configuration

-

Advanced Settings

- - - - - - - - - - - - - - - - - - - - - - -
-
- - - -
- - - -
- - - -
-
-
-
- - - - - - - - - - - - \ No newline at end of file diff --git a/getting-started/docker.html b/getting-started/docker.html new file mode 100644 index 0000000..39fa40a --- /dev/null +++ b/getting-started/docker.html @@ -0,0 +1 @@ + Docker Deployment - MCP Server for Home Assistant
Skip to content

Docker Deployment Guide 🐳

Detailed guide for deploying MCP Server with Docker...

\ No newline at end of file diff --git a/getting-started/docker/index.html b/getting-started/docker/index.html deleted file mode 100644 index 39fd5b0..0000000 --- a/getting-started/docker/index.html +++ /dev/null @@ -1,1799 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - Docker Deployment - Advanced Home Assistant MCP - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - Skip to content - - -
-
- -
- - - - - - -
- - -
- -
- - - - - - -
-
- - - -
-
-
- - - - - -
-
-
- - - -
-
-
- - - -
-
-
- - - -
-
- - - - - - - - -

Docker Deployment Guide 🐳

-

Detailed guide for deploying MCP Server with Docker...

- - - - - - - - - - - - - - - - - - - - - - -
-
- - - -
- - - -
- - - -
-
-
-
- - - - - - - - - - - - \ No newline at end of file diff --git a/getting-started/index.html b/getting-started/index.html index 8c3c7cb..3f5c400 100644 --- a/getting-started/index.html +++ b/getting-started/index.html @@ -1,1914 +1 @@ - - - - - - - - - - - - - - - - - - - - - - - - - Overview - Advanced Home Assistant MCP - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - Skip to content - - -
-
- -
- - - - - - -
- - -
- -
- - - - - - -
-
- - - -
-
-
- - - - - -
-
-
- - - -
-
-
- - - -
-
-
- - - -
-
- - - - - - - - -

Getting Started

-

Begin your journey with the Home Assistant MCP Server by following these steps:

-
    -
  • API Documentation: Read the API Documentation for available endpoints.
  • -
  • Real-Time Updates: Learn about Server-Sent Events for live communication.
  • -
  • Tools: Explore available Tools for device control and automation.
  • -
  • Configuration: Refer to the Configuration Guide for setup and advanced settings.
  • -
-

Troubleshooting

-

If you encounter any issues: -1. Verify that your Home Assistant instance is accessible. -2. Ensure that all required environment variables are properly set. -3. Consult the Troubleshooting Guide for additional solutions.

-

Development

-

For contributors: -1. Fork the repository. -2. Create a feature branch. -3. Follow the Development Guide for contribution guidelines. -4. Submit a pull request with your enhancements.

-

Support

-

Need help? -- Visit our GitHub Issues. -- Review the Troubleshooting Guide. -- Check the FAQ for common questions.

- - - - - - - - - - - - - - - - - - - - - - -
-
- - - -
- - - -
- - - -
-
-
-
- - - - - - - - - - - - \ No newline at end of file + Overview - MCP Server for Home Assistant
Skip to content

Getting Started

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
\ No newline at end of file diff --git a/getting-started/installation.html b/getting-started/installation.html new file mode 100644 index 0000000..51bbc12 --- /dev/null +++ b/getting-started/installation.html @@ -0,0 +1,75 @@ + Installation - MCP Server for Home Assistant
Skip to content

Installation Guide 🛠️

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.

Prerequisites

Before installing MCP Server, ensure you have:

  • Home Assistant instance running and accessible
  • Node.js 18+ or Docker installed
  • Home Assistant Long-Lived Access Token (How to get one)

Installation Methods

The easiest way to install MCP Server is through Smithery:

Smithery Configuration

The project includes a smithery.yaml configuration:

# Add smithery.yaml contents and explanation
+

Installation Steps

npx -y @smithery/cli install @jango-blockchained/advanced-homeassistant-mcp --client claude
+

2. 🐳 Docker Installation

For a containerized deployment:

# Clone the repository
+git clone --depth 1 https://github.com/jango-blockchained/advanced-homeassistant-mcp.git
+cd advanced-homeassistant-mcp
+
+# Configure environment variables
+cp .env.example .env
+# Edit .env with your Home Assistant details:
+# - HA_URL: Your Home Assistant URL
+# - HA_TOKEN: Your Long-Lived Access Token
+# - Other configuration options
+
+# Build and start containers
+docker compose up -d --build
+
+# View logs (optional)
+docker compose logs -f --tail=50
+

3. 💻 Manual Installation

For direct installation on your system:

# Install Bun runtime
+curl -fsSL https://bun.sh/install | bash
+
+# Clone and install
+git clone https://github.com/jango-blockchained/advanced-homeassistant-mcp.git
+cd advanced-homeassistant-mcp
+bun install --frozen-lockfile
+
+# Configure environment
+cp .env.example .env
+# Edit .env with your configuration
+
+# Start the server
+bun run dev --watch
+

Configuration

Environment Variables

Key configuration options in your .env file:

# Home Assistant Configuration
+HA_URL=http://your-homeassistant:8123
+HA_TOKEN=your_long_lived_access_token
+
+# Server Configuration
+PORT=3000
+HOST=0.0.0.0
+NODE_ENV=production
+
+# Security Settings
+JWT_SECRET=your_secure_jwt_secret
+RATE_LIMIT=100
+

Client Integration

Cursor Integration

Add to .cursor/config/config.json:

{
+  "mcpServers": {
+    "homeassistant-mcp": {
+      "command": "bun",
+      "args": ["run", "start"],
+      "cwd": "${workspaceRoot}",
+      "env": {
+        "NODE_ENV": "development"
+      }
+    }
+  }
+}
+

Claude Desktop Integration

Add to your Claude configuration:

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

Verification

To verify your installation:

  1. Check server status:

    curl http://localhost:3000/health
    +

  2. Test Home Assistant connection:

    curl http://localhost:3000/api/state
    +

Troubleshooting

If you encounter issues:

  1. Check the Troubleshooting Guide
  2. Verify your environment variables
  3. Check server logs:
    # For Docker installation
    +docker compose logs -f
    +
    +# For manual installation
    +bun run dev
    +

Next Steps

Support

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

\ No newline at end of file diff --git a/getting-started/installation/index.html b/getting-started/installation/index.html deleted file mode 100644 index 7e89276..0000000 --- a/getting-started/installation/index.html +++ /dev/null @@ -1,2308 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - Installation - Advanced Home Assistant MCP - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - Skip to content - - -
-
- -
- - - - - - -
- - -
- -
- - - - - - -
-
- - - -
-
-
- - - - - -
-
-
- - - - - - - -
-
- - - - - - - - -

Installation Guide 🛠️

-

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.

-

Prerequisites

-

Before installing MCP Server, ensure you have:

-
    -
  • Home Assistant instance running and accessible
  • -
  • Node.js 18+ or Docker installed
  • -
  • Home Assistant Long-Lived Access Token (How to get one)
  • -
-

Installation Methods

- -

The easiest way to install MCP Server is through Smithery:

-

Smithery Configuration

-

The project includes a smithery.yaml configuration:

-
# Add smithery.yaml contents and explanation
-
-

Installation Steps

-
npx -y @smithery/cli install @jango-blockchained/advanced-homeassistant-mcp --client claude
-
-

2. 🐳 Docker Installation

-

For a containerized deployment:

-
# Clone the repository
-git clone --depth 1 https://github.com/jango-blockchained/advanced-homeassistant-mcp.git
-cd advanced-homeassistant-mcp
-
-# Configure environment variables
-cp .env.example .env
-# Edit .env with your Home Assistant details:
-# - HA_URL: Your Home Assistant URL
-# - HA_TOKEN: Your Long-Lived Access Token
-# - Other configuration options
-
-# Build and start containers
-docker compose up -d --build
-
-# View logs (optional)
-docker compose logs -f --tail=50
-
-

3. 💻 Manual Installation

-

For direct installation on your system:

-
# Install Bun runtime
-curl -fsSL https://bun.sh/install | bash
-
-# Clone and install
-git clone https://github.com/jango-blockchained/advanced-homeassistant-mcp.git
-cd advanced-homeassistant-mcp
-bun install --frozen-lockfile
-
-# Configure environment
-cp .env.example .env
-# Edit .env with your configuration
-
-# Start the server
-bun run dev --watch
-
-

Configuration

-

Environment Variables

-

Key configuration options in your .env file:

-
# Home Assistant Configuration
-HA_URL=http://your-homeassistant:8123
-HA_TOKEN=your_long_lived_access_token
-
-# Server Configuration
-PORT=3000
-HOST=0.0.0.0
-NODE_ENV=production
-
-# Security Settings
-JWT_SECRET=your_secure_jwt_secret
-RATE_LIMIT=100
-
-

Client Integration

-

Cursor Integration

-

Add to .cursor/config/config.json:

-
{
-  "mcpServers": {
-    "homeassistant-mcp": {
-      "command": "bun",
-      "args": ["run", "start"],
-      "cwd": "${workspaceRoot}",
-      "env": {
-        "NODE_ENV": "development"
-      }
-    }
-  }
-}
-
-

Claude Desktop Integration

-

Add to your Claude configuration:

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

Verification

-

To verify your installation:

-
    -
  1. -

    Check server status: -

    curl http://localhost:3000/health
    -

    -
  2. -
  3. -

    Test Home Assistant connection: -

    curl http://localhost:3000/api/state
    -

    -
  4. -
-

Troubleshooting

-

If you encounter issues:

-
    -
  1. Check the Troubleshooting Guide
  2. -
  3. Verify your environment variables
  4. -
  5. Check server logs: -
    # For Docker installation
    -docker compose logs -f
    -
    -# For manual installation
    -bun run dev
    -
  6. -
-

Next Steps

- -

Support

-

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

- - - - - - - - - - - - - - - - - - - - - - -
-
- - - -
- - - -
- - - -
-
-
-
- - - - - - - - - - - - \ No newline at end of file diff --git a/getting-started/quickstart.html b/getting-started/quickstart.html new file mode 100644 index 0000000..e7d5cfc --- /dev/null +++ b/getting-started/quickstart.html @@ -0,0 +1,128 @@ + Quick Start - MCP Server for Home Assistant
Skip to content

Quick Start Guide 🚀

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

First Steps

1. Verify Connection

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

# Check server health
+curl http://localhost:3000/health
+
+# Verify Home Assistant connection
+curl http://localhost:3000/api/state
+

2. Basic Voice Commands

Try these basic voice commands to test your setup:

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

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

Real-World Examples

1. Smart Lighting Control

// Browser example using fetch
+const response = await fetch('http://localhost:3000/api/command', {
+  method: 'POST',
+  headers: {
+    'Content-Type': 'application/json',
+  },
+  body: JSON.stringify({
+    command: 'Set living room lights to 50% brightness and warm white color'
+  })
+});
+

2. Real-Time Updates

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

const eventSource = new EventSource('http://localhost:3000/subscribe_events?token=YOUR_TOKEN&domain=light');
+
+eventSource.onmessage = (event) => {
+    const data = JSON.parse(event.data);
+    console.log('Device state changed:', data);
+    // Update your UI here
+};
+

3. Scene Automation

Create and trigger scenes for different activities:

// Create a "Movie Night" scene
+const createScene = async () => {
+  await fetch('http://localhost:3000/api/scene', {
+    method: 'POST',
+    headers: {
+      'Content-Type': 'application/json',
+    },
+    body: JSON.stringify({
+      name: 'Movie Night',
+      actions: [
+        { device: 'living_room_lights', action: 'dim', value: 20 },
+        { device: 'tv', action: 'on' },
+        { device: 'soundbar', action: 'on' }
+      ]
+    })
+  });
+};
+
+// Trigger the scene with voice command:
+// "Hey MCP, activate movie night scene"
+

Integration Examples

1. Web Dashboard Integration

// React component example
+function SmartHomeControl() {
+    const [devices, setDevices] = useState([]);
+
+    useEffect(() => {
+        // Subscribe to device updates
+        const events = new EventSource('http://localhost:3000/subscribe_events');
+        events.onmessage = (event) => {
+            const data = JSON.parse(event.data);
+            setDevices(currentDevices => 
+                currentDevices.map(device => 
+                    device.id === data.id ? {...device, ...data} : device
+                )
+            );
+        };
+
+        return () => events.close();
+    }, []);
+
+    return (
+        <div className="dashboard">
+            {devices.map(device => (
+                <DeviceCard key={device.id} device={device} />
+            ))}
+        </div>
+    );
+}
+

2. Voice Assistant Integration

// Example using speech-to-text with MCP
+async function handleVoiceCommand(audioBlob: Blob) {
+    // First, convert speech to text
+    const text = await speechToText(audioBlob);
+
+    // Then send command to MCP
+    const response = await fetch('http://localhost:3000/api/command', {
+        method: 'POST',
+        headers: {
+            'Content-Type': 'application/json',
+        },
+        body: JSON.stringify({ command: text })
+    });
+
+    return response.json();
+}
+

Best Practices

  1. Error Handling

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

  2. Connection Management

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

Next Steps

Troubleshooting

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.

\ No newline at end of file diff --git a/getting-started/quickstart/index.html b/getting-started/quickstart/index.html deleted file mode 100644 index 5ea0c3f..0000000 --- a/getting-started/quickstart/index.html +++ /dev/null @@ -1,2286 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - Quick Start - Advanced Home Assistant MCP - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - Skip to content - - -
-
- -
- - - - - - -
- - -
- -
- - - - - - -
-
- - - -
-
-
- - - - - -
-
-
- - - - - - - -
-
- - - - - - - - -

Quick Start Guide 🚀

-

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

-

First Steps

-

1. Verify Connection

-

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

-
# Check server health
-curl http://localhost:3000/health
-
-# Verify Home Assistant connection
-curl http://localhost:3000/api/state
-
-

2. Basic Voice Commands

-

Try these basic voice commands to test your setup:

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

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

-

Real-World Examples

-

1. Smart Lighting Control

-
// Browser example using fetch
-const response = await fetch('http://localhost:3000/api/command', {
-  method: 'POST',
-  headers: {
-    'Content-Type': 'application/json',
-  },
-  body: JSON.stringify({
-    command: 'Set living room lights to 50% brightness and warm white color'
-  })
-});
-
-

2. Real-Time Updates

-

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

-
const eventSource = new EventSource('http://localhost:3000/subscribe_events?token=YOUR_TOKEN&domain=light');
-
-eventSource.onmessage = (event) => {
-    const data = JSON.parse(event.data);
-    console.log('Device state changed:', data);
-    // Update your UI here
-};
-
-

3. Scene Automation

-

Create and trigger scenes for different activities:

-
// Create a "Movie Night" scene
-const createScene = async () => {
-  await fetch('http://localhost:3000/api/scene', {
-    method: 'POST',
-    headers: {
-      'Content-Type': 'application/json',
-    },
-    body: JSON.stringify({
-      name: 'Movie Night',
-      actions: [
-        { device: 'living_room_lights', action: 'dim', value: 20 },
-        { device: 'tv', action: 'on' },
-        { device: 'soundbar', action: 'on' }
-      ]
-    })
-  });
-};
-
-// Trigger the scene with voice command:
-// "Hey MCP, activate movie night scene"
-
-

Integration Examples

-

1. Web Dashboard Integration

-
// React component example
-function SmartHomeControl() {
-    const [devices, setDevices] = useState([]);
-
-    useEffect(() => {
-        // Subscribe to device updates
-        const events = new EventSource('http://localhost:3000/subscribe_events');
-        events.onmessage = (event) => {
-            const data = JSON.parse(event.data);
-            setDevices(currentDevices => 
-                currentDevices.map(device => 
-                    device.id === data.id ? {...device, ...data} : device
-                )
-            );
-        };
-
-        return () => events.close();
-    }, []);
-
-    return (
-        <div className="dashboard">
-            {devices.map(device => (
-                <DeviceCard key={device.id} device={device} />
-            ))}
-        </div>
-    );
-}
-
-

2. Voice Assistant Integration

-
// Example using speech-to-text with MCP
-async function handleVoiceCommand(audioBlob: Blob) {
-    // First, convert speech to text
-    const text = await speechToText(audioBlob);
-
-    // Then send command to MCP
-    const response = await fetch('http://localhost:3000/api/command', {
-        method: 'POST',
-        headers: {
-            'Content-Type': 'application/json',
-        },
-        body: JSON.stringify({ command: text })
-    });
-
-    return response.json();
-}
-
-

Best Practices

-
    -
  1. -

    Error Handling -

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

    -
  2. -
  3. -

    Connection Management -

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

    -
  4. -
-

Next Steps

- -

Troubleshooting

-

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.

- - - - - - - - - - - - - - - - - - - - - - -
-
- - - -
- - - -
- - - -
-
-
-
- - - - - - - - - - - - \ No newline at end of file diff --git a/index.html b/index.html index 0875aa0..6001cdf 100644 --- a/index.html +++ b/index.html @@ -1,2058 +1 @@ - - - - - - - - - - - - - - - - - - - - - - - Home - Advanced Home Assistant MCP - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - Skip to content - - -
-
- -
- - - - - - -
- - -
- -
- - - - - - -
-
- - - -
-
-
- - - - - -
-
-
- - - -
-
-
- - - -
-
-
- - - -
-
- - - - - - - - -

🏠 MCP Server for Home Assistant

-

Welcome to the Model Context Protocol (MCP) Server documentation! This guide will help you get started with integrating a lightweight automation tool with your Home Assistant setup.

-

What is MCP Server?

-

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.

-

Key Features

-

🎮 Device Control

-
    -
  • Basic REST API for device management
  • -
  • WebSocket and Server-Sent Events (SSE) for real-time updates
  • -
  • Simple automation rule support
  • -
-

🛡️ Security & Performance

-
    -
  • JWT authentication
  • -
  • Basic request validation
  • -
  • Lightweight server design
  • -
-

Documentation Structure

-

Getting Started

- -

Core Documentation

- -

Support

-

Need help or want to report issues?

- -

License

-

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

- - - - - - - - - - - - - - - - - - - - - - -
-
- - - -
- - - -
- - - -
-
-
-
- - - - - - - - - - - - \ No newline at end of file + Home - MCP Server for Home Assistant
Skip to content

Advanced Home Assistant MCP

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.

What is MCP Server?

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.

Key Features

🎮 Device Control

  • Basic REST API for device management
  • WebSocket and Server-Sent Events (SSE) for real-time updates
  • Simple automation rule support

🛡️ Security & Performance

  • JWT authentication
  • Basic request validation
  • Lightweight server design

Documentation Structure

Getting Started

Core Documentation

Support

Need help or want to report issues?

License

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

\ No newline at end of file diff --git a/javascripts/extra.js b/javascripts/extra.js new file mode 100644 index 0000000..58e5466 --- /dev/null +++ b/javascripts/extra.js @@ -0,0 +1,62 @@ +// Dark mode handling +document.addEventListener('DOMContentLoaded', function () { + // Check for saved dark mode preference + const darkMode = localStorage.getItem('darkMode'); + if (darkMode === 'true') { + document.body.classList.add('dark-mode'); + } +}); + +// Smooth scrolling for anchor links +document.querySelectorAll('a[href^="#"]').forEach(anchor => { + anchor.addEventListener('click', function (e) { + e.preventDefault(); + document.querySelector(this.getAttribute('href')).scrollIntoView({ + behavior: 'smooth' + }); + }); +}); + +// Add copy button to code blocks +document.querySelectorAll('pre code').forEach((block) => { + const button = document.createElement('button'); + button.className = 'copy-button'; + button.textContent = 'Copy'; + + button.addEventListener('click', async () => { + await navigator.clipboard.writeText(block.textContent); + button.textContent = 'Copied!'; + setTimeout(() => { + button.textContent = 'Copy'; + }, 2000); + }); + + const pre = block.parentNode; + pre.insertBefore(button, block); +}); + +// Add version selector handling +const versionSelector = document.querySelector('.version-selector'); +if (versionSelector) { + versionSelector.addEventListener('change', (e) => { + const version = e.target.value; + window.location.href = `/${version}/`; + }); +} + +// Add feedback handling +document.querySelectorAll('.feedback-button').forEach(button => { + button.addEventListener('click', function () { + const feedback = this.getAttribute('data-feedback'); + // Send feedback to analytics + if (typeof gtag !== 'undefined') { + gtag('event', 'feedback', { + 'event_category': 'Documentation', + 'event_label': feedback + }); + } + // Show thank you message + this.textContent = 'Thank you!'; + this.disabled = true; + }); +}); \ No newline at end of file diff --git a/javascripts/mathjax.js b/javascripts/mathjax.js new file mode 100644 index 0000000..14cbd3b --- /dev/null +++ b/javascripts/mathjax.js @@ -0,0 +1,12 @@ +window.MathJax = { + tex: { + inlineMath: [["\\(", "\\)"]], + displayMath: [["\\[", "\\]"]], + processEscapes: true, + processEnvironments: true + }, + options: { + ignoreHtmlClass: ".*|", + processHtmlClass: "arithmatex" + } +}; \ No newline at end of file diff --git a/objects.inv b/objects.inv deleted file mode 100644 index d0567039fbb3059deee852dc6b3dd50d2622eaeb..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 149 zcmXAhu?oUK5JZDz@)HB;gIJ~uHa0>aVt?Lkyp?1x+@2x&skZ)z2QtOLW8Tyl7SFPQ zWhF@=zOYhM4uV5jqmSW1Hnr&7YQ&PmDa?dUl{FbjI3N2wyZ)6H`z9xYizh^y4U40Q iFd}(Yj64x?+b}PYRP)_aS?+jGd~3?>^W7CiRa8I1Vlk5d diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..de240f3 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,42 @@ +# Core +mkdocs>=1.5.3 +mkdocs-material>=9.5.3 + +# Enhanced Functionality +mkdocs-minify-plugin>=0.7.1 +mkdocs-git-revision-date-localized-plugin>=1.2.1 +mkdocs-glightbox>=0.3.4 +mkdocs-git-authors-plugin>=0.7.2 +mkdocs-git-committers-plugin>=0.2.3 +mkdocs-static-i18n>=1.2.0 +mkdocs-awesome-pages-plugin>=2.9.2 +mkdocs-redirects>=1.2.1 +mkdocs-include-markdown-plugin>=6.0.4 +mkdocs-macros-plugin>=1.0.4 +mkdocs-meta-descriptions-plugin>=3.0.0 +mkdocs-print-site-plugin>=2.3.6 + +# Code Documentation +mkdocstrings>=0.24.0 +mkdocstrings-python>=1.7.5 + +# Markdown Extensions +pymdown-extensions>=10.5 +markdown>=3.5.1 +mdx_truly_sane_lists>=1.3 +pygments>=2.17.2 + +# Math Support +python-markdown-math>=0.8 + +# Diagrams +plantuml-markdown>=3.9.2 +mkdocs-mermaid2-plugin>=1.1.1 + +# Search Enhancements +mkdocs-material[imaging]>=9.5.3 +pillow>=10.2.0 +cairosvg>=2.7.1 + +# Development Tools +mike>=2.0.0 # For version management \ No newline at end of file diff --git a/roadmap.html b/roadmap.html new file mode 100644 index 0000000..d7fc806 --- /dev/null +++ b/roadmap.html @@ -0,0 +1 @@ + Roadmap - MCP Server for Home Assistant
Skip to content

Roadmap for MCP Server

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.

Near-Term Goals

  • Core Functionality Improvements:
  • Enhance REST API capabilities
  • Improve WebSocket and SSE reliability
  • Develop more robust error handling

  • Security Enhancements:

  • Strengthen JWT authentication
  • Improve input validation
  • Add basic logging for security events

  • Performance Optimizations:

  • Optimize server response times
  • Improve resource utilization
  • Implement basic caching mechanisms

Mid-Term Goals

  • Device Integration:
  • Expand support for additional Home Assistant device types
  • Improve device state synchronization
  • Develop more flexible automation rule support

  • Developer Experience:

  • Improve documentation
  • Create more comprehensive examples
  • Develop basic CLI tools for configuration

Long-Term Vision

  • Extensibility:
  • Design a simple plugin system
  • Create guidelines for community contributions
  • Establish a clear extension mechanism

  • Reliability:

  • Implement comprehensive testing
  • Develop monitoring and basic health check features
  • Improve overall system stability

How to Follow the Roadmap

  • Community Involvement: We welcome feedback and contributions.
  • Transparency: Check our GitHub repository for ongoing discussions.
  • Iterative Development: Goals may change based on community needs and technical feasibility.

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

\ No newline at end of file diff --git a/roadmap/index.html b/roadmap/index.html deleted file mode 100644 index f6a3b23..0000000 --- a/roadmap/index.html +++ /dev/null @@ -1,1968 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - Roadmap - Advanced Home Assistant MCP - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - Skip to content - - -
-
- -
- - - - - - -
- - -
- -
- - - - - - -
-
- - - -
-
-
- - - - - -
-
-
- - - -
-
-
- - - -
-
-
- - - -
-
- - - - - - - - -

Roadmap for MCP Server

-

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.

-

Near-Term Goals

-
    -
  • Core Functionality Improvements:
  • -
  • Enhance REST API capabilities
  • -
  • Improve WebSocket and SSE reliability
  • -
  • -

    Develop more robust error handling

    -
  • -
  • -

    Security Enhancements:

    -
  • -
  • Strengthen JWT authentication
  • -
  • Improve input validation
  • -
  • -

    Add basic logging for security events

    -
  • -
  • -

    Performance Optimizations:

    -
  • -
  • Optimize server response times
  • -
  • Improve resource utilization
  • -
  • Implement basic caching mechanisms
  • -
-

Mid-Term Goals

-
    -
  • Device Integration:
  • -
  • Expand support for additional Home Assistant device types
  • -
  • Improve device state synchronization
  • -
  • -

    Develop more flexible automation rule support

    -
  • -
  • -

    Developer Experience:

    -
  • -
  • Improve documentation
  • -
  • Create more comprehensive examples
  • -
  • Develop basic CLI tools for configuration
  • -
-

Long-Term Vision

-
    -
  • Extensibility:
  • -
  • Design a simple plugin system
  • -
  • Create guidelines for community contributions
  • -
  • -

    Establish a clear extension mechanism

    -
  • -
  • -

    Reliability:

    -
  • -
  • Implement comprehensive testing
  • -
  • Develop monitoring and basic health check features
  • -
  • Improve overall system stability
  • -
-

How to Follow the Roadmap

-
    -
  • Community Involvement: We welcome feedback and contributions.
  • -
  • Transparency: Check our GitHub repository for ongoing discussions.
  • -
  • Iterative Development: Goals may change based on community needs and technical feasibility.
  • -
-

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

- - - - - - - - - - - - - - - - - - - - - - -
-
- - - -
- - - -
- - - -
-
-
-
- - - - - - - - - - - - \ No newline at end of file diff --git a/search/search_index.js b/search/search_index.js new file mode 100644 index 0000000..1640b53 --- /dev/null +++ b/search/search_index.js @@ -0,0 +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 a hierarchical configuration structure:

server:\n  host: 0.0.0.0\n  port: 8123\n  log_level: INFO\n\nsecurity:\n  jwt_secret: YOUR_SECRET_KEY\n  allowed_origins:\n    - http://localhost:3000\n    - https://your-domain.com\n\ndevices:\n  scan_interval: 30\n  default_timeout: 10\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#device-management","title":"Device Management","text":""},{"location":"configuration.html#environment-variables","title":"Environment Variables","text":"

Environment variables override configuration file settings:

MCP_HOST=0.0.0.0\nMCP_PORT=8123\nMCP_LOG_LEVEL=INFO\nMCP_JWT_SECRET=your-secret-key\n
"},{"location":"configuration.html#advanced-configuration","title":"Advanced Configuration","text":""},{"location":"configuration.html#rate-limiting","title":"Rate Limiting","text":"
rate_limit:\n  enabled: true\n  requests_per_minute: 100\n  burst: 20\n
"},{"location":"configuration.html#caching","title":"Caching","text":"
cache:\n  enabled: true\n  ttl: 300  # seconds\n  max_size: 1000  # entries\n
"},{"location":"configuration.html#logging","title":"Logging","text":"
logging:\n  file: /var/log/mcp-server.log\n  max_size: 10MB\n  backup_count: 5\n  format: \"%(asctime)s - %(name)s - %(levelname)s - %(message)s\"\n
"},{"location":"configuration.html#best-practices","title":"Best Practices","text":"
  1. Always use environment variables for sensitive information
  2. Keep configuration files in a secure location
  3. Regularly backup your configuration
  4. Use SSL in production environments
  5. Monitor log files for issues
"},{"location":"configuration.html#validation","title":"Validation","text":"

The server validates configuration on startup: - Required fields are checked - Value types are verified - Ranges are validated - Security settings are assessed

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

Common configuration issues: 1. Permission denied accessing files 2. Invalid YAML syntax 3. Missing required fields 4. Type mismatches in values

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 diff --git a/search/search_index.json b/search/search_index.json index a0861de..c2ced0a 100644 --- a/search/search_index.json +++ b/search/search_index.json @@ -1 +1 @@ -{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"\ud83c\udfe0 MCP Server for Home Assistant","text":"

Welcome to the Model Context Protocol (MCP) Server documentation! This guide will help you get started with integrating a lightweight automation tool with your Home Assistant setup.

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

Need help or want to report issues?

"},{"location":"#license","title":"License","text":"

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

"},{"location":"api/","title":"Home Assistant MCP Server API Documentation","text":""},{"location":"api/#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/#authentication","title":"Authentication","text":"

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

Authorization: Bearer YOUR_TOKEN\n
"},{"location":"api/#core-endpoints","title":"Core Endpoints","text":""},{"location":"api/#device-state-management","title":"Device State Management","text":""},{"location":"api/#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/#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/#device-control","title":"Device Control","text":""},{"location":"api/#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/#real-time-updates","title":"Real-Time Updates","text":""},{"location":"api/#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/#error-handling","title":"Error Handling","text":""},{"location":"api/#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/#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/#supported-operations","title":"Supported Operations","text":""},{"location":"api/#supported-commands","title":"Supported Commands","text":""},{"location":"api/#supported-entities","title":"Supported Entities","text":""},{"location":"api/#limitations","title":"Limitations","text":""},{"location":"api/#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/#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/#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/","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/#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\n
"},{"location":"architecture/#core-components","title":"Core Components","text":""},{"location":"architecture/#api-gateway","title":"API Gateway","text":""},{"location":"architecture/#sse-manager","title":"SSE Manager","text":""},{"location":"architecture/#websocket-server","title":"WebSocket Server","text":""},{"location":"architecture/#command-manager","title":"Command Manager","text":""},{"location":"architecture/#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/#key-design-principles","title":"Key Design Principles","text":""},{"location":"architecture/#limitations","title":"Limitations","text":""},{"location":"architecture/#future-improvements","title":"Future Improvements","text":"

Architecture is subject to change as the project evolves.

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

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

"},{"location":"contributing/#getting-started","title":"Getting Started","text":""},{"location":"contributing/#prerequisites","title":"Prerequisites","text":""},{"location":"contributing/#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/#development-workflow","title":"Development Workflow","text":""},{"location":"contributing/#branch-naming","title":"Branch Naming","text":"

Example:

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

"},{"location":"contributing/#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/#code-style","title":"Code Style","text":""},{"location":"contributing/#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/#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/#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/#reporting-issues","title":"Reporting Issues","text":""},{"location":"contributing/#code-of-conduct","title":"Code of Conduct","text":""},{"location":"contributing/#resources","title":"Resources","text":"

Thank you for contributing!

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

Begin your journey with the Home Assistant MCP Server by following these steps:

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

If you encounter any issues: 1. Verify that your Home Assistant instance is accessible. 2. Ensure that all required environment variables are properly set. 3. Consult the Troubleshooting Guide for additional solutions.

"},{"location":"getting-started/#development","title":"Development","text":"

For contributors: 1. Fork the repository. 2. Create a feature branch. 3. Follow the Development Guide for contribution guidelines. 4. Submit a pull request with your enhancements.

"},{"location":"getting-started/#support","title":"Support","text":"

Need help? - Visit our GitHub Issues. - Review the Troubleshooting Guide. - Check the FAQ for common questions.

"},{"location":"roadmap/","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/#near-term-goals","title":"Near-Term Goals","text":""},{"location":"roadmap/#mid-term-goals","title":"Mid-Term Goals","text":""},{"location":"roadmap/#long-term-vision","title":"Long-Term Vision","text":""},{"location":"roadmap/#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":"testing/","title":"Testing Documentation","text":""},{"location":"testing/#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/#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/#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/#test-configuration","title":"Test Configuration","text":""},{"location":"testing/#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/#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/#test-setup","title":"Test Setup","text":""},{"location":"testing/#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/#test-environment","title":"Test Environment","text":""},{"location":"testing/#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/#advanced-debugging","title":"Advanced Debugging","text":""},{"location":"testing/#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/#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/#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/#writing-tests","title":"Writing Tests","text":""},{"location":"testing/#test-file-naming","title":"Test File Naming","text":""},{"location":"testing/#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/#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/#security-middleware-testing","title":"Security Middleware Testing","text":""},{"location":"testing/#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/#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/#testing-philosophy","title":"Testing Philosophy","text":""},{"location":"testing/#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/#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/#continuous-improvement","title":"Continuous Improvement","text":""},{"location":"testing/#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/#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/#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/#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/#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/#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/","title":"Troubleshooting Guide \ud83d\udd27","text":"

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

"},{"location":"troubleshooting/#quick-diagnostics","title":"Quick Diagnostics","text":""},{"location":"troubleshooting/#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/#common-issues","title":"Common Issues","text":""},{"location":"troubleshooting/#1-connection-issues","title":"1. Connection Issues","text":""},{"location":"troubleshooting/#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/#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/#2-authentication-issues","title":"2. Authentication Issues","text":""},{"location":"troubleshooting/#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/#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/#3-real-time-updates-issues","title":"3. Real-time Updates Issues","text":""},{"location":"troubleshooting/#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/#4-performance-issues","title":"4. Performance Issues","text":""},{"location":"troubleshooting/#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/#5-device-control-issues","title":"5. Device Control Issues","text":""},{"location":"troubleshooting/#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/#debugging-tools","title":"Debugging Tools","text":""},{"location":"troubleshooting/#log-analysis","title":"Log Analysis","text":"

Enable debug logging:

LOG_LEVEL=debug\nDEBUG=mcp:*\n
"},{"location":"troubleshooting/#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/#performance-profiling","title":"Performance Profiling","text":"

Enable performance monitoring:

ENABLE_METRICS=true\nMETRICS_PORT=9090\n
"},{"location":"troubleshooting/#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/#maintenance","title":"Maintenance","text":""},{"location":"troubleshooting/#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/#log-rotation","title":"Log Rotation","text":"

Configure log rotation:

logging:\n  maxSize: \"100m\"\n  maxFiles: \"7d\"\n  compress: true\n
"},{"location":"troubleshooting/#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/#faq","title":"FAQ","text":""},{"location":"troubleshooting/#general-questions","title":"General Questions","text":""},{"location":"troubleshooting/#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/#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/#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/#integration-questions","title":"Integration Questions","text":""},{"location":"troubleshooting/#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/#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/#security-questions","title":"Security Questions","text":""},{"location":"troubleshooting/#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/#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/#troubleshooting-questions","title":"Troubleshooting Questions","text":""},{"location":"troubleshooting/#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/#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/","title":"Usage Guide","text":"

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

"},{"location":"usage/#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/#device-control","title":"Device Control","text":""},{"location":"usage/#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/#supported-commands","title":"Supported Commands","text":""},{"location":"usage/#supported-entities","title":"Supported Entities","text":""},{"location":"usage/#real-time-updates","title":"Real-Time Updates","text":""},{"location":"usage/#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/#authentication","title":"Authentication","text":"

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

"},{"location":"usage/#limitations","title":"Limitations","text":""},{"location":"usage/#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/#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/#next-steps","title":"Next Steps","text":""},{"location":"api/","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/#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/#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/#core-endpoints","title":"Core Endpoints","text":""},{"location":"api/#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/#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/#real-time-events","title":"Real-Time Events","text":""},{"location":"api/#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/#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/#scene-management","title":"Scene Management","text":""},{"location":"api/#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/#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/#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/#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/#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/#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/#further-reading","title":"Further Reading","text":""},{"location":"api/core/","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/#device-control","title":"Device Control","text":""},{"location":"api/core/#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/#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/#natural-language-commands","title":"Natural Language Commands","text":""},{"location":"api/core/#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/#scene-management","title":"Scene Management","text":""},{"location":"api/core/#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/#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/#groups","title":"Groups","text":""},{"location":"api/core/#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/#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/#system-operations","title":"System Operations","text":""},{"location":"api/core/#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/#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/#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/#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/#related-resources","title":"Related Resources","text":""},{"location":"api/sse/","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/#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/#basic-usage","title":"Basic Usage","text":""},{"location":"api/sse/#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/#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/#event-types","title":"Event Types","text":""},{"location":"api/sse/#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/#filtered-subscriptions","title":"Filtered Subscriptions","text":""},{"location":"api/sse/#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/#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/#advanced-usage","title":"Advanced Usage","text":""},{"location":"api/sse/#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/#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/#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/#common-issues","title":"Common Issues","text":""},{"location":"api/sse/#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/#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/#related-resources","title":"Related Resources","text":""},{"location":"development/best-practices/","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/#code-style","title":"Code Style","text":""},{"location":"development/best-practices/#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/#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/#architecture","title":"Architecture","text":""},{"location":"development/best-practices/#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/#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/#error-handling","title":"Error Handling","text":""},{"location":"development/best-practices/#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/#testing","title":"Testing","text":""},{"location":"development/best-practices/#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/#performance","title":"Performance","text":""},{"location":"development/best-practices/#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/#security","title":"Security","text":""},{"location":"development/best-practices/#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/#documentation","title":"Documentation","text":""},{"location":"development/best-practices/#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/#logging","title":"Logging","text":""},{"location":"development/best-practices/#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/#version-control","title":"Version Control","text":""},{"location":"development/best-practices/#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/#see-also","title":"See Also","text":""},{"location":"development/development/","title":"Development Guide","text":"

This guide provides information for developers who want to contribute to or extend the Home Assistant MCP.

"},{"location":"development/development/#project-structure","title":"Project Structure","text":"
homeassistant-mcp/\n\u251c\u2500\u2500 src/\n\u2502   \u251c\u2500\u2500 __tests__/        # Test files\n\u2502   \u251c\u2500\u2500 __mocks__/       # Mock files\n\u2502   \u251c\u2500\u2500 api/           # API endpoints and route handlers\n\u2502   \u251c\u2500\u2500 config/        # Configuration management\n\u2502   \u251c\u2500\u2500 hass/         # Home Assistant integration\n\u2502   \u251c\u2500\u2500 interfaces/    # TypeScript interfaces\n\u2502   \u251c\u2500\u2500 mcp/          # MCP core functionality\n\u2502   \u251c\u2500\u2500 middleware/    # Express middleware\n\u2502   \u251c\u2500\u2500 routes/       # Route definitions\n\u2502   \u251c\u2500\u2500 security/     # Security utilities\n\u2502   \u251c\u2500\u2500 sse/          # Server-Sent Events handling\n\u2502   \u251c\u2500\u2500 tools/        # Tool implementations\n\u2502   \u251c\u2500\u2500 types/        # TypeScript type definitions\n\u2502   \u2514\u2500\u2500 utils/        # Utility functions\n\u251c\u2500\u2500 __tests__/        # Test files\n\u251c\u2500\u2500 docs/            # Documentation\n\u251c\u2500\u2500 dist/           # Compiled JavaScript\n\u2514\u2500\u2500 scripts/        # Build and utility scripts\n
"},{"location":"development/development/#development-setup","title":"Development Setup","text":"
  1. Install dependencies:

    npm install\n

  2. Set up development environment:

    cp .env.example .env.development\n

  3. Start development server:

    npm run dev\n

"},{"location":"development/development/#code-style","title":"Code Style","text":"

We follow these coding standards:

  1. TypeScript best practices
  2. Use strict type checking
  3. Avoid any types
  4. Document complex types

  5. ESLint rules

  6. Run npm run lint to check
  7. Run npm run lint:fix to auto-fix

  8. Code formatting

  9. Use Prettier
  10. Run npm run format to format code
"},{"location":"development/development/#testing","title":"Testing","text":"
  1. Unit tests:

    npm run test\n

  2. Integration tests:

    npm run test:integration\n

  3. Coverage report:

    npm run test:coverage\n

"},{"location":"development/development/#creating-new-tools","title":"Creating New Tools","text":"
  1. Create a new file in src/tools/:

    import { z } from 'zod';\nimport { Tool } from '../types';\n\nexport const myTool: Tool = {\n  name: 'my_tool',\n  description: 'Description of my tool',\n  parameters: z.object({\n    // Define parameters\n  }),\n  execute: async (params) => {\n    // Implement tool logic\n  }\n};\n

  2. Add to src/tools/index.ts

  3. Create tests in __tests__/tools/
  4. Add documentation in docs/tools/
"},{"location":"development/development/#contributing","title":"Contributing","text":"
  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Write/update tests
  5. Update documentation
  6. Submit a pull request
"},{"location":"development/development/#pull-request-process","title":"Pull Request Process","text":"
  1. Ensure all tests pass
  2. Update documentation
  3. Update CHANGELOG.md
  4. Get review from maintainers
"},{"location":"development/development/#building","title":"Building","text":"
  1. Development build:

    npm run build:dev\n

  2. Production build:

    npm run build\n

"},{"location":"development/development/#documentation","title":"Documentation","text":"
  1. Update documentation for changes
  2. Follow documentation structure
  3. Include examples
  4. Update type definitions
"},{"location":"development/development/#debugging","title":"Debugging","text":"
  1. Development debugging:

    npm run dev:debug\n

  2. Test debugging:

    npm run test:debug\n

  3. VSCode launch configurations provided

"},{"location":"development/development/#performance","title":"Performance","text":"
  1. Follow performance best practices
  2. Use caching where appropriate
  3. Implement rate limiting
  4. Monitor memory usage
"},{"location":"development/development/#security","title":"Security","text":"
  1. Follow security best practices
  2. Validate all inputs
  3. Use proper authentication
  4. Handle errors securely
"},{"location":"development/development/#deployment","title":"Deployment","text":"
  1. Build for production:

    npm run build\n

  2. Start production server:

    npm start\n

  3. Docker deployment:

    docker-compose up -d\n

"},{"location":"development/development/#support","title":"Support","text":"

Need development help? 1. Check documentation 2. Search issues 3. Create new issue 4. Join discussions

"},{"location":"development/interfaces/","title":"Interface Documentation","text":"

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

"},{"location":"development/interfaces/#core-interfaces","title":"Core Interfaces","text":""},{"location":"development/interfaces/#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/#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/#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/#event-interfaces","title":"Event Interfaces","text":""},{"location":"development/interfaces/#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/#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/#device-interfaces","title":"Device Interfaces","text":""},{"location":"development/interfaces/#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/#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/#authentication-interfaces","title":"Authentication Interfaces","text":""},{"location":"development/interfaces/#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/#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/#error-interfaces","title":"Error Interfaces","text":""},{"location":"development/interfaces/#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/#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/#configuration-interfaces","title":"Configuration Interfaces","text":""},{"location":"development/interfaces/#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/#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/#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/#see-also","title":"See Also","text":""},{"location":"development/test-migration-guide/","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/#table-of-contents","title":"Table of Contents","text":""},{"location":"development/test-migration-guide/#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/#import-changes","title":"Import Changes","text":""},{"location":"development/test-migration-guide/#before-jest","title":"Before (Jest):","text":"
import { jest, describe, it, expect, beforeEach, afterEach } from '@jest/globals';\n
"},{"location":"development/test-migration-guide/#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/#api-changes","title":"API Changes","text":""},{"location":"development/test-migration-guide/#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/#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/#mocking","title":"Mocking","text":""},{"location":"development/test-migration-guide/#function-mocking","title":"Function Mocking","text":""},{"location":"development/test-migration-guide/#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/#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/#module-mocking","title":"Module Mocking","text":""},{"location":"development/test-migration-guide/#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/#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/#mock-resetclear","title":"Mock Reset/Clear","text":""},{"location":"development/test-migration-guide/#before-jest_3","title":"Before (Jest):","text":"
jest.clearAllMocks();\nmockFn.mockClear();\njest.resetModules();\n
"},{"location":"development/test-migration-guide/#after-bun_3","title":"After (Bun):","text":"
mockFn.mockReset();\n// or for specific calls\nmockFn.mock.calls = [];\n
"},{"location":"development/test-migration-guide/#spy-on-methods","title":"Spy on Methods","text":""},{"location":"development/test-migration-guide/#before-jest_4","title":"Before (Jest):","text":"
jest.spyOn(object, 'method');\n
"},{"location":"development/test-migration-guide/#after-bun_4","title":"After (Bun):","text":"
const spy = mock(((...args) => object.method(...args)));\nobject.method = spy;\n
"},{"location":"development/test-migration-guide/#common-patterns","title":"Common Patterns","text":""},{"location":"development/test-migration-guide/#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/#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/#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/#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/#examples","title":"Examples","text":""},{"location":"development/test-migration-guide/#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/#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/#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/#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/#common-issues-and-solutions","title":"Common Issues and Solutions","text":""},{"location":"development/test-migration-guide/#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/#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/#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/","title":"Tool Development Guide","text":"

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

"},{"location":"development/tools/#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/#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/#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/#tool-categories","title":"Tool Categories","text":""},{"location":"development/tools/#api-integration","title":"API Integration","text":""},{"location":"development/tools/#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/#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/#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/#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/#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/#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/#websocket","title":"WebSocket","text":"
// WebSocket usage\n
"},{"location":"development/tools/#examples","title":"Examples","text":""},{"location":"development/tools/#example-1","title":"Example 1","text":"
// Usage example\n
"},{"location":"development/tools/#response-format","title":"Response Format","text":"

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

"},{"location":"development/tools/#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/#see-also","title":"See Also","text":""},{"location":"examples/","title":"Example Projects \ud83d\udcda","text":"

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

"},{"location":"examples/#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/#more-examples-coming-soon","title":"More Examples Coming Soon","text":"

...

"},{"location":"getting-started/configuration/","title":"Configuration","text":""},{"location":"getting-started/configuration/#basic-configuration","title":"Basic Configuration","text":""},{"location":"getting-started/configuration/#advanced-settings","title":"Advanced Settings","text":""},{"location":"getting-started/docker/","title":"Docker Deployment Guide \ud83d\udc33","text":"

Detailed guide for deploying MCP Server with Docker...

"},{"location":"getting-started/installation/","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/#prerequisites","title":"Prerequisites","text":"

Before installing MCP Server, ensure you have:

"},{"location":"getting-started/installation/#installation-methods","title":"Installation Methods","text":""},{"location":"getting-started/installation/#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/#smithery-configuration","title":"Smithery Configuration","text":"

The project includes a smithery.yaml configuration:

# Add smithery.yaml contents and explanation\n
"},{"location":"getting-started/installation/#installation-steps","title":"Installation Steps","text":"
npx -y @smithery/cli install @jango-blockchained/advanced-homeassistant-mcp --client claude\n
"},{"location":"getting-started/installation/#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/#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/#configuration","title":"Configuration","text":""},{"location":"getting-started/installation/#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/#client-integration","title":"Client Integration","text":""},{"location":"getting-started/installation/#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/#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/#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/#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/#next-steps","title":"Next Steps","text":""},{"location":"getting-started/installation/#support","title":"Support","text":"

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

"},{"location":"getting-started/quickstart/","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/#first-steps","title":"First Steps","text":""},{"location":"getting-started/quickstart/#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/#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/#real-world-examples","title":"Real-World Examples","text":""},{"location":"getting-started/quickstart/#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/#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/#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/#integration-examples","title":"Integration Examples","text":""},{"location":"getting-started/quickstart/#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/#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/#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/#next-steps","title":"Next Steps","text":""},{"location":"getting-started/quickstart/#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/tools/","title":"Home Assistant MCP Tools","text":"

This section documents all available tools in the Home Assistant MCP.

"},{"location":"tools/tools/#available-tools","title":"Available Tools","text":""},{"location":"tools/tools/#device-management","title":"Device Management","text":"
  1. List Devices
  2. List all available Home Assistant devices
  3. Group devices by domain
  4. Get device states and attributes

  5. Device Control

  6. Control various device types
  7. Support for lights, switches, covers, climate devices
  8. Domain-specific commands and parameters
"},{"location":"tools/tools/#history-and-state","title":"History and State","text":"
  1. History
  2. Fetch device state history
  3. Filter by time range
  4. Get significant changes

  5. Scene Management

  6. List available scenes
  7. Activate scenes
  8. Scene state information
"},{"location":"tools/tools/#automation","title":"Automation","text":"
  1. Automation Management
  2. List automations
  3. Toggle automation state
  4. Trigger automations manually

  5. Automation Configuration

  6. Create new automations
  7. Update existing automations
  8. Delete automations
  9. Duplicate automations
"},{"location":"tools/tools/#add-ons-and-packages","title":"Add-ons and Packages","text":"
  1. Add-on Management
  2. List available add-ons
  3. Install/uninstall add-ons
  4. Start/stop/restart add-ons
  5. Get add-on information

  6. Package Management

  7. Manage HACS packages
  8. Install/update/remove packages
  9. List available packages by category
"},{"location":"tools/tools/#notifications","title":"Notifications","text":"
  1. Notify
  2. Send notifications
  3. Support for multiple notification services
  4. Custom notification data
"},{"location":"tools/tools/#real-time-events","title":"Real-time Events","text":"
  1. Event Subscription
  2. Subscribe to Home Assistant events
  3. Monitor specific entities
  4. Domain-based monitoring

  5. SSE Statistics

  6. Get SSE connection statistics
  7. Monitor active subscriptions
  8. Connection management
"},{"location":"tools/tools/#using-tools","title":"Using Tools","text":"

All tools can be accessed through:

  1. REST API endpoints
  2. WebSocket connections
  3. Server-Sent Events (SSE)
"},{"location":"tools/tools/#authentication","title":"Authentication","text":"

Tools require authentication using: - Home Assistant Long-Lived Access Token - JWT tokens for specific operations

"},{"location":"tools/tools/#error-handling","title":"Error Handling","text":"

All tools follow a consistent error handling pattern:

{\n    success: boolean;\n    message?: string;\n    data?: any;\n}\n

"},{"location":"tools/tools/#rate-limiting","title":"Rate Limiting","text":"

Tools are subject to rate limiting: - Default: 100 requests per 15 minutes - Configurable through environment variables

"},{"location":"tools/tools/#tool-development","title":"Tool Development","text":"

Want to create a new tool? Check out: - Tool Development Guide - Tool Interface Documentation - Best Practices

"},{"location":"tools/tools/#examples","title":"Examples","text":"

Each tool documentation includes: - Usage examples - Code snippets - Common use cases - Troubleshooting tips

"},{"location":"tools/tools/#support","title":"Support","text":"

Need help with tools? - Check individual tool documentation - See Troubleshooting Guide - Create an issue on GitHub

"},{"location":"tools/addons-packages/addon/","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/#features","title":"Features","text":""},{"location":"tools/addons-packages/addon/#usage","title":"Usage","text":""},{"location":"tools/addons-packages/addon/#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/#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/#examples","title":"Examples","text":""},{"location":"tools/addons-packages/addon/#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/#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/#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/#response-format","title":"Response Format","text":""},{"location":"tools/addons-packages/addon/#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/#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/#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/#error-handling","title":"Error Handling","text":""},{"location":"tools/addons-packages/addon/#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/addons-packages/addon/#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/#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/addons-packages/addon/#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/#add-on-security","title":"Add-on Security","text":""},{"location":"tools/addons-packages/addon/#see-also","title":"See Also","text":""},{"location":"tools/addons-packages/package/","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/#features","title":"Features","text":""},{"location":"tools/addons-packages/package/#usage","title":"Usage","text":""},{"location":"tools/addons-packages/package/#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/#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/#package-categories","title":"Package Categories","text":""},{"location":"tools/addons-packages/package/#examples","title":"Examples","text":""},{"location":"tools/addons-packages/package/#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/#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/#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/#response-format","title":"Response Format","text":""},{"location":"tools/addons-packages/package/#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/#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/#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/#error-handling","title":"Error Handling","text":""},{"location":"tools/addons-packages/package/#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/addons-packages/package/#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/#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/addons-packages/package/#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/#package-security","title":"Package Security","text":""},{"location":"tools/addons-packages/package/#see-also","title":"See Also","text":""},{"location":"tools/automation/automation-config/","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/#features","title":"Features","text":""},{"location":"tools/automation/automation-config/#usage","title":"Usage","text":""},{"location":"tools/automation/automation-config/#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/#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/#automation-configuration","title":"Automation Configuration","text":""},{"location":"tools/automation/automation-config/#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/#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/#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/#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/#examples","title":"Examples","text":""},{"location":"tools/automation/automation-config/#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/#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/#response-format","title":"Response Format","text":""},{"location":"tools/automation/automation-config/#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/#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/#error-handling","title":"Error Handling","text":""},{"location":"tools/automation/automation-config/#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/automation/automation-config/#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/#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/#see-also","title":"See Also","text":""},{"location":"tools/automation/automation/","title":"Automation Management Tool","text":"

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

"},{"location":"tools/automation/automation/#features","title":"Features","text":""},{"location":"tools/automation/automation/#usage","title":"Usage","text":""},{"location":"tools/automation/automation/#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/#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/#examples","title":"Examples","text":""},{"location":"tools/automation/automation/#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/#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/#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/#response-format","title":"Response Format","text":""},{"location":"tools/automation/automation/#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/#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/#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/#error-handling","title":"Error Handling","text":""},{"location":"tools/automation/automation/#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/automation/automation/#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/#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/automation/automation/#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/#see-also","title":"See Also","text":""},{"location":"tools/device-management/control/","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/#supported-device-types","title":"Supported Device Types","text":""},{"location":"tools/device-management/control/#usage","title":"Usage","text":""},{"location":"tools/device-management/control/#rest-api","title":"REST API","text":"
POST /api/devices/{device_id}/control\n
"},{"location":"tools/device-management/control/#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/#domain-specific-commands","title":"Domain-Specific Commands","text":""},{"location":"tools/device-management/control/#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/#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/#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/#examples","title":"Examples","text":""},{"location":"tools/device-management/control/#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/#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/#response-format","title":"Response Format","text":""},{"location":"tools/device-management/control/#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/#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/#error-handling","title":"Error Handling","text":""},{"location":"tools/device-management/control/#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/device-management/control/#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/device-management/control/#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/#see-also","title":"See Also","text":""},{"location":"tools/device-management/list-devices/","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/#features","title":"Features","text":""},{"location":"tools/device-management/list-devices/#usage","title":"Usage","text":""},{"location":"tools/device-management/list-devices/#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/#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/#examples","title":"Examples","text":""},{"location":"tools/device-management/list-devices/#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/#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/#response-format","title":"Response Format","text":""},{"location":"tools/device-management/list-devices/#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/#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/#error-handling","title":"Error Handling","text":""},{"location":"tools/device-management/list-devices/#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/device-management/list-devices/#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/#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/device-management/list-devices/#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/#see-also","title":"See Also","text":""},{"location":"tools/events/sse-stats/","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/#features","title":"Features","text":""},{"location":"tools/events/sse-stats/#usage","title":"Usage","text":""},{"location":"tools/events/sse-stats/#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/#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/#examples","title":"Examples","text":""},{"location":"tools/events/sse-stats/#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/#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/#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/#response-format","title":"Response Format","text":""},{"location":"tools/events/sse-stats/#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/#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/#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/#error-handling","title":"Error Handling","text":""},{"location":"tools/events/sse-stats/#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/events/sse-stats/#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/#monitoring-metrics","title":"Monitoring Metrics","text":""},{"location":"tools/events/sse-stats/#connection-metrics","title":"Connection Metrics","text":""},{"location":"tools/events/sse-stats/#event-metrics","title":"Event Metrics","text":""},{"location":"tools/events/sse-stats/#resource-metrics","title":"Resource Metrics","text":""},{"location":"tools/events/sse-stats/#alert-thresholds","title":"Alert Thresholds","text":""},{"location":"tools/events/sse-stats/#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/#performance-optimization","title":"Performance Optimization","text":""},{"location":"tools/events/sse-stats/#see-also","title":"See Also","text":""},{"location":"tools/events/subscribe-events/","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/#features","title":"Features","text":""},{"location":"tools/events/subscribe-events/#usage","title":"Usage","text":""},{"location":"tools/events/subscribe-events/#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/#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/#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/#event-types","title":"Event Types","text":""},{"location":"tools/events/subscribe-events/#examples","title":"Examples","text":""},{"location":"tools/events/subscribe-events/#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/#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/#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/#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/#response-format","title":"Response Format","text":""},{"location":"tools/events/subscribe-events/#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/#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/#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/#error-handling","title":"Error Handling","text":""},{"location":"tools/events/subscribe-events/#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/events/subscribe-events/#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/#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/events/subscribe-events/#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/#connection-management","title":"Connection Management","text":""},{"location":"tools/events/subscribe-events/#see-also","title":"See Also","text":""},{"location":"tools/history-state/history/","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/#features","title":"Features","text":""},{"location":"tools/history-state/history/#usage","title":"Usage","text":""},{"location":"tools/history-state/history/#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/#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/#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/#examples","title":"Examples","text":""},{"location":"tools/history-state/history/#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/#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/#response-format","title":"Response Format","text":""},{"location":"tools/history-state/history/#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/#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/#error-handling","title":"Error Handling","text":""},{"location":"tools/history-state/history/#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/history-state/history/#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/#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/history-state/history/#data-retention","title":"Data Retention","text":""},{"location":"tools/history-state/history/#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/#see-also","title":"See Also","text":""},{"location":"tools/history-state/scene/","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/#features","title":"Features","text":""},{"location":"tools/history-state/scene/#usage","title":"Usage","text":""},{"location":"tools/history-state/scene/#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/#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/#scene-configuration","title":"Scene Configuration","text":""},{"location":"tools/history-state/scene/#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/#examples","title":"Examples","text":""},{"location":"tools/history-state/scene/#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/#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/#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/#response-format","title":"Response Format","text":""},{"location":"tools/history-state/scene/#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/#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/#error-handling","title":"Error Handling","text":""},{"location":"tools/history-state/scene/#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/history-state/scene/#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/#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/history-state/scene/#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/#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/#see-also","title":"See Also","text":""},{"location":"tools/notifications/notify/","title":"Notification Tool","text":"

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

"},{"location":"tools/notifications/notify/#features","title":"Features","text":""},{"location":"tools/notifications/notify/#usage","title":"Usage","text":""},{"location":"tools/notifications/notify/#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/#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/#supported-services","title":"Supported Services","text":""},{"location":"tools/notifications/notify/#examples","title":"Examples","text":""},{"location":"tools/notifications/notify/#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/#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/#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/#response-format","title":"Response Format","text":""},{"location":"tools/notifications/notify/#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/#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/#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/#error-handling","title":"Error Handling","text":""},{"location":"tools/notifications/notify/#common-error-codes","title":"Common Error Codes","text":""},{"location":"tools/notifications/notify/#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/#rate-limiting","title":"Rate Limiting","text":""},{"location":"tools/notifications/notify/#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/#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/#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 a hierarchical configuration structure:

server:\n  host: 0.0.0.0\n  port: 8123\n  log_level: INFO\n\nsecurity:\n  jwt_secret: YOUR_SECRET_KEY\n  allowed_origins:\n    - http://localhost:3000\n    - https://your-domain.com\n\ndevices:\n  scan_interval: 30\n  default_timeout: 10\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#device-management","title":"Device Management","text":""},{"location":"configuration.html#environment-variables","title":"Environment Variables","text":"

Environment variables override configuration file settings:

MCP_HOST=0.0.0.0\nMCP_PORT=8123\nMCP_LOG_LEVEL=INFO\nMCP_JWT_SECRET=your-secret-key\n
"},{"location":"configuration.html#advanced-configuration","title":"Advanced Configuration","text":""},{"location":"configuration.html#rate-limiting","title":"Rate Limiting","text":"
rate_limit:\n  enabled: true\n  requests_per_minute: 100\n  burst: 20\n
"},{"location":"configuration.html#caching","title":"Caching","text":"
cache:\n  enabled: true\n  ttl: 300  # seconds\n  max_size: 1000  # entries\n
"},{"location":"configuration.html#logging","title":"Logging","text":"
logging:\n  file: /var/log/mcp-server.log\n  max_size: 10MB\n  backup_count: 5\n  format: \"%(asctime)s - %(name)s - %(levelname)s - %(message)s\"\n
"},{"location":"configuration.html#best-practices","title":"Best Practices","text":"
  1. Always use environment variables for sensitive information
  2. Keep configuration files in a secure location
  3. Regularly backup your configuration
  4. Use SSL in production environments
  5. Monitor log files for issues
"},{"location":"configuration.html#validation","title":"Validation","text":"

The server validates configuration on startup: - Required fields are checked - Value types are verified - Ranges are validated - Security settings are assessed

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

Common configuration issues: 1. Permission denied accessing files 2. Invalid YAML syntax 3. Missing required fields 4. Type mismatches in values

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 diff --git a/security.html b/security.html new file mode 100644 index 0000000..fc94a02 --- /dev/null +++ b/security.html @@ -0,0 +1,28 @@ + Security - MCP Server for Home Assistant
Skip to content

Security Guide

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

Authentication

JWT Authentication

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

Authorization: Bearer YOUR_JWT_TOKEN
+

Token Configuration

security:
+  jwt_secret: YOUR_SECRET_KEY
+  token_expiry: 24h
+  refresh_token_expiry: 7d
+

Access Control

CORS Configuration

Configure allowed origins to prevent unauthorized access:

security:
+  allowed_origins:
+    - http://localhost:3000
+    - https://your-domain.com
+

IP Filtering

Restrict access by IP address:

security:
+  allowed_ips:
+    - 192.168.1.0/24
+    - 10.0.0.0/8
+

SSL/TLS Configuration

Enable HTTPS

ssl:
+  enabled: true
+  cert_file: /path/to/cert.pem
+  key_file: /path/to/key.pem
+

Certificate Management

  1. Use Let's Encrypt for free SSL certificates
  2. Regularly renew certificates
  3. Monitor certificate expiration

Rate Limiting

Basic Rate Limiting

rate_limit:
+  enabled: true
+  requests_per_minute: 100
+  burst: 20
+

Advanced Rate Limiting

rate_limit:
+  rules:
+    - endpoint: /api/control
+      requests_per_minute: 50
+    - endpoint: /api/state
+      requests_per_minute: 200
+

Data Protection

Sensitive Data

  • Use environment variables for secrets
  • Encrypt sensitive data at rest
  • Implement secure backup procedures

Logging Security

  • Avoid logging sensitive information
  • Rotate logs regularly
  • Protect log file access

Best Practices

  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

Security Checklist

  • Configure SSL/TLS
  • Set up JWT authentication
  • Configure CORS properly
  • Enable rate limiting
  • Implement IP filtering
  • Secure sensitive data
  • Set up monitoring
  • Configure backup encryption
  • Update security policies

Incident Response

  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

Additional Resources

\ No newline at end of file diff --git a/sitemap.xml b/sitemap.xml index 9b6f0b9..20e7276 100644 --- a/sitemap.xml +++ b/sitemap.xml @@ -1,139 +1,159 @@ - https://jango-blockchained.github.io/advanced-homeassitant-mcp/ - 2025-02-05 + https://jango-blockchained.github.io/advanced-homeassistant-mcp/index.html + 2025-02-06 - https://jango-blockchained.github.io/advanced-homeassitant-mcp/api/ - 2025-02-05 + https://jango-blockchained.github.io/advanced-homeassistant-mcp/api.html + 2025-02-06 - https://jango-blockchained.github.io/advanced-homeassitant-mcp/architecture/ - 2025-02-05 + https://jango-blockchained.github.io/advanced-homeassistant-mcp/architecture.html + 2025-02-06 - https://jango-blockchained.github.io/advanced-homeassitant-mcp/contributing/ - 2025-02-05 + https://jango-blockchained.github.io/advanced-homeassistant-mcp/configuration.html + 2025-02-06 - https://jango-blockchained.github.io/advanced-homeassitant-mcp/getting-started/ - 2025-02-05 + https://jango-blockchained.github.io/advanced-homeassistant-mcp/contributing.html + 2025-02-06 - https://jango-blockchained.github.io/advanced-homeassitant-mcp/roadmap/ - 2025-02-05 + https://jango-blockchained.github.io/advanced-homeassistant-mcp/deployment.html + 2025-02-06 - https://jango-blockchained.github.io/advanced-homeassitant-mcp/testing/ - 2025-02-05 + https://jango-blockchained.github.io/advanced-homeassistant-mcp/roadmap.html + 2025-02-06 - https://jango-blockchained.github.io/advanced-homeassitant-mcp/troubleshooting/ - 2025-02-05 + https://jango-blockchained.github.io/advanced-homeassistant-mcp/security.html + 2025-02-06 - https://jango-blockchained.github.io/advanced-homeassitant-mcp/usage/ - 2025-02-05 + https://jango-blockchained.github.io/advanced-homeassistant-mcp/testing.html + 2025-02-06 - https://jango-blockchained.github.io/advanced-homeassitant-mcp/api/ - 2025-02-05 + https://jango-blockchained.github.io/advanced-homeassistant-mcp/troubleshooting.html + 2025-02-06 - https://jango-blockchained.github.io/advanced-homeassitant-mcp/api/core/ - 2025-02-05 + https://jango-blockchained.github.io/advanced-homeassistant-mcp/usage.html + 2025-02-06 - https://jango-blockchained.github.io/advanced-homeassitant-mcp/api/sse/ - 2025-02-05 + https://jango-blockchained.github.io/advanced-homeassistant-mcp/api/index.html + 2025-02-06 - https://jango-blockchained.github.io/advanced-homeassitant-mcp/development/best-practices/ - 2025-02-05 + https://jango-blockchained.github.io/advanced-homeassistant-mcp/api/core.html + 2025-02-06 - https://jango-blockchained.github.io/advanced-homeassitant-mcp/development/development/ - 2025-02-05 + https://jango-blockchained.github.io/advanced-homeassistant-mcp/api/sse.html + 2025-02-06 - https://jango-blockchained.github.io/advanced-homeassitant-mcp/development/interfaces/ - 2025-02-05 + https://jango-blockchained.github.io/advanced-homeassistant-mcp/config/index.html + 2025-02-06 - https://jango-blockchained.github.io/advanced-homeassitant-mcp/development/test-migration-guide/ - 2025-02-05 + https://jango-blockchained.github.io/advanced-homeassistant-mcp/development/index.html + 2025-02-06 - https://jango-blockchained.github.io/advanced-homeassitant-mcp/development/tools/ - 2025-02-05 + https://jango-blockchained.github.io/advanced-homeassistant-mcp/development/best-practices.html + 2025-02-06 - https://jango-blockchained.github.io/advanced-homeassitant-mcp/examples/ - 2025-02-05 + https://jango-blockchained.github.io/advanced-homeassistant-mcp/development/environment.html + 2025-02-06 - https://jango-blockchained.github.io/advanced-homeassitant-mcp/getting-started/configuration/ - 2025-02-05 + https://jango-blockchained.github.io/advanced-homeassistant-mcp/development/interfaces.html + 2025-02-06 - https://jango-blockchained.github.io/advanced-homeassitant-mcp/getting-started/docker/ - 2025-02-05 + https://jango-blockchained.github.io/advanced-homeassistant-mcp/development/test-migration-guide.html + 2025-02-06 - https://jango-blockchained.github.io/advanced-homeassitant-mcp/getting-started/installation/ - 2025-02-05 + https://jango-blockchained.github.io/advanced-homeassistant-mcp/development/tools.html + 2025-02-06 - https://jango-blockchained.github.io/advanced-homeassitant-mcp/getting-started/quickstart/ - 2025-02-05 + https://jango-blockchained.github.io/advanced-homeassistant-mcp/examples/index.html + 2025-02-06 - https://jango-blockchained.github.io/advanced-homeassitant-mcp/tools/tools/ - 2025-02-05 + https://jango-blockchained.github.io/advanced-homeassistant-mcp/getting-started/index.html + 2025-02-06 - https://jango-blockchained.github.io/advanced-homeassitant-mcp/tools/addons-packages/addon/ - 2025-02-05 + https://jango-blockchained.github.io/advanced-homeassistant-mcp/getting-started/configuration.html + 2025-02-06 - https://jango-blockchained.github.io/advanced-homeassitant-mcp/tools/addons-packages/package/ - 2025-02-05 + https://jango-blockchained.github.io/advanced-homeassistant-mcp/getting-started/docker.html + 2025-02-06 - https://jango-blockchained.github.io/advanced-homeassitant-mcp/tools/automation/automation-config/ - 2025-02-05 + https://jango-blockchained.github.io/advanced-homeassistant-mcp/getting-started/installation.html + 2025-02-06 - https://jango-blockchained.github.io/advanced-homeassitant-mcp/tools/automation/automation/ - 2025-02-05 + https://jango-blockchained.github.io/advanced-homeassistant-mcp/getting-started/quickstart.html + 2025-02-06 - https://jango-blockchained.github.io/advanced-homeassitant-mcp/tools/device-management/control/ - 2025-02-05 + https://jango-blockchained.github.io/advanced-homeassistant-mcp/tools/index.html + 2025-02-06 - https://jango-blockchained.github.io/advanced-homeassitant-mcp/tools/device-management/list-devices/ - 2025-02-05 + https://jango-blockchained.github.io/advanced-homeassistant-mcp/tools/addons-packages/addon.html + 2025-02-06 - https://jango-blockchained.github.io/advanced-homeassitant-mcp/tools/events/sse-stats/ - 2025-02-05 + https://jango-blockchained.github.io/advanced-homeassistant-mcp/tools/addons-packages/package.html + 2025-02-06 - https://jango-blockchained.github.io/advanced-homeassitant-mcp/tools/events/subscribe-events/ - 2025-02-05 + https://jango-blockchained.github.io/advanced-homeassistant-mcp/tools/automation/automation-config.html + 2025-02-06 - https://jango-blockchained.github.io/advanced-homeassitant-mcp/tools/history-state/history/ - 2025-02-05 + https://jango-blockchained.github.io/advanced-homeassistant-mcp/tools/automation/automation.html + 2025-02-06 - https://jango-blockchained.github.io/advanced-homeassitant-mcp/tools/history-state/scene/ - 2025-02-05 + https://jango-blockchained.github.io/advanced-homeassistant-mcp/tools/device-management/control.html + 2025-02-06 - https://jango-blockchained.github.io/advanced-homeassitant-mcp/tools/notifications/notify/ - 2025-02-05 + https://jango-blockchained.github.io/advanced-homeassistant-mcp/tools/device-management/list-devices.html + 2025-02-06 + + + https://jango-blockchained.github.io/advanced-homeassistant-mcp/tools/events/sse-stats.html + 2025-02-06 + + + https://jango-blockchained.github.io/advanced-homeassistant-mcp/tools/events/subscribe-events.html + 2025-02-06 + + + https://jango-blockchained.github.io/advanced-homeassistant-mcp/tools/history-state/history.html + 2025-02-06 + + + https://jango-blockchained.github.io/advanced-homeassistant-mcp/tools/history-state/scene.html + 2025-02-06 + + + https://jango-blockchained.github.io/advanced-homeassistant-mcp/tools/notifications/notify.html + 2025-02-06 \ No newline at end of file diff --git a/sitemap.xml.gz b/sitemap.xml.gz index df5aab3c4fad3bbe45b67acf27358beb87f7fc23..fe29794962ff7c9fd646cd6e3bff50874a3bf27f 100644 GIT binary patch literal 538 zcmV+#0_FW5iwFpS`=e(9|8r?{Wo=<_E_iKh0M(e?uG26K$M4TmOuJ7zCV>ELJ9j(* zJV2UwZCDzY*xAS1`8bYC2AzZs(>e4dTb7Dc zi^w^2h2@awB=j&ve2kD-CtpVEMIdy-5x9~AKXlSDklwoEjHQb}1EOBYLbeCBeM5O$ z6YFvvZ)&N63+bR+}H$^js zew`XkUxJ4Us1c*m`Gl>2)_Y83ChIOT<3H`1fS(K1$c1rSj@Fx{Srx51Zq2|lD#%!CMw_G} zmVsgU@r1E1=qP*4>L$(PGMFW%`35&U12$E>fn0dnadE{ z%;44WWwd@CF>PE7q_Ur!v2+n=KvcqGdMEbZqTp{8#LgJ>A@ibGm zj)MbIjr!i!%o!3xK3nbOoENhhL!T{+)H8hvUiVRD#Hg>N@Mgy;D(v;|f<@HTIrL?1 zw|ZJH??YCP8Io8r-bYQpmf$Xnqfd=3v#oQ&S1Rj0CNh(C7ZGNge Testing - MCP Server for Home Assistant

Testing Documentation

Quick Reference

# Most Common Commands
+bun test                    # Run all tests
+bun test --watch           # Run tests in watch mode
+bun test --coverage        # Run tests with coverage
+bun test path/to/test.ts   # Run a specific test file
+
+# Additional Options
+DEBUG=true bun test        # Run with debug output
+bun test --pattern "auth"  # Run tests matching a pattern
+bun test --timeout 60000   # Run with a custom timeout
+

Overview

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.

Test Structure

Tests are organized in two main locations:

  1. Root Level Integration Tests (/__tests__/):
__tests__/
+├── ai/              # AI/ML component tests
+├── api/             # API integration tests
+├── context/         # Context management tests
+├── hass/            # Home Assistant integration tests
+├── schemas/         # Schema validation tests
+├── security/        # Security integration tests
+├── tools/           # Tools and utilities tests
+├── websocket/       # WebSocket integration tests
+├── helpers.test.ts  # Helper function tests
+├── index.test.ts    # Main application tests
+└── server.test.ts   # Server integration tests
+
  1. Component Level Unit Tests (src/**/):
src/
+├── __tests__/   # Global test setup and utilities
+│   └── setup.ts # Global test configuration
+├── component/
+│   ├── __tests__/   # Component-specific unit tests
+│   └── component.ts
+

Test Configuration

Bun Test Configuration (bunfig.toml)

[test]
+preload = ["./src/__tests__/setup.ts"]  # Global test setup
+coverage = true                         # Enable coverage by default
+timeout = 30000                         # Test timeout in milliseconds
+testMatch = ["**/__tests__/**/*.test.ts"] # Test file patterns
+

Bun Scripts

Available test commands in package.json:

# Run all tests
+bun test
+
+# Watch mode for development
+bun test --watch
+
+# Generate coverage report
+bun test --coverage
+
+# Run linting
+bun run lint
+
+# Format code
+bun run format
+

Test Setup

Global Configuration

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

Test Environment

  • Environment variables are loaded from .env.test.
  • Console output is minimized unless DEBUG=true.
  • JWT secrets and tokens are preconfigured for testing.
  • Rate limiting and security features are initialized appropriately.

Running Tests

# Basic test run
+bun test
+
+# Run tests with coverage
+bun test --coverage
+
+# Run a specific test file
+bun test path/to/test.test.ts
+
+# Run tests in watch mode
+bun test --watch
+
+# Run tests with debug output
+DEBUG=true bun test
+
+# Run tests with increased timeout
+bun test --timeout 60000
+
+# Run tests matching a pattern
+bun test --pattern "auth"
+

Advanced Debugging

Using Node Inspector

# Start tests with inspector
+bun test --inspect
+
+# Start tests with inspector and break on first line
+bun test --inspect-brk
+

Using VS Code

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

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

Test Isolation

To run a single test in isolation:

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

Writing Tests

Test File Naming

  • Place test files in a __tests__ directory adjacent to the code being tested.
  • Name files with the pattern *.test.ts.
  • Mirror the structure of the source code in your test organization.

Example Test Structure

describe("Security Features", () => {
+  it("should validate tokens correctly", () => {
+    const payload = { userId: "123", role: "user" };
+    const token = jwt.sign(payload, validSecret, { expiresIn: "1h" });
+    const result = TokenManager.validateToken(token, testIp);
+    expect(result.valid).toBe(true);
+  });
+});
+

Coverage

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

Generate a coverage report with:

bun test --coverage
+

Security Middleware Testing

Utility Function Testing

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.

Key Utility Functions

  1. Rate Limiting (checkRateLimit)
  2. Tests multiple scenarios:
    • Requests under threshold
    • Requests exceeding threshold
    • Rate limit reset after window expiration
// Example test
+it('should throw when requests exceed threshold', () => {
+  const ip = '127.0.0.2';
+  for (let i = 0; i < 11; i++) {
+    if (i < 10) {
+      expect(() => checkRateLimit(ip, 10)).not.toThrow();
+    } else {
+      expect(() => checkRateLimit(ip, 10)).toThrow('Too many requests from this IP');
+    }
+  }
+});
+
  1. Request Validation (validateRequestHeaders)
  2. Tests content type validation
  3. Checks request size limits
  4. Validates authorization headers
it('should reject invalid content type', () => {
+  const mockRequest = new Request('http://localhost', {
+    method: 'POST',
+    headers: { 'content-type': 'text/plain' }
+  });
+  expect(() => validateRequestHeaders(mockRequest)).toThrow('Content-Type must be application/json');
+});
+
  1. Input Sanitization (sanitizeValue)
  2. Sanitizes HTML tags
  3. Handles nested objects
  4. Preserves non-string values
it('should sanitize HTML tags', () => {
+  const input = '<script>alert("xss")</script>Hello';
+  const sanitized = sanitizeValue(input);
+  expect(sanitized).toBe('&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;Hello');
+});
+
  1. Security Headers (applySecurityHeaders)
  2. Verifies correct security header application
  3. Checks CSP, frame options, and other security headers
it('should apply security headers', () => {
+  const mockRequest = new Request('http://localhost');
+  const headers = applySecurityHeaders(mockRequest);
+  expect(headers['content-security-policy']).toBeDefined();
+  expect(headers['x-frame-options']).toBeDefined();
+});
+
  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', () => {
+  const error = new Error('Test error');
+  const result = handleError(error, 'development');
+  expect(result).toEqual({
+    error: true,
+    message: 'Internal server error',
+    error: 'Test error',
+    stack: expect.any(String)
+  });
+});
+

Testing Philosophy

  • Isolation: Each utility function is tested independently
  • Comprehensive Coverage: Multiple scenarios for each function
  • Predictable Behavior: Clear expectations for input and output
  • Error Handling: Robust testing of error conditions

Best Practices

  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

Running Security Tests

# Run all tests
+bun test
+
+# Run specific security tests
+bun test __tests__/security/
+

Continuous Improvement

  • Regularly update test cases
  • Add new test scenarios as security requirements evolve
  • Perform periodic security audits

Best Practices

  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.

Coverage

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
+

Debugging Tests

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

Advanced Debugging

  1. Using Node Inspector:

    # Start tests with inspector
    +bun test --inspect
    +
    +# Start tests with inspector and break on first line
    +bun test --inspect-brk
    +

  2. Using VS Code:

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

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

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

Contributing

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

Coverage Requirements

The project maintains strict coverage requirements:

  • Minimum overall coverage: 80%
  • Critical paths (security, API, data validation): 90%
  • New features must include tests with >= 85% coverage

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
+bun test --coverage && open coverage/index.html
+

\ No newline at end of file diff --git a/testing/index.html b/testing/index.html deleted file mode 100644 index 8f456e1..0000000 --- a/testing/index.html +++ /dev/null @@ -1,2835 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - Testing Guide - Advanced Home Assistant MCP - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
- - - - - - -
- - -
- -
- - - - - - -
-
- - - -
-
-
- - - - - -
-
-
- - - - - - - -
-
- - - - - - - - -

Testing Documentation

-

Quick Reference

-
# Most Common Commands
-bun test                    # Run all tests
-bun test --watch           # Run tests in watch mode
-bun test --coverage        # Run tests with coverage
-bun test path/to/test.ts   # Run a specific test file
-
-# Additional Options
-DEBUG=true bun test        # Run with debug output
-bun test --pattern "auth"  # Run tests matching a pattern
-bun test --timeout 60000   # Run with a custom timeout
-
-

Overview

-

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.

-

Test Structure

-

Tests are organized in two main locations:

-
    -
  1. Root Level Integration Tests (/__tests__/):
  2. -
-
__tests__/
-├── ai/              # AI/ML component tests
-├── api/             # API integration tests
-├── context/         # Context management tests
-├── hass/            # Home Assistant integration tests
-├── schemas/         # Schema validation tests
-├── security/        # Security integration tests
-├── tools/           # Tools and utilities tests
-├── websocket/       # WebSocket integration tests
-├── helpers.test.ts  # Helper function tests
-├── index.test.ts    # Main application tests
-└── server.test.ts   # Server integration tests
-
-
    -
  1. Component Level Unit Tests (src/**/):
  2. -
-
src/
-├── __tests__/   # Global test setup and utilities
-│   └── setup.ts # Global test configuration
-├── component/
-│   ├── __tests__/   # Component-specific unit tests
-│   └── component.ts
-
-

Test Configuration

-

Bun Test Configuration (bunfig.toml)

-
[test]
-preload = ["./src/__tests__/setup.ts"]  # Global test setup
-coverage = true                         # Enable coverage by default
-timeout = 30000                         # Test timeout in milliseconds
-testMatch = ["**/__tests__/**/*.test.ts"] # Test file patterns
-
-

Bun Scripts

-

Available test commands in package.json:

-
# Run all tests
-bun test
-
-# Watch mode for development
-bun test --watch
-
-# Generate coverage report
-bun test --coverage
-
-# Run linting
-bun run lint
-
-# Format code
-bun run format
-
-

Test Setup

-

Global Configuration

-

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

-

Test Environment

-
    -
  • Environment variables are loaded from .env.test.
  • -
  • Console output is minimized unless DEBUG=true.
  • -
  • JWT secrets and tokens are preconfigured for testing.
  • -
  • Rate limiting and security features are initialized appropriately.
  • -
-

Running Tests

-
# Basic test run
-bun test
-
-# Run tests with coverage
-bun test --coverage
-
-# Run a specific test file
-bun test path/to/test.test.ts
-
-# Run tests in watch mode
-bun test --watch
-
-# Run tests with debug output
-DEBUG=true bun test
-
-# Run tests with increased timeout
-bun test --timeout 60000
-
-# Run tests matching a pattern
-bun test --pattern "auth"
-
-

Advanced Debugging

-

Using Node Inspector

-
# Start tests with inspector
-bun test --inspect
-
-# Start tests with inspector and break on first line
-bun test --inspect-brk
-
-

Using VS Code

-

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

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

Test Isolation

-

To run a single test in isolation:

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

Writing Tests

-

Test File Naming

-
    -
  • Place test files in a __tests__ directory adjacent to the code being tested.
  • -
  • Name files with the pattern *.test.ts.
  • -
  • Mirror the structure of the source code in your test organization.
  • -
-

Example Test Structure

-
describe("Security Features", () => {
-  it("should validate tokens correctly", () => {
-    const payload = { userId: "123", role: "user" };
-    const token = jwt.sign(payload, validSecret, { expiresIn: "1h" });
-    const result = TokenManager.validateToken(token, testIp);
-    expect(result.valid).toBe(true);
-  });
-});
-
-

Coverage

-

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

-

Generate a coverage report with:

-
bun test --coverage
-
-

Security Middleware Testing

-

Utility Function Testing

-

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.

-

Key Utility Functions

-
    -
  1. Rate Limiting (checkRateLimit)
  2. -
  3. Tests multiple scenarios:
      -
    • Requests under threshold
    • -
    • Requests exceeding threshold
    • -
    • Rate limit reset after window expiration
    • -
    -
  4. -
-
// Example test
-it('should throw when requests exceed threshold', () => {
-  const ip = '127.0.0.2';
-  for (let i = 0; i < 11; i++) {
-    if (i < 10) {
-      expect(() => checkRateLimit(ip, 10)).not.toThrow();
-    } else {
-      expect(() => checkRateLimit(ip, 10)).toThrow('Too many requests from this IP');
-    }
-  }
-});
-
-
    -
  1. Request Validation (validateRequestHeaders)
  2. -
  3. Tests content type validation
  4. -
  5. Checks request size limits
  6. -
  7. Validates authorization headers
  8. -
-
it('should reject invalid content type', () => {
-  const mockRequest = new Request('http://localhost', {
-    method: 'POST',
-    headers: { 'content-type': 'text/plain' }
-  });
-  expect(() => validateRequestHeaders(mockRequest)).toThrow('Content-Type must be application/json');
-});
-
-
    -
  1. Input Sanitization (sanitizeValue)
  2. -
  3. Sanitizes HTML tags
  4. -
  5. Handles nested objects
  6. -
  7. Preserves non-string values
  8. -
-
it('should sanitize HTML tags', () => {
-  const input = '<script>alert("xss")</script>Hello';
-  const sanitized = sanitizeValue(input);
-  expect(sanitized).toBe('&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;Hello');
-});
-
-
    -
  1. Security Headers (applySecurityHeaders)
  2. -
  3. Verifies correct security header application
  4. -
  5. Checks CSP, frame options, and other security headers
  6. -
-
it('should apply security headers', () => {
-  const mockRequest = new Request('http://localhost');
-  const headers = applySecurityHeaders(mockRequest);
-  expect(headers['content-security-policy']).toBeDefined();
-  expect(headers['x-frame-options']).toBeDefined();
-});
-
-
    -
  1. Error Handling (handleError)
  2. -
  3. Tests error responses in production and development modes
  4. -
  5. Verifies error message and stack trace inclusion
  6. -
-
it('should include error details in development mode', () => {
-  const error = new Error('Test error');
-  const result = handleError(error, 'development');
-  expect(result).toEqual({
-    error: true,
-    message: 'Internal server error',
-    error: 'Test error',
-    stack: expect.any(String)
-  });
-});
-
-

Testing Philosophy

-
    -
  • Isolation: Each utility function is tested independently
  • -
  • Comprehensive Coverage: Multiple scenarios for each function
  • -
  • Predictable Behavior: Clear expectations for input and output
  • -
  • Error Handling: Robust testing of error conditions
  • -
-

Best Practices

-
    -
  1. Use minimal, focused test cases
  2. -
  3. Test both successful and failure scenarios
  4. -
  5. Verify input sanitization and security measures
  6. -
  7. Mock external dependencies when necessary
  8. -
-

Running Security Tests

-
# Run all tests
-bun test
-
-# Run specific security tests
-bun test __tests__/security/
-
-

Continuous Improvement

-
    -
  • Regularly update test cases
  • -
  • Add new test scenarios as security requirements evolve
  • -
  • Perform periodic security audits
  • -
-

Best Practices

-
    -
  1. Isolation: Each test should be independent and not rely on the state of other tests.
  2. -
  3. Mocking: Use the provided mock utilities for external dependencies.
  4. -
  5. Cleanup: Clean up any resources or state modifications in afterEach or afterAll hooks.
  6. -
  7. Descriptive Names: Use clear, descriptive test names that explain the expected behavior.
  8. -
  9. Assertions: Make specific, meaningful assertions rather than general ones.
  10. -
  11. Setup: Use beforeEach for common test setup to avoid repetition.
  12. -
  13. Error Cases: Test both success and error cases for complete coverage.
  14. -
-

Coverage

-

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
-

-

Debugging Tests

-

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

-

Advanced Debugging

-
    -
  1. -

    Using Node Inspector: -

    # Start tests with inspector
    -bun test --inspect
    -
    -# Start tests with inspector and break on first line
    -bun test --inspect-brk
    -

    -
  2. -
  3. -

    Using VS Code: -

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

    -
  4. -
  5. -

    Test Isolation: - To run a single test in isolation: -

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

    -
  6. -
-

Contributing

-

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

-

Coverage Requirements

-

The project maintains strict coverage requirements:

-
    -
  • Minimum overall coverage: 80%
  • -
  • Critical paths (security, API, data validation): 90%
  • -
  • New features must include tests with >= 85% coverage
  • -
-

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
-bun test --coverage && open coverage/index.html
-

- - - - - - - - - - - - - - - - - - - - - - -
-
- - - -
- - - -
- - - -
-
-
-
- - - - - - - - - - - - \ No newline at end of file diff --git a/tools/addons-packages/addon.html b/tools/addons-packages/addon.html new file mode 100644 index 0000000..d2c478c --- /dev/null +++ b/tools/addons-packages/addon.html @@ -0,0 +1,133 @@ + Add-on Management - MCP Server for Home Assistant

Add-on Management Tool

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

Features

  • List available add-ons
  • Install/uninstall add-ons
  • Start/stop/restart add-ons
  • Get add-on information
  • Update add-ons
  • Configure add-ons
  • View add-on logs
  • Monitor add-on status

Usage

REST API

GET /api/addons
+GET /api/addons/{addon_slug}
+POST /api/addons/{addon_slug}/install
+POST /api/addons/{addon_slug}/uninstall
+POST /api/addons/{addon_slug}/start
+POST /api/addons/{addon_slug}/stop
+POST /api/addons/{addon_slug}/restart
+GET /api/addons/{addon_slug}/logs
+PUT /api/addons/{addon_slug}/config
+GET /api/addons/{addon_slug}/stats
+

WebSocket

// List add-ons
+{
+    "type": "get_addons"
+}
+
+// Get add-on info
+{
+    "type": "get_addon_info",
+    "addon_slug": "required_addon_slug"
+}
+
+// Install add-on
+{
+    "type": "install_addon",
+    "addon_slug": "required_addon_slug",
+    "version": "optional_version"
+}
+
+// Control add-on
+{
+    "type": "control_addon",
+    "addon_slug": "required_addon_slug",
+    "action": "start|stop|restart"
+}
+

Examples

List All Add-ons

const response = await fetch('http://your-ha-mcp/api/addons', {
+    headers: {
+        'Authorization': 'Bearer your_access_token'
+    }
+});
+const addons = await response.json();
+

Install Add-on

const response = await fetch('http://your-ha-mcp/api/addons/mosquitto/install', {
+    method: 'POST',
+    headers: {
+        'Authorization': 'Bearer your_access_token',
+        'Content-Type': 'application/json'
+    },
+    body: JSON.stringify({
+        "version": "latest"
+    })
+});
+

Configure Add-on

const response = await fetch('http://your-ha-mcp/api/addons/mosquitto/config', {
+    method: 'PUT',
+    headers: {
+        'Authorization': 'Bearer your_access_token',
+        'Content-Type': 'application/json'
+    },
+    body: JSON.stringify({
+        "logins": [
+            {
+                "username": "mqtt_user",
+                "password": "mqtt_password"
+            }
+        ],
+        "customize": {
+            "active": true,
+            "folder": "mosquitto"
+        }
+    })
+});
+

Response Format

Add-on List Response

{
+    "success": true,
+    "data": {
+        "addons": [
+            {
+                "slug": "addon_slug",
+                "name": "Add-on Name",
+                "version": "1.0.0",
+                "state": "started",
+                "repository": "core",
+                "installed": true,
+                "update_available": false
+            }
+        ]
+    }
+}
+

Add-on Info Response

{
+    "success": true,
+    "data": {
+        "addon": {
+            "slug": "addon_slug",
+            "name": "Add-on Name",
+            "version": "1.0.0",
+            "description": "Add-on description",
+            "long_description": "Detailed description",
+            "repository": "core",
+            "installed": true,
+            "state": "started",
+            "webui": "http://[HOST]:[PORT:80]",
+            "boot": "auto",
+            "options": {
+                // Add-on specific options
+            },
+            "schema": {
+                // Add-on options schema
+            },
+            "ports": {
+                "80/tcp": 8080
+            },
+            "ingress": true,
+            "ingress_port": 8099
+        }
+    }
+}
+

Add-on Stats Response

{
+    "success": true,
+    "data": {
+        "stats": {
+            "cpu_percent": 2.5,
+            "memory_usage": 128974848,
+            "memory_limit": 536870912,
+            "network_rx": 1234,
+            "network_tx": 5678,
+            "blk_read": 12345,
+            "blk_write": 67890
+        }
+    }
+}
+

Error Handling

Common Error Codes

  • 404: Add-on not found
  • 401: Unauthorized
  • 400: Invalid request
  • 409: Add-on operation failed
  • 422: Invalid configuration

Error Response Format

{
+    "success": false,
+    "message": "Error description",
+    "error_code": "ERROR_CODE"
+}
+

Rate Limiting

  • Default limit: 50 requests per 15 minutes
  • Configurable through environment variables:
  • ADDON_RATE_LIMIT
  • ADDON_RATE_WINDOW

Best Practices

  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

Add-on Security

  • Use secure passwords
  • Regularly update add-ons
  • Monitor add-on logs
  • Restrict network access
  • Use SSL/TLS when available
  • Follow principle of least privilege

See Also

\ No newline at end of file diff --git a/tools/addons-packages/addon/index.html b/tools/addons-packages/addon/index.html deleted file mode 100644 index ec09b1e..0000000 --- a/tools/addons-packages/addon/index.html +++ /dev/null @@ -1,2434 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - Add-on Management - Advanced Home Assistant MCP - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
- - - - - - -
- - -
- -
- - - - - - -
-
- - - -
-
-
- - - - - -
-
-
- - - - - - - -
-
- - - - - - - - -

Add-on Management Tool

-

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

-

Features

-
    -
  • List available add-ons
  • -
  • Install/uninstall add-ons
  • -
  • Start/stop/restart add-ons
  • -
  • Get add-on information
  • -
  • Update add-ons
  • -
  • Configure add-ons
  • -
  • View add-on logs
  • -
  • Monitor add-on status
  • -
-

Usage

-

REST API

-
GET /api/addons
-GET /api/addons/{addon_slug}
-POST /api/addons/{addon_slug}/install
-POST /api/addons/{addon_slug}/uninstall
-POST /api/addons/{addon_slug}/start
-POST /api/addons/{addon_slug}/stop
-POST /api/addons/{addon_slug}/restart
-GET /api/addons/{addon_slug}/logs
-PUT /api/addons/{addon_slug}/config
-GET /api/addons/{addon_slug}/stats
-
-

WebSocket

-
// List add-ons
-{
-    "type": "get_addons"
-}
-
-// Get add-on info
-{
-    "type": "get_addon_info",
-    "addon_slug": "required_addon_slug"
-}
-
-// Install add-on
-{
-    "type": "install_addon",
-    "addon_slug": "required_addon_slug",
-    "version": "optional_version"
-}
-
-// Control add-on
-{
-    "type": "control_addon",
-    "addon_slug": "required_addon_slug",
-    "action": "start|stop|restart"
-}
-
-

Examples

-

List All Add-ons

-
const response = await fetch('http://your-ha-mcp/api/addons', {
-    headers: {
-        'Authorization': 'Bearer your_access_token'
-    }
-});
-const addons = await response.json();
-
-

Install Add-on

-
const response = await fetch('http://your-ha-mcp/api/addons/mosquitto/install', {
-    method: 'POST',
-    headers: {
-        'Authorization': 'Bearer your_access_token',
-        'Content-Type': 'application/json'
-    },
-    body: JSON.stringify({
-        "version": "latest"
-    })
-});
-
-

Configure Add-on

-
const response = await fetch('http://your-ha-mcp/api/addons/mosquitto/config', {
-    method: 'PUT',
-    headers: {
-        'Authorization': 'Bearer your_access_token',
-        'Content-Type': 'application/json'
-    },
-    body: JSON.stringify({
-        "logins": [
-            {
-                "username": "mqtt_user",
-                "password": "mqtt_password"
-            }
-        ],
-        "customize": {
-            "active": true,
-            "folder": "mosquitto"
-        }
-    })
-});
-
-

Response Format

-

Add-on List Response

-
{
-    "success": true,
-    "data": {
-        "addons": [
-            {
-                "slug": "addon_slug",
-                "name": "Add-on Name",
-                "version": "1.0.0",
-                "state": "started",
-                "repository": "core",
-                "installed": true,
-                "update_available": false
-            }
-        ]
-    }
-}
-
-

Add-on Info Response

-
{
-    "success": true,
-    "data": {
-        "addon": {
-            "slug": "addon_slug",
-            "name": "Add-on Name",
-            "version": "1.0.0",
-            "description": "Add-on description",
-            "long_description": "Detailed description",
-            "repository": "core",
-            "installed": true,
-            "state": "started",
-            "webui": "http://[HOST]:[PORT:80]",
-            "boot": "auto",
-            "options": {
-                // Add-on specific options
-            },
-            "schema": {
-                // Add-on options schema
-            },
-            "ports": {
-                "80/tcp": 8080
-            },
-            "ingress": true,
-            "ingress_port": 8099
-        }
-    }
-}
-
-

Add-on Stats Response

-
{
-    "success": true,
-    "data": {
-        "stats": {
-            "cpu_percent": 2.5,
-            "memory_usage": 128974848,
-            "memory_limit": 536870912,
-            "network_rx": 1234,
-            "network_tx": 5678,
-            "blk_read": 12345,
-            "blk_write": 67890
-        }
-    }
-}
-
-

Error Handling

-

Common Error Codes

-
    -
  • 404: Add-on not found
  • -
  • 401: Unauthorized
  • -
  • 400: Invalid request
  • -
  • 409: Add-on operation failed
  • -
  • 422: Invalid configuration
  • -
-

Error Response Format

-
{
-    "success": false,
-    "message": "Error description",
-    "error_code": "ERROR_CODE"
-}
-
-

Rate Limiting

-
    -
  • Default limit: 50 requests per 15 minutes
  • -
  • Configurable through environment variables:
  • -
  • ADDON_RATE_LIMIT
  • -
  • ADDON_RATE_WINDOW
  • -
-

Best Practices

-
    -
  1. Always check add-on compatibility
  2. -
  3. Back up configurations before updates
  4. -
  5. Monitor resource usage
  6. -
  7. Use appropriate update strategies
  8. -
  9. Implement proper error handling
  10. -
  11. Test configurations in safe environment
  12. -
  13. Handle rate limiting gracefully
  14. -
  15. Keep add-ons updated
  16. -
-

Add-on Security

-
    -
  • Use secure passwords
  • -
  • Regularly update add-ons
  • -
  • Monitor add-on logs
  • -
  • Restrict network access
  • -
  • Use SSL/TLS when available
  • -
  • Follow principle of least privilege
  • -
-

See Also

- - - - - - - - - - - - - - - - - - - - - - - -
-
- - - -
- - - -
- - - -
-
-
-
- - - - - - - - - - - - \ No newline at end of file diff --git a/tools/addons-packages/package.html b/tools/addons-packages/package.html new file mode 100644 index 0000000..8815504 --- /dev/null +++ b/tools/addons-packages/package.html @@ -0,0 +1,118 @@ + Package Management - MCP Server for Home Assistant

Package Management Tool

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

Features

  • List available packages
  • Install/update/remove packages
  • Search packages
  • Get package information
  • Manage package repositories
  • Track package updates
  • View package documentation
  • Monitor package status

Usage

REST API

GET /api/packages
+GET /api/packages/{package_id}
+POST /api/packages/{package_id}/install
+POST /api/packages/{package_id}/uninstall
+POST /api/packages/{package_id}/update
+GET /api/packages/search
+GET /api/packages/categories
+GET /api/packages/repositories
+

WebSocket

// List packages
+{
+    "type": "get_packages",
+    "category": "optional_category"
+}
+
+// Search packages
+{
+    "type": "search_packages",
+    "query": "search_query",
+    "category": "optional_category"
+}
+
+// Install package
+{
+    "type": "install_package",
+    "package_id": "required_package_id",
+    "version": "optional_version"
+}
+

Package Categories

  • Integrations
  • Frontend
  • Themes
  • AppDaemon Apps
  • NetDaemon Apps
  • Python Scripts
  • Plugins

Examples

List All Packages

const response = await fetch('http://your-ha-mcp/api/packages', {
+    headers: {
+        'Authorization': 'Bearer your_access_token'
+    }
+});
+const packages = await response.json();
+

Search Packages

const response = await fetch('http://your-ha-mcp/api/packages/search?q=weather&category=integrations', {
+    headers: {
+        'Authorization': 'Bearer your_access_token'
+    }
+});
+const searchResults = await response.json();
+

Install Package

const response = await fetch('http://your-ha-mcp/api/packages/custom-weather-card/install', {
+    method: 'POST',
+    headers: {
+        'Authorization': 'Bearer your_access_token',
+        'Content-Type': 'application/json'
+    },
+    body: JSON.stringify({
+        "version": "latest"
+    })
+});
+

Response Format

Package List Response

{
+    "success": true,
+    "data": {
+        "packages": [
+            {
+                "id": "package_id",
+                "name": "Package Name",
+                "category": "integrations",
+                "description": "Package description",
+                "version": "1.0.0",
+                "installed": true,
+                "update_available": false,
+                "stars": 150,
+                "downloads": 10000
+            }
+        ]
+    }
+}
+

Package Info Response

{
+    "success": true,
+    "data": {
+        "package": {
+            "id": "package_id",
+            "name": "Package Name",
+            "category": "integrations",
+            "description": "Package description",
+            "long_description": "Detailed description",
+            "version": "1.0.0",
+            "installed_version": "0.9.0",
+            "available_version": "1.0.0",
+            "installed": true,
+            "update_available": true,
+            "stars": 150,
+            "downloads": 10000,
+            "repository": "https://github.com/author/repo",
+            "author": {
+                "name": "Author Name",
+                "url": "https://github.com/author"
+            },
+            "documentation": "https://github.com/author/repo/wiki",
+            "dependencies": [
+                "dependency1",
+                "dependency2"
+            ]
+        }
+    }
+}
+

Search Response

{
+    "success": true,
+    "data": {
+        "results": [
+            {
+                "id": "package_id",
+                "name": "Package Name",
+                "category": "integrations",
+                "description": "Package description",
+                "version": "1.0.0",
+                "score": 0.95
+            }
+        ],
+        "total": 42
+    }
+}
+

Error Handling

Common Error Codes

  • 404: Package not found
  • 401: Unauthorized
  • 400: Invalid request
  • 409: Package operation failed
  • 422: Invalid configuration
  • 424: Dependency error

Error Response Format

{
+    "success": false,
+    "message": "Error description",
+    "error_code": "ERROR_CODE"
+}
+

Rate Limiting

  • Default limit: 50 requests per 15 minutes
  • Configurable through environment variables:
  • PACKAGE_RATE_LIMIT
  • PACKAGE_RATE_WINDOW

Best Practices

  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

Package Security

  • Verify package sources
  • Review package permissions
  • Check package reputation
  • Monitor package activity
  • Keep dependencies updated
  • Follow security advisories

See Also

\ No newline at end of file diff --git a/tools/addons-packages/package/index.html b/tools/addons-packages/package/index.html deleted file mode 100644 index 4eae1e9..0000000 --- a/tools/addons-packages/package/index.html +++ /dev/null @@ -1,2448 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - Package Management - Advanced Home Assistant MCP - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
- - - - - - -
- - -
- -
- - - - - - -
-
- - - -
-
-
- - - - - -
-
-
- - - - - - - -
-
- - - - - - - - -

Package Management Tool

-

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

-

Features

-
    -
  • List available packages
  • -
  • Install/update/remove packages
  • -
  • Search packages
  • -
  • Get package information
  • -
  • Manage package repositories
  • -
  • Track package updates
  • -
  • View package documentation
  • -
  • Monitor package status
  • -
-

Usage

-

REST API

-
GET /api/packages
-GET /api/packages/{package_id}
-POST /api/packages/{package_id}/install
-POST /api/packages/{package_id}/uninstall
-POST /api/packages/{package_id}/update
-GET /api/packages/search
-GET /api/packages/categories
-GET /api/packages/repositories
-
-

WebSocket

-
// List packages
-{
-    "type": "get_packages",
-    "category": "optional_category"
-}
-
-// Search packages
-{
-    "type": "search_packages",
-    "query": "search_query",
-    "category": "optional_category"
-}
-
-// Install package
-{
-    "type": "install_package",
-    "package_id": "required_package_id",
-    "version": "optional_version"
-}
-
-

Package Categories

-
    -
  • Integrations
  • -
  • Frontend
  • -
  • Themes
  • -
  • AppDaemon Apps
  • -
  • NetDaemon Apps
  • -
  • Python Scripts
  • -
  • Plugins
  • -
-

Examples

-

List All Packages

-
const response = await fetch('http://your-ha-mcp/api/packages', {
-    headers: {
-        'Authorization': 'Bearer your_access_token'
-    }
-});
-const packages = await response.json();
-
-

Search Packages

-
const response = await fetch('http://your-ha-mcp/api/packages/search?q=weather&category=integrations', {
-    headers: {
-        'Authorization': 'Bearer your_access_token'
-    }
-});
-const searchResults = await response.json();
-
-

Install Package

-
const response = await fetch('http://your-ha-mcp/api/packages/custom-weather-card/install', {
-    method: 'POST',
-    headers: {
-        'Authorization': 'Bearer your_access_token',
-        'Content-Type': 'application/json'
-    },
-    body: JSON.stringify({
-        "version": "latest"
-    })
-});
-
-

Response Format

-

Package List Response

-
{
-    "success": true,
-    "data": {
-        "packages": [
-            {
-                "id": "package_id",
-                "name": "Package Name",
-                "category": "integrations",
-                "description": "Package description",
-                "version": "1.0.0",
-                "installed": true,
-                "update_available": false,
-                "stars": 150,
-                "downloads": 10000
-            }
-        ]
-    }
-}
-
-

Package Info Response

-
{
-    "success": true,
-    "data": {
-        "package": {
-            "id": "package_id",
-            "name": "Package Name",
-            "category": "integrations",
-            "description": "Package description",
-            "long_description": "Detailed description",
-            "version": "1.0.0",
-            "installed_version": "0.9.0",
-            "available_version": "1.0.0",
-            "installed": true,
-            "update_available": true,
-            "stars": 150,
-            "downloads": 10000,
-            "repository": "https://github.com/author/repo",
-            "author": {
-                "name": "Author Name",
-                "url": "https://github.com/author"
-            },
-            "documentation": "https://github.com/author/repo/wiki",
-            "dependencies": [
-                "dependency1",
-                "dependency2"
-            ]
-        }
-    }
-}
-
-

Search Response

-
{
-    "success": true,
-    "data": {
-        "results": [
-            {
-                "id": "package_id",
-                "name": "Package Name",
-                "category": "integrations",
-                "description": "Package description",
-                "version": "1.0.0",
-                "score": 0.95
-            }
-        ],
-        "total": 42
-    }
-}
-
-

Error Handling

-

Common Error Codes

-
    -
  • 404: Package not found
  • -
  • 401: Unauthorized
  • -
  • 400: Invalid request
  • -
  • 409: Package operation failed
  • -
  • 422: Invalid configuration
  • -
  • 424: Dependency error
  • -
-

Error Response Format

-
{
-    "success": false,
-    "message": "Error description",
-    "error_code": "ERROR_CODE"
-}
-
-

Rate Limiting

-
    -
  • Default limit: 50 requests per 15 minutes
  • -
  • Configurable through environment variables:
  • -
  • PACKAGE_RATE_LIMIT
  • -
  • PACKAGE_RATE_WINDOW
  • -
-

Best Practices

-
    -
  1. Check package compatibility
  2. -
  3. Review package documentation
  4. -
  5. Verify package dependencies
  6. -
  7. Back up before updates
  8. -
  9. Test in safe environment
  10. -
  11. Monitor resource usage
  12. -
  13. Keep packages updated
  14. -
  15. Handle rate limiting gracefully
  16. -
-

Package Security

-
    -
  • Verify package sources
  • -
  • Review package permissions
  • -
  • Check package reputation
  • -
  • Monitor package activity
  • -
  • Keep dependencies updated
  • -
  • Follow security advisories
  • -
-

See Also

- - - - - - - - - - - - - - - - - - - - - - - -
-
- - - -
- - - -
- - - -
-
-
-
- - - - - - - - - - - - \ No newline at end of file diff --git a/tools/automation/automation-config.html b/tools/automation/automation-config.html new file mode 100644 index 0000000..1302a24 --- /dev/null +++ b/tools/automation/automation-config.html @@ -0,0 +1,221 @@ + Automation Configuration - MCP Server for Home Assistant

Automation Configuration Tool

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

Features

  • Create new automations
  • Update existing automations
  • Delete automations
  • Duplicate automations
  • Import/Export automation configurations
  • Validate automation configurations

Usage

REST API

POST /api/automations
+PUT /api/automations/{automation_id}
+DELETE /api/automations/{automation_id}
+POST /api/automations/{automation_id}/duplicate
+POST /api/automations/validate
+

WebSocket

// Create automation
+{
+    "type": "create_automation",
+    "automation": {
+        // Automation configuration
+    }
+}
+
+// Update automation
+{
+    "type": "update_automation",
+    "automation_id": "required_automation_id",
+    "automation": {
+        // Updated configuration
+    }
+}
+
+// Delete automation
+{
+    "type": "delete_automation",
+    "automation_id": "required_automation_id"
+}
+

Automation Configuration

Basic Structure

{
+    "id": "morning_routine",
+    "alias": "Morning Routine",
+    "description": "Turn on lights and adjust temperature in the morning",
+    "trigger": [
+        {
+            "platform": "time",
+            "at": "07:00:00"
+        }
+    ],
+    "condition": [
+        {
+            "condition": "time",
+            "weekday": ["mon", "tue", "wed", "thu", "fri"]
+        }
+    ],
+    "action": [
+        {
+            "service": "light.turn_on",
+            "target": {
+                "entity_id": "light.bedroom"
+            },
+            "data": {
+                "brightness": 255,
+                "transition": 300
+            }
+        }
+    ],
+    "mode": "single"
+}
+

Trigger Types

// Time-based trigger
+{
+    "platform": "time",
+    "at": "07:00:00"
+}
+
+// State-based trigger
+{
+    "platform": "state",
+    "entity_id": "binary_sensor.motion",
+    "to": "on"
+}
+
+// Event-based trigger
+{
+    "platform": "event",
+    "event_type": "custom_event"
+}
+
+// Numeric state trigger
+{
+    "platform": "numeric_state",
+    "entity_id": "sensor.temperature",
+    "above": 25
+}
+

Condition Types

// Time condition
+{
+    "condition": "time",
+    "after": "07:00:00",
+    "before": "22:00:00"
+}
+
+// State condition
+{
+    "condition": "state",
+    "entity_id": "device_tracker.phone",
+    "state": "home"
+}
+
+// Numeric state condition
+{
+    "condition": "numeric_state",
+    "entity_id": "sensor.temperature",
+    "below": 25
+}
+

Action Types

// Service call action
+{
+    "service": "light.turn_on",
+    "target": {
+        "entity_id": "light.bedroom"
+    }
+}
+
+// Delay action
+{
+    "delay": "00:00:30"
+}
+
+// Scene activation
+{
+    "scene": "scene.evening_mode"
+}
+
+// Conditional action
+{
+    "choose": [
+        {
+            "conditions": [
+                {
+                    "condition": "state",
+                    "entity_id": "sun.sun",
+                    "state": "below_horizon"
+                }
+            ],
+            "sequence": [
+                {
+                    "service": "light.turn_on",
+                    "target": {
+                        "entity_id": "light.living_room"
+                    }
+                }
+            ]
+        }
+    ]
+}
+

Examples

Create New Automation

const response = await fetch('http://your-ha-mcp/api/automations', {
+    method: 'POST',
+    headers: {
+        'Authorization': 'Bearer your_access_token',
+        'Content-Type': 'application/json'
+    },
+    body: JSON.stringify({
+        "alias": "Morning Routine",
+        "description": "Turn on lights in the morning",
+        "trigger": [
+            {
+                "platform": "time",
+                "at": "07:00:00"
+            }
+        ],
+        "action": [
+            {
+                "service": "light.turn_on",
+                "target": {
+                    "entity_id": "light.bedroom"
+                }
+            }
+        ]
+    })
+});
+

Update Existing Automation

const response = await fetch('http://your-ha-mcp/api/automations/morning_routine', {
+    method: 'PUT',
+    headers: {
+        'Authorization': 'Bearer your_access_token',
+        'Content-Type': 'application/json'
+    },
+    body: JSON.stringify({
+        "alias": "Morning Routine",
+        "trigger": [
+            {
+                "platform": "time",
+                "at": "07:30:00"  // Updated time
+            }
+        ],
+        "action": [
+            {
+                "service": "light.turn_on",
+                "target": {
+                    "entity_id": "light.bedroom"
+                }
+            }
+        ]
+    })
+});
+

Response Format

Success Response

{
+    "success": true,
+    "data": {
+        "automation": {
+            "id": "created_automation_id",
+            // Full automation configuration
+        }
+    }
+}
+

Validation Response

{
+    "success": true,
+    "data": {
+        "valid": true,
+        "warnings": [
+            "No conditions specified"
+        ]
+    }
+}
+

Error Handling

Common Error Codes

  • 404: Automation not found
  • 401: Unauthorized
  • 400: Invalid configuration
  • 409: Automation creation/update failed

Error Response Format

{
+    "success": false,
+    "message": "Error description",
+    "error_code": "ERROR_CODE",
+    "validation_errors": [
+        {
+            "path": "trigger[0].platform",
+            "message": "Invalid trigger platform"
+        }
+    ]
+}
+

Best Practices

  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

See Also

\ No newline at end of file diff --git a/tools/automation/automation-config/index.html b/tools/automation/automation-config/index.html deleted file mode 100644 index 5d0cdeb..0000000 --- a/tools/automation/automation-config/index.html +++ /dev/null @@ -1,2538 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - Automation Configuration - Advanced Home Assistant MCP - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
- - - - - - -
- - -
- -
- - - - - - -
-
- - - -
-
-
- - - - - -
-
-
- - - - - - - -
-
- - - - - - - - -

Automation Configuration Tool

-

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

-

Features

-
    -
  • Create new automations
  • -
  • Update existing automations
  • -
  • Delete automations
  • -
  • Duplicate automations
  • -
  • Import/Export automation configurations
  • -
  • Validate automation configurations
  • -
-

Usage

-

REST API

-
POST /api/automations
-PUT /api/automations/{automation_id}
-DELETE /api/automations/{automation_id}
-POST /api/automations/{automation_id}/duplicate
-POST /api/automations/validate
-
-

WebSocket

-
// Create automation
-{
-    "type": "create_automation",
-    "automation": {
-        // Automation configuration
-    }
-}
-
-// Update automation
-{
-    "type": "update_automation",
-    "automation_id": "required_automation_id",
-    "automation": {
-        // Updated configuration
-    }
-}
-
-// Delete automation
-{
-    "type": "delete_automation",
-    "automation_id": "required_automation_id"
-}
-
-

Automation Configuration

-

Basic Structure

-
{
-    "id": "morning_routine",
-    "alias": "Morning Routine",
-    "description": "Turn on lights and adjust temperature in the morning",
-    "trigger": [
-        {
-            "platform": "time",
-            "at": "07:00:00"
-        }
-    ],
-    "condition": [
-        {
-            "condition": "time",
-            "weekday": ["mon", "tue", "wed", "thu", "fri"]
-        }
-    ],
-    "action": [
-        {
-            "service": "light.turn_on",
-            "target": {
-                "entity_id": "light.bedroom"
-            },
-            "data": {
-                "brightness": 255,
-                "transition": 300
-            }
-        }
-    ],
-    "mode": "single"
-}
-
-

Trigger Types

-
// Time-based trigger
-{
-    "platform": "time",
-    "at": "07:00:00"
-}
-
-// State-based trigger
-{
-    "platform": "state",
-    "entity_id": "binary_sensor.motion",
-    "to": "on"
-}
-
-// Event-based trigger
-{
-    "platform": "event",
-    "event_type": "custom_event"
-}
-
-// Numeric state trigger
-{
-    "platform": "numeric_state",
-    "entity_id": "sensor.temperature",
-    "above": 25
-}
-
-

Condition Types

-
// Time condition
-{
-    "condition": "time",
-    "after": "07:00:00",
-    "before": "22:00:00"
-}
-
-// State condition
-{
-    "condition": "state",
-    "entity_id": "device_tracker.phone",
-    "state": "home"
-}
-
-// Numeric state condition
-{
-    "condition": "numeric_state",
-    "entity_id": "sensor.temperature",
-    "below": 25
-}
-
-

Action Types

-
// Service call action
-{
-    "service": "light.turn_on",
-    "target": {
-        "entity_id": "light.bedroom"
-    }
-}
-
-// Delay action
-{
-    "delay": "00:00:30"
-}
-
-// Scene activation
-{
-    "scene": "scene.evening_mode"
-}
-
-// Conditional action
-{
-    "choose": [
-        {
-            "conditions": [
-                {
-                    "condition": "state",
-                    "entity_id": "sun.sun",
-                    "state": "below_horizon"
-                }
-            ],
-            "sequence": [
-                {
-                    "service": "light.turn_on",
-                    "target": {
-                        "entity_id": "light.living_room"
-                    }
-                }
-            ]
-        }
-    ]
-}
-
-

Examples

-

Create New Automation

-
const response = await fetch('http://your-ha-mcp/api/automations', {
-    method: 'POST',
-    headers: {
-        'Authorization': 'Bearer your_access_token',
-        'Content-Type': 'application/json'
-    },
-    body: JSON.stringify({
-        "alias": "Morning Routine",
-        "description": "Turn on lights in the morning",
-        "trigger": [
-            {
-                "platform": "time",
-                "at": "07:00:00"
-            }
-        ],
-        "action": [
-            {
-                "service": "light.turn_on",
-                "target": {
-                    "entity_id": "light.bedroom"
-                }
-            }
-        ]
-    })
-});
-
-

Update Existing Automation

-
const response = await fetch('http://your-ha-mcp/api/automations/morning_routine', {
-    method: 'PUT',
-    headers: {
-        'Authorization': 'Bearer your_access_token',
-        'Content-Type': 'application/json'
-    },
-    body: JSON.stringify({
-        "alias": "Morning Routine",
-        "trigger": [
-            {
-                "platform": "time",
-                "at": "07:30:00"  // Updated time
-            }
-        ],
-        "action": [
-            {
-                "service": "light.turn_on",
-                "target": {
-                    "entity_id": "light.bedroom"
-                }
-            }
-        ]
-    })
-});
-
-

Response Format

-

Success Response

-
{
-    "success": true,
-    "data": {
-        "automation": {
-            "id": "created_automation_id",
-            // Full automation configuration
-        }
-    }
-}
-
-

Validation Response

-
{
-    "success": true,
-    "data": {
-        "valid": true,
-        "warnings": [
-            "No conditions specified"
-        ]
-    }
-}
-
-

Error Handling

-

Common Error Codes

-
    -
  • 404: Automation not found
  • -
  • 401: Unauthorized
  • -
  • 400: Invalid configuration
  • -
  • 409: Automation creation/update failed
  • -
-

Error Response Format

-
{
-    "success": false,
-    "message": "Error description",
-    "error_code": "ERROR_CODE",
-    "validation_errors": [
-        {
-            "path": "trigger[0].platform",
-            "message": "Invalid trigger platform"
-        }
-    ]
-}
-
-

Best Practices

-
    -
  1. Always validate configurations before saving
  2. -
  3. Use descriptive aliases and descriptions
  4. -
  5. Group related automations
  6. -
  7. Test automations in a safe environment
  8. -
  9. Document automation dependencies
  10. -
  11. Use variables for reusable values
  12. -
  13. Implement proper error handling
  14. -
  15. Consider automation modes carefully
  16. -
-

See Also

- - - - - - - - - - - - - - - - - - - - - - - -
-
- - - -
- - - -
- - - -
-
-
-
- - - - - - - - - - - - \ No newline at end of file diff --git a/tools/automation/automation.html b/tools/automation/automation.html new file mode 100644 index 0000000..704f5da --- /dev/null +++ b/tools/automation/automation.html @@ -0,0 +1,117 @@ + Automation Management - MCP Server for Home Assistant

Automation Management Tool

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

Features

  • List all automations
  • Get automation details
  • Toggle automation state (enable/disable)
  • Trigger automations manually
  • Monitor automation execution
  • View automation history

Usage

REST API

GET /api/automations
+GET /api/automations/{automation_id}
+POST /api/automations/{automation_id}/toggle
+POST /api/automations/{automation_id}/trigger
+GET /api/automations/{automation_id}/history
+

WebSocket

// List automations
+{
+    "type": "get_automations"
+}
+
+// Toggle automation
+{
+    "type": "toggle_automation",
+    "automation_id": "required_automation_id"
+}
+
+// Trigger automation
+{
+    "type": "trigger_automation",
+    "automation_id": "required_automation_id",
+    "variables": {
+        // Optional variables
+    }
+}
+

Examples

List All Automations

const response = await fetch('http://your-ha-mcp/api/automations', {
+    headers: {
+        'Authorization': 'Bearer your_access_token'
+    }
+});
+const automations = await response.json();
+

Toggle Automation State

const response = await fetch('http://your-ha-mcp/api/automations/morning_routine/toggle', {
+    method: 'POST',
+    headers: {
+        'Authorization': 'Bearer your_access_token'
+    }
+});
+

Trigger Automation Manually

const response = await fetch('http://your-ha-mcp/api/automations/morning_routine/trigger', {
+    method: 'POST',
+    headers: {
+        'Authorization': 'Bearer your_access_token',
+        'Content-Type': 'application/json'
+    },
+    body: JSON.stringify({
+        "variables": {
+            "brightness": 100,
+            "temperature": 22
+        }
+    })
+});
+

Response Format

Automation List Response

{
+    "success": true,
+    "data": {
+        "automations": [
+            {
+                "id": "automation_id",
+                "name": "Automation Name",
+                "enabled": true,
+                "last_triggered": "2024-02-05T12:00:00Z",
+                "trigger_count": 42
+            }
+        ]
+    }
+}
+

Automation Details Response

{
+    "success": true,
+    "data": {
+        "automation": {
+            "id": "automation_id",
+            "name": "Automation Name",
+            "enabled": true,
+            "triggers": [
+                {
+                    "platform": "time",
+                    "at": "07:00:00"
+                }
+            ],
+            "conditions": [],
+            "actions": [
+                {
+                    "service": "light.turn_on",
+                    "target": {
+                        "entity_id": "light.bedroom"
+                    }
+                }
+            ],
+            "mode": "single",
+            "max": 10,
+            "last_triggered": "2024-02-05T12:00:00Z",
+            "trigger_count": 42
+        }
+    }
+}
+

Automation History Response

{
+    "success": true,
+    "data": {
+        "history": [
+            {
+                "timestamp": "2024-02-05T12:00:00Z",
+                "trigger": {
+                    "platform": "time",
+                    "at": "07:00:00"
+                },
+                "context": {
+                    "user_id": "user_123",
+                    "variables": {}
+                },
+                "result": "success"
+            }
+        ]
+    }
+}
+

Error Handling

Common Error Codes

  • 404: Automation not found
  • 401: Unauthorized
  • 400: Invalid request
  • 409: Automation execution failed

Error Response Format

{
+    "success": false,
+    "message": "Error description",
+    "error_code": "ERROR_CODE"
+}
+

Rate Limiting

  • Default limit: 50 requests per 15 minutes
  • Configurable through environment variables:
  • AUTOMATION_RATE_LIMIT
  • AUTOMATION_RATE_WINDOW

Best Practices

  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

See Also

\ No newline at end of file diff --git a/tools/automation/automation/index.html b/tools/automation/automation/index.html deleted file mode 100644 index ee6550b..0000000 --- a/tools/automation/automation/index.html +++ /dev/null @@ -1,2387 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - Automation Management - Advanced Home Assistant MCP - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
- - - - - - -
- - -
- -
- - - - - - -
-
- - - -
-
-
- - - - - -
-
-
- - - - - - - -
-
- - - - - - - - -

Automation Management Tool

-

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

-

Features

-
    -
  • List all automations
  • -
  • Get automation details
  • -
  • Toggle automation state (enable/disable)
  • -
  • Trigger automations manually
  • -
  • Monitor automation execution
  • -
  • View automation history
  • -
-

Usage

-

REST API

-
GET /api/automations
-GET /api/automations/{automation_id}
-POST /api/automations/{automation_id}/toggle
-POST /api/automations/{automation_id}/trigger
-GET /api/automations/{automation_id}/history
-
-

WebSocket

-
// List automations
-{
-    "type": "get_automations"
-}
-
-// Toggle automation
-{
-    "type": "toggle_automation",
-    "automation_id": "required_automation_id"
-}
-
-// Trigger automation
-{
-    "type": "trigger_automation",
-    "automation_id": "required_automation_id",
-    "variables": {
-        // Optional variables
-    }
-}
-
-

Examples

-

List All Automations

-
const response = await fetch('http://your-ha-mcp/api/automations', {
-    headers: {
-        'Authorization': 'Bearer your_access_token'
-    }
-});
-const automations = await response.json();
-
-

Toggle Automation State

-
const response = await fetch('http://your-ha-mcp/api/automations/morning_routine/toggle', {
-    method: 'POST',
-    headers: {
-        'Authorization': 'Bearer your_access_token'
-    }
-});
-
-

Trigger Automation Manually

-
const response = await fetch('http://your-ha-mcp/api/automations/morning_routine/trigger', {
-    method: 'POST',
-    headers: {
-        'Authorization': 'Bearer your_access_token',
-        'Content-Type': 'application/json'
-    },
-    body: JSON.stringify({
-        "variables": {
-            "brightness": 100,
-            "temperature": 22
-        }
-    })
-});
-
-

Response Format

-

Automation List Response

-
{
-    "success": true,
-    "data": {
-        "automations": [
-            {
-                "id": "automation_id",
-                "name": "Automation Name",
-                "enabled": true,
-                "last_triggered": "2024-02-05T12:00:00Z",
-                "trigger_count": 42
-            }
-        ]
-    }
-}
-
-

Automation Details Response

-
{
-    "success": true,
-    "data": {
-        "automation": {
-            "id": "automation_id",
-            "name": "Automation Name",
-            "enabled": true,
-            "triggers": [
-                {
-                    "platform": "time",
-                    "at": "07:00:00"
-                }
-            ],
-            "conditions": [],
-            "actions": [
-                {
-                    "service": "light.turn_on",
-                    "target": {
-                        "entity_id": "light.bedroom"
-                    }
-                }
-            ],
-            "mode": "single",
-            "max": 10,
-            "last_triggered": "2024-02-05T12:00:00Z",
-            "trigger_count": 42
-        }
-    }
-}
-
-

Automation History Response

-
{
-    "success": true,
-    "data": {
-        "history": [
-            {
-                "timestamp": "2024-02-05T12:00:00Z",
-                "trigger": {
-                    "platform": "time",
-                    "at": "07:00:00"
-                },
-                "context": {
-                    "user_id": "user_123",
-                    "variables": {}
-                },
-                "result": "success"
-            }
-        ]
-    }
-}
-
-

Error Handling

-

Common Error Codes

-
    -
  • 404: Automation not found
  • -
  • 401: Unauthorized
  • -
  • 400: Invalid request
  • -
  • 409: Automation execution failed
  • -
-

Error Response Format

-
{
-    "success": false,
-    "message": "Error description",
-    "error_code": "ERROR_CODE"
-}
-
-

Rate Limiting

-
    -
  • Default limit: 50 requests per 15 minutes
  • -
  • Configurable through environment variables:
  • -
  • AUTOMATION_RATE_LIMIT
  • -
  • AUTOMATION_RATE_WINDOW
  • -
-

Best Practices

-
    -
  1. Monitor automation execution history
  2. -
  3. Use descriptive automation names
  4. -
  5. Implement proper error handling
  6. -
  7. Cache automation configurations when possible
  8. -
  9. Handle rate limiting gracefully
  10. -
  11. Test automations before enabling
  12. -
  13. Use variables for flexible automation behavior
  14. -
-

See Also

- - - - - - - - - - - - - - - - - - - - - - - -
-
- - - -
- - - -
- - - -
-
-
-
- - - - - - - - - - - - \ No newline at end of file diff --git a/tools/device-management/control.html b/tools/device-management/control.html new file mode 100644 index 0000000..f19fc67 --- /dev/null +++ b/tools/device-management/control.html @@ -0,0 +1,101 @@ + Device Control - MCP Server for Home Assistant

Device Control Tool

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

Supported Device Types

  • Lights
  • Switches
  • Covers
  • Climate devices
  • Media players
  • And more...

Usage

REST API

POST /api/devices/{device_id}/control
+

WebSocket

{
+    "type": "control_device",
+    "device_id": "required_device_id",
+    "domain": "required_domain",
+    "service": "required_service",
+    "data": {
+        // Service-specific data
+    }
+}
+

Domain-Specific Commands

Lights

// Turn on/off
+POST /api/devices/light/{device_id}/control
+{
+    "service": "turn_on",  // or "turn_off"
+}
+
+// Set brightness
+{
+    "service": "turn_on",
+    "data": {
+        "brightness": 255  // 0-255
+    }
+}
+
+// Set color
+{
+    "service": "turn_on",
+    "data": {
+        "rgb_color": [255, 0, 0]  // Red
+    }
+}
+

Covers

// Open/close
+POST /api/devices/cover/{device_id}/control
+{
+    "service": "open_cover",  // or "close_cover"
+}
+
+// Set position
+{
+    "service": "set_cover_position",
+    "data": {
+        "position": 50  // 0-100
+    }
+}
+

Climate

// Set temperature
+POST /api/devices/climate/{device_id}/control
+{
+    "service": "set_temperature",
+    "data": {
+        "temperature": 22.5
+    }
+}
+
+// Set mode
+{
+    "service": "set_hvac_mode",
+    "data": {
+        "hvac_mode": "heat"  // heat, cool, auto, off
+    }
+}
+

Examples

Control Light Brightness

const response = await fetch('http://your-ha-mcp/api/devices/light/living_room/control', {
+    method: 'POST',
+    headers: {
+        'Authorization': 'Bearer your_access_token',
+        'Content-Type': 'application/json'
+    },
+    body: JSON.stringify({
+        "service": "turn_on",
+        "data": {
+            "brightness": 128
+        }
+    })
+});
+

Control Cover Position

const response = await fetch('http://your-ha-mcp/api/devices/cover/bedroom/control', {
+    method: 'POST',
+    headers: {
+        'Authorization': 'Bearer your_access_token',
+        'Content-Type': 'application/json'
+    },
+    body: JSON.stringify({
+        "service": "set_cover_position",
+        "data": {
+            "position": 75
+        }
+    })
+});
+

Response Format

Success Response

{
+    "success": true,
+    "data": {
+        "state": "on",
+        "attributes": {
+            // Updated device attributes
+        }
+    }
+}
+

Error Response

{
+    "success": false,
+    "message": "Error description",
+    "error_code": "ERROR_CODE"
+}
+

Error Handling

Common Error Codes

  • 404: Device not found
  • 401: Unauthorized
  • 400: Invalid service or parameters
  • 409: Device unavailable or offline

Rate Limiting

  • Default limit: 100 requests per 15 minutes
  • Configurable through environment variables:
  • DEVICE_CONTROL_RATE_LIMIT
  • DEVICE_CONTROL_RATE_WINDOW

Best Practices

  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

See Also

\ No newline at end of file diff --git a/tools/device-management/control/index.html b/tools/device-management/control/index.html deleted file mode 100644 index 8b48441..0000000 --- a/tools/device-management/control/index.html +++ /dev/null @@ -1,2400 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - Device Control - Advanced Home Assistant MCP - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
- - - - - - -
- - -
- -
- - - - - - -
-
- - - -
-
-
- - - - - -
-
-
- - - -
- -
- - - -
-
- - - - - - - - -

Device Control Tool

-

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

-

Supported Device Types

-
    -
  • Lights
  • -
  • Switches
  • -
  • Covers
  • -
  • Climate devices
  • -
  • Media players
  • -
  • And more...
  • -
-

Usage

-

REST API

-
POST /api/devices/{device_id}/control
-
-

WebSocket

-
{
-    "type": "control_device",
-    "device_id": "required_device_id",
-    "domain": "required_domain",
-    "service": "required_service",
-    "data": {
-        // Service-specific data
-    }
-}
-
-

Domain-Specific Commands

-

Lights

-
// Turn on/off
-POST /api/devices/light/{device_id}/control
-{
-    "service": "turn_on",  // or "turn_off"
-}
-
-// Set brightness
-{
-    "service": "turn_on",
-    "data": {
-        "brightness": 255  // 0-255
-    }
-}
-
-// Set color
-{
-    "service": "turn_on",
-    "data": {
-        "rgb_color": [255, 0, 0]  // Red
-    }
-}
-
-

Covers

-
// Open/close
-POST /api/devices/cover/{device_id}/control
-{
-    "service": "open_cover",  // or "close_cover"
-}
-
-// Set position
-{
-    "service": "set_cover_position",
-    "data": {
-        "position": 50  // 0-100
-    }
-}
-
-

Climate

-
// Set temperature
-POST /api/devices/climate/{device_id}/control
-{
-    "service": "set_temperature",
-    "data": {
-        "temperature": 22.5
-    }
-}
-
-// Set mode
-{
-    "service": "set_hvac_mode",
-    "data": {
-        "hvac_mode": "heat"  // heat, cool, auto, off
-    }
-}
-
-

Examples

-

Control Light Brightness

-
const response = await fetch('http://your-ha-mcp/api/devices/light/living_room/control', {
-    method: 'POST',
-    headers: {
-        'Authorization': 'Bearer your_access_token',
-        'Content-Type': 'application/json'
-    },
-    body: JSON.stringify({
-        "service": "turn_on",
-        "data": {
-            "brightness": 128
-        }
-    })
-});
-
-

Control Cover Position

-
const response = await fetch('http://your-ha-mcp/api/devices/cover/bedroom/control', {
-    method: 'POST',
-    headers: {
-        'Authorization': 'Bearer your_access_token',
-        'Content-Type': 'application/json'
-    },
-    body: JSON.stringify({
-        "service": "set_cover_position",
-        "data": {
-            "position": 75
-        }
-    })
-});
-
-

Response Format

-

Success Response

-
{
-    "success": true,
-    "data": {
-        "state": "on",
-        "attributes": {
-            // Updated device attributes
-        }
-    }
-}
-
-

Error Response

-
{
-    "success": false,
-    "message": "Error description",
-    "error_code": "ERROR_CODE"
-}
-
-

Error Handling

-

Common Error Codes

-
    -
  • 404: Device not found
  • -
  • 401: Unauthorized
  • -
  • 400: Invalid service or parameters
  • -
  • 409: Device unavailable or offline
  • -
-

Rate Limiting

-
    -
  • Default limit: 100 requests per 15 minutes
  • -
  • Configurable through environment variables:
  • -
  • DEVICE_CONTROL_RATE_LIMIT
  • -
  • DEVICE_CONTROL_RATE_WINDOW
  • -
-

Best Practices

-
    -
  1. Validate device availability before sending commands
  2. -
  3. Implement proper error handling
  4. -
  5. Use appropriate retry strategies for failed commands
  6. -
  7. Cache device capabilities when possible
  8. -
  9. Handle rate limiting gracefully
  10. -
-

See Also

- - - - - - - - - - - - - - - - - - - - - - - -
-
- - - -
- - - -
- - - -
-
-
-
- - - - - - - - - - - - \ No newline at end of file diff --git a/tools/device-management/list-devices.html b/tools/device-management/list-devices.html new file mode 100644 index 0000000..87ff754 --- /dev/null +++ b/tools/device-management/list-devices.html @@ -0,0 +1,61 @@ + List Devices - MCP Server for Home Assistant

List Devices Tool

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

Features

  • List all available Home Assistant devices
  • Group devices by domain
  • Get device states and attributes
  • Filter devices by various criteria

Usage

REST API

GET /api/devices
+GET /api/devices/{domain}
+GET /api/devices/{device_id}/state
+

WebSocket

// List all devices
+{
+    "type": "list_devices",
+    "domain": "optional_domain"
+}
+
+// Get device state
+{
+    "type": "get_device_state",
+    "device_id": "required_device_id"
+}
+

Examples

List All Devices

const response = await fetch('http://your-ha-mcp/api/devices', {
+    headers: {
+        'Authorization': 'Bearer your_access_token'
+    }
+});
+const devices = await response.json();
+

Get Devices by Domain

const response = await fetch('http://your-ha-mcp/api/devices/light', {
+    headers: {
+        'Authorization': 'Bearer your_access_token'
+    }
+});
+const lightDevices = await response.json();
+

Response Format

Device List Response

{
+    "success": true,
+    "data": {
+        "devices": [
+            {
+                "id": "device_id",
+                "name": "Device Name",
+                "domain": "light",
+                "state": "on",
+                "attributes": {
+                    "brightness": 255,
+                    "color_temp": 370
+                }
+            }
+        ]
+    }
+}
+

Device State Response

{
+    "success": true,
+    "data": {
+        "state": "on",
+        "attributes": {
+            "brightness": 255,
+            "color_temp": 370
+        },
+        "last_changed": "2024-02-05T12:00:00Z",
+        "last_updated": "2024-02-05T12:00:00Z"
+    }
+}
+

Error Handling

Common Error Codes

  • 404: Device not found
  • 401: Unauthorized
  • 400: Invalid request parameters

Error Response Format

{
+    "success": false,
+    "message": "Error description",
+    "error_code": "ERROR_CODE"
+}
+

Rate Limiting

  • Default limit: 100 requests per 15 minutes
  • Configurable through environment variables:
  • DEVICE_LIST_RATE_LIMIT
  • DEVICE_LIST_RATE_WINDOW

Best Practices

  1. Cache device lists when possible
  2. Use domain filtering for better performance
  3. Implement proper error handling
  4. Handle rate limiting gracefully

See Also

\ No newline at end of file diff --git a/tools/device-management/list-devices/index.html b/tools/device-management/list-devices/index.html deleted file mode 100644 index 4b99306..0000000 --- a/tools/device-management/list-devices/index.html +++ /dev/null @@ -1,2285 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - List Devices - Advanced Home Assistant MCP - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
- - - - - - -
- - -
- -
- - - - - - -
-
- - - -
-
-
- - - - - -
-
-
- - - -
-
- -
-
- - - -
-
- - - - - - - - -

List Devices Tool

-

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

-

Features

-
    -
  • List all available Home Assistant devices
  • -
  • Group devices by domain
  • -
  • Get device states and attributes
  • -
  • Filter devices by various criteria
  • -
-

Usage

-

REST API

-
GET /api/devices
-GET /api/devices/{domain}
-GET /api/devices/{device_id}/state
-
-

WebSocket

-
// List all devices
-{
-    "type": "list_devices",
-    "domain": "optional_domain"
-}
-
-// Get device state
-{
-    "type": "get_device_state",
-    "device_id": "required_device_id"
-}
-
-

Examples

-

List All Devices

-
const response = await fetch('http://your-ha-mcp/api/devices', {
-    headers: {
-        'Authorization': 'Bearer your_access_token'
-    }
-});
-const devices = await response.json();
-
-

Get Devices by Domain

-
const response = await fetch('http://your-ha-mcp/api/devices/light', {
-    headers: {
-        'Authorization': 'Bearer your_access_token'
-    }
-});
-const lightDevices = await response.json();
-
-

Response Format

-

Device List Response

-
{
-    "success": true,
-    "data": {
-        "devices": [
-            {
-                "id": "device_id",
-                "name": "Device Name",
-                "domain": "light",
-                "state": "on",
-                "attributes": {
-                    "brightness": 255,
-                    "color_temp": 370
-                }
-            }
-        ]
-    }
-}
-
-

Device State Response

-
{
-    "success": true,
-    "data": {
-        "state": "on",
-        "attributes": {
-            "brightness": 255,
-            "color_temp": 370
-        },
-        "last_changed": "2024-02-05T12:00:00Z",
-        "last_updated": "2024-02-05T12:00:00Z"
-    }
-}
-
-

Error Handling

-

Common Error Codes

-
    -
  • 404: Device not found
  • -
  • 401: Unauthorized
  • -
  • 400: Invalid request parameters
  • -
-

Error Response Format

-
{
-    "success": false,
-    "message": "Error description",
-    "error_code": "ERROR_CODE"
-}
-
-

Rate Limiting

-
    -
  • Default limit: 100 requests per 15 minutes
  • -
  • Configurable through environment variables:
  • -
  • DEVICE_LIST_RATE_LIMIT
  • -
  • DEVICE_LIST_RATE_WINDOW
  • -
-

Best Practices

-
    -
  1. Cache device lists when possible
  2. -
  3. Use domain filtering for better performance
  4. -
  5. Implement proper error handling
  6. -
  7. Handle rate limiting gracefully
  8. -
-

See Also

- - - - - - - - - - - - - - - - - - - - - - - -
-
- - - -
- - - -
- - - -
-
-
-
- - - - - - - - - - - - \ No newline at end of file diff --git a/tools/events/sse-stats.html b/tools/events/sse-stats.html new file mode 100644 index 0000000..7ab2732 --- /dev/null +++ b/tools/events/sse-stats.html @@ -0,0 +1,117 @@ + SSE Statistics - MCP Server for Home Assistant

SSE Statistics Tool

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

Features

  • Monitor active SSE connections
  • Track connection statistics
  • Analyze event delivery
  • Monitor resource usage
  • Connection management
  • Performance metrics
  • Historical data
  • Alert configuration

Usage

REST API

GET /api/sse/stats
+GET /api/sse/connections
+GET /api/sse/connections/{connection_id}
+GET /api/sse/metrics
+GET /api/sse/history
+

WebSocket

// Get SSE stats
+{
+    "type": "get_sse_stats"
+}
+
+// Get connection details
+{
+    "type": "get_sse_connection",
+    "connection_id": "required_connection_id"
+}
+
+// Get performance metrics
+{
+    "type": "get_sse_metrics",
+    "period": "1h|24h|7d|30d"
+}
+

Examples

Get Current Statistics

const response = await fetch('http://your-ha-mcp/api/sse/stats', {
+    headers: {
+        'Authorization': 'Bearer your_access_token'
+    }
+});
+const stats = await response.json();
+

Get Connection Details

const response = await fetch('http://your-ha-mcp/api/sse/connections/conn_123', {
+    headers: {
+        'Authorization': 'Bearer your_access_token'
+    }
+});
+const connection = await response.json();
+

Get Performance Metrics

const response = await fetch('http://your-ha-mcp/api/sse/metrics?period=24h', {
+    headers: {
+        'Authorization': 'Bearer your_access_token'
+    }
+});
+const metrics = await response.json();
+

Response Format

Statistics Response

{
+    "success": true,
+    "data": {
+        "active_connections": 42,
+        "total_events_sent": 12345,
+        "events_per_second": 5.2,
+        "memory_usage": 128974848,
+        "cpu_usage": 2.5,
+        "uptime": "PT24H",
+        "event_backlog": 0
+    }
+}
+

Connection Details Response

{
+    "success": true,
+    "data": {
+        "connection": {
+            "id": "conn_123",
+            "client_id": "client_456",
+            "user_id": "user_789",
+            "connected_at": "2024-02-05T12:00:00Z",
+            "last_event_at": "2024-02-05T12:05:00Z",
+            "events_sent": 150,
+            "subscriptions": [
+                {
+                    "event_type": "state_changed",
+                    "entity_id": "light.living_room"
+                }
+            ],
+            "state": "active",
+            "ip_address": "192.168.1.100",
+            "user_agent": "Mozilla/5.0 ..."
+        }
+    }
+}
+

Performance Metrics Response

{
+    "success": true,
+    "data": {
+        "metrics": {
+            "connections": {
+                "current": 42,
+                "max": 100,
+                "average": 35.5
+            },
+            "events": {
+                "total": 12345,
+                "rate": {
+                    "current": 5.2,
+                    "max": 15.0,
+                    "average": 4.8
+                }
+            },
+            "latency": {
+                "p50": 15,
+                "p95": 45,
+                "p99": 100
+            },
+            "resources": {
+                "memory": {
+                    "current": 128974848,
+                    "max": 536870912
+                },
+                "cpu": {
+                    "current": 2.5,
+                    "max": 10.0,
+                    "average": 3.2
+                }
+            }
+        },
+        "period": "24h",
+        "timestamp": "2024-02-05T12:00:00Z"
+    }
+}
+

Error Handling

Common Error Codes

  • 404: Connection not found
  • 401: Unauthorized
  • 400: Invalid request parameters
  • 503: Service overloaded

Error Response Format

{
+    "success": false,
+    "message": "Error description",
+    "error_code": "ERROR_CODE"
+}
+

Monitoring Metrics

Connection Metrics

  • Active connections
  • Connection duration
  • Connection state
  • Client information
  • Geographic distribution
  • Protocol version

Event Metrics

  • Events per second
  • Event types distribution
  • Delivery success rate
  • Event latency
  • Queue size
  • Backlog size

Resource Metrics

  • Memory usage
  • CPU usage
  • Network bandwidth
  • Disk I/O
  • Connection pool status
  • Thread pool status

Alert Thresholds

  • Connection limits
  • Event rate limits
  • Resource usage limits
  • Latency thresholds
  • Error rate thresholds
  • Backlog thresholds

Best Practices

  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

Performance Optimization

  • Connection pooling
  • Event batching
  • Resource throttling
  • Load balancing
  • Cache optimization
  • Connection cleanup

See Also

\ No newline at end of file diff --git a/tools/events/sse-stats/index.html b/tools/events/sse-stats/index.html deleted file mode 100644 index 2f5beb9..0000000 --- a/tools/events/sse-stats/index.html +++ /dev/null @@ -1,2531 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - SSE Statistics - Advanced Home Assistant MCP - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
- - - - - - -
- - -
- -
- - - - - - -
-
- - - -
-
-
- - - - - -
-
-
- - - - - - - -
-
- - - - - - - - -

SSE Statistics Tool

-

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

-

Features

-
    -
  • Monitor active SSE connections
  • -
  • Track connection statistics
  • -
  • Analyze event delivery
  • -
  • Monitor resource usage
  • -
  • Connection management
  • -
  • Performance metrics
  • -
  • Historical data
  • -
  • Alert configuration
  • -
-

Usage

-

REST API

-
GET /api/sse/stats
-GET /api/sse/connections
-GET /api/sse/connections/{connection_id}
-GET /api/sse/metrics
-GET /api/sse/history
-
-

WebSocket

-
// Get SSE stats
-{
-    "type": "get_sse_stats"
-}
-
-// Get connection details
-{
-    "type": "get_sse_connection",
-    "connection_id": "required_connection_id"
-}
-
-// Get performance metrics
-{
-    "type": "get_sse_metrics",
-    "period": "1h|24h|7d|30d"
-}
-
-

Examples

-

Get Current Statistics

-
const response = await fetch('http://your-ha-mcp/api/sse/stats', {
-    headers: {
-        'Authorization': 'Bearer your_access_token'
-    }
-});
-const stats = await response.json();
-
-

Get Connection Details

-
const response = await fetch('http://your-ha-mcp/api/sse/connections/conn_123', {
-    headers: {
-        'Authorization': 'Bearer your_access_token'
-    }
-});
-const connection = await response.json();
-
-

Get Performance Metrics

-
const response = await fetch('http://your-ha-mcp/api/sse/metrics?period=24h', {
-    headers: {
-        'Authorization': 'Bearer your_access_token'
-    }
-});
-const metrics = await response.json();
-
-

Response Format

-

Statistics Response

-
{
-    "success": true,
-    "data": {
-        "active_connections": 42,
-        "total_events_sent": 12345,
-        "events_per_second": 5.2,
-        "memory_usage": 128974848,
-        "cpu_usage": 2.5,
-        "uptime": "PT24H",
-        "event_backlog": 0
-    }
-}
-
-

Connection Details Response

-
{
-    "success": true,
-    "data": {
-        "connection": {
-            "id": "conn_123",
-            "client_id": "client_456",
-            "user_id": "user_789",
-            "connected_at": "2024-02-05T12:00:00Z",
-            "last_event_at": "2024-02-05T12:05:00Z",
-            "events_sent": 150,
-            "subscriptions": [
-                {
-                    "event_type": "state_changed",
-                    "entity_id": "light.living_room"
-                }
-            ],
-            "state": "active",
-            "ip_address": "192.168.1.100",
-            "user_agent": "Mozilla/5.0 ..."
-        }
-    }
-}
-
-

Performance Metrics Response

-
{
-    "success": true,
-    "data": {
-        "metrics": {
-            "connections": {
-                "current": 42,
-                "max": 100,
-                "average": 35.5
-            },
-            "events": {
-                "total": 12345,
-                "rate": {
-                    "current": 5.2,
-                    "max": 15.0,
-                    "average": 4.8
-                }
-            },
-            "latency": {
-                "p50": 15,
-                "p95": 45,
-                "p99": 100
-            },
-            "resources": {
-                "memory": {
-                    "current": 128974848,
-                    "max": 536870912
-                },
-                "cpu": {
-                    "current": 2.5,
-                    "max": 10.0,
-                    "average": 3.2
-                }
-            }
-        },
-        "period": "24h",
-        "timestamp": "2024-02-05T12:00:00Z"
-    }
-}
-
-

Error Handling

-

Common Error Codes

-
    -
  • 404: Connection not found
  • -
  • 401: Unauthorized
  • -
  • 400: Invalid request parameters
  • -
  • 503: Service overloaded
  • -
-

Error Response Format

-
{
-    "success": false,
-    "message": "Error description",
-    "error_code": "ERROR_CODE"
-}
-
-

Monitoring Metrics

-

Connection Metrics

-
    -
  • Active connections
  • -
  • Connection duration
  • -
  • Connection state
  • -
  • Client information
  • -
  • Geographic distribution
  • -
  • Protocol version
  • -
-

Event Metrics

-
    -
  • Events per second
  • -
  • Event types distribution
  • -
  • Delivery success rate
  • -
  • Event latency
  • -
  • Queue size
  • -
  • Backlog size
  • -
-

Resource Metrics

-
    -
  • Memory usage
  • -
  • CPU usage
  • -
  • Network bandwidth
  • -
  • Disk I/O
  • -
  • Connection pool status
  • -
  • Thread pool status
  • -
-

Alert Thresholds

-
    -
  • Connection limits
  • -
  • Event rate limits
  • -
  • Resource usage limits
  • -
  • Latency thresholds
  • -
  • Error rate thresholds
  • -
  • Backlog thresholds
  • -
-

Best Practices

-
    -
  1. Monitor connection health
  2. -
  3. Track resource usage
  4. -
  5. Set up alerts
  6. -
  7. Analyze usage patterns
  8. -
  9. Optimize performance
  10. -
  11. Plan capacity
  12. -
  13. Implement failover
  14. -
  15. Regular maintenance
  16. -
-

Performance Optimization

-
    -
  • Connection pooling
  • -
  • Event batching
  • -
  • Resource throttling
  • -
  • Load balancing
  • -
  • Cache optimization
  • -
  • Connection cleanup
  • -
-

See Also

- - - - - - - - - - - - - - - - - - - - - - - -
-
- - - -
- - - -
- - - -
-
-
-
- - - - - - - - - - - - \ No newline at end of file diff --git a/tools/events/subscribe-events.html b/tools/events/subscribe-events.html new file mode 100644 index 0000000..de1378b --- /dev/null +++ b/tools/events/subscribe-events.html @@ -0,0 +1,122 @@ + Event Subscription - MCP Server for Home Assistant

Event Subscription Tool

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

Features

  • Subscribe to Home Assistant events
  • Monitor specific entities
  • Domain-based monitoring
  • Event filtering
  • Real-time updates
  • Event history
  • Custom event handling
  • Connection management

Usage

REST API

POST /api/events/subscribe
+DELETE /api/events/unsubscribe
+GET /api/events/subscriptions
+GET /api/events/history
+

WebSocket

// Subscribe to events
+{
+    "type": "subscribe_events",
+    "event_type": "optional_event_type",
+    "entity_id": "optional_entity_id",
+    "domain": "optional_domain"
+}
+
+// Unsubscribe from events
+{
+    "type": "unsubscribe_events",
+    "subscription_id": "required_subscription_id"
+}
+

Server-Sent Events (SSE)

GET /api/events/stream?event_type=state_changed&entity_id=light.living_room
+

Event Types

  • state_changed: Entity state changes
  • automation_triggered: Automation executions
  • scene_activated: Scene activations
  • device_registered: New device registrations
  • service_registered: New service registrations
  • homeassistant_start: System startup
  • homeassistant_stop: System shutdown
  • Custom events

Examples

Subscribe to All State Changes

const response = await fetch('http://your-ha-mcp/api/events/subscribe', {
+    method: 'POST',
+    headers: {
+        'Authorization': 'Bearer your_access_token',
+        'Content-Type': 'application/json'
+    },
+    body: JSON.stringify({
+        "event_type": "state_changed"
+    })
+});
+

Monitor Specific Entity

const response = await fetch('http://your-ha-mcp/api/events/subscribe', {
+    method: 'POST',
+    headers: {
+        'Authorization': 'Bearer your_access_token',
+        'Content-Type': 'application/json'
+    },
+    body: JSON.stringify({
+        "event_type": "state_changed",
+        "entity_id": "light.living_room"
+    })
+});
+

Domain-Based Monitoring

const response = await fetch('http://your-ha-mcp/api/events/subscribe', {
+    method: 'POST',
+    headers: {
+        'Authorization': 'Bearer your_access_token',
+        'Content-Type': 'application/json'
+    },
+    body: JSON.stringify({
+        "event_type": "state_changed",
+        "domain": "light"
+    })
+});
+

SSE Connection Example

const eventSource = new EventSource(
+    'http://your-ha-mcp/api/events/stream?event_type=state_changed&entity_id=light.living_room',
+    {
+        headers: {
+            'Authorization': 'Bearer your_access_token'
+        }
+    }
+);
+
+eventSource.onmessage = (event) => {
+    const data = JSON.parse(event.data);
+    console.log('Event received:', data);
+};
+
+eventSource.onerror = (error) => {
+    console.error('SSE error:', error);
+    eventSource.close();
+};
+

Response Format

Subscription Response

{
+    "success": true,
+    "data": {
+        "subscription_id": "sub_123",
+        "event_type": "state_changed",
+        "entity_id": "light.living_room",
+        "created_at": "2024-02-05T12:00:00Z"
+    }
+}
+

Event Message Format

{
+    "event_type": "state_changed",
+    "entity_id": "light.living_room",
+    "data": {
+        "old_state": {
+            "state": "off",
+            "attributes": {},
+            "last_changed": "2024-02-05T11:55:00Z"
+        },
+        "new_state": {
+            "state": "on",
+            "attributes": {
+                "brightness": 255
+            },
+            "last_changed": "2024-02-05T12:00:00Z"
+        }
+    },
+    "origin": "LOCAL",
+    "time_fired": "2024-02-05T12:00:00Z",
+    "context": {
+        "id": "context_123",
+        "parent_id": null,
+        "user_id": "user_123"
+    }
+}
+

Subscriptions List Response

{
+    "success": true,
+    "data": {
+        "subscriptions": [
+            {
+                "id": "sub_123",
+                "event_type": "state_changed",
+                "entity_id": "light.living_room",
+                "created_at": "2024-02-05T12:00:00Z",
+                "last_event": "2024-02-05T12:05:00Z"
+            }
+        ]
+    }
+}
+

Error Handling

Common Error Codes

  • 404: Event type not found
  • 401: Unauthorized
  • 400: Invalid subscription parameters
  • 409: Subscription already exists
  • 429: Too many subscriptions

Error Response Format

{
+    "success": false,
+    "message": "Error description",
+    "error_code": "ERROR_CODE"
+}
+

Rate Limiting

  • Default limits:
  • Maximum subscriptions: 100 per client
  • Maximum event rate: 1000 events per minute
  • Configurable through environment variables:
  • EVENT_SUB_MAX_SUBSCRIPTIONS
  • EVENT_SUB_RATE_LIMIT
  • EVENT_SUB_RATE_WINDOW

Best Practices

  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

Connection Management

  • Implement heartbeat monitoring
  • Use reconnection strategies
  • Handle connection timeouts
  • Monitor connection quality
  • Implement fallback mechanisms
  • Clean up resources properly

See Also

\ No newline at end of file diff --git a/tools/events/subscribe-events/index.html b/tools/events/subscribe-events/index.html deleted file mode 100644 index fd6be1e..0000000 --- a/tools/events/subscribe-events/index.html +++ /dev/null @@ -1,2495 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - Event Subscription - Advanced Home Assistant MCP - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
- - - - - - -
- - -
- -
- - - - - - -
-
- - - -
-
-
- - - - - -
-
-
- - - - - - - -
-
- - - - - - - - -

Event Subscription Tool

-

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

-

Features

-
    -
  • Subscribe to Home Assistant events
  • -
  • Monitor specific entities
  • -
  • Domain-based monitoring
  • -
  • Event filtering
  • -
  • Real-time updates
  • -
  • Event history
  • -
  • Custom event handling
  • -
  • Connection management
  • -
-

Usage

-

REST API

-
POST /api/events/subscribe
-DELETE /api/events/unsubscribe
-GET /api/events/subscriptions
-GET /api/events/history
-
-

WebSocket

-
// Subscribe to events
-{
-    "type": "subscribe_events",
-    "event_type": "optional_event_type",
-    "entity_id": "optional_entity_id",
-    "domain": "optional_domain"
-}
-
-// Unsubscribe from events
-{
-    "type": "unsubscribe_events",
-    "subscription_id": "required_subscription_id"
-}
-
-

Server-Sent Events (SSE)

-
GET /api/events/stream?event_type=state_changed&entity_id=light.living_room
-
-

Event Types

-
    -
  • state_changed: Entity state changes
  • -
  • automation_triggered: Automation executions
  • -
  • scene_activated: Scene activations
  • -
  • device_registered: New device registrations
  • -
  • service_registered: New service registrations
  • -
  • homeassistant_start: System startup
  • -
  • homeassistant_stop: System shutdown
  • -
  • Custom events
  • -
-

Examples

-

Subscribe to All State Changes

-
const response = await fetch('http://your-ha-mcp/api/events/subscribe', {
-    method: 'POST',
-    headers: {
-        'Authorization': 'Bearer your_access_token',
-        'Content-Type': 'application/json'
-    },
-    body: JSON.stringify({
-        "event_type": "state_changed"
-    })
-});
-
-

Monitor Specific Entity

-
const response = await fetch('http://your-ha-mcp/api/events/subscribe', {
-    method: 'POST',
-    headers: {
-        'Authorization': 'Bearer your_access_token',
-        'Content-Type': 'application/json'
-    },
-    body: JSON.stringify({
-        "event_type": "state_changed",
-        "entity_id": "light.living_room"
-    })
-});
-
-

Domain-Based Monitoring

-
const response = await fetch('http://your-ha-mcp/api/events/subscribe', {
-    method: 'POST',
-    headers: {
-        'Authorization': 'Bearer your_access_token',
-        'Content-Type': 'application/json'
-    },
-    body: JSON.stringify({
-        "event_type": "state_changed",
-        "domain": "light"
-    })
-});
-
-

SSE Connection Example

-
const eventSource = new EventSource(
-    'http://your-ha-mcp/api/events/stream?event_type=state_changed&entity_id=light.living_room',
-    {
-        headers: {
-            'Authorization': 'Bearer your_access_token'
-        }
-    }
-);
-
-eventSource.onmessage = (event) => {
-    const data = JSON.parse(event.data);
-    console.log('Event received:', data);
-};
-
-eventSource.onerror = (error) => {
-    console.error('SSE error:', error);
-    eventSource.close();
-};
-
-

Response Format

-

Subscription Response

-
{
-    "success": true,
-    "data": {
-        "subscription_id": "sub_123",
-        "event_type": "state_changed",
-        "entity_id": "light.living_room",
-        "created_at": "2024-02-05T12:00:00Z"
-    }
-}
-
-

Event Message Format

-
{
-    "event_type": "state_changed",
-    "entity_id": "light.living_room",
-    "data": {
-        "old_state": {
-            "state": "off",
-            "attributes": {},
-            "last_changed": "2024-02-05T11:55:00Z"
-        },
-        "new_state": {
-            "state": "on",
-            "attributes": {
-                "brightness": 255
-            },
-            "last_changed": "2024-02-05T12:00:00Z"
-        }
-    },
-    "origin": "LOCAL",
-    "time_fired": "2024-02-05T12:00:00Z",
-    "context": {
-        "id": "context_123",
-        "parent_id": null,
-        "user_id": "user_123"
-    }
-}
-
-

Subscriptions List Response

-
{
-    "success": true,
-    "data": {
-        "subscriptions": [
-            {
-                "id": "sub_123",
-                "event_type": "state_changed",
-                "entity_id": "light.living_room",
-                "created_at": "2024-02-05T12:00:00Z",
-                "last_event": "2024-02-05T12:05:00Z"
-            }
-        ]
-    }
-}
-
-

Error Handling

-

Common Error Codes

-
    -
  • 404: Event type not found
  • -
  • 401: Unauthorized
  • -
  • 400: Invalid subscription parameters
  • -
  • 409: Subscription already exists
  • -
  • 429: Too many subscriptions
  • -
-

Error Response Format

-
{
-    "success": false,
-    "message": "Error description",
-    "error_code": "ERROR_CODE"
-}
-
-

Rate Limiting

-
    -
  • Default limits:
  • -
  • Maximum subscriptions: 100 per client
  • -
  • Maximum event rate: 1000 events per minute
  • -
  • Configurable through environment variables:
  • -
  • EVENT_SUB_MAX_SUBSCRIPTIONS
  • -
  • EVENT_SUB_RATE_LIMIT
  • -
  • EVENT_SUB_RATE_WINDOW
  • -
-

Best Practices

-
    -
  1. Use specific event types when possible
  2. -
  3. Implement proper error handling
  4. -
  5. Handle connection interruptions
  6. -
  7. Process events asynchronously
  8. -
  9. Implement backoff strategies
  10. -
  11. Monitor subscription health
  12. -
  13. Clean up unused subscriptions
  14. -
  15. Handle rate limiting gracefully
  16. -
-

Connection Management

-
    -
  • Implement heartbeat monitoring
  • -
  • Use reconnection strategies
  • -
  • Handle connection timeouts
  • -
  • Monitor connection quality
  • -
  • Implement fallback mechanisms
  • -
  • Clean up resources properly
  • -
-

See Also

- - - - - - - - - - - - - - - - - - - - - - - -
-
- - - -
- - - -
- - - -
-
-
-
- - - - - - - - - - - - \ No newline at end of file diff --git a/tools/history-state/history.html b/tools/history-state/history.html new file mode 100644 index 0000000..cef36d4 --- /dev/null +++ b/tools/history-state/history.html @@ -0,0 +1,68 @@ + History - MCP Server for Home Assistant

Device History Tool

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

Features

  • Fetch device state history
  • Filter by time range
  • Get significant changes
  • Aggregate data by time periods
  • Export historical data

Usage

REST API

GET /api/history/{device_id}
+GET /api/history/{device_id}/period/{start_time}
+GET /api/history/{device_id}/period/{start_time}/{end_time}
+

WebSocket

{
+    "type": "get_history",
+    "device_id": "required_device_id",
+    "start_time": "optional_iso_timestamp",
+    "end_time": "optional_iso_timestamp",
+    "significant_changes_only": false
+}
+

Query Parameters

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

Examples

Get Recent History

const response = await fetch('http://your-ha-mcp/api/history/light.living_room', {
+    headers: {
+        'Authorization': 'Bearer your_access_token'
+    }
+});
+const history = await response.json();
+

Get History for Specific Period

const startTime = '2024-02-01T00:00:00Z';
+const endTime = '2024-02-02T00:00:00Z';
+const response = await fetch(
+    `http://your-ha-mcp/api/history/light.living_room/period/${startTime}/${endTime}`, 
+    {
+        headers: {
+            'Authorization': 'Bearer your_access_token'
+        }
+    }
+);
+const history = await response.json();
+

Response Format

History Response

{
+    "success": true,
+    "data": {
+        "history": [
+            {
+                "state": "on",
+                "attributes": {
+                    "brightness": 255
+                },
+                "last_changed": "2024-02-05T12:00:00Z",
+                "last_updated": "2024-02-05T12:00:00Z"
+            },
+            {
+                "state": "off",
+                "last_changed": "2024-02-05T13:00:00Z",
+                "last_updated": "2024-02-05T13:00:00Z"
+            }
+        ]
+    }
+}
+

Aggregated History Response

{
+    "success": true,
+    "data": {
+        "aggregates": {
+            "daily": [
+                {
+                    "date": "2024-02-05",
+                    "on_time": "PT5H30M",
+                    "off_time": "PT18H30M",
+                    "changes": 10
+                }
+            ]
+        }
+    }
+}
+

Error Handling

Common Error Codes

  • 404: Device not found
  • 401: Unauthorized
  • 400: Invalid parameters
  • 416: Time range too large

Error Response Format

{
+    "success": false,
+    "message": "Error description",
+    "error_code": "ERROR_CODE"
+}
+

Rate Limiting

  • Default limit: 50 requests per 15 minutes
  • Configurable through environment variables:
  • HISTORY_RATE_LIMIT
  • HISTORY_RATE_WINDOW

Data Retention

  • Default retention period: 30 days
  • Configurable through environment variables:
  • HISTORY_RETENTION_DAYS
  • Older data may be automatically aggregated

Best Practices

  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

See Also

\ No newline at end of file diff --git a/tools/history-state/history/index.html b/tools/history-state/history/index.html deleted file mode 100644 index 29f90fe..0000000 --- a/tools/history-state/history/index.html +++ /dev/null @@ -1,2376 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - History - Advanced Home Assistant MCP - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
- - - - - - -
- - -
- -
- - - - - - -
-
- - - -
-
-
- - - - - -
-
-
- - - - - - - -
-
- - - - - - - - -

Device History Tool

-

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

-

Features

-
    -
  • Fetch device state history
  • -
  • Filter by time range
  • -
  • Get significant changes
  • -
  • Aggregate data by time periods
  • -
  • Export historical data
  • -
-

Usage

-

REST API

-
GET /api/history/{device_id}
-GET /api/history/{device_id}/period/{start_time}
-GET /api/history/{device_id}/period/{start_time}/{end_time}
-
-

WebSocket

-
{
-    "type": "get_history",
-    "device_id": "required_device_id",
-    "start_time": "optional_iso_timestamp",
-    "end_time": "optional_iso_timestamp",
-    "significant_changes_only": false
-}
-
-

Query Parameters

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ParameterTypeDescription
start_timeISO timestampStart of the period to fetch history for
end_timeISO timestampEnd of the period to fetch history for
significant_changes_onlybooleanOnly return significant state changes
minimal_responsebooleanReturn minimal state information
no_attributesbooleanExclude attribute data from response
-

Examples

-

Get Recent History

-
const response = await fetch('http://your-ha-mcp/api/history/light.living_room', {
-    headers: {
-        'Authorization': 'Bearer your_access_token'
-    }
-});
-const history = await response.json();
-
-

Get History for Specific Period

-
const startTime = '2024-02-01T00:00:00Z';
-const endTime = '2024-02-02T00:00:00Z';
-const response = await fetch(
-    `http://your-ha-mcp/api/history/light.living_room/period/${startTime}/${endTime}`, 
-    {
-        headers: {
-            'Authorization': 'Bearer your_access_token'
-        }
-    }
-);
-const history = await response.json();
-
-

Response Format

-

History Response

-
{
-    "success": true,
-    "data": {
-        "history": [
-            {
-                "state": "on",
-                "attributes": {
-                    "brightness": 255
-                },
-                "last_changed": "2024-02-05T12:00:00Z",
-                "last_updated": "2024-02-05T12:00:00Z"
-            },
-            {
-                "state": "off",
-                "last_changed": "2024-02-05T13:00:00Z",
-                "last_updated": "2024-02-05T13:00:00Z"
-            }
-        ]
-    }
-}
-
-

Aggregated History Response

-
{
-    "success": true,
-    "data": {
-        "aggregates": {
-            "daily": [
-                {
-                    "date": "2024-02-05",
-                    "on_time": "PT5H30M",
-                    "off_time": "PT18H30M",
-                    "changes": 10
-                }
-            ]
-        }
-    }
-}
-
-

Error Handling

-

Common Error Codes

-
    -
  • 404: Device not found
  • -
  • 401: Unauthorized
  • -
  • 400: Invalid parameters
  • -
  • 416: Time range too large
  • -
-

Error Response Format

-
{
-    "success": false,
-    "message": "Error description",
-    "error_code": "ERROR_CODE"
-}
-
-

Rate Limiting

-
    -
  • Default limit: 50 requests per 15 minutes
  • -
  • Configurable through environment variables:
  • -
  • HISTORY_RATE_LIMIT
  • -
  • HISTORY_RATE_WINDOW
  • -
-

Data Retention

-
    -
  • Default retention period: 30 days
  • -
  • Configurable through environment variables:
  • -
  • HISTORY_RETENTION_DAYS
  • -
  • Older data may be automatically aggregated
  • -
-

Best Practices

-
    -
  1. Use appropriate time ranges to avoid large responses
  2. -
  3. Enable significant_changes_only for better performance
  4. -
  5. Use minimal_response when full state data isn't needed
  6. -
  7. Implement proper error handling
  8. -
  9. Cache frequently accessed historical data
  10. -
  11. Handle rate limiting gracefully
  12. -
-

See Also

- - - - - - - - - - - - - - - - - - - - - - - -
-
- - - -
- - - -
- - - -
-
-
-
- - - - - - - - - - - - \ No newline at end of file diff --git a/tools/history-state/scene.html b/tools/history-state/scene.html new file mode 100644 index 0000000..1ddf460 --- /dev/null +++ b/tools/history-state/scene.html @@ -0,0 +1,113 @@ + Scene Management - MCP Server for Home Assistant

Scene Management Tool

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

Features

  • List available scenes
  • Activate scenes
  • Create new scenes
  • Update existing scenes
  • Delete scenes
  • Get scene state information

Usage

REST API

GET /api/scenes
+GET /api/scenes/{scene_id}
+POST /api/scenes/{scene_id}/activate
+POST /api/scenes
+PUT /api/scenes/{scene_id}
+DELETE /api/scenes/{scene_id}
+

WebSocket

// List scenes
+{
+    "type": "get_scenes"
+}
+
+// Activate scene
+{
+    "type": "activate_scene",
+    "scene_id": "required_scene_id"
+}
+
+// Create/Update scene
+{
+    "type": "create_scene",
+    "scene": {
+        "name": "required_scene_name",
+        "entities": {
+            // Entity states
+        }
+    }
+}
+

Scene Configuration

Scene Definition

{
+    "name": "Movie Night",
+    "entities": {
+        "light.living_room": {
+            "state": "on",
+            "brightness": 50,
+            "color_temp": 2700
+        },
+        "cover.living_room": {
+            "state": "closed"
+        },
+        "media_player.tv": {
+            "state": "on",
+            "source": "HDMI 1"
+        }
+    }
+}
+

Examples

List All Scenes

const response = await fetch('http://your-ha-mcp/api/scenes', {
+    headers: {
+        'Authorization': 'Bearer your_access_token'
+    }
+});
+const scenes = await response.json();
+

Activate a Scene

const response = await fetch('http://your-ha-mcp/api/scenes/movie_night/activate', {
+    method: 'POST',
+    headers: {
+        'Authorization': 'Bearer your_access_token'
+    }
+});
+

Create a New Scene

const response = await fetch('http://your-ha-mcp/api/scenes', {
+    method: 'POST',
+    headers: {
+        'Authorization': 'Bearer your_access_token',
+        'Content-Type': 'application/json'
+    },
+    body: JSON.stringify({
+        "name": "Movie Night",
+        "entities": {
+            "light.living_room": {
+                "state": "on",
+                "brightness": 50
+            },
+            "cover.living_room": {
+                "state": "closed"
+            }
+        }
+    })
+});
+

Response Format

Scene List Response

{
+    "success": true,
+    "data": {
+        "scenes": [
+            {
+                "id": "scene_id",
+                "name": "Scene Name",
+                "entities": {
+                    // Entity configurations
+                }
+            }
+        ]
+    }
+}
+

Scene Activation Response

{
+    "success": true,
+    "data": {
+        "scene_id": "activated_scene_id",
+        "status": "activated",
+        "timestamp": "2024-02-05T12:00:00Z"
+    }
+}
+

Error Handling

Common Error Codes

  • 404: Scene not found
  • 401: Unauthorized
  • 400: Invalid scene configuration
  • 409: Scene activation failed

Error Response Format

{
+    "success": false,
+    "message": "Error description",
+    "error_code": "ERROR_CODE"
+}
+

Rate Limiting

  • Default limit: 50 requests per 15 minutes
  • Configurable through environment variables:
  • SCENE_RATE_LIMIT
  • SCENE_RATE_WINDOW

Best Practices

  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

Scene Transitions

Scenes can include transition settings for smooth state changes:

{
+    "name": "Sunset Mode",
+    "entities": {
+        "light.living_room": {
+            "state": "on",
+            "brightness": 128,
+            "transition": 5  // 5 seconds
+        }
+    }
+}
+

See Also

\ No newline at end of file diff --git a/tools/history-state/scene/index.html b/tools/history-state/scene/index.html deleted file mode 100644 index 22bb9af..0000000 --- a/tools/history-state/scene/index.html +++ /dev/null @@ -1,2434 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - Scene Management - Advanced Home Assistant MCP - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
- - - - - - -
- - -
- -
- - - - - - -
-
- - - -
-
-
- - - - - -
-
-
- - - - - - - -
-
- - - - - - - - -

Scene Management Tool

-

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

-

Features

-
    -
  • List available scenes
  • -
  • Activate scenes
  • -
  • Create new scenes
  • -
  • Update existing scenes
  • -
  • Delete scenes
  • -
  • Get scene state information
  • -
-

Usage

-

REST API

-
GET /api/scenes
-GET /api/scenes/{scene_id}
-POST /api/scenes/{scene_id}/activate
-POST /api/scenes
-PUT /api/scenes/{scene_id}
-DELETE /api/scenes/{scene_id}
-
-

WebSocket

-
// List scenes
-{
-    "type": "get_scenes"
-}
-
-// Activate scene
-{
-    "type": "activate_scene",
-    "scene_id": "required_scene_id"
-}
-
-// Create/Update scene
-{
-    "type": "create_scene",
-    "scene": {
-        "name": "required_scene_name",
-        "entities": {
-            // Entity states
-        }
-    }
-}
-
-

Scene Configuration

-

Scene Definition

-
{
-    "name": "Movie Night",
-    "entities": {
-        "light.living_room": {
-            "state": "on",
-            "brightness": 50,
-            "color_temp": 2700
-        },
-        "cover.living_room": {
-            "state": "closed"
-        },
-        "media_player.tv": {
-            "state": "on",
-            "source": "HDMI 1"
-        }
-    }
-}
-
-

Examples

-

List All Scenes

-
const response = await fetch('http://your-ha-mcp/api/scenes', {
-    headers: {
-        'Authorization': 'Bearer your_access_token'
-    }
-});
-const scenes = await response.json();
-
-

Activate a Scene

-
const response = await fetch('http://your-ha-mcp/api/scenes/movie_night/activate', {
-    method: 'POST',
-    headers: {
-        'Authorization': 'Bearer your_access_token'
-    }
-});
-
-

Create a New Scene

-
const response = await fetch('http://your-ha-mcp/api/scenes', {
-    method: 'POST',
-    headers: {
-        'Authorization': 'Bearer your_access_token',
-        'Content-Type': 'application/json'
-    },
-    body: JSON.stringify({
-        "name": "Movie Night",
-        "entities": {
-            "light.living_room": {
-                "state": "on",
-                "brightness": 50
-            },
-            "cover.living_room": {
-                "state": "closed"
-            }
-        }
-    })
-});
-
-

Response Format

-

Scene List Response

-
{
-    "success": true,
-    "data": {
-        "scenes": [
-            {
-                "id": "scene_id",
-                "name": "Scene Name",
-                "entities": {
-                    // Entity configurations
-                }
-            }
-        ]
-    }
-}
-
-

Scene Activation Response

-
{
-    "success": true,
-    "data": {
-        "scene_id": "activated_scene_id",
-        "status": "activated",
-        "timestamp": "2024-02-05T12:00:00Z"
-    }
-}
-
-

Error Handling

-

Common Error Codes

-
    -
  • 404: Scene not found
  • -
  • 401: Unauthorized
  • -
  • 400: Invalid scene configuration
  • -
  • 409: Scene activation failed
  • -
-

Error Response Format

-
{
-    "success": false,
-    "message": "Error description",
-    "error_code": "ERROR_CODE"
-}
-
-

Rate Limiting

-
    -
  • Default limit: 50 requests per 15 minutes
  • -
  • Configurable through environment variables:
  • -
  • SCENE_RATE_LIMIT
  • -
  • SCENE_RATE_WINDOW
  • -
-

Best Practices

-
    -
  1. Validate entity availability before creating scenes
  2. -
  3. Use meaningful scene names
  4. -
  5. Group related entities in scenes
  6. -
  7. Implement proper error handling
  8. -
  9. Cache scene configurations when possible
  10. -
  11. Handle rate limiting gracefully
  12. -
-

Scene Transitions

-

Scenes can include transition settings for smooth state changes:

-
{
-    "name": "Sunset Mode",
-    "entities": {
-        "light.living_room": {
-            "state": "on",
-            "brightness": 128,
-            "transition": 5  // 5 seconds
-        }
-    }
-}
-
-

See Also

- - - - - - - - - - - - - - - - - - - - - - - -
-
- - - -
- - - -
- - - -
-
-
-
- - - - - - - - - - - - \ No newline at end of file diff --git a/tools/index.html b/tools/index.html new file mode 100644 index 0000000..940560f --- /dev/null +++ b/tools/index.html @@ -0,0 +1 @@ + Overview - MCP Server for Home Assistant

Tools Overview

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

Available Tools

Device Management

History & State

Automation

Add-ons & Packages

Notifications

  • Notify - Send and manage notifications

Events

Getting Started

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

Next Steps

\ No newline at end of file diff --git a/tools/notifications/notify.html b/tools/notifications/notify.html new file mode 100644 index 0000000..2b8d7a4 --- /dev/null +++ b/tools/notifications/notify.html @@ -0,0 +1,135 @@ + Notify - MCP Server for Home Assistant

Notification Tool

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

Features

  • Send notifications
  • Support for multiple notification services
  • Custom notification data
  • Rich media support
  • Notification templates
  • Delivery tracking
  • Priority levels
  • Notification groups

Usage

REST API

POST /api/notify
+POST /api/notify/{service_id}
+GET /api/notify/services
+GET /api/notify/history
+

WebSocket

// Send notification
+{
+    "type": "send_notification",
+    "service": "required_service_id",
+    "message": "required_message",
+    "title": "optional_title",
+    "data": {
+        // Service-specific data
+    }
+}
+
+// Get notification services
+{
+    "type": "get_notification_services"
+}
+

Supported Services

  • Mobile App
  • Email
  • SMS
  • Telegram
  • Discord
  • Slack
  • Push Notifications
  • Custom Services

Examples

Basic Notification

const response = await fetch('http://your-ha-mcp/api/notify/mobile_app', {
+    method: 'POST',
+    headers: {
+        'Authorization': 'Bearer your_access_token',
+        'Content-Type': 'application/json'
+    },
+    body: JSON.stringify({
+        "message": "Motion detected in living room",
+        "title": "Security Alert"
+    })
+});
+

Rich Notification

const response = await fetch('http://your-ha-mcp/api/notify/mobile_app', {
+    method: 'POST',
+    headers: {
+        'Authorization': 'Bearer your_access_token',
+        'Content-Type': 'application/json'
+    },
+    body: JSON.stringify({
+        "message": "Motion detected in living room",
+        "title": "Security Alert",
+        "data": {
+            "image": "https://your-camera-snapshot.jpg",
+            "actions": [
+                {
+                    "action": "view_camera",
+                    "title": "View Camera"
+                },
+                {
+                    "action": "dismiss",
+                    "title": "Dismiss"
+                }
+            ],
+            "priority": "high",
+            "ttl": 3600,
+            "group": "security"
+        }
+    })
+});
+

Service-Specific Example (Telegram)

const response = await fetch('http://your-ha-mcp/api/notify/telegram', {
+    method: 'POST',
+    headers: {
+        'Authorization': 'Bearer your_access_token',
+        'Content-Type': 'application/json'
+    },
+    body: JSON.stringify({
+        "message": "Temperature is too high!",
+        "title": "Climate Alert",
+        "data": {
+            "parse_mode": "markdown",
+            "inline_keyboard": [
+                [
+                    {
+                        "text": "Turn On AC",
+                        "callback_data": "turn_on_ac"
+                    }
+                ]
+            ]
+        }
+    })
+});
+

Response Format

Success Response

{
+    "success": true,
+    "data": {
+        "notification_id": "notification_123",
+        "status": "sent",
+        "timestamp": "2024-02-05T12:00:00Z",
+        "service": "mobile_app"
+    }
+}
+

Services List Response

{
+    "success": true,
+    "data": {
+        "services": [
+            {
+                "id": "mobile_app",
+                "name": "Mobile App",
+                "enabled": true,
+                "features": [
+                    "actions",
+                    "images",
+                    "sound"
+                ]
+            }
+        ]
+    }
+}
+

Notification History Response

{
+    "success": true,
+    "data": {
+        "history": [
+            {
+                "id": "notification_123",
+                "service": "mobile_app",
+                "message": "Motion detected",
+                "title": "Security Alert",
+                "timestamp": "2024-02-05T12:00:00Z",
+                "status": "delivered"
+            }
+        ]
+    }
+}
+

Error Handling

Common Error Codes

  • 404: Service not found
  • 401: Unauthorized
  • 400: Invalid request
  • 408: Delivery timeout
  • 422: Invalid notification data

Error Response Format

{
+    "success": false,
+    "message": "Error description",
+    "error_code": "ERROR_CODE"
+}
+

Rate Limiting

  • Default limit: 100 notifications per hour
  • Configurable through environment variables:
  • NOTIFY_RATE_LIMIT
  • NOTIFY_RATE_WINDOW

Best Practices

  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

Notification Templates

// Template example
+{
+    "template": "security_alert",
+    "data": {
+        "location": "living_room",
+        "event_type": "motion",
+        "timestamp": "2024-02-05T12:00:00Z"
+    }
+}
+

See Also

\ No newline at end of file diff --git a/tools/notifications/notify/index.html b/tools/notifications/notify/index.html deleted file mode 100644 index 3d0f4ca..0000000 --- a/tools/notifications/notify/index.html +++ /dev/null @@ -1,2458 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - Notify - Advanced Home Assistant MCP - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
- - - - - - -
- - -
- -
- - - - - - -
-
- - - -
-
-
- - - - - -
-
-
- - - - - - - -
-
- - - - - - - - -

Notification Tool

-

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

-

Features

-
    -
  • Send notifications
  • -
  • Support for multiple notification services
  • -
  • Custom notification data
  • -
  • Rich media support
  • -
  • Notification templates
  • -
  • Delivery tracking
  • -
  • Priority levels
  • -
  • Notification groups
  • -
-

Usage

-

REST API

-
POST /api/notify
-POST /api/notify/{service_id}
-GET /api/notify/services
-GET /api/notify/history
-
-

WebSocket

-
// Send notification
-{
-    "type": "send_notification",
-    "service": "required_service_id",
-    "message": "required_message",
-    "title": "optional_title",
-    "data": {
-        // Service-specific data
-    }
-}
-
-// Get notification services
-{
-    "type": "get_notification_services"
-}
-
-

Supported Services

-
    -
  • Mobile App
  • -
  • Email
  • -
  • SMS
  • -
  • Telegram
  • -
  • Discord
  • -
  • Slack
  • -
  • Push Notifications
  • -
  • Custom Services
  • -
-

Examples

-

Basic Notification

-
const response = await fetch('http://your-ha-mcp/api/notify/mobile_app', {
-    method: 'POST',
-    headers: {
-        'Authorization': 'Bearer your_access_token',
-        'Content-Type': 'application/json'
-    },
-    body: JSON.stringify({
-        "message": "Motion detected in living room",
-        "title": "Security Alert"
-    })
-});
-
-

Rich Notification

-
const response = await fetch('http://your-ha-mcp/api/notify/mobile_app', {
-    method: 'POST',
-    headers: {
-        'Authorization': 'Bearer your_access_token',
-        'Content-Type': 'application/json'
-    },
-    body: JSON.stringify({
-        "message": "Motion detected in living room",
-        "title": "Security Alert",
-        "data": {
-            "image": "https://your-camera-snapshot.jpg",
-            "actions": [
-                {
-                    "action": "view_camera",
-                    "title": "View Camera"
-                },
-                {
-                    "action": "dismiss",
-                    "title": "Dismiss"
-                }
-            ],
-            "priority": "high",
-            "ttl": 3600,
-            "group": "security"
-        }
-    })
-});
-
-

Service-Specific Example (Telegram)

-
const response = await fetch('http://your-ha-mcp/api/notify/telegram', {
-    method: 'POST',
-    headers: {
-        'Authorization': 'Bearer your_access_token',
-        'Content-Type': 'application/json'
-    },
-    body: JSON.stringify({
-        "message": "Temperature is too high!",
-        "title": "Climate Alert",
-        "data": {
-            "parse_mode": "markdown",
-            "inline_keyboard": [
-                [
-                    {
-                        "text": "Turn On AC",
-                        "callback_data": "turn_on_ac"
-                    }
-                ]
-            ]
-        }
-    })
-});
-
-

Response Format

-

Success Response

-
{
-    "success": true,
-    "data": {
-        "notification_id": "notification_123",
-        "status": "sent",
-        "timestamp": "2024-02-05T12:00:00Z",
-        "service": "mobile_app"
-    }
-}
-
-

Services List Response

-
{
-    "success": true,
-    "data": {
-        "services": [
-            {
-                "id": "mobile_app",
-                "name": "Mobile App",
-                "enabled": true,
-                "features": [
-                    "actions",
-                    "images",
-                    "sound"
-                ]
-            }
-        ]
-    }
-}
-
-

Notification History Response

-
{
-    "success": true,
-    "data": {
-        "history": [
-            {
-                "id": "notification_123",
-                "service": "mobile_app",
-                "message": "Motion detected",
-                "title": "Security Alert",
-                "timestamp": "2024-02-05T12:00:00Z",
-                "status": "delivered"
-            }
-        ]
-    }
-}
-
-

Error Handling

-

Common Error Codes

-
    -
  • 404: Service not found
  • -
  • 401: Unauthorized
  • -
  • 400: Invalid request
  • -
  • 408: Delivery timeout
  • -
  • 422: Invalid notification data
  • -
-

Error Response Format

-
{
-    "success": false,
-    "message": "Error description",
-    "error_code": "ERROR_CODE"
-}
-
-

Rate Limiting

-
    -
  • Default limit: 100 notifications per hour
  • -
  • Configurable through environment variables:
  • -
  • NOTIFY_RATE_LIMIT
  • -
  • NOTIFY_RATE_WINDOW
  • -
-

Best Practices

-
    -
  1. Use appropriate priority levels
  2. -
  3. Group related notifications
  4. -
  5. Include relevant context
  6. -
  7. Implement proper error handling
  8. -
  9. Use templates for consistency
  10. -
  11. Consider time zones
  12. -
  13. Respect user preferences
  14. -
  15. Handle rate limiting gracefully
  16. -
-

Notification Templates

-
// Template example
-{
-    "template": "security_alert",
-    "data": {
-        "location": "living_room",
-        "event_type": "motion",
-        "timestamp": "2024-02-05T12:00:00Z"
-    }
-}
-
-

See Also

- - - - - - - - - - - - - - - - - - - - - - - -
-
- - - -
- - - -
- - - -
-
-
-
- - - - - - - - - - - - \ No newline at end of file diff --git a/tools/tools/index.html b/tools/tools/index.html deleted file mode 100644 index 8f2b8be..0000000 --- a/tools/tools/index.html +++ /dev/null @@ -1,2238 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - Overview - Advanced Home Assistant MCP - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
- - - - - - -
- - -
- -
- - - - - - -
-
- - - -
-
-
- - - - - -
-
-
- - - - - - - -
-
- - - - - - - - -

Home Assistant MCP Tools

-

This section documents all available tools in the Home Assistant MCP.

-

Available Tools

-

Device Management

-
    -
  1. List Devices
  2. -
  3. List all available Home Assistant devices
  4. -
  5. Group devices by domain
  6. -
  7. -

    Get device states and attributes

    -
  8. -
  9. -

    Device Control

    -
  10. -
  11. Control various device types
  12. -
  13. Support for lights, switches, covers, climate devices
  14. -
  15. Domain-specific commands and parameters
  16. -
-

History and State

-
    -
  1. History
  2. -
  3. Fetch device state history
  4. -
  5. Filter by time range
  6. -
  7. -

    Get significant changes

    -
  8. -
  9. -

    Scene Management

    -
  10. -
  11. List available scenes
  12. -
  13. Activate scenes
  14. -
  15. Scene state information
  16. -
-

Automation

-
    -
  1. Automation Management
  2. -
  3. List automations
  4. -
  5. Toggle automation state
  6. -
  7. -

    Trigger automations manually

    -
  8. -
  9. -

    Automation Configuration

    -
  10. -
  11. Create new automations
  12. -
  13. Update existing automations
  14. -
  15. Delete automations
  16. -
  17. Duplicate automations
  18. -
-

Add-ons and Packages

-
    -
  1. Add-on Management
  2. -
  3. List available add-ons
  4. -
  5. Install/uninstall add-ons
  6. -
  7. Start/stop/restart add-ons
  8. -
  9. -

    Get add-on information

    -
  10. -
  11. -

    Package Management

    -
  12. -
  13. Manage HACS packages
  14. -
  15. Install/update/remove packages
  16. -
  17. List available packages by category
  18. -
-

Notifications

-
    -
  1. Notify
  2. -
  3. Send notifications
  4. -
  5. Support for multiple notification services
  6. -
  7. Custom notification data
  8. -
-

Real-time Events

-
    -
  1. Event Subscription
  2. -
  3. Subscribe to Home Assistant events
  4. -
  5. Monitor specific entities
  6. -
  7. -

    Domain-based monitoring

    -
  8. -
  9. -

    SSE Statistics

    -
  10. -
  11. Get SSE connection statistics
  12. -
  13. Monitor active subscriptions
  14. -
  15. Connection management
  16. -
-

Using Tools

-

All tools can be accessed through:

-
    -
  1. REST API endpoints
  2. -
  3. WebSocket connections
  4. -
  5. Server-Sent Events (SSE)
  6. -
-

Authentication

-

Tools require authentication using: -- Home Assistant Long-Lived Access Token -- JWT tokens for specific operations

-

Error Handling

-

All tools follow a consistent error handling pattern: -

{
-    success: boolean;
-    message?: string;
-    data?: any;
-}
-

-

Rate Limiting

-

Tools are subject to rate limiting: -- Default: 100 requests per 15 minutes -- Configurable through environment variables

-

Tool Development

-

Want to create a new tool? Check out: -- Tool Development Guide -- Tool Interface Documentation -- Best Practices

-

Examples

-

Each tool documentation includes: -- Usage examples -- Code snippets -- Common use cases -- Troubleshooting tips

-

Support

-

Need help with tools? -- Check individual tool documentation -- See Troubleshooting Guide -- Create an issue on GitHub

- - - - - - - - - - - - - - - - - - - - - - -
-
- - - -
- - - -
- - - -
-
-
-
- - - - - - - - - - - - \ No newline at end of file diff --git a/troubleshooting.html b/troubleshooting.html new file mode 100644 index 0000000..e9d8a83 --- /dev/null +++ b/troubleshooting.html @@ -0,0 +1,96 @@ + Troubleshooting - MCP Server for Home Assistant

Troubleshooting Guide 🔧

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

Quick Diagnostics

Health Check

First, verify the server's health:

curl http://localhost:3000/health
+

Expected response:

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

Common Issues

1. Connection Issues

Cannot Connect to MCP Server

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

Solutions:

  1. Check if the server is running:

    # For Docker installation
    +docker compose ps
    +
    +# For manual installation
    +ps aux | grep mcp
    +

  2. Verify port availability:

    # Check if port is in use
    +netstat -tuln | grep 3000
    +

  3. Check logs:

    # Docker logs
    +docker compose logs mcp
    +
    +# Manual installation logs
    +bun run dev
    +

Home Assistant Connection Failed

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
    +HA_TOKEN=your_long_lived_access_token
    +

  2. Test Home Assistant connection:

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

  3. Check network connectivity:

    # For Docker setup
    +docker compose exec mcp ping homeassistant
    +

2. Authentication Issues

Invalid Token

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

Solutions:

  1. Generate a new token:

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

  2. Verify token format:

    // Token should be in format:
    +Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
    +

Rate Limiting

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

Solutions:

  1. Check current rate limit status:

    curl -I http://localhost:3000/api/state
    +

  2. Adjust rate limits in configuration:

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

3. Real-time Updates Issues

SSE Connection Drops

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

Solutions:

  1. Implement proper reconnection logic:

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

  2. Check network stability:

    # Monitor connection stability
    +ping -c 100 localhost
    +

4. Performance Issues

High Latency

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

Solutions:

  1. Enable Redis caching:

    REDIS_ENABLED=true
    +REDIS_URL=redis://localhost:6379
    +

  2. Monitor system resources:

    # Check CPU and memory usage
    +docker stats
    +
    +# Or for manual installation
    +top -p $(pgrep -f mcp)
    +

  3. Optimize database queries and caching:

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

5. Device Control Issues

Commands Not Executing

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
    +

  2. Check command syntax:

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

  3. Review Home Assistant logs:

    docker compose exec homeassistant journalctl -f
    +

Debugging Tools

Log Analysis

Enable debug logging:

LOG_LEVEL=debug
+DEBUG=mcp:*
+

Network Debugging

Monitor network traffic:

# TCP dump for API traffic
+tcpdump -i any port 3000 -w debug.pcap
+

Performance Profiling

Enable performance monitoring:

ENABLE_METRICS=true
+METRICS_PORT=9090
+

Getting Help

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

Maintenance

Regular Health Checks

Run periodic health checks:

# Create a cron job
+*/5 * * * * curl -f http://localhost:3000/health || notify-admin
+

Log Rotation

Configure log rotation:

logging:
+  maxSize: "100m"
+  maxFiles: "7d"
+  compress: true
+

Backup Configuration

Regularly backup your configuration:

# Backup script
+tar -czf mcp-backup-$(date +%Y%m%d).tar.gz \
+    .env \
+    config/ \
+    data/
+

FAQ

General Questions

Q: What is MCP Server?

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

Q: What are the system requirements?

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

Q: How do I update MCP Server?

A: For Docker installation:

docker compose pull
+docker compose up -d
+
For manual installation:
git pull
+bun install
+bun run build
+

Integration Questions

Q: Can I use MCP Server with any Home Assistant instance?

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

Q: Does MCP Server support all Home Assistant integrations?

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

Security Questions

Q: Is my Home Assistant token secure?

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

Q: Can I use MCP Server remotely?

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

Troubleshooting Questions

Q: Why are my device states not updating?

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

Q: Why are my commands not working?

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

\ No newline at end of file diff --git a/troubleshooting/index.html b/troubleshooting/index.html deleted file mode 100644 index 34b76d9..0000000 --- a/troubleshooting/index.html +++ /dev/null @@ -1,2992 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - Troubleshooting - Advanced Home Assistant MCP - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
- - - - - - -
- - -
- -
- - - - - - -
-
- - - -
-
-
- - - - - -
-
-
- - - -
-
-
- - - -
-
-
- - - -
-
- - - - - - - - -

Troubleshooting Guide 🔧

-

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

-

Quick Diagnostics

-

Health Check

-

First, verify the server's health:

-
curl http://localhost:3000/health
-
-

Expected response: -

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

-

Common Issues

-

1. Connection Issues

-

Cannot Connect to MCP Server

-

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

-

Solutions:

-
    -
  1. -

    Check if the server is running: -

    # For Docker installation
    -docker compose ps
    -
    -# For manual installation
    -ps aux | grep mcp
    -

    -
  2. -
  3. -

    Verify port availability: -

    # Check if port is in use
    -netstat -tuln | grep 3000
    -

    -
  4. -
  5. -

    Check logs: -

    # Docker logs
    -docker compose logs mcp
    -
    -# Manual installation logs
    -bun run dev
    -

    -
  6. -
-

Home Assistant Connection Failed

-

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
    -HA_TOKEN=your_long_lived_access_token
    -

    -
  2. -
  3. -

    Test Home Assistant connection: -

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

    -
  4. -
  5. -

    Check network connectivity: -

    # For Docker setup
    -docker compose exec mcp ping homeassistant
    -

    -
  6. -
-

2. Authentication Issues

-

Invalid Token

-

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

-

Solutions:

-
    -
  1. -

    Generate a new token: -

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

    -
  2. -
  3. -

    Verify token format: -

    // Token should be in format:
    -Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
    -

    -
  4. -
-

Rate Limiting

-

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

-

Solutions:

-
    -
  1. -

    Check current rate limit status: -

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

    -
  2. -
  3. -

    Adjust rate limits in configuration: -

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

    -
  4. -
-

3. Real-time Updates Issues

-

SSE Connection Drops

-

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

-

Solutions:

-
    -
  1. -

    Implement proper reconnection logic: -

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

    -
  2. -
  3. -

    Check network stability: -

    # Monitor connection stability
    -ping -c 100 localhost
    -

    -
  4. -
-

4. Performance Issues

-

High Latency

-

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

-

Solutions:

-
    -
  1. -

    Enable Redis caching: -

    REDIS_ENABLED=true
    -REDIS_URL=redis://localhost:6379
    -

    -
  2. -
  3. -

    Monitor system resources: -

    # Check CPU and memory usage
    -docker stats
    -
    -# Or for manual installation
    -top -p $(pgrep -f mcp)
    -

    -
  4. -
  5. -

    Optimize database queries and caching: -

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

    -
  6. -
-

5. Device Control Issues

-

Commands Not Executing

-

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
    -

    -
  2. -
  3. -

    Check command syntax: -

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

    -
  4. -
  5. -

    Review Home Assistant logs: -

    docker compose exec homeassistant journalctl -f
    -

    -
  6. -
-

Debugging Tools

-

Log Analysis

-

Enable debug logging:

-
LOG_LEVEL=debug
-DEBUG=mcp:*
-
-

Network Debugging

-

Monitor network traffic:

-
# TCP dump for API traffic
-tcpdump -i any port 3000 -w debug.pcap
-
-

Performance Profiling

-

Enable performance monitoring:

-
ENABLE_METRICS=true
-METRICS_PORT=9090
-
-

Getting Help

-

If you're still experiencing issues:

-
    -
  1. Check the GitHub Issues
  2. -
  3. Search Discussions
  4. -
  5. Create a new issue with:
  6. -
  7. Detailed description
  8. -
  9. Logs
  10. -
  11. Configuration (sanitized)
  12. -
  13. Steps to reproduce
  14. -
-

Maintenance

-

Regular Health Checks

-

Run periodic health checks:

-
# Create a cron job
-*/5 * * * * curl -f http://localhost:3000/health || notify-admin
-
-

Log Rotation

-

Configure log rotation:

-
logging:
-  maxSize: "100m"
-  maxFiles: "7d"
-  compress: true
-
-

Backup Configuration

-

Regularly backup your configuration:

-
# Backup script
-tar -czf mcp-backup-$(date +%Y%m%d).tar.gz \
-    .env \
-    config/ \
-    data/
-
-

FAQ

-

General Questions

-

Q: What is MCP Server?

-

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

-

Q: What are the system requirements?

-

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

-

Q: How do I update MCP Server?

-

A: For Docker installation: -

docker compose pull
-docker compose up -d
-
-For manual installation: -
git pull
-bun install
-bun run build
-

-

Integration Questions

-

Q: Can I use MCP Server with any Home Assistant instance?

-

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

-

Q: Does MCP Server support all Home Assistant integrations?

-

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

-

Security Questions

-

Q: Is my Home Assistant token secure?

-

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

-

Q: Can I use MCP Server remotely?

-

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

-

Troubleshooting Questions

-

Q: Why are my device states not updating?

-

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

-

Q: Why are my commands not working?

-

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

- - - - - - - - - - - - - - - - - - - - - - -
-
- - - -
- - - -
- - - -
-
-
-
- - - - - - - - - - - - \ No newline at end of file diff --git a/usage.html b/usage.html new file mode 100644 index 0000000..4cb4ce1 --- /dev/null +++ b/usage.html @@ -0,0 +1,22 @@ + Usage - MCP Server for Home Assistant

Usage Guide

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

Basic Setup

  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

Device Control

REST API Interactions

Basic device control can be performed via the REST API:

// Turn on a light
+fetch('http://localhost:3000/api/control', {
+  method: 'POST',
+  headers: {
+    'Content-Type': 'application/json',
+    'Authorization': `Bearer ${token}`
+  },
+  body: JSON.stringify({
+    entity_id: 'light.living_room',
+    command: 'turn_on',
+    parameters: { brightness: 50 }
+  })
+});
+

Supported Commands

  • turn_on
  • turn_off
  • toggle
  • set_brightness

Supported Entities

  • Lights
  • Switches
  • Climate controls
  • Media players

Real-Time Updates

WebSocket Connection

Subscribe to real-time device state changes:

const ws = new WebSocket('ws://localhost:3000/events');
+ws.onmessage = (event) => {
+  const deviceUpdate = JSON.parse(event.data);
+  console.log('Device state changed:', deviceUpdate);
+};
+

Authentication

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

Limitations

  • Basic device control only
  • Limited error handling
  • Minimal third-party integrations

Troubleshooting

  1. Verify Home Assistant connection
  2. Check JWT token validity
  3. Ensure correct entity IDs
  4. Review server logs for detailed errors

Configuration

Configure the server using environment variables in .env:

HA_URL=http://homeassistant:8123
+HA_TOKEN=your_home_assistant_token
+JWT_SECRET=your_jwt_secret
+

Next Steps

\ No newline at end of file diff --git a/usage/index.html b/usage/index.html deleted file mode 100644 index f946c11..0000000 --- a/usage/index.html +++ /dev/null @@ -1,2158 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - Usage - Advanced Home Assistant MCP - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
- - - - - - -
- - -
- -
- - - - - - -
-
- - - -
-
-
- - - - - -
-
-
- - - - - - - -
-
- - - - - - - - -

Usage Guide

-

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

-

Basic Setup

-
    -
  1. Starting the Server:
  2. -
  3. Development mode: bun run dev
  4. -
  5. -

    Production mode: bun run start

    -
  6. -
  7. -

    Accessing the Server:

    -
  8. -
  9. Default URL: http://localhost:3000
  10. -
  11. Ensure Home Assistant credentials are configured in .env
  12. -
-

Device Control

-

REST API Interactions

-

Basic device control can be performed via the REST API:

-
// Turn on a light
-fetch('http://localhost:3000/api/control', {
-  method: 'POST',
-  headers: {
-    'Content-Type': 'application/json',
-    'Authorization': `Bearer ${token}`
-  },
-  body: JSON.stringify({
-    entity_id: 'light.living_room',
-    command: 'turn_on',
-    parameters: { brightness: 50 }
-  })
-});
-
-

Supported Commands

-
    -
  • turn_on
  • -
  • turn_off
  • -
  • toggle
  • -
  • set_brightness
  • -
-

Supported Entities

-
    -
  • Lights
  • -
  • Switches
  • -
  • Climate controls
  • -
  • Media players
  • -
-

Real-Time Updates

-

WebSocket Connection

-

Subscribe to real-time device state changes:

-
const ws = new WebSocket('ws://localhost:3000/events');
-ws.onmessage = (event) => {
-  const deviceUpdate = JSON.parse(event.data);
-  console.log('Device state changed:', deviceUpdate);
-};
-
-

Authentication

-

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

-

Limitations

-
    -
  • Basic device control only
  • -
  • Limited error handling
  • -
  • Minimal third-party integrations
  • -
-

Troubleshooting

-
    -
  1. Verify Home Assistant connection
  2. -
  3. Check JWT token validity
  4. -
  5. Ensure correct entity IDs
  6. -
  7. Review server logs for detailed errors
  8. -
-

Configuration

-

Configure the server using environment variables in .env:

-
HA_URL=http://homeassistant:8123
-HA_TOKEN=your_home_assistant_token
-JWT_SECRET=your_jwt_secret
-
-

Next Steps

- - - - - - - - - - - - - - - - - - - - - - - -
-
- - - -
- - - -
- - - -
-
-
-
- - - - - - - - - - - - \ No newline at end of file