311 lines
12 KiB
C#
311 lines
12 KiB
C#
using System.Collections.Concurrent;
|
|
using System.ComponentModel;
|
|
using System.Text.Json;
|
|
using HomeAssistant.McpServer.Services;
|
|
using ModelContextProtocol.Server;
|
|
|
|
namespace HomeAssistant.McpServer.Tools;
|
|
|
|
[McpServerToolType]
|
|
public sealed class ValidationTools
|
|
{
|
|
private const string UnavailableState = "unavailable";
|
|
private const string UnknownState = "unknown";
|
|
private const int DefaultLogbookWindowMinutes = 30;
|
|
private const int MaxDegreeOfParallelism = 4;
|
|
|
|
private static readonly string[] CriticalDomains = ["sensor", "switch", "binary_sensor", "light"];
|
|
|
|
private static readonly JsonSerializerOptions SerializerOptions = new()
|
|
{
|
|
WriteIndented = true
|
|
};
|
|
|
|
private readonly IHomeAssistantApiClient _client;
|
|
|
|
public ValidationTools(IHomeAssistantApiClient client)
|
|
{
|
|
_client = client;
|
|
}
|
|
|
|
[McpServerTool, Description(
|
|
"Run a smoke test against the live Home Assistant environment. " +
|
|
"Checks API health, validates that critical entities are not unavailable/unknown, " +
|
|
"and verifies recent logbook activity for specified domains. " +
|
|
"Returns a structured pass/fail report.")]
|
|
public async Task<string> RunSmokeTest(
|
|
[Description(
|
|
"Comma-separated domains to check, e.g. 'switch,sensor,light'. " +
|
|
"Leave empty to check all critical domains (sensor, switch, binary_sensor, light).")]
|
|
string? domains = null,
|
|
[Description(
|
|
"Minutes of logbook history to scan for activity. Defaults to 30.")]
|
|
int? logbookWindowMinutes = null,
|
|
CancellationToken cancellationToken = default)
|
|
{
|
|
var targetDomains = ParseDomains(domains);
|
|
var windowMinutes = logbookWindowMinutes ?? DefaultLogbookWindowMinutes;
|
|
|
|
var apiHealthTask = CheckApiHealthAsync(cancellationToken);
|
|
var entityCheckTask = CheckEntitiesAsync(targetDomains, cancellationToken);
|
|
var logbookCheckTask = CheckRecentActivityAsync(windowMinutes, cancellationToken);
|
|
|
|
await Task.WhenAll(apiHealthTask, entityCheckTask, logbookCheckTask).ConfigureAwait(false);
|
|
|
|
var report = new
|
|
{
|
|
timestamp = DateTimeOffset.UtcNow,
|
|
apiHealth = await apiHealthTask.ConfigureAwait(false),
|
|
entityCheck = await entityCheckTask.ConfigureAwait(false),
|
|
recentActivity = await logbookCheckTask.ConfigureAwait(false),
|
|
overall = DetermineOverallStatus(
|
|
await apiHealthTask.ConfigureAwait(false),
|
|
await entityCheckTask.ConfigureAwait(false))
|
|
};
|
|
|
|
return JsonSerializer.Serialize(report, SerializerOptions);
|
|
}
|
|
|
|
[McpServerTool, Description(
|
|
"Assert that a specific Home Assistant entity has an expected state value. " +
|
|
"Returns a pass/fail result with the actual vs expected values and entity attributes.")]
|
|
public async Task<string> AssertEntityState(
|
|
[Description("Full entity ID, e.g. 'switch.boiler' or 'sensor.nordpool_current_price'")] string entityId,
|
|
[Description("Expected state value, e.g. 'on', 'off', '22.5'")] string expectedState,
|
|
CancellationToken cancellationToken = default)
|
|
{
|
|
var entity = await _client.GetEntityStateAsync(entityId, cancellationToken).ConfigureAwait(false);
|
|
|
|
var actualState = entity.TryGetProperty("state", out var stateProp)
|
|
? stateProp.GetString() ?? string.Empty
|
|
: string.Empty;
|
|
|
|
var passed = string.Equals(actualState, expectedState, StringComparison.OrdinalIgnoreCase);
|
|
|
|
var result = new
|
|
{
|
|
entityId,
|
|
expectedState,
|
|
actualState,
|
|
passed,
|
|
lastChanged = entity.TryGetProperty("last_changed", out var lc) ? lc.GetString() : null,
|
|
lastUpdated = entity.TryGetProperty("last_updated", out var lu) ? lu.GetString() : null
|
|
};
|
|
|
|
return JsonSerializer.Serialize(result, SerializerOptions);
|
|
}
|
|
|
|
[McpServerTool, Description(
|
|
"Validate multiple Home Assistant entities in parallel. " +
|
|
"Checks that each entity exists, is reachable, and is not in unavailable/unknown state. " +
|
|
"Optionally assert expected state values.")]
|
|
public async Task<string> ValidateEntities(
|
|
[Description(
|
|
"Comma-separated entity IDs to validate, e.g. 'switch.boiler,sensor.nordpool_current_price'")]
|
|
string entityIds,
|
|
[Description(
|
|
"Optional comma-separated expected states matching the entity IDs order. " +
|
|
"Use empty string to skip assertion for an entity, e.g. 'on,,42.5'")]
|
|
string? expectedStates = null,
|
|
CancellationToken cancellationToken = default)
|
|
{
|
|
var ids = entityIds.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
|
var states = expectedStates?.Split(',') ?? [];
|
|
|
|
var results = new ConcurrentBag<object>();
|
|
var parallelOptions = new ParallelOptions
|
|
{
|
|
MaxDegreeOfParallelism = MaxDegreeOfParallelism,
|
|
CancellationToken = cancellationToken
|
|
};
|
|
|
|
await Parallel.ForEachAsync(
|
|
ids.Select((id, index) => (id, index)),
|
|
parallelOptions,
|
|
async (item, ct) =>
|
|
{
|
|
var expectedState = item.index < states.Length
|
|
? states[item.index]?.Trim()
|
|
: null;
|
|
|
|
var result = await ValidateSingleEntityAsync(item.id, expectedState, ct).ConfigureAwait(false);
|
|
results.Add(result);
|
|
}).ConfigureAwait(false);
|
|
|
|
var ordered = results.Cast<dynamic>()
|
|
.OrderBy(r => (string)r.entityId)
|
|
.ToList();
|
|
|
|
var allPassed = ordered.All(r => (bool)r.passed);
|
|
|
|
var report = new
|
|
{
|
|
timestamp = DateTimeOffset.UtcNow,
|
|
passed = allPassed,
|
|
total = ordered.Count,
|
|
failed = ordered.Count(r => !(bool)r.passed),
|
|
entities = ordered
|
|
};
|
|
|
|
return JsonSerializer.Serialize(report, SerializerOptions);
|
|
}
|
|
|
|
private static string[] ParseDomains(string? domains) =>
|
|
string.IsNullOrWhiteSpace(domains)
|
|
? CriticalDomains
|
|
: domains.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
|
|
|
private async Task<object> CheckApiHealthAsync(CancellationToken cancellationToken)
|
|
{
|
|
try
|
|
{
|
|
var status = await _client.GetApiStatusAsync(cancellationToken).ConfigureAwait(false);
|
|
var message = status.TryGetProperty("message", out var msg) ? msg.GetString() : "unknown";
|
|
return new { status = "healthy", message };
|
|
}
|
|
catch (HttpRequestException ex)
|
|
{
|
|
return new { status = "unreachable", message = ex.Message };
|
|
}
|
|
catch (TaskCanceledException)
|
|
{
|
|
return new { status = "timeout", message = "Home Assistant API did not respond in time" };
|
|
}
|
|
}
|
|
|
|
private async Task<object> CheckEntitiesAsync(string[] targetDomains, CancellationToken cancellationToken)
|
|
{
|
|
var allStates = await _client.GetAllStatesAsync(cancellationToken).ConfigureAwait(false);
|
|
var domainSet = new HashSet<string>(targetDomains, StringComparer.OrdinalIgnoreCase);
|
|
|
|
var unhealthy = new ConcurrentBag<object>();
|
|
var totalChecked = 0;
|
|
|
|
foreach (var entity in allStates.EnumerateArray())
|
|
{
|
|
if (!entity.TryGetProperty("entity_id", out var eidProp))
|
|
continue;
|
|
|
|
var entityId = eidProp.GetString() ?? string.Empty;
|
|
var entityDomain = entityId.Split('.').FirstOrDefault() ?? string.Empty;
|
|
|
|
if (!domainSet.Contains(entityDomain))
|
|
continue;
|
|
|
|
Interlocked.Increment(ref totalChecked);
|
|
|
|
if (!entity.TryGetProperty("state", out var stateProp))
|
|
continue;
|
|
|
|
var state = stateProp.GetString();
|
|
if (string.Equals(state, UnavailableState, StringComparison.OrdinalIgnoreCase) ||
|
|
string.Equals(state, UnknownState, StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
unhealthy.Add(new
|
|
{
|
|
entityId,
|
|
state,
|
|
lastChanged = entity.TryGetProperty("last_changed", out var lc) ? lc.GetString() : null
|
|
});
|
|
}
|
|
}
|
|
|
|
return new
|
|
{
|
|
passed = unhealthy.IsEmpty,
|
|
totalChecked,
|
|
unhealthyCount = unhealthy.Count,
|
|
unhealthyEntities = unhealthy.OrderBy(e => e.ToString()).ToList()
|
|
};
|
|
}
|
|
|
|
private async Task<object> CheckRecentActivityAsync(int windowMinutes, CancellationToken cancellationToken)
|
|
{
|
|
try
|
|
{
|
|
var startTime = DateTimeOffset.UtcNow.AddMinutes(-windowMinutes);
|
|
var logbook = await _client.GetLogbookAsync(
|
|
entityId: null,
|
|
startTime: startTime,
|
|
endTime: null,
|
|
cancellationToken: cancellationToken).ConfigureAwait(false);
|
|
|
|
var entryCount = logbook.ValueKind == JsonValueKind.Array ? logbook.GetArrayLength() : 0;
|
|
return new
|
|
{
|
|
windowMinutes,
|
|
entryCount,
|
|
hasActivity = entryCount > 0
|
|
};
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return new
|
|
{
|
|
windowMinutes,
|
|
entryCount = 0,
|
|
hasActivity = false,
|
|
error = ex.Message
|
|
};
|
|
}
|
|
}
|
|
|
|
private static string DetermineOverallStatus(object apiHealth, object entityCheck)
|
|
{
|
|
var apiJson = JsonSerializer.SerializeToElement(apiHealth);
|
|
var entityJson = JsonSerializer.SerializeToElement(entityCheck);
|
|
|
|
var apiHealthy = apiJson.TryGetProperty("status", out var s) &&
|
|
string.Equals(s.GetString(), "healthy", StringComparison.OrdinalIgnoreCase);
|
|
|
|
var entitiesHealthy = entityJson.TryGetProperty("passed", out var p) && p.GetBoolean();
|
|
|
|
return apiHealthy && entitiesHealthy ? "PASS" : "FAIL";
|
|
}
|
|
|
|
private async Task<object> ValidateSingleEntityAsync(
|
|
string entityId,
|
|
string? expectedState,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
try
|
|
{
|
|
var entity = await _client.GetEntityStateAsync(entityId, cancellationToken).ConfigureAwait(false);
|
|
|
|
var actualState = entity.TryGetProperty("state", out var stateProp)
|
|
? stateProp.GetString() ?? string.Empty
|
|
: string.Empty;
|
|
|
|
var isAvailable = !string.Equals(actualState, UnavailableState, StringComparison.OrdinalIgnoreCase) &&
|
|
!string.Equals(actualState, UnknownState, StringComparison.OrdinalIgnoreCase);
|
|
|
|
var stateMatch = string.IsNullOrEmpty(expectedState) ||
|
|
string.Equals(actualState, expectedState, StringComparison.OrdinalIgnoreCase);
|
|
|
|
return new
|
|
{
|
|
entityId,
|
|
actualState,
|
|
expectedState = expectedState ?? "(any)",
|
|
isAvailable,
|
|
stateMatch,
|
|
passed = isAvailable && stateMatch,
|
|
lastChanged = entity.TryGetProperty("last_changed", out var lc) ? lc.GetString() : null
|
|
};
|
|
}
|
|
catch (HttpRequestException)
|
|
{
|
|
return new
|
|
{
|
|
entityId,
|
|
actualState = "error",
|
|
expectedState = expectedState ?? "(any)",
|
|
isAvailable = false,
|
|
stateMatch = false,
|
|
passed = false,
|
|
lastChanged = (string?)null
|
|
};
|
|
}
|
|
}
|
|
}
|