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

76 lines
3.0 KiB
C#

using System.ComponentModel;
using System.Text.Json;
using HomeAssistant.McpServer.Services;
using ModelContextProtocol.Server;
namespace HomeAssistant.McpServer.Tools;
[McpServerToolType]
public sealed class ServiceTools
{
private readonly IHomeAssistantApiClient _client;
public ServiceTools(IHomeAssistantApiClient client)
{
_client = client;
}
[McpServerTool, Description(
"List available Home Assistant services. Optionally filter by domain (e.g. 'light', 'climate', 'switch'). " +
"Each service shows its domain and available service names.")]
public async Task<string> ListServices(
[Description("Optional domain filter, e.g. 'light', 'climate'. Leave empty for all.")] string? domain = null,
CancellationToken cancellationToken = default)
{
var allServices = await _client.GetServicesAsync(cancellationToken).ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(domain))
return FormatJson(allServices);
var filtered = allServices.EnumerateArray()
.Where(s => s.TryGetProperty("domain", out var d) &&
string.Equals(d.GetString(), domain, StringComparison.OrdinalIgnoreCase))
.ToList();
return JsonSerializer.Serialize(filtered, SerializerOptions);
}
[McpServerTool, Description(
"Call a Home Assistant service. Examples: domain='light', service='turn_on', entityId='light.living_room'. " +
"For services requiring extra data, pass it as a JSON string in serviceData.")]
public async Task<string> CallService(
[Description("Service domain, e.g. 'light', 'climate', 'switch', 'input_boolean'")] string domain,
[Description("Service name, e.g. 'turn_on', 'turn_off', 'set_temperature'")] string service,
[Description("Optional target entity ID, e.g. 'light.living_room'")] string? entityId = null,
[Description("Optional JSON service data, e.g. '{\"brightness\": 255}' or '{\"temperature\": 22}'")] string? serviceData = null,
CancellationToken cancellationToken = default)
{
JsonElement? data = null;
if (!string.IsNullOrWhiteSpace(serviceData) || !string.IsNullOrWhiteSpace(entityId))
{
var dataDict = string.IsNullOrWhiteSpace(serviceData)
? new Dictionary<string, object>()
: JsonSerializer.Deserialize<Dictionary<string, object>>(serviceData) ?? [];
if (!string.IsNullOrWhiteSpace(entityId))
dataDict["entity_id"] = entityId;
data = JsonSerializer.SerializeToElement(dataDict);
}
var result = await _client.CallServiceAsync(domain, service, data, cancellationToken)
.ConfigureAwait(false);
return FormatJson(result);
}
private static string FormatJson(JsonElement element) =>
JsonSerializer.Serialize(element, SerializerOptions);
private static readonly JsonSerializerOptions SerializerOptions = new()
{
WriteIndented = true
};
}