Files
HomeAssistant/HomeAssistant.McpServer/Tools/EntityStateTools.cs
T

99 lines
3.8 KiB
C#

using System.ComponentModel;
using System.Text.Json;
using HomeAssistant.McpServer.Services;
using ModelContextProtocol.Server;
namespace HomeAssistant.McpServer.Tools;
[McpServerToolType]
public sealed class EntityStateTools
{
private readonly IHomeAssistantApiClient _client;
public EntityStateTools(IHomeAssistantApiClient client)
{
_client = client;
}
[McpServerTool, Description(
"Get the current state and attributes of a single Home Assistant entity. " +
"Provide the full entity_id, e.g. 'sensor.nordpool_kwh_lt_eur_3_10_0' or 'switch.boiler'.")]
public async Task<string> GetEntityState(
[Description("Full entity ID, e.g. 'sensor.temperature' or 'light.living_room'")] string entityId,
CancellationToken cancellationToken = default)
{
var result = await _client.GetEntityStateAsync(entityId, cancellationToken).ConfigureAwait(false);
return FormatJson(result);
}
[McpServerTool, Description(
"Get the current states of all Home Assistant entities. " +
"Optionally filter by domain (e.g. 'sensor', 'switch', 'climate', 'light'). " +
"Returns entity_id, state, and key attributes for each entity.")]
public async Task<string> GetAllStates(
[Description("Optional domain filter, e.g. 'sensor', 'switch', 'climate'. Leave empty for all.")] string? domain = null,
CancellationToken cancellationToken = default)
{
var allStates = await _client.GetAllStatesAsync(cancellationToken).ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(domain))
return FormatJson(allStates);
var filtered = allStates.EnumerateArray()
.Where(e => e.TryGetProperty("entity_id", out var eid) &&
eid.GetString()?.StartsWith(domain + ".", StringComparison.OrdinalIgnoreCase) == true)
.ToList();
return JsonSerializer.Serialize(filtered, SerializerOptions);
}
[McpServerTool, Description(
"Search Home Assistant entities by partial match on entity_id or friendly_name. " +
"Useful for discovering entities related to a topic (e.g. 'nordpool', 'boiler', 'temperature').")]
public async Task<string> SearchEntities(
[Description("Search term to match against entity_id or friendly_name")] string query,
CancellationToken cancellationToken = default)
{
var allStates = await _client.GetAllStatesAsync(cancellationToken).ConfigureAwait(false);
var matches = allStates.EnumerateArray()
.Where(e => MatchesQuery(e, query))
.Select(e => new
{
entity_id = e.GetProperty("entity_id").GetString(),
state = e.GetProperty("state").GetString(),
friendly_name = e.TryGetProperty("attributes", out var attrs) &&
attrs.TryGetProperty("friendly_name", out var fn)
? fn.GetString()
: null
})
.ToList();
return JsonSerializer.Serialize(matches, SerializerOptions);
}
private static bool MatchesQuery(JsonElement entity, string query)
{
var q = query.ToUpperInvariant();
if (entity.TryGetProperty("entity_id", out var eid) &&
(eid.GetString()?.ToUpperInvariant().Contains(q) ?? false))
return true;
if (entity.TryGetProperty("attributes", out var attrs) &&
attrs.TryGetProperty("friendly_name", out var fn) &&
(fn.GetString()?.ToUpperInvariant().Contains(q) ?? false))
return true;
return false;
}
private static string FormatJson(JsonElement element) =>
JsonSerializer.Serialize(element, SerializerOptions);
private static readonly JsonSerializerOptions SerializerOptions = new()
{
WriteIndented = true
};
}