Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ jobs:
from-file: samples/WeatherServer.Tests/mcp-tools.json
baseline: samples/WeatherServer.Tests/mcp-tools.json
config: samples/WeatherServer.Tests/mcpprobe.json
lint-baseline: samples/WeatherServer.Tests/mcpprobe-lint-baseline.json

- name: Assert HTML reports were written
if: matrix.os == 'ubuntu-latest' || matrix.os == 'windows-latest'
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ All notable changes to this project are documented here. The format is based on
- `mcpprobe.json`: a committed config file for `mcpprobe lint` (`failOn`, `strict`, `nested`, `minDescriptionLength`, `minDescriptionWords`, `rules`, and `ignore`). `lint` uses the nearest file, starting in the current directory and going up to the repository root (the first folder with a `.git`), and says `Using config <path>.` on stderr. New flags: `--config <file>` and `--no-config`. Order of precedence: defaults, then the file, then flags typed on the command line (`--nested false` and `--strict false` can turn a file setting off; `--rule` merges per rule id). Without a file nothing changes. The file is read strictly (unknown keys, wrong types and unknown rule ids exit 2), allows comments and trailing commas, and holds lint settings only, not a server to start. A repository that already has an unrelated `mcpprobe.json` will now have it read by `lint`. JSON schema: `docs/mcpprobe.schema.json`.
- `ignore` entries hide findings by rule, tool pattern and parameter pattern (`*` and `?`, case-sensitive), with an optional `reason`. Hidden findings never fail the run. The report ends with `Hidden: N ignored.` and lists entries that matched nothing (it never fails for them).
- `LintSuppression`, `LintOptions.Suppressions`, `LintReport.SuppressedFindings` and `LintReport.UnusedSuppressions`, the same thing for library users. The library does not read `mcpprobe.json`.
- Lint baseline: `mcpprobe lint --write-baseline <file>` writes the current findings (sorted, no timestamps) and exits 0; `lint --baseline <file>`, or `"baseline"` in `mcpprobe.json`, hides them so only new findings fail. The report says `Hidden: N baselined.` and lists entries that no longer match (they never fail the run). Entries are rule, tool and optional parameter, not the message. Library: `LintBaseline`, `LintBaselineEntry`, `LintOptions.Baseline`, `LintReport.BaselinedFindings` and `LintReport.StaleBaselineEntries`. Action input `lint-baseline` and template parameter `lintBaseline` (passed as `--baseline`).
- GitHub Action and Azure Pipelines template input `config` (passed as `--config`). Empty by default: lint finds a committed `mcpprobe.json` on its own. It needs a CLI that has `--config`; the wrapper fails fast if the installed tool does not.

