Labsco
coffeerunhobby logo

MCP-HA-Connect

3

from coffeerunhobby

A production-ready Model Context Protocol (MCP) server for Home Assistant integration with AI assistants like Claude.

🔥🔥🔥✓ VerifiedPaid serviceAdvanced setup

MCP-HA-Connect

A production-ready Model Context Protocol (MCP) server for Home Assistant integration with AI assistants like Claude and LM Studio.

See docs/QUICK_START.md for Docker, HTTP server mode, n8n integration, and more installation options.

Key Features

Core Functionality

  • Smart Device Control
  • Lights: Brightness, color temperature, RGB color, transitions
  • Climate: Temperature, HVAC modes, fan modes, humidity
  • Covers: Position and tilt control
  • Switches: On/off control
  • Sensors & Contacts: State monitoring
  • Media Players: Playback control, volume, source selection
  • Fans: Speed, oscillation, direction
  • Locks: Lock/unlock control
  • Vacuums: Start, stop, return to base
  • Cameras: Motion detection, snapshots

Automation Management

  • List all automations with status
  • Trigger automations manually with variables
  • Enable/disable/toggle automations
  • Create new automations via API
  • Delete automations
  • View automation execution traces
  • Reload automations from configuration

System Features

  • Direct Home Assistant API integration
  • Long-lived access token authentication
  • Entity state management
  • Service call support
  • Advanced entity search
  • AI-powered sensor analysis with Ollama
  • Multiple transport modes (stdio, Streamable HTTP)
  • HTTP server with health checks
  • CORS support for browser-based clients
  • Structured logging (plain, JSON, GCP-JSON formats)
  • Comprehensive configuration validation with Zod
  • Full type safety with TypeScript
  • Stateful and stateless session support
  • JWT authentication with role-based access control
  • MCP Server Instructions for improved LLM tool selection

Bring your home network into the same assistant that runs your home. These are the high-value questions an LLM can actually answer about your network:

  • Internet & WAN status — "Is my internet up? What's my WAN IP and uplink speed?" Live per-WAN status, plus multi-WAN / ISP health and load-balancing for the gateway.
  • Event & alert logs — "What happened on my network?" The site event and alert logs, time-windowed (defaults to the last 7 days), to correlate with Home Assistant history.
  • Wireless security — rogue-AP scan results and (on Omada Pro) wireless intrusion detection (WIDS) for genuine network-security awareness.
  • Controller & device health — dashboard overview plus top devices by CPU and memory usage, HA-style monitoring of your network stack.
  • Speed tests — surface the controller's own speed-test results, pairing with AI-powered analyzeSensors for anomaly detection.
  • Pending devices — "Is there a new device waiting to be adopted?"
  • Firmware awareness — per-device firmware info and a controller-wide critical-upgrade overview, mirroring the Home Assistant checkUpdates philosophy across the network.
  • Client management — list/inspect connected clients, traffic activity, and apply rate-limit profiles, with presence correlation against Home Assistant device trackers.

A discoverable resource-graph mode (MCP_TOOL_REGISTRATION_MODE=graph) exposes all of the above through two tools — omada_browse + omada_read — keeping the tool-schema budget small for low-context models. See the Omada tool tables below for the full eager surface.

Available Tools (60 Total)

Home Assistant Tools (35)

State & Entity Tools

ToolDescription
getStatesGet all entity states (paginated, 50/page default). Use includeAttributes=true for full data
getStateGet the state of a specific entity by entity_id
getEntitiesByDomainGet entities for a domain (paginated, 50/page default). Use includeAttributes=true for full data
searchEntitiesSearch entities by name/entity_id (paginated, 50/page default). Use includeAttributes=true for full data
getAllSensorsGet all sensors (paginated, 50/page default). Use includeAttributes=true for full data
listEntitiesList entities with filtering (domain, state, search, limit). Use includeAttributes=true for full data
getDomainSummaryGet summary statistics for a domain
getHistoryGet historical data for an entity
listPersonsList all household members with location state (home/away)

Service & Control Tools

ToolDescription
callServiceCall any Home Assistant service
entityActionSimple turn_on/turn_off/toggle actions

Device Control Tools

ToolDescription
controlLightControl lights with brightness, color, temperature
controlClimateControl thermostats with temperature, HVAC mode
controlMediaPlayerControl media players with playback, volume
controlCoverControl covers/blinds with position, tilt
controlFanControl fans with speed, oscillation, direction
activateSceneActivate a Home Assistant scene
runScriptRun a Home Assistant script
sendNotificationSend notifications with full mobile app support (actions, priority, images)
listNotificationTargetsDiscover available mobile app notification targets

