diff --git a/CHANGELOG.md b/CHANGELOG.md index 1572790..2551d15 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,9 @@ All notable changes to this project are documented here. The format is based on ### Added +- `--format text|json|sarif` on `lint` and `diff` picks the stdout format. `json` is the McpProbe report format (format 1, see `docs/mcpprobe-report.schema.json`), `sarif` is SARIF 2.1.0. The default is still `text`. +- `--sarif ` on `lint` and `diff` also writes a SARIF 2.1.0 file, like `--report`. In SARIF, each result points at the baseline or `--from-file` snapshot (default `mcp-tools.json`) and has a stable fingerprint for GitHub code scanning. +- `LintReport.ToJson()` and `ToSarif()`, and `ToolSurfaceDiff.ToJson()` and `ToSarif()` in the library. - `--bearer-env ` and `--header-env 'Name: VAR'` on the CLI: HTTP authentication read from environment variables, so tokens are not on the command line. Later sources win for the same header name (`--header`, then `--header-env`, then `--bearer-env`). A missing or empty variable is exit 2 and names the variable, not the value. GitHub Action inputs `bearer-env` and `header-env`, and Azure Pipelines parameters `bearerEnv` and `headerEnv`, pass the variable names through. They need a CLI that has these flags. - `McpProbeHostOptions.IncludeServerExceptions` (default `true`): in the in-memory host, when a tool throws an exception that is not an `McpException`, the tool error result shows the exception type and message (for example `An error occurred invoking 'update_todo_item': FormatException: ...`) instead of the SDK's generic message, `An error occurred invoking 'update_todo_item'.` Prompts and resources that throw are reported the same way. Set it to `false` for the generic text a remote client would see. - `ToolSurfaceChange.Before` and `After` hold the previous and current title or description when that is what changed. Other change kinds leave them unset. diff --git a/Directory.Packages.props b/Directory.Packages.props index 9ee9547..657c4de 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -11,5 +11,6 @@ + diff --git a/README.md b/README.md index ecb3029..f367ec6 100644 --- a/README.md +++ b/README.md @@ -224,6 +224,37 @@ The `mcpprobe` tool is packed for net8.0 and net10.0 (`RollForward=Major`), so a 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. To compare two snapshots, use `mcpprobe diff --baseline old.json --from-file new.json`. Run `mcpprobe --help` for every option. +### JSON and SARIF output + +`lint` and `diff` take `--format text|json|sarif` to choose what goes to stdout. The default is `text`, so nothing changes unless you pass the flag. `--format json` writes the [McpProbe report format](docs/mcpprobe-report.schema.json) (format 1): a summary with counts, then the findings or changes. For title and description changes, a diff change also has `before` and `after`. `--format sarif` writes a [SARIF 2.1.0](https://docs.oasis-open.org/sarif/sarif/v2.1.0/sarif-v2.1.0.html) log. + +`--sarif ` is the SARIF version of `--report`: it writes the SARIF file and leaves stdout and the exit code alone. You can combine it with `--format` and `--report`. Like `--report`, nothing is written on a usage or connection error (exit `2`). + +```bash +mcpprobe lint --stdio "dotnet run --project src/MyServer" --format json +mcpprobe diff --stdio "dotnet run --project src/MyServer" --baseline mcp-tools.json --sarif mcp-diff.sarif +``` + +With `--format json` or `--format sarif`, stdout holds exactly one document. The `diff` hint ("If the change is intended, ...") and the lint `--write-baseline` line ("Wrote N finding(s) to ...") go to stderr instead. Exit codes don't change. The JSON `result` is `fail` when the command exits `1` and `pass` when it exits `0`, so `--fail-on-non-breaking` and `--write-baseline` are reflected there. + +SARIF levels: lint errors are `error`, warnings are `warning`, info is `note`. Diff breaking changes are `error`, non-breaking changes are `note`. Lint rules keep their `MCPP0xx` ids; diff change kinds use kebab-case ids such as `tool-removed` or `description-changed`. Every result has a `partialFingerprints.primaryLocationLineHash` computed from the rule id, tool and path, so GitHub code scanning recognizes the same alert from run to run even when the snapshot is rewritten. When several results share the same rule, tool and path (for example allowed values removed and added on one parameter), they get `:1`, `:2` and so on in the order they appear, like GitHub's own fingerprints. + +Each SARIF result points at a file in the repository, because GitHub doesn't display results without one. `diff` uses `--baseline` and `lint` uses `--from-file`, relative to the working directory with forward slashes. If that path is outside the working directory, only the file name is used. When lint reads a live server, the default is `mcp-tools.json`, so in CI run lint from the repo root or pass a real `--from-file` snapshot. Run `diff` from the repo root too, so the `--baseline` artifact path is relative to the repository root and GitHub can resolve it. + +To send the file to GitHub code scanning, upload it in your own workflow (the McpProbe Action doesn't upload SARIF yet): + +```yaml + - run: mcpprobe lint --stdio "dotnet run --project src/MyServer" --sarif mcp-lint.sarif + - uses: github/codeql-action/upload-sarif@v3 + if: always() + with: + sarif_file: mcp-lint.sarif +``` + +One limitation: GitHub shows PR annotations only for alerts whose file lines changed in that PR. A finding on a live server, or a tool-surface change whose `mcp-tools.json` line didn't move, still shows up in the repository's code scanning alerts, but it may not annotate the PR diff. The text output in the job summary and the HTML report stay the best view of a PR. + +In code, use `LintReport.ToJson()`, `LintReport.ToSarif(artifactUri)`, `ToolSurfaceDiff.ToJson(failOnNonBreakingChanges)` and `ToolSurfaceDiff.ToSarif(artifactUri)`. + ### 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, when there are findings or changes, a table. 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()`. diff --git a/docs/mcpprobe-report.schema.json b/docs/mcpprobe-report.schema.json new file mode 100644 index 0000000..7fa8ce3 --- /dev/null +++ b/docs/mcpprobe-report.schema.json @@ -0,0 +1,117 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://raw.githubusercontent.com/ShmueLior/mcpprobe/main/docs/mcpprobe-report.schema.json", + "title": "McpProbe JSON report", + "description": "Output of 'mcpprobe lint --format json' and 'mcpprobe diff --format json', and of LintReport.ToJson() and ToolSurfaceDiff.ToJson(). Fields may be added in later versions; formatVersion changes only on a breaking change to this shape.", + "oneOf": [ + { "$ref": "#/$defs/lint" }, + { "$ref": "#/$defs/diff" } + ], + "$defs": { + "tool": { + "type": "object", + "additionalProperties": false, + "required": ["name", "version"], + "properties": { + "name": { "const": "McpProbe" }, + "version": { "description": "The McpProbe package version, without build metadata.", "type": "string" } + } + }, + "result": { + "description": "Whether the command exited 1 (fail) or 0 (pass).", + "enum": ["pass", "fail"] + }, + "lint": { + "type": "object", + "additionalProperties": false, + "required": ["formatVersion", "kind", "tool", "result", "summary", "findings"], + "properties": { + "formatVersion": { "const": 1 }, + "kind": { "const": "lint" }, + "tool": { "$ref": "#/$defs/tool" }, + "result": { "$ref": "#/$defs/result" }, + "summary": { + "type": "object", + "additionalProperties": false, + "required": ["findings", "error", "warning", "info", "hiddenIgnored", "hiddenBaselined", "unusedIgnore", "staleBaseline", "failOn"], + "properties": { + "findings": { "type": "integer", "minimum": 0 }, + "error": { "type": "integer", "minimum": 0 }, + "warning": { "type": "integer", "minimum": 0 }, + "info": { "type": "integer", "minimum": 0 }, + "hiddenIgnored": { "description": "Findings hidden by ignore entries.", "type": "integer", "minimum": 0 }, + "hiddenBaselined": { "description": "Findings hidden by the lint baseline.", "type": "integer", "minimum": 0 }, + "unusedIgnore": { "description": "Ignore entries that matched nothing.", "type": "integer", "minimum": 0 }, + "staleBaseline": { "description": "Lint baseline entries that no longer match.", "type": "integer", "minimum": 0 }, + "failOn": { "$ref": "#/$defs/lintSeverity" } + } + }, + "findings": { + "description": "The visible findings, most severe first. Hidden findings are only counted in the summary.", + "type": "array", + "items": { "$ref": "#/$defs/finding" } + } + } + }, + "lintSeverity": { "enum": ["none", "info", "warning", "error"] }, + "finding": { + "type": "object", + "additionalProperties": false, + "required": ["ruleId", "severity", "tool", "message", "failsTheRun"], + "properties": { + "ruleId": { "type": "string", "pattern": "^MCPP[0-9]{3}$" }, + "severity": { "enum": ["info", "warning", "error"] }, + "tool": { "type": "string" }, + "path": { "description": "The parameter or schema path. Omitted for tool-level findings.", "type": "string" }, + "message": { "type": "string" }, + "failsTheRun": { "type": "boolean" } + } + }, + "diff": { + "type": "object", + "additionalProperties": false, + "required": ["formatVersion", "kind", "tool", "result", "summary", "changes"], + "properties": { + "formatVersion": { "const": 1 }, + "kind": { "const": "diff" }, + "tool": { "$ref": "#/$defs/tool" }, + "result": { "$ref": "#/$defs/result" }, + "summary": { + "type": "object", + "additionalProperties": false, + "required": ["changes", "breaking", "nonBreaking"], + "properties": { + "changes": { "type": "integer", "minimum": 0 }, + "breaking": { "type": "integer", "minimum": 0 }, + "nonBreaking": { "type": "integer", "minimum": 0 } + } + }, + "changes": { + "description": "Every change, breaking first.", + "type": "array", + "items": { "$ref": "#/$defs/change" } + } + } + }, + "change": { + "type": "object", + "additionalProperties": false, + "required": ["tool", "kind", "severity", "message"], + "properties": { + "tool": { "type": "string" }, + "path": { "description": "Where in the tool, for example input.city. Omitted for tool-level changes.", "type": "string" }, + "kind": { + "enum": [ + "tool-added", "tool-removed", "title-changed", "description-changed", "annotations-changed", + "property-added", "property-removed", "became-required", "became-optional", "type-changed", + "enum-changed", "output-schema-added", "output-schema-removed", "keyword-changed", "constraint-changed" + ] + }, + "severity": { "enum": ["breaking", "nonBreaking"] }, + "message": { "type": "string" }, + "before": { "description": "The previous title or description. Only for title-changed and description-changed; omitted when there was none.", "type": "string" }, + "after": { "description": "The current title or description. Only for title-changed and description-changed; omitted when there is none.", "type": "string" } + } + } + } +} diff --git a/src/McpProbe.Cli/CliApp.cs b/src/McpProbe.Cli/CliApp.cs index dd08db3..adc0825 100644 --- a/src/McpProbe.Cli/CliApp.cs +++ b/src/McpProbe.Cli/CliApp.cs @@ -43,7 +43,7 @@ private static RootCommand BuildRootCommand(TextWriter stdout, TextWriter stderr var root = new RootCommand("Check an MCP server's tool surface: snapshot it, diff it against a committed snapshot, and lint it.") { BuildSnapshotCommand(stdout, stderr), - BuildDiffCommand(stdout, stderr), + BuildDiffCommand(stdout, stderr, workingDirectory), BuildLintCommand(stdout, stderr, workingDirectory), }; return root; @@ -83,6 +83,32 @@ private static Command BuildSnapshotCommand(TextWriter stdout, TextWriter stderr Description = "Also write a self-contained HTML report to this file. stdout and the exit code are unchanged.", }; + internal static readonly string[] FormatNames = ["text", "json", "sarif"]; + + private static Option BuildFormatOption() + { + var option = new Option("--format") + { + Description = "Output on stdout: text (default), json (McpProbe report format) or sarif (SARIF 2.1.0).", + DefaultValueFactory = _ => "text", + }; + option.AcceptOnlyFromAmong(FormatNames); + return option; + } + + private static Option BuildSarifOption() => new("--sarif") + { + Description = "Also write a SARIF 2.1.0 file here, for tools such as GitHub code scanning. stdout and the exit code are unchanged.", + }; + + /// Writes the chosen format to stdout. Machine-readable output already ends with a newline, so it is written as is. + private static Task WriteOutputAsync(TextWriter stdout, string format, string text, string json, string sarif) => format switch + { + "json" => stdout.WriteAsync(json), + "sarif" => stdout.WriteAsync(sarif), + _ => stdout.WriteLineAsync(text), + }; + /// A blank --report is a usage error; checked before connecting so nothing is written. private static string? ReportPath(ParseResult parse, Option report) => FilePath(parse.GetValue(report), "--report"); @@ -105,7 +131,7 @@ private static async Task WriteFileAtomicAsync(string path, string text, Cancell } } - private static Command BuildDiffCommand(TextWriter stdout, TextWriter stderr) + private static Command BuildDiffCommand(TextWriter stdout, TextWriter stderr, string? workingDirectory) { var server = new ServerOptions(allowFile: true); var baseline = new Option("--baseline", "-b") @@ -119,15 +145,21 @@ private static Command BuildDiffCommand(TextWriter stdout, TextWriter stderr) }; var report = BuildReportOption(); + var format = BuildFormatOption(); + var sarif = BuildSarifOption(); 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.Options.Add(format); + command.Options.Add(sarif); command.SetAction((parse, ct) => RunGuardedAsync(stderr, async () => { var reportPath = ReportPath(parse, report); + var sarifPath = FilePath(parse.GetValue(sarif), "--sarif"); + var outputFormat = parse.GetValue(format)!; var baselinePath = Path.GetFullPath(parse.GetValue(baseline)!); if (!File.Exists(baselinePath)) { @@ -138,15 +170,38 @@ private static Command BuildDiffCommand(TextWriter stdout, TextWriter stderr) var expected = ToolSurface.Parse(await File.ReadAllTextAsync(baselinePath, ct).ConfigureAwait(false)); var current = await server.CaptureAsync(parse, stderr, ct).ConfigureAwait(false); var diff = ToolSurfaceComparer.Compare(expected, current); - await stdout.WriteLineAsync(diff.ToReport()).ConfigureAwait(false); + var failNonBreaking = parse.GetValue(failOnNonBreaking); + var failed = diff.HasBreakingChanges || (diff.HasChanges && failNonBreaking); + var artifact = SarifArtifact.Resolve(baselinePath, workingDirectory); + var sarifText = outputFormat == "sarif" || sarifPath is not null ? diff.ToSarif(artifact) : string.Empty; + await WriteOutputAsync( + stdout, + outputFormat, + diff.ToReport(), + outputFormat == "json" ? diff.ToJson(failNonBreaking) : string.Empty, + sarifText).ConfigureAwait(false); if (reportPath is not null) { await WriteFileAtomicAsync(reportPath, diff.ToHtml(), ct).ConfigureAwait(false); } - if (diff.HasBreakingChanges || (diff.HasChanges && parse.GetValue(failOnNonBreaking))) + if (sarifPath is not null) { - await stdout.WriteLineAsync("\nIf the change is intended, update the snapshot with 'mcpprobe snapshot' and commit it.").ConfigureAwait(false); + await WriteFileAtomicAsync(sarifPath, sarifText, ct).ConfigureAwait(false); + } + + if (failed) + { + const string hint = "If the change is intended, update the snapshot with 'mcpprobe snapshot' and commit it."; + if (outputFormat == "text") + { + await stdout.WriteLineAsync("\n" + hint).ConfigureAwait(false); + } + else + { + await stderr.WriteLineAsync(hint).ConfigureAwait(false); + } + return ExitCodes.CheckFailed; } @@ -200,6 +255,8 @@ private static Command BuildLintCommand(TextWriter stdout, TextWriter stderr, st Description = "Write every finding to this lint baseline file and exit 0. Run it again to refresh the file.", }; var report = BuildReportOption(); + var format = BuildFormatOption(); + var sarif = BuildSarifOption(); 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); @@ -212,9 +269,13 @@ private static Command BuildLintCommand(TextWriter stdout, TextWriter stderr, st command.Options.Add(baseline); command.Options.Add(writeBaseline); command.Options.Add(report); + command.Options.Add(format); + command.Options.Add(sarif); command.SetAction((parse, ct) => RunGuardedAsync(stderr, async () => { var reportPath = ReportPath(parse, report); + var sarifPath = FilePath(parse.GetValue(sarif), "--sarif"); + var outputFormat = parse.GetValue(format)!; var writePath = FilePath(parse.GetValue(writeBaseline), "--write-baseline"); var baselinePath = FilePath(parse.GetValue(baseline), "--baseline"); if (writePath is not null && baselinePath is not null) @@ -281,17 +342,30 @@ private static Command BuildLintCommand(TextWriter stdout, TextWriter stderr, st var surface = await server.CaptureAsync(parse, stderr, ct).ConfigureAwait(false); var lint = ToolLinter.Lint(surface, options); - await stdout.WriteLineAsync(lint.ToReport()).ConfigureAwait(false); + var artifact = SarifArtifact.Resolve(server.FromFilePath(parse), workingDirectory); + var sarifText = outputFormat == "sarif" || sarifPath is not null ? lint.ToSarif(artifact) : string.Empty; + await WriteOutputAsync( + stdout, + outputFormat, + lint.ToReport(), + outputFormat == "json" ? lint.ToJson(writePath is null && lint.Failed) : string.Empty, + sarifText).ConfigureAwait(false); if (reportPath is not null) { await WriteFileAtomicAsync(reportPath, lint.ToHtml(), ct).ConfigureAwait(false); } + if (sarifPath is not null) + { + await WriteFileAtomicAsync(sarifPath, sarifText, 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); + var wrote = string.Create(CultureInfo.InvariantCulture, $"Wrote {written.Entries.Count} finding(s) to {PrintableLines(writePath)}"); + await (outputFormat == "text" ? stdout : stderr).WriteLineAsync(wrote).ConfigureAwait(false); return ExitCodes.Success; } diff --git a/src/McpProbe.Cli/SarifArtifact.cs b/src/McpProbe.Cli/SarifArtifact.cs new file mode 100644 index 0000000..dd2661d --- /dev/null +++ b/src/McpProbe.Cli/SarifArtifact.cs @@ -0,0 +1,41 @@ +namespace McpProbe.Cli; + +/// +/// Picks the file a SARIF result points at and makes it relative to the working directory, so GitHub code scanning +/// can match it to a file in the repository. +/// +internal static class SarifArtifact +{ + /// + /// For diff, the baseline snapshot; for lint, the --from-file snapshot. Null (a live server) + /// gives mcp-tools.json. A path under the working directory becomes relative with forward slashes; a path + /// outside it keeps only its file name. + /// + public static string Resolve(string? path, string? workingDirectory = null) + { + if (string.IsNullOrWhiteSpace(path)) + { + return "mcp-tools.json"; + } + + try + { + var root = Path.GetFullPath(workingDirectory ?? Directory.GetCurrentDirectory()); + var full = Path.GetFullPath(path, root); + var relative = Path.GetRelativePath(root, full); + if (Path.IsPathRooted(relative) || relative == ".." || + relative.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal) || + relative.StartsWith("../", StringComparison.Ordinal)) + { + var name = Path.GetFileName(full); + return name.Length == 0 ? "mcp-tools.json" : name; + } + + return relative.Replace('\\', '/'); + } + catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException or IOException) + { + return "mcp-tools.json"; + } + } +} diff --git a/src/McpProbe.Cli/ServerOptions.cs b/src/McpProbe.Cli/ServerOptions.cs index 66e9a31..49eb1b1 100644 --- a/src/McpProbe.Cli/ServerOptions.cs +++ b/src/McpProbe.Cli/ServerOptions.cs @@ -125,6 +125,9 @@ public void AddTo(Command command) }); } + /// The --from-file snapshot path as typed, or null when the surface comes from a server. + internal string? FromFilePath(ParseResult parse) => _file is null ? null : parse.GetValue(_file); + public async Task CaptureAsync(ParseResult parse, TextWriter stderr, CancellationToken cancellationToken) { if (_file is not null && parse.GetValue(_file) is { } file) diff --git a/src/McpProbe/Internal/MachineReadableOutput.cs b/src/McpProbe/Internal/MachineReadableOutput.cs new file mode 100644 index 0000000..c2bb045 --- /dev/null +++ b/src/McpProbe/Internal/MachineReadableOutput.cs @@ -0,0 +1,344 @@ +using System.Globalization; +using System.Security.Cryptography; +using System.Text; +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Nodes; +using McpProbe.Linting; +using McpProbe.Snapshots; + +namespace McpProbe.Internal; + +/// +/// JSON (McpProbe report format 1) and SARIF 2.1.0 renderings of a lint report or a tool-surface diff. +/// Text values are written raw and escaped once by the JSON writer, so no value is escaped twice. +/// +internal static class MachineReadableOutput +{ + public const int ReportFormatVersion = 1; + + /// The snapshot file a SARIF result points at when the caller doesn't name one. + public const string DefaultArtifactUri = "mcp-tools.json"; + + private const string SarifSchema = "https://json.schemastore.org/sarif-2.1.0.json"; + private const string ProjectUrl = "https://github.com/ShmueLior/mcpprobe"; + private const int MaxTextLength = 2000; + + private static readonly JsonSerializerOptions s_writeOptions = new() + { + WriteIndented = true, + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + }; + + // Short descriptions for the diff change kinds, used as SARIF rules. The ids are stable and kebab-case. + private static readonly (ToolSurfaceChangeKind Kind, string Description)[] s_changeKinds = + [ + (ToolSurfaceChangeKind.ToolAdded, "Tool was added"), + (ToolSurfaceChangeKind.ToolRemoved, "Tool was removed"), + (ToolSurfaceChangeKind.TitleChanged, "Tool title changed"), + (ToolSurfaceChangeKind.DescriptionChanged, "Tool or property description changed"), + (ToolSurfaceChangeKind.AnnotationsChanged, "Tool behavior hints changed"), + (ToolSurfaceChangeKind.PropertyAdded, "Parameter or output property was added"), + (ToolSurfaceChangeKind.PropertyRemoved, "Parameter or output property was removed"), + (ToolSurfaceChangeKind.BecameRequired, "Parameter or output property became required"), + (ToolSurfaceChangeKind.BecameOptional, "Parameter or output property became optional"), + (ToolSurfaceChangeKind.TypeChanged, "Schema type changed"), + (ToolSurfaceChangeKind.EnumChanged, "Allowed values (enum) changed"), + (ToolSurfaceChangeKind.OutputSchemaAdded, "Output schema was added"), + (ToolSurfaceChangeKind.OutputSchemaRemoved, "Output schema was removed"), + (ToolSurfaceChangeKind.KeywordChanged, "Unclassified JSON Schema keyword changed"), + (ToolSurfaceChangeKind.ConstraintChanged, "Schema constraint changed"), + ]; + + public static string LintJson(LintReport report, bool failed) + { + var summary = new JsonObject + { + ["findings"] = report.Findings.Count, + ["error"] = Count(report, LintSeverity.Error), + ["warning"] = Count(report, LintSeverity.Warning), + ["info"] = Count(report, LintSeverity.Info), + ["hiddenIgnored"] = report.SuppressedFindings.Count, + ["hiddenBaselined"] = report.BaselinedFindings.Count, + ["unusedIgnore"] = report.UnusedSuppressions.Count, + ["staleBaseline"] = report.StaleBaselineEntries.Count, + ["failOn"] = LintFinding.SeverityLabel(report.FailOn), + }; + + var findings = new JsonArray(); + foreach (var finding in report.Findings) + { + var node = new JsonObject + { + ["ruleId"] = finding.RuleId, + ["severity"] = LintFinding.SeverityLabel(finding.Severity), + ["tool"] = finding.ToolName, + }; + AddIfPresent(node, "path", finding.ParameterName); + node["message"] = finding.Message; + node["failsTheRun"] = report.FindingFails(finding); + findings.Add(node); + } + + var root = Envelope("lint", failed); + root["summary"] = summary; + root["findings"] = findings; + return Serialize(root); + } + + public static string DiffJson(ToolSurfaceDiff diff, bool failed) + { + var summary = new JsonObject + { + ["changes"] = diff.Changes.Count, + ["breaking"] = diff.BreakingChanges.Count(), + ["nonBreaking"] = diff.NonBreakingChanges.Count(), + }; + + var changes = new JsonArray(); + foreach (var change in diff.Changes) + { + var node = new JsonObject { ["tool"] = change.ToolName }; + AddIfPresent(node, "path", change.Path); + node["kind"] = ChangeKindId(change.Kind); + node["severity"] = ChangeSeverityLabel(change.Severity); + node["message"] = change.Message; + AddIfPresent(node, "before", change.Before is null ? null : Printable.Truncate(change.Before, MaxTextLength)); + AddIfPresent(node, "after", change.After is null ? null : Printable.Truncate(change.After, MaxTextLength)); + changes.Add(node); + } + + var root = Envelope("diff", failed); + root["summary"] = summary; + root["changes"] = changes; + return Serialize(root); + } + + public static string LintSarif(LintReport report, string? artifactUri) + { + var rules = new JsonArray(); + foreach (var rule in LintRules.All) + { + rules.Add(Rule(rule.Id, rule.Title, LintLevel(rule.DefaultSeverity))); + } + + var results = new JsonArray(); + var occurrences = new Dictionary<(string, string, string), int>(); + foreach (var finding in report.Findings) + { + results.Add(Result(finding.RuleId, LintLevel(finding.Severity), finding.Message, finding.ToolName, finding.ParameterName, artifactUri, occurrences)); + } + + return Serialize(SarifLog(rules, results)); + } + + public static string DiffSarif(ToolSurfaceDiff diff, string? artifactUri) + { + var rules = new JsonArray(); + foreach (var (kind, description) in s_changeKinds) + { + // A rule's default level is only a fallback; each result sets its own level from the change's severity. + rules.Add(Rule(ChangeKindId(kind), description, "warning")); + } + + var results = new JsonArray(); + var occurrences = new Dictionary<(string, string, string), int>(); + foreach (var change in diff.Changes) + { + var result = Result( + ChangeKindId(change.Kind), + change.IsBreaking ? "error" : "note", + change.Message, + change.ToolName, + change.Path, + artifactUri, + occurrences); + + var properties = new JsonObject(); + if (change.Before is not null) + { + properties["before"] = Printable.Truncate(change.Before, MaxTextLength); + } + + if (change.After is not null) + { + properties["after"] = Printable.Truncate(change.After, MaxTextLength); + } + + if (properties.Count > 0) + { + result["properties"] = properties; + } + + results.Add(result); + } + + return Serialize(SarifLog(rules, results)); + } + + /// Stable kebab-case id of a change kind, for example description-changed. + public static string ChangeKindId(ToolSurfaceChangeKind kind) + { + var name = kind.ToString(); + var sb = new StringBuilder(name.Length + 4); + for (var i = 0; i < name.Length; i++) + { + if (i > 0 && char.IsUpper(name[i])) + { + sb.Append('-'); + } + + sb.Append(char.ToLowerInvariant(name[i])); + } + + return sb.ToString(); + } + + private static JsonObject Envelope(string kind, bool failed) => new() + { + ["formatVersion"] = ReportFormatVersion, + ["kind"] = kind, + ["tool"] = new JsonObject + { + ["name"] = "McpProbe", + ["version"] = ProductVersion.Value, + }, + ["result"] = failed ? "fail" : "pass", + }; + + private static JsonObject SarifLog(JsonArray rules, JsonArray results) => new() + { + ["$schema"] = SarifSchema, + ["version"] = "2.1.0", + ["runs"] = new JsonArray + { + new JsonObject + { + ["tool"] = new JsonObject + { + ["driver"] = new JsonObject + { + ["name"] = "McpProbe", + ["version"] = ProductVersion.Value, + ["semanticVersion"] = ProductVersion.Value, + ["informationUri"] = ProjectUrl, + ["rules"] = rules, + }, + }, + ["results"] = results, + }, + }, + }; + + private static JsonObject Rule(string id, string description, string level) => new() + { + ["id"] = id, + ["name"] = id, + ["shortDescription"] = new JsonObject { ["text"] = description }, + ["defaultConfiguration"] = new JsonObject { ["level"] = level }, + ["properties"] = new JsonObject { ["tags"] = new JsonArray("mcp", "tools") }, + }; + + private static JsonObject Result(string ruleId, string level, string message, string tool, string? path, string? artifactUri, Dictionary<(string, string, string), int> occurrences) => new() + { + ["ruleId"] = ruleId, + ["level"] = level, + ["message"] = new JsonObject { ["text"] = message }, + ["locations"] = new JsonArray + { + new JsonObject + { + ["physicalLocation"] = new JsonObject + { + ["artifactLocation"] = new JsonObject { ["uri"] = ArtifactUri(artifactUri) }, + }, + ["logicalLocations"] = new JsonArray + { + new JsonObject { ["fullyQualifiedName"] = LogicalName(tool, path) }, + }, + }, + }, + ["partialFingerprints"] = new JsonObject + { + ["primaryLocationLineHash"] = Fingerprint(ruleId, tool, path, occurrences), + }, + }; + + /// + /// A stable fingerprint of the finding's identity (rule, tool, path), not of the file contents or the message, + /// so GitHub code scanning matches the same alert across runs even when the snapshot is rewritten. + /// + private static string Fingerprint(string ruleId, string tool, string? path, Dictionary<(string, string, string), int> occurrences) + { + // One diff can report several changes with the same kind, tool and path (allowed values removed and added, + // or two constraints on one parameter). GitHub tells identical fingerprints apart with the ":N" suffix, in + // order of appearance, so number repeats the same way instead of emitting the same fingerprint twice. + var key = (ruleId, tool, path ?? string.Empty); + occurrences.TryGetValue(key, out var seen); + occurrences[key] = seen + 1; + var identity = ruleId + "|" + tool + "|" + (path ?? string.Empty); + var hash = SHA256.HashData(Encoding.UTF8.GetBytes(identity)); + return Convert.ToHexString(hash, 0, 8).ToLowerInvariant() + ":" + (seen + 1).ToString(CultureInfo.InvariantCulture); + } + + private static string LogicalName(string tool, string? path) => + string.IsNullOrEmpty(path) ? tool : tool + "/" + path; + + /// + /// Normalizes a caller-supplied artifact to a non-empty, forward-slash URI reference. Rooted paths keep only the + /// file name, so a machine path such as C:\... never leaks into the SARIF file. + /// + private static string ArtifactUri(string? artifactUri) + { + if (string.IsNullOrWhiteSpace(artifactUri)) + { + return DefaultArtifactUri; + } + + var value = artifactUri.Trim().Replace('\\', '/'); + if (Path.IsPathRooted(artifactUri) || value.StartsWith('/') || (value.Length >= 2 && value[1] == ':')) + { + var slash = value.LastIndexOf('/'); + value = slash < 0 ? value : value[(slash + 1)..]; + if (value.Length >= 2 && value[1] == ':') + { + value = value[2..]; + } + } + + while (value.StartsWith("./", StringComparison.Ordinal)) + { + value = value[2..]; + } + + if (value.Length == 0) + { + return DefaultArtifactUri; + } + + return string.Join('/', value.Split('/').Select(Uri.EscapeDataString)); + } + + private static string LintLevel(LintSeverity severity) => severity switch + { + LintSeverity.Error => "error", + LintSeverity.Warning => "warning", + _ => "note", + }; + + private static string ChangeSeverityLabel(ChangeSeverity severity) => + severity == ChangeSeverity.Breaking ? "breaking" : "nonBreaking"; + + private static int Count(LintReport report, LintSeverity severity) => report.Findings.Count(f => f.Severity == severity); + + private static void AddIfPresent(JsonObject node, string name, string? value) + { + if (value is not null) + { + node[name] = value; + } + } + + private static string Serialize(JsonNode node) => + node.ToJsonString(s_writeOptions).Replace("\r\n", "\n", StringComparison.Ordinal) + "\n"; +} diff --git a/src/McpProbe/Internal/ProductVersion.cs b/src/McpProbe/Internal/ProductVersion.cs new file mode 100644 index 0000000..8662ab5 --- /dev/null +++ b/src/McpProbe/Internal/ProductVersion.cs @@ -0,0 +1,22 @@ +using System.Reflection; + +namespace McpProbe.Internal; + +/// The McpProbe package version, without the +sha build metadata, so machine-readable output stays stable across commits. +internal static class ProductVersion +{ + public static string Value { get; } = Read(); + + private static string Read() + { + var assembly = typeof(ProductVersion).Assembly; + var informational = assembly.GetCustomAttribute()?.InformationalVersion; + if (string.IsNullOrEmpty(informational)) + { + return assembly.GetName().Version?.ToString(3) ?? "0.0.0"; + } + + var plus = informational.IndexOf('+', StringComparison.Ordinal); + return plus < 0 ? informational : informational[..plus]; + } +} diff --git a/src/McpProbe/Linting/LintReport.cs b/src/McpProbe/Linting/LintReport.cs index 6b73c30..cfef228 100644 --- a/src/McpProbe/Linting/LintReport.cs +++ b/src/McpProbe/Linting/LintReport.cs @@ -59,9 +59,9 @@ internal LintReport( /// Findings from the schema-portability rules (MCPP009-MCPP012) fail only when their effective severity is /// ; does not change that floor. /// - public bool Failed => Findings.Any(Fails); + public bool Failed => Findings.Any(FindingFails); - private bool Fails(LintFinding finding) + internal bool FindingFails(LintFinding finding) { if (LintRules.IsPortabilityRule(finding.RuleId)) { @@ -139,7 +139,7 @@ public string ToHtml() 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", + FindingFails(f) ? "yes" : "no", })); return HtmlReport.Page( "McpProbe lint report", @@ -150,6 +150,23 @@ public string ToHtml() rows); } + /// + /// Formats the report as a JSON document (McpProbe report format 1): a summary with counts, including hidden + /// findings, and the visible findings. Indented, LF line endings, ending with a newline. + /// + /// The JSON text. + public string ToJson() => ToJson(Failed); + + internal string ToJson(bool failed) => MachineReadableOutput.LintJson(this, failed); + + /// + /// Formats the visible findings as a SARIF 2.1.0 log for tools such as GitHub code scanning. Each result points at + /// (default mcp-tools.json) and has a stable fingerprint of rule, tool and path. + /// + /// The file the results point at, as a path relative to the repository root. Rooted paths keep only the file name. + /// The SARIF JSON text, ending with a newline. + public string ToSarif(string? artifactUri = null) => MachineReadableOutput.LintSarif(this, artifactUri); + /// Throws when is . /// A finding failed the run (see ). public void ThrowIfFailed() diff --git a/src/McpProbe/PublicAPI.Unshipped.txt b/src/McpProbe/PublicAPI.Unshipped.txt index 5dc8da6..0b1b063 100644 --- a/src/McpProbe/PublicAPI.Unshipped.txt +++ b/src/McpProbe/PublicAPI.Unshipped.txt @@ -106,8 +106,10 @@ McpProbe.Linting.LintReport.Findings.get -> System.Collections.Generic.IReadOnly 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.ToJson() -> string! McpProbe.Linting.LintReport.ToHtml() -> string! McpProbe.Linting.LintReport.ToReport() -> string! +McpProbe.Linting.LintReport.ToSarif(string? artifactUri = null) -> string! McpProbe.Linting.LintReport.UnusedSuppressions.get -> System.Collections.Generic.IReadOnlyList! McpProbe.Linting.LintRule McpProbe.Linting.LintRule.$() -> McpProbe.Linting.LintRule! @@ -254,7 +256,9 @@ 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.ToJson(bool failOnNonBreakingChanges = false) -> string! McpProbe.Snapshots.ToolSurfaceDiff.ToReport() -> string! +McpProbe.Snapshots.ToolSurfaceDiff.ToSarif(string? artifactUri = null) -> 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! diff --git a/src/McpProbe/Snapshots/ToolSurfaceDiff.cs b/src/McpProbe/Snapshots/ToolSurfaceDiff.cs index 1f0261f..81fcf7b 100644 --- a/src/McpProbe/Snapshots/ToolSurfaceDiff.cs +++ b/src/McpProbe/Snapshots/ToolSurfaceDiff.cs @@ -83,6 +83,24 @@ public string ToHtml() rows); } + /// + /// Formats the changes as a JSON document (McpProbe report format 1): a summary with counts and every change, + /// with before and after for title and description changes. Indented, LF line endings, ending with a newline. + /// + /// Whether non-breaking changes count as a failure, as with the CLI --fail-on-non-breaking. Sets result. + /// The JSON text. + public string ToJson(bool failOnNonBreakingChanges = false) => + MachineReadableOutput.DiffJson(this, HasBreakingChanges || (HasChanges && failOnNonBreakingChanges)); + + /// + /// Formats the changes as a SARIF 2.1.0 log for tools such as GitHub code scanning. Breaking changes are + /// error, non-breaking changes are note. Each result points at + /// (default mcp-tools.json) and has a stable fingerprint of change kind, tool and path. + /// + /// The file the results point at, as a path relative to the repository root. Rooted paths keep only the file name. + /// The SARIF JSON text, ending with a newline. + public string ToSarif(string? artifactUri = null) => MachineReadableOutput.DiffSarif(this, artifactUri); + private static string Summary(int breaking, int nonBreaking) => string.Create(CultureInfo.InvariantCulture, $"Tool surface changed: {breaking} breaking, {nonBreaking} non-breaking."); diff --git a/tests/McpProbe.Tests/CliMachineReadableOutputTests.cs b/tests/McpProbe.Tests/CliMachineReadableOutputTests.cs new file mode 100644 index 0000000..3a09b8e --- /dev/null +++ b/tests/McpProbe.Tests/CliMachineReadableOutputTests.cs @@ -0,0 +1,237 @@ +using System.Text.Json; +using McpProbe.Cli; +using McpProbe.Linting; +using McpProbe.Snapshots; +using McpProbe.Tests.TestSupport; +using static McpProbe.Tests.TestSupport.SchemaTools; + +namespace McpProbe.Tests; + +public sealed class CliMachineReadableOutputTests : IDisposable +{ + private const string UndescribedParameter = """{"type":"object","properties":{"city":{"type":"string"}}}"""; + + private readonly TempDirectory _dir = new(); + + public void Dispose() => _dir.Dispose(); + + private string WriteSurface(string name, ToolSurface surface) + { + var path = _dir.File(name); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllText(path, surface.ToJson()); + return path; + } + + private async Task<(int Exit, string Out, string Err)> RunAsync(params string[] args) + { + using var stdout = new StringWriter(); + using var stderr = new StringWriter(); + var exit = await CliApp.RunAsync(args, stdout, stderr, _dir.Path, TestContext.Current.CancellationToken); + return (exit, stdout.ToString(), stderr.ToString()); + } + + private string LintServer() => WriteSurface("server.json", Surface(Tool("search", UndescribedParameter))); + + private (string Baseline, string Current) DiffFiles() + { + var baseline = WriteSurface("old.json", Surface(Tool("gone"), Tool("keep", description: "Old description for the tool."))); + var current = WriteSurface("new.json", Surface(Tool("keep", description: "New description for the tool."))); + return (baseline, current); + } + + [Fact] + public async Task Diff_FormatJson_StdoutIsOnlyJson_AndHintGoesToStderr() + { + var (baseline, current) = DiffFiles(); + + var (exit, output, error) = await RunAsync("diff", "--baseline", baseline, "--from-file", current); + + var (jsonExit, json, jsonError) = await RunAsync("diff", "--baseline", baseline, "--from-file", current, "--format", "json"); + Assert.Equal(ExitCodes.CheckFailed, exit); + Assert.Equal(exit, jsonExit); + using var doc = JsonDocument.Parse(json); + Assert.Equal("diff", doc.RootElement.GetProperty("kind").GetString()); + Assert.Equal("fail", doc.RootElement.GetProperty("result").GetString()); + Assert.DoesNotContain("If the change is intended", json, StringComparison.Ordinal); + Assert.Contains("If the change is intended", output, StringComparison.Ordinal); + Assert.Equal("If the change is intended, update the snapshot with 'mcpprobe snapshot' and commit it." + Environment.NewLine, jsonError); + Assert.Equal("", error); + } + + [Fact] + public async Task Diff_FormatJson_NonBreakingOnly_PassesUnlessFlagged() + { + var baseline = WriteSurface("old.json", Surface(Tool("keep", description: "Old description for the tool."))); + var current = WriteSurface("new.json", Surface(Tool("keep", description: "New description for the tool."))); + + var pass = await RunAsync("diff", "--baseline", baseline, "--from-file", current, "--format", "json"); + var fail = await RunAsync("diff", "--baseline", baseline, "--from-file", current, "--format", "json", "--fail-on-non-breaking"); + + Assert.Equal(ExitCodes.Success, pass.Exit); + Assert.Contains("\"result\": \"pass\"", pass.Out, StringComparison.Ordinal); + Assert.Equal("", pass.Err); + Assert.Equal(ExitCodes.CheckFailed, fail.Exit); + Assert.Contains("\"result\": \"fail\"", fail.Out, StringComparison.Ordinal); + } + + [Fact] + public async Task SarifFile_LeavesStdoutAsText_AndMatchesFormatSarif() + { + var (baseline, current) = DiffFiles(); + var sarifPath = _dir.File("out.sarif"); + + var text = await RunAsync("diff", "--baseline", baseline, "--from-file", current); + var withFile = await RunAsync("diff", "--baseline", baseline, "--from-file", current, "--sarif", sarifPath); + var formatSarif = await RunAsync("diff", "--baseline", baseline, "--from-file", current, "--format", "sarif"); + + Assert.Equal(text, withFile); + Assert.True(File.Exists(sarifPath)); + Assert.Equal(File.ReadAllText(sarifPath), formatSarif.Out); + Assert.Equal(ExitCodes.CheckFailed, formatSarif.Exit); + Assert.Contains("If the change is intended", formatSarif.Err, StringComparison.Ordinal); + } + + [Fact] + public async Task Lint_FormatJson_AndSarifFile_WorkTogetherWithHtmlReport() + { + var server = LintServer(); + var report = _dir.File("lint.html"); + var sarif = _dir.File("lint.sarif"); + + var plain = await RunAsync("lint", "--from-file", server); + var all = await RunAsync("lint", "--from-file", server, "--format", "json", "--report", report, "--sarif", sarif); + + Assert.Equal(ExitCodes.CheckFailed, plain.Exit); + Assert.Equal(plain.Exit, all.Exit); + using var doc = JsonDocument.Parse(all.Out); + Assert.Equal("lint", doc.RootElement.GetProperty("kind").GetString()); + Assert.Contains("banner fail", File.ReadAllText(report), StringComparison.Ordinal); + using var sarifDoc = JsonDocument.Parse(File.ReadAllText(sarif)); + Assert.Equal("2.1.0", sarifDoc.RootElement.GetProperty("version").GetString()); + } + + [Fact] + public async Task InvalidFormat_IsAUsageError_AndWritesNoFiles() + { + var server = LintServer(); + var sarif = _dir.File("never.sarif"); + var report = _dir.File("never.html"); + + var (exit, output, error) = await RunAsync("lint", "--from-file", server, "--format", "xml", "--sarif", sarif, "--report", report); + + Assert.Equal(ExitCodes.Error, exit); + Assert.Equal("", output); + Assert.NotEqual("", error); + Assert.False(File.Exists(sarif)); + Assert.False(File.Exists(report)); + } + + [Fact] + public async Task BlankSarifPath_IsAUsageError() + { + var server = LintServer(); + + var (exit, _, error) = await RunAsync("lint", "--from-file", server, "--sarif", " "); + + Assert.Equal(ExitCodes.Error, exit); + Assert.Contains("--sarif needs a file path", error, StringComparison.Ordinal); + } + + [Fact] + public async Task Errors_WriteNoSarifFile_AndNoDocumentOnStdout() + { + var server = LintServer(); + var sarif = _dir.File("never.sarif"); + + var missingBaseline = await RunAsync("diff", "--baseline", _dir.File("missing.json"), "--from-file", server, "--format", "json", "--sarif", sarif); + var missingCurrent = await RunAsync("lint", "--from-file", _dir.File("missing.json"), "--format", "sarif", "--sarif", sarif); + + Assert.Equal(ExitCodes.Error, missingBaseline.Exit); + Assert.Equal(ExitCodes.Error, missingCurrent.Exit); + Assert.Equal("", missingBaseline.Out); + Assert.Equal("", missingCurrent.Out); + Assert.False(File.Exists(sarif)); + } + + [Fact] + public async Task WriteBaseline_WithFormatJson_KeepsStdoutParseable_AndReportsPass() + { + var server = LintServer(); + var baseline = _dir.File("lint-baseline.json"); + + var (exit, output, error) = await RunAsync("lint", "--from-file", server, "--write-baseline", baseline, "--format", "json"); + + Assert.Equal(ExitCodes.Success, exit); + using var doc = JsonDocument.Parse(output); + Assert.Equal("pass", doc.RootElement.GetProperty("result").GetString()); + Assert.StartsWith("Wrote ", error, StringComparison.Ordinal); + Assert.True(File.Exists(baseline)); + + var text = await RunAsync("lint", "--from-file", server, "--write-baseline", baseline); + Assert.Contains("Wrote ", text.Out, StringComparison.Ordinal); + Assert.Equal("", text.Err); + } + + [Fact] + public async Task Cli_JsonAndSarif_MatchTheLibrary() + { + var (baseline, current) = DiffFiles(); + + var json = await RunAsync("diff", "--baseline", baseline, "--from-file", current, "--format", "json"); + var sarif = await RunAsync("diff", "--baseline", baseline, "--from-file", current, "--format", "sarif"); + var expected = ToolSurface.Parse(File.ReadAllText(baseline)); + var actual = ToolSurface.Parse(File.ReadAllText(current)); + var diff = ToolSurfaceComparer.Compare(expected, actual); + + Assert.Equal(diff.ToJson(), json.Out); + Assert.Equal(diff.ToSarif(SarifArtifact.Resolve(baseline, _dir.Path)), sarif.Out); + + var server = LintServer(); + var lintJson = await RunAsync("lint", "--from-file", server, "--format", "json"); + var lint = ToolLinter.Lint(ToolSurface.Parse(File.ReadAllText(server))); + Assert.Equal(lint.ToJson(), lintJson.Out); + } + + [Theory] + [InlineData("snapshots/base.json", "snapshots/base.json")] + [InlineData("base.json", "base.json")] + public async Task DiffSarif_Artifact_IsTheBaselineRelativeToTheWorkingDirectory(string baselineName, string expected) + { + var baseline = WriteSurface(baselineName, Surface(Tool("gone"), Tool("keep"))); + var current = WriteSurface("new.json", Surface(Tool("keep"))); + + var (_, output, _) = await RunAsync("diff", "--baseline", baseline, "--from-file", current, "--format", "sarif"); + + Assert.Equal(expected, ArtifactOf(output)); + } + + [Fact] + public async Task LintSarif_Artifact_IsFromFile_OrDefaultForALiveServerShape() + { + var server = WriteSurface(Path.Combine("snap", "tools.json"), Surface(Tool("search", UndescribedParameter))); + + var (_, output, _) = await RunAsync("lint", "--from-file", server, "--format", "sarif"); + + Assert.Equal("snap/tools.json", ArtifactOf(output)); + Assert.Equal("mcp-tools.json", SarifArtifact.Resolve(null, _dir.Path)); + } + + [Fact] + public void Artifact_OutsideTheWorkingDirectory_KeepsOnlyTheFileName() + { + var outside = Path.Combine(Path.GetTempPath(), "elsewhere", "mcp-tools.json"); + + var artifact = SarifArtifact.Resolve(outside, _dir.Path); + + Assert.Equal("mcp-tools.json", artifact); + Assert.DoesNotContain("/", artifact, StringComparison.Ordinal); + } + + private static string? ArtifactOf(string sarif) + { + using var doc = JsonDocument.Parse(sarif); + return doc.RootElement.GetProperty("runs")[0].GetProperty("results")[0] + .GetProperty("locations")[0].GetProperty("physicalLocation").GetProperty("artifactLocation").GetProperty("uri").GetString(); + } +} diff --git a/tests/McpProbe.Tests/Goldens/diff.json b/tests/McpProbe.Tests/Goldens/diff.json new file mode 100644 index 0000000..931be39 --- /dev/null +++ b/tests/McpProbe.Tests/Goldens/diff.json @@ -0,0 +1,46 @@ +{ + "formatVersion": 1, + "kind": "diff", + "tool": { + "name": "McpProbe", + "version": "" + }, + "result": "fail", + "summary": { + "changes": 4, + "breaking": 1, + "nonBreaking": 3 + }, + "changes": [ + { + "tool": "get_alerts", + "kind": "tool-removed", + "severity": "breaking", + "message": "Tool was removed." + }, + { + "tool": "get_forecast", + "kind": "description-changed", + "severity": "nonBreaking", + "message": "Description changed from 'Get the weather forecast for a city.' to 'Get a 7-day weather forecast for a city.'.", + "before": "Get the weather forecast for a city.", + "after": "Get a 7-day weather forecast for a city." + }, + { + "tool": "get_forecast", + "path": "input.city", + "kind": "description-changed", + "severity": "nonBreaking", + "message": "Description of parameter 'city' changed from 'City.' to 'City name.'.", + "before": "City.", + "after": "City name." + }, + { + "tool": "get_forecast", + "path": "input.days", + "kind": "property-added", + "severity": "nonBreaking", + "message": "Parameter 'days' was added (optional)." + } + ] +} diff --git a/tests/McpProbe.Tests/Goldens/diff.sarif b/tests/McpProbe.Tests/Goldens/diff.sarif new file mode 100644 index 0000000..084455f --- /dev/null +++ b/tests/McpProbe.Tests/Goldens/diff.sarif @@ -0,0 +1,364 @@ +{ + "$schema": "https://json.schemastore.org/sarif-2.1.0.json", + "version": "2.1.0", + "runs": [ + { + "tool": { + "driver": { + "name": "McpProbe", + "version": "", + "semanticVersion": "", + "informationUri": "https://github.com/ShmueLior/mcpprobe", + "rules": [ + { + "id": "tool-added", + "name": "tool-added", + "shortDescription": { + "text": "Tool was added" + }, + "defaultConfiguration": { + "level": "warning" + }, + "properties": { + "tags": [ + "mcp", + "tools" + ] + } + }, + { + "id": "tool-removed", + "name": "tool-removed", + "shortDescription": { + "text": "Tool was removed" + }, + "defaultConfiguration": { + "level": "warning" + }, + "properties": { + "tags": [ + "mcp", + "tools" + ] + } + }, + { + "id": "title-changed", + "name": "title-changed", + "shortDescription": { + "text": "Tool title changed" + }, + "defaultConfiguration": { + "level": "warning" + }, + "properties": { + "tags": [ + "mcp", + "tools" + ] + } + }, + { + "id": "description-changed", + "name": "description-changed", + "shortDescription": { + "text": "Tool or property description changed" + }, + "defaultConfiguration": { + "level": "warning" + }, + "properties": { + "tags": [ + "mcp", + "tools" + ] + } + }, + { + "id": "annotations-changed", + "name": "annotations-changed", + "shortDescription": { + "text": "Tool behavior hints changed" + }, + "defaultConfiguration": { + "level": "warning" + }, + "properties": { + "tags": [ + "mcp", + "tools" + ] + } + }, + { + "id": "property-added", + "name": "property-added", + "shortDescription": { + "text": "Parameter or output property was added" + }, + "defaultConfiguration": { + "level": "warning" + }, + "properties": { + "tags": [ + "mcp", + "tools" + ] + } + }, + { + "id": "property-removed", + "name": "property-removed", + "shortDescription": { + "text": "Parameter or output property was removed" + }, + "defaultConfiguration": { + "level": "warning" + }, + "properties": { + "tags": [ + "mcp", + "tools" + ] + } + }, + { + "id": "became-required", + "name": "became-required", + "shortDescription": { + "text": "Parameter or output property became required" + }, + "defaultConfiguration": { + "level": "warning" + }, + "properties": { + "tags": [ + "mcp", + "tools" + ] + } + }, + { + "id": "became-optional", + "name": "became-optional", + "shortDescription": { + "text": "Parameter or output property became optional" + }, + "defaultConfiguration": { + "level": "warning" + }, + "properties": { + "tags": [ + "mcp", + "tools" + ] + } + }, + { + "id": "type-changed", + "name": "type-changed", + "shortDescription": { + "text": "Schema type changed" + }, + "defaultConfiguration": { + "level": "warning" + }, + "properties": { + "tags": [ + "mcp", + "tools" + ] + } + }, + { + "id": "enum-changed", + "name": "enum-changed", + "shortDescription": { + "text": "Allowed values (enum) changed" + }, + "defaultConfiguration": { + "level": "warning" + }, + "properties": { + "tags": [ + "mcp", + "tools" + ] + } + }, + { + "id": "output-schema-added", + "name": "output-schema-added", + "shortDescription": { + "text": "Output schema was added" + }, + "defaultConfiguration": { + "level": "warning" + }, + "properties": { + "tags": [ + "mcp", + "tools" + ] + } + }, + { + "id": "output-schema-removed", + "name": "output-schema-removed", + "shortDescription": { + "text": "Output schema was removed" + }, + "defaultConfiguration": { + "level": "warning" + }, + "properties": { + "tags": [ + "mcp", + "tools" + ] + } + }, + { + "id": "keyword-changed", + "name": "keyword-changed", + "shortDescription": { + "text": "Unclassified JSON Schema keyword changed" + }, + "defaultConfiguration": { + "level": "warning" + }, + "properties": { + "tags": [ + "mcp", + "tools" + ] + } + }, + { + "id": "constraint-changed", + "name": "constraint-changed", + "shortDescription": { + "text": "Schema constraint changed" + }, + "defaultConfiguration": { + "level": "warning" + }, + "properties": { + "tags": [ + "mcp", + "tools" + ] + } + } + ] + } + }, + "results": [ + { + "ruleId": "tool-removed", + "level": "error", + "message": { + "text": "Tool was removed." + }, + "locations": [ + { + "physicalLocation": { + "artifactLocation": { + "uri": "mcp-tools.json" + } + }, + "logicalLocations": [ + { + "fullyQualifiedName": "get_alerts" + } + ] + } + ], + "partialFingerprints": { + "primaryLocationLineHash": "19683b3760cd54b3:1" + } + }, + { + "ruleId": "description-changed", + "level": "note", + "message": { + "text": "Description changed from 'Get the weather forecast for a city.' to 'Get a 7-day weather forecast for a city.'." + }, + "locations": [ + { + "physicalLocation": { + "artifactLocation": { + "uri": "mcp-tools.json" + } + }, + "logicalLocations": [ + { + "fullyQualifiedName": "get_forecast" + } + ] + } + ], + "partialFingerprints": { + "primaryLocationLineHash": "f45479cad924588d:1" + }, + "properties": { + "before": "Get the weather forecast for a city.", + "after": "Get a 7-day weather forecast for a city." + } + }, + { + "ruleId": "description-changed", + "level": "note", + "message": { + "text": "Description of parameter 'city' changed from 'City.' to 'City name.'." + }, + "locations": [ + { + "physicalLocation": { + "artifactLocation": { + "uri": "mcp-tools.json" + } + }, + "logicalLocations": [ + { + "fullyQualifiedName": "get_forecast/input.city" + } + ] + } + ], + "partialFingerprints": { + "primaryLocationLineHash": "4eb98f978f8570c1:1" + }, + "properties": { + "before": "City.", + "after": "City name." + } + }, + { + "ruleId": "property-added", + "level": "note", + "message": { + "text": "Parameter 'days' was added (optional)." + }, + "locations": [ + { + "physicalLocation": { + "artifactLocation": { + "uri": "mcp-tools.json" + } + }, + "logicalLocations": [ + { + "fullyQualifiedName": "get_forecast/input.days" + } + ] + } + ], + "partialFingerprints": { + "primaryLocationLineHash": "e1fa1008b03363e2:1" + } + } + ] + } + ] +} diff --git a/tests/McpProbe.Tests/Goldens/lint.json b/tests/McpProbe.Tests/Goldens/lint.json new file mode 100644 index 0000000..625fd89 --- /dev/null +++ b/tests/McpProbe.Tests/Goldens/lint.json @@ -0,0 +1,37 @@ +{ + "formatVersion": 1, + "kind": "lint", + "tool": { + "name": "McpProbe", + "version": "" + }, + "result": "fail", + "summary": { + "findings": 2, + "error": 1, + "warning": 1, + "info": 0, + "hiddenIgnored": 1, + "hiddenBaselined": 0, + "unusedIgnore": 0, + "staleBaseline": 0, + "failOn": "warning" + }, + "findings": [ + { + "ruleId": "MCPP001", + "severity": "error", + "tool": "no_description", + "message": "Tool has no description. Models pick tools by their description; say what it does and when to use it.", + "failsTheRun": true + }, + { + "ruleId": "MCPP003", + "severity": "warning", + "tool": "search", + "path": "city", + "message": "Parameter 'city' has no description. Say what it is and what format it expects.", + "failsTheRun": true + } + ] +} diff --git a/tests/McpProbe.Tests/Goldens/lint.sarif b/tests/McpProbe.Tests/Goldens/lint.sarif new file mode 100644 index 0000000..36bcfd5 --- /dev/null +++ b/tests/McpProbe.Tests/Goldens/lint.sarif @@ -0,0 +1,308 @@ +{ + "$schema": "https://json.schemastore.org/sarif-2.1.0.json", + "version": "2.1.0", + "runs": [ + { + "tool": { + "driver": { + "name": "McpProbe", + "version": "", + "semanticVersion": "", + "informationUri": "https://github.com/ShmueLior/mcpprobe", + "rules": [ + { + "id": "MCPP001", + "name": "MCPP001", + "shortDescription": { + "text": "Tool has no description" + }, + "defaultConfiguration": { + "level": "error" + }, + "properties": { + "tags": [ + "mcp", + "tools" + ] + } + }, + { + "id": "MCPP002", + "name": "MCPP002", + "shortDescription": { + "text": "Tool description is too short" + }, + "defaultConfiguration": { + "level": "warning" + }, + "properties": { + "tags": [ + "mcp", + "tools" + ] + } + }, + { + "id": "MCPP003", + "name": "MCPP003", + "shortDescription": { + "text": "Parameter has no description" + }, + "defaultConfiguration": { + "level": "warning" + }, + "properties": { + "tags": [ + "mcp", + "tools" + ] + } + }, + { + "id": "MCPP004", + "name": "MCPP004", + "shortDescription": { + "text": "Tool name doesn't follow MCP naming guidance" + }, + "defaultConfiguration": { + "level": "warning" + }, + "properties": { + "tags": [ + "mcp", + "tools" + ] + } + }, + { + "id": "MCPP005", + "name": "MCPP005", + "shortDescription": { + "text": "Tool names mix naming styles" + }, + "defaultConfiguration": { + "level": "warning" + }, + "properties": { + "tags": [ + "mcp", + "tools" + ] + } + }, + { + "id": "MCPP006", + "name": "MCPP006", + "shortDescription": { + "text": "Parameter names mix naming styles" + }, + "defaultConfiguration": { + "level": "warning" + }, + "properties": { + "tags": [ + "mcp", + "tools" + ] + } + }, + { + "id": "MCPP007", + "name": "MCPP007", + "shortDescription": { + "text": "Parameter name is vague" + }, + "defaultConfiguration": { + "level": "note" + }, + "properties": { + "tags": [ + "mcp", + "tools" + ] + } + }, + { + "id": "MCPP009", + "name": "MCPP009", + "shortDescription": { + "text": "Bare boolean used where a schema object is expected" + }, + "defaultConfiguration": { + "level": "error" + }, + "properties": { + "tags": [ + "mcp", + "tools" + ] + } + }, + { + "id": "MCPP010", + "name": "MCPP010", + "shortDescription": { + "text": "Schema type is a union array" + }, + "defaultConfiguration": { + "level": "warning" + }, + "properties": { + "tags": [ + "mcp", + "tools" + ] + } + }, + { + "id": "MCPP011", + "name": "MCPP011", + "shortDescription": { + "text": "Schema has no constraining keyword" + }, + "defaultConfiguration": { + "level": "warning" + }, + "properties": { + "tags": [ + "mcp", + "tools" + ] + } + }, + { + "id": "MCPP012", + "name": "MCPP012", + "shortDescription": { + "text": "Schema $ref points outside this document" + }, + "defaultConfiguration": { + "level": "warning" + }, + "properties": { + "tags": [ + "mcp", + "tools" + ] + } + }, + { + "id": "MCPP013", + "name": "MCPP013", + "shortDescription": { + "text": "Destructive hint contradicts other hints or the tool name" + }, + "defaultConfiguration": { + "level": "warning" + }, + "properties": { + "tags": [ + "mcp", + "tools" + ] + } + }, + { + "id": "MCPP014", + "name": "MCPP014", + "shortDescription": { + "text": "Structured results described but no outputSchema" + }, + "defaultConfiguration": { + "level": "warning" + }, + "properties": { + "tags": [ + "mcp", + "tools" + ] + } + }, + { + "id": "MCPP015", + "name": "MCPP015", + "shortDescription": { + "text": "Tool description only restates the name" + }, + "defaultConfiguration": { + "level": "warning" + }, + "properties": { + "tags": [ + "mcp", + "tools" + ] + } + }, + { + "id": "MCPP016", + "name": "MCPP016", + "shortDescription": { + "text": "Enum is empty or has no type" + }, + "defaultConfiguration": { + "level": "warning" + }, + "properties": { + "tags": [ + "mcp", + "tools" + ] + } + } + ] + } + }, + "results": [ + { + "ruleId": "MCPP001", + "level": "error", + "message": { + "text": "Tool has no description. Models pick tools by their description; say what it does and when to use it." + }, + "locations": [ + { + "physicalLocation": { + "artifactLocation": { + "uri": "snapshots/mcp-tools.json" + } + }, + "logicalLocations": [ + { + "fullyQualifiedName": "no_description" + } + ] + } + ], + "partialFingerprints": { + "primaryLocationLineHash": "ae20849e3beccff5:1" + } + }, + { + "ruleId": "MCPP003", + "level": "warning", + "message": { + "text": "Parameter 'city' has no description. Say what it is and what format it expects." + }, + "locations": [ + { + "physicalLocation": { + "artifactLocation": { + "uri": "snapshots/mcp-tools.json" + } + }, + "logicalLocations": [ + { + "fullyQualifiedName": "search/city" + } + ] + } + ], + "partialFingerprints": { + "primaryLocationLineHash": "2e598172023df269:1" + } + } + ] + } + ] +} diff --git a/tests/McpProbe.Tests/MachineReadableOutputTests.cs b/tests/McpProbe.Tests/MachineReadableOutputTests.cs new file mode 100644 index 0000000..1d1965a --- /dev/null +++ b/tests/McpProbe.Tests/MachineReadableOutputTests.cs @@ -0,0 +1,319 @@ +using System.Globalization; +using System.Text.Json; +using Json.Schema; +using McpProbe.Internal; +using McpProbe.Linting; +using McpProbe.Snapshots; +using static McpProbe.Tests.TestSupport.SchemaTools; + +namespace McpProbe.Tests; + +/// JSON (report format 1) and SARIF 2.1.0 output of lint and diff, checked against golden files and the schemas. +public sealed class MachineReadableOutputTests +{ + private const string UndescribedParameter = """{"type":"object","properties":{"city":{"type":"string"},"days":{"type":"integer","description":"Days."}}}"""; + + private static string RepoRoot() + { + for (var directory = new DirectoryInfo(AppContext.BaseDirectory); directory is not null; directory = directory.Parent) + { + if (File.Exists(Path.Combine(directory.FullName, "McpProbe.slnx"))) + { + return directory.FullName; + } + } + + throw new InvalidOperationException("Could not find the repository root."); + } + + private static string OutputFile(params string[] parts) => Path.Combine([AppContext.BaseDirectory, .. parts]); + + /// Replaces the package version so goldens don't change on a version bump. + private static string Normalize(string text) => + text.Replace($"\"{ProductVersion.Value}\"", "\"\"", StringComparison.Ordinal); + + private static void AssertGolden(string name, string actual) + { + // Compare with the source golden, not the copy in the output directory, so MCPPROBE_UPDATE_GOLDENS=1 takes + // effect in the same run instead of after the next build copies it. + var path = Path.Combine(RepoRoot(), "tests", "McpProbe.Tests", "Goldens", name); + if (Environment.GetEnvironmentVariable("MCPPROBE_UPDATE_GOLDENS") == "1") + { + File.WriteAllText(path, Normalize(actual)); + } + + Assert.True(File.Exists(path), $"Missing golden {path}"); + Assert.Equal(File.ReadAllText(path).Replace("\r\n", "\n", StringComparison.Ordinal), Normalize(actual)); + } + + // JsonSchema.Net registers each schema by its $id in a global registry and rejects loading the same file twice, + // and xUnit runs tests in parallel. Loading takes a lock, and each schema is built with its own registry, so a + // schema loaded by another test class doesn't collide either. + private static readonly Dictionary s_schemas = new(StringComparer.Ordinal); + private static readonly object s_schemaLock = new(); + + private static JsonSchema LoadSchema(string schemaPath) + { + lock (s_schemaLock) + { + if (!s_schemas.TryGetValue(schemaPath, out var schema)) + { + var options = new BuildOptions { SchemaRegistry = new SchemaRegistry() }; + schema = JsonSchema.FromText(File.ReadAllText(schemaPath), options); + s_schemas[schemaPath] = schema; + } + + return schema; + } + } + + private static EvaluationResults Validate(string schemaPath, string json) + { + var schema = LoadSchema(schemaPath); + using var doc = JsonDocument.Parse(json); + return schema.Evaluate(doc.RootElement, new EvaluationOptions { OutputFormat = OutputFormat.List }); + } + + private static void AssertValid(string schemaPath, string json) + { + var result = Validate(schemaPath, json); + var errors = (result.Details ?? []) + .Where(d => d.Errors is { Count: > 0 }) + .SelectMany(d => d.Errors!.Select(e => $"{d.InstanceLocation}: {e.Key}: {e.Value}")); + Assert.True(result.IsValid, string.Join("\n", errors)); + } + + private static LintReport LintWithFindings() + { + var options = new LintOptions(); + options.Suppressions.Add(new LintSuppression(ToolPattern: "ignored_tool")); + return ToolLinter.Lint( + Surface( + Tool("ignored_tool", UndescribedParameter), + Tool("search", UndescribedParameter), + Tool("no_description", description: null)), + options); + } + + private static ToolSurfaceDiff DiffWithChanges() => + ToolSurfaceComparer.Compare( + Surface( + Tool("get_alerts", description: "Get weather alerts for a state."), + Tool("get_forecast", """{"type":"object","properties":{"city":{"type":"string","description":"City."}}}""", "Get the weather forecast for a city.")), + Surface( + Tool("get_forecast", """{"type":"object","properties":{"city":{"type":"string","description":"City name."},"days":{"type":"integer"}}}""", "Get a 7-day weather forecast for a city."))); + + [Fact] + public void LintJson_MatchesGolden_AndReportSchema() + { + var json = LintWithFindings().ToJson(); + + AssertGolden("lint.json", json); + AssertValid(Path.Combine(RepoRoot(), "docs", "mcpprobe-report.schema.json"), json); + } + + [Fact] + public void DiffJson_MatchesGolden_AndReportSchema_WithBeforeAndAfter() + { + var json = DiffWithChanges().ToJson(); + + AssertGolden("diff.json", json); + AssertValid(Path.Combine(RepoRoot(), "docs", "mcpprobe-report.schema.json"), json); + Assert.Contains("\"before\": \"City.\"", json, StringComparison.Ordinal); + Assert.Contains("\"after\": \"City name.\"", json, StringComparison.Ordinal); + } + + [Fact] + public void LintSarif_MatchesGolden_AndOfficialSarifSchema() + { + var sarif = LintWithFindings().ToSarif("snapshots/mcp-tools.json"); + + AssertGolden("lint.sarif", sarif); + AssertValid(OutputFile("Schemas", "sarif-schema-2.1.0.json"), sarif); + } + + [Fact] + public void DiffSarif_MatchesGolden_AndOfficialSarifSchema() + { + var sarif = DiffWithChanges().ToSarif(); + + AssertGolden("diff.sarif", sarif); + AssertValid(OutputFile("Schemas", "sarif-schema-2.1.0.json"), sarif); + } + + [Fact] + public void Json_EndsWithSingleNewline_UsesLf_AndOmitsNullOptionalFields() + { + var json = DiffWithChanges().ToJson(); + + Assert.EndsWith("}\n", json, StringComparison.Ordinal); + Assert.DoesNotContain("\r", json, StringComparison.Ordinal); + var unchanged = ToolSurfaceComparer.Compare(Surface(Tool("a")), Surface(Tool("a"))).ToJson(); + Assert.Contains("\"result\": \"pass\"", unchanged, StringComparison.Ordinal); + Assert.DoesNotContain("\"before\"", unchanged, StringComparison.Ordinal); + Assert.DoesNotContain("\"path\"", unchanged, StringComparison.Ordinal); + } + + [Fact] + public void DiffJson_ResultFollowsFailOnNonBreaking() + { + var diff = ToolSurfaceComparer.Compare(Surface(Tool("a")), Surface(Tool("a"), Tool("b"))); + + Assert.False(diff.HasBreakingChanges); + Assert.Contains("\"result\": \"pass\"", diff.ToJson(), StringComparison.Ordinal); + Assert.Contains("\"result\": \"fail\"", diff.ToJson(failOnNonBreakingChanges: true), StringComparison.Ordinal); + } + + [Fact] + public void DiffJson_TitleAddedFromUnset_HasAfterButNoBefore() + { + var after = Tool("t"); + after.Title = "Weather forecast"; + var json = Diff(Tool("t"), after).ToJson(); + + Assert.Contains("\"kind\": \"title-changed\"", json, StringComparison.Ordinal); + Assert.DoesNotContain("\"before\"", json, StringComparison.Ordinal); + Assert.Contains("\"after\": \"Weather forecast\"", json, StringComparison.Ordinal); + } + + [Fact] + public void DiffJson_LongBeforeAndAfter_AreTruncatedAt2000() + { + var diff = Diff(Tool("t", description: new string('a', 5000)), Tool("t", description: new string('b', 5000))); + + using var doc = JsonDocument.Parse(diff.ToJson()); + var change = doc.RootElement.GetProperty("changes")[0]; + Assert.Equal(2000, change.GetProperty("before").GetString()!.Length); + Assert.EndsWith("...", change.GetProperty("after").GetString(), StringComparison.Ordinal); + Assert.Equal(new string('a', 5000), diff.Changes[0].Before); + } + + [Fact] + public void Json_HostileText_IsValidJsonAndEscapesControlCharactersOnce() + { + const string hostile = " & \"q\" 'a' \\ \u001b[31m \u202E"; + var diff = Diff(Tool("t", description: "safe"), Tool(hostile, description: hostile)); + + var json = diff.ToJson(); + using var doc = JsonDocument.Parse(json); + Assert.DoesNotContain('\u001b', json); + Assert.Contains("\\u001B", json, StringComparison.Ordinal); + Assert.DoesNotContain("\\\\u001B", json, StringComparison.Ordinal); + Assert.Contains("