diff --git a/CHANGELOG.md b/CHANGELOG.md index c271f85..c98e0f2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,12 +7,14 @@ All notable changes to this project are documented here. The format is based on ### Added +- Lint checks prompts when the server declares the prompts capability: MCPP017 (no description, warning), MCPP018 (short description), MCPP019 (argument has no description), MCPP020 (prompt name guidance), MCPP021 and MCPP022 (naming style), MCPP023 (vague argument name, info) and MCPP024 (description only restates the name). `LintFinding.Kind` says whether a finding is about a tool or a prompt. Lint baselines and `ignore` entries accept an optional `kind`; omitted means any kind. `--from-file` still lints tools only. JSON findings include an optional `kind` (`prompt`, `resource` or `resourceTemplate`); it is omitted for tools. Lint SARIF fingerprints for those kinds are `ruleId|kind|tool|path`; tool findings stay `ruleId|tool|path`, the same as format 1 on main. To keep the previous tool-only result, set `--rule MCPP017=none` through `--rule MCPP024=none`. - Tool snapshots store each tool's `icons` (`src`, and optional `mimeType`, `sizes` and `theme`) when the server declares them. The field is omitted when there are no icons, and `formatVersion` stays 1, so existing snapshot files stay the same. A change to icons is `IconsChanged` and non-breaking. `data:` icon URIs are stored as declared. - `--format text|json|sarif` on `lint` and `diff` picks the stdout format. `json` is the McpProbe report format (format 1, see `docs/mcpprobe-report.schema.json`), `sarif` is SARIF 2.1.0. The default is still `text`. - `--sarif ` on `lint` and `diff` also writes a SARIF 2.1.0 file, like `--report`. In SARIF, each result points at the baseline or `--from-file` snapshot (default `mcp-tools.json`) and has a stable fingerprint for GitHub code scanning. - `LintReport.ToJson()` and `ToSarif()`, and `ToolSurfaceDiff.ToJson()` and `ToSarif()` in the library. - `--bearer-env ` and `--header-env 'Name: VAR'` on the CLI: HTTP authentication read from environment variables, so tokens are not on the command line. Later sources win for the same header name (`--header`, then `--header-env`, then `--bearer-env`). A missing or empty variable is exit 2 and names the variable, not the value. GitHub Action inputs `bearer-env` and `header-env`, and Azure Pipelines parameters `bearerEnv` and `headerEnv`, pass the variable names through. They need a CLI that has these flags. - `McpProbeHostOptions.IncludeServerExceptions` (default `true`): in the in-memory host, when a tool throws an exception that is not an `McpException`, the tool error result shows the exception type and message (for example `An error occurred invoking 'update_todo_item': FormatException: ...`) instead of the SDK's generic message, `An error occurred invoking 'update_todo_item'.` Prompts and resources that throw are reported the same way. Set it to `false` for the generic text a remote client would see. + - `ToolSurfaceChange.Before` and `After` hold the previous and current title or description when that is what changed. Other change kinds leave them unset. ### Changed diff --git a/README.md b/README.md index 0130294..e401e29 100644 --- a/README.md +++ b/README.md @@ -149,11 +149,21 @@ strict.ThrowIfFailed(); | MCPP014 | warning | A description that promises structured results ("returns JSON", "structured content", ...) comes with an `outputSchema`. | | MCPP015 | warning | The description says more than the tool name or title. | | MCPP016 | warning | No empty `enum`, and an `enum` declares its `type`. | +| MCPP017 | warning | The prompt has a description. | +| MCPP018 | warning | The prompt description is at least `MinToolDescriptionLength` (20) characters, or at least `MinToolDescriptionWords` (4) words. | +| MCPP019 | warning | Every prompt argument has a description. | +| MCPP020 | warning | The prompt name is 1-128 characters of `A-Z a-z 0-9 _ - .`. | +| MCPP021 | warning | All prompt names use the same style. | +| MCPP022 | warning | All prompt argument names use the same style. | +| MCPP023 | info | Prompt argument names aren't vague (`data`, `value`, `input`, ...). | +| MCPP024 | warning | The prompt description says more than the prompt name or title. | Change severities with `LintOptions.Severities["MCPP007"] = LintSeverity.None`, and the threshold with `LintOptions.FailOn`. By default MCPP003, MCPP006 and MCPP007 check top-level parameters. Set `LintOptions.CheckNestedParameters = true` (CLI: `mcpprobe lint --nested`) to also check nested object properties and array items (reported as `home.zip` or `stops[].city`), following local `$ref`s; a schema used in several places is checked once. Set `LintOptions.Strict = true` (CLI: `mcpprobe lint --strict`) to also run MCPP009-MCPP012, the schema-portability checks from MCP Inspector, on `inputSchema` and `outputSchema`. Those findings are reported with paths such as `inputSchema.properties.city` (the existing parameter rules still use `city`). MCPP010 does not report `[T, "null"]` (for example `["integer","null"]`): the C# and Go SDKs write that for every nullable parameter and an author can't change it, so this differs from Inspector's type-union check; use Inspector if you need its exact report. Unions of two or more non-null types, and longer unions with `null`, are still reported. Portability findings fail the report only when their effective severity is error, so a type-union warning does not trip the default `FailOn = Warning` gate; use `--rule MCPP010=error` if you want that warning to fail. A single portability rule can be turned on without `--strict` by setting its severity, or turned off with `--rule MCPP011=none`. MCPP008 is reserved for a community issue and is not implemented here. +`lint` and `LintToolsAsync` also check prompts when the server declares the prompts capability. They skip `prompts/list` when it does not, so a tool-only server is unchanged. A snapshot passed with `--from-file` has tools only. Prompt findings are labeled `prompt` in the text and HTML reports. Ignore entries and lint baselines can set `kind` to `prompt`; if `kind` is omitted, the entry matches any kind. To get the previous tool-only lint result, turn the prompt rules off with `--rule MCPP017=none` through `--rule MCPP024=none`. + 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 @@ -172,7 +182,8 @@ A server with legacy debt can keep its lint settings, and the findings it has de "rules": { "MCPP007": "none", "MCPP003": "error" }, "ignore": [ { "rule": "MCPP005", "tool": "sql_*", "reason": "Server convention: namespace_resource_verb-noun" }, - { "rule": "MCPP003", "tool": "legacy_export", "parameter": "opts" } + { "rule": "MCPP003", "tool": "legacy_export", "parameter": "opts" }, + { "rule": "MCPP017", "kind": "prompt", "reason": "Prompt descriptions come from the template" } ], "baseline": "mcpprobe-lint-baseline.json" } @@ -180,7 +191,7 @@ A server with legacy debt can keep its lint settings, and the findings it has de ``` - `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. +- 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`. `kind` limits the entry to `tool`, `prompt`, `resource` or `resourceTemplate`; omitted, it matches any kind. 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. @@ -237,7 +248,7 @@ mcpprobe diff --stdio "dotnet run --project src/MyServer" --baseline mcp-tools.j With `--format json` or `--format sarif`, stdout holds exactly one document. The `diff` hint ("If the change is intended, ...") and the lint `--write-baseline` line ("Wrote N finding(s) to ...") go to stderr instead. Exit codes don't change. The JSON `result` is `fail` when the command exits `1` and `pass` when it exits `0`, so `--fail-on-non-breaking` and `--write-baseline` are reflected there. -SARIF levels: lint errors are `error`, warnings are `warning`, info is `note`. Diff breaking changes are `error`, non-breaking changes are `note`. Lint rules keep their `MCPP0xx` ids; diff change kinds use kebab-case ids such as `tool-removed` or `description-changed`. Every result has a `partialFingerprints.primaryLocationLineHash` computed from the rule id, tool and path, so GitHub code scanning recognizes the same alert from run to run even when the snapshot is rewritten. When several results share the same rule, tool and path (for example allowed values removed and added on one parameter), they get `:1`, `:2` and so on in the order they appear, like GitHub's own fingerprints. +SARIF levels: lint errors are `error`, warnings are `warning`, info is `note`. Diff breaking changes are `error`, non-breaking changes are `note`. Lint rules keep their `MCPP0xx` ids; diff change kinds use kebab-case ids such as `tool-removed` or `description-changed`. Every result has a `partialFingerprints.primaryLocationLineHash` computed from the rule id, tool and path. Lint findings about a prompt, resource or resource template also include the finding `kind` (`ruleId|kind|tool|path`). Tool findings stay `ruleId|tool|path`, the same as format 1 on main, so existing code scanning alerts keep matching. When several results share the same identity (for example allowed values removed and added on one parameter), they get `:1`, `:2` and so on in the order they appear, like GitHub's own fingerprints. JSON lint findings include an optional `kind` (`prompt`, `resource` or `resourceTemplate`); it is omitted for tools. Each SARIF result points at a file in the repository, because GitHub doesn't display results without one. `diff` uses `--baseline` and `lint` uses `--from-file`, relative to the working directory with forward slashes. If that path is outside the working directory, only the file name is used. When lint reads a live server, the default is `mcp-tools.json`, so in CI run lint from the repo root or pass a real `--from-file` snapshot. Run `diff` from the repo root too, so the `--baseline` artifact path is relative to the repository root and GitHub can resolve it. diff --git a/docs/mcpprobe-report.schema.json b/docs/mcpprobe-report.schema.json index 2e02c01..0b07b85 100644 --- a/docs/mcpprobe-report.schema.json +++ b/docs/mcpprobe-report.schema.json @@ -62,6 +62,7 @@ "ruleId": { "type": "string", "pattern": "^MCPP[0-9]{3}$" }, "severity": { "enum": ["info", "warning", "error"] }, "tool": { "type": "string" }, + "kind": { "description": "The item kind. Omitted for tools; prompt, resource or resourceTemplate otherwise.", "enum": ["tool", "prompt", "resource", "resourceTemplate"] }, "path": { "description": "The parameter or schema path. Omitted for tool-level findings.", "type": "string" }, "message": { "type": "string" }, "failsTheRun": { "type": "boolean" } diff --git a/docs/mcpprobe.schema.json b/docs/mcpprobe.schema.json index a51fac8..fbfcc2f 100644 --- a/docs/mcpprobe.schema.json +++ b/docs/mcpprobe.schema.json @@ -79,6 +79,10 @@ "type": "string", "minLength": 1 }, + "kind": { + "description": "Item kind: tool, prompt, resource or resourceTemplate. Omitted matches any kind.", + "enum": ["tool", "prompt", "resource", "resourceTemplate"] + }, "reason": { "description": "Why the finding is accepted. Not evaluated.", "type": "string" @@ -119,7 +123,15 @@ "MCPP013", "MCPP014", "MCPP015", - "MCPP016" + "MCPP016", + "MCPP017", + "MCPP018", + "MCPP019", + "MCPP020", + "MCPP021", + "MCPP022", + "MCPP023", + "MCPP024" ] } } diff --git a/src/McpProbe.Cli/CliApp.cs b/src/McpProbe.Cli/CliApp.cs index adc0825..d5f0878 100644 --- a/src/McpProbe.Cli/CliApp.cs +++ b/src/McpProbe.Cli/CliApp.cs @@ -40,7 +40,7 @@ public static async Task RunAsync(string[] args, TextWriter stdout, TextWri 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.") + var root = new RootCommand("Check an MCP server's tool surface: snapshot it, diff it against a committed snapshot, and lint it, including prompts when the server has them.") { BuildSnapshotCommand(stdout, stderr), BuildDiffCommand(stdout, stderr, workingDirectory), @@ -257,7 +257,7 @@ private static Command BuildLintCommand(TextWriter stdout, TextWriter stderr, st var report = BuildReportOption(); var format = BuildFormatOption(); var sarif = BuildSarifOption(); - var command = new Command("lint", "Lint tool names, descriptions and parameters. Exits 1 on findings at or above --fail-on, or on a portability error when --strict is set."); + var command = new Command("lint", "Lint tool names, descriptions and parameters, and prompts when the server has them. Exits 1 on findings at or above --fail-on, or on a portability error when --strict is set."); server.AddTo(command); command.Options.Add(failOn); command.Options.Add(minLength); @@ -340,8 +340,8 @@ private static Command BuildLintCommand(TextWriter stdout, TextWriter stderr, st options.Severities[parts[0]] = ParseSeverity(parts[1]); } - var surface = await server.CaptureAsync(parse, stderr, ct).ConfigureAwait(false); - var lint = ToolLinter.Lint(surface, options); + var (surface, prompts) = await server.CaptureForLintAsync(parse, stderr, ct).ConfigureAwait(false); + var lint = prompts is null ? ToolLinter.Lint(surface, options) : ToolLinter.Lint(surface, prompts, options); var artifact = SarifArtifact.Resolve(server.FromFilePath(parse), workingDirectory); var sarifText = outputFormat == "sarif" || sarifPath is not null ? lint.ToSarif(artifact) : string.Empty; await WriteOutputAsync( diff --git a/src/McpProbe.Cli/LintConfig.cs b/src/McpProbe.Cli/LintConfig.cs index 76b48d3..6e5777a 100644 --- a/src/McpProbe.Cli/LintConfig.cs +++ b/src/McpProbe.Cli/LintConfig.cs @@ -15,7 +15,7 @@ internal sealed class LintConfig public static readonly string[] RootKeys = ["$schema", "lint"]; public static readonly string[] LintKeys = ["failOn", "strict", "nested", "minDescriptionLength", "minDescriptionWords", "rules", "ignore", "baseline"]; - public static readonly string[] IgnoreKeys = ["rule", "tool", "parameter", "reason"]; + public static readonly string[] IgnoreKeys = ["rule", "tool", "parameter", "kind", "reason"]; private static readonly JsonDocumentOptions s_documentOptions = new() { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true }; @@ -164,17 +164,28 @@ private static List ParseIgnore(JsonNode? node, string name) 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; + var kind = entry.TryGetPropertyValue("kind", out var k) ? ParseKind(AsString(k, name, $"{where}.kind"), name, where) : (LintTargetKind?)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)); + entries.Add(new LintSuppression(rule, tool, parameter, reason) { Kind = kind }); } return entries; } + private static LintTargetKind ParseKind(string value, string name, string where) => value switch + { + "tool" => LintTargetKind.Tool, + "prompt" => LintTargetKind.Prompt, + "resource" => LintTargetKind.Resource, + "resourceTemplate" => LintTargetKind.ResourceTemplate, + "resource template" => LintTargetKind.ResourceTemplate, + _ => throw new FormatException($"{name}: {where}.kind: unknown kind '{Printable.Text(value, 50)}'. Use tool, prompt, resource or resourceTemplate."), + }; + 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))}."); diff --git a/src/McpProbe.Cli/ServerOptions.cs b/src/McpProbe.Cli/ServerOptions.cs index 49eb1b1..153abb2 100644 --- a/src/McpProbe.Cli/ServerOptions.cs +++ b/src/McpProbe.Cli/ServerOptions.cs @@ -1,6 +1,8 @@ using System.CommandLine; +using McpProbe.Internal; using McpProbe.Snapshots; using ModelContextProtocol.Client; +using ModelContextProtocol.Protocol; namespace McpProbe.Cli; @@ -128,7 +130,13 @@ public void AddTo(Command command) /// The --from-file snapshot path as typed, or null when the surface comes from a server. internal string? FromFilePath(ParseResult parse) => _file is null ? null : parse.GetValue(_file); - public async Task CaptureAsync(ParseResult parse, TextWriter stderr, CancellationToken cancellationToken) + public async Task CaptureAsync(ParseResult parse, TextWriter stderr, CancellationToken cancellationToken) => + (await CaptureCoreAsync(parse, stderr, includeListedContracts: false, cancellationToken).ConfigureAwait(false)).Surface; + + public async Task<(ToolSurface Surface, IReadOnlyList? Prompts)> CaptureForLintAsync(ParseResult parse, TextWriter stderr, CancellationToken cancellationToken) => + await CaptureCoreAsync(parse, stderr, includeListedContracts: true, cancellationToken).ConfigureAwait(false); + + private async Task<(ToolSurface Surface, IReadOnlyList? Prompts)> CaptureCoreAsync(ParseResult parse, TextWriter stderr, bool includeListedContracts, CancellationToken cancellationToken) { if (_file is not null && parse.GetValue(_file) is { } file) { @@ -138,7 +146,7 @@ public async Task CaptureAsync(ParseResult parse, TextWriter stderr throw new FileNotFoundException($"Snapshot file not found: {path}", path); } - return ToolSurface.Parse(await File.ReadAllTextAsync(path, cancellationToken).ConfigureAwait(false)); + return (ToolSurface.Parse(await File.ReadAllTextAsync(path, cancellationToken).ConfigureAwait(false)), null); } var timeoutSeconds = parse.GetValue(_timeout); @@ -166,7 +174,14 @@ public async Task CaptureAsync(ParseResult parse, TextWriter stderr var client = await ServerConnector.ConnectAsync(target, serverStderr, challenge, timeout.Token).ConfigureAwait(false); await using (client.ConfigureAwait(false)) { - return await ToolSurface.CaptureAsync(client, timeout.Token).ConfigureAwait(false); + var surface = await ToolSurface.CaptureAsync(client, timeout.Token).ConfigureAwait(false); + if (!includeListedContracts) + { + return (surface, null); + } + + var prompts = await ListedContracts.ListPromptsAsync(client, timeout.Token).ConfigureAwait(false); + return (surface, prompts); } } catch (Exception ex) diff --git a/src/McpProbe/Internal/ListedContracts.cs b/src/McpProbe/Internal/ListedContracts.cs new file mode 100644 index 0000000..336d9a0 --- /dev/null +++ b/src/McpProbe/Internal/ListedContracts.cs @@ -0,0 +1,19 @@ +using ModelContextProtocol.Client; +using ModelContextProtocol.Protocol; + +namespace McpProbe.Internal; + +/// Lists prompts when the server declares the prompts capability. +internal static class ListedContracts +{ + public static async Task?> ListPromptsAsync(McpClient client, CancellationToken cancellationToken) + { + if (client.ServerCapabilities.Prompts is null) + { + return null; + } + + var prompts = await client.ListPromptsAsync(cancellationToken: cancellationToken).ConfigureAwait(false); + return prompts.Select(p => p.ProtocolPrompt).ToList(); + } +} diff --git a/src/McpProbe/Internal/MachineReadableOutput.cs b/src/McpProbe/Internal/MachineReadableOutput.cs index fed09e1..0c126fb 100644 --- a/src/McpProbe/Internal/MachineReadableOutput.cs +++ b/src/McpProbe/Internal/MachineReadableOutput.cs @@ -75,6 +75,11 @@ public static string LintJson(LintReport report, bool failed) ["severity"] = LintFinding.SeverityLabel(finding.Severity), ["tool"] = finding.ToolName, }; + if (finding.Kind != LintTargetKind.Tool) + { + node["kind"] = LintFinding.JsonKind(finding.Kind); + } + AddIfPresent(node, "path", finding.ParameterName); node["message"] = finding.Message; node["failsTheRun"] = report.FindingFails(finding); @@ -124,10 +129,12 @@ public static string LintSarif(LintReport report, string? artifactUri) } var results = new JsonArray(); - var occurrences = new Dictionary<(string, string, string), int>(); + var occurrences = new Dictionary<(string, string, string, string), int>(); foreach (var finding in report.Findings) { - results.Add(Result(finding.RuleId, LintLevel(finding.Severity), finding.Message, finding.ToolName, finding.ParameterName, artifactUri, occurrences)); + // Tool findings omit kind so the fingerprint stays ruleId|tool|path, the same as format 1 on main. + var kind = finding.Kind == LintTargetKind.Tool ? null : LintFinding.JsonKind(finding.Kind); + results.Add(Result(finding.RuleId, LintLevel(finding.Severity), finding.Message, finding.ToolName, finding.ParameterName, artifactUri, occurrences, kind)); } return Serialize(SarifLog(rules, results)); @@ -143,7 +150,7 @@ public static string DiffSarif(ToolSurfaceDiff diff, string? artifactUri) } var results = new JsonArray(); - var occurrences = new Dictionary<(string, string, string), int>(); + var occurrences = new Dictionary<(string, string, string, string), int>(); foreach (var change in diff.Changes) { var result = Result( @@ -240,7 +247,7 @@ public static string ChangeKindId(ToolSurfaceChangeKind kind) ["properties"] = new JsonObject { ["tags"] = new JsonArray("mcp", "tools") }, }; - private static JsonObject Result(string ruleId, string level, string message, string tool, string? path, string? artifactUri, Dictionary<(string, string, string), int> occurrences) => new() + private static JsonObject Result(string ruleId, string level, string message, string tool, string? path, string? artifactUri, Dictionary<(string, string, string, string), int> occurrences, string? targetKind = null) => new() { ["ruleId"] = ruleId, ["level"] = level, @@ -261,23 +268,28 @@ public static string ChangeKindId(ToolSurfaceChangeKind kind) }, ["partialFingerprints"] = new JsonObject { - ["primaryLocationLineHash"] = Fingerprint(ruleId, tool, path, occurrences), + ["primaryLocationLineHash"] = Fingerprint(ruleId, tool, path, occurrences, targetKind), }, }; /// - /// A stable fingerprint of the finding's identity (rule, tool, path), not of the file contents or the message, - /// so GitHub code scanning matches the same alert across runs even when the snapshot is rewritten. + /// A stable fingerprint of the finding's identity (rule, optional target kind, tool, path), not of the file contents + /// or the message, so GitHub code scanning matches the same alert across runs even when the snapshot is rewritten. + /// Lint fingerprints for a prompt, resource or resource template are ruleId|kind|tool|path. Tool lint + /// fingerprints and diff fingerprints stay ruleId|tool|path, so tool alerts match format 1 on main. Diff + /// omits kind because the change kind is already the rule id. /// - private static string Fingerprint(string ruleId, string tool, string? path, Dictionary<(string, string, string), int> occurrences) + private static string Fingerprint(string ruleId, string tool, string? path, Dictionary<(string, string, string, string), int> occurrences, string? targetKind) { // One diff can report several changes with the same kind, tool and path (allowed values removed and added, // or two constraints on one parameter). GitHub tells identical fingerprints apart with the ":N" suffix, in // order of appearance, so number repeats the same way instead of emitting the same fingerprint twice. - var key = (ruleId, tool, path ?? string.Empty); + var key = (ruleId, targetKind ?? string.Empty, tool, path ?? string.Empty); occurrences.TryGetValue(key, out var seen); occurrences[key] = seen + 1; - var identity = ruleId + "|" + tool + "|" + (path ?? string.Empty); + var identity = targetKind is null + ? ruleId + "|" + tool + "|" + (path ?? string.Empty) + : ruleId + "|" + targetKind + "|" + tool + "|" + (path ?? string.Empty); var hash = SHA256.HashData(Encoding.UTF8.GetBytes(identity)); return Convert.ToHexString(hash, 0, 8).ToLowerInvariant() + ":" + (seen + 1).ToString(CultureInfo.InvariantCulture); } diff --git a/src/McpProbe/Linting/LintBaseline.cs b/src/McpProbe/Linting/LintBaseline.cs index e601b96..ab507ee 100644 --- a/src/McpProbe/Linting/LintBaseline.cs +++ b/src/McpProbe/Linting/LintBaseline.cs @@ -11,7 +11,22 @@ namespace McpProbe.Linting; /// The parameter or schema path, or null for tool-level findings. Compared ordinally. public sealed record LintBaselineEntry(string RuleId, string ToolName, string? ParameterName = null) { - internal static LintBaselineEntry Of(LintFinding finding) => new(finding.RuleId.ToUpperInvariant(), finding.ToolName, finding.ParameterName); + /// + /// Gets the item kind this entry applies to. Null matches any kind, which is how older baseline files behave. + /// + public LintTargetKind? Kind { get; init; } + + internal static LintBaselineEntry Of(LintFinding finding) => + new(finding.RuleId.ToUpperInvariant(), finding.ToolName, finding.ParameterName) + { + Kind = finding.Kind == LintTargetKind.Tool ? null : finding.Kind, + }; + + internal bool Matches(LintFinding finding) => + string.Equals(RuleId, finding.RuleId, StringComparison.OrdinalIgnoreCase) && + string.Equals(ToolName, finding.ToolName, StringComparison.Ordinal) && + string.Equals(ParameterName, finding.ParameterName, StringComparison.Ordinal) && + (Kind is null || Kind == finding.Kind); internal string Describe() => ParameterName is null ? $"{RuleId} {Printable.Text(ToolName, 100)}" @@ -105,10 +120,7 @@ public static LintBaseline Parse(string json) throw new FormatException("The lint baseline has no 'findings' array."); } - return new(findings.Select(node => node is JsonObject entry && Text(entry["rule"]) is { Length: > 0 } rule && Text(entry["tool"]) is { } tool && - (entry["parameter"] is null || Text(entry["parameter"]) is not null) - ? new LintBaselineEntry(rule, tool, Text(entry["parameter"])) - : throw new FormatException("Every lint baseline finding needs a 'rule' and a 'tool' string, and 'parameter' must be a string when present."))); + return new(findings.Select(ReadEntry)); } /// Serializes the baseline (indented, LF line endings, sorted), so the file is stable and easy to review. @@ -124,6 +136,11 @@ public string ToJson() node["parameter"] = entry.ParameterName; } + if (entry.Kind is { } kind && kind != LintTargetKind.Tool) + { + node["kind"] = LintFinding.KindLabel(kind); + } + findings.Add(node); } @@ -136,28 +153,57 @@ public string ToJson() /// An entry is not stale when it could not have matched: its rule did not run, or it is a nested path without nested checks. /// internal static (List Active, List Baselined, List Stale) Apply( - List all, List active, LintBaseline? baseline, LintOptions options) + List all, List active, LintBaseline? baseline, LintOptions options, LintListedKinds listed = LintListedKinds.All) { if (baseline is null) { return (active, [], []); } - var accepted = baseline.Entries.ToHashSet(); var kept = new List(); var baselined = new List(); foreach (var finding in active) { - (accepted.Contains(LintBaselineEntry.Of(finding)) ? baselined : kept).Add(finding); + (baseline.Entries.Any(e => e.Matches(finding)) ? baselined : kept).Add(finding); } // Compare with every finding, ignored ones too, so an entry that an ignore rule also covers is not called stale. - var found = all.Select(LintBaselineEntry.Of).ToHashSet(); var stale = baseline.Entries - .Where(e => !found.Contains(e) && new LintSuppression(e.RuleId, ParameterPattern: e.ParameterName).CouldMatch(options)) + .Where(e => !all.Any(e.Matches) && new LintSuppression(e.RuleId, ParameterPattern: e.ParameterName).CouldMatch(options) && + (e.Kind is not { } kind || kind == LintTargetKind.Tool || listed.Includes(kind))) .ToList(); return (kept, baselined, stale); } + private static LintBaselineEntry ReadEntry(JsonNode? node) + { + if (node is not JsonObject entry || Text(entry["rule"]) is not { Length: > 0 } rule || Text(entry["tool"]) is not { } tool || + (entry["parameter"] is not null && Text(entry["parameter"]) is null)) + { + throw new FormatException("Every lint baseline finding needs a 'rule' and a 'tool' string, and 'parameter' must be a string when present."); + } + + return new LintBaselineEntry(rule, tool, Text(entry["parameter"])) { Kind = ReadKind(entry) }; + } + + private static LintTargetKind? ReadKind(JsonObject entry) + { + if (!entry.ContainsKey("kind") || entry["kind"] is null) + { + return null; + } + + var text = Text(entry["kind"]); + return text switch + { + "tool" => LintTargetKind.Tool, + "prompt" => LintTargetKind.Prompt, + "resource" => LintTargetKind.Resource, + "resource template" => LintTargetKind.ResourceTemplate, + "resourceTemplate" => LintTargetKind.ResourceTemplate, + _ => throw new FormatException($"Unknown lint baseline kind '{Printable.Text(text ?? string.Empty, 50)}'. Use tool, prompt, resource or resourceTemplate."), + }; + } + private static string? Text(JsonNode? node) => node is JsonValue value && value.TryGetValue(out var text) ? text : null; } diff --git a/src/McpProbe/Linting/LintFinding.cs b/src/McpProbe/Linting/LintFinding.cs index 25ce47d..3c0291b 100644 --- a/src/McpProbe/Linting/LintFinding.cs +++ b/src/McpProbe/Linting/LintFinding.cs @@ -10,13 +10,30 @@ namespace McpProbe.Linting; /// What is wrong and how to fix it. public sealed record LintFinding(string RuleId, LintSeverity Severity, string ToolName, string? ParameterName, string Message) { + /// + /// Gets which kind of item this finding is about. Defaults to . + /// + public LintTargetKind Kind { get; init; } + /// public override string ToString() { - var target = ParameterName is null ? Printable.Text(ToolName, 100) : $"{Printable.Text(ToolName, 100)}.{Printable.Text(ParameterName, 100)}"; + var name = string.IsNullOrEmpty(ParameterName) ? Printable.Text(ToolName, 100) : $"{Printable.Text(ToolName, 100)}.{Printable.Text(ParameterName, 100)}"; + var target = Kind == LintTargetKind.Tool ? name : $"{KindLabel(Kind)} {name}"; return $"{SeverityLabel(Severity)} {RuleId} {target}: {Printable.Text(Message, 500)}"; } + internal static string KindLabel(LintTargetKind kind) => kind switch + { + LintTargetKind.Prompt => "prompt", + LintTargetKind.Resource => "resource", + LintTargetKind.ResourceTemplate => "resource template", + _ => "tool", + }; + + /// The JSON / baseline spelling of a kind: tool, prompt, resource or resourceTemplate. + internal static string JsonKind(LintTargetKind kind) => kind == LintTargetKind.ResourceTemplate ? "resourceTemplate" : KindLabel(kind); + internal static string SeverityLabel(LintSeverity severity) => severity switch { LintSeverity.Error => "error", diff --git a/src/McpProbe/Linting/LintListedKinds.cs b/src/McpProbe/Linting/LintListedKinds.cs new file mode 100644 index 0000000..354c640 --- /dev/null +++ b/src/McpProbe/Linting/LintListedKinds.cs @@ -0,0 +1,24 @@ +namespace McpProbe.Linting; + +// Which contracts a lint run listed. Tools always count as listed (a snapshot has them). +[Flags] +internal enum LintListedKinds +{ + None = 0, + Prompts = 1, + ResourceTemplates = 2, + Resources = 4, + + All = Prompts | ResourceTemplates | Resources, +} + +internal static class LintListedKindsExtensions +{ + public static bool Includes(this LintListedKinds listed, LintTargetKind kind) => kind switch + { + LintTargetKind.Prompt => listed.HasFlag(LintListedKinds.Prompts), + LintTargetKind.ResourceTemplate => listed.HasFlag(LintListedKinds.ResourceTemplates), + LintTargetKind.Resource => listed.HasFlag(LintListedKinds.Resources), + _ => true, + }; +} diff --git a/src/McpProbe/Linting/LintReport.cs b/src/McpProbe/Linting/LintReport.cs index cfef228..1d43106 100644 --- a/src/McpProbe/Linting/LintReport.cs +++ b/src/McpProbe/Linting/LintReport.cs @@ -136,8 +136,8 @@ public string ToHtml() { LintFinding.SeverityLabel(f.Severity), f.RuleId, - Printable.Text(f.ToolName, 100), - f.ParameterName is null ? string.Empty : Printable.Text(f.ParameterName, 100), + f.Kind == LintTargetKind.Tool ? Printable.Text(f.ToolName, 100) : $"{LintFinding.KindLabel(f.Kind)} {Printable.Text(f.ToolName, 100)}", + string.IsNullOrEmpty(f.ParameterName) ? string.Empty : Printable.Text(f.ParameterName, 100), Printable.Text(f.Message, 500), FindingFails(f) ? "yes" : "no", })); diff --git a/src/McpProbe/Linting/LintRule.cs b/src/McpProbe/Linting/LintRule.cs index 5bcbf24..27b467e 100644 --- a/src/McpProbe/Linting/LintRule.cs +++ b/src/McpProbe/Linting/LintRule.cs @@ -56,6 +56,30 @@ public static class LintRules /// MCPP016: a schema has an empty enum, or an enum without a type. public static readonly LintRule EnumWithoutValuesOrType = new("MCPP016", "Enum is empty or has no type", LintSeverity.Warning); + /// MCPP017: a prompt has no description. + public static readonly LintRule PromptMissingDescription = new("MCPP017", "Prompt has no description", LintSeverity.Warning); + + /// MCPP018: a prompt description is shorter than . + public static readonly LintRule PromptDescriptionTooShort = new("MCPP018", "Prompt description is too short", LintSeverity.Warning); + + /// MCPP019: a prompt argument has no description. + public static readonly LintRule PromptArgumentMissingDescription = new("MCPP019", "Prompt argument has no description", LintSeverity.Warning); + + /// MCPP020: a prompt name doesn't follow the MCP tool-name guidance (1-128 characters: letters, digits, '_', '-', '.'). + public static readonly LintRule InvalidPromptName = new("MCPP020", "Prompt name doesn't follow MCP naming guidance", LintSeverity.Warning); + + /// MCPP021: prompt names mix naming styles. + public static readonly LintRule InconsistentPromptNaming = new("MCPP021", "Prompt names mix naming styles", LintSeverity.Warning); + + /// MCPP022: prompt argument names mix naming styles. + public static readonly LintRule InconsistentPromptArgumentNaming = new("MCPP022", "Prompt argument names mix naming styles", LintSeverity.Warning); + + /// MCPP023: a prompt argument has a vague name such as data or value. + public static readonly LintRule VaguePromptArgumentName = new("MCPP023", "Prompt argument name is vague", LintSeverity.Info); + + /// MCPP024: the prompt description only restates the prompt name or title. + public static readonly LintRule PromptDescriptionRestatesName = new("MCPP024", "Prompt description only restates the name", LintSeverity.Warning); + /// Gets all built-in rules, ordered by id. public static IReadOnlyList All { get; } = [ @@ -74,6 +98,14 @@ public static class LintRules StructuredOutputWithoutSchema, DescriptionRestatesName, EnumWithoutValuesOrType, + PromptMissingDescription, + PromptDescriptionTooShort, + PromptArgumentMissingDescription, + InvalidPromptName, + InconsistentPromptNaming, + InconsistentPromptArgumentNaming, + VaguePromptArgumentName, + PromptDescriptionRestatesName, ]; internal static bool IsPortabilityRule(string ruleId) => diff --git a/src/McpProbe/Linting/LintSuppression.cs b/src/McpProbe/Linting/LintSuppression.cs index 649b840..cb2156f 100644 --- a/src/McpProbe/Linting/LintSuppression.cs +++ b/src/McpProbe/Linting/LintSuppression.cs @@ -12,10 +12,14 @@ namespace McpProbe.Linting; /// 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) { + /// Gets the item kind this entry applies to. Null matches any kind. + public LintTargetKind? Kind { get; init; } + 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))); + (ParameterPattern is null || (finding.ParameterName is not null && GlobMatches(ParameterPattern, finding.ParameterName))) && + (Kind is null || Kind == finding.Kind); /// 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) @@ -51,12 +55,21 @@ internal string Describe() parts.Add($"parameter {Printable.Text(ParameterPattern, 100)}"); } + if (Kind is { } kind) + { + parts.Add($"kind {LintFinding.KindLabel(kind)}"); + } + return string.Join(", ", parts); } + /// Whether the entry is about a prompt, resource or resource template that this run did not list, so it can't be called unused. + internal bool TargetsUnlistedKind(LintListedKinds listed) => + Kind is { } kind && kind != LintTargetKind.Tool && !listed.Includes(kind); + /// 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) + List findings, IList suppressions, LintOptions options, LintListedKinds listed = LintListedKinds.All) { if (suppressions.Count == 0) { @@ -80,7 +93,7 @@ internal static (List Active, List Hidden, List