diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 28eb8ad..9ed7574 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -83,6 +83,7 @@ jobs: from-file: samples/WeatherServer.Tests/mcp-tools.json baseline: samples/WeatherServer.Tests/mcp-tools.json config: samples/WeatherServer.Tests/mcpprobe.json + lint-baseline: samples/WeatherServer.Tests/mcpprobe-lint-baseline.json - name: Assert HTML reports were written if: matrix.os == 'ubuntu-latest' || matrix.os == 'windows-latest' diff --git a/CHANGELOG.md b/CHANGELOG.md index 6648be0..c74867f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ All notable changes to this project are documented here. The format is based on - `mcpprobe.json`: a committed config file for `mcpprobe lint` (`failOn`, `strict`, `nested`, `minDescriptionLength`, `minDescriptionWords`, `rules`, and `ignore`). `lint` uses the nearest file, starting in the current directory and going up to the repository root (the first folder with a `.git`), and says `Using config .` on stderr. New flags: `--config ` and `--no-config`. Order of precedence: defaults, then the file, then flags typed on the command line (`--nested false` and `--strict false` can turn a file setting off; `--rule` merges per rule id). Without a file nothing changes. The file is read strictly (unknown keys, wrong types and unknown rule ids exit 2), allows comments and trailing commas, and holds lint settings only, not a server to start. A repository that already has an unrelated `mcpprobe.json` will now have it read by `lint`. JSON schema: `docs/mcpprobe.schema.json`. - `ignore` entries hide findings by rule, tool pattern and parameter pattern (`*` and `?`, case-sensitive), with an optional `reason`. Hidden findings never fail the run. The report ends with `Hidden: N ignored.` and lists entries that matched nothing (it never fails for them). - `LintSuppression`, `LintOptions.Suppressions`, `LintReport.SuppressedFindings` and `LintReport.UnusedSuppressions`, the same thing for library users. The library does not read `mcpprobe.json`. +- Lint baseline: `mcpprobe lint --write-baseline ` writes the current findings (sorted, no timestamps) and exits 0; `lint --baseline `, or `"baseline"` in `mcpprobe.json`, hides them so only new findings fail. The report says `Hidden: N baselined.` and lists entries that no longer match (they never fail the run). Entries are rule, tool and optional parameter, not the message. Library: `LintBaseline`, `LintBaselineEntry`, `LintOptions.Baseline`, `LintReport.BaselinedFindings` and `LintReport.StaleBaselineEntries`. Action input `lint-baseline` and template parameter `lintBaseline` (passed as `--baseline`). - GitHub Action and Azure Pipelines template input `config` (passed as `--config`). Empty by default: lint finds a committed `mcpprobe.json` on its own. It needs a CLI that has `--config`; the wrapper fails fast if the installed tool does not. ### Changed diff --git a/README.md b/README.md index 3de015d..58461ee 100644 --- a/README.md +++ b/README.md @@ -164,7 +164,8 @@ A server with legacy debt can keep its lint settings, and the findings it has de "ignore": [ { "rule": "MCPP005", "tool": "sql_*", "reason": "Server convention: namespace_resource_verb-noun" }, { "rule": "MCPP003", "tool": "legacy_export", "parameter": "opts" } - ] + ], + "baseline": "mcpprobe-lint-baseline.json" } } ``` @@ -177,6 +178,22 @@ A server with legacy debt can keep its lint settings, and the findings it has de In code, the same thing is `LintOptions.Suppressions.Add(new LintSuppression(RuleId: "MCPP005", ToolPattern: "sql_*"))`. The library does not read `mcpprobe.json`; hidden findings are in `LintReport.SuppressedFindings` and unused entries in `LintReport.UnusedSuppressions`. +### Lint baseline + +To adopt lint on a server that already has findings, accept the current ones and fail only on new ones. Write a baseline once, commit it, and check against it in CI: + +```bash +mcpprobe lint --stdio "dotnet run --project src/MyServer" --write-baseline mcpprobe-lint-baseline.json +mcpprobe lint --stdio "dotnet run --project src/MyServer" --baseline mcpprobe-lint-baseline.json +``` + +- `--write-baseline ` writes every finding of the run (after `ignore`) and exits 0. It is sorted and has no timestamps, so a refresh is an easy diff to review. Run it with the same flags and config as CI (`--strict`, `--nested`). +- `--baseline `, or `"baseline"` in `mcpprobe.json` (relative to that file; the flag wins), hides the findings it lists. The report says `Hidden: 20 baselined.`, and new findings fail as usual. A missing or unreadable file is exit 2. Use either `--baseline` or `--write-baseline`, not both; `--write-baseline` ignores `"baseline"` from the config, so the first write works before the file exists. +- An entry is a rule, a tool and an optional parameter. The message is not part of it, so a baseline survives wording changes in a new McpProbe, but a finding that changes meaning on the same tool and parameter stays hidden. +- Entries that no longer match (the tool was fixed, renamed or removed) are listed under `Baseline: N entries no longer match.` They never fail the run; write the baseline again to drop them. Entries for a rule that did not run, such as MCPP010 without `--strict`, are not listed. A baseline written without `--strict` does not hide the `--strict` findings. + +In code: `new LintOptions { Baseline = LintBaseline.Load("mcpprobe-lint-baseline.json") }`, and `LintBaseline.FromReport(report).ToJson()` to write one. Hidden findings are in `LintReport.BaselinedFindings` and entries that matched nothing in `LintReport.StaleBaselineEntries`. + ## CLI in CI Write a snapshot once and commit it, then check it in CI: @@ -250,12 +267,14 @@ jobs: baseline: mcp-tools.json ``` -Inputs follow the CLI: `stdio`, `http`, or `from-file` (exactly one), plus `baseline` (default `mcp-tools.json`), `header`, `env`, `cwd`, `timeout`, `diff`, `lint`, `fail-on-non-breaking`, `fail-on`, `nested`, `rule`, `min-description-length`, `strict`, `transport`, `report`, `config`, `version`, and `source`. Both `diff` and `lint` are on by default. The Action fails the step on a breaking change or a lint finding at or above `--fail-on` (default `warning`, or `failOn` from [`mcpprobe.json`](#config-file-and-ignore-rules) when `fail-on` is empty). +Inputs follow the CLI: `stdio`, `http`, or `from-file` (exactly one), plus `baseline` (default `mcp-tools.json`), `header`, `env`, `cwd`, `timeout`, `diff`, `lint`, `fail-on-non-breaking`, `fail-on`, `nested`, `rule`, `min-description-length`, `strict`, `transport`, `report`, `config`, `lint-baseline`, `version`, and `source`. Both `diff` and `lint` are on by default. The Action fails the step on a breaking change or a lint finding at or above `--fail-on` (default `warning`, or `failOn` from [`mcpprobe.json`](#config-file-and-ignore-rules) when `fail-on` is empty). `strict`, `transport`, and `report` are off by default, so an unchanged workflow runs the same commands as before. `strict` is lint-only. `transport` is only used with `http`. `report` is a directory, not a file: the Action writes `lint.html` and/or `diff.html` there (both checks run by default, so a single file path would overwrite one report with the other). The job summary stays the plain-text report. Upload is left to your workflow. `config` is the path of a [`mcpprobe.json`](#config-file-and-ignore-rules) for lint. Leave it empty and lint finds one on its own, starting in the step's working directory (the repository root after `actions/checkout`), so a committed `mcpprobe.json` is used without any input. `config` needs a CLI that has `--config`, the release after 0.4.0-preview; the Action fails fast with a message if the installed tool lacks it. +`lint-baseline` is passed to lint as `--baseline` (the `baseline` input is the snapshot for `diff`). It overrides `"baseline"` in `mcpprobe.json` and has the same CLI requirement as `config`. There is no input to write a baseline; do that locally and commit the file. + `strict` and `transport` also work against the 0.3.0-preview CLI. `report` needs a CLI that has `--report`, which is 0.4.0-preview or later. If you set `report` and the installed tool lacks the flag, the Action fails fast with a message instead of a generic "unrecognized option". Do not add these inputs to a workflow that pins `ShmueLior/mcpprobe@v0.3.0-preview`; that tag's wrapper does not have them. ```yaml @@ -301,7 +320,7 @@ steps: baseline: mcp-tools.json ``` -The template needs bash (Git Bash on Windows). It also accepts `strict`, `transport`, `report` (a directory, as in the Action) and `config`. Do not add those parameters to a pipeline that pins `refs/tags/v0.3.0-preview`; that tag's template does not have them. Upload is a separate step; the template does not publish an artifact: +The template needs bash (Git Bash on Windows). It also accepts `strict`, `transport`, `report` (a directory, as in the Action), `config` and `lintBaseline`. Do not add those parameters to a pipeline that pins `refs/tags/v0.3.0-preview`; that tag's template does not have them. Upload is a separate step; the template does not publish an artifact: ```yaml - task: PublishPipelineArtifact@1 diff --git a/action.yml b/action.yml index b5a566f..93f6c5d 100644 --- a/action.yml +++ b/action.yml @@ -89,6 +89,13 @@ inputs: that has --config. required: false default: '' + lint-baseline: + description: >- + Path to a lint baseline written by 'mcpprobe lint --write-baseline'. Findings + in it don't fail lint. Not the snapshot (that is baseline). Overrides baseline + in mcpprobe.json. Requires a CLI that has lint --baseline. + required: false + default: '' transport: description: >- Pin the HTTP transport: auto, streamable-http, or sse. Only used with http. @@ -156,6 +163,7 @@ runs: MCPPROBE_MIN_DESCRIPTION_LENGTH: ${{ inputs.min-description-length }} MCPPROBE_STRICT: ${{ inputs.strict }} MCPPROBE_CONFIG: ${{ inputs.config }} + MCPPROBE_LINT_BASELINE: ${{ inputs.lint-baseline }} MCPPROBE_TRANSPORT: ${{ inputs.transport }} MCPPROBE_REPORT: ${{ inputs.report }} MCPPROBE_VERSION: ${{ inputs.version }} diff --git a/action/run.sh b/action/run.sh index 1b27cb1..5e2a652 100755 --- a/action/run.sh +++ b/action/run.sh @@ -275,6 +275,10 @@ config_path=$(trim_ws "${MCPPROBE_CONFIG:-}") if [[ -n "$config_path" && "$run_lint" == true ]]; then require_cli_flag config --config fi +lint_baseline=$(trim_ws "${MCPPROBE_LINT_BASELINE:-}") +if [[ -n "$lint_baseline" && "$run_lint" == true ]]; then + require_cli_flag lint-baseline --baseline +fi if [[ -n "$report_dir" ]]; then mkdir -p "$report_dir" || die "Could not create the report directory '$report_dir'." @@ -344,6 +348,7 @@ if [[ "$run_lint" == true ]]; then done < <(each_nonempty_line "${MCPPROBE_RULE:-}") is_true "${MCPPROBE_STRICT:-}" && lint_args+=(--strict) [[ -n "$config_path" ]] && lint_args+=(--config "$config_path") + [[ -n "$lint_baseline" ]] && lint_args+=(--baseline "$lint_baseline") [[ -n "$report_dir" ]] && lint_args+=(--report "$report_dir/lint.html") lint_exit=0 run_mcpprobe "McpProbe lint" "${lint_args[@]}" || lint_exit=$? diff --git a/docs/mcpprobe.schema.json b/docs/mcpprobe.schema.json index 1125a1d..a51fac8 100644 --- a/docs/mcpprobe.schema.json +++ b/docs/mcpprobe.schema.json @@ -85,6 +85,11 @@ } } } + }, + "baseline": { + "description": "Lint baseline file written by 'mcpprobe lint --write-baseline', relative to this file. Findings in it never fail the run. Same as --baseline, which overrides it.", + "type": "string", + "minLength": 1 } } } diff --git a/samples/WeatherServer.Tests/mcpprobe-lint-baseline.json b/samples/WeatherServer.Tests/mcpprobe-lint-baseline.json new file mode 100644 index 0000000..11b1754 --- /dev/null +++ b/samples/WeatherServer.Tests/mcpprobe-lint-baseline.json @@ -0,0 +1,4 @@ +{ + "formatVersion": 1, + "findings": [] +} diff --git a/src/McpProbe.Cli/CliApp.cs b/src/McpProbe.Cli/CliApp.cs index ce8d9f3..dd08db3 100644 --- a/src/McpProbe.Cli/CliApp.cs +++ b/src/McpProbe.Cli/CliApp.cs @@ -84,20 +84,19 @@ private static Command BuildSnapshotCommand(TextWriter stdout, TextWriter stderr }; /// 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); - } + private static string? ReportPath(ParseResult parse, Option report) => FilePath(parse.GetValue(report), "--report"); + + private static string? FilePath(string? value, string flag) => + value is null ? null : string.IsNullOrWhiteSpace(value) ? throw new ArgumentException($"{flag} 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) + /// Writes through a sibling temp file so a failure never leaves a partial file. + private static async Task WriteFileAtomicAsync(string path, string text, CancellationToken ct) { Directory.CreateDirectory(Path.GetDirectoryName(path)!); var temp = $"{path}.{Guid.NewGuid():N}.tmp"; try { - await File.WriteAllTextAsync(temp, html, ct).ConfigureAwait(false); + await File.WriteAllTextAsync(temp, text, ct).ConfigureAwait(false); File.Move(temp, path, overwrite: true); } finally @@ -142,7 +141,7 @@ private static Command BuildDiffCommand(TextWriter stdout, TextWriter stderr) await stdout.WriteLineAsync(diff.ToReport()).ConfigureAwait(false); if (reportPath is not null) { - await WriteReportAsync(reportPath, diff.ToHtml(), ct).ConfigureAwait(false); + await WriteFileAtomicAsync(reportPath, diff.ToHtml(), ct).ConfigureAwait(false); } if (diff.HasBreakingChanges || (diff.HasChanges && parse.GetValue(failOnNonBreaking))) @@ -192,6 +191,14 @@ private static Command BuildLintCommand(TextWriter stdout, TextWriter stderr, st { Description = $"Don't look for {LintConfig.FileName}.", }; + var baseline = new Option("--baseline") + { + Description = "Hide the findings listed in this lint baseline file, so only new findings fail. Overrides lint.baseline in the config file.", + }; + var writeBaseline = new Option("--write-baseline") + { + Description = "Write every finding to this lint baseline file and exit 0. Run it again to refresh the file.", + }; 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); @@ -202,10 +209,19 @@ private static Command BuildLintCommand(TextWriter stdout, TextWriter stderr, st command.Options.Add(strict); command.Options.Add(config); command.Options.Add(noConfig); + command.Options.Add(baseline); + command.Options.Add(writeBaseline); command.Options.Add(report); command.SetAction((parse, ct) => RunGuardedAsync(stderr, async () => { var reportPath = ReportPath(parse, report); + var writePath = FilePath(parse.GetValue(writeBaseline), "--write-baseline"); + var baselinePath = FilePath(parse.GetValue(baseline), "--baseline"); + if (writePath is not null && baselinePath is not null) + { + throw new ArgumentException("Use either --baseline or --write-baseline, not both."); + } + var options = new LintOptions(); // Library defaults < config file < flags typed on this command line (a flag left at its default doesn't count). @@ -213,7 +229,22 @@ private static Command BuildLintCommand(TextWriter stdout, TextWriter stderr, st if (configPath is not null) { await stderr.WriteLineAsync($"Using config {PrintableLines(configPath)}.").ConfigureAwait(false); - LintConfig.Load(configPath).ApplyTo(options); + var file = LintConfig.Load(configPath); + file.ApplyTo(options); + + // Writing a baseline must see every finding, so the file's baseline is only used for checking. + baselinePath ??= writePath is null ? file.Baseline : null; + } + + if (baselinePath is not null) + { + if (!File.Exists(baselinePath)) + { + await stderr.WriteLineAsync($"Lint baseline not found: {PrintableLines(baselinePath)}. Create it with 'mcpprobe lint --write-baseline '.").ConfigureAwait(false); + return ExitCodes.Error; + } + + options.Baseline = LintBaseline.Load(baselinePath); } if (IsSet(parse, failOn)) @@ -253,7 +284,15 @@ private static Command BuildLintCommand(TextWriter stdout, TextWriter stderr, st await stdout.WriteLineAsync(lint.ToReport()).ConfigureAwait(false); if (reportPath is not null) { - await WriteReportAsync(reportPath, lint.ToHtml(), ct).ConfigureAwait(false); + await WriteFileAtomicAsync(reportPath, lint.ToHtml(), ct).ConfigureAwait(false); + } + + if (writePath is not null) + { + var written = LintBaseline.FromReport(lint); + await WriteFileAtomicAsync(writePath, written.ToJson(), ct).ConfigureAwait(false); + await stdout.WriteLineAsync(string.Create(CultureInfo.InvariantCulture, $"Wrote {written.Entries.Count} finding(s) to {PrintableLines(writePath)}")).ConfigureAwait(false); + return ExitCodes.Success; } return lint.Failed ? ExitCodes.CheckFailed : ExitCodes.Success; diff --git a/src/McpProbe.Cli/LintConfig.cs b/src/McpProbe.Cli/LintConfig.cs index 8a4f044..76b48d3 100644 --- a/src/McpProbe.Cli/LintConfig.cs +++ b/src/McpProbe.Cli/LintConfig.cs @@ -14,7 +14,7 @@ internal sealed class LintConfig public const string FileName = "mcpprobe.json"; public static readonly string[] RootKeys = ["$schema", "lint"]; - public static readonly string[] LintKeys = ["failOn", "strict", "nested", "minDescriptionLength", "minDescriptionWords", "rules", "ignore"]; + public static readonly string[] LintKeys = ["failOn", "strict", "nested", "minDescriptionLength", "minDescriptionWords", "rules", "ignore", "baseline"]; public static readonly string[] IgnoreKeys = ["rule", "tool", "parameter", "reason"]; private static readonly JsonDocumentOptions s_documentOptions = new() { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true }; @@ -35,6 +35,9 @@ internal sealed class LintConfig public IReadOnlyList Ignore { get; private init; } = []; + /// The full path of lint.baseline, resolved against the config file's folder, or null. + public string? Baseline { get; private init; } + /// /// Finds the nearest mcpprobe.json, starting in and going up. The search stops /// after the first directory that has a .git entry (file or folder), so it never leaves the repository. @@ -102,10 +105,13 @@ private static LintConfig ParseNodes(JsonNode? root, string name, string path) MinDescriptionWords = lint.TryGetPropertyValue("minDescriptionWords", out var words) ? AsCount(words, name, "lint.minDescriptionWords") : null, Rules = lint.TryGetPropertyValue("rules", out var rules) ? ParseRules(rules, name) : new Dictionary(), Ignore = lint.TryGetPropertyValue("ignore", out var ignore) ? ParseIgnore(ignore, name) : [], + Baseline = lint.TryGetPropertyValue("baseline", out var baseline) + ? System.IO.Path.GetFullPath(AsString(baseline, name, "lint.baseline"), System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(path))!) + : null, }; } - /// Applies the file over the library defaults. Command-line flags are applied after this, so they win. + /// Applies the file over the library defaults. Command-line flags are applied after this, so they win. is loaded by the caller. public void ApplyTo(LintOptions options) { options.FailOn = FailOn ?? options.FailOn; diff --git a/src/McpProbe/Linting/LintBaseline.cs b/src/McpProbe/Linting/LintBaseline.cs new file mode 100644 index 0000000..e601b96 --- /dev/null +++ b/src/McpProbe/Linting/LintBaseline.cs @@ -0,0 +1,163 @@ +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Nodes; +using McpProbe.Internal; + +namespace McpProbe.Linting; + +/// One accepted finding in a . The message and severity are not part of the key, so a baseline survives wording changes. +/// The rule id, for example MCPP005. +/// The tool name. Compared ordinally. +/// The parameter or schema path, or null for tool-level findings. Compared ordinally. +public sealed record LintBaselineEntry(string RuleId, string ToolName, string? ParameterName = null) +{ + internal static LintBaselineEntry Of(LintFinding finding) => new(finding.RuleId.ToUpperInvariant(), finding.ToolName, finding.ParameterName); + + internal string Describe() => ParameterName is null + ? $"{RuleId} {Printable.Text(ToolName, 100)}" + : $"{RuleId} {Printable.Text(ToolName, 100)}.{Printable.Text(ParameterName, 100)}"; +} + +/// +/// Findings a team accepted at one point in time, usually kept in a committed mcpprobe-lint-baseline.json. +/// Findings in the baseline move to and never fail the report, so only new findings do. +/// +public sealed class LintBaseline +{ + /// The baseline file format version this library writes and reads. + public const int CurrentFormatVersion = 1; + + private static readonly JsonSerializerOptions s_writeOptions = new() + { + WriteIndented = true, + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + }; + + /// Creates a baseline. Rule ids are upper-cased, duplicates are dropped, and entries are sorted by tool, parameter and rule. + /// The accepted findings. + /// An entry is null or has no rule id or tool name. + public LintBaseline(IEnumerable entries) + { + ArgumentNullException.ThrowIfNull(entries); + Entries = entries + .Select(e => e is { RuleId.Length: > 0, ToolName: not null } + ? e with { RuleId = e.RuleId.ToUpperInvariant() } + : throw new ArgumentException("Every baseline entry needs a rule id and a tool name.", nameof(entries))) + .Distinct() + .OrderBy(e => e.ToolName, StringComparer.Ordinal) + .ThenBy(e => e.ParameterName ?? string.Empty, StringComparer.Ordinal) + .ThenBy(e => e.RuleId, StringComparer.Ordinal) + .ToList(); + } + + /// Gets the entries, sorted by tool, parameter and rule. + public IReadOnlyList Entries { get; } + + /// Creates a baseline that accepts every finding in , including ones already baselined. Findings hidden by are not included. + /// A lint report. + /// The baseline. + public static LintBaseline FromReport(LintReport report) + { + ArgumentNullException.ThrowIfNull(report); + return new(report.Findings.Concat(report.BaselinedFindings).Where(f => f.Severity != LintSeverity.None).Select(LintBaselineEntry.Of)); + } + + /// Reads a baseline file. + /// The file path. + /// The baseline. + /// The file is not a valid lint baseline. + public static LintBaseline Load(string path) => Parse(File.ReadAllText(path)); + + /// Parses a baseline file's content. Unknown properties are ignored. + /// The file content. + /// The baseline. + /// The text is not a valid lint baseline. + public static LintBaseline Parse(string json) + { + ArgumentNullException.ThrowIfNull(json); + JsonNode? root; + try + { + root = JsonNode.Parse(json); + } + catch (JsonException ex) + { + throw new FormatException($"The lint baseline is not valid JSON: {ex.Message}", ex); + } + + if (root is not JsonObject obj) + { + throw new FormatException("The lint baseline must be a JSON object."); + } + + if (obj["formatVersion"] is not JsonValue versionNode || !versionNode.TryGetValue(out int version)) + { + throw new FormatException("The lint baseline has no 'formatVersion'."); + } + + if (version != CurrentFormatVersion) + { + throw new FormatException($"Lint baseline format version {version} is not supported. This version of McpProbe reads version {CurrentFormatVersion}."); + } + + if (obj["findings"] is not JsonArray findings) + { + throw new FormatException("The lint baseline has no 'findings' array."); + } + + return new(findings.Select(node => node is JsonObject entry && Text(entry["rule"]) is { Length: > 0 } rule && Text(entry["tool"]) is { } tool && + (entry["parameter"] is null || Text(entry["parameter"]) is not null) + ? new LintBaselineEntry(rule, tool, Text(entry["parameter"])) + : throw new FormatException("Every lint baseline finding needs a 'rule' and a 'tool' string, and 'parameter' must be a string when present."))); + } + + /// Serializes the baseline (indented, LF line endings, sorted), so the file is stable and easy to review. + /// The JSON text, ending with a newline. + public string ToJson() + { + var findings = new JsonArray(); + foreach (var entry in Entries) + { + var node = new JsonObject { ["rule"] = entry.RuleId, ["tool"] = entry.ToolName }; + if (entry.ParameterName is not null) + { + node["parameter"] = entry.ParameterName; + } + + findings.Add(node); + } + + var root = new JsonObject { ["formatVersion"] = CurrentFormatVersion, ["findings"] = findings }; + return root.ToJsonString(s_writeOptions).Replace("\r\n", "\n", StringComparison.Ordinal) + "\n"; + } + + /// + /// Moves the active findings that are in the baseline aside, and lists the entries that matched no finding of this run. + /// An entry is not stale when it could not have matched: its rule did not run, or it is a nested path without nested checks. + /// + internal static (List Active, List Baselined, List Stale) Apply( + List all, List active, LintBaseline? baseline, LintOptions options) + { + if (baseline is null) + { + return (active, [], []); + } + + var accepted = baseline.Entries.ToHashSet(); + var kept = new List(); + var baselined = new List(); + foreach (var finding in active) + { + (accepted.Contains(LintBaselineEntry.Of(finding)) ? baselined : kept).Add(finding); + } + + // Compare with every finding, ignored ones too, so an entry that an ignore rule also covers is not called stale. + var found = all.Select(LintBaselineEntry.Of).ToHashSet(); + var stale = baseline.Entries + .Where(e => !found.Contains(e) && new LintSuppression(e.RuleId, ParameterPattern: e.ParameterName).CouldMatch(options)) + .ToList(); + return (kept, baselined, stale); + } + + private static string? Text(JsonNode? node) => node is JsonValue value && value.TryGetValue(out var text) ? text : null; +} diff --git a/src/McpProbe/Linting/LintOptions.cs b/src/McpProbe/Linting/LintOptions.cs index fa0b499..a6a2b66 100644 --- a/src/McpProbe/Linting/LintOptions.cs +++ b/src/McpProbe/Linting/LintOptions.cs @@ -83,6 +83,12 @@ public sealed class LintOptions /// public IList Suppressions { get; } = new List(); + /// + /// Gets or sets accepted findings, usually loaded with . Findings in it move to + /// and never fail the report. Null (the default) means no baseline. + /// + public LintBaseline? Baseline { get; set; } + internal LintSeverity SeverityOf(LintRule rule) => Severities.TryGetValue(rule.Id, out var severity) ? severity : rule.DefaultSeverity; diff --git a/src/McpProbe/Linting/LintReport.cs b/src/McpProbe/Linting/LintReport.cs index 13b66b6..6b73c30 100644 --- a/src/McpProbe/Linting/LintReport.cs +++ b/src/McpProbe/Linting/LintReport.cs @@ -7,22 +7,30 @@ namespace McpProbe.Linting; /// The findings of a lint run. public sealed class LintReport { - private const int MaxUnusedListed = 20; + private const int MaxListed = 20; internal LintReport(IReadOnlyList findings, LintSeverity failOn) : this(findings, failOn, [], []) { } - internal LintReport(IReadOnlyList findings, LintSeverity failOn, IReadOnlyList suppressed, IReadOnlyList unusedSuppressions) + internal LintReport( + IReadOnlyList findings, + LintSeverity failOn, + IReadOnlyList suppressed, + IReadOnlyList unusedSuppressions, + IReadOnlyList? baselined = null, + IReadOnlyList? staleBaselineEntries = null) { Findings = findings; FailOn = failOn; SuppressedFindings = suppressed; UnusedSuppressions = unusedSuppressions; + BaselinedFindings = baselined ?? []; + StaleBaselineEntries = staleBaselineEntries ?? []; } - /// Gets the findings, most severe first, then by tool, parameter and rule. Findings hidden by are not included. + /// Gets the findings, most severe first, then by tool, parameter and rule. Findings hidden by or are not included. public IReadOnlyList Findings { get; } /// Gets the findings that hid, in the same order as . They never fail the report. @@ -34,6 +42,15 @@ internal LintReport(IReadOnlyList findings, LintSeverity failOn, IR /// public IReadOnlyList UnusedSuppressions { get; } + /// Gets the findings that accepted, in the same order as . They never fail the report. + public IReadOnlyList BaselinedFindings { get; } + + /// + /// Gets the entries of that matched no finding in this run, so the baseline can be refreshed. + /// They never fail the report. Entries for a rule that did not run, or for a nested path without , are not listed. + /// + public IReadOnlyList StaleBaselineEntries { get; } + /// Gets the lowest severity that counts as a failure. public LintSeverity FailOn { get; } @@ -80,14 +97,28 @@ public string ToReport() if (UnusedSuppressions.Count > 0) { sb.Append("\nUnused ignore entries (they matched no finding):"); - foreach (var unused in UnusedSuppressions.Take(MaxUnusedListed)) + foreach (var unused in UnusedSuppressions.Take(MaxListed)) { sb.Append("\n ").Append(unused.Describe()); } - if (UnusedSuppressions.Count > MaxUnusedListed) + if (UnusedSuppressions.Count > MaxListed) + { + sb.Append("\n and ").Append(UnusedSuppressions.Count - MaxListed).Append(" more"); + } + } + + if (StaleBaselineEntries.Count > 0) + { + sb.Append(string.Create(CultureInfo.InvariantCulture, $"\nBaseline: {StaleBaselineEntries.Count} {(StaleBaselineEntries.Count == 1 ? "entry no longer matches" : "entries no longer match")}. Run lint with --write-baseline to refresh.")); + foreach (var stale in StaleBaselineEntries.Take(MaxListed)) + { + sb.Append("\n ").Append(stale.Describe()); + } + + if (StaleBaselineEntries.Count > MaxListed) { - sb.Append("\n and ").Append(UnusedSuppressions.Count - MaxUnusedListed).Append(" more"); + sb.Append("\n and ").Append(StaleBaselineEntries.Count - MaxListed).Append(" more"); } } @@ -138,7 +169,21 @@ private string Summary() => string.Create(CultureInfo.InvariantCulture, private string NoFindings() => HiddenSummary() is { } hidden ? $"No lint findings. ({hidden})" : "No lint findings."; - private string? HiddenSummary() => SuppressedFindings.Count == 0 ? null : string.Create(CultureInfo.InvariantCulture, $"Hidden: {SuppressedFindings.Count} ignored."); + private string? HiddenSummary() + { + var parts = new List(2); + if (BaselinedFindings.Count > 0) + { + parts.Add(string.Create(CultureInfo.InvariantCulture, $"{BaselinedFindings.Count} baselined")); + } + + if (SuppressedFindings.Count > 0) + { + parts.Add(string.Create(CultureInfo.InvariantCulture, $"{SuppressedFindings.Count} ignored")); + } + + return parts.Count == 0 ? null : $"Hidden: {string.Join(", ", parts)}."; + } private int Count(LintSeverity severity) => Findings.Count(f => f.Severity == severity); } diff --git a/src/McpProbe/Linting/ToolLinter.cs b/src/McpProbe/Linting/ToolLinter.cs index e37c3b8..a8ee6d5 100644 --- a/src/McpProbe/Linting/ToolLinter.cs +++ b/src/McpProbe/Linting/ToolLinter.cs @@ -98,7 +98,8 @@ public static LintReport Lint(ToolSurface surface, LintOptions? options = null) findings); var (active, suppressed, unused) = LintSuppression.Apply(findings, options.Suppressions, options); - return new LintReport(Order(active), options.FailOn, Order(suppressed), unused); + var (remaining, baselined, stale) = LintBaseline.Apply(findings, active, options.Baseline, options); + return new LintReport(Order(remaining), options.FailOn, Order(suppressed), unused, Order(baselined), stale); } private static List Order(List findings) => findings diff --git a/src/McpProbe/PublicAPI.Unshipped.txt b/src/McpProbe/PublicAPI.Unshipped.txt index 2d11c2c..8e6dc19 100644 --- a/src/McpProbe/PublicAPI.Unshipped.txt +++ b/src/McpProbe/PublicAPI.Unshipped.txt @@ -48,6 +48,21 @@ McpProbe.Assertions.ToolListAssertions.DoesNotContainTool(string! name) -> McpPr McpProbe.Assertions.ToolListAssertions.HasCount(int expected) -> McpProbe.Assertions.ToolListAssertions! McpProbe.Assertions.ToolListAssertions.PassesLint(McpProbe.Linting.LintOptions? options = null) -> McpProbe.Linting.LintReport! McpProbe.Assertions.ToolListAssertions.Tools.get -> System.Collections.Generic.IReadOnlyList! +McpProbe.Linting.LintBaseline +McpProbe.Linting.LintBaseline.Entries.get -> System.Collections.Generic.IReadOnlyList! +McpProbe.Linting.LintBaseline.LintBaseline(System.Collections.Generic.IEnumerable! entries) -> void +McpProbe.Linting.LintBaseline.ToJson() -> string! +McpProbe.Linting.LintBaselineEntry +McpProbe.Linting.LintBaselineEntry.$() -> McpProbe.Linting.LintBaselineEntry! +McpProbe.Linting.LintBaselineEntry.Deconstruct(out string! RuleId, out string! ToolName, out string? ParameterName) -> void +McpProbe.Linting.LintBaselineEntry.Equals(McpProbe.Linting.LintBaselineEntry? other) -> bool +McpProbe.Linting.LintBaselineEntry.LintBaselineEntry(string! RuleId, string! ToolName, string? ParameterName = null) -> void +McpProbe.Linting.LintBaselineEntry.ParameterName.get -> string? +McpProbe.Linting.LintBaselineEntry.ParameterName.init -> void +McpProbe.Linting.LintBaselineEntry.RuleId.get -> string! +McpProbe.Linting.LintBaselineEntry.RuleId.init -> void +McpProbe.Linting.LintBaselineEntry.ToolName.get -> string! +McpProbe.Linting.LintBaselineEntry.ToolName.init -> void McpProbe.Linting.LintFinding McpProbe.Linting.LintFinding.$() -> McpProbe.Linting.LintFinding! McpProbe.Linting.LintFinding.Deconstruct(out string! RuleId, out McpProbe.Linting.LintSeverity Severity, out string! ToolName, out string? ParameterName, out string! Message) -> void @@ -64,6 +79,8 @@ McpProbe.Linting.LintFinding.Severity.init -> void McpProbe.Linting.LintFinding.ToolName.get -> string! McpProbe.Linting.LintFinding.ToolName.init -> void McpProbe.Linting.LintOptions +McpProbe.Linting.LintOptions.Baseline.get -> McpProbe.Linting.LintBaseline? +McpProbe.Linting.LintOptions.Baseline.set -> void McpProbe.Linting.LintOptions.CheckNestedParameters.get -> bool McpProbe.Linting.LintOptions.CheckNestedParameters.set -> void McpProbe.Linting.LintOptions.DestructiveNameTokens.get -> System.Collections.Generic.ISet! @@ -82,9 +99,11 @@ McpProbe.Linting.LintOptions.StructuredOutputCues.get -> System.Collections.Gene McpProbe.Linting.LintOptions.Suppressions.get -> System.Collections.Generic.IList! McpProbe.Linting.LintOptions.VagueParameterNames.get -> System.Collections.Generic.ISet! McpProbe.Linting.LintReport +McpProbe.Linting.LintReport.BaselinedFindings.get -> System.Collections.Generic.IReadOnlyList! 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.StaleBaselineEntries.get -> System.Collections.Generic.IReadOnlyList! McpProbe.Linting.LintReport.SuppressedFindings.get -> System.Collections.Generic.IReadOnlyList! McpProbe.Linting.LintReport.ThrowIfFailed() -> void McpProbe.Linting.LintReport.ToHtml() -> string! @@ -230,9 +249,13 @@ 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.Linting.LintBaseline.CurrentFormatVersion = 1 -> int const McpProbe.Snapshots.SnapshotOptions.UpdateEnvironmentVariable = "MCPPROBE_UPDATE_SNAPSHOTS" -> string! const McpProbe.Snapshots.ToolSnapshot.DefaultFileName = "mcp-tools.json" -> string! const McpProbe.Snapshots.ToolSurface.CurrentFormatVersion = 1 -> int +override McpProbe.Linting.LintBaselineEntry.Equals(object? obj) -> bool +override McpProbe.Linting.LintBaselineEntry.GetHashCode() -> int +override McpProbe.Linting.LintBaselineEntry.ToString() -> string! override McpProbe.Linting.LintFinding.Equals(object? obj) -> bool override McpProbe.Linting.LintFinding.GetHashCode() -> int override McpProbe.Linting.LintFinding.ToString() -> string! @@ -250,6 +273,11 @@ override McpProbe.Snapshots.ToolSurfaceChange.Equals(object? obj) -> bool override McpProbe.Snapshots.ToolSurfaceChange.GetHashCode() -> int override McpProbe.Snapshots.ToolSurfaceChange.ToString() -> string! override McpProbe.Snapshots.ToolSurfaceDiff.ToString() -> string! +static McpProbe.Linting.LintBaseline.FromReport(McpProbe.Linting.LintReport! report) -> McpProbe.Linting.LintBaseline! +static McpProbe.Linting.LintBaseline.Load(string! path) -> McpProbe.Linting.LintBaseline! +static McpProbe.Linting.LintBaseline.Parse(string! json) -> McpProbe.Linting.LintBaseline! +static McpProbe.Linting.LintBaselineEntry.operator !=(McpProbe.Linting.LintBaselineEntry? left, McpProbe.Linting.LintBaselineEntry? right) -> bool +static McpProbe.Linting.LintBaselineEntry.operator ==(McpProbe.Linting.LintBaselineEntry? left, McpProbe.Linting.LintBaselineEntry? right) -> bool static McpProbe.Linting.LintFinding.operator !=(McpProbe.Linting.LintFinding? left, McpProbe.Linting.LintFinding? right) -> bool static McpProbe.Linting.LintFinding.operator ==(McpProbe.Linting.LintFinding? left, McpProbe.Linting.LintFinding? right) -> bool static McpProbe.Linting.LintRule.operator !=(McpProbe.Linting.LintRule? left, McpProbe.Linting.LintRule? right) -> bool diff --git a/templates/azure-pipelines/mcpprobe.yml b/templates/azure-pipelines/mcpprobe.yml index 712bb1b..d10b78c 100644 --- a/templates/azure-pipelines/mcpprobe.yml +++ b/templates/azure-pipelines/mcpprobe.yml @@ -72,6 +72,9 @@ parameters: - name: config type: string default: '' +- name: lintBaseline + type: string + default: '' - name: transport type: string default: '' @@ -133,6 +136,7 @@ steps: MCPPROBE_MIN_DESCRIPTION_LENGTH: ${{ parameters.minDescriptionLength }} MCPPROBE_STRICT: ${{ parameters.strict }} MCPPROBE_CONFIG: ${{ parameters.config }} + MCPPROBE_LINT_BASELINE: ${{ parameters.lintBaseline }} MCPPROBE_TRANSPORT: ${{ parameters.transport }} MCPPROBE_REPORT: ${{ parameters.report }} MCPPROBE_VERSION: ${{ parameters.version }} diff --git a/tests/McpProbe.Tests/CliLintBaselineTests.cs b/tests/McpProbe.Tests/CliLintBaselineTests.cs new file mode 100644 index 0000000..ea615b5 --- /dev/null +++ b/tests/McpProbe.Tests/CliLintBaselineTests.cs @@ -0,0 +1,154 @@ +using McpProbe.Cli; +using McpProbe.Linting; +using McpProbe.Tests.TestSupport; +using static McpProbe.Tests.TestSupport.SchemaTools; + +namespace McpProbe.Tests; + +public sealed class CliLintBaselineTests : IDisposable +{ + private readonly TempDirectory _dir = new(); + + public CliLintBaselineTests() => Directory.CreateDirectory(_dir.File(".git")); + + public void Dispose() => _dir.Dispose(); + + private string Write(string name, string content) + { + var path = _dir.File(name); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllText(path, content); + return path; + } + + // 21 snake_case tools and 20 camelCase offenders, like a large server with a deliberate legacy convention. + private string Server(params string[] extra) => Write("tools.json", Surface( + [.. Enumerable.Range(0, 21).Select(i => Tool($"get_item_{i:00}")), .. Enumerable.Range(0, 20).Select(i => Tool($"getThing{i:00}")), .. extra.Select(n => Tool(n))]).ToJson()); + + private async Task<(int Exit, string Out, string Err)> LintAsync(params string[] args) + { + using var stdout = new StringWriter(); + using var stderr = new StringWriter(); + var exit = await CliApp.RunAsync(["lint", .. args], stdout, stderr, _dir.Path, TestContext.Current.CancellationToken); + return (exit, stdout.ToString(), stderr.ToString()); + } + + [Fact] + public async Task WriteBaseline_ExitsZero_ThenOnlyNewFindingsFail() + { + var server = Server(); + var baseline = _dir.File(Path.Combine("ci", "mcpprobe-lint-baseline.json")); + var (exit, _, _) = await LintAsync("--from-file", server); + Assert.Equal(1, exit); + + (exit, var output, var error) = await LintAsync("--from-file", server, "--write-baseline", baseline); + Assert.Equal((0, ""), (exit, error)); + Assert.EndsWith($"Wrote 20 finding(s) to {baseline}", output.TrimEnd(), StringComparison.Ordinal); + var written = File.ReadAllText(baseline); + Assert.Equal(written, LintBaseline.Parse(written).ToJson()); + Assert.Empty(Directory.GetFiles(Path.GetDirectoryName(baseline)!, "*.tmp")); + + (exit, output, _) = await LintAsync("--from-file", server, "--baseline", baseline); + Assert.Equal((0, "No lint findings. (Hidden: 20 baselined.)"), (exit, output.TrimEnd())); + + (exit, output, _) = await LintAsync("--from-file", Server("get_item_new", "getNew"), "--baseline", baseline); + Assert.Equal(1, exit); + Assert.StartsWith("1 lint finding(s): 0 error, 1 warning, 0 info.\n warning MCPP005 getNew: ", output, StringComparison.Ordinal); + Assert.Contains("\nHidden: 20 baselined.", output, StringComparison.Ordinal); + } + + [Fact] + public async Task WriteBaseline_RefreshDropsStaleEntries() + { + var baseline = Write("b.json", """{"formatVersion":1,"findings":[{"rule":"MCPP005","tool":"gone"}]}"""); + var server = Server(); + + var (exit, output, _) = await LintAsync("--from-file", server, "--baseline", baseline, "--fail-on", "none"); + Assert.Equal(0, exit); + Assert.Contains("\nBaseline: 1 entry no longer matches. Run lint with --write-baseline to refresh.\n MCPP005 gone", output, StringComparison.Ordinal); + + await LintAsync("--from-file", server, "--write-baseline", baseline); + Assert.DoesNotContain("gone", File.ReadAllText(baseline), StringComparison.Ordinal); + } + + [Fact] + public async Task ConfigBaseline_ResolvesAgainstTheConfigFolder_AndTheFlagWins() + { + var server = Server(); + var config = Write(Path.Combine("lintcfg", "mcpprobe.json"), """{"lint":{"baseline":"accepted.json"}}"""); + await LintAsync("--from-file", server, "--config", config, "--write-baseline", _dir.File(Path.Combine("lintcfg", "accepted.json"))); + + var (exit, output, _) = await LintAsync("--from-file", server, "--config", config); + Assert.Equal((0, "No lint findings. (Hidden: 20 baselined.)"), (exit, output.TrimEnd())); + + var empty = Write("empty.json", """{"formatVersion":1,"findings":[]}"""); + (exit, output, _) = await LintAsync("--from-file", server, "--config", config, "--baseline", empty); + Assert.Equal(1, exit); + Assert.StartsWith("20 lint finding(s)", output, StringComparison.Ordinal); + } + + [Fact] + public async Task WriteBaseline_IgnoresTheConfigBaseline_EvenWhenItDoesNotExistYet() + { + var server = Server(); + var config = Write("mcpprobe.json", """{"lint":{"baseline":"mcpprobe-lint-baseline.json","ignore":[{"tool":"getThing0*"}]}}"""); + + var (exit, output, _) = await LintAsync("--from-file", server, "--write-baseline", _dir.File("mcpprobe-lint-baseline.json")); + + Assert.Equal(0, exit); + Assert.Contains("Wrote 10 finding(s)", output, StringComparison.Ordinal); + Assert.Equal((0, "No lint findings. (Hidden: 10 baselined, 10 ignored.)"), await ExitAndOut(LintAsync("--from-file", server, "--config", config))); + } + + private static async Task<(int, string)> ExitAndOut(Task<(int Exit, string Out, string Err)> run) + { + var (exit, output, _) = await run; + return (exit, output.TrimEnd()); + } + + [Fact] + public async Task BaselineErrors_ExitTwoBeforeConnecting_AndWriteNoReport() + { + var report = _dir.File("lint.html"); + var missing = _dir.File("missing.json"); + + var (exit, output, error) = await LintAsync("--stdio", "does-not-exist-mcpprobe", "--baseline", missing, "--report", report); + Assert.Equal((2, ""), (exit, output)); + Assert.Equal($"Lint baseline not found: {missing}. Create it with 'mcpprobe lint --write-baseline '.", error.TrimEnd()); + + var bad = Write("bad.json", """{"findings":[]}"""); + (exit, _, error) = await LintAsync("--stdio", "does-not-exist-mcpprobe", "--baseline", bad, "--report", report); + Assert.Equal(2, exit); + Assert.Contains("has no 'formatVersion'", error, StringComparison.Ordinal); + + (exit, _, error) = await LintAsync("--stdio", "does-not-exist-mcpprobe", "--baseline", bad, "--write-baseline", missing); + Assert.Equal(2, exit); + Assert.Contains("Use either --baseline or --write-baseline, not both.", error, StringComparison.Ordinal); + + (exit, _, error) = await LintAsync("--stdio", "does-not-exist-mcpprobe", "--write-baseline", " "); + Assert.Equal(2, exit); + Assert.Contains("--write-baseline needs a file path.", error, StringComparison.Ordinal); + + Write("mcpprobe.json", """{"lint":{"baseline":"nope.json"}}"""); + (exit, _, error) = await LintAsync("--stdio", "does-not-exist-mcpprobe"); + Assert.Equal(2, exit); + Assert.Contains($"Lint baseline not found: {_dir.File("nope.json")}.", error, StringComparison.Ordinal); + + Assert.False(File.Exists(report)); + Assert.False(File.Exists(missing)); + } + + [Fact] + public async Task Baseline_WithReport_ShowsHiddenCountInHtml() + { + var server = Server(); + var baseline = _dir.File("b.json"); + await LintAsync("--from-file", server, "--write-baseline", baseline); + var report = _dir.File(Path.Combine("out", "lint.html")); + + var (exit, _, _) = await LintAsync("--from-file", server, "--baseline", baseline, "--report", report); + + Assert.Equal(0, exit); + Assert.Contains("No lint findings. (Hidden: 20 baselined.)", File.ReadAllText(report), StringComparison.Ordinal); + } +} diff --git a/tests/McpProbe.Tests/LintBaselineTests.cs b/tests/McpProbe.Tests/LintBaselineTests.cs new file mode 100644 index 0000000..02c8d71 --- /dev/null +++ b/tests/McpProbe.Tests/LintBaselineTests.cs @@ -0,0 +1,196 @@ +using McpProbe.Linting; +using McpProbe.Tests.TestSupport; +using ModelContextProtocol.Protocol; +using WeatherServer; +using static McpProbe.Tests.TestSupport.SchemaTools; + +namespace McpProbe.Tests; + +public sealed class LintBaselineTests +{ + private const string Undescribed = """{"type":"object","properties":{"city":{"type":"string"}}}"""; + + private static readonly Tool[] Debt = [Tool("get_a"), Tool("get_b"), Tool("get_c"), Tool("getC"), Tool("search", Undescribed, description: "Short.")]; + + private static LintReport Lint(LintBaseline? baseline, params Tool[] tools) => ToolLinter.Lint(tools, new LintOptions { Baseline = baseline }); + + [Fact] + public void Baseline_HidesEveryFindingItWasWrittenFrom_AndOnlyNewOnesFail() + { + var before = Lint(null, Debt); + Assert.True(before.Failed); + var baseline = LintBaseline.FromReport(before); + + var same = Lint(baseline, Debt); + Assert.Empty(same.Findings); + Assert.False(same.Failed); + Assert.Equal(before.Findings, same.BaselinedFindings); + Assert.Empty(same.StaleBaselineEntries); + Assert.Equal("No lint findings. (Hidden: 3 baselined.)", same.ToReport()); + + var added = Lint(baseline, [.. Debt, Tool("getD")]); + var finding = Assert.Single(added.Findings); + Assert.Equal(("MCPP005", "getD"), (finding.RuleId, finding.ToolName)); + Assert.True(added.Failed); + } + + [Fact] + public void Baseline_RenamedToolIsOneNewFindingAndOneStaleEntry() + { + var baseline = LintBaseline.FromReport(Lint(null, Debt)); + var renamed = Debt.Select(t => t.Name == "getC" ? Tool("getX") : t).ToArray(); + + var report = Lint(baseline, renamed); + + Assert.Equal("getX", Assert.Single(report.Findings).ToolName); + Assert.Equal(new LintBaselineEntry("MCPP005", "getC"), Assert.Single(report.StaleBaselineEntries)); + Assert.EndsWith("\nBaseline: 1 entry no longer matches. Run lint with --write-baseline to refresh.\n MCPP005 getC", report.ToReport(), StringComparison.Ordinal); + Assert.Contains("Hidden: 2 baselined.", report.ToReport(), StringComparison.Ordinal); + } + + [Fact] + public void ToJson_IsSortedDedupedAndByteStable() + { + var shuffled = new LintBaseline([new("mcpp003", "b", "x"), new("MCPP002", "b"), new("MCPP005", "a"), new("MCPP003", "b", "x")]); + + Assert.Equal( + "{\n \"formatVersion\": 1,\n \"findings\": [\n {\n \"rule\": \"MCPP005\",\n \"tool\": \"a\"\n },\n" + + " {\n \"rule\": \"MCPP002\",\n \"tool\": \"b\"\n },\n {\n \"rule\": \"MCPP003\",\n \"tool\": \"b\",\n \"parameter\": \"x\"\n }\n ]\n}\n", + shuffled.ToJson()); + Assert.Equal(shuffled.ToJson(), LintBaseline.Parse(shuffled.ToJson()).ToJson()); + Assert.Equal(LintBaseline.FromReport(Lint(null, Debt)).ToJson(), LintBaseline.FromReport(Lint(null, Enumerable.Reverse(Debt).ToArray())).ToJson()); + } + + [Fact] + public void ToJson_RoundTripsOddToolNames() + { + var names = new[] { "quote\"d", "back\\slash", "ünï-cødé_日本", "ctrl\u001b\u0007", new string('x', 5000) }; + var baseline = new LintBaseline(names.Select(n => new LintBaselineEntry("MCPP001", n, n))); + + Assert.Equal(baseline.Entries, LintBaseline.Parse(baseline.ToJson()).Entries); + Assert.DoesNotContain('\u001b', baseline.ToJson()); + + // MCPP004 reports a tool with an empty name, so the file must read back what it wrote. + var empty = LintBaseline.FromReport(Lint(null, Tool(""))); + Assert.Equal(empty.Entries, LintBaseline.Parse(empty.ToJson()).Entries); + Assert.Contains(empty.Entries, e => e is { RuleId: "MCPP004", ToolName: "" }); + } + + [Theory] + [InlineData("", "not valid JSON")] + [InlineData("[]", "must be a JSON object")] + [InlineData("""{"findings":[]}""", "has no 'formatVersion'")] + [InlineData("""{"formatVersion":2,"findings":[]}""", "format version 2 is not supported")] + [InlineData("""{"formatVersion":"1","findings":[]}""", "has no 'formatVersion'")] + [InlineData("""{"formatVersion":1}""", "has no 'findings' array")] + [InlineData("""{"formatVersion":1,"findings":[5]}""", "needs a 'rule' and a 'tool'")] + [InlineData("""{"formatVersion":1,"findings":[{"rule":"MCPP001"}]}""", "needs a 'rule' and a 'tool'")] + [InlineData("""{"formatVersion":1,"findings":[{"rule":"","tool":"a"}]}""", "needs a 'rule' and a 'tool'")] + [InlineData("""{"formatVersion":1,"findings":[{"rule":"MCPP001","tool":"a","parameter":3}]}""", "'parameter' must be a string")] + public void Parse_RejectsBadInput(string json, string message) => + Assert.Contains(message, Assert.Throws(() => LintBaseline.Parse(json)).Message, StringComparison.Ordinal); + + [Fact] + public void Parse_IgnoresUnknownProperties() + { + var baseline = LintBaseline.Parse("""{"formatVersion":1,"note":"x","findings":[{"rule":"mcpp002","tool":"a","message":"old text","severity":"warning"}]}"""); + + Assert.Equal(new LintBaselineEntry("MCPP002", "a"), Assert.Single(baseline.Entries)); + } + + [Fact] + public void Baseline_KeyIgnoresMessageAndSeverity() + { + var tool = Tool("search", description: "Short."); + var baseline = new LintBaseline([new("MCPP002", "search")]); + var options = new LintOptions { Baseline = baseline }; + options.Severities["MCPP002"] = LintSeverity.Error; + + Assert.Single(ToolLinter.Lint([tool], options).BaselinedFindings); + } + + [Fact] + public void StaleEntries_SkipRulesThatDidNotRunAndNestedPathsWithoutNested() + { + var baseline = new LintBaseline( + [ + new("MCPP010", "a", "inputSchema.properties.x"), + new("MCPP003", "a", "address.zip"), + new("MCPP002", "gone"), + ]); + + var defaults = Lint(baseline, Tool("a")); + Assert.Equal([new LintBaselineEntry("MCPP002", "gone")], defaults.StaleBaselineEntries); + + var options = new LintOptions { Baseline = baseline, Strict = true, CheckNestedParameters = true }; + options.Severities["MCPP002"] = LintSeverity.None; + Assert.Equal(["address.zip", "inputSchema.properties.x"], ToolLinter.Lint([Tool("a")], options).StaleBaselineEntries.Select(e => e.ParameterName)); + Assert.False(ToolLinter.Lint([Tool("a")], options).Failed); + } + + [Fact] + public void StaleEntries_AreCappedAt20AndPrintable() + { + var baseline = new LintBaseline(Enumerable.Range(0, 25).Select(i => new LintBaselineEntry("MCPP002", $"gone{i:00}\u001b"))); + + var text = Lint(baseline, Tool("a")).ToReport(); + + Assert.StartsWith("No lint findings.\nBaseline: 25 entries no longer match.", text, StringComparison.Ordinal); + Assert.EndsWith("\n and 5 more", text, StringComparison.Ordinal); + Assert.DoesNotContain('\u001b', text); + Assert.DoesNotContain("gone", Lint(baseline, Tool("a")).ToHtml(), StringComparison.Ordinal); + } + + [Fact] + public void Baseline_AndIgnore_CountSeparately_AndAnIgnoredEntryIsNotStale() + { + var baseline = LintBaseline.FromReport(Lint(null, Debt)); + var options = new LintOptions { Baseline = baseline }; + options.Suppressions.Add(new LintSuppression("MCPP003")); + + var report = ToolLinter.Lint(Debt, options); + + Assert.Equal((2, 1), (report.BaselinedFindings.Count, report.SuppressedFindings.Count)); + Assert.Empty(report.StaleBaselineEntries); + Assert.Equal("No lint findings. (Hidden: 2 baselined, 1 ignored.)", report.ToReport()); + Assert.Contains("Hidden: 2 baselined, 1 ignored.", report.ToHtml(), StringComparison.Ordinal); + + // Ignored findings are policy, not history, so they are not written. + Assert.DoesNotContain(LintBaseline.FromReport(report).Entries, e => e.RuleId == "MCPP003"); + Assert.Equal(3, LintBaseline.FromReport(ToolLinter.Lint(Debt, new LintOptions { Baseline = baseline })).Entries.Count); + } + + [Fact] + public void NoBaseline_ReportIsUnchanged() + { + var report = Lint(null, Debt); + + Assert.Empty(report.BaselinedFindings); + Assert.Empty(report.StaleBaselineEntries); + Assert.Equal(new LintReport(report.Findings, report.FailOn).ToReport(), report.ToReport()); + Assert.Equal(new LintReport(report.Findings, report.FailOn).ToHtml(), report.ToHtml()); + } + + [Fact] + public void Constructor_RejectsEntriesWithoutRuleOrTool() + { + Assert.Throws(() => new LintBaseline([new LintBaselineEntry("", "a")])); + Assert.Throws(() => new LintBaseline([new LintBaselineEntry("MCPP001", null!)])); + Assert.Throws(() => new LintBaseline([null!])); + } + + [Fact] + public async Task Baseline_FlowsThroughTheHostAndEveryOverload() + { + await using var probe = await McpProbeHost.StartAsync(mcp => mcp.WithWeatherFeatures(), TestContext.Current.CancellationToken); + var baseline = new LintBaseline([new("MCPP002", "gone")]); + + var report = await probe.LintToolsAsync(new LintOptions { Baseline = baseline }, TestContext.Current.CancellationToken); + Assert.Single(report.StaleBaselineEntries); + + var tool = Tool("search", description: "Short."); + var options = new LintOptions { Baseline = new LintBaseline([new("MCPP002", "search")]) }; + Assert.False(ToolLinter.Lint([tool], options).Failed); + Assert.False(ToolLinter.Lint(Surface(tool), options).Failed); + } +} diff --git a/tests/McpProbe.Tests/LintConfigTests.cs b/tests/McpProbe.Tests/LintConfigTests.cs index 7e44aea..46db396 100644 --- a/tests/McpProbe.Tests/LintConfigTests.cs +++ b/tests/McpProbe.Tests/LintConfigTests.cs @@ -110,7 +110,7 @@ public void ApplyTo_OverridesTheDefaultsAndAddsRulesAndSuppressions() [InlineData("""{"lnt":{}}""", "mcpprobe.json: unknown key 'lnt'. Keys: $schema, lint.")] [InlineData("""{"$schema":5}""", "mcpprobe.json: $schema: expected a non-empty string.")] [InlineData("""{"lint":null}""", "mcpprobe.json: lint: expected a JSON object.")] - [InlineData("""{"lint":{"baseline":"x.json"}}""", "mcpprobe.json: lint: unknown key 'baseline'.")] + [InlineData("""{"lint":{"baseline":""}}""", "mcpprobe.json: lint.baseline: expected a non-empty string.")] [InlineData("""{"lint":{"FailOn":"error"}}""", "mcpprobe.json: lint: unknown key 'FailOn'.")] [InlineData("""{"lint":{"failOn":"loud"}}""", "mcpprobe.json: lint.failOn: unknown severity 'loud'. Use none, info, warning, error.")] [InlineData("""{"lint":{"failOn":3}}""", "mcpprobe.json: lint.failOn: expected a non-empty string.")] @@ -220,6 +220,7 @@ public void KnownKeys_MatchWhatTheLoaderAccepts() "strict" or "nested" => true, "minDescriptionLength" or "minDescriptionWords" => 1, "rules" => new JsonObject(), + "baseline" => "mcpprobe-lint-baseline.json", _ => new JsonArray(), }; }