diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 90c30e6..28eb8ad 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -75,6 +75,15 @@ jobs: strict: true report: mcpprobe-reports + - name: Check MCP tool surface with a config file + if: matrix.os == 'ubuntu-latest' || matrix.os == 'windows-latest' + uses: ./ + with: + source: artifacts + from-file: samples/WeatherServer.Tests/mcp-tools.json + baseline: samples/WeatherServer.Tests/mcp-tools.json + config: samples/WeatherServer.Tests/mcpprobe.json + - name: Assert HTML reports were written if: matrix.os == 'ubuntu-latest' || matrix.os == 'windows-latest' shell: bash diff --git a/CHANGELOG.md b/CHANGELOG.md index 34727ef..6648be0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,17 @@ All notable changes to this project are documented here. The format is based on ## [Unreleased] +### Added + +- `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`. +- 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 + +- The Action's `fail-on` input and the template's `failOn` parameter now default to empty instead of `warning`, so `failOn` from `mcpprobe.json` is not overridden. With no config the CLI default is still `warning`, so the result is the same; the wrapper just no longer passes `--fail-on warning` when the input is empty. + ## [0.4.0-preview] - 2026-11-28 ### Added diff --git a/README.md b/README.md index ed8780b..3de015d 100644 --- a/README.md +++ b/README.md @@ -147,6 +147,36 @@ Set `LintOptions.Strict = true` (CLI: `mcpprobe lint --strict`) to also run MCPP MCPP013-MCPP016 run by default and use `FailOn` like MCPP001-MCPP007. They are kept narrow on purpose: MCPP013 only reads explicit hints (an unset `destructiveHint` is fine) and matches whole name segments from `LintOptions.DestructiveNameTokens`; MCPP014 only fires on the phrases in `LintOptions.StructuredOutputCues`; MCPP016 walks `inputSchema` and `outputSchema` with the same paths as the `--strict` rules, and does not ask for a `type` on mixed-type enums (including ones with `null`) or on `anyOf`/`oneOf`/`allOf` branches, which usually take their type from the parent. +### Config file and ignore rules + +A server with legacy debt can keep its lint settings, and the findings it has decided to accept, in a committed `mcpprobe.json`. `mcpprobe lint` reads the nearest one, starting in the current directory and going up to the repository root (the first folder with a `.git`). When it uses a file it prints `Using config .` on stderr. Use `--config ` to pick a file (it must exist) or `--no-config` to skip the search. + +```jsonc +{ + "$schema": "https://raw.githubusercontent.com/ShmueLior/mcpprobe/main/docs/mcpprobe.schema.json", + "lint": { + "failOn": "warning", + "strict": false, + "nested": false, + "minDescriptionLength": 20, + "minDescriptionWords": 4, + "rules": { "MCPP007": "none", "MCPP003": "error" }, + "ignore": [ + { "rule": "MCPP005", "tool": "sql_*", "reason": "Server convention: namespace_resource_verb-noun" }, + { "rule": "MCPP003", "tool": "legacy_export", "parameter": "opts" } + ] + } +} +``` + +- `failOn`, `strict`, `nested`, `minDescriptionLength` and `rules` are the same as `--fail-on`, `--strict`, `--nested`, `--min-description-length` and `--rule`. `minDescriptionWords` has no flag. Defaults come first, then the file, then the flags you type: `--fail-on error` beats `failOn` in the file, `--nested false` turns off `"nested": true`, and `--rule MCPP007=info` changes only MCPP007. +- Each `ignore` entry hides the findings that match every field it sets: `rule` (an id), `tool` and `parameter` (patterns where `*` matches any run of characters and `?` matches one; case-sensitive), plus a free-text `reason`. Set at least a `rule` or a `tool`. `parameter` is the path the finding prints: `city`, `address.zip`, `stops[].city`, or `inputSchema.properties.city` for the `--strict` rules. +- Hidden findings never fail the run. The report says how many were hidden (`Hidden: 3 ignored.`), and lists entries that matched nothing so you can delete them (this never fails the run either). An entry for a rule that did not run, such as MCPP010 without `--strict`, is not listed as unused. +- The file is strict: JSON with comments and trailing commas, but an unknown key, a wrong type or an unknown rule id is an error (exit 2) rather than being ignored. A CLI older than the file may not know a newer key. +- It holds lint settings only. It can't name a server to start or connect to, so a checked-out repository can't make `mcpprobe` run a command. `snapshot` and `diff` don't read it. + +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`. + ## CLI in CI Write a snapshot once and commit it, then check it in CI: @@ -220,10 +250,12 @@ 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`, `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`). +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). `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. + `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 @@ -269,7 +301,7 @@ steps: baseline: mcp-tools.json ``` -The template needs bash (Git Bash on Windows). It also accepts `strict`, `transport`, and `report` (`report` is a directory, as in the Action). 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) 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: ```yaml - task: PublishPipelineArtifact@1 diff --git a/action.yml b/action.yml index f7c9e24..b5a566f 100644 --- a/action.yml +++ b/action.yml @@ -61,9 +61,11 @@ inputs: required: false default: 'false' fail-on: - description: Lowest lint severity that fails the job. error, warning, info, or none. + description: >- + Lowest lint severity that fails the job: error, warning, info, or none. Leave + empty to use failOn from mcpprobe.json, or warning if the file does not set it. required: false - default: warning + default: '' nested: description: Also lint nested object properties and array items, not just top-level parameters. required: false @@ -80,6 +82,13 @@ inputs: description: Also run schema-portability lint rules MCPP009-MCPP012 (lint only). Off by default. required: false default: 'false' + config: + description: >- + Path to a mcpprobe.json for lint. Leave empty to let lint find one, starting + in the working directory and going up to the repository root. Requires a CLI + that has --config. + required: false + default: '' transport: description: >- Pin the HTTP transport: auto, streamable-http, or sse. Only used with http. @@ -146,6 +155,7 @@ runs: MCPPROBE_RULE: ${{ inputs.rule }} MCPPROBE_MIN_DESCRIPTION_LENGTH: ${{ inputs.min-description-length }} MCPPROBE_STRICT: ${{ inputs.strict }} + MCPPROBE_CONFIG: ${{ inputs.config }} MCPPROBE_TRANSPORT: ${{ inputs.transport }} MCPPROBE_REPORT: ${{ inputs.report }} MCPPROBE_VERSION: ${{ inputs.version }} diff --git a/action/run.sh b/action/run.sh index 4cc9723..1b27cb1 100755 --- a/action/run.sh +++ b/action/run.sh @@ -271,6 +271,10 @@ fi if [[ -n "$transport" ]]; then require_cli_flag transport --transport fi +config_path=$(trim_ws "${MCPPROBE_CONFIG:-}") +if [[ -n "$config_path" && "$run_lint" == true ]]; then + require_cli_flag config --config +fi if [[ -n "$report_dir" ]]; then mkdir -p "$report_dir" || die "Could not create the report directory '$report_dir'." @@ -339,6 +343,7 @@ if [[ "$run_lint" == true ]]; then lint_args+=(--rule "$line") done < <(each_nonempty_line "${MCPPROBE_RULE:-}") is_true "${MCPPROBE_STRICT:-}" && lint_args+=(--strict) + [[ -n "$config_path" ]] && lint_args+=(--config "$config_path") [[ -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 new file mode 100644 index 0000000..1125a1d --- /dev/null +++ b/docs/mcpprobe.schema.json @@ -0,0 +1,121 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://raw.githubusercontent.com/ShmueLior/mcpprobe/main/docs/mcpprobe.schema.json", + "title": "mcpprobe.json", + "description": "Settings for 'mcpprobe lint'. Flags on the command line override this file.", + "type": "object", + "additionalProperties": false, + "properties": { + "$schema": { + "type": "string" + }, + "lint": { + "description": "Settings for 'mcpprobe lint'.", + "type": "object", + "additionalProperties": false, + "properties": { + "failOn": { + "description": "Lowest severity that makes lint exit 1. Same as --fail-on. Default: warning.", + "$ref": "#/$defs/severity" + }, + "strict": { + "description": "Also run the schema-portability rules MCPP009-MCPP012. Same as --strict.", + "type": "boolean" + }, + "nested": { + "description": "Also check nested object properties and array items. Same as --nested.", + "type": "boolean" + }, + "minDescriptionLength": { + "description": "Minimum tool description length for MCPP002. Same as --min-description-length. Default: 20.", + "type": "integer", + "minimum": 0 + }, + "minDescriptionWords": { + "description": "Words that exempt a short tool description from MCPP002. Default: 4. Set 0 to check length only.", + "type": "integer", + "minimum": 0 + }, + "rules": { + "description": "Severity per rule id, same as --rule. A flag overrides only the rule it names.", + "type": "object", + "propertyNames": { + "$ref": "#/$defs/ruleId" + }, + "additionalProperties": { + "$ref": "#/$defs/severity" + } + }, + "ignore": { + "description": "Findings to hide. Each entry hides the findings that match every field it sets. Hidden findings never fail the run.", + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "anyOf": [ + { + "required": [ + "rule" + ] + }, + { + "required": [ + "tool" + ] + } + ], + "properties": { + "rule": { + "description": "A rule id, for example MCPP005.", + "$ref": "#/$defs/ruleId" + }, + "tool": { + "description": "Tool name pattern. * matches any run of characters, ? matches one. Case-sensitive.", + "type": "string", + "minLength": 1 + }, + "parameter": { + "description": "Parameter pattern, for example city, address.zip, stops[].city or inputSchema.properties.city. Same wildcards as tool.", + "type": "string", + "minLength": 1 + }, + "reason": { + "description": "Why the finding is accepted. Not evaluated.", + "type": "string" + } + } + } + } + } + } + }, + "$defs": { + "severity": { + "enum": [ + "none", + "info", + "warning", + "error" + ] + }, + "ruleId": { + "enum": [ + "MCPP001", + "MCPP002", + "MCPP003", + "MCPP004", + "MCPP005", + "MCPP006", + "MCPP007", + "MCPP009", + "MCPP010", + "MCPP011", + "MCPP012", + "MCPP013", + "MCPP014", + "MCPP015", + "MCPP016" + ] + } + } +} diff --git a/samples/WeatherServer.Tests/mcpprobe.json b/samples/WeatherServer.Tests/mcpprobe.json new file mode 100644 index 0000000..25490dc --- /dev/null +++ b/samples/WeatherServer.Tests/mcpprobe.json @@ -0,0 +1,8 @@ +{ + "$schema": "https://raw.githubusercontent.com/ShmueLior/mcpprobe/main/docs/mcpprobe.schema.json", + "lint": { + // Lint settings for this sample. The CI workflow passes this file to the Action's "config" input. + "strict": true, + "rules": { "MCPP007": "info" } + } +} diff --git a/src/McpProbe.Cli/CliApp.cs b/src/McpProbe.Cli/CliApp.cs index 2c7f2cc..ce8d9f3 100644 --- a/src/McpProbe.Cli/CliApp.cs +++ b/src/McpProbe.Cli/CliApp.cs @@ -9,11 +9,19 @@ namespace McpProbe.Cli; /// The mcpprobe command line. Kept separate from Program so tests can run it in-process. internal static class CliApp { - private static readonly string[] s_severityNames = ["none", "info", "warning", "error"]; + internal static readonly string[] SeverityNames = ["none", "info", "warning", "error"]; - public static async Task RunAsync(string[] args, TextWriter stdout, TextWriter stderr, CancellationToken cancellationToken = default) + public static Task RunAsync(string[] args, TextWriter stdout, TextWriter stderr, CancellationToken cancellationToken = default) => + RunAsync(args, stdout, stderr, workingDirectory: null, cancellationToken); + + /// The command line. + /// Where results go. + /// Where errors and notes go. + /// Where lint starts looking for mcpprobe.json. Null means the current directory. + /// Cancels the run. + public static async Task RunAsync(string[] args, TextWriter stdout, TextWriter stderr, string? workingDirectory, CancellationToken cancellationToken) { - var root = BuildRootCommand(stdout, stderr); + var root = BuildRootCommand(stdout, stderr, workingDirectory); var parse = root.Parse(args); if (parse.Errors.Count > 0) { @@ -30,13 +38,13 @@ public static async Task RunAsync(string[] args, TextWriter stdout, TextWri return await parse.InvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } - private static RootCommand BuildRootCommand(TextWriter stdout, TextWriter stderr) + private static RootCommand BuildRootCommand(TextWriter stdout, TextWriter stderr, string? workingDirectory) { 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), - BuildLintCommand(stdout, stderr), + BuildLintCommand(stdout, stderr, workingDirectory), }; return root; } @@ -148,7 +156,7 @@ private static Command BuildDiffCommand(TextWriter stdout, TextWriter stderr) return command; } - private static Command BuildLintCommand(TextWriter stdout, TextWriter stderr) + private static Command BuildLintCommand(TextWriter stdout, TextWriter stderr, string? workingDirectory) { var server = new ServerOptions(allowFile: true); var failOn = new Option("--fail-on") @@ -156,7 +164,7 @@ private static Command BuildLintCommand(TextWriter stdout, TextWriter stderr) Description = "Lowest severity that makes the command exit 1: error, warning, info or none.", DefaultValueFactory = _ => "warning", }; - failOn.AcceptOnlyFromAmong(s_severityNames); + failOn.AcceptOnlyFromAmong(SeverityNames); var minLength = new Option("--min-description-length") { Description = "Minimum tool description length for MCPP002.", @@ -176,6 +184,14 @@ private static Command BuildLintCommand(TextWriter stdout, TextWriter stderr) { Description = "Also run schema-portability rules MCPP009-MCPP012. Those findings fail the command only when their severity is error.", }; + var config = new Option("--config") + { + Description = $"Read lint settings from this file instead of the nearest {LintConfig.FileName} (looked up from the current directory to the repository root). Flags override the file.", + }; + var noConfig = new Option("--no-config") + { + Description = $"Don't look for {LintConfig.FileName}.", + }; 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); @@ -184,23 +200,47 @@ private static Command BuildLintCommand(TextWriter stdout, TextWriter stderr) command.Options.Add(rules); command.Options.Add(nested); command.Options.Add(strict); + command.Options.Add(config); + command.Options.Add(noConfig); command.Options.Add(report); command.SetAction((parse, ct) => RunGuardedAsync(stderr, async () => { var reportPath = ReportPath(parse, report); - var options = new LintOptions + var options = new LintOptions(); + + // Library defaults < config file < flags typed on this command line (a flag left at its default doesn't count). + var configPath = ConfigPath(parse.GetValue(config), parse.GetValue(noConfig), workingDirectory); + if (configPath is not null) { - FailOn = ParseSeverity(parse.GetValue(failOn)!), - MinToolDescriptionLength = parse.GetValue(minLength), - CheckNestedParameters = parse.GetValue(nested), - Strict = parse.GetValue(strict), - }; + await stderr.WriteLineAsync($"Using config {PrintableLines(configPath)}.").ConfigureAwait(false); + LintConfig.Load(configPath).ApplyTo(options); + } + + if (IsSet(parse, failOn)) + { + options.FailOn = ParseSeverity(parse.GetValue(failOn)!); + } + + if (IsSet(parse, minLength)) + { + options.MinToolDescriptionLength = parse.GetValue(minLength); + } + + if (IsSet(parse, nested)) + { + options.CheckNestedParameters = parse.GetValue(nested); + } + + if (IsSet(parse, strict)) + { + options.Strict = parse.GetValue(strict); + } foreach (var rule in parse.GetValue(rules) ?? []) { var parts = rule.Split('=', 2, StringSplitOptions.TrimEntries); if (parts.Length != 2 || !LintRules.All.Any(r => string.Equals(r.Id, parts[0], StringComparison.OrdinalIgnoreCase)) || - !s_severityNames.Contains(parts[1], StringComparer.OrdinalIgnoreCase)) + !SeverityNames.Contains(parts[1], StringComparer.OrdinalIgnoreCase)) { throw new ArgumentException($"Invalid --rule '{rule}'. Use RULE=severity, for example MCPP007=none. Rules: {string.Join(", ", LintRules.All.Select(r => r.Id))}."); } @@ -221,7 +261,26 @@ private static Command BuildLintCommand(TextWriter stdout, TextWriter stderr) return command; } - private static LintSeverity ParseSeverity(string value) => value.ToUpperInvariant() switch + private static bool IsSet(ParseResult parse, Option option) => parse.GetResult(option) is { Implicit: false }; + + /// The config file to use, or null. --config must exist; otherwise the nearest one up to the repository root is used. + private static string? ConfigPath(string? explicitPath, bool noConfig, string? workingDirectory) + { + if (noConfig) + { + return explicitPath is null ? null : throw new ArgumentException("Use either --config or --no-config, not both."); + } + + if (explicitPath is null) + { + return LintConfig.Discover(workingDirectory ?? Directory.GetCurrentDirectory()); + } + + var path = string.IsNullOrWhiteSpace(explicitPath) ? throw new ArgumentException("--config needs a file path.") : Path.GetFullPath(explicitPath); + return File.Exists(path) ? path : throw new FileNotFoundException($"Config file not found: {path}."); + } + + internal static LintSeverity ParseSeverity(string value) => value.ToUpperInvariant() switch { "NONE" => LintSeverity.None, "INFO" => LintSeverity.Info, diff --git a/src/McpProbe.Cli/LintConfig.cs b/src/McpProbe.Cli/LintConfig.cs new file mode 100644 index 0000000..8a4f044 --- /dev/null +++ b/src/McpProbe.Cli/LintConfig.cs @@ -0,0 +1,210 @@ +using System.Text.Json; +using System.Text.Json.Nodes; +using McpProbe.Internal; +using McpProbe.Linting; + +namespace McpProbe.Cli; + +/// +/// The lint section of mcpprobe.json. Parsed by hand and strictly: an unknown key, a wrong type or an unknown rule +/// is an error, so a typo can't silently stop a suppression from working. Holds lint settings only; it never names a server to connect to. +/// +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[] IgnoreKeys = ["rule", "tool", "parameter", "reason"]; + + private static readonly JsonDocumentOptions s_documentOptions = new() { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true }; + + public required string Path { get; init; } + + public LintSeverity? FailOn { get; private init; } + + public bool? Strict { get; private init; } + + public bool? Nested { get; private init; } + + public int? MinDescriptionLength { get; private init; } + + public int? MinDescriptionWords { get; private init; } + + public IReadOnlyDictionary Rules { get; private init; } = new Dictionary(); + + public IReadOnlyList Ignore { 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. + /// + public static string? Discover(string startDirectory) + { + for (var directory = new DirectoryInfo(startDirectory); directory is not null; directory = directory.Parent) + { + var candidate = System.IO.Path.Combine(directory.FullName, FileName); + if (File.Exists(candidate)) + { + return candidate; + } + + var git = System.IO.Path.Combine(directory.FullName, ".git"); + if (Directory.Exists(git) || File.Exists(git)) + { + return null; + } + } + + return null; + } + + public static LintConfig Load(string path) => Parse(File.ReadAllText(path), path); + + /// Parses config text. Errors name the file and the key, for example mcpprobe.json: lint.rules: unknown rule 'X'. + public static LintConfig Parse(string json, string path) + { + var name = System.IO.Path.GetFileName(path); + try + { + return ParseNodes(JsonNode.Parse(json, documentOptions: s_documentOptions), name, path); + } + catch (Exception ex) when (ex is JsonException or ArgumentException) + { + // A duplicate key throws ArgumentException (while the tree is read, not when it is parsed) on the net8.0 and net10.0 runtimes. + throw new FormatException($"{name} is not valid JSON: {ex.Message}", ex); + } + } + + private static LintConfig ParseNodes(JsonNode? root, string name, string path) + { + var top = AsObject(root, name, string.Empty); + CheckKeys(top, RootKeys, name, string.Empty); + if (top.TryGetPropertyValue("$schema", out var schema)) + { + _ = AsString(schema, name, "$schema"); + } + + if (!top.TryGetPropertyValue("lint", out var lintNode)) + { + return new LintConfig { Path = path }; + } + + var lint = AsObject(lintNode, name, "lint"); + CheckKeys(lint, LintKeys, name, "lint"); + return new LintConfig + { + Path = path, + FailOn = lint.TryGetPropertyValue("failOn", out var failOn) ? ParseSeverity(failOn, name, "lint.failOn") : null, + Strict = lint.TryGetPropertyValue("strict", out var strict) ? AsBool(strict, name, "lint.strict") : null, + Nested = lint.TryGetPropertyValue("nested", out var nested) ? AsBool(nested, name, "lint.nested") : null, + MinDescriptionLength = lint.TryGetPropertyValue("minDescriptionLength", out var length) ? AsCount(length, name, "lint.minDescriptionLength") : null, + 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) : [], + }; + } + + /// Applies the file over the library defaults. Command-line flags are applied after this, so they win. + public void ApplyTo(LintOptions options) + { + options.FailOn = FailOn ?? options.FailOn; + options.Strict = Strict ?? options.Strict; + options.CheckNestedParameters = Nested ?? options.CheckNestedParameters; + options.MinToolDescriptionLength = MinDescriptionLength ?? options.MinToolDescriptionLength; + options.MinToolDescriptionWords = MinDescriptionWords ?? options.MinToolDescriptionWords; + foreach (var (rule, severity) in Rules) + { + options.Severities[rule] = severity; + } + + foreach (var suppression in Ignore) + { + options.Suppressions.Add(suppression); + } + } + + private static Dictionary ParseRules(JsonNode? node, string name) + { + var rules = new Dictionary(StringComparer.Ordinal); + foreach (var (key, value) in AsObject(node, name, "lint.rules")) + { + var id = FindRule(key, name, "lint.rules"); + if (rules.ContainsKey(id)) + { + throw new FormatException($"{name}: lint.rules: rule '{id}' is listed twice."); + } + + rules[id] = ParseSeverity(value, name, $"lint.rules.{id}"); + } + + return rules; + } + + private static List ParseIgnore(JsonNode? node, string name) + { + if (node is not JsonArray array) + { + throw new FormatException($"{name}: lint.ignore: expected an array of entries."); + } + + var entries = new List(); + for (var i = 0; i < array.Count; i++) + { + var where = $"lint.ignore[{i}]"; + var entry = AsObject(array[i], name, where); + CheckKeys(entry, IgnoreKeys, name, where); + var rule = entry.TryGetPropertyValue("rule", out var r) ? FindRule(AsString(r, name, $"{where}.rule"), name, where) : null; + var tool = entry.TryGetPropertyValue("tool", out var t) ? AsString(t, name, $"{where}.tool") : null; + var parameter = entry.TryGetPropertyValue("parameter", out var p) ? AsString(p, name, $"{where}.parameter") : null; + var reason = entry.TryGetPropertyValue("reason", out var why) ? AsString(why, name, $"{where}.reason", allowEmpty: true) : null; + if (rule is null && tool is null) + { + throw new FormatException($"{name}: {where}: needs a 'rule' or a 'tool'. To hide everything, set lint.failOn to \"none\"."); + } + + entries.Add(new LintSuppression(rule, tool, parameter, reason)); + } + + return entries; + } + + private static string FindRule(string id, string name, string where) => + LintRules.All.FirstOrDefault(r => string.Equals(r.Id, id, StringComparison.OrdinalIgnoreCase))?.Id + ?? throw new FormatException($"{name}: {where}: unknown rule '{Printable.Text(id, 50)}'. Rules: {string.Join(", ", LintRules.All.Select(r => r.Id))}."); + + private static LintSeverity ParseSeverity(JsonNode? node, string name, string where) + { + var value = AsString(node, name, where); + return CliApp.SeverityNames.Contains(value, StringComparer.OrdinalIgnoreCase) + ? CliApp.ParseSeverity(value) + : throw new FormatException($"{name}: {where}: unknown severity '{Printable.Text(value, 50)}'. Use {string.Join(", ", CliApp.SeverityNames)}."); + } + + private static JsonObject AsObject(JsonNode? node, string name, string where) => + node as JsonObject ?? throw new FormatException($"{Prefix(name, where)}: expected a JSON object."); + + private static void CheckKeys(JsonObject obj, string[] known, string name, string where) + { + foreach (var key in obj.Select(p => p.Key)) + { + if (!known.Contains(key, StringComparer.Ordinal)) + { + throw new FormatException($"{Prefix(name, where)}: unknown key '{Printable.Text(key, 50)}'. Keys: {string.Join(", ", known)}."); + } + } + } + + private static string AsString(JsonNode? node, string name, string where, bool allowEmpty = false) => + node is JsonValue value && value.TryGetValue(out var text) && (allowEmpty || text.Length > 0) + ? text + : throw new FormatException($"{name}: {where}: expected a non-empty string."); + + private static bool AsBool(JsonNode? node, string name, string where) => + node is JsonValue value && value.TryGetValue(out var flag) ? flag : throw new FormatException($"{name}: {where}: expected true or false."); + + private static int AsCount(JsonNode? node, string name, string where) => + node is JsonValue value && value.TryGetValue(out var count) && count >= 0 ? count : throw new FormatException($"{name}: {where}: expected a whole number, 0 or more."); + + private static string Prefix(string name, string where) => where.Length == 0 ? name : $"{name}: {where}"; +} diff --git a/src/McpProbe/Linting/LintOptions.cs b/src/McpProbe/Linting/LintOptions.cs index 7bb5d8d..fa0b499 100644 --- a/src/McpProbe/Linting/LintOptions.cs +++ b/src/McpProbe/Linting/LintOptions.cs @@ -77,6 +77,12 @@ public sealed class LintOptions /// public bool Strict { get; set; } + /// + /// Gets the findings to hide, such as one rule on tools matching a name pattern. Hidden findings move to + /// and never fail the report. Empty by default. + /// + public IList Suppressions { get; } = new List(); + 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 1959957..13b66b6 100644 --- a/src/McpProbe/Linting/LintReport.cs +++ b/src/McpProbe/Linting/LintReport.cs @@ -7,15 +7,33 @@ namespace McpProbe.Linting; /// The findings of a lint run. public sealed class LintReport { + private const int MaxUnusedListed = 20; + internal LintReport(IReadOnlyList findings, LintSeverity failOn) + : this(findings, failOn, [], []) + { + } + + internal LintReport(IReadOnlyList findings, LintSeverity failOn, IReadOnlyList suppressed, IReadOnlyList unusedSuppressions) { Findings = findings; FailOn = failOn; + SuppressedFindings = suppressed; + UnusedSuppressions = unusedSuppressions; } - /// Gets the findings, most severe first, then by tool, parameter and rule. + /// Gets the findings, most severe first, then by tool, parameter and rule. Findings hidden by are not included. public IReadOnlyList Findings { get; } + /// Gets the findings that hid, in the same order as . They never fail the report. + public IReadOnlyList SuppressedFindings { get; } + + /// + /// Gets the entries of that hid nothing in this run, so stale ones can be removed. + /// Entries for a rule that did not run (a portability rule without , or a rule set to none) are not listed. + /// + public IReadOnlyList UnusedSuppressions { get; } + /// Gets the lowest severity that counts as a failure. public LintSeverity FailOn { get; } @@ -40,16 +58,37 @@ private bool Fails(LintFinding finding) /// The report. public string ToReport() { + var sb = new StringBuilder(); if (Findings.Count == 0) { - return "No lint findings."; + sb.Append(NoFindings()); } + else + { + sb.Append(Summary()); + foreach (var finding in Findings) + { + sb.Append('\n').Append(" ").Append(finding); + } - var sb = new StringBuilder(); - sb.Append(Summary()); - foreach (var finding in Findings) + if (HiddenSummary() is { } hidden) + { + sb.Append('\n').Append(hidden); + } + } + + if (UnusedSuppressions.Count > 0) { - sb.Append('\n').Append(" ").Append(finding); + sb.Append("\nUnused ignore entries (they matched no finding):"); + foreach (var unused in UnusedSuppressions.Take(MaxUnusedListed)) + { + sb.Append("\n ").Append(unused.Describe()); + } + + if (UnusedSuppressions.Count > MaxUnusedListed) + { + sb.Append("\n and ").Append(UnusedSuppressions.Count - MaxUnusedListed).Append(" more"); + } } return sb.ToString(); @@ -75,7 +114,7 @@ public string ToHtml() "McpProbe lint report", Failed ? "fail" : "pass", Failed ? "Failed" : "Passed", - Findings.Count == 0 ? "No lint findings." : $"{Summary()} Fails on: {LintFinding.SeverityLabel(FailOn)}.", + Findings.Count == 0 ? NoFindings() : string.Join(' ', new[] { Summary(), HiddenSummary(), $"Fails on: {LintFinding.SeverityLabel(FailOn)}." }.Where(part => part is not null)), ["Severity", "Rule", "Tool", "Path", "Message", "Fails the run"], rows); } @@ -97,5 +136,9 @@ public void ThrowIfFailed() private string Summary() => string.Create(CultureInfo.InvariantCulture, $"{Findings.Count} lint finding(s): {Count(LintSeverity.Error)} error, {Count(LintSeverity.Warning)} warning, {Count(LintSeverity.Info)} info."); + private 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 int Count(LintSeverity severity) => Findings.Count(f => f.Severity == severity); } diff --git a/src/McpProbe/Linting/LintSuppression.cs b/src/McpProbe/Linting/LintSuppression.cs new file mode 100644 index 0000000..649b840 --- /dev/null +++ b/src/McpProbe/Linting/LintSuppression.cs @@ -0,0 +1,121 @@ +using McpProbe.Internal; + +namespace McpProbe.Linting; + +/// +/// Hides lint findings a team has decided to accept. A finding is hidden when every field that is set matches it; +/// an omitted field matches anything. Hidden findings do not count toward . +/// +/// The rule id, for example MCPP005. Compared case-insensitively. Null matches every rule. +/// A tool name pattern: * matches any run of characters (including none), ? matches one character. Case-sensitive. Null matches every tool. +/// A pattern for , with the same wildcards. Null matches every parameter, and findings that have none. +/// Why the finding is accepted. Never evaluated; it documents the entry. +public sealed record LintSuppression(string? RuleId = null, string? ToolPattern = null, string? ParameterPattern = null, string? Reason = null) +{ + internal bool Matches(LintFinding finding) => + (RuleId is null || string.Equals(RuleId, finding.RuleId, StringComparison.OrdinalIgnoreCase)) && + (ToolPattern is null || GlobMatches(ToolPattern, finding.ToolName)) && + (ParameterPattern is null || (finding.ParameterName is not null && GlobMatches(ParameterPattern, finding.ParameterName))); + + /// Whether the entry could have matched in a run with these options. A rule that did not run can't have findings, so its entries aren't "unused". + internal bool CouldMatch(LintOptions options) + { + if (RuleId is not null && LintRules.All.FirstOrDefault(r => string.Equals(r.Id, RuleId, StringComparison.OrdinalIgnoreCase)) is { } rule) + { + if (options.SeverityOf(rule) == LintSeverity.None || (LintRules.IsPortabilityRule(rule.Id) && !options.IsPortabilityRuleEnabled(rule))) + { + return false; + } + } + + // Nested paths (address.zip, stops[].city) only exist with CheckNestedParameters; schema paths (inputSchema...) don't depend on it. + return options.CheckNestedParameters || ParameterPattern is null || !ParameterPattern.AsSpan().ContainsAny('.', '[') || + ParameterPattern.StartsWith("inputSchema", StringComparison.Ordinal) || ParameterPattern.StartsWith("outputSchema", StringComparison.Ordinal); + } + + internal string Describe() + { + var parts = new List(3); + if (RuleId is not null) + { + parts.Add($"rule {Printable.Text(RuleId, 20)}"); + } + + if (ToolPattern is not null) + { + parts.Add($"tool {Printable.Text(ToolPattern, 100)}"); + } + + if (ParameterPattern is not null) + { + parts.Add($"parameter {Printable.Text(ParameterPattern, 100)}"); + } + + return string.Join(", ", parts); + } + + /// Splits the findings into the ones to report and the ones a suppression hides, and lists the entries that hid nothing. + internal static (List Active, List Hidden, List Unused) Apply( + List findings, IList suppressions, LintOptions options) + { + if (suppressions.Count == 0) + { + return (findings, [], []); + } + + var used = new bool[suppressions.Count]; + var active = new List(); + var hidden = new List(); + foreach (var finding in findings) + { + var matched = false; + for (var i = 0; i < suppressions.Count; i++) + { + if (suppressions[i].Matches(finding)) + { + used[i] = matched = true; + } + } + + (matched ? hidden : active).Add(finding); + } + + var unused = suppressions.Where((s, i) => !used[i] && s.CouldMatch(options)).Distinct().ToList(); + return (active, hidden, unused); + } + + /// Matches against a pattern with * and ?. Iterative, so a long input can't backtrack exponentially. + internal static bool GlobMatches(string pattern, string value) + { + int p = 0, v = 0, star = -1, resume = 0; + while (v < value.Length) + { + if (p < pattern.Length && pattern[p] == '*') + { + star = p++; + resume = v; + } + else if (p < pattern.Length && (pattern[p] == '?' || pattern[p] == value[v])) + { + p++; + v++; + } + else if (star >= 0) + { + p = star + 1; + v = ++resume; + } + else + { + return false; + } + } + + while (p < pattern.Length && pattern[p] == '*') + { + p++; + } + + return p == pattern.Length; + } +} diff --git a/src/McpProbe/Linting/ToolLinter.cs b/src/McpProbe/Linting/ToolLinter.cs index 8dafe5c..e37c3b8 100644 --- a/src/McpProbe/Linting/ToolLinter.cs +++ b/src/McpProbe/Linting/ToolLinter.cs @@ -61,6 +61,14 @@ public static LintReport Lint(ToolSurface surface, LintOptions? options = null) throw new ArgumentOutOfRangeException(nameof(options), "MinToolDescriptionWords can't be negative."); } + foreach (var suppression in options.Suppressions) + { + if (suppression is null || (suppression.RuleId is null && suppression.ToolPattern is null)) + { + throw new ArgumentException("Every suppression needs a RuleId or a ToolPattern. To hide everything, set FailOn to None.", nameof(options)); + } + } + var findings = new List(); var parameterNames = new List<(string Tool, string Path, string Name)>(); @@ -89,15 +97,17 @@ public static LintReport Lint(ToolSurface surface, LintOptions? options = null) options, findings); - var ordered = findings - .OrderByDescending(f => f.Severity) - .ThenBy(f => f.ToolName, StringComparer.Ordinal) - .ThenBy(f => f.ParameterName ?? string.Empty, StringComparer.Ordinal) - .ThenBy(f => f.RuleId, StringComparer.Ordinal) - .ToList(); - return new LintReport(ordered, options.FailOn); + var (active, suppressed, unused) = LintSuppression.Apply(findings, options.Suppressions, options); + return new LintReport(Order(active), options.FailOn, Order(suppressed), unused); } + private static List Order(List findings) => findings + .OrderByDescending(f => f.Severity) + .ThenBy(f => f.ToolName, StringComparer.Ordinal) + .ThenBy(f => f.ParameterName ?? string.Empty, StringComparer.Ordinal) + .ThenBy(f => f.RuleId, StringComparer.Ordinal) + .ToList(); + private static void LintProperties(Walk walk, JsonNode? schema, string? prefix) { var nested = walk.Options.CheckNestedParameters; diff --git a/src/McpProbe/PublicAPI.Unshipped.txt b/src/McpProbe/PublicAPI.Unshipped.txt index 7c63e03..2d11c2c 100644 --- a/src/McpProbe/PublicAPI.Unshipped.txt +++ b/src/McpProbe/PublicAPI.Unshipped.txt @@ -79,14 +79,17 @@ McpProbe.Linting.LintOptions.Severities.get -> System.Collections.Generic.IDicti McpProbe.Linting.LintOptions.Strict.get -> bool McpProbe.Linting.LintOptions.Strict.set -> void McpProbe.Linting.LintOptions.StructuredOutputCues.get -> System.Collections.Generic.ISet! +McpProbe.Linting.LintOptions.Suppressions.get -> System.Collections.Generic.IList! McpProbe.Linting.LintOptions.VagueParameterNames.get -> System.Collections.Generic.ISet! McpProbe.Linting.LintReport 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.SuppressedFindings.get -> System.Collections.Generic.IReadOnlyList! McpProbe.Linting.LintReport.ThrowIfFailed() -> void McpProbe.Linting.LintReport.ToHtml() -> string! McpProbe.Linting.LintReport.ToReport() -> string! +McpProbe.Linting.LintReport.UnusedSuppressions.get -> System.Collections.Generic.IReadOnlyList! McpProbe.Linting.LintRule McpProbe.Linting.LintRule.$() -> McpProbe.Linting.LintRule! McpProbe.Linting.LintRule.Deconstruct(out string! Id, out string! Title, out McpProbe.Linting.LintSeverity DefaultSeverity) -> void @@ -104,6 +107,19 @@ McpProbe.Linting.LintSeverity.Error = 3 -> McpProbe.Linting.LintSeverity McpProbe.Linting.LintSeverity.Info = 1 -> McpProbe.Linting.LintSeverity McpProbe.Linting.LintSeverity.None = 0 -> McpProbe.Linting.LintSeverity McpProbe.Linting.LintSeverity.Warning = 2 -> McpProbe.Linting.LintSeverity +McpProbe.Linting.LintSuppression +McpProbe.Linting.LintSuppression.$() -> McpProbe.Linting.LintSuppression! +McpProbe.Linting.LintSuppression.Deconstruct(out string? RuleId, out string? ToolPattern, out string? ParameterPattern, out string? Reason) -> void +McpProbe.Linting.LintSuppression.Equals(McpProbe.Linting.LintSuppression? other) -> bool +McpProbe.Linting.LintSuppression.LintSuppression(string? RuleId = null, string? ToolPattern = null, string? ParameterPattern = null, string? Reason = null) -> void +McpProbe.Linting.LintSuppression.ParameterPattern.get -> string? +McpProbe.Linting.LintSuppression.ParameterPattern.init -> void +McpProbe.Linting.LintSuppression.Reason.get -> string? +McpProbe.Linting.LintSuppression.Reason.init -> void +McpProbe.Linting.LintSuppression.RuleId.get -> string? +McpProbe.Linting.LintSuppression.RuleId.init -> void +McpProbe.Linting.LintSuppression.ToolPattern.get -> string? +McpProbe.Linting.LintSuppression.ToolPattern.init -> void McpProbe.Linting.ToolLinter McpProbe.McpAssert McpProbe.McpProbeAssertionException @@ -224,6 +240,9 @@ override McpProbe.Linting.LintReport.ToString() -> string! override McpProbe.Linting.LintRule.Equals(object? obj) -> bool override McpProbe.Linting.LintRule.GetHashCode() -> int override McpProbe.Linting.LintRule.ToString() -> string! +override McpProbe.Linting.LintSuppression.Equals(object? obj) -> bool +override McpProbe.Linting.LintSuppression.GetHashCode() -> int +override McpProbe.Linting.LintSuppression.ToString() -> string! override McpProbe.Snapshots.ToolContractAnnotations.Equals(object? obj) -> bool override McpProbe.Snapshots.ToolContractAnnotations.GetHashCode() -> int override McpProbe.Snapshots.ToolContractAnnotations.ToString() -> string! @@ -236,6 +255,8 @@ static McpProbe.Linting.LintFinding.operator ==(McpProbe.Linting.LintFinding? le static McpProbe.Linting.LintRule.operator !=(McpProbe.Linting.LintRule? left, McpProbe.Linting.LintRule? right) -> bool static McpProbe.Linting.LintRule.operator ==(McpProbe.Linting.LintRule? left, McpProbe.Linting.LintRule? right) -> bool static McpProbe.Linting.LintRules.All.get -> System.Collections.Generic.IReadOnlyList! +static McpProbe.Linting.LintSuppression.operator !=(McpProbe.Linting.LintSuppression? left, McpProbe.Linting.LintSuppression? right) -> bool +static McpProbe.Linting.LintSuppression.operator ==(McpProbe.Linting.LintSuppression? left, McpProbe.Linting.LintSuppression? right) -> bool static McpProbe.Linting.ToolLinter.Lint(McpProbe.Snapshots.ToolSurface! surface, McpProbe.Linting.LintOptions? options = null) -> McpProbe.Linting.LintReport! static McpProbe.Linting.ToolLinter.Lint(System.Collections.Generic.IEnumerable! tools, McpProbe.Linting.LintOptions? options = null) -> McpProbe.Linting.LintReport! static McpProbe.Linting.ToolLinter.Lint(System.Collections.Generic.IEnumerable! tools, McpProbe.Linting.LintOptions? options = null) -> McpProbe.Linting.LintReport! diff --git a/templates/azure-pipelines/mcpprobe.yml b/templates/azure-pipelines/mcpprobe.yml index a62a4ff..712bb1b 100644 --- a/templates/azure-pipelines/mcpprobe.yml +++ b/templates/azure-pipelines/mcpprobe.yml @@ -56,7 +56,7 @@ parameters: default: false - name: failOn type: string - default: warning + default: '' - name: nested type: boolean default: false @@ -69,6 +69,9 @@ parameters: - name: strict type: boolean default: false +- name: config + type: string + default: '' - name: transport type: string default: '' @@ -129,6 +132,7 @@ steps: MCPPROBE_RULE: ${{ parameters.rule }} MCPPROBE_MIN_DESCRIPTION_LENGTH: ${{ parameters.minDescriptionLength }} MCPPROBE_STRICT: ${{ parameters.strict }} + MCPPROBE_CONFIG: ${{ parameters.config }} MCPPROBE_TRANSPORT: ${{ parameters.transport }} MCPPROBE_REPORT: ${{ parameters.report }} MCPPROBE_VERSION: ${{ parameters.version }} diff --git a/tests/McpProbe.Tests/CliLintConfigTests.cs b/tests/McpProbe.Tests/CliLintConfigTests.cs new file mode 100644 index 0000000..67e4e37 --- /dev/null +++ b/tests/McpProbe.Tests/CliLintConfigTests.cs @@ -0,0 +1,306 @@ +using System.Globalization; +using McpProbe.Cli; +using McpProbe.Snapshots; +using McpProbe.Tests.TestSupport; +using static McpProbe.Tests.TestSupport.SchemaTools; + +namespace McpProbe.Tests; + +public sealed class CliLintConfigTests : IDisposable +{ + private const string Undescribed = """{"type":"object","properties":{"city":{"type":"string"}}}"""; + + private readonly TempDirectory _dir = new(); + + public CliLintConfigTests() => 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; + } + + private string Surface(params ModelContextProtocol.Protocol.Tool[] tools) => Write("tools.json", SchemaTools.Surface(tools).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 NoConfig_KeepsStdoutStderrAndExitCodesExactlyAsBefore() + { + var passing = Surface(Tool("search")); + var (exit, output, error) = await LintAsync("--from-file", passing); + Assert.Equal((0, "No lint findings.", ""), (exit, output.TrimEnd(), error)); + + var failing = Write("failing.json", SchemaTools.Surface(Tool("search", description: "Short.")).ToJson()); + (exit, output, error) = await LintAsync("--from-file", failing); + Assert.Equal(1, exit); + Assert.StartsWith("1 lint finding(s): 0 error, 1 warning, 0 info.\n warning MCPP002 search: ", output, StringComparison.Ordinal); + Assert.DoesNotContain("Hidden", output, StringComparison.Ordinal); + Assert.Equal("", error); + } + + [Fact] + public async Task Discovery_UsesTheNearestFileFromTheWorkingDirectoryAndSaysSoOnStderr() + { + var config = Write("mcpprobe.json", """{"lint":{"ignore":[{"rule":"MCPP003"}]}}"""); + var file = Surface(Tool("search", Undescribed)); + + var (exit, output, error) = await LintAsync("--from-file", file); + + Assert.Equal(0, exit); + Assert.Equal("No lint findings. (Hidden: 1 ignored.)", output.TrimEnd()); + Assert.Equal($"Using config {config}.", error.TrimEnd()); + } + + [Fact] + public async Task Discovery_WalksUpFromASubfolder_ButNotPastTheRepositoryRoot() + { + var outer = new TempDirectory(); + try + { + File.WriteAllText(outer.File("mcpprobe.json"), """{"lint":{"failOn":"none"}}"""); + var repo = Path.Combine(outer.Path, "repo"); + Directory.CreateDirectory(Path.Combine(repo, ".git")); + var sub = Path.Combine(repo, "src", "server"); + Directory.CreateDirectory(sub); + var file = Path.Combine(repo, "tools.json"); + File.WriteAllText(file, SchemaTools.Surface(Tool("search", description: "Short.")).ToJson()); + using var stdout = new StringWriter(); + using var stderr = new StringWriter(); + + var outside = await CliApp.RunAsync(["lint", "--from-file", file], stdout, stderr, sub, TestContext.Current.CancellationToken); + Assert.Equal(1, outside); + Assert.Equal("", stderr.ToString()); + + File.WriteAllText(Path.Combine(repo, "mcpprobe.json"), """{"lint":{"failOn":"none"}}"""); + var inside = await CliApp.RunAsync(["lint", "--from-file", file], stdout, stderr, sub, TestContext.Current.CancellationToken); + Assert.Equal(0, inside); + Assert.Contains("Using config", stderr.ToString(), StringComparison.Ordinal); + } + finally + { + outer.Dispose(); + } + } + + [Fact] + public async Task ConfigFlag_UsesThatFileAndNeedsItToExist() + { + Write("mcpprobe.json", """{"lint":{"failOn":"none"}}"""); + var other = Write(Path.Combine("ci", "lint.json"), """{"lint":{"ignore":[{"rule":"MCPP003"}]}}"""); + var file = Surface(Tool("search", Undescribed)); + + var (exit, output, error) = await LintAsync("--from-file", file, "--config", other); + Assert.Equal((0, $"Using config {other}."), (exit, error.TrimEnd())); + Assert.Contains("(Hidden: 1 ignored.)", output, StringComparison.Ordinal); + + var missing = _dir.File("nope.json"); + (exit, output, error) = await LintAsync("--from-file", file, "--config", missing); + Assert.Equal(2, exit); + Assert.Contains($"error: Config file not found: {missing}.", error, StringComparison.Ordinal); + Assert.Equal("", output); + } + + [Fact] + public async Task NoConfigFlag_SkipsDiscovery_AndConflictsWithConfig() + { + var config = Write("mcpprobe.json", """{"lint":{"failOn":"none"}}"""); + var file = Surface(Tool("search", description: "Short.")); + + Assert.Equal(0, (await LintAsync("--from-file", file)).Exit); + var skipped = await LintAsync("--from-file", file, "--no-config"); + Assert.Equal((1, ""), (skipped.Exit, skipped.Err)); + + var both = await LintAsync("--from-file", file, "--no-config", "--config", config); + Assert.Equal(2, both.Exit); + Assert.Contains("Use either --config or --no-config", both.Err, StringComparison.Ordinal); + } + + [Fact] + public async Task Precedence_EachFlagOverridesTheFile_AndAFlagLeftAloneDoesNot() + { + // Each case: a file that changes the result away from the default, a flag that changes it back. + var short1 = Surface(Tool("search", description: "Short.")); + var nested = Write("nested.json", SchemaTools.Surface(Tool("search", """{"type":"object","properties":{"home":{"type":"object","description":"Home.","properties":{"zip":{"type":"string"}}}}}""")).ToJson()); + var portability = Write("portability.json", SchemaTools.Surface(Tool("search", """{"type":"object","properties":{"x":true}}""")).ToJson()); + + // failOn: file none passes, --fail-on warning fails again. + Write("mcpprobe.json", """{"lint":{"failOn":"none"}}"""); + Assert.Equal(0, (await LintAsync("--from-file", short1)).Exit); + Assert.Equal(1, (await LintAsync("--from-file", short1, "--fail-on", "warning")).Exit); + + // failOn default: a file saying error must not be overridden by the flag's default of warning. + Write("mcpprobe.json", """{"lint":{"failOn":"error"}}"""); + Assert.Equal(0, (await LintAsync("--from-file", short1)).Exit); + + // minDescriptionLength. + Write("mcpprobe.json", """{"lint":{"minDescriptionLength":3,"minDescriptionWords":0}}"""); + Assert.Equal(0, (await LintAsync("--from-file", short1)).Exit); + Assert.Equal(1, (await LintAsync("--from-file", short1, "--min-description-length", "20")).Exit); + + // nested: file on finds MCPP003, --nested false turns it off, --nested alone works without the file. + Write("mcpprobe.json", """{"lint":{"nested":true}}"""); + Assert.Equal(1, (await LintAsync("--from-file", nested)).Exit); + Assert.Equal(0, (await LintAsync("--from-file", nested, "--nested", "false")).Exit); + + // strict. + Write("mcpprobe.json", """{"lint":{"strict":true,"failOn":"none"}}"""); + Assert.Equal(1, (await LintAsync("--from-file", portability)).Exit); + Assert.Equal(0, (await LintAsync("--from-file", portability, "--strict", "false")).Exit); + Write("mcpprobe.json", """{"lint":{"strict":false,"failOn":"none"}}"""); + Assert.Equal(1, (await LintAsync("--from-file", portability, "--strict")).Exit); + } + + [Fact] + public async Task Precedence_RulesMergePerRuleId() + { + Write("mcpprobe.json", """{"lint":{"rules":{"MCPP002":"none","MCPP007":"error"}}}"""); + var file = Surface(Tool("search", """{"type":"object","properties":{"data":{"type":"string","description":"The data to look at."}}}""", description: "Short.")); + + var fromFile = await LintAsync("--from-file", file); + Assert.Equal(1, fromFile.Exit); + Assert.Contains("error MCPP007 search.data", fromFile.Out, StringComparison.Ordinal); + Assert.DoesNotContain("MCPP002", fromFile.Out, StringComparison.Ordinal); + + // The flag changes MCPP007 only; the file's MCPP002=none stays. + var merged = await LintAsync("--from-file", file, "--rule", "MCPP007=info", "--fail-on", "error"); + Assert.Equal(0, merged.Exit); + Assert.Contains("info MCPP007 search.data", merged.Out, StringComparison.Ordinal); + Assert.DoesNotContain("MCPP002", merged.Out, StringComparison.Ordinal); + } + + [Fact] + public async Task Ignore_TurnsAFailingRunIntoAPassingOne_AndNewFindingsStillFail() + { + Write("mcpprobe.json", """{"lint":{"ignore":[{"rule":"MCPP002","tool":"legacy_*","reason":"old"}]}}"""); + var tools = new[] { Tool("legacy_a", description: "Short."), Tool("legacy_b", description: "Short.") }; + + var legacy = await LintAsync("--from-file", Surface(tools)); + Assert.Equal(0, legacy.Exit); + Assert.Equal("No lint findings. (Hidden: 2 ignored.)", legacy.Out.TrimEnd()); + + var added = await LintAsync("--from-file", Surface([.. tools, Tool("fresh", description: "Short.")])); + Assert.Equal(1, added.Exit); + Assert.Contains("1 lint finding(s)", added.Out, StringComparison.Ordinal); + Assert.Contains("MCPP002 fresh", added.Out, StringComparison.Ordinal); + Assert.Contains("Hidden: 2 ignored.", added.Out, StringComparison.Ordinal); + } + + [Fact] + public async Task Ignore_LargeServerWithADeliberateNamingConvention() + { + // 20 tools follow "ns_resource_verb-noun" on purpose, 20 are plain snake_case. + var plain = Enumerable.Range(0, 20).Select(i => Tool($"get_item_{i}")); + var convention = Enumerable.Range(0, 20).Select(i => Tool($"sql_server_firewall-rule_{i}")); + var all = plain.Concat(convention).ToArray(); + + var before = await LintAsync("--from-file", Surface(all), "--no-config"); + Assert.Equal(1, before.Exit); + + Write("mcpprobe.json", """{"lint":{"ignore":[{"rule":"MCPP005","tool":"sql_*","reason":"ns_resource_verb-noun"}]}}"""); + var after = await LintAsync("--from-file", Surface(all)); + Assert.Equal(0, after.Exit); + Assert.StartsWith("No lint findings. (Hidden: ", after.Out, StringComparison.Ordinal); + + var next = await LintAsync("--from-file", Surface([.. all, Tool("getNewThing")])); + Assert.Equal(1, next.Exit); + Assert.Contains("1 lint finding(s)", next.Out, StringComparison.Ordinal); + Assert.Contains("getNewThing", next.Out, StringComparison.Ordinal); + } + + [Fact] + public async Task UnusedIgnoreEntries_AreReportedButNeverFailTheRun() + { + Write("mcpprobe.json", """{"lint":{"ignore":[{"rule":"MCPP005","tool":"gone_*"}]}}"""); + + var (exit, output, _) = await LintAsync("--from-file", Surface(Tool("search"))); + + Assert.Equal(0, exit); + Assert.Equal("No lint findings.\nUnused ignore entries (they matched no finding):\n rule MCPP005, tool gone_*", output.TrimEnd().ReplaceLineEndings("\n")); + } + + [Theory] + [InlineData("""{"lint":{"strict":"yes"}}""", "mcpprobe.json: lint.strict: expected true or false.")] + [InlineData("""{"lint":{"rules":{"MCPP099":"none"}}}""", "mcpprobe.json: lint.rules: unknown rule 'MCPP099'. Rules: MCPP001")] + [InlineData("""{"lint":{"ignore":[{"parameter":"x"}]}}""", "needs a 'rule' or a 'tool'")] + [InlineData("""{"lint": {""", "not valid JSON")] + [InlineData("""{"server":{"stdio":"rm -rf /"}}""", "unknown key 'server'")] + public async Task InvalidConfig_ExitsTwoBeforeConnecting_AndWritesNoReport(string content, string expected) + { + Write("mcpprobe.json", content); + var report = _dir.File("lint.html"); + + // The server option points at a command that would fail loudly if lint got as far as connecting. + var (exit, output, error) = await LintAsync("--stdio", "definitely-not-a-real-command-mcpprobe", "--report", report); + + Assert.Equal(2, exit); + Assert.Equal("", output); + Assert.Contains($"error: ", error, StringComparison.Ordinal); + Assert.Contains(expected, error, StringComparison.Ordinal); + Assert.DoesNotContain("definitely-not-a-real-command", error, StringComparison.Ordinal); + Assert.False(File.Exists(report)); + } + + [Fact] + public async Task Report_IsWrittenWithTheHiddenCountOnExitZeroAndOne() + { + Write("mcpprobe.json", """{"lint":{"ignore":[{"rule":"MCPP003","tool":"a"}]}}"""); + var report = _dir.File("out/lint.html"); + + Assert.Equal(0, (await LintAsync("--from-file", Surface(Tool("a", Undescribed)), "--report", report)).Exit); + Assert.Contains("No lint findings. (Hidden: 1 ignored.)", File.ReadAllText(report), StringComparison.Ordinal); + + Assert.Equal(1, (await LintAsync("--from-file", Surface(Tool("a", Undescribed), Tool("b", Undescribed)), "--report", report)).Exit); + Assert.Contains("Hidden: 1 ignored. Fails on: warning.", File.ReadAllText(report), StringComparison.Ordinal); + } + + [Theory] + [InlineData("tr-TR")] + [InlineData("de-DE")] + public async Task Config_IsCultureIndependent(string culture) + { + var previous = CultureInfo.CurrentCulture; + CultureInfo.CurrentCulture = CultureInfo.CurrentUICulture = new CultureInfo(culture); + try + { + // Lowercase ids and "INFO"/"ERROR" would break under a culture-sensitive ToUpper (Turkish dotless i). + Write("mcpprobe.json", """{"lint":{"failOn":"ERROR","rules":{"mcpp007":"info"},"ignore":[{"rule":"mcpp003","tool":"tool_i*"}]}}"""); + var file = Surface(Tool("tool_item", Undescribed), Tool("tool_other", Undescribed)); + + var (exit, output, _) = await LintAsync("--from-file", file); + + Assert.Equal(0, exit); + Assert.Contains("Hidden: 1 ignored.", output, StringComparison.Ordinal); + Assert.Contains("warning MCPP003 tool_other.city", output, StringComparison.Ordinal); + } + finally + { + CultureInfo.CurrentCulture = CultureInfo.CurrentUICulture = previous; + } + } + + [Fact] + public async Task Help_ShowsTheNewFlags_AndTheDefaultsAreStillListed() + { + using var stdout = new StringWriter(); + using var stderr = new StringWriter(); + + await CliApp.RunAsync(["lint", "--help"], stdout, stderr, TestContext.Current.CancellationToken); + + var help = stdout.ToString(); + Assert.Contains("--config", help, StringComparison.Ordinal); + Assert.Contains("--no-config", help, StringComparison.Ordinal); + Assert.Contains("[default: warning]", help, StringComparison.Ordinal); + Assert.Contains("[default: 20]", help, StringComparison.Ordinal); + } +} diff --git a/tests/McpProbe.Tests/LintConfigSchemaTests.cs b/tests/McpProbe.Tests/LintConfigSchemaTests.cs new file mode 100644 index 0000000..74d950a --- /dev/null +++ b/tests/McpProbe.Tests/LintConfigSchemaTests.cs @@ -0,0 +1,89 @@ +using System.Text.Json.Nodes; +using McpProbe.Cli; +using McpProbe.Linting; + +namespace McpProbe.Tests; + +/// Keeps docs/mcpprobe.schema.json and the README example in step with the loader, which is the source of truth. +public sealed class LintConfigSchemaTests +{ + 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 JsonObject Schema() => + JsonNode.Parse(File.ReadAllText(Path.Combine(RepoRoot(), "docs", "mcpprobe.schema.json")))!.AsObject(); + + private static string[] Keys(JsonNode? properties) => [.. properties!.AsObject().Select(p => p.Key)]; + + [Fact] + public void Schema_PropertyNamesMatchTheLoader() + { + var root = Schema(); + var lint = root["properties"]!["lint"]!; + var ignoreEntry = lint["properties"]!["ignore"]!["items"]!; + + Assert.Equal(LintConfig.RootKeys.Order(StringComparer.Ordinal), Keys(root["properties"]).Order(StringComparer.Ordinal)); + Assert.Equal(LintConfig.LintKeys.Order(StringComparer.Ordinal), Keys(lint["properties"]).Order(StringComparer.Ordinal)); + Assert.Equal(LintConfig.IgnoreKeys.Order(StringComparer.Ordinal), Keys(ignoreEntry["properties"]).Order(StringComparer.Ordinal)); + Assert.False(root["additionalProperties"]!.GetValue()); + Assert.False(lint["additionalProperties"]!.GetValue()); + Assert.False(ignoreEntry["additionalProperties"]!.GetValue()); + } + + [Fact] + public void Schema_EnumsMatchTheRulesAndSeverities() + { + var defs = Schema()["$defs"]!; + + Assert.Equal(LintRules.All.Select(r => r.Id), defs["ruleId"]!["enum"]!.AsArray().Select(n => n!.GetValue())); + Assert.Equal(CliApp.SeverityNames, defs["severity"]!["enum"]!.AsArray().Select(n => n!.GetValue())); + } + + [Fact] + public void Schema_IdMatchesTheUrlTheReadmeAndSamplesReference() + { + var id = Schema()["$id"]!.GetValue(); + + Assert.Contains(id, File.ReadAllText(Path.Combine(RepoRoot(), "README.md")), StringComparison.Ordinal); + Assert.Contains(id, File.ReadAllText(Path.Combine(RepoRoot(), "samples", "WeatherServer.Tests", "mcpprobe.json")), StringComparison.Ordinal); + } + + [Fact] + public void Readme_ConfigExampleParsesWithTheLoader() + { + var lines = File.ReadAllText(Path.Combine(RepoRoot(), "README.md")).ReplaceLineEndings("\n").Split('\n'); + var start = Array.FindIndex(lines, l => l.StartsWith("```jsonc", StringComparison.Ordinal)); + Assert.True(start >= 0, "README has no jsonc example."); + var end = Array.FindIndex(lines, start + 1, l => l.StartsWith("```", StringComparison.Ordinal)); + var example = string.Join('\n', lines[(start + 1)..end]); + + var config = LintConfig.Parse(example, "mcpprobe.json"); + + Assert.Equal(LintSeverity.Warning, config.FailOn); + Assert.Equal(2, config.Ignore.Count); + Assert.Equal(2, config.Rules.Count); + // Every key the loader knows is shown in the example. + foreach (var key in LintConfig.LintKeys.Concat(LintConfig.IgnoreKeys)) + { + Assert.Contains($"\"{key}\"", example, StringComparison.Ordinal); + } + } + + [Fact] + public void SampleConfig_ParsesWithTheLoader() + { + var config = LintConfig.Load(Path.Combine(RepoRoot(), "samples", "WeatherServer.Tests", "mcpprobe.json")); + + Assert.True(config.Strict); + } +} diff --git a/tests/McpProbe.Tests/LintConfigTests.cs b/tests/McpProbe.Tests/LintConfigTests.cs new file mode 100644 index 0000000..7e44aea --- /dev/null +++ b/tests/McpProbe.Tests/LintConfigTests.cs @@ -0,0 +1,231 @@ +using System.Text; +using System.Text.Json.Nodes; +using McpProbe.Cli; +using McpProbe.Linting; +using McpProbe.Tests.TestSupport; + +namespace McpProbe.Tests; + +public sealed class LintConfigTests : IDisposable +{ + private readonly TempDirectory _dir = new(); + + public void Dispose() => _dir.Dispose(); + + private static LintConfig Parse(string json) => LintConfig.Parse(json, "/repo/mcpprobe.json"); + + private string Touch(string relative, string content = "{}") + { + var path = _dir.File(relative); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllText(path, content); + return path; + } + + [Fact] + public void Parse_ReadsEverySetting() + { + var config = Parse(""" + { + "$schema": "https://example.test/schema.json", + "lint": { + "failOn": "Error", + "strict": true, + "nested": false, + "minDescriptionLength": 12, + "minDescriptionWords": 0, + "rules": { "mcpp007": "none", "MCPP003": "ERROR" }, + "ignore": [ + { "rule": "mcpp005", "tool": "sql_*", "reason": "Server convention" }, + { "tool": "legacy", "parameter": "opts" } + ] + } + } + """); + + Assert.Equal(LintSeverity.Error, config.FailOn); + Assert.True(config.Strict); + Assert.False(config.Nested); + Assert.Equal(12, config.MinDescriptionLength); + Assert.Equal(0, config.MinDescriptionWords); + Assert.Equal(LintSeverity.None, config.Rules["MCPP007"]); + Assert.Equal(LintSeverity.Error, config.Rules["MCPP003"]); + Assert.Equal( + [new LintSuppression("MCPP005", "sql_*", null, "Server convention"), new LintSuppression(null, "legacy", "opts", null)], + config.Ignore); + } + + [Fact] + public void Parse_AcceptsCommentsTrailingCommasAndABom() + { + var json = "\uFEFF// why\n{ /* block */ \"lint\": { \"strict\": true, \"rules\": { \"MCPP007\": \"info\", }, }, }\n"; + var path = Touch("bom.json", string.Empty); + File.WriteAllBytes(path, [.. Encoding.UTF8.GetPreamble(), .. Encoding.UTF8.GetBytes(json.TrimStart('\uFEFF'))]); + + var config = LintConfig.Load(path); + + Assert.True(config.Strict); + Assert.Equal(LintSeverity.Info, config.Rules["MCPP007"]); + Assert.True(Parse(json.TrimStart('\uFEFF')).Strict); + } + + [Theory] + [InlineData("{}")] + [InlineData("""{"$schema":"x"}""")] + [InlineData("""{"lint":{}}""")] + public void Parse_EmptyConfigChangesNothing(string json) + { + var options = new LintOptions(); + + Parse(json).ApplyTo(options); + + Assert.Equal(LintSeverity.Warning, options.FailOn); + Assert.Equal(20, options.MinToolDescriptionLength); + Assert.Equal(4, options.MinToolDescriptionWords); + Assert.False(options.Strict); + Assert.False(options.CheckNestedParameters); + Assert.Empty(options.Severities); + Assert.Empty(options.Suppressions); + } + + [Fact] + public void ApplyTo_OverridesTheDefaultsAndAddsRulesAndSuppressions() + { + var options = new LintOptions(); + + Parse("""{"lint":{"failOn":"none","nested":true,"minDescriptionLength":5,"minDescriptionWords":1,"rules":{"MCPP007":"none"},"ignore":[{"rule":"MCPP005"}]}}""").ApplyTo(options); + + Assert.Equal(LintSeverity.None, options.FailOn); + Assert.True(options.CheckNestedParameters); + Assert.Equal(5, options.MinToolDescriptionLength); + Assert.Equal(1, options.MinToolDescriptionWords); + Assert.Equal(LintSeverity.None, options.Severities["MCPP007"]); + Assert.Equal("MCPP005", Assert.Single(options.Suppressions).RuleId); + } + + [Theory] + [InlineData("", "not valid JSON")] + [InlineData("""{"lint":""", "not valid JSON")] + [InlineData("[]", "mcpprobe.json: expected a JSON object.")] + [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":{"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.")] + [InlineData("""{"lint":{"strict":"yes"}}""", "mcpprobe.json: lint.strict: expected true or false.")] + [InlineData("""{"lint":{"nested":1}}""", "mcpprobe.json: lint.nested: expected true or false.")] + [InlineData("""{"lint":{"minDescriptionLength":-1}}""", "mcpprobe.json: lint.minDescriptionLength: expected a whole number, 0 or more.")] + [InlineData("""{"lint":{"minDescriptionLength":2.5}}""", "mcpprobe.json: lint.minDescriptionLength: expected a whole number, 0 or more.")] + [InlineData("""{"lint":{"minDescriptionWords":99999999999}}""", "mcpprobe.json: lint.minDescriptionWords: expected a whole number, 0 or more.")] + [InlineData("""{"lint":{"rules":[]}}""", "mcpprobe.json: lint.rules: expected a JSON object.")] + [InlineData("""{"lint":{"rules":{"MCPP099":"none"}}}""", "mcpprobe.json: lint.rules: unknown rule 'MCPP099'. Rules: MCPP001, MCPP002")] + [InlineData("""{"lint":{"rules":{"MCPP008":"none"}}}""", "mcpprobe.json: lint.rules: unknown rule 'MCPP008'.")] + [InlineData("""{"lint":{"rules":{"MCPP007":"quiet"}}}""", "mcpprobe.json: lint.rules.MCPP007: unknown severity 'quiet'.")] + [InlineData("""{"lint":{"rules":{"MCPP007":"none","mcpp007":"info"}}}""", "mcpprobe.json: lint.rules: rule 'MCPP007' is listed twice.")] + [InlineData("""{"lint":{"ignore":{}}}""", "mcpprobe.json: lint.ignore: expected an array of entries.")] + [InlineData("""{"lint":{"ignore":["MCPP005"]}}""", "mcpprobe.json: lint.ignore[0]: expected a JSON object.")] + [InlineData("""{"lint":{"ignore":[{"rule":"MCPP005"},{}]}}""", "mcpprobe.json: lint.ignore[1]: needs a 'rule' or a 'tool'.")] + [InlineData("""{"lint":{"ignore":[{"rule":"MCPP005","why":"x"}]}}""", "mcpprobe.json: lint.ignore[0]: unknown key 'why'. Keys: rule, tool, parameter, reason.")] + [InlineData("""{"lint":{"ignore":[{"rule":"MCPP098"}]}}""", "mcpprobe.json: lint.ignore[0]: unknown rule 'MCPP098'.")] + [InlineData("""{"lint":{"ignore":[{"tool":""}]}}""", "mcpprobe.json: lint.ignore[0].tool: expected a non-empty string.")] + [InlineData("""{"lint":{"ignore":[{"tool":"a","parameter":7}]}}""", "mcpprobe.json: lint.ignore[0].parameter: expected a non-empty string.")] + [InlineData("""{"lint":{"ignore":[{"tool":"a","reason":false}]}}""", "mcpprobe.json: lint.ignore[0].reason: expected a non-empty string.")] + public void Parse_RejectsBadInputWithAPreciseMessage(string json, string expected) + { + var error = Assert.Throws(() => Parse(json)); + + Assert.Contains(expected, error.Message, StringComparison.Ordinal); + } + + [Fact] + public void Parse_UnknownKeysAreSanitized() + { + var error = Assert.Throws(() => Parse("{\"bad\\u001b[2Jkey\":1}")); + + Assert.DoesNotContain('\u001b', error.Message); + } + + [Fact] + public void Parse_DuplicateKeysAreRejectedNotSilentlyMerged() + { + var error = Assert.Throws(() => Parse("""{"lint":{"strict":true,"strict":false}}""")); + + Assert.Contains("mcpprobe.json is not valid JSON", error.Message, StringComparison.Ordinal); + } + + [Fact] + public void Discover_FindsTheFileInTheStartDirectoryAndInParents() + { + var file = Touch(Path.Combine("repo", "mcpprobe.json")); + Directory.CreateDirectory(_dir.File(Path.Combine("repo", "src", "server"))); + Directory.CreateDirectory(_dir.File(Path.Combine("repo", ".git"))); + + Assert.Equal(file, LintConfig.Discover(_dir.File("repo"))); + Assert.Equal(file, LintConfig.Discover(_dir.File(Path.Combine("repo", "src", "server")))); + } + + [Fact] + public void Discover_NearestFileWins() + { + Touch(Path.Combine("repo", "mcpprobe.json")); + var nearer = Touch(Path.Combine("repo", "src", "mcpprobe.json")); + Directory.CreateDirectory(_dir.File(Path.Combine("repo", "src", "server"))); + + Assert.Equal(nearer, LintConfig.Discover(_dir.File(Path.Combine("repo", "src", "server")))); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void Discover_StopsAtTheRepositoryRoot_GitFolderOrWorktreeFile(bool gitIsAFolder) + { + Touch(Path.Combine("outer", "mcpprobe.json")); + var repo = _dir.File(Path.Combine("outer", "repo")); + var inner = Path.Combine(repo, "src"); + Directory.CreateDirectory(inner); + if (gitIsAFolder) + { + Directory.CreateDirectory(Path.Combine(repo, ".git")); + } + else + { + File.WriteAllText(Path.Combine(repo, ".git"), "gitdir: ../elsewhere"); + } + + Assert.Null(LintConfig.Discover(inner)); + var inRoot = Touch(Path.Combine("outer", "repo", "mcpprobe.json")); + Assert.Equal(inRoot, LintConfig.Discover(inner)); + } + + [Fact] + public void Discover_IgnoresADirectoryNamedLikeTheFile() + { + Directory.CreateDirectory(_dir.File(Path.Combine("repo", "mcpprobe.json"))); + Directory.CreateDirectory(_dir.File(Path.Combine("repo", ".git"))); + + Assert.Null(LintConfig.Discover(_dir.File("repo"))); + } + + [Fact] + public void KnownKeys_MatchWhatTheLoaderAccepts() + { + var lint = new JsonObject(); + foreach (var key in LintConfig.LintKeys) + { + lint[key] = key switch + { + "failOn" => "info", + "strict" or "nested" => true, + "minDescriptionLength" or "minDescriptionWords" => 1, + "rules" => new JsonObject(), + _ => new JsonArray(), + }; + } + + var json = new JsonObject { ["lint"] = lint }.ToJsonString(); + + Assert.NotNull(Parse(json)); + } +} diff --git a/tests/McpProbe.Tests/ToolLinterSuppressionTests.cs b/tests/McpProbe.Tests/ToolLinterSuppressionTests.cs new file mode 100644 index 0000000..e1d025f --- /dev/null +++ b/tests/McpProbe.Tests/ToolLinterSuppressionTests.cs @@ -0,0 +1,317 @@ +using McpProbe.Linting; +using McpProbe.Tests.TestSupport; +using ModelContextProtocol.Protocol; +using WeatherServer; +using static McpProbe.Tests.TestSupport.SchemaTools; + +namespace McpProbe.Tests; + +public sealed class ToolLinterSuppressionTests +{ + private const string Undescribed = """{"type":"object","properties":{"city":{"type":"string"},"zip":{"type":"string"}}}"""; + + private static LintOptions With(params LintSuppression[] suppressions) + { + var options = new LintOptions(); + foreach (var suppression in suppressions) + { + options.Suppressions.Add(suppression); + } + + return options; + } + + private static LintReport Lint(LintOptions options, params Tool[] tools) => ToolLinter.Lint(tools, options); + + [Theory] + [InlineData("*", "", true)] + [InlineData("", "", true)] + [InlineData("", "a", false)] + [InlineData("a*", "abc", true)] + [InlineData("*c", "abc", true)] + [InlineData("a*c", "ac", true)] + [InlineData("a?c", "abc", true)] + [InlineData("a?c", "ac", false)] + [InlineData("?", "", false)] + [InlineData("sql_*", "sql_server_list", true)] + [InlineData("sql_*", "SQL_server_list", false)] + [InlineData("sql_*", "nosql_server_list", false)] + [InlineData("a.b", "a.b", true)] + [InlineData("a.b", "axb", false)] + [InlineData("[ab]", "a", false)] + [InlineData("stops[].city", "stops[].city", true)] + [InlineData("address.*", "address.zip", true)] + [InlineData("*a*b*c", "xaxbxcxc", true)] + [InlineData("*a*b*c", "xaxbxcx", false)] + public void Glob_MatchesStarAndQuestionMarkOnly(string pattern, string value, bool expected) => + Assert.Equal(expected, LintSuppression.GlobMatches(pattern, value)); + + [Fact] + public void Glob_LongInputDoesNotBacktrackExponentially() + { + var value = new string('a', 10_000); + + Assert.False(LintSuppression.GlobMatches("*a*a*a*a*a*a*b", value)); + Assert.True(LintSuppression.GlobMatches("*a*a*a*a*a*a", value)); + } + + [Fact] + public void Suppressions_AreEmptyByDefault_AndChangeNothing() + { + var tools = new[] { Tool("search", Undescribed), Tool("nope", description: null) }; + + var plain = ToolLinter.Lint(tools); + var withEmpty = ToolLinter.Lint(tools, new LintOptions()); + + Assert.Empty(new LintOptions().Suppressions); + Assert.Equal(plain.Findings, withEmpty.Findings); + Assert.Empty(plain.SuppressedFindings); + Assert.Empty(plain.UnusedSuppressions); + Assert.Equal(plain.ToReport(), withEmpty.ToReport()); + Assert.DoesNotContain("Hidden", plain.ToReport(), StringComparison.Ordinal); + } + + [Fact] + public void Suppress_ByRule_HidesEveryFindingOfThatRule() + { + var report = Lint(With(new LintSuppression(RuleId: "mcpp003")), Tool("a", Undescribed), Tool("b", Undescribed)); + + Assert.Empty(report.Findings); + Assert.Equal(4, report.SuppressedFindings.Count); + Assert.All(report.SuppressedFindings, f => Assert.Equal("MCPP003", f.RuleId)); + Assert.False(report.Failed); + } + + [Fact] + public void Suppress_ByToolGlob_OnlyHidesMatchingTools() + { + var report = Lint(With(new LintSuppression(ToolPattern: "sql_*")), Tool("sql_list", Undescribed), Tool("sql_get", Undescribed), Tool("web_get", Undescribed)); + + Assert.All(report.Findings, f => Assert.Equal("web_get", f.ToolName)); + Assert.Equal(2, report.Findings.Count); + Assert.Equal(4, report.SuppressedFindings.Count); + Assert.True(report.Failed); + } + + [Fact] + public void Suppress_ByParameterGlob_OnlyHidesMatchingParameters() + { + var report = Lint(With(new LintSuppression(RuleId: "MCPP003", ParameterPattern: "zip")), Tool("a", Undescribed)); + + Assert.Equal("city", Assert.Single(report.Findings).ParameterName); + Assert.Equal("zip", Assert.Single(report.SuppressedFindings).ParameterName); + } + + [Fact] + public void Suppress_ParameterPattern_NeverMatchesToolLevelFindings() + { + var report = Lint(With(new LintSuppression(ToolPattern: "*", ParameterPattern: "*")), Tool("a", description: null)); + + Assert.Equal("MCPP001", Assert.Single(report.Findings).RuleId); + Assert.Empty(report.SuppressedFindings); + Assert.Single(report.UnusedSuppressions); + } + + [Fact] + public void Suppress_RuleAndToolAndParameter_AllMustMatch() + { + var options = With(new LintSuppression("MCPP003", "a", "zip")); + + var report = Lint(options, Tool("a", Undescribed), Tool("b", Undescribed)); + + Assert.Equal(3, report.Findings.Count); + Assert.DoesNotContain(report.Findings, f => f is { ToolName: "a", ParameterName: "zip" }); + Assert.Single(report.SuppressedFindings); + } + + [Fact] + public void Suppress_NestedParameterPaths_MatchWithDotsAndBrackets() + { + var schema = """{"type":"object","properties":{"address":{"type":"object","description":"Where.","properties":{"zip":{"type":"string"}}},"stops":{"type":"array","description":"Stops.","items":{"type":"object","properties":{"city":{"type":"string"}}}}}}"""; + var options = With(new LintSuppression("MCPP003", ParameterPattern: "address.*"), new LintSuppression("MCPP003", ParameterPattern: "stops[].city")); + options.CheckNestedParameters = true; + + var report = Lint(options, Tool("trip", schema)); + + Assert.Empty(report.Findings); + Assert.Equal(["address.zip", "stops[].city"], report.SuppressedFindings.Select(f => f.ParameterName).Order(StringComparer.Ordinal)); + Assert.Empty(report.UnusedSuppressions); + } + + [Fact] + public void Suppress_SchemaPathFindings_WithStrictAndWithARuleSeverityOnly() + { + var schema = """{"type":"object","properties":{"city":true}}"""; + var suppression = new LintSuppression("MCPP009", ParameterPattern: "inputSchema.properties.*"); + + var strict = With(suppression); + strict.Strict = true; + var onlyThroughRule = With(suppression); + onlyThroughRule.Severities["MCPP009"] = LintSeverity.Error; + + foreach (var options in new[] { strict, onlyThroughRule }) + { + var report = Lint(options, Tool("a", schema, description: "Looks things up in the catalog.")); + + Assert.DoesNotContain(report.Findings, f => f.RuleId == "MCPP009"); + Assert.Contains(report.SuppressedFindings, f => f.RuleId == "MCPP009" && f.ParameterName == "inputSchema.properties.city"); + } + + Assert.True(Lint(new LintOptions { Strict = true }, Tool("a", schema, description: "Looks things up in the catalog.")).Failed); + } + + [Fact] + public void Suppress_PortabilityErrorsKeepTheirFloorForTheRemainingFindings() + { + var schema = """{"type":"object","properties":{"a":true,"b":true}}"""; + var options = With(new LintSuppression("MCPP009", ParameterPattern: "inputSchema.properties.a")); + options.Strict = true; + options.FailOn = LintSeverity.None; + + var report = Lint(options, Tool("t", schema, description: "Looks things up in the catalog.")); + + Assert.Equal("inputSchema.properties.b", Assert.Single(report.Findings, f => f.RuleId == "MCPP009").ParameterName); + Assert.True(report.Failed); + } + + [Fact] + public void Suppress_FailOnOnlySeesTheRemainingFindings() + { + var tool = Tool("search", description: "Short."); + + Assert.True(Lint(new LintOptions(), tool).Failed); + Assert.False(Lint(With(new LintSuppression(RuleId: "MCPP002")), tool).Failed); + Assert.True(Lint(With(new LintSuppression(RuleId: "MCPP002", ToolPattern: "other")), tool).Failed); + } + + [Fact] + public void Suppress_ConsistencyFindings_AreKeyedByTheOffendingTool() + { + var options = With(new LintSuppression("MCPP005", "getC")); + var tools = new[] { Tool("get_a"), Tool("get_b"), Tool("get_c"), Tool("getC") }; + + Assert.Empty(Lint(options, tools).Findings); + Assert.Equal("getC", Assert.Single(Lint(options, tools).SuppressedFindings).ToolName); + + // A new offender is not covered by an entry for another tool. + var more = Lint(options, [.. tools, Tool("getD")]); + Assert.Equal("getD", Assert.Single(more.Findings).ToolName); + } + + [Fact] + public void Suppress_OddToolNames() + { + var tool = Tool("we\"ird\u202e\n名前*", description: null); + + var report = Lint(With(new LintSuppression(ToolPattern: "we\"ird*")), tool); + + Assert.Empty(report.Findings); + Assert.Contains(report.SuppressedFindings, f => f.RuleId == "MCPP001"); + } + + [Fact] + public void Report_ListsHiddenCountsAndUnusedEntries_WithoutFailing() + { + var options = With(new LintSuppression(RuleId: "MCPP003", ToolPattern: "a"), new LintSuppression(RuleId: "MCPP004", ToolPattern: "gone_*", Reason: "old")); + + var report = Lint(options, Tool("a", Undescribed), Tool("b", Undescribed)); + + Assert.Single(report.UnusedSuppressions); + var lines = report.ToReport().Split('\n'); + Assert.Equal("2 lint finding(s): 0 error, 2 warning, 0 info.", lines[0]); + Assert.StartsWith(" warning MCPP003 b.city: ", lines[1], StringComparison.Ordinal); + Assert.StartsWith(" warning MCPP003 b.zip: ", lines[2], StringComparison.Ordinal); + Assert.Equal(["Hidden: 2 ignored.", "Unused ignore entries (they matched no finding):", " rule MCPP004, tool gone_*"], lines[3..]); + } + + [Fact] + public void Report_NoFindingsButHidden_SaysSo_AndHtmlGetsTheSameSentence() + { + var report = Lint(With(new LintSuppression(RuleId: "MCPP003")), Tool("a", Undescribed)); + + Assert.Equal("No lint findings. (Hidden: 2 ignored.)", report.ToReport()); + Assert.False(report.Failed); + var html = report.ToHtml(); + Assert.Contains("No lint findings. (Hidden: 2 ignored.)", html, StringComparison.Ordinal); + Assert.Contains("Passed", html, StringComparison.Ordinal); + } + + [Fact] + public void Report_HtmlSummaryMentionsHiddenFindings() + { + var report = Lint(With(new LintSuppression(RuleId: "MCPP003", ToolPattern: "a")), Tool("a", Undescribed), Tool("b", Undescribed)); + + Assert.Contains("2 lint finding(s): 0 error, 2 warning, 0 info. Hidden: 2 ignored. Fails on: warning.", report.ToHtml(), StringComparison.Ordinal); + } + + [Fact] + public void UnusedSuppressions_AreCappedAndSanitized() + { + var options = new LintOptions(); + for (var i = 0; i < 25; i++) + { + options.Suppressions.Add(new LintSuppression(ToolPattern: $"gone_{i}\u001b[2J")); + } + + var text = Lint(options, Tool("a")).ToReport(); + + Assert.Contains("\n tool gone_19\\u001B[2J", text, StringComparison.Ordinal); + Assert.DoesNotContain("gone_20", text, StringComparison.Ordinal); + Assert.EndsWith("\n and 5 more", text, StringComparison.Ordinal); + Assert.DoesNotContain('\u001b', text); + } + + [Fact] + public void UnusedSuppressions_SkipEntriesForRulesThatDidNotRun() + { + var portability = new LintSuppression("MCPP010", "*"); + var off = new LintSuppression("MCPP002", "*"); + var nested = new LintSuppression("MCPP003", ParameterPattern: "address.zip"); + var schemaPath = new LintSuppression("MCPP011", ParameterPattern: "inputSchema.properties.x"); + + var defaults = Lint(With(portability, off, nested, schemaPath), Tool("a")); + Assert.Equal([off], defaults.UnusedSuppressions); + + var ranOptions = With(portability, off, nested, schemaPath); + ranOptions.Strict = true; + ranOptions.CheckNestedParameters = true; + ranOptions.Severities["MCPP002"] = LintSeverity.None; + var ran = Lint(ranOptions, Tool("a")); + Assert.Equal([portability, nested, schemaPath], ran.UnusedSuppressions); + } + + [Fact] + public void Lint_RejectsSuppressionsThatWouldHideEverything() + { + Assert.Throws(() => Lint(With(new LintSuppression()), Tool("a"))); + Assert.Throws(() => Lint(With(new LintSuppression(ParameterPattern: "*")), Tool("a"))); + + var options = new LintOptions(); + options.Suppressions.Add(null!); + Assert.Throws(() => Lint(options, Tool("a"))); + } + + [Fact] + public void Suppressions_ApplyToEveryLintOverload() + { + var tools = new[] { Tool("a", description: null) }; + var options = With(new LintSuppression(RuleId: "MCPP001")); + + Assert.Empty(ToolLinter.Lint(tools, options).Findings); + Assert.Empty(ToolLinter.Lint(Surface(tools), options).Findings); + Assert.Single(ToolLinter.Lint(Surface(tools), options).SuppressedFindings); + } + + [Fact] + public async Task Suppressions_FlowThroughTheHostAndThePassesLintAssertion() + { + await using var probe = await McpProbeHost.StartAsync(mcp => mcp.WithWeatherFeatures(), TestContext.Current.CancellationToken); + var options = With(new LintSuppression(RuleId: "MCPP005", ToolPattern: "*")); + + var report = await probe.LintToolsAsync(options, TestContext.Current.CancellationToken); + + Assert.Empty(report.Findings); + Assert.Single(report.UnusedSuppressions); + Assert.Contains("Unused ignore entries", report.ToReport(), StringComparison.Ordinal); + } +}