From fa7f53a2f9ec4a642610dec9fef2c26540f040db Mon Sep 17 00:00:00 2001 From: Lior Shmueli <48066416+ShmueLior@users.noreply.github.com> Date: Sat, 28 Nov 2026 08:46:32 +0200 Subject: [PATCH 1/3] Add HTML report: LintReport.ToHtml, ToolSurfaceDiff.ToHtml and --report on lint and diff --- CHANGELOG.md | 5 + README.md | 21 +++ src/McpProbe.Cli/CliApp.cs | 50 +++++- src/McpProbe/Internal/HtmlReport.cs | 68 ++++++++ src/McpProbe/Linting/LintReport.cs | 32 +++- src/McpProbe/PublicAPI.Unshipped.txt | 2 + src/McpProbe/Snapshots/ToolSurfaceDiff.cs | 30 +++- tests/McpProbe.Tests/CliTests.cs | 120 +++++++++++++++ tests/McpProbe.Tests/HtmlReportTests.cs | 180 ++++++++++++++++++++++ 9 files changed, 502 insertions(+), 6 deletions(-) create mode 100644 src/McpProbe/Internal/HtmlReport.cs create mode 100644 tests/McpProbe.Tests/HtmlReportTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index fb56c9e..dd7a822 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,11 @@ All notable changes to this project are documented here. The format is based on ## [Unreleased] +### Added + +- `LintReport.ToHtml()` and `ToolSurfaceDiff.ToHtml()`: a self-contained HTML page (inline CSS, no scripts) with a banner, a summary and a table. Server text is sanitized and HTML-encoded. +- `mcpprobe lint --report ` and `mcpprobe diff --report ` also write that page. Stdout and exit codes are unchanged. The file is written on exit 0 and 1, not on a usage or connection error (exit 2). + ## [0.3.0-preview] - 2026-11-28 ### Added diff --git a/README.md b/README.md index ecd26cd..885cb75 100644 --- a/README.md +++ b/README.md @@ -140,6 +140,27 @@ mcpprobe lint --http http://localhost:5000/sse --transport sse --header "Aut Exit codes: `0` passed, `1` check failed (breaking change or lint findings), `2` usage or connection error. The server's stderr is printed when it fails to start. `diff` and `lint` also take `--from-file ` to check a file without starting a server. Run `mcpprobe --help` for every option. +### HTML report + +`lint` and `diff` take `--report ` to also write a self-contained HTML page (inline CSS, no scripts): a banner, a one-line summary and a table of findings or changes. It is not in 0.3.0-preview; it comes with the next release. The text report on stdout and the exit code do not change, the file is written whether the check passed or failed (exit `0` or `1`), and nothing is written on a usage or connection error (exit `2`). In code, use `LintReport.ToHtml()` and `ToolSurfaceDiff.ToHtml()`. + +```bash +mcpprobe lint --stdio "dotnet run --project src/MyServer" --report mcp-lint.html +mcpprobe diff --stdio "dotnet run --project src/MyServer" --baseline mcp-tools.json --report mcp-diff.html +``` + +To keep the files from a CI run, upload them as an artifact. `if: always()` keeps the upload when the check fails: + +```yaml + - uses: actions/upload-artifact@v4 + if: always() + with: + name: mcpprobe-reports + path: | + mcp-lint.html + mcp-diff.html +``` + ### GitHub Actions The `McpProbe tool surface check` Action installs the same `McpProbe.Cli` version as the tag you pin, then runs `diff` and `lint`. It needs `actions/setup-dotnet` (a .NET 8 or .NET 10 SDK) and your server already built. Reports go to the job summary. Pin an exact release tag that includes the Action (0.3.0-preview or later): diff --git a/src/McpProbe.Cli/CliApp.cs b/src/McpProbe.Cli/CliApp.cs index 3472c66..8f026f3 100644 --- a/src/McpProbe.Cli/CliApp.cs +++ b/src/McpProbe.Cli/CliApp.cs @@ -70,6 +70,34 @@ private static Command BuildSnapshotCommand(TextWriter stdout, TextWriter stderr return command; } + private static Option BuildReportOption() => new("--report") + { + Description = "Also write a self-contained HTML report to this file. stdout and the exit code are unchanged.", + }; + + /// A blank --report is a usage error; checked before connecting so nothing is written. + private static string? ReportPath(ParseResult parse, Option report) + { + var value = parse.GetValue(report); + return value is null ? null : string.IsNullOrWhiteSpace(value) ? throw new ArgumentException("--report needs a file path.") : Path.GetFullPath(value); + } + + /// Writes through a sibling temp file so a failure never leaves a partial report. + private static async Task WriteReportAsync(string path, string html, CancellationToken ct) + { + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + var temp = $"{path}.{Guid.NewGuid():N}.tmp"; + try + { + await File.WriteAllTextAsync(temp, html, ct).ConfigureAwait(false); + File.Move(temp, path, overwrite: true); + } + finally + { + File.Delete(temp); + } + } + private static Command BuildDiffCommand(TextWriter stdout, TextWriter stderr) { var server = new ServerOptions(allowFile: true); @@ -83,12 +111,16 @@ private static Command BuildDiffCommand(TextWriter stdout, TextWriter stderr) Description = "Also fail (exit 1) on non-breaking changes, so the snapshot is always kept up to date.", }; + var report = BuildReportOption(); + var command = new Command("diff", "Compare a server's tool surface with a snapshot. Exits 1 on breaking changes."); server.AddTo(command); command.Options.Add(baseline); command.Options.Add(failOnNonBreaking); + command.Options.Add(report); command.SetAction((parse, ct) => RunGuardedAsync(stderr, async () => { + var reportPath = ReportPath(parse, report); var baselinePath = Path.GetFullPath(parse.GetValue(baseline)!); if (!File.Exists(baselinePath)) { @@ -100,6 +132,10 @@ private static Command BuildDiffCommand(TextWriter stdout, TextWriter stderr) var current = await server.CaptureAsync(parse, stderr, ct).ConfigureAwait(false); var diff = ToolSurfaceComparer.Compare(expected, current); await stdout.WriteLineAsync(diff.ToReport()).ConfigureAwait(false); + if (reportPath is not null) + { + await WriteReportAsync(reportPath, diff.ToHtml(), ct).ConfigureAwait(false); + } if (diff.HasBreakingChanges || (diff.HasChanges && parse.GetValue(failOnNonBreaking))) { @@ -140,6 +176,7 @@ private static Command BuildLintCommand(TextWriter stdout, TextWriter stderr) { Description = "Also run schema-portability rules MCPP009-MCPP012. Those findings fail the command only when their severity is error.", }; + var report = BuildReportOption(); var command = new Command("lint", "Lint tool names, descriptions and parameters. Exits 1 on findings at or above --fail-on, or on a portability error when --strict is set."); server.AddTo(command); command.Options.Add(failOn); @@ -147,8 +184,10 @@ private static Command BuildLintCommand(TextWriter stdout, TextWriter stderr) command.Options.Add(rules); command.Options.Add(nested); command.Options.Add(strict); + command.Options.Add(report); command.SetAction((parse, ct) => RunGuardedAsync(stderr, async () => { + var reportPath = ReportPath(parse, report); var options = new LintOptions { FailOn = ParseSeverity(parse.GetValue(failOn)!), @@ -170,9 +209,14 @@ private static Command BuildLintCommand(TextWriter stdout, TextWriter stderr) } var surface = await server.CaptureAsync(parse, stderr, ct).ConfigureAwait(false); - var report = ToolLinter.Lint(surface, options); - await stdout.WriteLineAsync(report.ToReport()).ConfigureAwait(false); - return report.Failed ? ExitCodes.CheckFailed : ExitCodes.Success; + var lint = ToolLinter.Lint(surface, options); + await stdout.WriteLineAsync(lint.ToReport()).ConfigureAwait(false); + if (reportPath is not null) + { + await WriteReportAsync(reportPath, lint.ToHtml(), ct).ConfigureAwait(false); + } + + return lint.Failed ? ExitCodes.CheckFailed : ExitCodes.Success; })); return command; } diff --git a/src/McpProbe/Internal/HtmlReport.cs b/src/McpProbe/Internal/HtmlReport.cs new file mode 100644 index 0000000..581d4ef --- /dev/null +++ b/src/McpProbe/Internal/HtmlReport.cs @@ -0,0 +1,68 @@ +using System.Net; +using System.Text; + +namespace McpProbe.Internal; + +/// +/// Builds the self-contained HTML for lint and diff reports. Callers pass cells already run through +/// ; every cell, title and summary is HTML-encoded here, and only as element text. +/// +internal static class HtmlReport +{ + private const string Css = + "body{font-family:system-ui,sans-serif;margin:2rem;color:#1f2328}" + + ".banner{display:inline-block;padding:.25rem .75rem;border-radius:.25rem;font-weight:600;color:#fff}" + + ".pass{background:#1a7f37}.fail{background:#cf222e}.note{background:#9a6700}" + + "table{border-collapse:collapse;margin-top:1rem}th,td{border:1px solid #d0d7de;padding:.35rem .6rem;text-align:left;vertical-align:top}" + + "th{background:#f6f8fa}td{overflow-wrap:anywhere}.error td:first-child,.breaking td:first-child{color:#cf222e;font-weight:600}" + + ".warning td:first-child,.non-breaking td:first-child{color:#9a6700;font-weight:600}"; + + /// The page title and heading. + /// One of pass, fail or note; fixed values, never server text. + /// The banner text. + /// The one-line summary. + /// The table headers. + /// The rows: a fixed CSS class (never server text) and the cells. + public static string Page(string title, string bannerClass, string banner, string summary, string[] headers, IEnumerable<(string RowClass, string[] Cells)> rows) + { + var sb = new StringBuilder("\n"); + sb.Append(""); + sb.Append("").Append(Encode(title)).Append("\n"); + sb.Append("