### Changed
Expand Down
25 changes: 22 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,8 @@ A server with legacy debt can keep its lint settings, and the findings it has de
"ignore": [
{ "rule": "MCPP005", "tool": "sql_*", "reason": "Server convention: namespace_resource_verb-noun" },
{ "rule": "MCPP003", "tool": "legacy_export", "parameter": "opts" }
]
],
"baseline": "mcpprobe-lint-baseline.json"
}
}
```
Expand All @@ -177,6 +178,22 @@ A server with legacy debt can keep its lint settings, and the findings it has de

In code, the same thing is `LintOptions.Suppressions.Add(new LintSuppression(RuleId: "MCPP005", ToolPattern: "sql_*"))`. The library does not read `mcpprobe.json`; hidden findings are in `LintReport.SuppressedFindings` and unused entries in `LintReport.UnusedSuppressions`.

### Lint baseline

To adopt lint on a server that already has findings, accept the current ones and fail only on new ones. Write a baseline once, commit it, and check against it in CI:

```bash
mcpprobe lint --stdio "dotnet run --project src/MyServer" --write-baseline mcpprobe-lint-baseline.json
mcpprobe lint --stdio "dotnet run --project src/MyServer" --baseline mcpprobe-lint-baseline.json
```

- `--write-baseline <file>` writes every finding of the run (after `ignore`) and exits 0. It is sorted and has no timestamps, so a refresh is an easy diff to review. Run it with the same flags and config as CI (`--strict`, `--nested`).
- `--baseline <file>`, or `"baseline"` in `mcpprobe.json` (relative to that file; the flag wins), hides the findings it lists. The report says `Hidden: 20 baselined.`, and new findings fail as usual. A missing or unreadable file is exit 2. Use either `--baseline` or `--write-baseline`, not both; `--write-baseline` ignores `"baseline"` from the config, so the first write works before the file exists.
- An entry is a rule, a tool and an optional parameter. The message is not part of it, so a baseline survives wording changes in a new McpProbe, but a finding that changes meaning on the same tool and parameter stays hidden.
- Entries that no longer match (the tool was fixed, renamed or removed) are listed under `Baseline: N entries no longer match.` They never fail the run; write the baseline again to drop them. Entries for a rule that did not run, such as MCPP010 without `--strict`, are not listed. A baseline written without `--strict` does not hide the `--strict` findings.

In code: `new LintOptions { Baseline = LintBaseline.Load("mcpprobe-lint-baseline.json") }`, and `LintBaseline.FromReport(report).ToJson()` to write one. Hidden findings are in `LintReport.BaselinedFindings` and entries that matched nothing in `LintReport.StaleBaselineEntries`.

## CLI in CI

Write a snapshot once and commit it, then check it in CI:
Expand Down Expand Up @@ -250,12 +267,14 @@ jobs:
baseline: mcp-tools.json
```