Automation Tools

ToolDescription
listAutomationsList all automations with status
triggerAutomationManually trigger an automation
enableAutomationEnable a disabled automation
disableAutomationDisable an automation
toggleAutomationToggle automation state
reloadAutomationsReload automations from config
createAutomationCreate a new automation
deleteAutomationDelete an automation
getAutomationTraceGet automation execution history

System Tools

ToolDescription
getVersionGet Home Assistant version and config info
restartHomeAssistantRestart the Home Assistant server
getSystemLogGet system log entries from logbook
checkUpdatesCheck for available updates

Calendar Tools

ToolDescription
listCalendarsList all calendar entities
getCalendarEventsGet events from one or all calendars

Omada Network Tools (24)

Site Tools

ToolDescription
omada_listSitesList all sites configured on the Omada controller

Device Tools

ToolDescription
omada_listDevicesList all network devices (APs, switches, gateways) in a site
omada_getDeviceGet detailed information about a specific network device
omada_searchDevicesSearch for devices globally across all sites
omada_getSwitchStackDetailGet detailed information about a switch stack
omada_listDevicesStatsGet statistics for global adopted devices with filtering

Client Tools

ToolDescription
omada_listClientsList all connected clients (devices/users) in a site
omada_getClientGet detailed information about a specific connected client
omada_listMostActiveClientsGet the most active clients sorted by total traffic
omada_listClientsActivityGet client activity statistics over time
omada_listClientsPastConnectionsGet historical client connection data

Rate Limit Tools

ToolDescription
omada_getRateLimitProfilesGet available rate limit profiles for a site
omada_setClientRateLimitSet custom bandwidth limits for a client (download/upload in Kbps)
omada_setClientRateLimitProfileApply a rate limit profile to a client
omada_disableClientRateLimitRemove bandwidth limits from a client

Security Tools

ToolDescription
omada_getThreatListGet security threat management list

Network Configuration Tools

ToolDescription
omada_getInternetInfoGet internet connection configuration for a site
omada_getPortForwardingStatusGet port forwarding rules (User or UPnP)
omada_getLanNetworkListGet LAN network configuration list
omada_getLanProfileListGet LAN profile configuration list
omada_getWlanGroupListGet WLAN group configuration list
omada_getSsidListGet SSID list for a WLAN group
omada_getSsidDetailGet detailed SSID configuration
omada_getFirewallSettingGet firewall configuration for a site

AI Tools (1)

ToolDescription
analyzeSensorsAnalyze sensor data using AI (Ollama) to detect issues and provide recommendations

MCP Resources

Resource URIDescription
hass://entitiesList all entities grouped by domain
hass://entities/{entity_id}Get state of a specific entity
hass://entities/{entity_id}/detailedGet detailed entity info with all attributes
hass://entities/domain/{domain}Get all entities for a domain
hass://search/{query}/{limit}Search entities with result limit

Getting Your Home Assistant Token

  1. Log into your Home Assistant instance
  2. Click on your profile (bottom left)
  3. Scroll down to "Long-Lived Access Tokens"
  4. Click "Create Token"
  5. Give it a name (e.g., "MCP Server")
  6. Copy the token (shown only once!)

Environment Variables

Required

VariableDescriptionExample
HA_URLHome Assistant URLhttp://homeassistant.10.0.0.19.nip.io:8123
HA_TOKENLong-lived access tokeneyJhbGciOiJIUzI1NiIsInR5cCI...

Optional - Home Assistant

VariableDefaultDescription
HA_PLUGIN_ENABLEDtrueEnable Home Assistant plugin
HA_STRICT_SSLtrueValidate SSL certificates
HA_TIMEOUT30000API request timeout (ms)

Optional - MCP Server

VariableDefaultDescription
MCP_SERVER_LOG_LEVELinfoLog level: debug, info, warn, error
MCP_SERVER_LOG_FORMATplainLog format: plain, json, gcp-json
MCP_SERVER_USE_HTTPfalseEnable HTTP mode (vs stdio)
MCP_SERVER_STATEFULfalseEnable stateful sessions in HTTP mode

Optional - HTTP Mode