").Append(Encode(title)).Append("

\n"); + sb.Append("

").Append(Encode(banner)).Append("

\n"); + sb.Append("

").Append(Encode(summary)).Append("

\n"); + + var any = false; + foreach (var (rowClass, cells) in rows) + { + if (!any) + { + any = true; + sb.Append(""); + foreach (var header in headers) + { + sb.Append(""); + } + + sb.Append("\n"); + } + + sb.Append(""); + foreach (var cell in cells) + { + sb.Append(""); + } + + sb.Append("\n"); + } + + if (any) + { + sb.Append("
").Append(Encode(header)).Append("
").Append(Encode(cell)).Append("
\n"); + } + + return sb.Append("\n").ToString(); + } + + private static string Encode(string value) => WebUtility.HtmlEncode(value); +} diff --git a/src/McpProbe/Linting/LintReport.cs b/src/McpProbe/Linting/LintReport.cs index 45eca3e..1959957 100644 --- a/src/McpProbe/Linting/LintReport.cs +++ b/src/McpProbe/Linting/LintReport.cs @@ -1,5 +1,6 @@ using System.Globalization; using System.Text; +using McpProbe.Internal; namespace McpProbe.Linting; @@ -45,8 +46,7 @@ public string ToReport() } var sb = new StringBuilder(); - sb.Append(CultureInfo.InvariantCulture, - $"{Findings.Count} lint finding(s): {Count(LintSeverity.Error)} error, {Count(LintSeverity.Warning)} warning, {Count(LintSeverity.Info)} info."); + sb.Append(Summary()); foreach (var finding in Findings) { sb.Append('\n').Append(" ").Append(finding); @@ -55,6 +55,31 @@ public string ToReport() return sb.ToString(); } + /// + /// Formats the findings as a complete, self-contained HTML document: inline CSS, no scripts and no external assets. + /// Server-supplied text is already sanitized and HTML-encoded, so the result is safe to write to a file. + /// + /// The HTML document. + public string ToHtml() + { + var rows = Findings.Select(f => (RowClass: LintFinding.SeverityLabel(f.Severity), Cells: new[] + { + LintFinding.SeverityLabel(f.Severity), + f.RuleId, + Printable.Text(f.ToolName, 100), + f.ParameterName is null ? string.Empty : Printable.Text(f.ParameterName, 100), + Printable.Text(f.Message, 500), + Fails(f) ? "yes" : "no", + })); + return HtmlReport.Page( + "McpProbe lint report", + Failed ? "fail" : "pass", + Failed ? "Failed" : "Passed", + Findings.Count == 0 ? "No lint findings." : $"{Summary()} Fails on: {LintFinding.SeverityLabel(FailOn)}.", + ["Severity", "Rule", "Tool", "Path", "Message", "Fails the run"], + rows); + } + /// Throws when is . /// A finding failed the run (see ). public void ThrowIfFailed() @@ -69,5 +94,8 @@ public void ThrowIfFailed() /// public override string ToString() => ToReport(); + private string Summary() => string.Create(CultureInfo.InvariantCulture, + $"{Findings.Count} lint finding(s): {Count(LintSeverity.Error)} error, {Count(LintSeverity.Warning)} warning, {Count(LintSeverity.Info)} info."); + private int Count(LintSeverity severity) => Findings.Count(f => f.Severity == severity); } diff --git a/src/McpProbe/PublicAPI.Unshipped.txt b/src/McpProbe/PublicAPI.Unshipped.txt index 9289675..cd8c386 100644 --- a/src/McpProbe/PublicAPI.Unshipped.txt +++ b/src/McpProbe/PublicAPI.Unshipped.txt @@ -82,6 +82,7 @@ McpProbe.Linting.LintReport.FailOn.get -> McpProbe.Linting.LintSeverity McpProbe.Linting.LintReport.Failed.get -> bool McpProbe.Linting.LintReport.Findings.get -> System.Collections.Generic.IReadOnlyList! McpProbe.Linting.LintReport.ThrowIfFailed() -> void +McpProbe.Linting.LintReport.ToHtml() -> string! McpProbe.Linting.LintReport.ToReport() -> string! McpProbe.Linting.LintRule McpProbe.Linting.LintRule.$() -> McpProbe.Linting.LintRule! @@ -207,6 +208,7 @@ McpProbe.Snapshots.ToolSurfaceDiff.Changes.get -> System.Collections.Generic.IRe McpProbe.Snapshots.ToolSurfaceDiff.HasBreakingChanges.get -> bool McpProbe.Snapshots.ToolSurfaceDiff.HasChanges.get -> bool McpProbe.Snapshots.ToolSurfaceDiff.NonBreakingChanges.get -> System.Collections.Generic.IEnumerable! +McpProbe.Snapshots.ToolSurfaceDiff.ToHtml() -> string! McpProbe.Snapshots.ToolSurfaceDiff.ToReport() -> string! const McpProbe.Snapshots.SnapshotOptions.UpdateEnvironmentVariable = "MCPPROBE_UPDATE_SNAPSHOTS" -> string! const McpProbe.Snapshots.ToolSnapshot.DefaultFileName = "mcp-tools.json" -> string! diff --git a/src/McpProbe/Snapshots/ToolSurfaceDiff.cs b/src/McpProbe/Snapshots/ToolSurfaceDiff.cs index fea981b..1f0261f 100644 --- a/src/McpProbe/Snapshots/ToolSurfaceDiff.cs +++ b/src/McpProbe/Snapshots/ToolSurfaceDiff.cs @@ -1,5 +1,6 @@ using System.Globalization; using System.Text; +using McpProbe.Internal; namespace McpProbe.Snapshots; @@ -35,7 +36,7 @@ public string ToReport() var breaking = BreakingChanges.ToList(); var nonBreaking = NonBreakingChanges.ToList(); var sb = new StringBuilder(); - sb.Append(CultureInfo.InvariantCulture, $"Tool surface changed: {breaking.Count} breaking, {nonBreaking.Count} non-breaking.").Append('\n'); + sb.Append(Summary(breaking.Count, nonBreaking.Count)).Append('\n'); if (breaking.Count > 0) { @@ -58,6 +59,33 @@ public string ToReport() return sb.ToString().TrimEnd('\n'); } + /// + /// Formats the changes as a complete, self-contained HTML document: inline CSS, no scripts and no external assets. + /// Server-supplied text is already sanitized and HTML-encoded, so the result is safe to write to a file. + /// + /// The HTML document. + public string ToHtml() + { + var rows = Changes.Select(c => (RowClass: c.IsBreaking ? "breaking" : "non-breaking", Cells: new[] + { + c.IsBreaking ? "breaking" : "non-breaking", + c.Kind.ToString(), + Printable.Text(c.ToolName, 100), + c.Path is null ? string.Empty : Printable.Text(c.Path, 200), + Printable.Text(c.Message, 500), + })); + return HtmlReport.Page( + "McpProbe diff report", + HasBreakingChanges ? "fail" : HasChanges ? "note" : "pass", + HasBreakingChanges ? "Breaking changes" : HasChanges ? "Non-breaking changes only" : "Unchanged", + HasChanges ? Summary(BreakingChanges.Count(), NonBreakingChanges.Count()) : "Tool surface unchanged.", + ["Impact", "Kind", "Tool", "Path", "Message"], + rows); + } + + private static string Summary(int breaking, int nonBreaking) => string.Create(CultureInfo.InvariantCulture, + $"Tool surface changed: {breaking} breaking, {nonBreaking} non-breaking."); + /// public override string ToString() => ToReport(); } diff --git a/tests/McpProbe.Tests/CliTests.cs b/tests/McpProbe.Tests/CliTests.cs index f5b70c5..042fc65 100644 --- a/tests/McpProbe.Tests/CliTests.cs +++ b/tests/McpProbe.Tests/CliTests.cs @@ -191,6 +191,126 @@ public async Task Lint_Strict_IsOptInAndFailsOnlyOnPortabilityErrors() Assert.Contains("error MCPP010", upgraded.Out, StringComparison.Ordinal); } + [Fact] + public async Task Report_Lint_WritesHtmlAndLeavesStdoutAndExitCodeUnchanged() + { + var file = WriteSurface("tools.json", Surface(Tool("ok"))); + var failing = WriteSurface("failing.json", Surface(Tool("bad", description: ""))); + var report = _dir.File(Path.Combine("nested", "dir", "lint.html")); + + var plain = await RunAsync("lint", "--from-file", file); + var withReport = await RunAsync("lint", "--from-file", file, "--report", report); + + Assert.Equal(plain, withReport); + Assert.Contains("banner pass", File.ReadAllText(report), StringComparison.Ordinal); + + var failedPlain = await RunAsync("lint", "--from-file", failing); + var failed = await RunAsync("lint", "--from-file", failing, "--report", report); + Assert.Equal(ExitCodes.CheckFailed, failed.Exit); + Assert.Equal(failedPlain, failed); + Assert.Contains("banner fail", File.ReadAllText(report), StringComparison.Ordinal); + Assert.Contains("MCPP001", File.ReadAllText(report), StringComparison.Ordinal); + Assert.Equal(["lint.html"], Directory.GetFiles(Path.GetDirectoryName(report)!).Select(Path.GetFileName)); + } + + [Fact] + public async Task Report_Diff_WritesHtmlOnExitZeroAndOne() + { + var baseline = WriteSurface("base.json", Surface(Tool("keep"), Tool("gone"))); + var same = WriteSurface("same.json", Surface(Tool("keep"), Tool("gone"))); + var added = WriteSurface("added.json", Surface(Tool("keep"), Tool("gone"), Tool("added"))); + var removed = WriteSurface("removed.json", Surface(Tool("keep"))); + var report = _dir.File("diff.html"); + + Assert.Equal(ExitCodes.Success, (await RunAsync("diff", "--baseline", baseline, "--from-file", same, "--report", report)).Exit); + Assert.Contains("Tool surface unchanged.", File.ReadAllText(report), StringComparison.Ordinal); + + Assert.Equal(ExitCodes.Success, (await RunAsync("diff", "--baseline", baseline, "--from-file", added, "--report", report)).Exit); + Assert.Contains("Non-breaking changes only", File.ReadAllText(report), StringComparison.Ordinal); + + var flagged = await RunAsync("diff", "--baseline", baseline, "--from-file", added, "--fail-on-non-breaking", "--report", report); + Assert.Equal(ExitCodes.CheckFailed, flagged.Exit); + Assert.Contains("Non-breaking changes only", File.ReadAllText(report), StringComparison.Ordinal); + + var plain = await RunAsync("diff", "--baseline", baseline, "--from-file", removed); + var breaking = await RunAsync("diff", "--baseline", baseline, "--from-file", removed, "--report", report); + Assert.Equal(ExitCodes.CheckFailed, breaking.Exit); + Assert.Equal(plain, breaking); + Assert.Contains("Breaking changes", File.ReadAllText(report), StringComparison.Ordinal); + } + + [Fact] + public async Task Report_SampleServerOverStdio_WritesBothReports() + { + var snapshot = _dir.File("mcp-tools.json"); + var lintReport = _dir.File("lint.html"); + var diffReport = _dir.File("diff.html"); + Assert.Equal(0, (await RunAsync("snapshot", "--stdio", StdioCommand, "--out", snapshot)).Exit); + + Assert.Equal(0, (await RunAsync("lint", "--stdio", StdioCommand, "--report", lintReport)).Exit); + Assert.Equal(0, (await RunAsync("diff", "--stdio", StdioCommand, "--baseline", snapshot, "--report", diffReport)).Exit); + + Assert.Contains("No lint findings.", File.ReadAllText(lintReport), StringComparison.Ordinal); + Assert.Contains("Tool surface unchanged.", File.ReadAllText(diffReport), StringComparison.Ordinal); + } + + [Fact] + public async Task Report_UsageAndConnectionErrorsDoNotWriteTheFile() + { + var current = WriteSurface("current.json", Surface(Tool("keep"))); + var report = _dir.File("never.html"); + + var results = new[] + { + await RunAsync("lint", "--from-file", _dir.File("missing.json"), "--report", report), + await RunAsync("lint", "--from-file", current, "--rule", "MCPP999=none", "--report", report), + await RunAsync("lint", "--report", report), + await RunAsync("lint", "--http", "not a url", "--report", report), + await RunAsync("diff", "--baseline", _dir.File("nope.json"), "--from-file", current, "--report", report), + await RunAsync("diff", "--baseline", current, "--from-file", _dir.File("missing.json"), "--report", report), + }; + + Assert.All(results, r => Assert.Equal(ExitCodes.Error, r.Exit)); + Assert.False(File.Exists(report)); + Assert.Empty(Directory.GetFiles(_dir.Path, "never*")); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + public async Task Report_BlankPathIsAUsageError(string path) + { + var current = WriteSurface("current.json", Surface(Tool("keep"))); + + var lint = await RunAsync("lint", "--from-file", current, "--report", path); + var diff = await RunAsync("diff", "--baseline", current, "--from-file", current, "--report", path); + + Assert.Equal(ExitCodes.Error, lint.Exit); + Assert.Equal(ExitCodes.Error, diff.Exit); + Assert.Contains("--report needs a file path", lint.Err + diff.Err, StringComparison.Ordinal); + Assert.Equal("", lint.Out + diff.Out); + } + + [Fact] + public async Task Report_ReplacesAnExistingFile_AndAFailedWriteLeavesNoPartialFile() + { + var current = WriteSurface("current.json", Surface(Tool("keep"))); + var report = _dir.File("report.html"); + File.WriteAllText(report, "old"); + + Assert.Equal(0, (await RunAsync("lint", "--from-file", current, "--report", report)).Exit); + Assert.StartsWith("", File.ReadAllText(report), StringComparison.Ordinal); + + var directory = _dir.File("a-directory"); + Directory.CreateDirectory(directory); + var (exit, _, error) = await RunAsync("lint", "--from-file", current, "--report", directory); + + Assert.Equal(ExitCodes.Error, exit); + Assert.StartsWith("error:", error, StringComparison.Ordinal); + Assert.Empty(Directory.GetFileSystemEntries(directory)); + Assert.DoesNotContain(Directory.GetFiles(_dir.Path), f => f.EndsWith(".tmp", StringComparison.Ordinal)); + } + [Theory] [InlineData("MCPP999=none")] [InlineData("MCPP008=error")] diff --git a/tests/McpProbe.Tests/HtmlReportTests.cs b/tests/McpProbe.Tests/HtmlReportTests.cs new file mode 100644 index 0000000..43cdaa3 --- /dev/null +++ b/tests/McpProbe.Tests/HtmlReportTests.cs @@ -0,0 +1,180 @@ +using System.Globalization; +using McpProbe.Linting; +using McpProbe.Snapshots; +using static McpProbe.Tests.TestSupport.SchemaTools; + +namespace McpProbe.Tests; + +public sealed class HtmlReportTests +{ + private const string Hostile = " & \"q\" 'a' \u001b[31m \u202E"; + + private static LintFinding Finding(string rule, LintSeverity severity, string tool = "tool", string? parameter = null, string message = "Fix it.") => + new(rule, severity, tool, parameter, message); + + private static ToolSurfaceChange Change(ChangeSeverity severity, ToolSurfaceChangeKind kind = ToolSurfaceChangeKind.ToolRemoved, string tool = "tool", string? path = null, string message = "Changed.") => + new(tool, path, kind, severity, message); + + [Fact] + public void Lint_NoFindings_IsASmallPassedPage() + { + var html = new LintReport([], LintSeverity.Warning).ToHtml(); + + Assert.StartsWith("", html, StringComparison.Ordinal); + Assert.Contains("", html, StringComparison.Ordinal); + Assert.Contains("McpProbe lint report", html, StringComparison.Ordinal); + Assert.Contains("Passed", html, StringComparison.Ordinal); + Assert.Contains("No lint findings.", html, StringComparison.Ordinal); + Assert.DoesNotContain("Fails the run", html, StringComparison.Ordinal); + Assert.Contains("errorMCPP003searchhome.zipNo description.yes", html, StringComparison.Ordinal); + Assert.Contains("warningMCPP014otherFix it.yes", html, StringComparison.Ordinal); + Assert.Contains("Failed", html, StringComparison.Ordinal); + Assert.Contains("2 lint finding(s): 1 error, 1 warning, 0 info. Fails on: warning.", html, StringComparison.Ordinal); + } + + [Fact] + public void Lint_FailOnError_WarningsPassAndSayTheyDoNotFail() + { + var html = new LintReport([Finding("MCPP002", LintSeverity.Warning)], LintSeverity.Error).ToHtml(); + + Assert.Contains("class=\"banner pass\">Passed", html, StringComparison.Ordinal); + Assert.Contains("no", html, StringComparison.Ordinal); + Assert.Contains("Fails on: error.", html, StringComparison.Ordinal); + } + + [Fact] + public void Lint_PortabilityWarningDoesNotFail_ButPortabilityErrorDoes() + { + var warning = new LintReport([Finding("MCPP010", LintSeverity.Warning, parameter: "inputSchema.properties.city")], LintSeverity.Info).ToHtml(); + var error = new LintReport([Finding("MCPP009", LintSeverity.Error, parameter: "inputSchema.properties.city")], LintSeverity.None).ToHtml(); + + Assert.Contains("banner pass", warning, StringComparison.Ordinal); + Assert.Contains("inputSchema.properties.cityFix it.no", warning, StringComparison.Ordinal); + Assert.Contains("banner fail", error, StringComparison.Ordinal); + Assert.Contains("yes", error, StringComparison.Ordinal); + } + + [Fact] + public void Lint_FailOnNone_NothingFailsExceptPortabilityErrors() + { + var html = new LintReport([Finding("MCPP013", LintSeverity.Error)], LintSeverity.None).ToHtml(); + + Assert.Contains("banner pass", html, StringComparison.Ordinal); + Assert.Contains("Fails on: none.", html, StringComparison.Ordinal); + } + + [Fact] + public void Lint_HostileServerText_IsOnlyEverElementText() + { + var html = new LintReport([Finding("MCPP001", LintSeverity.Error, Hostile, Hostile, Hostile)], LintSeverity.Warning).ToHtml(); + + AssertEncoded(html); + Assert.Equal(3, CountOf(html, "<script>alert(1)</script>")); + Assert.Equal(1, CountOf(html, "{new string('a', 497)}...", lint, StringComparison.Ordinal); + Assert.Contains($"{new string('a', 97)}...", lint, StringComparison.Ordinal); + Assert.DoesNotContain(new string('a', 498), lint, StringComparison.Ordinal); + Assert.Contains($"{new string('a', 197)}...", diff, StringComparison.Ordinal); + Assert.DoesNotContain(new string('a', 501), diff, StringComparison.Ordinal); + } + + [Fact] + public void LoneSurrogatesAndBackslashes_FollowToString() + { + var text = "ab\ud83d" + "cd\\e"; + var html = new LintReport([Finding("MCPP001", LintSeverity.Error, text)], LintSeverity.Warning).ToHtml(); + + Assert.DoesNotContain(html, char.IsSurrogate); + Assert.Contains("ab\\uD83Dcd\\\\e", html, StringComparison.Ordinal); + } + + [Fact] + public void Diff_Banners_FollowBreakingAndNonBreaking() + { + var unchanged = new ToolSurfaceDiff([]).ToHtml(); + var nonBreaking = new ToolSurfaceDiff([Change(ChangeSeverity.NonBreaking, ToolSurfaceChangeKind.ToolAdded, path: "input.city")]).ToHtml(); + var mixed = new ToolSurfaceDiff([Change(ChangeSeverity.Breaking), Change(ChangeSeverity.NonBreaking, ToolSurfaceChangeKind.PropertyAdded)]).ToHtml(); + + Assert.Contains("class=\"banner pass\">Unchanged", unchanged, StringComparison.Ordinal); + Assert.Contains("Tool surface unchanged.", unchanged, StringComparison.Ordinal); + Assert.DoesNotContain("Non-breaking changes only", nonBreaking, StringComparison.Ordinal); + Assert.Contains("non-breakingToolAddedtoolinput.cityChanged.", nonBreaking, StringComparison.Ordinal); + Assert.Contains("class=\"banner fail\">Breaking changes", mixed, StringComparison.Ordinal); + Assert.Contains("Tool surface changed: 1 breaking, 1 non-breaking.", mixed, StringComparison.Ordinal); + Assert.Contains("breakingToolRemoved", mixed, StringComparison.Ordinal); + } + + [Fact] + public void Diff_RealComparison_ListsConstraintAndKeywordChanges() + { + var before = Tool("t", """{"type":"object","properties":{"n":{"type":"integer","maximum":10}}}"""); + var after = Tool("t", """{"type":"object","properties":{"n":{"type":"integer","maximum":5}}}"""); + + var html = Diff(before, after).ToHtml(); + + Assert.Contains("ConstraintChanged", html, StringComparison.Ordinal); + Assert.Contains("input.n", html, StringComparison.Ordinal); + } + + [Theory] + [InlineData("de-DE")] + [InlineData("tr-TR")] + public void Counts_UseInvariantCulture(string culture) + { + var original = CultureInfo.CurrentCulture; + try + { + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(culture); + var findings = Enumerable.Range(0, 1234).Select(_ => Finding("MCPP001", LintSeverity.Error)).ToList(); + var html = new LintReport(findings, LintSeverity.Warning).ToHtml(); + + Assert.Contains("1234 lint finding(s): 1234 error, 0 warning, 0 info.", html, StringComparison.Ordinal); + } + finally + { + CultureInfo.CurrentCulture = original; + } + } + + private static void AssertEncoded(string html) + { + Assert.DoesNotContain(" text.Split(value).Length - 1; +} From 7fbffd4c8f4866b26a472f015b73f056cec35029 Mon Sep 17 00:00:00 2001 From: Lior Shmueli <48066416+ShmueLior@users.noreply.github.com> Date: Sat, 28 Nov 2026 08:57:09 +0200 Subject: [PATCH 2/3] Tweak HTML report: white background, table wording, and clean-diff stdout check --- CHANGELOG.md | 2 +- README.md | 2 +- src/McpProbe/Internal/HtmlReport.cs | 2 +- tests/McpProbe.Tests/CliTests.cs | 10 ++++++++-- 4 files changed, 11 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dd7a822..768100e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ All notable changes to this project are documented here. The format is based on ### Added -- `LintReport.ToHtml()` and `ToolSurfaceDiff.ToHtml()`: a self-contained HTML page (inline CSS, no scripts) with a banner, a summary and a table. Server text is sanitized and HTML-encoded. +- `LintReport.ToHtml()` and `ToolSurfaceDiff.ToHtml()`: a self-contained HTML page (inline CSS, no scripts) with a banner, a summary and, when there are findings or changes, a table. Server text is sanitized and HTML-encoded. - `mcpprobe lint --report ` and `mcpprobe diff --report ` also write that page. Stdout and exit codes are unchanged. The file is written on exit 0 and 1, not on a usage or connection error (exit 2). ## [0.3.0-preview] - 2026-11-28 diff --git a/README.md b/README.md index 885cb75..70c02d3 100644 --- a/README.md +++ b/README.md @@ -142,7 +142,7 @@ Exit codes: `0` passed, `1` check failed (breaking change or lint findings), `2` ### HTML report -`lint` and `diff` take `--report ` to also write a self-contained HTML page (inline CSS, no scripts): a banner, a one-line summary and a table of findings or changes. It is not in 0.3.0-preview; it comes with the next release. The text report on stdout and the exit code do not change, the file is written whether the check passed or failed (exit `0` or `1`), and nothing is written on a usage or connection error (exit `2`). In code, use `LintReport.ToHtml()` and `ToolSurfaceDiff.ToHtml()`. +`lint` and `diff` take `--report ` to also write a self-contained HTML page (inline CSS, no scripts): a banner, a one-line summary and, when there are findings or changes, a table. It is not in 0.3.0-preview; it comes with the next release. The text report on stdout and the exit code do not change, the file is written whether the check passed or failed (exit `0` or `1`), and nothing is written on a usage or connection error (exit `2`). In code, use `LintReport.ToHtml()` and `ToolSurfaceDiff.ToHtml()`. ```bash mcpprobe lint --stdio "dotnet run --project src/MyServer" --report mcp-lint.html diff --git a/src/McpProbe/Internal/HtmlReport.cs b/src/McpProbe/Internal/HtmlReport.cs index 581d4ef..9bd791f 100644 --- a/src/McpProbe/Internal/HtmlReport.cs +++ b/src/McpProbe/Internal/HtmlReport.cs @@ -10,7 +10,7 @@ namespace McpProbe.Internal; internal static class HtmlReport { private const string Css = - "body{font-family:system-ui,sans-serif;margin:2rem;color:#1f2328}" + + "body{font-family:system-ui,sans-serif;margin:2rem;background:#fff;color:#1f2328}" + ".banner{display:inline-block;padding:.25rem .75rem;border-radius:.25rem;font-weight:600;color:#fff}" + ".pass{background:#1a7f37}.fail{background:#cf222e}.note{background:#9a6700}" + "table{border-collapse:collapse;margin-top:1rem}th,td{border:1px solid #d0d7de;padding:.35rem .6rem;text-align:left;vertical-align:top}" + diff --git a/tests/McpProbe.Tests/CliTests.cs b/tests/McpProbe.Tests/CliTests.cs index 042fc65..38eaab4 100644 --- a/tests/McpProbe.Tests/CliTests.cs +++ b/tests/McpProbe.Tests/CliTests.cs @@ -222,10 +222,16 @@ public async Task Report_Diff_WritesHtmlOnExitZeroAndOne() var removed = WriteSurface("removed.json", Surface(Tool("keep"))); var report = _dir.File("diff.html"); - Assert.Equal(ExitCodes.Success, (await RunAsync("diff", "--baseline", baseline, "--from-file", same, "--report", report)).Exit); + var plainSame = await RunAsync("diff", "--baseline", baseline, "--from-file", same); + var sameWithReport = await RunAsync("diff", "--baseline", baseline, "--from-file", same, "--report", report); + Assert.Equal(ExitCodes.Success, sameWithReport.Exit); + Assert.Equal(plainSame, sameWithReport); Assert.Contains("Tool surface unchanged.", File.ReadAllText(report), StringComparison.Ordinal); - Assert.Equal(ExitCodes.Success, (await RunAsync("diff", "--baseline", baseline, "--from-file", added, "--report", report)).Exit); + var plainAdded = await RunAsync("diff", "--baseline", baseline, "--from-file", added); + var addedWithReport = await RunAsync("diff", "--baseline", baseline, "--from-file", added, "--report", report); + Assert.Equal(ExitCodes.Success, addedWithReport.Exit); + Assert.Equal(plainAdded, addedWithReport); Assert.Contains("Non-breaking changes only", File.ReadAllText(report), StringComparison.Ordinal); var flagged = await RunAsync("diff", "--baseline", baseline, "--from-file", added, "--fail-on-non-breaking", "--report", report); From f2b066da286f89ded12d2e5920c4bd61dd8bf37f Mon Sep 17 00:00:00 2001 From: Lior Shmueli <48066416+ShmueLior@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:11:56 +0200 Subject: [PATCH 3/3] Keep short HTML report columns from wrapping mid-token --- src/McpProbe/Internal/HtmlReport.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/McpProbe/Internal/HtmlReport.cs b/src/McpProbe/Internal/HtmlReport.cs index 9bd791f..eb8670d 100644 --- a/src/McpProbe/Internal/HtmlReport.cs +++ b/src/McpProbe/Internal/HtmlReport.cs @@ -14,7 +14,7 @@ internal static class HtmlReport ".banner{display:inline-block;padding:.25rem .75rem;border-radius:.25rem;font-weight:600;color:#fff}" + ".pass{background:#1a7f37}.fail{background:#cf222e}.note{background:#9a6700}" + "table{border-collapse:collapse;margin-top:1rem}th,td{border:1px solid #d0d7de;padding:.35rem .6rem;text-align:left;vertical-align:top}" + - "th{background:#f6f8fa}td{overflow-wrap:anywhere}.error td:first-child,.breaking td:first-child{color:#cf222e;font-weight:600}" + + "th{background:#f6f8fa}td{overflow-wrap:anywhere}th:nth-child(1),th:nth-child(2),th:nth-child(6),td:nth-child(1),td:nth-child(2),td:nth-child(6){white-space:nowrap}.error td:first-child,.breaking td:first-child{color:#cf222e;font-weight:600}" + ".warning td:first-child,.non-breaking td:first-child{color:#9a6700;font-weight:600}"; /// The page title and heading.