From 986b1949cd99ac27b8c16db4e43098a1efd842a3 Mon Sep 17 00:00:00 2001 From: jango-blockchained Date: Sat, 8 Feb 2025 17:26:20 +0100 Subject: [PATCH] Remove documentation from main branch (moved to gh-pages) --- docs/Gemfile | 23 - docs/_config.yml | 78 ---- docs/_layouts/default.html | 52 --- docs/api.md | 170 -------- docs/api/core.md | 326 -------------- docs/api/index.md | 242 ----------- docs/api/sse.md | 266 ------------ docs/architecture.md | 88 ---- docs/assets/css/style.scss | 54 --- docs/assets/stylesheets/extra.css | 28 -- docs/config/claude_desktop_config.json | 16 - docs/config/cline_config.json | 18 - docs/config/index.md | 30 -- docs/configuration.md | 429 ------------------- docs/contributing.md | 124 ------ docs/deployment.md | 141 ------ docs/development/best-practices.md | 310 -------------- docs/development/environment.md | 197 --------- docs/development/index.md | 54 --- docs/development/interfaces.md | 296 ------------- docs/development/tools.md | 226 ---------- docs/examples/index.md | 22 - docs/extras.md | 228 ---------- docs/features/speech.md | 212 --------- docs/getting-started/configuration.md | 5 - docs/getting-started/docker.md | 255 ----------- docs/getting-started/index.md | 8 - docs/getting-started/installation.md | 181 -------- docs/getting-started/quickstart.md | 219 ---------- docs/index.md | 143 ------- docs/javascripts/extra.js | 62 --- docs/javascripts/mathjax.js | 12 - docs/nlp.md | 196 --------- docs/prompts.md | 263 ------------ docs/requirements.txt | 42 -- docs/roadmap.md | 52 --- docs/security.md | 146 ------- docs/stylesheets/extra.css | 164 ------- docs/testing.md | 422 ------------------ docs/tools/addons-packages/addon.md | 240 ----------- docs/tools/addons-packages/package.md | 236 ---------- docs/tools/automation/automation-config.md | 321 -------------- docs/tools/automation/automation.md | 211 --------- docs/tools/device-management/control.md | 195 --------- docs/tools/device-management/list-devices.md | 139 ------ docs/tools/events/sse-stats.md | 251 ----------- docs/tools/events/subscribe-events.md | 253 ----------- docs/tools/history-state/history.md | 167 -------- docs/tools/history-state/scene.md | 215 ---------- docs/tools/index.md | 42 -- docs/tools/notifications/notify.md | 249 ----------- docs/troubleshooting.md | 374 ---------------- docs/usage.md | 96 ----- mkdocs.yml | 169 -------- 54 files changed, 8958 deletions(-) delete mode 100644 docs/Gemfile delete mode 100644 docs/_config.yml delete mode 100644 docs/_layouts/default.html delete mode 100644 docs/api.md delete mode 100644 docs/api/core.md delete mode 100644 docs/api/index.md delete mode 100644 docs/api/sse.md delete mode 100644 docs/architecture.md delete mode 100644 docs/assets/css/style.scss delete mode 100644 docs/assets/stylesheets/extra.css delete mode 100644 docs/config/claude_desktop_config.json delete mode 100644 docs/config/cline_config.json delete mode 100644 docs/config/index.md delete mode 100644 docs/configuration.md delete mode 100644 docs/contributing.md delete mode 100644 docs/deployment.md delete mode 100644 docs/development/best-practices.md delete mode 100644 docs/development/environment.md delete mode 100644 docs/development/index.md delete mode 100644 docs/development/interfaces.md delete mode 100644 docs/development/tools.md delete mode 100644 docs/examples/index.md delete mode 100644 docs/extras.md delete mode 100644 docs/features/speech.md delete mode 100644 docs/getting-started/configuration.md delete mode 100644 docs/getting-started/docker.md delete mode 100644 docs/getting-started/index.md delete mode 100644 docs/getting-started/installation.md delete mode 100644 docs/getting-started/quickstart.md delete mode 100644 docs/index.md delete mode 100644 docs/javascripts/extra.js delete mode 100644 docs/javascripts/mathjax.js delete mode 100644 docs/nlp.md delete mode 100644 docs/prompts.md delete mode 100644 docs/requirements.txt delete mode 100644 docs/roadmap.md delete mode 100644 docs/security.md delete mode 100644 docs/stylesheets/extra.css delete mode 100644 docs/testing.md delete mode 100644 docs/tools/addons-packages/addon.md delete mode 100644 docs/tools/addons-packages/package.md delete mode 100644 docs/tools/automation/automation-config.md delete mode 100644 docs/tools/automation/automation.md delete mode 100644 docs/tools/device-management/control.md delete mode 100644 docs/tools/device-management/list-devices.md delete mode 100644 docs/tools/events/sse-stats.md delete mode 100644 docs/tools/events/subscribe-events.md delete mode 100644 docs/tools/history-state/history.md delete mode 100644 docs/tools/history-state/scene.md delete mode 100644 docs/tools/index.md delete mode 100644 docs/tools/notifications/notify.md delete mode 100644 docs/troubleshooting.md delete mode 100644 docs/usage.md delete mode 100644 mkdocs.yml diff --git a/docs/Gemfile b/docs/Gemfile deleted file mode 100644 index 3791019..0000000 --- a/docs/Gemfile +++ /dev/null @@ -1,23 +0,0 @@ -source "https://rubygems.org" - -gem "github-pages", group: :jekyll_plugins -gem "jekyll-theme-minimal" -gem "jekyll-relative-links" -gem "jekyll-seo-tag" -gem "jekyll-remote-theme" -gem "jekyll-github-metadata" -gem "faraday-retry" - -# Windows and JRuby does not include zoneinfo files, so bundle the tzinfo-data gem -# and associated library. -platforms :mingw, :x64_mingw, :mswin, :jruby do - gem "tzinfo", ">= 1" - gem "tzinfo-data" -end - -# Lock `http_parser.rb` gem to `v0.6.x` on JRuby builds since newer versions of the gem -# do not have a Java counterpart. -gem "http_parser.rb", "~> 0.6.0", :platforms => [:jruby] - -# Add webrick for Ruby 3.0+ -gem "webrick", "~> 1.7" \ No newline at end of file diff --git a/docs/_config.yml b/docs/_config.yml deleted file mode 100644 index 808b492..0000000 --- a/docs/_config.yml +++ /dev/null @@ -1,78 +0,0 @@ -title: Model Context Protocol (MCP) -description: A bridge between Home Assistant and Language Learning Models -theme: jekyll-theme-minimal -markdown: kramdown - -# Repository settings -repository: jango-blockchained/advanced-homeassistant-mcp -github: [metadata] - -# Add base URL and URL settings -baseurl: "/advanced-homeassistant-mcp" # the subpath of your site -url: "https://jango-blockchained.github.io" # the base hostname & protocol - -# Theme settings -logo: /assets/img/logo.png # path to logo (create this if you want a logo) -show_downloads: true # show download buttons for your repo - -plugins: - - jekyll-relative-links - - jekyll-seo-tag - - jekyll-remote-theme - - jekyll-github-metadata - -# Enable relative links -relative_links: - enabled: true - collections: true - -# Navigation structure -header_pages: - - index.md - - getting-started.md - - api.md - - usage.md - - tools/tools.md - - development/development.md - - troubleshooting.md - - contributing.md - - roadmap.md - -# Collections -collections: - tools: - output: true - permalink: /:collection/:name - development: - output: true - permalink: /:collection/:name - -# Default layouts -defaults: - - scope: - path: "" - type: "pages" - values: - layout: "default" - - scope: - path: "tools" - type: "tools" - values: - layout: "default" - - scope: - path: "development" - type: "development" - values: - layout: "default" - -# Exclude files from processing -exclude: - - Gemfile - - Gemfile.lock - - node_modules - - vendor - -# Sass settings -sass: - style: compressed - sass_dir: _sass \ No newline at end of file diff --git a/docs/_layouts/default.html b/docs/_layouts/default.html deleted file mode 100644 index e350c93..0000000 --- a/docs/_layouts/default.html +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - - - {% seo %} - - - - -
-
-