VariableDefaultDescription
MCP_HTTP_PORT3000HTTP server port
MCP_HTTP_BIND_ADDR127.0.0.1Bind address
MCP_HTTP_PATH/mcpMCP endpoint path
MCP_HTTP_ENABLE_HEALTHCHECKtrueEnable health check endpoint
MCP_HTTP_HEALTHCHECK_PATH/healthHealth check path
MCP_HTTP_ALLOW_CORStrueEnable CORS
MCP_HTTP_ALLOWED_ORIGINS127.0.0.1,localhostAllowed CORS origins

Optional - SSE Events

VariableDefaultDescription
MCP_SSE_EVENTS_ENABLEDfalseEnable real-time SSE events
MCP_SSE_EVENTS_PATH/subscribe_eventsSSE endpoint path

Optional - Rate Limiting

VariableDefaultDescription
MCP_RATE_LIMIT_ENABLEDfalseEnable rate limiting
MCP_RATE_LIMIT_WINDOW_MS60000Rate limit window (ms)
MCP_RATE_LIMIT_MAX_REQUESTS100Max requests per window

Optional - Authentication

VariableDefaultDescription
MCP_AUTH_METHODnoneAuth method: none or bearer
MCP_AUTH_SECRET-JWT signing secret (min 32 chars, required for bearer method)
MCP_PERMISSIONS_CONFIG-JSON config for user roles and permissions

JWT Authentication

When MCP_AUTH_METHOD=bearer, clients must provide a JWT token in the Authorization header:

Authorization: Bearer <jwt-token>

Generate tokens with your MCP_AUTH_SECRET using HS256 algorithm. The JWT payload should include:

  • sub (subject): User identifier for permission lookup
  • exp (optional): Expiration timestamp

Permission System

The server uses role-based access control with binary permission masks:

PermissionFlagDescription
ADMIN1System operations (restart, updates)
CONFIGURE2Create/modify automations, scripts
CONTROL4Control devices (lights, climate, etc.)
QUERY8Read entity states, history, lists
NOTIFY16Send notifications
AI32Use AI analysis features

Predefined Roles:

RolePermissions
NONENo permissions
READONLYQUERY only
OPERATORQUERY + CONTROL + NOTIFY
CONTRIBUTORQUERY + CONTROL + NOTIFY + CONFIGURE
ADMINAll except AI
SUPERUSERAll permissions

Configuration Example:

{
  "users": [
    { "sub": "admin@example.com", "role": "admin" },
    { "sub": "user@example.com", "role": "operator" },
    { "sub": "viewer@example.com", "role": "readonly" }
  ],
  "defaultRole": "NONE"
}

Set via environment variable (escape quotes for shell):

MCP_PERMISSIONS_CONFIG='{"users":[{"sub":"admin","role":"admin"}],"defaultRole":"NONE"}'

Optional - AI Provider

VariableDefaultDescription
AI_PLUGIN_ENABLEDtrueEnable AI plugin
AI_PROVIDERollamaAI provider: ollama, openai, or none
AI_URLhttp://localhost:11434AI server URL (Ollama)
AI_MODELllama2AI model name
AI_TIMEOUT60000AI request timeout (ms)

Optional - Omada Network Controller

VariableDefaultDescription
OMADA_PLUGIN_ENABLEDfalseEnable Omada plugin
OMADA_BASE_URL-Omada controller URL (e.g., https://192.168.0.1:8043)
OMADA_CLIENT_ID-OAuth2 client ID from Omada controller
OMADA_CLIENT_SECRET-OAuth2 client secret from Omada controller
OMADA_OMADAC_ID-Omada controller ID
OMADA_SITE_ID-Default site ID for operations
OMADA_STRICT_SSLtrueValidate SSL certificates
OMADA_TIMEOUT30000API request timeout (ms)

Integration Examples

With Claude Desktop

Once configured, you can ask Claude:

  • "Show me all lights in my house"
  • "Turn on the kitchen lights to 50% brightness"
  • "Set the living room temperature to 72 degrees"
  • "Create an automation that turns off all lights at midnight"
  • "What automations are currently enabled?"
  • "Trigger the morning routine automation"
  • "Search for entities with 'bedroom' in their name"
  • "Get all climate entities"
  • "Analyze my sensors for any issues" (requires Ollama)
  • "Check the history of my thermostat"

With n8n Workflows

The server can be integrated with n8n for automated home monitoring. Pre-built workflows are available in the n8n/ directory:

  1. ai-agent-safety-monitor - Critical safety monitoring every 5 minutes

Importing Workflows

Method 1: n8n UI

  1. Open n8n: http://127.0.0.1:5678
  2. Click WorkflowsImport from File
  3. Select JSON file from n8n-files/
  4. Activate the workflow

Method 2: Docker CLI

# Copy workflow to n8n container
docker cp "n8n-files/AI Agent Safety Monitor - Updated.json" n8n:/files/workflow.json

# Import using n8n CLI
docker exec -it n8n n8n import:workflow --input=/files/workflow.json

# Verify import
docker exec -it n8n n8n list:workflow

With Web Applications

Use the HTTP transport with your MCP-compatible web client:

  1. Start server in HTTP mode
  2. Configure client to use http://localhost:3000/mcp
  3. Set transport to Streamable HTTP (MCP 2025-03-26)
  4. Enable CORS by adding your origin to MCP_HTTP_ALLOWED_ORIGINS

With Remote MCP Proxy (mcp-remote)

Connect a stdio-only client (Claude Desktop, LM Studio) to a remote HTTP MCP server using mcp-remote. On Windows, launch it through cmd /c and include -y so the first run never blocks on the npx install prompt:

{
  "mcpServers": {
    "homeassistant": {
      "command": "cmd",
      "args": [
        "/c",
        "npx",
        "-y",
        "mcp-remote",
        "https://your-server.example/mcp",
        "--header",
        "Authorization: Bearer <your-jwt-token>"
      ]
    }
  }
}

⚠️ Do not use ${VAR} placeholders in the --header value. A config like "Authorization: Bearer ${MCP_AUTH_TOKEN}" with a matching env block does not work on Windows: cmd /c only expands %VAR% (not ${VAR}), and mcp-remote does not substitute it either. The literal text ${MCP_AUTH_TOKEN} is sent as the token, the server replies 401, and mcp-remote then falls into a failing OAuth flow that surfaces as "Server disconnected". Inline the actual JWT instead. (On macOS/Linux you can instead let your shell expand the variable before the client launches.)

Security Best Practices

Network Security

  • Network Segmentation: Run MCP server on private LAN only
  • Docker Networks: Use Docker networks for container isolation
  • VLAN: Consider VLAN for IoT devices
  • No Internet Exposure: Never expose MCP server directly to internet

Token & Configuration Security

  • Store .env securely (contains access token)
  • Never commit .env to version control
  • Set .env permissions: chmod 600 .env
  • Use HA_STRICT_SSL=true for HTTPS in production
  • Rotate access tokens periodically
  • Restrict MCP_HTTP_ALLOWED_ORIGINS (avoid wildcard *)
  • Bind to 127.0.0.1 for local-only access
  • Enable rate limiting in production (MCP_RATE_LIMIT_ENABLED=true)

MCP Client Configuration Security

⚠️ Important: Storing tokens directly in MCP client config files (Claude Desktop, LM Studio) exposes them to anyone with filesystem access. Consider:

  • Using .env files with restricted permissions for Docker/local deployments
  • Setting file permissions on config files (e.g., chmod 600)
  • Using environment variable substitution if supported by your client
  • Never committing config files with real tokens to version control

Server Instructions

The server provides MCP Server Instructions during initialization to help LLMs understand how to optimally use the available tools. Instructions are dynamically generated based on enabled plugins and include:

  • Entity Queries: Guidance on pagination, attribute inclusion, and using specialized tools like listPersons
  • Device Control: When to use specialized control tools vs generic callService
  • Automation Workflows: Best practices for creating and testing automations
  • Omada Operations: Site context requirements, client vs device distinction, rate limiting safety
  • Cross-Plugin Integration: How HA presence detection correlates with Omada network clients

Instructions follow MCP best practices: concise, actionable, and focused on tool relationships rather than repeating individual tool descriptions.

Development

Setup

# Clone repository
git clone https://github.com/coffeerunhobby/mcp-ha-connect.git
cd mcp-ha-connect

# Install dependencies
npm install

# Copy environment template
cp .env.example .env

# Edit .env with your Home Assistant details
nano .env

# Build
npm run build

# Run
npm start

Available Scripts

npm run build      # Build TypeScript to dist/
npm run dev        # Run in development mode with watch
npm start          # Run built version
npm test           # Run tests
npm run lint       # Run ESLint
npm run format     # Format code with Prettier

Author

Coffee Run Hobby (github.com/coffeerunhobby)

Documentation