homeassistant-mcp-server
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseHome Assistant MCP Server
Home Assistant MCP Server
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-mcpRun with:
bash
export HASS_HOST="http://homeassistant.local:8123"
export HASS_TOKEN="your_token_here"
homeassistant-mcpbash
pip install homeassistant-mcp运行命令:
bash
export HASS_HOST="http://homeassistant.local:8123"
export HASS_TOKEN="your_token_here"
homeassistant-mcpFrom 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-mcpbash
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-mcpConfiguration
配置
Required Environment Variables
必填环境变量
| Variable | Description | Example |
|---|---|---|
| Home Assistant URL | |
| Long-lived access token | Generate from HA profile page |
| 变量 | 描述 | 示例 |
|---|---|---|
| Home Assistant的URL | |
| 长期访问令牌 | 从HA个人资料页面生成 |
Optional Environment Variables
可选环境变量
| Variable | Default | Description |
|---|---|---|
| | Cache TTL for bulk state queries (seconds) |
| | Cache TTL for individual entity queries (seconds) |
| | Logging level (DEBUG, INFO, WARNING, ERROR) |
| 变量 | 默认值 | 描述 |
|---|---|---|
| | 批量状态查询的缓存TTL(秒) |
| | 单个实体查询的缓存TTL(秒) |
| | 日志级别(DEBUG、INFO、WARNING、ERROR) |
Claude Desktop Configuration
Claude桌面端配置
macOS:
Windows:
~/Library/Application Support/Claude/claude_desktop_config.jsonWindows:
%APPDATA%\Claude\claude_desktop_config.jsonjson
{
"mcpServers": {
"homeassistant": {
"command": "uvx",
"args": ["homeassistant-mcp"],
"env": {
"HASS_HOST": "http://homeassistant.local:8123",
"HASS_TOKEN": "eyJ0eXAiOiJKV1QiLCJhbGc..."
}
}
}
}macOS:
Windows:
~/Library/Application Support/Claude/claude_desktop_config.jsonWindows:
%APPDATA%\Claude\claude_desktop_config.jsonjson
{
"mcpServers": {
"homeassistant": {
"command": "uvx",
"args": ["homeassistant-mcp"],
"env": {
"HASS_HOST": "http://homeassistant.local:8123",
"HASS_TOKEN": "eyJ0eXAiOiJKV1QiLCJhbGc..."
}
}
}
}Cursor Configuration
Cursor配置
.cursor/mcp.jsonjson
{
"mcpServers": {
"homeassistant": {
"command": "uvx",
"args": ["homeassistant-mcp"],
"env": {
"HASS_HOST": "${HASS_HOST}",
"HASS_TOKEN": "${HASS_TOKEN}"
}
}
}
}.cursor/mcp.jsonjson
{
"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
undefinedpython
undefined1. 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
使用给定参数执行指定工具
undefinedundefinedExample Tool Discovery Flow
工具发现流程示例
python
undefinedpython
undefinedStep 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
)
undefinedlights_control(
action="turn_on",
entity_id="light.living_room",
brightness=80,
color_temp=370
)
undefinedKey Tools by Category
按类别划分的核心工具
Device Control Tools (16 total)
设备控制工具(共16种)
Light Control
灯光控制
python
undefinedpython
undefinedTurn 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
)
undefinedlights_control(
action="turn_on",
entity_id="light.all_lights",
brightness=50
)
undefinedClimate Control
气候控制
python
undefinedpython
undefinedSet 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")
undefinedclimate_control(action="get", entity_id="climate.living_room")
undefinedCover Control
窗帘控制
python
undefinedpython
undefinedSet 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
)
undefinedcover_control(
action="set_tilt",
entity_id="cover.venetian_blinds",
tilt=45
)
undefinedLock Control
门锁控制
python
undefinedpython
undefinedLock/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")
undefinedlock_control(action="get", entity_id="lock.front_door")
undefinedMedia Player Control
媒体播放器控制
python
undefinedpython
undefinedPlay/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"
)
undefinedmedia_player_control(
action="select_source",
entity_id="media_player.receiver",
source="HDMI 1"
)
undefinedVacuum Control
吸尘器控制
python
undefinedpython
undefinedStart 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"
)
undefinedvacuum_control(
action="set_fan_speed",
entity_id="vacuum.roborock",
fan_speed="turbo"
)
undefinedState Management
状态管理
python
undefinedpython
undefinedList 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")
undefinedstates_control(action="delete", entity_id="sensor.old_sensor")
undefinedDevice Discovery
设备发现
python
undefinedpython
undefinedList 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")
undefinedlist_devices(domain="switch", area="bedroom")
undefinedService Calls
服务调用
python
undefinedpython
undefinedCall 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"
}
)
undefinedcall_service(
domain="tts",
service="google_translate_say",
service_data={
"entity_id": "media_player.kitchen_speaker",
"message": "晚餐准备好了"
}
)
undefinedAutomation Control
自动化控制
python
undefinedpython
undefinedList 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")
undefinedautomation_control(action="reload")
undefinedScene Control
场景控制
python
undefinedpython
undefinedList scenes
列出场景
scene_control(action="list")
scene_control(action="list")
Activate scene
激活场景
scene_control(action="activate", scene_id="scene.movie_time")
undefinedscene_control(action="activate", scene_id="scene.movie_time")
undefinedScript Control
脚本控制
python
undefinedpython
undefinedList 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")
undefinedscript_control(action="reload")
undefinedTemplate Rendering
模板渲染
python
undefinedpython
undefinedRender 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
"""
)
undefinedtemplate_render(
template="""
{% set lights = states.light | selectattr('state', 'eq', 'on') | list %}
{{ lights | length }} 盏灯当前处于开启状态
"""
)
undefinedHistory & Logbook
历史记录与日志
python
undefinedpython
undefinedGet 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()
undefinederror_log_get()
undefinedCalendar Access
日历访问
python
undefinedpython
undefinedList 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"
)
undefinedcalendar_access(
action="get_events",
calendar_id="calendar.family",
start_date="2024-05-01",
end_date="2024-05-31"
)
undefinedCamera Operations
摄像头操作
python
undefinedpython
undefinedGet 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"
)
undefinedcamera_control(
action="snapshot",
entity_id="camera.backyard",
filename="/config/www/snapshots/backyard.jpg"
)
undefinedMCP Resources
MCP资源
Resources provide read-only access to Home Assistant data via URIs.
资源通过URI提供对Home Assistant数据的只读访问。
Entity Resource
实体资源
python
undefinedpython
undefinedAccess 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, ...}}
undefinedundefinedArea Resource
区域资源
python
undefinedpython
undefinedGet 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
返回结果: 包含状态和关键属性的实体列表
undefinedundefinedDevice Resource
设备资源
python
undefinedpython
undefinedGet 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
返回结果: 包含状态的设备实体列表
undefinedundefinedServices Resource
服务资源
python
undefinedpython
undefinedGet all available services organized by domain
获取按域组织的所有可用服务
URI: hass://services
URI: hass://services
hass://services
hass://services
Returns: All service definitions with parameters
返回结果: 包含参数的所有服务定义
undefinedundefinedEntity History Resource
实体历史资源
python
undefinedpython
undefinedGet 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
返回结果: 带状态变化的分页历史记录
undefinedundefinedCommon Patterns
常见模式
Morning Routine Automation
晨间例行自动化
python
undefinedpython
undefined1. 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
)
undefinedlights_control(
action="turn_on",
entity_id="light.bedroom",
brightness=30,
transition=60 # 秒
)
undefinedSecurity Check Routine
安全检查例行程序
python
undefinedpython
undefinedCheck 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
undefineddoors = 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"])
# 处理门状态
undefinedEnergy Optimization
能耗优化
python
undefinedpython
undefinedTurn 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"
)
undefinedclimate_control(
action="set_temperature",
entity_id="climate.all",
temperature=19, # 外出时调低温度
hvac_mode="heat"
)
undefinedMedia Room Scene
影音室场景
python
undefinedpython
undefinedDim 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")
undefinedmedia_player_control(
action="select_source",
entity_id="media_player.tv",
source="Netflix"
)
media_player_control(action="play", entity_id="media_player.tv")
undefinedConditional Device Control
条件设备控制
python
undefinedpython
undefinedOnly 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")
undefinedlux_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")
undefinedDevelopment
开发
Running Tests
运行测试
bash
undefinedbash
undefinedInstall dev dependencies
安装开发依赖
pip install -e ".[dev]"
pip install -e ".[dev]"
Run tests
运行测试
pytest
pytest
Run with coverage
带覆盖率运行测试
pytest --cov=src --cov-report=html
undefinedpytest --cov=src --cov-report=html
undefinedCode Quality
代码质量
bash
undefinedbash
undefinedFormat code
格式化代码
black src/ tests/
black src/ tests/
Lint
代码检查
ruff check src/ tests/
ruff check src/ tests/
Type checking
类型检查
mypy src/
undefinedmypy src/
undefinedLocal Development
本地开发
bash
undefinedbash
undefinedClone 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
undefinedhomeassistant-mcp
undefinedAdding 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
undefinedpython
undefinedCheck 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
验证令牌未过期
undefinedundefinedEntity Not Found
实体未找到
python
undefinedpython
undefinedList 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")
undefineddevices = list_devices(area="bedroom")
undefinedService Call Failures
服务调用失败
python
undefinedpython
undefinedList 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()
undefinedconfig_check()
undefinedTool Not Available
工具不可用
python
undefinedpython
undefinedDiscover 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={...})
undefinedcall_tool(tool_name="tool_name", arguments={...})
undefinedCache Issues
缓存问题
bash
undefinedbash
undefinedAdjust 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
undefinedexport LOG_LEVEL=DEBUG
undefinedError Log Analysis
错误日志分析
python
undefinedpython
undefinedGet parsed error log with deduplication
获取已解析并去重的错误日志
errors = error_log_get()
errors = error_log_get()
Returns: Deduplicated errors with component counts and timestamps
返回结果:带组件计数和时间戳的去重错误信息
undefinedundefinedAuthentication Errors
认证错误
- Verify is a long-lived access token (not temporary)
HASS_TOKEN - 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