{{ site.title | default: site.github.repository_name }}

- - {% if site.logo %} - Logo - {% endif %} - -

{{ site.description | default: site.github.project_tagline }}

- -

View the Project on GitHub {{ - site.github.repository_nwo }}

- - -
-
- {{ content }} -
- -
- - - - \ No newline at end of file diff --git a/docs/api.md b/docs/api.md deleted file mode 100644 index 731192f..0000000 --- a/docs/api.md +++ /dev/null @@ -1,170 +0,0 @@ -# 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: - -```http -Authorization: Bearer YOUR_TOKEN -``` - -## Core Endpoints - -### Device State Management - -#### Get Device State -```http -GET /api/state/{entity_id} -``` - -**Response:** -```json -{ - "entity_id": "light.living_room", - "state": "on", - "attributes": { - "brightness": 128 - } -} -``` - -#### Update Device State -```http -POST /api/state -Content-Type: application/json - -{ - "entity_id": "light.living_room", - "state": "on", - "attributes": { - "brightness": 128 - } -} -``` - -### Device Control - -#### Execute Device Command -```http -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: - -```javascript -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 - -```json -{ - "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 - -```typescript -async function controlDevice(entityId: string, command: string, params?: Record) { - 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.* diff --git a/docs/api/core.md b/docs/api/core.md deleted file mode 100644 index adc20e6..0000000 --- a/docs/api/core.md +++ /dev/null @@ -1,326 +0,0 @@ ---- -layout: default -title: Core Functions -parent: API Reference -nav_order: 3 ---- - -# 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. - -```http -GET /api/state -GET /api/state/{entity_id} -``` - -Parameters: -- `entity_id` (optional): Specific device ID to query - -```bash -# Get all states -curl http://localhost:3000/api/state - -# Get specific device state -curl http://localhost:3000/api/state/light.living_room -``` - -Response: -```json -{ - "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. - -```http -POST /api/device/control -``` - -Request body: -```json -{ - "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: -```bash -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. - -```http -POST /api/command -``` - -Request body: -```json -{ - "command": "Turn on the living room lights and set them to 50% brightness" -} -``` - -Example usage: -```bash -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: -```json -{ - "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. - -```http -POST /api/scene -``` - -Request body: -```json -{ - "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. - -```http -POST /api/scene/{scene_name}/activate -``` - -Example: -```bash -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. - -```http -POST /api/group -``` - -Request body: -```json -{ - "name": "Living Room", - "entities": [ - "light.living_room_main", - "light.living_room_accent", - "switch.living_room_fan" - ] -} -``` - -### Control Group - -Control multiple devices in a group. - -```http -POST /api/group/{group_name}/control -``` - -Request body: -```json -{ - "action": "turn_off" -} -``` - -## System Operations - -### Health Check - -Check server status and connectivity. - -```http -GET /health -``` - -Response: -```json -{ - "status": "healthy", - "version": "1.0.0", - "uptime": 3600, - "homeAssistant": { - "connected": true, - "version": "2024.1.0" - } -} -``` - -### Configuration - -Get current server configuration. - -```http -GET /api/config -``` - -Response: -```json -{ - "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: - -```json -{ - "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 - -```typescript -interface DeviceState { - entity_id: string; - state: string; - attributes: Record; - last_changed: string; -} - -interface DeviceCommand { - entity_id: string; - action: 'turn_on' | 'turn_off' | 'toggle' | 'set_value'; - parameters?: Record; -} - -interface Scene { - name: string; - description?: string; - actions: DeviceCommand[]; -} - -interface Group { - name: string; - entities: string[]; -} -``` - -## Related Resources - -- [API Overview](index.md) -- [SSE API](sse.md) -- [Architecture](../architecture.md) -- [Examples](https://github.com/jango-blockchained/advanced-homeassistant-mcp/tree/main/examples) \ No newline at end of file diff --git a/docs/api/index.md b/docs/api/index.md deleted file mode 100644 index debcbb2..0000000 --- a/docs/api/index.md +++ /dev/null @@ -1,242 +0,0 @@ ---- -layout: default -title: API Overview -parent: API Reference -nav_order: 1 -has_children: false ---- - -# 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: - -```bash -# Include the token in your requests -curl -H "Authorization: Bearer YOUR_JWT_TOKEN" http://localhost:3000/api/state -``` - -To obtain a token: - -```bash -curl -X POST http://localhost:3000/auth/token \ - -H "Content-Type: application/json" \ - -d '{"username": "your_username", "password": "your_password"}' -``` - -## Core Endpoints - -### Device State - -```http -GET /api/state -``` - -Retrieve the current state of all devices: - -```bash -curl http://localhost:3000/api/state -``` - -Response: -```json -{ - "devices": [ - { - "id": "light.living_room", - "state": "on", - "attributes": { - "brightness": 255, - "color_temp": 370 - } - } - ] -} -``` - -### Command Execution - -```http -POST /api/command -``` - -Execute a natural language command: - -```bash -curl -X POST http://localhost:3000/api/command \ - -H "Content-Type: application/json" \ - -d '{"command": "Turn on the kitchen lights"}' -``` - -Response: -```json -{ - "success": true, - "action": "turn_on", - "device": "light.kitchen", - "message": "Kitchen lights turned on" -} -``` - -## Real-Time Events - -### Event Subscription - -```http -GET /subscribe_events -``` - -Subscribe to device state changes: - -```javascript -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: - -```http -GET /subscribe_events?domain=light -GET /subscribe_events?entity_id=light.living_room -``` - -## Scene Management - -### Create Scene - -```http -POST /api/scene -``` - -Create a new scene: - -```bash -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 - -```http -POST /api/scene/activate -``` - -Activate an existing scene: - -```bash -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: - -```json -{ - "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: - -```http -X-RateLimit-Limit: 100 -X-RateLimit-Remaining: 99 -X-RateLimit-Reset: 1640995200 -``` - -When exceeded, returns `429 Too Many Requests`: - -```json -{ - "error": true, - "message": "Rate limit exceeded", - "reset": 1640995200 -} -``` - -## WebSocket API - -For bi-directional communication: - -```javascript -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: - -```http -/api/v1/state -/api/v1/command -``` - -## Further Reading - -- [SSE API Details](sse.md) - In-depth SSE documentation -- [Core Functions](core.md) - Detailed endpoint documentation -- [Architecture Overview](../architecture.md) - System design details -- [Troubleshooting](../troubleshooting.md) - Common issues and solutions - -# API Reference - -The Advanced Home Assistant MCP provides several APIs for integration and automation: - -- [Core API](core.md) - Primary interface for system control -- [SSE API](sse.md) - Server-Sent Events for real-time updates -- [Core Functions](core.md) - Essential system functions \ No newline at end of file diff --git a/docs/api/sse.md b/docs/api/sse.md deleted file mode 100644 index fa75bd5..0000000 --- a/docs/api/sse.md +++ /dev/null @@ -1,266 +0,0 @@ ---- -layout: default -title: SSE API -parent: API Reference -nav_order: 2 ---- - -# 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: - -```javascript -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: - -```javascript -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: - -```javascript -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: -```json -{ - "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: - -```javascript -// 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: - -```javascript -// 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: - -```javascript -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: - -```javascript -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** - - Always include authentication tokens - - Implement token refresh mechanisms - - Handle authentication errors gracefully - -2. **Error Handling** - - Implement progressive retry logic - - Log connection issues - - Notify users of connection status - -3. **Resource Management** - - Close EventSource connections when not needed - - Limit the number of concurrent connections - - Use filtered subscriptions when possible - -4. **Performance** - - Process events efficiently - - Batch UI updates - - Consider debouncing frequent updates - -## Common Issues - -### Connection Drops -If the connection drops, the EventSource will automatically attempt to reconnect. You can customize this behavior: - -```javascript -eventSource.addEventListener('error', (error) => { - if (eventSource.readyState === EventSource.CLOSED) { - // Connection closed, implement custom retry logic - } -}); -``` - -### Memory Leaks -Always clean up EventSource connections: - -```javascript -// In a React component -useEffect(() => { - const eventSource = new EventSource('http://localhost:3000/subscribe_events'); - - return () => { - eventSource.close(); // Cleanup on unmount - }; -}, []); -``` - -## Related Resources - -- [API Overview](index.md) -- [Core Functions](core.md) -- [WebSocket API](index.md#websocket-api) -- [Troubleshooting](../troubleshooting.md) \ No newline at end of file diff --git a/docs/architecture.md b/docs/architecture.md deleted file mode 100644 index 3a0e5a5..0000000 --- a/docs/architecture.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -layout: default -title: Architecture -nav_order: 4 ---- - -# 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 - -```mermaid -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/docs/assets/css/style.scss b/docs/assets/css/style.scss deleted file mode 100644 index bd19b34..0000000 --- a/docs/assets/css/style.scss +++ /dev/null @@ -1,54 +0,0 @@ -@import "{{ site.theme }}"; - -// Custom styles -.main-nav { - margin-top: 20px; - - ul { - list-style: none; - padding: 0; - margin: 0; - } - - li { - margin-bottom: 8px; - } - - a { - color: #267CB9; - text-decoration: none; - - &:hover { - text-decoration: underline; - } - } -} - -h1, -h2, -h3 { - color: #333; -} - -code { - background-color: #f8f8f8; - border: 1px solid #ddd; - border-radius: 3px; - padding: 2px 5px; -} - -pre { - background-color: #f8f8f8; - border: 1px solid #ddd; - border-radius: 3px; - padding: 10px; - overflow-x: auto; -} - -.wrapper { - max-width: 960px; -} - -section { - max-width: 700px; -} \ No newline at end of file diff --git a/docs/assets/stylesheets/extra.css b/docs/assets/stylesheets/extra.css deleted file mode 100644 index b6a4017..0000000 --- a/docs/assets/stylesheets/extra.css +++ /dev/null @@ -1,28 +0,0 @@ -:root { - --md-primary-fg-color: #1a73e8; - --md-primary-fg-color--light: #5195ee; - --md-primary-fg-color--dark: #0d47a1; -} - -.md-header { - box-shadow: 0 0 0.2rem rgba(0,0,0,.1), 0 0.2rem 0.4rem rgba(0,0,0,.2); -} - -.md-main__inner { - margin-top: 1.5rem; -} - -.md-typeset h1 { - font-weight: 700; - color: var(--md-primary-fg-color); -} - -.md-typeset .admonition { - font-size: .8rem; -} - -code { - background-color: rgba(175,184,193,0.2); - padding: .2em .4em; - border-radius: 6px; -} \ No newline at end of file diff --git a/docs/config/claude_desktop_config.json b/docs/config/claude_desktop_config.json deleted file mode 100644 index ec8b609..0000000 --- a/docs/config/claude_desktop_config.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "mcpServers": { - "homeassistant-mcp": { - "command": "bun", - "args": [ - "run", - "start", - "--port", - "8080" - ], - "env": { - "NODE_ENV": "production" - } - } - } -} \ No newline at end of file diff --git a/docs/config/cline_config.json b/docs/config/cline_config.json deleted file mode 100644 index a86f75c..0000000 --- a/docs/config/cline_config.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "mcpServers": { - "homeassistant-mcp": { - "command": "bun", - "args": [ - "run", - "start", - "--enable-cline", - "--config", - "${configDir}/.env" - ], - "env": { - "NODE_ENV": "production", - "CLINE_MODE": "true" - } - } - } -} \ No newline at end of file diff --git a/docs/config/index.md b/docs/config/index.md deleted file mode 100644 index aec4d5a..0000000 --- a/docs/config/index.md +++ /dev/null @@ -1,30 +0,0 @@ -# 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 - -- See [System Configuration](../configuration.md) for detailed configuration options -- Check [Environment Setup](../getting-started/configuration.md) for initial setup -- Review [Security](../security.md) for security-related configurations \ No newline at end of file diff --git a/docs/configuration.md b/docs/configuration.md deleted file mode 100644 index d335d08..0000000 --- a/docs/configuration.md +++ /dev/null @@ -1,429 +0,0 @@ -# System Configuration - -This document provides detailed information about configuring the Home Assistant MCP Server. - -## Environment File Structure - -The MCP Server uses a flexible environment configuration system with support for different environments and local overrides: - -### Environment Files - -1. `.env.example` - Template file containing all available configuration options with example values - - Use this as a reference to create your environment-specific configuration files - - Not loaded by the application - -2. Environment-specific files (loaded based on NODE_ENV): - - `.env.dev` - Development environment (default) - - `.env.test` - Test environment - - `.env.prod` - Production environment - -3. `.env` - Optional local override file - - If present, values in this file override those from the environment-specific file - - Useful for local development without modifying the environment-specific files - -### File Loading Order - -1. First, the environment-specific file is loaded based on NODE_ENV: - - `NODE_ENV=production` → `.env.prod` - - `NODE_ENV=development` → `.env.dev` (default) - - `NODE_ENV=test` → `.env.test` - -2. Then, if a `.env` file exists, its values override any previously loaded values - -Example setup: -```bash -# .env.dev - Development configuration -PORT=4000 -HASS_HOST=http://homeassistant.local:8123 -LOG_LEVEL=debug - -# .env - Local overrides -PORT=3000 # Overrides PORT from .env.dev -HASS_HOST=http://localhost:8123 # Overrides HASS_HOST from .env.dev -``` - -## Configuration File Structure - -The MCP Server uses environment variables for configuration, with support for different environments (development, test, production): - -```bash -# .env, .env.development, or .env.test -PORT=4000 -NODE_ENV=development -HASS_HOST=http://192.168.178.63:8123 -HASS_TOKEN=your_token_here -JWT_SECRET=your_secret_key -``` - -## Server Settings - -### Basic Server Configuration -- `PORT`: Server port number (default: 4000) -- `NODE_ENV`: Environment mode (development, production, test) -- `HASS_HOST`: Home Assistant instance URL -- `HASS_TOKEN`: Home Assistant long-lived access token - -### Security Settings -- `JWT_SECRET`: Secret key for JWT token generation -- `RATE_LIMIT`: Rate limiting configuration - - `windowMs`: Time window in milliseconds (default: 15 minutes) - - `max`: Maximum requests per window (default: 100) - -### WebSocket Settings -- `SSE`: Server-Sent Events configuration - - `MAX_CLIENTS`: Maximum concurrent clients (default: 1000) - - `PING_INTERVAL`: Keep-alive ping interval in ms (default: 30000) - -### Speech Features (Optional) -- `ENABLE_SPEECH_FEATURES`: Enable speech processing features (default: false) -- `ENABLE_WAKE_WORD`: Enable wake word detection (default: false) -- `ENABLE_SPEECH_TO_TEXT`: Enable speech-to-text conversion (default: false) -- `WHISPER_MODEL_PATH`: Path to Whisper models directory (default: /models) -- `WHISPER_MODEL_TYPE`: Whisper model type (default: base) - - Available models: tiny.en, base.en, small.en, medium.en, large-v2 - -## Environment Variables - -All configuration is managed through environment variables: - -```bash -# Server -PORT=4000 -NODE_ENV=development - -# Home Assistant -HASS_HOST=http://your-hass-instance:8123 -HASS_TOKEN=your_token_here - -# Security -JWT_SECRET=your-secret-key - -# Logging -LOG_LEVEL=info -LOG_DIR=logs -LOG_MAX_SIZE=20m -LOG_MAX_DAYS=14d -LOG_COMPRESS=true -LOG_REQUESTS=true - -# Speech Features (Optional) -ENABLE_SPEECH_FEATURES=false -ENABLE_WAKE_WORD=false -ENABLE_SPEECH_TO_TEXT=false -WHISPER_MODEL_PATH=/models -WHISPER_MODEL_TYPE=base -``` - -## Advanced Configuration - -### Security Rate Limiting -Rate limiting is enabled by default to protect against brute force attacks: - -```typescript -RATE_LIMIT: { - windowMs: 15 * 60 * 1000, // 15 minutes - max: 100 // limit each IP to 100 requests per window -} -``` - -### Logging -The server uses Bun's built-in logging capabilities with additional configuration: - -```typescript -LOGGING: { - LEVEL: "info", // debug, info, warn, error - DIR: "logs", - MAX_SIZE: "20m", - MAX_DAYS: "14d", - COMPRESS: true, - TIMESTAMP_FORMAT: "YYYY-MM-DD HH:mm:ss:ms", - LOG_REQUESTS: true -} -``` - -### Speech-to-Text Configuration -When speech features are enabled, you can configure the following options: - -```typescript -SPEECH: { - ENABLED: false, // Master switch for all speech features - WAKE_WORD_ENABLED: false, // Enable wake word detection - SPEECH_TO_TEXT_ENABLED: false, // Enable speech-to-text - WHISPER_MODEL_PATH: "/models", // Path to Whisper models - WHISPER_MODEL_TYPE: "base", // Model type to use -} -``` - -Available Whisper models: -- `tiny.en`: Fastest, lowest accuracy -- `base.en`: Good balance of speed and accuracy -- `small.en`: Better accuracy, slower -- `medium.en`: High accuracy, much slower -- `large-v2`: Best accuracy, very slow - -For production deployments, we recommend using system tools like `logrotate` for log management. - -Example logrotate configuration (`/etc/logrotate.d/mcp-server`): -``` -/var/log/mcp-server.log { - daily - rotate 7 - compress - delaycompress - missingok - notifempty - create 644 mcp mcp -} -``` - -## Best Practices - -1. Always use environment variables for sensitive information -2. Keep .env files secure and never commit them to version control -3. Use different environment files for development, test, and production -4. Enable SSL/TLS in production (preferably via reverse proxy) -5. Monitor log files for issues -6. Regularly rotate logs in production -7. Start with smaller Whisper models and upgrade if needed -8. Consider GPU acceleration for larger Whisper models - -## Validation - -The server validates configuration on startup using Zod schemas: -- Required fields are checked (e.g., HASS_TOKEN) -- Value types are verified -- Enums are validated (e.g., LOG_LEVEL, WHISPER_MODEL_TYPE) -- Default values are applied when not specified - -## Troubleshooting - -Common configuration issues: -1. Missing required environment variables -2. Invalid environment variable values -3. Permission issues with log directories -4. Rate limiting too restrictive -5. Speech model loading failures -6. Docker not available for speech features -7. Insufficient system resources for larger models - -See the [Troubleshooting Guide](troubleshooting.md) for solutions. - -# Configuration Guide - -This document describes the environment configuration system for the Home Assistant MCP Server. - -## Environment Setup - -### Using the Setup Script - -The MCP Server provides a setup script to help manage your environment configuration: - -```bash -# Make the script executable -chmod +x scripts/setup-env.sh - -# Basic usage (uses NODE_ENV or defaults to development) -./scripts/setup-env.sh - -# Specify an environment -NODE_ENV=production ./scripts/setup-env.sh - -# Force override existing files -./scripts/setup-env.sh --force -``` - -The setup script will: -1. Check for `.env.example` and create `.env` if it doesn't exist -2. Detect the environment (development/production/test) -3. Optionally override `.env` with environment-specific settings -4. Maintain your existing configuration unless forced to override - -### Manual Setup - -If you prefer to set up manually: - -```bash -# Copy the example configuration -cp .env.example .env - -# Then copy the appropriate environment override -cp .env.dev .env # For development -cp .env.prod .env # For production -cp .env.test .env # For testing -``` - -## Environment File Hierarchy - -### Base Configuration Files -- `.env.example` - Template with all available options and documentation -- `.env` - Your main configuration file (copied from .env.example) - -### Environment-Specific Files -- `.env.dev` - Development environment settings -- `.env.prod` - Production environment settings -- `.env.test` - Test environment settings - -### Loading Order and Priority - -Files are loaded in the following sequence, with later files overriding earlier ones: - -1. `.env` (base configuration) -2. Environment-specific file based on NODE_ENV: - - `NODE_ENV=development` → `.env.dev` - - `NODE_ENV=production` → `.env.prod` - - `NODE_ENV=test` → `.env.test` - -### Docker Environment Handling - -When using Docker, the environment is loaded as follows: - -1. `.env` file (base configuration) -2. `.env.${NODE_ENV}` file (environment-specific overrides) -3. Environment variables from docker-compose.yml -4. Command-line environment variables - -Example docker-compose.yml configuration: -```yaml -services: - homeassistant-mcp: - env_file: - - .env - - .env.${NODE_ENV:-development} - environment: - - NODE_ENV=${NODE_ENV:-development} - - PORT=4000 - - HASS_HOST - - HASS_TOKEN - - LOG_LEVEL=${LOG_LEVEL:-info} -``` - -Override examples: -```bash -# Override NODE_ENV -NODE_ENV=production docker compose up -d - -# Override multiple variables -NODE_ENV=production LOG_LEVEL=debug docker compose up -d -``` - -## Configuration Options - -### Required Settings - -```bash -# Server Configuration -PORT=4000 # Server port number -NODE_ENV=development # Environment (development/production/test) - -# Home Assistant -HASS_HOST=http://homeassistant.local:8123 # Home Assistant URL -HASS_TOKEN=your_token_here # Long-lived access token - -# Security -JWT_SECRET=your_secret_key # JWT signing secret -``` - -### Optional Settings - -#### Security -```bash -# Rate Limiting -RATE_LIMIT_WINDOW=900000 # Time window in ms (15 minutes) -RATE_LIMIT_MAX_REQUESTS=100 # Max requests per window -RATE_LIMIT_REGULAR=100 # Regular endpoint rate limit -RATE_LIMIT_WEBSOCKET=1000 # WebSocket connection rate limit - -# CORS Configuration -CORS_ORIGINS=http://localhost:3000,http://localhost:8123 -CORS_METHODS=GET,POST,PUT,DELETE,OPTIONS -CORS_ALLOWED_HEADERS=Content-Type,Authorization,X-Requested-With -CORS_EXPOSED_HEADERS= -CORS_CREDENTIALS=true -CORS_MAX_AGE=86400 - -# Cookie Security -COOKIE_SECRET=your_cookie_secret_key_min_32_chars -COOKIE_SECURE=true -COOKIE_HTTP_ONLY=true -COOKIE_SAME_SITE=Strict -``` - -#### Logging -```bash -# Logging Configuration -LOG_LEVEL=info # debug, info, warn, error -LOG_DIR=logs # Log directory -LOG_MAX_SIZE=20m # Max log file size -LOG_MAX_DAYS=14d # Log retention period -LOG_COMPRESS=true # Enable log compression -LOG_REQUESTS=true # Log HTTP requests -``` - -#### Speech Features -```bash -# Speech Processing -ENABLE_SPEECH_FEATURES=false # Master switch for speech features -ENABLE_WAKE_WORD=false # Enable wake word detection -ENABLE_SPEECH_TO_TEXT=false # Enable speech-to-text -WHISPER_MODEL_PATH=/models # Path to Whisper models -WHISPER_MODEL_TYPE=base # Whisper model type - -# Audio Configuration -NOISE_THRESHOLD=0.05 -MIN_SPEECH_DURATION=1.0 -SILENCE_DURATION=0.5 -SAMPLE_RATE=16000 -CHANNELS=1 -CHUNK_SIZE=1024 -PULSE_SERVER=unix:/run/user/1000/pulse/native -``` - -## Best Practices - -1. **Version Control** - - Never commit `.env` files to version control - - Always commit `.env.example` with documentation - - Consider committing `.env.dev` and `.env.test` for team development - -2. **Security** - - Use strong, unique values for secrets - - Enable HTTPS in production - - Keep tokens and secrets in `.env` only - -3. **Development** - - Use `.env.dev` for shared development settings - - Keep `.env` for personal overrides - - Enable debug logging in development - -4. **Production** - - Use `.env.prod` for production defaults - - Set appropriate rate limits - - Configure proper logging - - Enable all security features - -5. **Testing** - - Use `.env.test` for test configuration - - Use mock tokens and endpoints - - Enable detailed logging for debugging - -## Troubleshooting - -### Common Issues - -1. **Missing Required Variables** - - Error: "Missing required environment variable: HASS_TOKEN" - - Solution: Ensure HASS_TOKEN is set in your .env file - -2. **Permission Issues** - - Error: "EACCES: permission denied, access '/app/logs'" - - Solution: Ensure proper permissions on the logs directory - -3. **Invalid Configuration** - - Error: "Invalid configuration value for PORT" - - Solution: Check the value format in your .env file - -4. **Environment Override Issues** - - Problem: Environment-specific settings not applying - - Solution: Check NODE_ENV value and file naming - -See [Troubleshooting Guide](troubleshooting.md) for more solutions. \ No newline at end of file diff --git a/docs/contributing.md b/docs/contributing.md deleted file mode 100644 index 0783fe5..0000000 --- a/docs/contributing.md +++ /dev/null @@ -1,124 +0,0 @@ ---- -layout: default -title: Contributing -nav_order: 5 ---- - -# Contributing Guide 🤝 - -Thank you for your interest in contributing to the MCP Server project! - -## Getting Started - -### Prerequisites - -- [Bun](https://bun.sh) >= 1.0.26 -- Home Assistant instance -- Basic understanding of TypeScript - -### Development Setup - -1. Fork the repository -2. Clone your fork: - ```bash - git clone https://github.com/YOUR_USERNAME/homeassistant-mcp.git - cd homeassistant-mcp - ``` - -3. Install dependencies: - ```bash - bun install - ``` - -4. Configure environment: - ```bash - 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: -```bash -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: - -```bash -# 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 - -```markdown -## 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 - -- [API Documentation](api.md) -- [Troubleshooting Guide](troubleshooting.md) - -*Thank you for contributing!* \ No newline at end of file diff --git a/docs/deployment.md b/docs/deployment.md deleted file mode 100644 index 3490a9d..0000000 --- a/docs/deployment.md +++ /dev/null @@ -1,141 +0,0 @@ -# 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: - -```yaml -name: Deploy MkDocs -on: - push: - branches: - - main - - master - workflow_dispatch: # Allow manual trigger -``` - -## Manual Deployment - -If needed, you can deploy manually using: - -```bash -# 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** - - Check GitHub Actions logs - - Verify dependencies are up to date - - Ensure all required files exist - -2. **Broken Links** - - Run `mkdocs build --strict` - - Use relative paths in markdown - - Check case sensitivity - -3. **Style Issues** - - Verify theme configuration - - Check CSS customizations - - Test on multiple browsers - -## Configuration Files - -### requirements.txt - -Create a requirements file for documentation dependencies: - -```txt -mkdocs-material -mkdocs-minify-plugin -mkdocs-git-revision-date-plugin -mkdocs-mkdocstrings -mkdocs-social-plugin -mkdocs-redirects -``` - -## Monitoring - -- Check [GitHub Pages settings](https://github.com/jango-blockchained/advanced-homeassistant-mcp/settings/pages) -- Monitor build status in Actions tab -- Verify site accessibility - -## 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: - -```bash -# 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/docs/development/best-practices.md b/docs/development/best-practices.md deleted file mode 100644 index 77ae3be..0000000 --- a/docs/development/best-practices.md +++ /dev/null @@ -1,310 +0,0 @@ -# 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 - -```typescript -/** - * 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: - - Classes - - Interfaces - - Types - - Enums - -2. Use camelCase for: - - Variables - - Functions - - Methods - - Properties - -3. Use UPPER_SNAKE_CASE for: - - Constants - - Enum values - -```typescript -class DeviceManager { - private readonly DEFAULT_TIMEOUT = 5000; - - async getDeviceState(deviceId: string): Promise { - // Implementation - } -} -``` - -## Architecture - -### SOLID Principles - -1. Single Responsibility - - Each class/module has one job - - Split complex functionality - -2. Open/Closed - - Open for extension - - Closed for modification - -3. Liskov Substitution - - Subtypes must be substitutable - - Use interfaces properly - -4. Interface Segregation - - Keep interfaces focused - - Split large interfaces - -5. Dependency Inversion - - Depend on abstractions - - Use dependency injection - -### Example - -```typescript -// 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 - -```typescript -class DeviceError extends Error { - constructor( - message: string, - public code: string, - public context: Record - ) { - 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 - -```typescript -describe('DeviceManager', () => { - let manager: DeviceManager; - let mockDevice: jest.Mocked; - - 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 - -```typescript -class DeviceCache { - private cache = new Map(); - private readonly TTL = 60000; // 1 minute - - async getDevice(id: string): Promise { - 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 - -```typescript -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 - -```typescript -/** - * Manages device operations. - * @class - */ -class DeviceManager { - /** - * Gets the current state of a device. - * @param {string} deviceId - The device identifier. - * @returns {Promise} 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 { - // 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 - -```typescript -class Logger { - info(message: string, context: Record) { - 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 - -```bash -# Good commit messages -git commit -m "feat(device): add support for zigbee devices" -git commit -m "fix(api): handle timeout errors properly" -``` - -## See Also - -- [Tool Development Guide](tools.md) -- [Interface Documentation](interfaces.md) -- [Testing Guide](../testing.md) \ No newline at end of file diff --git a/docs/development/environment.md b/docs/development/environment.md deleted file mode 100644 index 0d418da..0000000 --- a/docs/development/environment.md +++ /dev/null @@ -1,197 +0,0 @@ -# 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 -```bash -git clone https://github.com/jango-blockchained/homeassistant-mcp.git -cd homeassistant-mcp -``` - -2. Create Virtual Environment -```bash -python -m venv .venv -source .venv/bin/activate # Linux/macOS -# or -.venv\Scripts\activate # Windows -``` - -3. Install Dependencies -```bash -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 -```json -{ - "python.linting.enabled": true, - "python.linting.pylintEnabled": true, - "python.formatting.provider": "black", - "editor.formatOnSave": true -} -``` - -## Configuration - -1. Create Local Config -```bash -cp config.example.yaml config.yaml -``` - -2. Set Environment Variables -```bash -cp .env.example .env -# Edit .env with your settings -``` - -## Running Tests - -### Unit Tests -```bash -pytest tests/unit -``` - -### Integration Tests -```bash -pytest tests/integration -``` - -### Coverage Report -```bash -pytest --cov=src tests/ -``` - -## Docker Development - -### Build Container -```bash -docker build -t mcp-server-dev -f Dockerfile.dev . -``` - -### Run Development Container -```bash -docker run -it --rm \ - -v $(pwd):/app \ - -p 8123:8123 \ - mcp-server-dev -``` - -## Database Setup - -### Local Development Database -```bash -docker run -d \ - -p 5432:5432 \ - -e POSTGRES_USER=mcp \ - -e POSTGRES_PASSWORD=development \ - -e POSTGRES_DB=mcp_dev \ - postgres:14 -``` - -### Run Migrations -```bash -alembic upgrade head -``` - -## Frontend Development - -1. Install Node.js Dependencies -```bash -cd frontend -npm install -``` - -2. Start Development Server -```bash -npm run dev -``` - -## Documentation - -### Build Documentation -```bash -mkdocs serve -``` - -### View Documentation -Open http://localhost:8000 in your browser - -## Debugging - -### VS Code Launch Configuration -```json -{ - "version": "0.2.0", - "configurations": [ - { - "name": "Python: MCP Server", - "type": "python", - "request": "launch", - "program": "src/main.py", - "console": "integratedTerminal" - } - ] -} -``` - -## Git Hooks - -### Install Pre-commit -```bash -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` - -2. Database connection issues - - Verify PostgreSQL is running - - Check connection settings in .env - -3. Virtual environment problems - - Delete and recreate: `rm -rf .venv && python -m venv .venv` - - Reinstall dependencies - -## Next Steps - -1. Review the [Architecture Guide](../architecture.md) -2. Check [Contributing Guidelines](../contributing.md) -3. Start with [Simple Issues](https://github.com/jango-blockchained/homeassistant-mcp/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22) \ No newline at end of file diff --git a/docs/development/index.md b/docs/development/index.md deleted file mode 100644 index ad07e5e..0000000 --- a/docs/development/index.md +++ /dev/null @@ -1,54 +0,0 @@ -# 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 - -- [Architecture](../architecture.md) - System architecture and design -- [Contributing](../contributing.md) - Contribution guidelines -- [Testing](../testing.md) - Testing framework and guidelines -- [Troubleshooting](../troubleshooting.md) - Common issues and solutions -- [Deployment](../deployment.md) - Deployment procedures -- [Roadmap](../roadmap.md) - Future development plans - -## 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 - -- Review the [Architecture](../architecture.md) -- Check [Contributing Guidelines](../contributing.md) -- Set up your [Development Environment](environment.md) \ No newline at end of file diff --git a/docs/development/interfaces.md b/docs/development/interfaces.md deleted file mode 100644 index 8abe32c..0000000 --- a/docs/development/interfaces.md +++ /dev/null @@ -1,296 +0,0 @@ -# Interface Documentation - -This document describes the core interfaces used throughout the Home Assistant MCP. - -## Core Interfaces - -### Tool Interface - -```typescript -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; -} -``` - -### Tool Result - -```typescript -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 - -```typescript -enum ToolCategory { - DeviceManagement = 'device_management', - HistoryState = 'history_state', - Automation = 'automation', - AddonsPackages = 'addons_packages', - Notifications = 'notifications', - Events = 'events', - Utility = 'utility' -} -``` - -## Event Interfaces - -### Event Subscription - -```typescript -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 - -```typescript -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 - -```typescript -interface Device { - /** Device ID */ - id: string; - - /** Device name */ - name: string; - - /** Device domain */ - domain: string; - - /** Current state */ - state: string; - - /** Device attributes */ - attributes: Record; - - /** Device capabilities */ - capabilities: DeviceCapabilities; -} -``` - -### Device Capabilities - -```typescript -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 - -```typescript -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 - -```typescript -interface User { - /** User ID */ - id: string; - - /** Username */ - username: string; - - /** User type */ - type: 'admin' | 'user' | 'service'; - - /** User permissions */ - permissions: string[]; -} -``` - -## Error Interfaces - -### Tool Error - -```typescript -interface ToolError extends Error { - /** Error code */ - code: string; - - /** HTTP status code */ - status: number; - - /** Error details */ - details?: Record; -} -``` - -### Validation Error - -```typescript -interface ValidationError { - /** Error path */ - path: string; - - /** Error message */ - message: string; - - /** Error code */ - code: string; -} -``` - -## Configuration Interfaces - -### Tool Configuration - -```typescript -interface ToolConfig { - /** Enable/disable tool */ - enabled: boolean; - - /** Tool-specific settings */ - settings: Record; - - /** Rate limiting */ - rate_limit?: { - /** Max requests */ - max: number; - /** Time window in seconds */ - window: number; - }; -} -``` - -### System Configuration - -```typescript -interface SystemConfig { - /** System name */ - name: string; - - /** Environment */ - environment: 'development' | 'production'; - - /** Log level */ - log_level: 'debug' | 'info' | 'warn' | 'error'; - - /** Tool configurations */ - tools: Record; -} -``` - -## 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 - -- [Tool Development Guide](tools.md) -- [Best Practices](best-practices.md) -- [Testing Guide](../testing.md) \ No newline at end of file diff --git a/docs/development/tools.md b/docs/development/tools.md deleted file mode 100644 index d20861a..0000000 --- a/docs/development/tools.md +++ /dev/null @@ -1,226 +0,0 @@ -# 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: - -```typescript -interface Tool { - id: string; - name: string; - description: string; - version: string; - category: ToolCategory; - execute(params: any): Promise; -} -``` - -## 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 - -```typescript -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 { - // 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 - -```typescript -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 - -```typescript -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 - -```typescript -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 { - try { - // Tool implementation - } catch (error) { - throw new ToolError( - 'Operation failed', - 'TOOL_ERROR', - 500 - ); - } -} -``` - -## Testing - -```typescript -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 - -```markdown -# Tool Name - -Description of the tool. - -## Features - -- Feature 1 -- Feature 2 - -## Usage - -### REST API - -```typescript -// API endpoints -``` - -### WebSocket - -```typescript -// WebSocket usage -``` - -## Examples - -### Example 1 - -```typescript -// Usage example -``` - -## Response Format - -```json -{ - "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 - -- [Interface Documentation](interfaces.md) -- [Best Practices](best-practices.md) -- [Testing Guide](../testing.md) \ No newline at end of file diff --git a/docs/examples/index.md b/docs/examples/index.md deleted file mode 100644 index 1586d26..0000000 --- a/docs/examples/index.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -layout: default -title: Examples -nav_order: 7 -has_children: true ---- - -# 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: - -```typescript -// 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/docs/extras.md b/docs/extras.md deleted file mode 100644 index 6a2a932..0000000 --- a/docs/extras.md +++ /dev/null @@ -1,228 +0,0 @@ -# Extras & Tools Guide 🛠️ - -## Overview - -I've included several additional tools and utilities in the `extra/` directory to enhance your Home Assistant MCP experience. These tools help with automation analysis, speech processing, and client integration. - -## Available Tools 🧰 - -### 1. Home Assistant Analyzer CLI -```bash -# Installation -bun install -g @homeassistant-mcp/ha-analyzer-cli - -# Usage -ha-analyzer analyze path/to/automation.yaml -``` - -Features: -- 🔍 Deep automation analysis using AI models -- 🚨 Security vulnerability scanning -- 💡 Performance optimization suggestions -- 📊 System health metrics -- ⚡ Energy usage analysis -- 🤖 Automation improvement recommendations - -### 2. Speech-to-Text Example -```bash -# Run the example -bun run extra/speech-to-text-example.ts -``` - -Features: -- 🎤 Wake word detection ("hey jarvis", "ok google", "alexa") -- 🗣️ Speech-to-text transcription -- 🌍 Multiple language support -- 🚀 GPU acceleration support -- 📝 Event handling and logging - -### 3. Claude Desktop Setup (macOS) -```bash -# Make script executable -chmod +x extra/claude-desktop-macos-setup.sh - -# Run setup -./extra/claude-desktop-macos-setup.sh -``` - -Features: -- 🖥️ Automated Claude Desktop installation -- ⚙️ Environment configuration -- 🔗 MCP integration setup -- 🚀 Performance optimization - -## Home Assistant Analyzer Details 📊 - -### Analysis Categories - -1. **System Overview** - - Current state assessment - - Health check - - Configuration review - - Integration status - - Issue detection - -2. **Performance Analysis** - - Resource usage monitoring - - Response time analysis - - Optimization opportunities - - Bottleneck detection - -3. **Security Assessment** - - Current security measures - - Vulnerability detection - - Security recommendations - - Best practices review - -4. **Optimization Suggestions** - - Performance improvements - - Configuration optimizations - - Integration enhancements - - Automation opportunities - -5. **Maintenance Tasks** - - Required updates - - Cleanup recommendations - - Regular maintenance tasks - - System health checks - -6. **Entity Usage Analysis** - - Most active entities - - Rarely used entities - - Potential duplicates - - Usage patterns - -7. **Automation Analysis** - - Inefficient automations - - Improvement suggestions - - Blueprint recommendations - - Condition optimizations - -8. **Energy Management** - - High consumption detection - - Monitoring suggestions - - Tariff optimization - - Usage patterns - -### Configuration - -```yaml -# config/analyzer.yaml -analysis: - depth: detailed # quick, basic, or detailed - models: # AI models to use - - gpt-4 # for complex analysis - - gpt-3.5-turbo # for quick checks - focus: # Analysis focus areas - - security - - performance - - automations - - energy - ignore: # Paths to ignore - - test/ - - disabled/ -``` - -## Speech-to-Text Integration 🎤 - -### Prerequisites -1. Docker installed and running -2. NVIDIA GPU with CUDA (optional, for faster processing) -3. Audio input device configured - -### Configuration -```yaml -# speech-config.yaml -wake_word: - enabled: true - words: - - "hey jarvis" - - "ok google" - - "alexa" - sensitivity: 0.5 - -speech_to_text: - model: "base" # tiny, base, small, medium, large - language: "en" # en, es, fr, etc. - use_gpu: true # Enable GPU acceleration -``` - -### Usage Example -```typescript -import { SpeechProcessor } from './speech-to-text-example'; - -const processor = new SpeechProcessor({ - wakeWord: true, - model: 'base', - language: 'en' -}); - -processor.on('wake_word', (timestamp) => { - console.log('Wake word detected!'); -}); - -processor.on('transcription', (text) => { - console.log('Transcribed:', text); -}); - -await processor.start(); -``` - -## Best Practices 🎯 - -1. **Analysis Tool Usage** - - Run regular system analyses - - Focus on specific areas when needed - - Review and implement suggestions - - Monitor improvements - -2. **Speech Processing** - - Choose appropriate models - - Test in your environment - - Adjust sensitivity as needed - - Monitor performance - -3. **Integration Setup** - - Follow security best practices - - Test in development first - - Monitor resource usage - - Keep configurations updated - -## Troubleshooting 🔧 - -### Common Issues - -1. **Analyzer CLI Issues** - - Verify API keys - - Check network connectivity - - Validate YAML syntax - - Review permissions - -2. **Speech Processing Issues** - - Check audio device - - Verify Docker setup - - Monitor GPU usage - - Check model compatibility - -3. **Integration Issues** - - Verify configurations - - Check dependencies - - Review logs - - Test connectivity - -## API Reference 🔌 - -### Analyzer API -```typescript -import { HomeAssistantAnalyzer } from './ha-analyzer-cli'; - -const analyzer = new HomeAssistantAnalyzer({ - depth: 'detailed', - focus: ['security', 'performance'] -}); - -const analysis = await analyzer.analyze(); -console.log(analysis.suggestions); -``` - -See [API Documentation](api.md) for more details. \ No newline at end of file diff --git a/docs/features/speech.md b/docs/features/speech.md deleted file mode 100644 index e136064..0000000 --- a/docs/features/speech.md +++ /dev/null @@ -1,212 +0,0 @@ -# Speech Features - -The Home Assistant MCP Server includes powerful speech processing capabilities powered by fast-whisper and custom wake word detection. This guide explains how to set up and use these features effectively. - -## Overview - -The speech processing system consists of two main components: -1. Wake Word Detection - Listens for specific trigger phrases -2. Speech-to-Text - Transcribes spoken commands using fast-whisper - -## Setup - -### Prerequisites - -1. Docker environment: -```bash -docker --version # Should be 20.10.0 or higher -``` - -2. For GPU acceleration: -- NVIDIA GPU with CUDA support -- NVIDIA Container Toolkit installed -- NVIDIA drivers 450.80.02 or higher - -### Installation - -1. Enable speech features in your `.env`: -```bash -ENABLE_SPEECH_FEATURES=true -ENABLE_WAKE_WORD=true -ENABLE_SPEECH_TO_TEXT=true -``` - -2. Configure model settings: -```bash -WHISPER_MODEL_PATH=/models -WHISPER_MODEL_TYPE=base -WHISPER_LANGUAGE=en -WHISPER_TASK=transcribe -WHISPER_DEVICE=cuda # or cpu -``` - -3. Start the services: -```bash -docker-compose up -d -``` - -## Usage - -### Wake Word Detection - -The wake word detector continuously listens for configured trigger phrases. Default wake words: -- "hey jarvis" -- "ok google" -- "alexa" - -Custom wake words can be configured: -```bash -WAKE_WORDS=computer,jarvis,assistant -``` - -When a wake word is detected: -1. The system starts recording audio -2. Audio is processed through the speech-to-text pipeline -3. The resulting command is processed by the server - -### Speech-to-Text - -#### Automatic Transcription - -After wake word detection: -1. Audio is automatically captured (default: 5 seconds) -2. The audio is transcribed using the configured whisper model -3. The transcribed text is processed as a command - -#### Manual Transcription - -You can also manually transcribe audio using the API: - -```typescript -// Using the TypeScript client -import { SpeechService } from '@ha-mcp/client'; - -const speech = new SpeechService(); - -// Transcribe from audio buffer -const buffer = await getAudioBuffer(); -const text = await speech.transcribe(buffer); - -// Transcribe from file -const text = await speech.transcribeFile('command.wav'); -``` - -```javascript -// Using the REST API -POST /api/speech/transcribe -Content-Type: multipart/form-data - -file: