diff --git a/docs/development/best-practices.md b/docs/development/best-practices.md new file mode 100644 index 0000000..77ae3be --- /dev/null +++ b/docs/development/best-practices.md @@ -0,0 +1,310 @@ +# 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/interfaces.md b/docs/development/interfaces.md new file mode 100644 index 0000000..8abe32c --- /dev/null +++ b/docs/development/interfaces.md @@ -0,0 +1,296 @@ +# 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 new file mode 100644 index 0000000..d20861a --- /dev/null +++ b/docs/development/tools.md @@ -0,0 +1,226 @@ +# 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/getting-started.md b/docs/getting-started.md index 7bab0ca..69d8608 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -5,7 +5,7 @@ Begin your journey with the Home Assistant MCP Server by following these steps: - **API Documentation:** Read the [API Documentation](api.md) for available endpoints. - **Real-Time Updates:** Learn about [Server-Sent Events](sse-api.md) for live communication. - **Tools:** Explore available [Tools](tools/tools.md) for device control and automation. -- **Configuration:** Refer to the [Configuration Guide](configuration.md) for setup and advanced settings. +- **Configuration:** Refer to the [Configuration Guide](getting-started/configuration.md) for setup and advanced settings. ## Troubleshooting diff --git a/docs/tools/addons-packages/addon.md b/docs/tools/addons-packages/addon.md new file mode 100644 index 0000000..c11a2cb --- /dev/null +++ b/docs/tools/addons-packages/addon.md @@ -0,0 +1,240 @@ +# 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 + +```typescript +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 + +```typescript +// 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 + +```typescript +const response = await fetch('http://your-ha-mcp/api/addons', { + headers: { + 'Authorization': 'Bearer your_access_token' + } +}); +const addons = await response.json(); +``` + +### Install Add-on + +```typescript +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 + +```typescript +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 + +```json +{ + "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 + +```json +{ + "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 + +```json +{ + "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 + +```json +{ + "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 + +- [Package Management](package.md) +- [Device Control](../device-management/control.md) +- [Event Subscription](../events/subscribe-events.md) \ No newline at end of file diff --git a/docs/tools/addons-packages/package.md b/docs/tools/addons-packages/package.md new file mode 100644 index 0000000..6006868 --- /dev/null +++ b/docs/tools/addons-packages/package.md @@ -0,0 +1,236 @@ +# 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 + +```typescript +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 + +```typescript +// 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 + +```typescript +const response = await fetch('http://your-ha-mcp/api/packages', { + headers: { + 'Authorization': 'Bearer your_access_token' + } +}); +const packages = await response.json(); +``` + +### Search Packages + +```typescript +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 + +```typescript +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 + +```json +{ + "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 + +```json +{ + "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 + +```json +{ + "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 + +```json +{ + "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 + +- [Add-on Management](addon.md) +- [Device Control](../device-management/control.md) +- [Event Subscription](../events/subscribe-events.md) \ No newline at end of file diff --git a/docs/tools/automation/automation-config.md b/docs/tools/automation/automation-config.md new file mode 100644 index 0000000..1f073d5 --- /dev/null +++ b/docs/tools/automation/automation-config.md @@ -0,0 +1,321 @@ +# 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 + +```typescript +POST /api/automations +PUT /api/automations/{automation_id} +DELETE /api/automations/{automation_id} +POST /api/automations/{automation_id}/duplicate +POST /api/automations/validate +``` + +### WebSocket + +```typescript +// 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 + +```json +{ + "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 + +```json +// 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 + +```json +// 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 + +```json +// 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 + +```typescript +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 + +```typescript +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 + +```json +{ + "success": true, + "data": { + "automation": { + "id": "created_automation_id", + // Full automation configuration + } + } +} +``` + +### Validation Response + +```json +{ + "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 + +```json +{ + "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 + +- [Automation Management](automation.md) +- [Event Subscription](../events/subscribe-events.md) +- [Scene Management](../history-state/scene.md) \ No newline at end of file diff --git a/docs/tools/automation/automation.md b/docs/tools/automation/automation.md new file mode 100644 index 0000000..bc1671b --- /dev/null +++ b/docs/tools/automation/automation.md @@ -0,0 +1,211 @@ +# 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 + +```typescript +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 + +```typescript +// 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 + +```typescript +const response = await fetch('http://your-ha-mcp/api/automations', { + headers: { + 'Authorization': 'Bearer your_access_token' + } +}); +const automations = await response.json(); +``` + +### Toggle Automation State + +```typescript +const response = await fetch('http://your-ha-mcp/api/automations/morning_routine/toggle', { + method: 'POST', + headers: { + 'Authorization': 'Bearer your_access_token' + } +}); +``` + +### Trigger Automation Manually + +```typescript +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 + +```json +{ + "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 + +```json +{ + "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 + +```json +{ + "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 + +```json +{ + "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 + +- [Automation Configuration](automation-config.md) +- [Event Subscription](../events/subscribe-events.md) +- [Device Control](../device-management/control.md) \ No newline at end of file diff --git a/docs/tools/device-management/control.md b/docs/tools/device-management/control.md new file mode 100644 index 0000000..5a00ed4 --- /dev/null +++ b/docs/tools/device-management/control.md @@ -0,0 +1,195 @@ +# 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 + +```typescript +POST /api/devices/{device_id}/control +``` + +### WebSocket + +```typescript +{ + "type": "control_device", + "device_id": "required_device_id", + "domain": "required_domain", + "service": "required_service", + "data": { + // Service-specific data + } +} +``` + +## Domain-Specific Commands + +### Lights + +```typescript +// 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 + +```typescript +// 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 + +```typescript +// 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 + +```typescript +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 + +```typescript +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 + +```json +{ + "success": true, + "data": { + "state": "on", + "attributes": { + // Updated device attributes + } + } +} +``` + +### Error Response + +```json +{ + "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 + +- [List Devices](list-devices.md) +- [Device History](../history-state/history.md) +- [Event Subscription](../events/subscribe-events.md) \ No newline at end of file diff --git a/docs/tools/device-management/list-devices.md b/docs/tools/device-management/list-devices.md new file mode 100644 index 0000000..093c52e --- /dev/null +++ b/docs/tools/device-management/list-devices.md @@ -0,0 +1,139 @@ +# 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 + +```typescript +GET /api/devices +GET /api/devices/{domain} +GET /api/devices/{device_id}/state +``` + +### WebSocket + +```typescript +// 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 + +```typescript +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 + +```typescript +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 + +```json +{ + "success": true, + "data": { + "devices": [ + { + "id": "device_id", + "name": "Device Name", + "domain": "light", + "state": "on", + "attributes": { + "brightness": 255, + "color_temp": 370 + } + } + ] + } +} +``` + +### Device State Response + +```json +{ + "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 + +```json +{ + "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 + +- [Device Control](control.md) +- [Device History](../history-state/history.md) +- [Event Subscription](../events/subscribe-events.md) \ No newline at end of file diff --git a/docs/tools/events/sse-stats.md b/docs/tools/events/sse-stats.md new file mode 100644 index 0000000..3150d07 --- /dev/null +++ b/docs/tools/events/sse-stats.md @@ -0,0 +1,251 @@ +# 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 + +```typescript +GET /api/sse/stats +GET /api/sse/connections +GET /api/sse/connections/{connection_id} +GET /api/sse/metrics +GET /api/sse/history +``` + +### WebSocket + +```typescript +// 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 + +```typescript +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 + +```typescript +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 + +```typescript +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 + +```json +{ + "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 + +```json +{ + "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 + +```json +{ + "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 + +```json +{ + "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 + +- [Event Subscription](subscribe-events.md) +- [Device Control](../device-management/control.md) +- [Automation Management](../automation/automation.md) \ No newline at end of file diff --git a/docs/tools/events/subscribe-events.md b/docs/tools/events/subscribe-events.md new file mode 100644 index 0000000..0ce59f2 --- /dev/null +++ b/docs/tools/events/subscribe-events.md @@ -0,0 +1,253 @@ +# 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 + +```typescript +POST /api/events/subscribe +DELETE /api/events/unsubscribe +GET /api/events/subscriptions +GET /api/events/history +``` + +### WebSocket + +```typescript +// 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) + +```typescript +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 + +```typescript +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 + +```typescript +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 + +```typescript +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 + +```typescript +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 + +```json +{ + "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 + +```json +{ + "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 + +```json +{ + "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 + +```json +{ + "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 + +- [SSE Statistics](sse-stats.md) +- [Device Control](../device-management/control.md) +- [Automation Management](../automation/automation.md) \ No newline at end of file diff --git a/docs/tools/history-state/history.md b/docs/tools/history-state/history.md new file mode 100644 index 0000000..80d6edb --- /dev/null +++ b/docs/tools/history-state/history.md @@ -0,0 +1,167 @@ +# 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 + +```typescript +GET /api/history/{device_id} +GET /api/history/{device_id}/period/{start_time} +GET /api/history/{device_id}/period/{start_time}/{end_time} +``` + +### WebSocket + +```typescript +{ + "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 + +```typescript +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 + +```typescript +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 + +```json +{ + "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 + +```json +{ + "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 + +```json +{ + "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 + +- [List Devices](../device-management/list-devices.md) +- [Device Control](../device-management/control.md) +- [Scene Management](scene.md) \ No newline at end of file diff --git a/docs/tools/history-state/scene.md b/docs/tools/history-state/scene.md new file mode 100644 index 0000000..15e5f79 --- /dev/null +++ b/docs/tools/history-state/scene.md @@ -0,0 +1,215 @@ +# 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 + +```typescript +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 + +```typescript +// 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 + +```json +{ + "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 + +```typescript +const response = await fetch('http://your-ha-mcp/api/scenes', { + headers: { + 'Authorization': 'Bearer your_access_token' + } +}); +const scenes = await response.json(); +``` + +### Activate a Scene + +```typescript +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 + +```typescript +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 + +```json +{ + "success": true, + "data": { + "scenes": [ + { + "id": "scene_id", + "name": "Scene Name", + "entities": { + // Entity configurations + } + } + ] + } +} +``` + +### Scene Activation Response + +```json +{ + "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 + +```json +{ + "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: + +```json +{ + "name": "Sunset Mode", + "entities": { + "light.living_room": { + "state": "on", + "brightness": 128, + "transition": 5 // 5 seconds + } + } +} +``` + +## See Also + +- [Device Control](../device-management/control.md) +- [Device History](history.md) +- [Automation Management](../automation/automation.md) \ No newline at end of file diff --git a/docs/tools/notifications/notify.md b/docs/tools/notifications/notify.md new file mode 100644 index 0000000..72cab9b --- /dev/null +++ b/docs/tools/notifications/notify.md @@ -0,0 +1,249 @@ +# 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 + +```typescript +POST /api/notify +POST /api/notify/{service_id} +GET /api/notify/services +GET /api/notify/history +``` + +### WebSocket + +```typescript +// 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 + +```typescript +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 + +```typescript +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) + +```typescript +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 + +```json +{ + "success": true, + "data": { + "notification_id": "notification_123", + "status": "sent", + "timestamp": "2024-02-05T12:00:00Z", + "service": "mobile_app" + } +} +``` + +### Services List Response + +```json +{ + "success": true, + "data": { + "services": [ + { + "id": "mobile_app", + "name": "Mobile App", + "enabled": true, + "features": [ + "actions", + "images", + "sound" + ] + } + ] + } +} +``` + +### Notification History Response + +```json +{ + "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 + +```json +{ + "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 + +```typescript +// Template example +{ + "template": "security_alert", + "data": { + "location": "living_room", + "event_type": "motion", + "timestamp": "2024-02-05T12:00:00Z" + } +} +``` + +## See Also + +- [Event Subscription](../events/subscribe-events.md) +- [Device Control](../device-management/control.md) +- [Automation Management](../automation/automation.md) \ No newline at end of file diff --git a/docs/tools/tools.md b/docs/tools/tools.md index ec49660..3ae628e 100644 --- a/docs/tools/tools.md +++ b/docs/tools/tools.md @@ -6,36 +6,36 @@ This section documents all available tools in the Home Assistant MCP. ### Device Management -1. [List Devices](./list-devices.md) +1. [List Devices](device-management/list-devices.md) - List all available Home Assistant devices - Group devices by domain - Get device states and attributes -2. [Device Control](./control.md) +2. [Device Control](device-management/control.md) - Control various device types - Support for lights, switches, covers, climate devices - Domain-specific commands and parameters ### History and State -1. [History](./history.md) +1. [History](history-state/history.md) - Fetch device state history - Filter by time range - Get significant changes -2. [Scene Management](./scene.md) +2. [Scene Management](history-state/scene.md) - List available scenes - Activate scenes - Scene state information ### Automation -1. [Automation Management](./automation.md) +1. [Automation Management](automation/automation.md) - List automations - Toggle automation state - Trigger automations manually -2. [Automation Configuration](./automation-config.md) +2. [Automation Configuration](automation/automation-config.md) - Create new automations - Update existing automations - Delete automations @@ -43,32 +43,32 @@ This section documents all available tools in the Home Assistant MCP. ### Add-ons and Packages -1. [Add-on Management](./addon.md) +1. [Add-on Management](addons-packages/addon.md) - List available add-ons - Install/uninstall add-ons - Start/stop/restart add-ons - Get add-on information -2. [Package Management](./package.md) +2. [Package Management](addons-packages/package.md) - Manage HACS packages - Install/update/remove packages - List available packages by category ### Notifications -1. [Notify](./notify.md) +1. [Notify](notifications/notify.md) - Send notifications - Support for multiple notification services - Custom notification data ### Real-time Events -1. [Event Subscription](./subscribe-events.md) +1. [Event Subscription](events/subscribe-events.md) - Subscribe to Home Assistant events - Monitor specific entities - Domain-based monitoring -2. [SSE Statistics](./sse-stats.md) +2. [SSE Statistics](events/sse-stats.md) - Get SSE connection statistics - Monitor active subscriptions - Connection management diff --git a/mkdocs.yml b/mkdocs.yml index 5158501..e616bf3 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -82,21 +82,45 @@ plugins: nav: - Home: index.md - Getting Started: + - Overview: getting-started.md - Installation: getting-started/installation.md + - Configuration: getting-started/configuration.md + - Docker Setup: getting-started/docker.md - Quick Start: getting-started/quickstart.md + - Usage: usage.md - API Reference: - Overview: api/index.md - - SSE API: api/sse.md + - Core API: api.md + - SSE API: sse-api.md - Core Functions: api/core.md + - Tools: + - Overview: tools/tools.md + - Device Management: + - List Devices: tools/device-management/list-devices.md + - Device Control: tools/device-management/control.md + - History & State: + - History: tools/history-state/history.md + - Scene Management: tools/history-state/scene.md + - Automation: + - Automation Management: tools/automation/automation.md + - Automation Configuration: tools/automation/automation-config.md + - Add-ons & Packages: + - Add-on Management: tools/addons-packages/addon.md + - Package Management: tools/addons-packages/package.md + - Notifications: + - Notify: tools/notifications/notify.md + - Events: + - Event Subscription: tools/events/subscribe-events.md + - SSE Statistics: tools/events/sse-stats.md + - Development: + - Overview: development/development.md + - Testing Guide: testing.md - Architecture: architecture.md - Contributing: contributing.md - Troubleshooting: troubleshooting.md - Examples: - Overview: examples/index.md - - Development: - - Setup: development/setup.md - - Testing: development/testing.md - - CI/CD: development/cicd.md + - Roadmap: roadmap.md extra: social: