homeassistant-mcp-server

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Home Assistant MCP Server

Home Assistant MCP Server

Skill by ara.so — MCP Skills collection
ara.so开发的Skill — MCP Skills合集

Overview

概述

The Home Assistant MCP Server enables AI assistants (Claude, GPT-4, Cursor, etc.) to control smart home devices through the Model Context Protocol. It provides 40 tools covering lights, climate, covers, locks, media players, vacuums, and more, with BM25 tool search to keep context lean and MCP resources for read-only data access.
Built with Python and FastMCP, it uses async operations with TTL-based caching to minimize API load.
Home Assistant MCP Server使AI助手(Claude、GPT-4、Cursor等)能够通过Model Context Protocol控制智能家居设备。它提供了40种工具,涵盖灯光、气候控制、窗帘、门锁、媒体播放器、吸尘器等设备,借助BM25工具搜索来精简上下文,并通过MCP资源实现只读数据访问。
基于Python和FastMCP构建,它采用异步操作和基于TTL的缓存机制,以最小化API负载。

Installation

安装

uvx (Recommended - No Installation Required)

uvx(推荐 - 无需安装)

Configure your MCP client with:
json
{
  "mcpServers": {
    "homeassistant": {
      "command": "uvx",
      "args": ["homeassistant-mcp"],
      "env": {
        "HASS_HOST": "http://homeassistant.local:8123",
        "HASS_TOKEN": "your_long_lived_access_token_here"
      }
    }
  }
}
使用以下配置你的MCP客户端:
json
{
  "mcpServers": {
    "homeassistant": {
      "command": "uvx",
      "args": ["homeassistant-mcp"],
      "env": {
        "HASS_HOST": "http://homeassistant.local:8123",
        "HASS_TOKEN": "your_long_lived_access_token_here"
      }
    }
  }
}

pip Installation

pip安装

bash
pip install homeassistant-mcp
Run with:
bash
export HASS_HOST="http://homeassistant.local:8123"
export HASS_TOKEN="your_token_here"
homeassistant-mcp
bash
pip install homeassistant-mcp
运行命令:
bash
export HASS_HOST="http://homeassistant.local:8123"
export HASS_TOKEN="your_token_here"
homeassistant-mcp

From Source

从源码安装

bash
git clone https://github.com/robbrad/homeassistant-mcp.git
cd homeassistant-mcp
python -m venv venv
source venv/bin/activate  # Windows: venv\Scripts\activate
pip install -e ".[dev]"
homeassistant-mcp
bash
git clone https://github.com/robbrad/homeassistant-mcp.git
cd homeassistant-mcp
python -m venv venv
source venv/bin/activate  # Windows系统:venv\Scripts\activate
pip install -e ".[dev]"
homeassistant-mcp

Configuration

配置

Required Environment Variables

必填环境变量

VariableDescriptionExample
HASS_HOST
Home Assistant URL
http://homeassistant.local:8123
HASS_TOKEN
Long-lived access tokenGenerate from HA profile page
变量描述示例
HASS_HOST
Home Assistant的URL
http://homeassistant.local:8123
HASS_TOKEN
长期访问令牌从HA个人资料页面生成

Optional Environment Variables

可选环境变量

VariableDefaultDescription
CACHE_TTL_STATES
30
Cache TTL for bulk state queries (seconds)
CACHE_TTL_ENTITY
10
Cache TTL for individual entity queries (seconds)
LOG_LEVEL
INFO
Logging level (DEBUG, INFO, WARNING, ERROR)
变量默认值描述
CACHE_TTL_STATES
30
批量状态查询的缓存TTL(秒)
CACHE_TTL_ENTITY
10
单个实体查询的缓存TTL(秒)
LOG_LEVEL
INFO
日志级别(DEBUG、INFO、WARNING、ERROR)

Claude Desktop Configuration

Claude桌面端配置

macOS:
~/Library/Application Support/Claude/claude_desktop_config.json

Windows:
%APPDATA%\Claude\claude_desktop_config.json
json
{
  "mcpServers": {
    "homeassistant": {
      "command": "uvx",
      "args": ["homeassistant-mcp"],
      "env": {
        "HASS_HOST": "http://homeassistant.local:8123",
        "HASS_TOKEN": "eyJ0eXAiOiJKV1QiLCJhbGc..."
      }
    }
  }
}
macOS:
~/Library/Application Support/Claude/claude_desktop_config.json

Windows:
%APPDATA%\Claude\claude_desktop_config.json
json
{
  "mcpServers": {
    "homeassistant": {
      "command": "uvx",
      "args": ["homeassistant-mcp"],
      "env": {
        "HASS_HOST": "http://homeassistant.local:8123",
        "HASS_TOKEN": "eyJ0eXAiOiJKV1QiLCJhbGc..."
      }
    }
  }
}

Cursor Configuration

Cursor配置

.cursor/mcp.json
:
json
{
  "mcpServers": {
    "homeassistant": {
      "command": "uvx",
      "args": ["homeassistant-mcp"],
      "env": {
        "HASS_HOST": "${HASS_HOST}",
        "HASS_TOKEN": "${HASS_TOKEN}"
      }
    }
  }
}
.cursor/mcp.json
:
json
{
  "mcpServers": {
    "homeassistant": {
      "command": "uvx",
      "args": ["homeassistant-mcp"],
      "env": {
        "HASS_HOST": "${HASS_HOST}",
        "HASS_TOKEN": "${HASS_TOKEN}"
      }
    }
  }
}

Tool Discovery System

工具发现系统

The server exposes 8 core tools for tool discovery instead of all 40 upfront:
服务器不会直接暴露全部40种工具,而是提供8种核心工具用于工具发现:

Core Discovery Tools

核心发现工具

python
undefined
python
undefined

1. Discover all available tools

1. 发现所有可用工具

discover_tools()
discover_tools()

Returns: Full catalog of 40 tools organized by category

返回结果:按类别组织的40种工具完整目录

2. Search for specific tools by description

2. 根据描述搜索特定工具

search_tools(query="lights brightness")
search_tools(query="lights brightness")

Returns: BM25-ranked tool schemas matching query

返回结果:匹配查询的BM25排序工具 schema

3. Call a discovered tool by name

3. 通过名称调用已发现的工具

call_tool(tool_name="lights_control", arguments={...})
call_tool(tool_name="lights_control", arguments={...})

Executes the specified tool with given arguments

使用给定参数执行指定工具

undefined
undefined

Example Tool Discovery Flow

工具发现流程示例

python
undefined
python
undefined

Step 1: Discover what tools are available

步骤1:发现可用工具

tools = discover_tools()
tools = discover_tools()

Returns categories: Device Control, Automation & Scenes, Input Helpers, etc.

返回类别:设备控制、自动化与场景、输入助手等

Step 2: Search for specific functionality

步骤2:搜索特定功能

results = search_tools(query="control lights and brightness")
results = search_tools(query="control lights and brightness")

Returns: lights_control schema with full parameters

返回结果:包含完整参数的lights_control schema

Step 3: Use the tool directly

步骤3:直接使用工具

lights_control( action="turn_on", entity_id="light.living_room", brightness=80, color_temp=370 )
undefined
lights_control( action="turn_on", entity_id="light.living_room", brightness=80, color_temp=370 )
undefined

Key Tools by Category

按类别划分的核心工具

Device Control Tools (16 total)

设备控制工具(共16种)

Light Control

灯光控制

python
undefined
python
undefined

Turn on lights with brightness and color

开启灯光并设置亮度和颜色

lights_control( action="turn_on", entity_id="light.bedroom", brightness=100, # 0-100 rgb_color=[255, 0, 0] # Red )
lights_control( action="turn_on", entity_id="light.bedroom", brightness=100, # 0-100 rgb_color=[255, 0, 0] # 红色 )

Set color temperature

设置色温

lights_control( action="turn_on", entity_id="light.kitchen", color_temp=370 # Warm white (153-500 mireds) )
lights_control( action="turn_on", entity_id="light.kitchen", color_temp=370 # 暖白色(153-500 mireds) )

Turn off

关闭灯光

lights_control(action="turn_off", entity_id="light.bedroom")
lights_control(action="turn_off", entity_id="light.bedroom")

Bulk operations

批量操作

lights_control( action="turn_on", entity_id="light.all_lights", brightness=50 )
undefined
lights_control( action="turn_on", entity_id="light.all_lights", brightness=50 )
undefined

Climate Control

气候控制

python
undefined
python
undefined

Set temperature and mode

设置温度和模式

climate_control( action="set_temperature", entity_id="climate.living_room", temperature=22, # Celsius hvac_mode="heat" # Options: heat, cool, auto, off, heat_cool )
climate_control( action="set_temperature", entity_id="climate.living_room", temperature=22, # 摄氏度 hvac_mode="heat" # 选项:heat、cool、auto、off、heat_cool )

Set fan mode

设置风扇模式

climate_control( action="set_fan_mode", entity_id="climate.bedroom", fan_mode="auto" # Options: auto, low, medium, high )
climate_control( action="set_fan_mode", entity_id="climate.bedroom", fan_mode="auto" # 选项:auto、low、medium、high )

Get current state

获取当前状态

climate_control(action="get", entity_id="climate.living_room")
undefined
climate_control(action="get", entity_id="climate.living_room")
undefined

Cover Control

窗帘控制

python
undefined
python
undefined

Set position

设置位置

cover_control( action="set_position", entity_id="cover.garage_door", position=50 # 0-100 (0=closed, 100=open) )
cover_control( action="set_position", entity_id="cover.garage_door", position=50 # 0-100(0=关闭,100=打开) )

Open/close

打开/关闭

cover_control(action="open", entity_id="cover.living_room_blinds") cover_control(action="close", entity_id="cover.bedroom_blinds")
cover_control(action="open", entity_id="cover.living_room_blinds") cover_control(action="close", entity_id="cover.bedroom_blinds")

Set tilt

设置倾斜角度

cover_control( action="set_tilt", entity_id="cover.venetian_blinds", tilt=45 )
undefined
cover_control( action="set_tilt", entity_id="cover.venetian_blinds", tilt=45 )
undefined

Lock Control

门锁控制

python
undefined
python
undefined

Lock/unlock

上锁/解锁

lock_control(action="lock", entity_id="lock.front_door") lock_control(action="unlock", entity_id="lock.back_door", code="1234")
lock_control(action="lock", entity_id="lock.front_door") lock_control(action="unlock", entity_id="lock.back_door", code="1234")

Get state

获取状态

lock_control(action="get", entity_id="lock.front_door")
undefined
lock_control(action="get", entity_id="lock.front_door")
undefined

Media Player Control

媒体播放器控制

python
undefined
python
undefined

Play/pause/stop

播放/暂停/停止

media_player_control(action="play", entity_id="media_player.living_room_tv") media_player_control(action="pause", entity_id="media_player.spotify")
media_player_control(action="play", entity_id="media_player.living_room_tv") media_player_control(action="pause", entity_id="media_player.spotify")

Volume control

音量控制

media_player_control( action="volume_set", entity_id="media_player.speakers", volume=0.5 # 0.0-1.0 )
media_player_control( action="volume_set", entity_id="media_player.speakers", volume=0.5 # 0.0-1.0 )

Select source

选择源

media_player_control( action="select_source", entity_id="media_player.receiver", source="HDMI 1" )
undefined
media_player_control( action="select_source", entity_id="media_player.receiver", source="HDMI 1" )
undefined

Vacuum Control

吸尘器控制

python
undefined
python
undefined

Start cleaning

开始清洁

vacuum_control(action="start", entity_id="vacuum.roborock")
vacuum_control(action="start", entity_id="vacuum.roborock")

Return to dock

返回基站

vacuum_control(action="dock", entity_id="vacuum.roborock")
vacuum_control(action="dock", entity_id="vacuum.roborock")

Set fan speed

设置风扇转速

vacuum_control( action="set_fan_speed", entity_id="vacuum.roborock", fan_speed="turbo" )
undefined
vacuum_control( action="set_fan_speed", entity_id="vacuum.roborock", fan_speed="turbo" )
undefined

State Management

状态管理

python
undefined
python
undefined

List all entities

列出所有实体

states_control(action="list")
states_control(action="list")

List entities by domain

按域列出实体

states_control(action="list", domain="light")
states_control(action="list", domain="light")

Get specific entity

获取特定实体

states_control(action="get", entity_id="sensor.temperature")
states_control(action="get", entity_id="sensor.temperature")

Set entity state

设置实体状态

states_control( action="set", entity_id="sensor.custom_sensor", state="active", attributes={"battery": 95} )
states_control( action="set", entity_id="sensor.custom_sensor", state="active", attributes={"battery": 95} )

Delete entity state

删除实体状态

states_control(action="delete", entity_id="sensor.old_sensor")
undefined
states_control(action="delete", entity_id="sensor.old_sensor")
undefined

Device Discovery

设备发现

python
undefined
python
undefined

List all devices

列出所有设备

list_devices()
list_devices()

Filter by domain

按域过滤

list_devices(domain="light")
list_devices(domain="light")

Filter by area

按区域过滤

list_devices(area="living_room")
list_devices(area="living_room")

Filter by floor

按楼层过滤

list_devices(floor="ground_floor")
list_devices(floor="ground_floor")

Combine filters

组合过滤

list_devices(domain="switch", area="bedroom")
undefined
list_devices(domain="switch", area="bedroom")
undefined

Service Calls

服务调用

python
undefined
python
undefined

Call any Home Assistant service directly

直接调用任意Home Assistant服务

call_service( domain="light", service="turn_on", service_data={ "entity_id": "light.bedroom", "brightness": 80, "rgb_color": [255, 120, 0] } )
call_service( domain="light", service="turn_on", service_data={ "entity_id": "light.bedroom", "brightness": 80, "rgb_color": [255, 120, 0] } )

Notify service

通知服务

call_service( domain="notify", service="mobile_app_phone", service_data={ "message": "Motion detected in garage", "title": "Security Alert" } )
call_service( domain="notify", service="mobile_app_phone", service_data={ "message": "车库检测到移动", "title": "安全警报" } )

TTS service

TTS服务

call_service( domain="tts", service="google_translate_say", service_data={ "entity_id": "media_player.kitchen_speaker", "message": "Dinner is ready" } )
undefined
call_service( domain="tts", service="google_translate_say", service_data={ "entity_id": "media_player.kitchen_speaker", "message": "晚餐准备好了" } )
undefined

Automation Control

自动化控制

python
undefined
python
undefined

List all automations

列出所有自动化

automation_control(action="list")
automation_control(action="list")

Trigger automation

触发自动化

automation_control(action="trigger", automation_id="automation.morning_routine")
automation_control(action="trigger", automation_id="automation.morning_routine")

Enable/disable

启用/禁用

automation_control(action="enable", automation_id="automation.night_mode") automation_control(action="disable", automation_id="automation.away_mode")
automation_control(action="enable", automation_id="automation.night_mode") automation_control(action="disable", automation_id="automation.away_mode")

Reload automations

重新加载自动化

automation_control(action="reload")
undefined
automation_control(action="reload")
undefined

Scene Control

场景控制

python
undefined
python
undefined

List scenes

列出场景

scene_control(action="list")
scene_control(action="list")

Activate scene

激活场景

scene_control(action="activate", scene_id="scene.movie_time")
undefined
scene_control(action="activate", scene_id="scene.movie_time")
undefined

Script Control

脚本控制

python
undefined
python
undefined

List scripts

列出脚本

script_control(action="list")
script_control(action="list")

Execute script with variables

使用变量执行脚本

script_control( action="execute", script_id="script.notification_routine", variables={"message": "Door left open", "priority": "high"} )
script_control( action="execute", script_id="script.notification_routine", variables={"message": "门未关闭", "priority": "high"} )

Reload scripts

重新加载脚本

script_control(action="reload")
undefined
script_control(action="reload")
undefined

Template Rendering

模板渲染

python
undefined
python
undefined

Render Jinja2 templates

渲染Jinja2模板

template_render( template="{{ states('sensor.temperature') | float + 5 }}" )
template_render( template="{{ states('sensor.temperature') | float + 5 }}" )

Complex template with entity states

包含实体状态的复杂模板

template_render( template=""" {% set lights = states.light | selectattr('state', 'eq', 'on') | list %} {{ lights | length }} lights are currently on """ )
undefined
template_render( template=""" {% set lights = states.light | selectattr('state', 'eq', 'on') | list %} {{ lights | length }} 盏灯当前处于开启状态 """ )
undefined

History & Logbook

历史记录与日志

python
undefined
python
undefined

Get entity history (last N hours)

获取实体历史记录(最近N小时)

history_query( entity_id="sensor.temperature", hours=24 )
history_query( entity_id="sensor.temperature", hours=24 )

Get logbook entries

获取日志条目

logbook_query( entity_id="binary_sensor.front_door", hours=12 )
logbook_query( entity_id="binary_sensor.front_door", hours=12 )

Get error log summary (parsed and deduplicated)

获取错误日志摘要(已解析并去重)

error_log_get()
undefined
error_log_get()
undefined

Calendar Access

日历访问

python
undefined
python
undefined

List all calendars

列出所有日历

calendar_access(action="list")
calendar_access(action="list")

Get events for date range

获取指定日期范围的事件

calendar_access( action="get_events", calendar_id="calendar.family", start_date="2024-05-01", end_date="2024-05-31" )
undefined
calendar_access( action="get_events", calendar_id="calendar.family", start_date="2024-05-01", end_date="2024-05-31" )
undefined

Camera Operations

摄像头操作

python
undefined
python
undefined

Get camera snapshot

获取摄像头快照

camera_proxy_get( entity_id="camera.front_door", width=640, height=480 )
camera_proxy_get( entity_id="camera.front_door", width=640, height=480 )

Enable motion detection

启用运动检测

camera_control( action="enable_motion_detection", entity_id="camera.garage" )
camera_control( action="enable_motion_detection", entity_id="camera.garage" )

Take snapshot

拍摄快照

camera_control( action="snapshot", entity_id="camera.backyard", filename="/config/www/snapshots/backyard.jpg" )
undefined
camera_control( action="snapshot", entity_id="camera.backyard", filename="/config/www/snapshots/backyard.jpg" )
undefined

MCP Resources

MCP资源

Resources provide read-only access to Home Assistant data via URIs.
资源通过URI提供对Home Assistant数据的只读访问。

Entity Resource

实体资源

python
undefined
python
undefined

Access entity state and attributes

访问实体状态和属性

URI: hass://entity/{entity_id}

URI: hass://entity/{entity_id}

hass://entity/light.living_room
hass://entity/light.living_room

Returns: {"state": "on", "attributes": {"brightness": 100, ...}}

返回结果: {"state": "on", "attributes": {"brightness": 100, ...}}

undefined
undefined

Area Resource

区域资源

python
undefined
python
undefined

Get all entities in an area (compact summaries)

获取某区域内的所有实体(精简摘要)

URI: hass://area/{area_id}

URI: hass://area/{area_id}

hass://area/living_room
hass://area/living_room

Returns: List of entities with state and key attributes

返回结果: 包含状态和关键属性的实体列表

undefined
undefined

Device Resource

设备资源

python
undefined
python
undefined

Get all entities for a device (compact summaries)

获取某设备的所有实体(精简摘要)

URI: hass://device/{device_id}

URI: hass://device/{device_id}

hass://device/abc123def456
hass://device/abc123def456

Returns: Device entities with states

返回结果: 包含状态的设备实体列表

undefined
undefined

Services Resource

服务资源

python
undefined
python
undefined

Get all available services organized by domain

获取按域组织的所有可用服务

URI: hass://services

URI: hass://services

hass://services
hass://services

Returns: All service definitions with parameters

返回结果: 包含参数的所有服务定义

undefined
undefined

Entity History Resource

实体历史资源

python
undefined
python
undefined

Get entity history with pagination

获取带分页的实体历史记录

URI: hass://entity/{entity_id}/history?hours=24&limit=100

URI: hass://entity/{entity_id}/history?hours=24&limit=100

hass://entity/sensor.temperature/history?hours=24
hass://entity/sensor.temperature/history?hours=24

Returns: Paginated history with state changes

返回结果: 带状态变化的分页历史记录

undefined
undefined

Common Patterns

常见模式

Morning Routine Automation

晨间例行自动化

python
undefined
python
undefined

1. Discover automation tools

1. 发现自动化工具

tools = discover_tools()
tools = discover_tools()

2. Create morning scene

2. 激活晨间场景

scene_control(action="activate", scene_id="scene.morning")
scene_control(action="activate", scene_id="scene.morning")

3. Set climate

3. 设置气候

climate_control( action="set_temperature", entity_id="climate.bedroom", temperature=21, hvac_mode="heat" )
climate_control( action="set_temperature", entity_id="climate.bedroom", temperature=21, hvac_mode="heat" )

4. Open blinds

4. 打开窗帘

cover_control(action="open", entity_id="cover.bedroom_blinds")
cover_control(action="open", entity_id="cover.bedroom_blinds")

5. Turn on lights gradually

5. 逐步开启灯光

lights_control( action="turn_on", entity_id="light.bedroom", brightness=30, transition=60 # Seconds )
undefined
lights_control( action="turn_on", entity_id="light.bedroom", brightness=30, transition=60 # 秒 )
undefined

Security Check Routine

安全检查例行程序

python
undefined
python
undefined

Check all locks

检查所有门锁

locks = list_devices(domain="lock") for lock in locks: state = lock_control(action="get", entity_id=lock["entity_id"]) if state["state"] == "unlocked": send_notification( message=f"{lock['name']} is unlocked!", title="Security Alert" )
locks = list_devices(domain="lock") for lock in locks: state = lock_control(action="get", entity_id=lock["entity_id"]) if state["state"] == "unlocked": send_notification( message=f"{lock['name']} 未上锁!", title="安全警报" )

Check door sensors

检查门传感器

doors = list_devices(domain="binary_sensor", area="entry") for door in doors: if "door" in door["entity_id"]: state = states_control(action="get", entity_id=door["entity_id"]) # Process door states
undefined
doors = list_devices(domain="binary_sensor", area="entry") for door in doors: if "door" in door["entity_id"]: state = states_control(action="get", entity_id=door["entity_id"]) # 处理门状态
undefined

Energy Optimization

能耗优化

python
undefined
python
undefined

Turn off unused devices

关闭未使用的设备

lights = states_control(action="list", domain="light") for light in lights: if light["state"] == "on": # Check if anyone home using presence sensors presence = states_control(action="get", entity_id="binary_sensor.occupancy") if presence["state"] == "off": lights_control(action="turn_off", entity_id=light["entity_id"])
lights = states_control(action="list", domain="light") for light in lights: if light["state"] == "on": # 使用存在传感器检查是否有人在家 presence = states_control(action="get", entity_id="binary_sensor.occupancy") if presence["state"] == "off": lights_control(action="turn_off", entity_id=light["entity_id"])

Optimize climate

优化气候控制

climate_control( action="set_temperature", entity_id="climate.all", temperature=19, # Lower when away hvac_mode="heat" )
undefined
climate_control( action="set_temperature", entity_id="climate.all", temperature=19, # 外出时调低温度 hvac_mode="heat" )
undefined

Media Room Scene

影音室场景

python
undefined
python
undefined

Dim lights

调暗灯光

lights_control( action="turn_on", entity_id="light.media_room", brightness=10, rgb_color=[255, 100, 0] )
lights_control( action="turn_on", entity_id="light.media_room", brightness=10, rgb_color=[255, 100, 0] )

Close blinds

关闭窗帘

cover_control(action="close", entity_id="cover.media_room_blinds")
cover_control(action="close", entity_id="cover.media_room_blinds")

Start media player

启动媒体播放器

media_player_control( action="select_source", entity_id="media_player.tv", source="Netflix" ) media_player_control(action="play", entity_id="media_player.tv")
undefined
media_player_control( action="select_source", entity_id="media_player.tv", source="Netflix" ) media_player_control(action="play", entity_id="media_player.tv")
undefined

Conditional Device Control

条件设备控制

python
undefined
python
undefined

Only turn on if temperature is low

仅在温度较低时开启

temp_state = states_control(action="get", entity_id="sensor.temperature") current_temp = float(temp_state["state"])
if current_temp < 18: climate_control( action="set_temperature", entity_id="climate.living_room", temperature=22, hvac_mode="heat" )
emp_state = states_control(action="get", entity_id="sensor.temperature") current_temp = float(temp_state["state"])
if current_temp < 18: climate_control( action="set_temperature", entity_id="climate.living_room", temperature=22, hvac_mode="heat" )

Turn on lights only if dark

仅在光线昏暗时开启灯光

lux_state = states_control(action="get", entity_id="sensor.illuminance") if float(lux_state["state"]) < 50: lights_control(action="turn_on", entity_id="light.all_lights")
undefined
lux_state = states_control(action="get", entity_id="sensor.illuminance") if float(lux_state["state"]) < 50: lights_control(action="turn_on", entity_id="light.all_lights")
undefined

Development

开发

Running Tests

运行测试

bash
undefined
bash
undefined

Install dev dependencies

安装开发依赖

pip install -e ".[dev]"
pip install -e ".[dev]"

Run tests

运行测试

pytest
pytest

Run with coverage

带覆盖率运行测试

pytest --cov=src --cov-report=html
undefined
pytest --cov=src --cov-report=html
undefined

Code Quality

代码质量

bash
undefined
bash
undefined

Format code

格式化代码

black src/ tests/
black src/ tests/

Lint

代码检查

ruff check src/ tests/
ruff check src/ tests/

Type checking

类型检查

mypy src/
undefined
mypy src/
undefined

Local Development

本地开发

bash
undefined
bash
undefined

Clone and setup

克隆并设置环境

git clone https://github.com/robbrad/homeassistant-mcp.git cd homeassistant-mcp python -m venv venv source venv/bin/activate pip install -e ".[dev]"
git clone https://github.com/robbrad/homeassistant-mcp.git cd homeassistant-mcp python -m venv venv source venv/bin/activate pip install -e ".[dev]"

Create .env file

创建.env文件

cat > .env << EOF HASS_HOST=http://homeassistant.local:8123 HASS_TOKEN=your_token_here LOG_LEVEL=DEBUG EOF
cat > .env << EOF HASS_HOST=http://homeassistant.local:8123 HASS_TOKEN=your_token_here LOG_LEVEL=DEBUG EOF

Run server

运行服务器

homeassistant-mcp
undefined
homeassistant-mcp
undefined

Adding New Tools

添加新工具

python
from fastmcp import FastMCP

mcp = FastMCP("homeassistant")

@mcp.tool(
    description="Control custom device",
    tags=["device", "custom"],
    timeout=30.0
)
async def custom_device_control(
    action: str,
    entity_id: str,
    value: int = 0
) -> dict:
    """
    Control custom device
    
    Args:
        action: Action to perform (on, off, set)
        entity_id: Entity ID
        value: Optional value parameter
    """
    client = get_hass_client()
    return await client.call_service(
        domain="custom_domain",
        service=action,
        service_data={"entity_id": entity_id, "value": value}
    )
python
from fastmcp import FastMCP

mcp = FastMCP("homeassistant")

@mcp.tool(
    description="Control custom device",
    tags=["device", "custom"],
    timeout=30.0
)
async def custom_device_control(
    action: str,
    entity_id: str,
    value: int = 0
) -> dict:
    """
    Control custom device
    
    Args:
        action: Action to perform (on, off, set)
        entity_id: Entity ID
        value: Optional value parameter
    """
    client = get_hass_client()
    return await client.call_service(
        domain="custom_domain",
        service=action,
        service_data={"entity_id": entity_id, "value": value}
    )

Troubleshooting

故障排除

Connection Issues

连接问题

python
undefined
python
undefined

Check API info

检查API信息

api_info()
api_info()

Returns HA version, loaded components, and connection status

返回HA版本、已加载组件和连接状态

Verify host and token

验证主机和令牌

Ensure HASS_HOST includes protocol (http:// or https://)

确保HASS_HOST包含协议(http://或https://)

Verify token has not expired

验证令牌未过期

undefined
undefined

Entity Not Found

实体未找到

python
undefined
python
undefined

List all entities to find correct entity_id

列出所有实体以找到正确的entity_id

all_entities = states_control(action="list")
all_entities = states_control(action="list")

Search by domain

按域搜索

lights = states_control(action="list", domain="light")
lights = states_control(action="list", domain="light")

List devices in area

列出某区域内的设备

devices = list_devices(area="bedroom")
undefined
devices = list_devices(area="bedroom")
undefined

Service Call Failures

服务调用失败

python
undefined
python
undefined

List available services

列出可用服务

services = services_control(action="list", domain="light")
services = services_control(action="list", domain="light")

Check service schema

检查服务schema

schema = services_control(action="get", domain="light", service="turn_on")
schema = services_control(action="get", domain="light", service="turn_on")

Validate configuration

验证配置

config_check()
undefined
config_check()
undefined

Tool Not Available

工具不可用

python
undefined
python
undefined

Discover all tools

发现所有工具

all_tools = discover_tools()
all_tools = discover_tools()

Search for specific functionality

搜索特定功能

matching_tools = search_tools(query="your search query")
matching_tools = search_tools(query="your search query")

Call tool by name if not directly available

如果无法直接调用,通过名称调用工具

call_tool(tool_name="tool_name", arguments={...})
undefined
call_tool(tool_name="tool_name", arguments={...})
undefined

Cache Issues

缓存问题

bash
undefined
bash
undefined

Adjust cache TTL for more frequent updates

调整缓存TTL以更频繁地更新

export CACHE_TTL_STATES=5 # 5 seconds instead of default 30 export CACHE_TTL_ENTITY=2 # 2 seconds instead of default 10
export CACHE_TTL_STATES=5 # 替换默认30秒为5秒 export CACHE_TTL_ENTITY=2 # 替换默认10秒为2秒

Enable debug logging to see cache hits/misses

启用调试日志查看缓存命中/未命中情况

export LOG_LEVEL=DEBUG
undefined
export LOG_LEVEL=DEBUG
undefined

Error Log Analysis

错误日志分析

python
undefined
python
undefined

Get parsed error log with deduplication

获取已解析并去重的错误日志

errors = error_log_get()
errors = error_log_get()

Returns: Deduplicated errors with component counts and timestamps

返回结果:带组件计数和时间戳的去重错误信息

undefined
undefined

Authentication Errors

认证错误

  • Verify
    HASS_TOKEN
    is a long-lived access token (not temporary)
  • Create new token: HA Profile → Long-Lived Access Tokens → Create Token
  • Check token has required permissions for device domains
  • 验证
    HASS_TOKEN
    是长期访问令牌(而非临时令牌)
  • 创建新令牌:HA个人资料 → 长期访问令牌 → 创建令牌
  • 检查令牌是否拥有设备域的必要权限

Rate Limiting

速率限制

The server uses TTL-based caching to reduce API load:
  • Bulk state queries cached for 30s (configurable via
    CACHE_TTL_STATES
    )
  • Individual entity queries cached for 10s (configurable via
    CACHE_TTL_ENTITY
    )
  • Adjust cache TTLs based on your update frequency needs
服务器使用基于TTL的缓存来减少API负载:
  • 批量状态查询缓存30秒(可通过
    CACHE_TTL_STATES
    配置)
  • 单个实体查询缓存10秒(可通过
    CACHE_TTL_ENTITY
    配置)
  • 根据你的更新频率需求调整缓存TTL