Home Assistant MCP Server Development
Expert guidance for developing and maintaining an MCP (Model Context Protocol) server that provides tools to interact with Home Assistant through its REST API.
What This Skill Does
This skill helps you work with a Python-based MCP server that allows AI assistants to control smart home devices, query states, and call services in Home Assistant. It enforces strict architectural principles, comprehensive testing, and clean code practices.
Architecture Overview
Core Components
**server.py** - MCP server using `mcp.server.Server`. Defines tools via `@server.list_tools()` and handles calls via `@server.call_tool()`. Uses global `HomeAssistantClient` initialized lazily.**client.py** - Async HTTP client using `httpx.AsyncClient` for Home Assistant REST API. All calls go through `_request()` method. Supports context manager protocol. Uses Jinja2 templates via `/api/template` for area queries.**config.py** - Pydantic-based configuration from environment variables (`HA_URL`, `HA_TOKEN`, `HA_VERIFY_SSL`, `HA_TIMEOUT`). Uses `python-dotenv` for `.env` support.**models.py** - Pydantic models: `EntityState`, `ServiceDomain`, `ConfigEntry`, `ServiceCallResponse`, `HistoryEntry`.Key Patterns
Server uses stdio transport for MCP communicationEntity operations infer domain from entity_id (e.g., `light.living_room` → domain `light`)Area queries use Home Assistant's template rendering with Jinja2 functionsTests use `pytest-httpx` for mocking, `pytest-asyncio` with `asyncio_mode = "auto"`Development Guidelines
1. Architectural Principles (MANDATORY)
Apply these principles to all code:
**SOLID Principles**: Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion**DDD and TDD**: Domain-Driven Design and Test-Driven Development**Clean Code**: Write readable, maintainable code**DRY**: Don't Repeat Yourself**KISS**: Keep It Simple**YAGNI**: You Ain't Gonna Need It**Modularization**: Create reusable components2. Code Organization Rules
**One class per file**: Use `snake_case` format**No multiple classes** in the same file**Google Style docstrings**: Document all functions and classes**Type hints**: Use strict type annotations3. Testing Requirements (MANDATORY)
#### Directory Structure
```
src/
home_assistant_mcp/
client.py
server.py
config.py
models.py
tests/
unit/ # Mirrors src/ structure
test_client.py
test_server.py
test_config.py
test_models.py
integration/ # Component interactions
test_server.py
e2e/ # Complete flows
data/ # Static test data
conftest.py # Global fixtures
```
#### Test Classification
**Unit Tests** (`tests/unit/`):
Test single logical units (function, method, class)No external services (HTTP, DB, queues)All dependencies mocked/stubbedExample: `tests/unit/test_client.py` for `src/home_assistant_mcp/client.py`**Integration Tests** (`tests/integration/`):
Test component interactionsUse real or semi-real resources (test DB, docker services)Mark with `@pytest.mark.integration`**E2E Tests** (`tests/e2e/`):
Cover complete business flowsTraverse entire stackMark with `@pytest.mark.e2e`#### Test Commands
```bash
uv run pytest # Run all tests
uv run pytest tests/unit # Unit tests only
uv run pytest tests/integration # Integration tests only
uv run pytest -k "test_name" # Pattern matching
uv run pytest --cov=src/home_assistant_mcp --cov-report=html # Coverage
```
4. Dependency Management
Use `uv` for all dependency operations:
```bash
uv add <package> # Production dependency
uv add --dev <package> # Development dependency
uv sync # Install dependencies
uv sync --group dev # Include dev dependencies
```
Step-by-Step Instructions
Creating a New Component
1. **Identify the layer** (Domain, Application, Infrastructure, UI)
2. **Create the file** in `snake_case`:
```bash
touch src/home_assistant_mcp/<component_name>.py
```
3. **Implement the class** with:
- Single Responsibility Principle
- Google-style docstrings for class and all methods
- Strict type hints
- Clean, readable code
4. **Create test file**:
```bash
touch tests/unit/test_<component_name>.py
```
5. **Write tests** covering success and error cases
6. **Run tests**:
```bash
uv run pytest
```
7. **Update README.md** if adding new functionality
8. **Commit with descriptive message**:
```bash
git add .
git commit -m "Add <component_name> with tests and documentation"
```
Adding a Dependency
1. **Determine dependency type** (production vs development)
2. **Add dependency**:
```bash
uv add httpx # Production
uv add --dev pytest # Development
```
3. **Update README.md** if dependency affects usage
4. **Commit**:
```bash
git commit -m "Add <package> dependency for <purpose>"
```
Running the Server
```bash
uv run home-assistant-mcp # Primary method
uv run python -m home_assistant_mcp.server # Alternative
```
Configuration
Required environment variables:
`HA_URL` - Home Assistant URL (e.g., `http://192.168.1.100:8123`)`HA_TOKEN` - Long-lived access tokenOptional:
`HA_VERIFY_SSL` - SSL verification (default: `true`)`HA_TIMEOUT` - Request timeout in seconds (default: `30`)Contribution Checklist
Before committing, verify:
[ ] Code follows SOLID, DDD, Clean Code principles[ ] Each class in own file (`snake_case`)[ ] Google-style documentation on all functions/classes[ ] Unit tests in `tests/unit/` mirror `src/` structure[ ] Integration tests marked with `@pytest.mark.integration`[ ] All tests pass: `uv run pytest`[ ] README.md updated if functionality added[ ] Dependencies added with `uv add` (or `uv add --dev`)[ ] Git commit with descriptive messageAvailable MCP Builder Skill
This project includes the official Anthropic mcp-builder skill in `.claude/skills/mcp-builder/`:
**Key References:**
`reference/python_mcp_server.md` - Python MCP server development guide`reference/mcp_best_practices.md` - MCP design best practices`reference/evaluation.md` - Evaluation methodologies**Scripts:**
`scripts/evaluation.py` - Evaluate MCP server quality`scripts/connections.py` - Manage MCP connections**Installation:**
```bash
./install-mcp-builder-skill.sh # Install/update
./install-mcp-builder-skill.sh --update # Update from Anthropic
./install-mcp-builder-skill.sh --install-deps # Install Python deps
```
Important Constraints
**NEVER** put multiple classes in one file**ALWAYS** write tests before considering code complete**ALWAYS** use `uv run` to execute commands**ALWAYS** document with Google-style docstrings**NEVER** commit untested code**ALWAYS** mirror `src/` structure in `tests/unit/`**ALWAYS** mark integration/e2e tests with pytest markersCI/CD Guidelines
**Every push**: Run `pytest tests/unit`**PRs to main**: Run `pytest tests/unit tests/integration -m "not e2e"`**Merges to main**: Run full suite `pytest tests`