From 3a54766b614c85cc5e1c3d227d60ff88867bf4d2 Mon Sep 17 00:00:00 2001 From: jango-blockchained Date: Tue, 4 Feb 2025 17:33:26 +0100 Subject: [PATCH] docs: refactor and improve documentation across multiple files - Streamline and enhance documentation for API, architecture, getting started, and usage - Improve clarity, readability, and organization of documentation files - Update content to be more concise and informative - Ensure consistent formatting and style across documentation --- docs/README.md | 6 +- docs/api.md | 216 ++++++++++++++++----------------- docs/architecture.md | 25 +++- docs/contributing.md | 22 ++-- docs/getting-started.md | 130 +++----------------- docs/roadmap.md | 28 ++--- docs/testing.md | 262 +++++++++++++--------------------------- docs/troubleshooting.md | 179 +++++++++++++-------------- docs/usage.md | 31 ++++- 9 files changed, 372 insertions(+), 527 deletions(-) diff --git a/docs/README.md b/docs/README.md index 71121ca..9ca82fd 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,8 +1,6 @@ # Home Assistant MCP Documentation -Welcome to the Home Assistant MCP (Model Context Protocol) documentation. This documentation provides comprehensive information about setting up, configuring, and using the Home Assistant MCP. - -The main documentation can be found in our [Documentation Index](index.md). +Welcome to the documentation for the Home Assistant MCP (Model Context Protocol) Server. Here you'll find comprehensive guides on setup, configuration, usage, and contribution. ## Quick Navigation @@ -19,4 +17,4 @@ The main documentation can be found in our [Documentation Index](index.md). ## License -This project is licensed under the MIT License - see the [LICENSE](../LICENSE) file for details. \ No newline at end of file +This project is licensed under the MIT License. See [LICENSE](../LICENSE) for details. \ No newline at end of file diff --git a/docs/api.md b/docs/api.md index e90843c..cd5288d 100644 --- a/docs/api.md +++ b/docs/api.md @@ -1,4 +1,105 @@ -# API Reference +# API Documentation + +This section details the available API endpoints for the Home Assistant MCP Server. + +## Device Control + +### Common Entity Controls + +```json +{ + "tool": "control", + "command": "turn_on", // Options: "turn_on", "turn_off", "toggle" + "entity_id": "light.living_room" +} +``` + +### Light Control + +```json +{ + "tool": "control", + "command": "turn_on", + "entity_id": "light.living_room", + "brightness": 128, + "color_temp": 4000, + "rgb_color": [255, 0, 0] +} +``` + +## Add-on Management + +### List Available Add-ons + +```json +{ + "tool": "addon", + "action": "list" +} +``` + +### Install Add-on + +```json +{ + "tool": "addon", + "action": "install", + "slug": "core_configurator", + "version": "5.6.0" +} +``` + +### Manage Add-on State + +```json +{ + "tool": "addon", + "action": "start", // Options: "start", "stop", "restart" + "slug": "core_configurator" +} +``` + +## Package Management + +### List HACS Packages + +```json +{ + "tool": "package", + "action": "list", + "category": "integration" // Options: "integration", "plugin", "theme", "python_script", "appdaemon", "netdaemon" +} +``` + +### Install Package + +```json +{ + "tool": "package", + "action": "install", + "category": "integration", + "repository": "hacs/integration", + "version": "1.32.0" +} +``` + +## Automation Management + +For automation management details and endpoints, please refer to the [Tools Documentation](tools/README.md). + +## Security Considerations + +- Validate and sanitize all user inputs. +- Enforce rate limiting to prevent abuse. +- Apply proper security headers. +- Gracefully handle errors based on the environment. + +## Troubleshooting + +If you experience issues with the API: +- Verify the endpoint and request payload. +- Check authentication tokens and required headers. +- Consult the [Troubleshooting Guide](troubleshooting.md) for further guidance. ## MCP Schema Endpoint @@ -43,119 +144,6 @@ Example response: Note: The `/mcp` endpoint is publicly accessible and does not require authentication, as it only provides schema information. -## Device Control - -### Common Entity Controls -```json -{ - "tool": "control", - "command": "turn_on", // or "turn_off", "toggle" - "entity_id": "light.living_room" -} -``` - -### Light Control -```json -{ - "tool": "control", - "command": "turn_on", - "entity_id": "light.living_room", - "brightness": 128, - "color_temp": 4000, - "rgb_color": [255, 0, 0] -} -``` - -## Add-on Management - -### List Available Add-ons -```json -{ - "tool": "addon", - "action": "list" -} -``` - -### Install Add-on -```json -{ - "tool": "addon", - "action": "install", - "slug": "core_configurator", - "version": "5.6.0" -} -``` - -### Manage Add-on State -```json -{ - "tool": "addon", - "action": "start", // or "stop", "restart" - "slug": "core_configurator" -} -``` - -## Package Management - -### List HACS Packages -```json -{ - "tool": "package", - "action": "list", - "category": "integration" // or "plugin", "theme", "python_script", "appdaemon", "netdaemon" -} -``` - -### Install Package -```json -{ - "tool": "package", - "action": "install", - "category": "integration", - "repository": "hacs/integration", - "version": "1.32.0" -} -``` - -## Automation Management - -### Create Automation -```json -{ - "tool": "automation_config", - "action": "create", - "config": { - "alias": "Motion Light", - "description": "Turn on light when motion detected", - "mode": "single", - "trigger": [ - { - "platform": "state", - "entity_id": "binary_sensor.motion", - "to": "on" - } - ], - "action": [ - { - "service": "light.turn_on", - "target": { - "entity_id": "light.living_room" - } - } - ] - } -} -``` - -### Duplicate Automation -```json -{ - "tool": "automation_config", - "action": "duplicate", - "automation_id": "automation.motion_light" -} -``` - ## Core Functions ### State Management diff --git a/docs/architecture.md b/docs/architecture.md index e0b2f9e..ee157c1 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -42,4 +42,27 @@ The MCP Server is designed as a high-performance, secure, and scalable bridge be The architecture of the MCP Server prioritizes performance, scalability, and security. By leveraging Bun's high-performance runtime, employing real-time communication through SSE, and maintaining a modular, secure design, the MCP Server provides a robust platform for integrating Home Assistant with modern LLM functionalities. -*This document is a living document and will be updated as the system evolves.* \ No newline at end of file +*This document is a living document and will be updated as the system evolves.* + +## Key Components + +- **API Module:** Handles RESTful endpoints, authentication, and error management. +- **SSE Module:** Provides real-time updates through Server-Sent Events. +- **Tools Module:** Offers various utilities for device control, automation, and data processing. +- **Security Module:** Implements token-based authentication and secure communications. +- **Integration Module:** Bridges data between Home Assistant and external systems. + +## Data Flow + +1. Requests enter via the API endpoints. +2. Security middleware validates and processes requests. +3. Core modules process data and execute the necessary business logic. +4. Real-time notifications are managed by the SSE module. + +## Future Enhancements + +- Expand modularity with potential microservices. +- Enhance security with multi-factor authentication. +- Improve scalability through distributed architectures. + +*Further diagrams and detailed breakdowns will be added in future updates.* \ No newline at end of file diff --git a/docs/contributing.md b/docs/contributing.md index 75cd536..f3e7924 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -1,27 +1,27 @@ # Contributing to Home Assistant MCP -We welcome contributions from the community! Your help and feedback are essential to improving the MCP Server. Please review the following guidelines before contributing. +We welcome community contributions to improve the MCP Server. Please review the following guidelines before contributing. ## How to Contribute -1. **Fork the Repository**: Create your personal fork of the project on GitHub. -2. **Create a Feature Branch**: Use clear branch names, e.g., `feature/your-feature` or `bugfix/short-description`. -3. **Make Changes**: Develop your feature or fix bugs. Ensure your code follows the project's coding conventions. -4. **Write Tests**: Include tests for new features or bug fixes. We aim for high code coverage. -5. **Submit a Pull Request (PR)**: Once your changes are complete, submit a PR. Our team will review your request and provide feedback. -6. **Address Feedback**: Make any necessary revisions based on code review feedback. +1. **Fork the Repository:** Create your personal fork on GitHub. +2. **Create a Feature Branch:** Use a clear name (e.g., `feature/your-feature` or `bugfix/short-description`). +3. **Make Changes:** Develop your feature or fix bugs while following our coding standards. +4. **Write Tests:** Include tests for new features or bug fixes. +5. **Submit a Pull Request:** Once your changes are complete, submit a PR for review. +6. **Address Feedback:** Revise your PR based on maintainers' suggestions. ## Code Style Guidelines - Follow the project's established coding style. - Use Bun tooling for linting and formatting: - - `bun run lint` for linting - - `bun run format` for formatting + - `bun run lint` + - `bun run format` ## Documentation -- Update relevant documentation alongside your code changes. -- Ensure that tests pass and coverage remains high. +- Update documentation alongside your code changes. +- Ensure tests pass and coverage remains high. ## Reporting Issues diff --git a/docs/getting-started.md b/docs/getting-started.md index a5eef83..b216853 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -1,122 +1,30 @@ -# Getting Started with Home Assistant MCP +# Getting Started -This guide will help you get started with the Home Assistant MCP (Model Context Protocol). +Begin your journey with the Home Assistant MCP Server by following these steps: -## Prerequisites - -Before you begin, ensure you have: - -1. Node.js (v16 or higher) -2. A running Home Assistant instance -3. A Home Assistant Long-Lived Access Token - -## Installation - -1. Clone the repository: - ```bash - git clone https://github.com/yourusername/homeassistant-mcp.git - cd homeassistant-mcp - ``` - -2. Install dependencies: - ```bash - bun install - ``` - -3. Copy the example environment file: - ```bash - cp .env.example .env - ``` - -4. Edit the `.env` file with your configuration: - ```env - # Server Configuration - PORT=3000 - BUN_ENV=development - - # Home Assistant Configuration - HASS_HOST=http://your-hass-instance:8123 - HASS_TOKEN=your-long-lived-access-token - - # Security Configuration - JWT_SECRET=your-secret-key - ``` - -## Configuration - -### Environment Variables - -- `PORT`: The port number for the MCP server (default: 3000) -- `BUN_ENV`: The environment mode (development, production, test) -- `HASS_HOST`: Your Home Assistant instance URL -- `HASS_TOKEN`: Your Home Assistant Long-Lived Access Token -- `JWT_SECRET`: Secret key for JWT token generation - -### Development Mode - -For development, you can use: - -```bash -bun run dev -``` - -This will start the server in development mode with hot reloading. - -### Production Mode - -For production, build and start the server: - -```bash -bun run build -bun start -``` - -## First Steps - -1. Check the server is running: - ```bash - curl http://localhost:3000/api/health - ``` - -2. List available devices: - ```bash - curl -H "Authorization: Bearer your-token" http://localhost:3000/api/tools/devices - ``` - -3. Subscribe to events: - ```bash - curl -H "Authorization: Bearer your-token" http://localhost:3000/api/sse/subscribe?events=state_changed - ``` - -## Next Steps - -- Read the [API Documentation](./API.md) for available endpoints -- Learn about [Server-Sent Events](./SSE_API.md) for real-time updates -- Explore available [Tools](./tools/README.md) for device control -- Check the [Configuration Guide](./configuration/README.md) for advanced settings +- **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/README.md) for device control and automation. +- **Configuration:** Refer to the [Configuration Guide](configuration.md) for setup and advanced settings. ## Troubleshooting -If you encounter issues: - -1. Verify your Home Assistant instance is accessible -2. Check your environment variables are correctly set -3. Look for errors in the server logs -4. Consult the [Troubleshooting Guide](./troubleshooting.md) +If you encounter any issues: +1. Verify that your Home Assistant instance is accessible. +2. Ensure that all required environment variables are properly set. +3. Consult the [Troubleshooting Guide](troubleshooting.md) for additional solutions. ## Development -For development and contributing: - -1. Fork the repository -2. Create a feature branch -3. Follow the [Development Guide](./development/README.md) -4. Submit a pull request +For contributors: +1. Fork the repository. +2. Create a feature branch. +3. Follow the [Development Guide](development/README.md) for contribution guidelines. +4. Submit a pull request with your enhancements. ## Support -Need help? Check out: - -- [GitHub Issues](https://github.com/yourusername/homeassistant-mcp/issues) -- [Troubleshooting Guide](./troubleshooting.md) -- [FAQ](./troubleshooting.md#faq) \ No newline at end of file +Need help? +- Visit our [GitHub Issues](https://github.com/jango-blockchained/homeassistant-mcp/issues). +- Review the [Troubleshooting Guide](troubleshooting.md). +- Check the [FAQ](troubleshooting.md#faq) for common questions. \ No newline at end of file diff --git a/docs/roadmap.md b/docs/roadmap.md index 7a156ea..77d9d64 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,12 +1,12 @@ # Roadmap for MCP Server -The following roadmap outlines our planned enhancements and future directions for the Home Assistant MCP Server. This document is a living artifact and will be updated regularly as new features are planned and developed. +The following roadmap outlines our planned enhancements and future directions for the Home Assistant MCP Server. This document is a living guide that will be updated as new features are planned and developed. ## Near-Term Goals - **Advanced Automation Capabilities:** - - Integrate more sophisticated automation rules with conditional logic and multi-step execution. - - Introduce a visual automation builder to simplify rule creation. + - Integrate sophisticated automation rules with conditional logic and multi-step execution. + - Introduce a visual automation builder for simplified rule creation. - **Enhanced Security Features:** - Implement multi-factor authentication for critical actions. @@ -14,15 +14,15 @@ The following roadmap outlines our planned enhancements and future directions fo - Expand monitoring and alerting for potential security breaches. - **Performance Optimizations:** - - Refine the server's resource utilization to reduce latency. - - Optimize real-time data streaming via SSE for higher throughput. + - Refine resource utilization to reduce latency. + - Optimize real-time data streaming via SSE. - Introduce advanced caching mechanisms for frequently requested data. ## Mid-Term Goals - **User Interface Improvements:** - - Develop an intuitive, web-based dashboard for easier device management and monitoring. - - Provide real-time analytics and performance metrics in the dashboard. + - Develop an intuitive web-based dashboard for device management and monitoring. + - Provide real-time analytics and performance metrics. - **Expanded Integrations:** - Support a broader range of smart home devices and brands. @@ -35,17 +35,17 @@ The following roadmap outlines our planned enhancements and future directions fo ## Long-Term Vision - **Ecosystem Expansion:** - - Build a modular plugin system that allows community-driven extensions and integrations. - - Enable seamless integration with future technologies in the smart home and AI domains. + - Build a modular plugin system for community-driven extensions and integrations. + - Enable seamless integration with future technologies in smart home and AI domains. - **Scalability and Resilience:** - - Architect the system to support large-scale deployments across multiple instances. + - Architect the system to support large-scale deployments. - Incorporate advanced load balancing and failover mechanisms. ## How to Follow the Roadmap -- **Community Involvement:** We encourage community feedback and contributions to help refine and prioritize our roadmap. -- **Regular Updates:** This document is regularly updated with new goals, milestones, and completed tasks. -- **Transparency:** Check the project's GitHub repository and issues for ongoing discussions and updates related to roadmap items. +- **Community Involvement:** We welcome and encourage feedback. +- **Regular Updates:** This document is updated regularly with new goals and milestones. +- **Transparency:** Check our GitHub repository and issue tracker for ongoing discussions. -*This roadmap is intended to serve as a guide and may evolve based on community needs, technological advancements, and strategic priorities.* \ No newline at end of file +*This roadmap is intended as a guide and may evolve based on community needs, technological advancements, and strategic priorities.* \ No newline at end of file diff --git a/docs/testing.md b/docs/testing.md index a5f3db1..64635e8 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -7,49 +7,49 @@ bun test # Run all tests bun test --watch # Run tests in watch mode bun test --coverage # Run tests with coverage -bun test path/to/test.ts # Run specific test file +bun test path/to/test.ts # Run a specific test file # Additional Options DEBUG=true bun test # Run with debug output -bun test --pattern "auth" # Run tests matching pattern -bun test --timeout 60000 # Run with custom timeout +bun test --pattern "auth" # Run tests matching a pattern +bun test --timeout 60000 # Run with a custom timeout ``` ## Overview -This document describes the testing setup and practices used in the Home Assistant MCP project. The project uses Bun's test runner for unit and integration testing, with a comprehensive test suite covering security, SSE (Server-Sent Events), middleware, and other core functionalities. +This document describes the testing setup and practices used in the Home Assistant MCP project. We use Bun's test runner for both unit and integration testing, ensuring comprehensive coverage across modules. ## Test Structure Tests are organized in two main locations: 1. **Root Level Integration Tests** (`/__tests__/`): - ``` - __tests__/ - ├── ai/ # AI/ML component tests - ├── api/ # API integration tests - ├── context/ # Context management tests - ├── hass/ # Home Assistant integration tests - ├── schemas/ # Schema validation tests - ├── security/ # Security integration tests - ├── tools/ # Tools and utilities tests - ├── websocket/ # WebSocket integration tests - ├── helpers.test.ts # Helper function tests - ├── index.test.ts # Main application tests - └── server.test.ts # Server integration tests - ``` + +``` +__tests__/ +├── ai/ # AI/ML component tests +├── api/ # API integration tests +├── context/ # Context management tests +├── hass/ # Home Assistant integration tests +├── schemas/ # Schema validation tests +├── security/ # Security integration tests +├── tools/ # Tools and utilities tests +├── websocket/ # WebSocket integration tests +├── helpers.test.ts # Helper function tests +├── index.test.ts # Main application tests +└── server.test.ts # Server integration tests +``` 2. **Component Level Unit Tests** (`src/**/`): - ``` - src/ - ├── __tests__/ # Global test setup and utilities - │ └── setup.ts # Global test configuration - ├── component/ - │ ├── __tests__/ # Component-specific unit tests - │ └── component.ts - ``` -The root level `__tests__` directory contains integration and end-to-end tests that verify the interaction between different components of the system, while the component-level tests focus on unit testing individual modules. +``` +src/ +├── __tests__/ # Global test setup and utilities +│ └── setup.ts # Global test configuration +├── component/ +│ ├── __tests__/ # Component-specific unit tests +│ └── component.ts +``` ## Test Configuration @@ -88,26 +88,21 @@ bun run format ### Global Configuration -The project uses a global test setup file (`src/__tests__/setup.ts`) that provides: - +A global test setup file (`src/__tests__/setup.ts`) provides: - Environment configuration - Mock utilities - Test helper functions -- Global test lifecycle hooks +- Global lifecycle hooks ### Test Environment -Tests run with the following configuration: - -- Environment variables are loaded from `.env.test` -- Console output is suppressed during tests (unless DEBUG=true) -- JWT secrets and tokens are automatically configured for testing -- Rate limiting and other security features are properly initialized +- Environment variables are loaded from `.env.test`. +- Console output is minimized unless `DEBUG=true`. +- JWT secrets and tokens are preconfigured for testing. +- Rate limiting and security features are initialized appropriately. ## Running Tests -To run the test suite: - ```bash # Basic test run bun test @@ -115,7 +110,7 @@ bun test # Run tests with coverage bun test --coverage -# Run specific test file +# Run a specific test file bun test path/to/test.test.ts # Run tests in watch mode @@ -131,82 +126,61 @@ bun test --timeout 60000 bun test --pattern "auth" ``` -### Test Environment Setup +## Advanced Debugging -1. **Prerequisites**: - - Bun >= 1.0.0 - - Node.js dependencies (see package.json) +### Using Node Inspector -2. **Environment Files**: - - `.env.test` - Test environment variables - - `.env.development` - Development environment variables +```bash +# Start tests with inspector +bun test --inspect -3. **Test Data**: - - Mock responses in `__tests__/mock-responses/` - - Test fixtures in `__tests__/fixtures/` +# Start tests with inspector and break on first line +bun test --inspect-brk +``` -### Continuous Integration +### Using VS Code -The project uses GitHub Actions for CI/CD. Tests are automatically run on: -- Pull requests -- Pushes to main branch -- Release tags +Create a launch configuration in `.vscode/launch.json`: + +```json +{ + "version": "0.2.0", + "configurations": [ + { + "type": "bun", + "request": "launch", + "name": "Debug Tests", + "program": "${workspaceFolder}/node_modules/bun/bin/bun", + "args": ["test", "${file}"], + "cwd": "${workspaceFolder}", + "env": { "DEBUG": "true" } + } + ] +} +``` + +### Test Isolation + +To run a single test in isolation: + +```typescript +describe.only("specific test suite", () => { + it.only("specific test case", () => { + // Only this test will run + }); +}); +``` ## Writing Tests ### Test File Naming -- Test files should be placed in a `__tests__` directory adjacent to the code being tested -- Test files should be named `*.test.ts` -- Test files should mirror the structure of the source code +- Place test files in a `__tests__` directory adjacent to the code being tested. +- Name files with the pattern `*.test.ts`. +- Mirror the structure of the source code in your test organization. -### Test Structure +### Example Test Structure -```typescript -import { describe, expect, it, beforeEach } from "bun:test"; - -describe("Module Name", () => { - beforeEach(() => { - // Setup for each test - }); - - describe("Feature/Function Name", () => { - it("should do something specific", () => { - // Test implementation - }); - }); -}); -``` - -### Test Utilities - -The project provides several test utilities: - -```typescript -import { testUtils } from "../__tests__/setup"; - -// Available utilities: -- mockWebSocket() // Mock WebSocket for SSE tests -- mockResponse() // Mock HTTP response for API tests -- mockRequest() // Mock HTTP request for API tests -- createTestClient() // Create test SSE client -- createTestEvent() // Create test event -- createTestEntity() // Create test Home Assistant entity -- wait() // Helper to wait for async operations -``` - -## Testing Patterns - -### Security Testing - -Security tests cover: -- Token validation and encryption -- Rate limiting -- Request validation -- Input sanitization -- Error handling - -Example: ```typescript describe("Security Features", () => { it("should validate tokens correctly", () => { @@ -218,83 +192,17 @@ describe("Security Features", () => { }); ``` -### SSE Testing +## Coverage -SSE tests cover: -- Client authentication -- Message broadcasting -- Rate limiting -- Subscription management -- Client cleanup +The project maintains strict coverage: +- Overall coverage: at least 80% +- Critical paths: 90%+ +- New features: ≥85% coverage -Example: -```typescript -describe("SSE Features", () => { - it("should authenticate valid clients", () => { - const client = createTestClient("test-client"); - const result = sseManager.addClient(client, validToken); - expect(result?.authenticated).toBe(true); - }); -}); -``` +Generate a coverage report with: -### Middleware Testing - -Middleware tests cover: -- Request validation -- Input sanitization -- Error handling -- Response formatting - -Example: -```typescript -describe("Middleware", () => { - it("should sanitize HTML in request body", () => { - const req = mockRequest({ - body: { text: '' } - }); - sanitizeInput(req, res, next); - expect(req.body.text).toBe(""); - }); -}); -``` - -### Integration Testing - -Integration tests in the root `__tests__` directory cover: - -- **AI/ML Components**: Testing machine learning model integrations and predictions -- **API Integration**: End-to-end API route testing -- **Context Management**: Testing context persistence and state management -- **Home Assistant Integration**: Testing communication with Home Assistant -- **Schema Validation**: Testing data validation across the application -- **Security Integration**: Testing security features in a full system context -- **WebSocket Communication**: Testing real-time communication -- **Server Integration**: Testing the complete server setup and configuration - -Example integration test: -```typescript -describe("API Integration", () => { - it("should handle a complete authentication flow", async () => { - // Setup test client - const client = await createTestClient(); - - // Test registration - const regResponse = await client.register(testUser); - expect(regResponse.status).toBe(201); - - // Test authentication - const authResponse = await client.authenticate(testCredentials); - expect(authResponse.status).toBe(200); - expect(authResponse.body.token).toBeDefined(); - - // Test protected endpoint access - const protectedResponse = await client.get("/api/protected", { - headers: { Authorization: `Bearer ${authResponse.body.token}` } - }); - expect(protectedResponse.status).toBe(200); - }); -}); +```bash +bun test --coverage ``` ## Security Middleware Testing diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 08f3c17..5a29c0e 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -1,144 +1,135 @@ # Troubleshooting Guide -This guide helps you diagnose and fix common issues with the Home Assistant Model Context Protocol (MCP). +This guide provides solutions to common issues encountered with the Home Assistant MCP Server. ## Common Issues -### Connection Issues +- **Server Not Starting:** + - Verify that all required environment variables are correctly set. + - Check for port conflicts or missing dependencies. + - Review the server logs for error details. -#### Cannot Connect to Home Assistant +- **Connection Problems:** + - Ensure your Home Assistant instance is reachable. + - Confirm that the authentication token is valid. + - Check network configurations and firewalls. + +## Tool Issues + +### Tool Not Found **Symptoms:** -- Connection timeout errors -- "Failed to connect to Home Assistant" messages -- 401 Unauthorized errors +- "Tool not found" errors or 404 responses. **Solutions:** -1. Verify Home Assistant is running -2. Check HASS_HOST environment variable -3. Validate HASS_TOKEN is correct -4. Ensure network connectivity -5. Check firewall settings +- Double-check the tool name spelling. +- Verify that the tool is correctly registered. +- Review tool imports and documentation. -#### SSE Connection Drops +### Tool Execution Failures **Symptoms:** -- Frequent disconnections -- Missing events -- Connection reset errors +- Execution errors or timeouts. **Solutions:** -1. Check network stability -2. Increase connection timeout -3. Implement reconnection logic -4. Monitor server resources +- Validate input parameters. +- Check and review error logs. +- Debug the tool implementation. +- Ensure proper permissions in Home Assistant. -### Authentication Issues - -#### Invalid Token - -**Symptoms:** -- 401 Unauthorized responses -- "Invalid token" messages -- Authentication failures - -**Solutions:** -1. Generate new Long-Lived Access Token -2. Check token expiration -3. Verify token format -4. Update environment variables - -#### Rate Limiting - -**Symptoms:** -- 429 Too Many Requests -- "Rate limit exceeded" messages - -**Solutions:** -1. Implement request throttling -2. Adjust rate limit settings -3. Cache responses -4. Optimize request patterns - -### Tool Issues - -#### Tool Not Found - -**Symptoms:** -- "Tool not found" errors -- 404 Not Found responses - -**Solutions:** -1. Check tool name spelling -2. Verify tool registration -3. Update tool imports -4. Check tool availability - -#### Tool Execution Fails - -**Symptoms:** -- Tool execution errors -- Unexpected responses -- Timeout issues - -**Solutions:** -1. Validate input parameters -2. Check error logs -3. Debug tool implementation -4. Verify Home Assistant permissions - -## Debugging +## Debugging Steps ### Server Logs -1. Enable debug logging: +1. Enable debug logging by setting: ```env LOG_LEVEL=debug ``` - 2. Check logs: ```bash npm run logs ``` - -3. Filter logs: +3. Filter errors: ```bash npm run logs | grep "error" ``` ### Network Debugging -1. Check API endpoints: +1. Test API endpoints: ```bash curl -v http://localhost:3000/api/health ``` - 2. Monitor SSE connections: ```bash curl -N http://localhost:3000/api/sse/stats ``` - -3. Test WebSocket: +3. Test WebSocket connectivity: ```bash wscat -c ws://localhost:3000 ``` ### Performance Issues -1. Monitor memory usage: - ```bash - npm run stats - ``` +- Monitor memory usage with: + ```bash + npm run stats + ``` -2. Check response times: - ```bash - curl -w "%{time_total}\n" -o /dev/null -s http://localhost:3000/api/health - ``` +## Security Middleware Troubleshooting -3. Profile code: - ```bash - npm run profile - ``` +### Rate Limiting Problems + +**Symptoms:** Receiving 429 (Too Many Requests) errors. + +**Solutions:** +- Adjust and fine-tune rate limit settings. +- Consider different limits for critical versus non-critical endpoints. + +### Request Validation Failures + +**Symptoms:** 400 or 415 errors on valid requests. + +**Solutions:** +- Verify that the `Content-Type` header is set correctly. +- Inspect request payload size and format. + +### Input Sanitization Issues + +**Symptoms:** Unexpected data transformation or loss. + +**Solutions:** +- Test sanitization with various input types. +- Implement custom sanitization for complex data if needed. + +### Security Header Configuration + +**Symptoms:** Missing or improper security headers. + +**Solutions:** +- Review and update security header configurations (e.g., Helmet settings). +- Ensure environment-specific header settings are in place. + +### Error Handling and Logging + +**Symptoms:** Inconsistent error responses. + +**Solutions:** +- Enhance logging for detailed error tracking. +- Adjust error handlers for production and development differences. + +## Additional Resources + +- [OWASP Security Guidelines](https://owasp.org/www-project-top-ten/) +- [Helmet.js Documentation](https://helmetjs.github.io/) +- [JWT Security Best Practices](https://jwt.io/introduction) + +## Getting Help + +If issues persist: +1. Review detailed logs. +2. Verify your configuration and environment. +3. Consult the GitHub issue tracker or community forums. ## FAQ diff --git a/docs/usage.md b/docs/usage.md index 86e9dbd..5c16cb7 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -1,5 +1,34 @@ # Usage Guide +This guide explains how to use the Home Assistant MCP Server for smart home device management and integration with language learning systems. + ## Basic Usage -## Advanced Features \ No newline at end of file +1. **Starting the Server:** + - For development: run `npm run dev`. + - For production: run `npm run build` followed by `npm start`. + +2. **Accessing the Web Interface:** + - Open [http://localhost:3000](http://localhost:3000) in your browser. + +3. **Real-Time Updates:** + - Connect to the SSE endpoint at `/subscribe_events?token=YOUR_TOKEN&domain=light` to receive live updates. + +## Advanced Features + +1. **API Interactions:** + - Use the REST API for operations such as device control, automation, and add-on management. + - See [API Documentation](api.md) for details. + +2. **Tool Integrations:** + - Multiple tools are available (see [Tools Documentation](tools/README.md)), for tasks like automation management and notifications. + +3. **Security Settings:** + - Configure token-based authentication and environment variables as per the [Configuration Guide](getting-started/configuration.md). + +4. **Customization and Extensions:** + - Extend server functionality by developing new tools as outlined in the [Development Guide](development/README.md). + +## Troubleshooting + +If you experience issues, review the [Troubleshooting Guide](troubleshooting.md). \ No newline at end of file