Generated by /repo-architecture skill v2.0.0

Home Assistant MCP Architecture

The Home Assistant MCP (Model Context Protocol) server provides AI agents with complete programmatic control over a Home Assistant smart home installation. It exposes 40+ MCP tools across 30+ tool modules that allow an AI client to query entity states, control devices, manage automations, read sensor history, configure dashboards, manage integrations, and interact with virtually every Home Assistant subsystem.

The server communicates with Home Assistant via its REST API and WebSocket API, translating MCP tool calls into HA service calls, state queries, and configuration operations. It supports multiple transport modes: stdio (for Claude Code / CLI), SSE (Server-Sent Events), and HTTP (Streamable HTTP for web-based MCP clients).

Upstream project: github.com/homeassistant-ai/ha-mcp (MIT license, by Julien). Version 7.1.0. Python 3.13, FastMCP 3.1.1 framework.
Package Version
7.1.0
Tool Modules
30+
Transport Modes
3
Runtime
Python 3.13
Framework
FastMCP 3.1.1
Container Port
8086

2. Runtime Architecture

Diagram A: Runtime Request Flow

stdio HTTP :8086 REST API WebSocket HTTP /api/* WS /api/ws Claude Code MCP client / stdio AI agent smart home control Web MCP Client HTTP / SSE transport Browser-based agents HA MCP Server Python 3.13 / FastMCP 3.1.1 / :8086 30+ tool modules, auth, transforms REST Client httpx / async HTTP State queries, service calls WebSocket Client websockets / persistent Subscriptions, real-time events Home Assistant homeassistant.sanchezfamily.ca Smart home hub (21 integrations) Legend Primary path Direct call External Services Code Orchestration

Request Flow

  1. An MCP client (Claude Code via stdio, or a web client via HTTP/SSE on port 8086) sends a tool call to the HA MCP Server.
  2. The server authenticates the request using the HOMEASSISTANT_TOKEN (long-lived access token) or OAuth2 flow.
  3. The appropriate tool module processes the request, delegating to the REST Client (for state queries, service calls, config operations) or the WebSocket Client (for real-time subscriptions, event streaming, template rendering).
  4. The client modules call the Home Assistant API at https://homeassistant.sanchezfamily.ca.
  5. Results are transformed, filtered (via transforms/ and utils/), and returned as structured MCP responses.

3. Component Classification

ComponentClassificationRole
server.pyPrimaryMain MCP server — registers all tools, handles routing, manages lifecycle
__main__.pyPrimaryEntry points for all transport modes (stdio, SSE, HTTP, OAuth)
client/rest_client.pyPrimaryAsync HTTP client for Home Assistant REST API (httpx-based)
client/websocket_client.pyPrimaryPersistent WebSocket connection for real-time HA communication
client/websocket_listener.pySecondaryEvent listener for WebSocket state change subscriptions
tools/ (30+ modules)PrimaryMCP tool implementations — entities, devices, automations, dashboards, etc.
auth/provider.pySecondaryOAuth2 authentication provider for HA authorization flow
auth/consent_form.pySecondaryHTML consent form for OAuth authorization UI
config.pySecondaryPydantic settings model — reads env vars for HA URL, token, options
errors.pySecondaryStructured error codes and error response factory
transforms/AuxiliaryResponse transforms — categorized search result formatting
utils/AuxiliaryFuzzy search, domain handlers, operation manager, Python sandbox, usage logger
resources/AuxiliaryStatic resources — dashboard guide, card types, HA best-practices skill

4. Tool Modules

The tools/ directory contains 30+ Python modules, each registering one or more MCP tools with the server. These are grouped by Home Assistant domain.

ModuleSizeDomain
tools_config_dashboards.py70KBDashboard CRUD, card management, view configuration
tools_config_helpers.py53KBInput helpers (boolean, number, text, select, datetime)
tools_registry.py48KBEntity and device registry queries
smart_search.py47KBIntelligent entity/device search with fuzzy matching
tools_search.py36KBGeneral search across all HA domains
tools_entities.py33KBEntity state queries, filtering, bulk operations
tools_hacs.py32KBHACS (Home Assistant Community Store) management
tools_history.py30KBEntity state history, statistics, trend analysis
device_control.py28KBDirect device control (lights, switches, covers, climate, media)
tools_updates.py28KBSystem and integration update management
tools_config_automations.py26KBAutomation CRUD, enable/disable, trigger
tools_bug_report.py24KBDiagnostic bug report generation
tools_resources.py23KBMCP resource endpoints (documentation, guides)
tools_config_entry_flow.py21KBIntegration setup flows (config entries)
tools_todo.py20KBTo-do list management
tools_traces.py21KBAutomation and script trace inspection
tools_utility.py21KBTemplate rendering, YAML validation, utility operations
tools_areas.py18KBArea/floor/room management
tools_filesystem.py18KBHA config file operations (read/write YAML)
backup.py18KBHA backup creation and management
tools_integrations.py16KBIntegration listing and management
tools_config_scripts.py15KBScript CRUD and execution
tools_calendar.py15KBCalendar entity queries and event management
tools_system.py15KBSystem info, restart, check config, logs
best_practice_checker.py15KBValidates automations against HA best practices
tools_service.py14KBHA service call execution
tools_blueprints.py14KBAutomation blueprint management
tools_zones.py13KBZone management (presence detection)
tools_addons.py13KBSupervisor add-on management
tools_groups.py12KBEntity group management
tools_mcp_component.py12KBMCP component self-inspection
tools_labels.py10KBLabel management for entities and devices
tools_config_info.py11KBConfiguration validation and diagnostics
tools_services.py11KBService domain listing and discovery
tools_camera.py6KBCamera snapshot capture
tools_voice_assistant.py7KBVoice assistant pipeline control

5. Public Interfaces (MCP Tools)

The server exposes MCP tools organized by domain. The following is a representative catalog of the key tool categories.

Entity Control & State

Tool CategoryModuleCapabilities
Entity Queriestools_entitiesGet entity states, filter by domain/area/label, bulk state retrieval
Device Controldevice_controlTurn on/off, set brightness, color, temperature, position, media playback
Service Callstools_serviceCall any HA service with arbitrary parameters
Smart Searchsmart_searchFuzzy entity/device search with natural language queries

Configuration & Automation

Tool CategoryModuleCapabilities
Automationstools_config_automationsCreate, update, delete, enable/disable, trigger automations
Scriptstools_config_scriptsCRUD for scripts, execute with parameters
Dashboardstools_config_dashboardsCreate/edit dashboards, cards, views (Lovelace YAML)
Helperstools_config_helpersCreate/manage input_boolean, input_number, input_text, input_select, etc.
Blueprintstools_blueprintsImport, list, and manage automation blueprints

Monitoring & History

Tool CategoryModuleCapabilities
State Historytools_historyQuery entity history over time ranges, statistics, trends
Tracestools_tracesInspect automation/script execution traces for debugging
System Infotools_systemHA version, uptime, restart, check config, view logs
Bug Reportstools_bug_reportGenerate diagnostic reports with system state

Organization & Management

Tool CategoryModuleCapabilities
Areas & Zonestools_areas, tools_zonesManage rooms/floors, presence zones
Registrytools_registryDevice/entity registry queries, rename, disable
Integrationstools_integrationsList configured integrations, config entry details
Labels & Groupstools_labels, tools_groupsTag entities, manage groups
HACStools_hacsCommunity store: browse, install, update custom components
Updatestools_updatesCheck for and install HA core, OS, and integration updates
BackupsbackupCreate and manage HA backups
Add-onstools_addonsSupervisor add-on lifecycle (start, stop, install)

Specialized Tools

Tool CategoryModuleCapabilities
Calendartools_calendarQuery calendar events, create events
Cameratools_cameraCapture camera snapshots
To-Dotools_todoTo-do list item CRUD
Voice Assistanttools_voice_assistantVoice pipeline control
Filesystemtools_filesystemRead/write HA configuration files (YAML)
Utilitytools_utilityTemplate rendering, YAML validation
Best Practicesbest_practice_checkerValidate automations against HA best practices

Transport Endpoints

TransportEntry PointUse Case
stdioha-mcpClaude Code, CLI-based MCP clients
SSEha-mcp-sseServer-Sent Events for streaming clients
HTTP (Streamable)ha-mcp-web (port 8086, path /mcp)Web-based MCP clients, deployed mode
OAuthha-mcp-oauthOAuth2 authorization code flow

6. Repository Structure

/app/
  fastmcp.json                 # FastMCP stdio config
  fastmcp-http.json            # FastMCP HTTP deployment config (port 8086, /mcp)
  .venv/                       # Python 3.13 virtual environment
  src/
    ha_mcp/
      __init__.py              # Package metadata (v7.1.0)
      __main__.py              # Entry points: main(), main_web(), main_sse(), main_oauth()
      server.py                # HomeAssistantSmartMCPServer - core MCP server class
      config.py                # Pydantic Settings model (env var parsing)
      errors.py                # Error codes and response factory
      smoke_test.py            # Connection smoke test utility
      auth/
        provider.py            # OAuth2 auth provider for HA
        consent_form.py        # HTML consent form renderer
      client/
        rest_client.py         # HomeAssistantClient (httpx async)
        websocket_client.py    # WebSocket client for HA WS API
        websocket_listener.py  # Event subscription listener
      tools/
        (30+ modules)          # MCP tool implementations by HA domain
        device_control.py      # DeviceControlTools class
        smart_search.py        # SmartSearchTools class
        registry.py            # Tool registry management
        helpers.py             # Shared tool helper functions
        enhanced.py            # Enhanced tool wrappers
        util_helpers.py        # Common utility functions for tools
      transforms/
        categorized_search.py  # Search result categorization/formatting
      utils/
        domain_handlers.py     # HA domain-specific logic
        fuzzy_search.py        # Fuzzy string matching for entity names
        operation_manager.py   # Rate limiting, operation tracking
        python_sandbox.py      # Sandboxed Python execution
        usage_logger.py        # Tool usage logging/analytics
      resources/
        card_types.json        # Dashboard card type definitions
        dashboard_guide.md     # Lovelace dashboard creation guide
        skills-vendor/         # HA best practices skill (Claude plugin)

7. Deployment & Operations

Docker Compose

services:
  ha-mcp:
    image: ghcr.io/homeassistant-ai/ha-mcp:latest
    container_name: ha-mcp
    restart: unless-stopped
    env_file:
      - /home/rod/.env
    command: ["ha-mcp-web"]
    ports:
      - "10.0.1.6:8086:8086"

Environment Variables

VariableRequiredDescription
HOMEASSISTANT_URLYesHome Assistant base URL (e.g., https://homeassistant.sanchezfamily.ca)
HOMEASSISTANT_TOKENYesLong-lived access token for HA API authentication

Network Binding

The container binds port 8086 to 10.0.1.6 only (LAN interface). It is not published to all interfaces. The MCP endpoint is available at http://10.0.1.6:8086/mcp.

Operational Commands

# Check container status
docker ps | grep ha-mcp

# View logs
docker logs -f ha-mcp

# Restart
cd /home/rod/_rod/_hosting/docker/ha-mcp
docker compose restart

# Smoke test
docker exec ha-mcp ha-mcp-smoke-test

# Test MCP endpoint
curl -s http://10.0.1.6:8086/mcp

Claude Code Integration

To use this MCP server with Claude Code, add it to ~/.claude/.mcp.json:

{
  "mcpServers": {
    "ha-mcp": {
      "command": "docker",
      "args": ["exec", "-i", "ha-mcp", "ha-mcp"],
      "env": {}
    }
  }
}

This uses the stdio transport by running the ha-mcp entry point inside the running container. Alternatively, use the HTTP transport at http://10.0.1.6:8086/mcp.

8. Dependencies

PackageVersionPurpose
fastmcp3.1.1MCP server framework (tool registration, transport handling)
httpx0.28.1Async HTTP client for Home Assistant REST API calls
websockets16.0WebSocket client for HA real-time event subscriptions
pydantic2.12.5Settings validation, data models, type safety
python-dotenv1.2.2Environment variable loading from .env files
truststore0.10.4System certificate store integration for TLS
cryptography46.0.5Cryptographic operations for OAuth2 token handling
jq1.11.0JSON query/filter for response processing (Linux only)

External Service Dependencies

ServiceAddressProtocolRequired
Home Assistanthomeassistant.sanchezfamily.caHTTPS (REST + WebSocket)Yes

9. Constraints & Risks

ItemSeverityDescription
Token in .env Medium The HOMEASSISTANT_TOKEN is a long-lived access token stored in /home/rod/.env. It grants full API access to Home Assistant. Rotate periodically.
Full HA API access Medium The MCP server can call any HA service, including destructive operations (restart, config changes, device removal). The tool set has no built-in permission scoping beyond what HA provides.
Python 3.13 requirement Low Requires Python >=3.13, <3.14. Managed by the container image, so no host impact.
Network dependency Low Depends on Home Assistant being reachable at the configured URL. If HA is down, all tools return connection errors.
No Traefik route Info Currently bound to 10.0.1.6:8086 only. No dynamic.yml router or DNS entry. Access is LAN-direct only. Add a Traefik route if external or .home domain access is needed.
Env file leaks other secrets Medium The env_file is /home/rod/.env which also contains PVE tokens and SSH keys. These are injected into the container as environment variables unnecessarily. Consider using a dedicated .env with only HOMEASSISTANT_URL and HOMEASSISTANT_TOKEN.