Inputs follow the CLI: `stdio`, `http`, or `from-file` (exactly one), plus `baseline` (default `mcp-tools.json`), `header`, `env`, `cwd`, `timeout`, `diff`, `lint`, `fail-on-non-breaking`, `fail-on`, `nested`, `rule`, `min-description-length`, `strict`, `transport`, `report`, `config`, `version`, and `source`. Both `diff` and `lint` are on by default. The Action fails the step on a breaking change or a lint finding at or above `--fail-on` (default `warning`, or `failOn` from [`mcpprobe.json`](#config-file-and-ignore-rules) when `fail-on` is empty).
Inputs follow the CLI: `stdio`, `http`, or `from-file` (exactly one), plus `baseline` (default `mcp-tools.json`), `header`, `env`, `cwd`, `timeout`, `diff`, `lint`, `fail-on-non-breaking`, `fail-on`, `nested`, `rule`, `min-description-length`, `strict`, `transport`, `report`, `config`, `lint-baseline`, `version`, and `source`. Both `diff` and `lint` are on by default. The Action fails the step on a breaking change or a lint finding at or above `--fail-on` (default `warning`, or `failOn` from [`mcpprobe.json`](#config-file-and-ignore-rules) when `fail-on` is empty).

`strict`, `transport`, and `report` are off by default, so an unchanged workflow runs the same commands as before. `strict` is lint-only. `transport` is only used with `http`. `report` is a directory, not a file: the Action writes `lint.html` and/or `diff.html` there (both checks run by default, so a single file path would overwrite one report with the other). The job summary stays the plain-text report. Upload is left to your workflow.

`config` is the path of a [`mcpprobe.json`](#config-file-and-ignore-rules) for lint. Leave it empty and lint finds one on its own, starting in the step's working directory (the repository root after `actions/checkout`), so a committed `mcpprobe.json` is used without any input. `config` needs a CLI that has `--config`, the release after 0.4.0-preview; the Action fails fast with a message if the installed tool lacks it.

`lint-baseline` is passed to lint as `--baseline` (the `baseline` input is the snapshot for `diff`). It overrides `"baseline"` in `mcpprobe.json` and has the same CLI requirement as `config`. There is no input to write a baseline; do that locally and commit the file.

`strict` and `transport` also work against the 0.3.0-preview CLI. `report` needs a CLI that has `--report`, which is 0.4.0-preview or later. If you set `report` and the installed tool lacks the flag, the Action fails fast with a message instead of a generic "unrecognized option". Do not add these inputs to a workflow that pins `ShmueLior/mcpprobe@v0.3.0-preview`; that tag's wrapper does not have them.

```yaml
Expand Down Expand Up @@ -301,7 +320,7 @@ steps:
baseline: mcp-tools.json
```

The template needs bash (Git Bash on Windows). It also accepts `strict`, `transport`, `report` (a directory, as in the Action) and `config`. Do not add those parameters to a pipeline that pins `refs/tags/v0.3.0-preview`; that tag's template does not have them. Upload is a separate step; the template does not publish an artifact:
The template needs bash (Git Bash on Windows). It also accepts `strict`, `transport`, `report` (a directory, as in the Action), `config` and `lintBaseline`. Do not add those parameters to a pipeline that pins `refs/tags/v0.3.0-preview`; that tag's template does not have them. Upload is a separate step; the template does not publish an artifact:

```yaml
- task: PublishPipelineArtifact@1
Expand Down
8 changes: 8 additions & 0 deletions action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,13 @@ inputs:
that has --config.
required: false
default: ''
lint-baseline:
description: >-
Path to a lint baseline written by 'mcpprobe lint --write-baseline'. Findings
in it don't fail lint. Not the snapshot (that is baseline). Overrides baseline
in mcpprobe.json. Requires a CLI that has lint --baseline.
required: false
default: ''
transport:
description: >-
Pin the HTTP transport: auto, streamable-http, or sse. Only used with http.
Expand Down Expand Up @@ -156,6 +163,7 @@ runs:
MCPPROBE_MIN_DESCRIPTION_LENGTH: ${{ inputs.min-description-length }}
MCPPROBE_STRICT: ${{ inputs.strict }}
MCPPROBE_CONFIG: ${{ inputs.config }}
MCPPROBE_LINT_BASELINE: ${{ inputs.lint-baseline }}
MCPPROBE_TRANSPORT: ${{ inputs.transport }}
MCPPROBE_REPORT: ${{ inputs.report }}
MCPPROBE_VERSION: ${{ inputs.version }}
Expand Down
5 changes: 5 additions & 0 deletions action/run.sh
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,10 @@ config_path=$(trim_ws "${MCPPROBE_CONFIG:-}")
if [[ -n "$config_path" && "$run_lint" == true ]]; then
require_cli_flag config --config
fi
lint_baseline=$(trim_ws "${MCPPROBE_LINT_BASELINE:-}")
if [[ -n "$lint_baseline" && "$run_lint" == true ]]; then
require_cli_flag lint-baseline --baseline
fi

if [[ -n "$report_dir" ]]; then
mkdir -p "$report_dir" || die "Could not create the report directory '$report_dir'."
Expand Down Expand Up @@ -344,6 +348,7 @@ if [[ "$run_lint" == true ]]; then
done < <(each_nonempty_line "${MCPPROBE_RULE:-}")
is_true "${MCPPROBE_STRICT:-}" && lint_args+=(--strict)
[[ -n "$config_path" ]] && lint_args+=(--config "$config_path")
[[ -n "$lint_baseline" ]] && lint_args+=(--baseline "$lint_baseline")
[[ -n "$report_dir" ]] && lint_args+=(--report "$report_dir/lint.html")
lint_exit=0
run_mcpprobe "McpProbe lint" "${lint_args[@]}" || lint_exit=$?
Expand Down
5 changes: 5 additions & 0 deletions docs/mcpprobe.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,11 @@
}
}
}
},
"baseline": {
"description": "Lint baseline file written by 'mcpprobe lint --write-baseline', relative to this file. Findings in it never fail the run. Same as --baseline, which overrides it.",
"type": "string",
"minLength": 1
}
}
}
Expand Down
4 changes: 4 additions & 0 deletions samples/WeatherServer.Tests/mcpprobe-lint-baseline.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"formatVersion": 1,
"findings": []
}
61 changes: 50 additions & 11 deletions src/McpProbe.Cli/CliApp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,20 +84,19 @@ private static Command BuildSnapshotCommand(TextWriter stdout, TextWriter stderr
};

/// <summary>A blank <c>--report</c> is a usage error; checked before connecting so nothing is written.</summary>
private static string? ReportPath(ParseResult parse, Option<string?> report)
{
var value = parse.GetValue(report);
return value is null ? null : string.IsNullOrWhiteSpace(value) ? throw new ArgumentException("--report needs a file path.") : Path.GetFullPath(value);
}
private static string? ReportPath(ParseResult parse, Option<string?> report) => FilePath(parse.GetValue(report), "--report");

private static string? FilePath(string? value, string flag) =>
value is null ? null : string.IsNullOrWhiteSpace(value) ? throw new ArgumentException($"{flag} needs a file path.") : Path.GetFullPath(value);

/// <summary>Writes through a sibling temp file so a failure never leaves a partial report.</summary>
private static async Task WriteReportAsync(string path, string html, CancellationToken ct)
/// <summary>Writes through a sibling temp file so a failure never leaves a partial file.</summary>
private static async Task WriteFileAtomicAsync(string path, string text, CancellationToken ct)
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
var temp = $"{path}.{Guid.NewGuid():N}.tmp";
try
{
await File.WriteAllTextAsync(temp, html, ct).ConfigureAwait(false);
await File.WriteAllTextAsync(temp, text, ct).ConfigureAwait(false);
File.Move(temp, path, overwrite: true);
}
finally
Expand Down Expand Up @@ -142,7 +141,7 @@ private static Command BuildDiffCommand(TextWriter stdout, TextWriter stderr)
await stdout.WriteLineAsync(diff.ToReport()).ConfigureAwait(false);
if (reportPath is not null)
{
await WriteReportAsync(reportPath, diff.ToHtml(), ct).ConfigureAwait(false);
await WriteFileAtomicAsync(reportPath, diff.ToHtml(), ct).ConfigureAwait(false);
}

if (diff.HasBreakingChanges || (diff.HasChanges && parse.GetValue(failOnNonBreaking)))
Expand Down Expand Up @@ -192,6 +191,14 @@ private static Command BuildLintCommand(TextWriter stdout, TextWriter stderr, st
{
Description = $"Don't look for {LintConfig.FileName}.",
};
var baseline = new Option<string?>("--baseline")
{
Description = "Hide the findings listed in this lint baseline file, so only new findings fail. Overrides lint.baseline in the config file.",
};
var writeBaseline = new Option<string?>("--write-baseline")
{
Description = "Write every finding to this lint baseline file and exit 0. Run it again to refresh the file.",
};
var report = BuildReportOption();
var command = new Command("lint", "Lint tool names, descriptions and parameters. Exits 1 on findings at or above --fail-on, or on a portability error when --strict is set.");
server.AddTo(command);
Expand All @@ -202,18 +209,42 @@ private static Command BuildLintCommand(TextWriter stdout, TextWriter stderr, st
command.Options.Add(strict);
command.Options.Add(config);
command.Options.Add(noConfig);
command.Options.Add(baseline);
command.Options.Add(writeBaseline);
command.Options.Add(report);
command.SetAction((parse, ct) => RunGuardedAsync(stderr, async () =>
{
var reportPath = ReportPath(parse, report);
var writePath = FilePath(parse.GetValue(writeBaseline), "--write-baseline");
var baselinePath = FilePath(parse.GetValue(baseline), "--baseline");
if (writePath is not null && baselinePath is not null)
{
throw new ArgumentException("Use either --baseline or --write-baseline, not both.");
}

var options = new LintOptions();

// Library defaults < config file < flags typed on this command line (a flag left at its default doesn't count).
var configPath = ConfigPath(parse.GetValue(config), parse.GetValue(noConfig), workingDirectory);
if (configPath is not null)
{
await stderr.WriteLineAsync($"Using config {PrintableLines(configPath)}.").ConfigureAwait(false);
LintConfig.Load(configPath).ApplyTo(options);
var file = LintConfig.Load(configPath);
file.ApplyTo(options);

// Writing a baseline must see every finding, so the file's baseline is only used for checking.
baselinePath ??= writePath is null ? file.Baseline : null;
}

if (baselinePath is not null)
{
if (!File.Exists(baselinePath))
{
await stderr.WriteLineAsync($"Lint baseline not found: {PrintableLines(baselinePath)}. Create it with 'mcpprobe lint --write-baseline <path>'.").ConfigureAwait(false);
return ExitCodes.Error;
}

options.Baseline = LintBaseline.Load(baselinePath);
}

if (IsSet(parse, failOn))
Expand Down Expand Up @@ -253,7 +284,15 @@ private static Command BuildLintCommand(TextWriter stdout, TextWriter stderr, st
await stdout.WriteLineAsync(lint.ToReport()).ConfigureAwait(false);
if (reportPath is not null)
{
await WriteReportAsync(reportPath, lint.ToHtml(), ct).ConfigureAwait(false);
await WriteFileAtomicAsync(reportPath, lint.ToHtml(), ct).ConfigureAwait(false);
}

if (writePath is not null)
{
var written = LintBaseline.FromReport(lint);
await WriteFileAtomicAsync(writePath, written.ToJson(), ct).ConfigureAwait(false);
await stdout.WriteLineAsync(string.Create(CultureInfo.InvariantCulture, $"Wrote {written.Entries.Count} finding(s) to {PrintableLines(writePath)}")).ConfigureAwait(false);
return ExitCodes.Success;
}

return lint.Failed ? ExitCodes.CheckFailed : ExitCodes.Success;
Expand Down
10 changes: 8 additions & 2 deletions src/McpProbe.Cli/LintConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ internal sealed class LintConfig
public const string FileName = "mcpprobe.json";

public static readonly string[] RootKeys = ["$schema", "lint"];
public static readonly string[] LintKeys = ["failOn", "strict", "nested", "minDescriptionLength", "minDescriptionWords", "rules", "ignore"];
public static readonly string[] LintKeys = ["failOn", "strict", "nested", "minDescriptionLength", "minDescriptionWords", "rules", "ignore", "baseline"];
public static readonly string[] IgnoreKeys = ["rule", "tool", "parameter", "reason"];

private static readonly JsonDocumentOptions s_documentOptions = new() { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true };
Expand All @@ -35,6 +35,9 @@ internal sealed class LintConfig

public IReadOnlyList<LintSuppression> Ignore { get; private init; } = [];

/// <summary>The full path of <c>lint.baseline</c>, resolved against the config file's folder, or null.</summary>
public string? Baseline { get; private init; }

/// <summary>
/// Finds the nearest <c>mcpprobe.json</c>, starting in <paramref name="startDirectory"/> and going up. The search stops
/// after the first directory that has a <c>.git</c> entry (file or folder), so it never leaves the repository.
Expand Down Expand Up @@ -102,10 +105,13 @@ private static LintConfig ParseNodes(JsonNode? root, string name, string path)
MinDescriptionWords = lint.TryGetPropertyValue("minDescriptionWords", out var words) ? AsCount(words, name, "lint.minDescriptionWords") : null,
Rules = lint.TryGetPropertyValue("rules", out var rules) ? ParseRules(rules, name) : new Dictionary<string, LintSeverity>(),
Ignore = lint.TryGetPropertyValue("ignore", out var ignore) ? ParseIgnore(ignore, name) : [],
Baseline = lint.TryGetPropertyValue("baseline", out var baseline)
? System.IO.Path.GetFullPath(AsString(baseline, name, "lint.baseline"), System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(path))!)
: null,
};
}

/// <summary>Applies the file over the library defaults. Command-line flags are applied after this, so they win.</summary>
/// <summary>Applies the file over the library defaults. Command-line flags are applied after this, so they win. <see cref="Baseline"/> is loaded by the caller.</summary>
public void ApplyTo(LintOptions options)
{
options.FailOn = FailOn ?? options.FailOn;
Expand Down
Loading
Loading