|
| 1 | +using System.ComponentModel; |
| 2 | +using System.Text.Json; |
| 3 | +using System.Text.Json.Nodes; |
| 4 | +using ModelContextProtocol.Protocol; |
| 5 | +using ModelContextProtocol.Server; |
| 6 | +using Motus.Abstractions; |
| 7 | + |
| 8 | +namespace Motus.Mcp; |
| 9 | + |
| 10 | +/// <summary> |
| 11 | +/// Checks the active page against the built-in WCAG accessibility rules and reports |
| 12 | +/// the violations found, each tied to a ref where the offending element can be |
| 13 | +/// addressed by other tools. |
| 14 | +/// </summary> |
| 15 | +[McpServerToolType] |
| 16 | +public sealed class AccessibilityTools |
| 17 | +{ |
| 18 | + [McpServerTool(Name = "audit_accessibility", Title = "Audit accessibility", Destructive = false, ReadOnly = true)] |
| 19 | + [Description("Runs WCAG 2.1 A and AA accessibility checks against the active page and returns the " |
| 20 | + + "violations found, each with a rule id, severity, message, and (when the element is addressable) " |
| 21 | + + "a ref usable with click, type, and other tools. A fresh snapshot is taken as part of the audit, " |
| 22 | + + "so refs from an earlier snapshot are replaced.")] |
| 23 | + public static async Task<CallToolResult> AuditAccessibilityAsync( |
| 24 | + [Description("Only return violations at or above this severity: error, warning, or info. " |
| 25 | + + "Omit to return all severities.")] string? min_severity, |
| 26 | + ActivePageService pageService, |
| 27 | + CancellationToken cancellationToken) |
| 28 | + { |
| 29 | + AccessibilityViolationSeverity? threshold = null; |
| 30 | + if (!string.IsNullOrWhiteSpace(min_severity)) |
| 31 | + { |
| 32 | + if (!Enum.TryParse(min_severity, ignoreCase: true, out AccessibilityViolationSeverity parsed)) |
| 33 | + return ToolResultHelper.Error( |
| 34 | + $"Unknown severity '{min_severity}'. Use error, warning, or info."); |
| 35 | + threshold = parsed; |
| 36 | + } |
| 37 | + |
| 38 | + try |
| 39 | + { |
| 40 | + var page = await pageService.GetOrCreateActivePageAsync(cancellationToken).ConfigureAwait(false); |
| 41 | + |
| 42 | + // A fresh snapshot refreshes the ref map so element-level violations can be |
| 43 | + // tied back to a ref the other tools accept. |
| 44 | + var snapshots = pageService.GetSnapshotService(page); |
| 45 | + await snapshots.TakeSnapshotAsync(cancellationToken).ConfigureAwait(false); |
| 46 | + |
| 47 | + var result = await page.RunAccessibilityAuditAsync(cancellationToken).ConfigureAwait(false); |
| 48 | + |
| 49 | + // Severity is ordered Error, Warning, Info, so "at or above" a threshold is |
| 50 | + // a lower-or-equal ordinal. |
| 51 | + var violations = threshold is { } min |
| 52 | + ? result.Violations.Where(v => (int)v.Severity <= (int)min).ToList() |
| 53 | + : result.Violations.ToList(); |
| 54 | + |
| 55 | + if (violations.Count == 0) |
| 56 | + { |
| 57 | + var none = threshold is { } onlyAbove |
| 58 | + ? $"No accessibility violations found at or above {onlyAbove.ToString().ToLowerInvariant()} severity." |
| 59 | + : "No accessibility violations found."; |
| 60 | + return ToolResultHelper.Text(Append(none, result.DiagnosticMessage)); |
| 61 | + } |
| 62 | + |
| 63 | + var array = new JsonArray(); |
| 64 | + foreach (var violation in violations) |
| 65 | + { |
| 66 | + var refId = violation.BackendDOMNodeId is long nodeId |
| 67 | + ? snapshots.GetRefForNodeId(nodeId) |
| 68 | + : null; |
| 69 | + |
| 70 | + array.Add(new JsonObject |
| 71 | + { |
| 72 | + ["ruleId"] = violation.RuleId, |
| 73 | + ["severity"] = violation.Severity.ToString(), |
| 74 | + ["message"] = violation.Message, |
| 75 | + ["nodeRole"] = violation.NodeRole, |
| 76 | + ["nodeName"] = violation.NodeName, |
| 77 | + ["ref"] = refId, |
| 78 | + }); |
| 79 | + } |
| 80 | + |
| 81 | + var payload = new JsonObject |
| 82 | + { |
| 83 | + ["violationCount"] = violations.Count, |
| 84 | + ["violations"] = array, |
| 85 | + }; |
| 86 | + |
| 87 | + // Build the structured value through the node API and parse it, rather than |
| 88 | + // reflection-serializing a type, so the trim and AOT analyzers stay satisfied. |
| 89 | + var element = JsonDocument.Parse(payload.ToJsonString()).RootElement.Clone(); |
| 90 | + var summary = Append( |
| 91 | + $"Found {violations.Count} accessibility violation(s).", |
| 92 | + result.DiagnosticMessage); |
| 93 | + return ToolResultHelper.Structured(element, summary); |
| 94 | + } |
| 95 | + catch (Exception ex) |
| 96 | + { |
| 97 | + return ToolResultHelper.Error($"Accessibility audit failed: {ex.Message}"); |
| 98 | + } |
| 99 | + } |
| 100 | + |
| 101 | + private static string Append(string text, string? diagnostic) |
| 102 | + => string.IsNullOrEmpty(diagnostic) ? text : $"{text} {diagnostic}"; |
| 103 | +} |
0 commit comments