From a204c0e6e66e60b8fe663b69e99ef634131bb371 Mon Sep 17 00:00:00 2001 From: Lior Shmueli <48066416+ShmueLior@users.noreply.github.com> Date: Fri, 4 Dec 2026 09:09:21 +0200 Subject: [PATCH 1/6] Lint prompts (MCPP017-MCPP024) and tag lint findings with a kind --- CHANGELOG.md | 2 + README.md | 15 +- docs/mcpprobe.schema.json | 14 +- src/McpProbe.Cli/CliApp.cs | 6 +- src/McpProbe.Cli/LintConfig.cs | 15 +- src/McpProbe.Cli/ServerOptions.cs | 21 +- src/McpProbe/Internal/ListedContracts.cs | 19 ++ src/McpProbe/Linting/LintBaseline.cs | 63 ++++- src/McpProbe/Linting/LintFinding.cs | 16 +- src/McpProbe/Linting/LintReport.cs | 2 +- src/McpProbe/Linting/LintRule.cs | 32 +++ src/McpProbe/Linting/LintSuppression.cs | 6 +- src/McpProbe/Linting/LintTargetKind.cs | 17 ++ src/McpProbe/Linting/PromptLinter.cs | 101 +++++++ src/McpProbe/Linting/ToolLinter.cs | 24 +- src/McpProbe/McpProbeHost.cs | 5 +- src/McpProbe/PublicAPI.Unshipped.txt | 20 ++ tests/McpProbe.Tests/CliTests.cs | 2 +- tests/McpProbe.Tests/LintConfigSchemaTests.cs | 3 +- tests/McpProbe.Tests/LintConfigTests.cs | 4 +- tests/McpProbe.Tests/PromptLinterTests.cs | 251 ++++++++++++++++++ tests/McpProbe.Tests/ToolLinterTests.cs | 2 +- 22 files changed, 604 insertions(+), 36 deletions(-) create mode 100644 src/McpProbe/Internal/ListedContracts.cs create mode 100644 src/McpProbe/Linting/LintTargetKind.cs create mode 100644 src/McpProbe/Linting/PromptLinter.cs create mode 100644 tests/McpProbe.Tests/PromptLinterTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 2551d15..a8ec6ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,11 +7,13 @@ 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. To keep the previous tool-only result, set `--rule MCPP017=none` through `--rule MCPP024=none`. - `--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 f367ec6..558c604 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. 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..dfa7721 100644 --- a/src/McpProbe.Cli/CliApp.cs +++ b/src/McpProbe.Cli/CliApp.cs @@ -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 = 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/Linting/LintBaseline.cs b/src/McpProbe/Linting/LintBaseline.cs index e601b96..9520b79 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); } @@ -143,21 +160,49 @@ internal static (List Active, List Baselined, 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)) .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")) + { + 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..4a627d8 100644 --- a/src/McpProbe/Linting/LintFinding.cs +++ b/src/McpProbe/Linting/LintFinding.cs @@ -10,13 +10,27 @@ 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 = ParameterName is null ? 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", + }; + internal static string SeverityLabel(LintSeverity severity) => severity switch { LintSeverity.Error => "error", diff --git a/src/McpProbe/Linting/LintReport.cs b/src/McpProbe/Linting/LintReport.cs index cfef228..16e8bdc 100644 --- a/src/McpProbe/Linting/LintReport.cs +++ b/src/McpProbe/Linting/LintReport.cs @@ -136,7 +136,7 @@ public string ToHtml() { LintFinding.SeverityLabel(f.Severity), f.RuleId, - Printable.Text(f.ToolName, 100), + f.Kind == LintTargetKind.Tool ? Printable.Text(f.ToolName, 100) : $"{LintFinding.KindLabel(f.Kind)} {Printable.Text(f.ToolName, 100)}", f.ParameterName is null ? 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..847e601 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) diff --git a/src/McpProbe/Linting/LintTargetKind.cs b/src/McpProbe/Linting/LintTargetKind.cs new file mode 100644 index 0000000..f459e8e --- /dev/null +++ b/src/McpProbe/Linting/LintTargetKind.cs @@ -0,0 +1,17 @@ +namespace McpProbe.Linting; + +/// Which kind of MCP item a lint finding is about. +public enum LintTargetKind +{ + /// A tool. + Tool = 0, + + /// A prompt. + Prompt = 1, + + /// A resource from resources/list. + Resource = 2, + + /// A resource template from resources/templates/list. + ResourceTemplate = 3, +} diff --git a/src/McpProbe/Linting/PromptLinter.cs b/src/McpProbe/Linting/PromptLinter.cs new file mode 100644 index 0000000..39ee698 --- /dev/null +++ b/src/McpProbe/Linting/PromptLinter.cs @@ -0,0 +1,101 @@ +using ModelContextProtocol.Protocol; + +namespace McpProbe.Linting; + +public static partial class ToolLinter +{ + private static void LintPrompts(IEnumerable? prompts, LintOptions options, List findings) + { + if (prompts is null) + { + return; + } + + var promptNames = new List<(string Tool, string? Parameter, string Name)>(); + var argumentNames = new List<(string Tool, string? Parameter, string Name)>(); + + foreach (var prompt in prompts) + { + var name = prompt.Name ?? string.Empty; + promptNames.Add((name, null, name)); + CheckPromptName(name, options, findings); + CheckPromptDescription(prompt, options, findings); + + if (prompt.Arguments is null) + { + continue; + } + + foreach (var argument in prompt.Arguments) + { + if (argument is null) + { + continue; + } + + var argumentName = argument.Name ?? string.Empty; + argumentNames.Add((name, argumentName, argumentName)); + if (string.IsNullOrWhiteSpace(argument.Description)) + { + Add(findings, options, LintRules.PromptArgumentMissingDescription, name, argumentName, + $"Argument '{argumentName}' has no description. Say what it is and what format it expects.", + LintTargetKind.Prompt); + } + + if (options.VagueParameterNames.Contains(argumentName) && !IsPayloadOfCreateTool(name, prefix: null, argumentName, options)) + { + Add(findings, options, LintRules.VaguePromptArgumentName, name, argumentName, + $"Argument name '{argumentName}' is vague. Use a name that says what the value is (for example 'city' instead of 'value').", + LintTargetKind.Prompt); + } + } + } + + CheckConsistency(promptNames, LintRules.InconsistentPromptNaming, "Prompt", options, findings, LintTargetKind.Prompt); + CheckConsistency(argumentNames, LintRules.InconsistentPromptArgumentNaming, "Argument", options, findings, LintTargetKind.Prompt); + } + + private static void CheckPromptName(string name, LintOptions options, List findings) + { + if (name.Length is < 1 or > 128 || !name.All(IsAllowedToolNameChar)) + { + Add(findings, options, LintRules.InvalidPromptName, name, null, + "Prompt names should be 1-128 characters and use only ASCII letters, digits, '_', '-' and '.'.", + LintTargetKind.Prompt); + } + } + + private static void CheckPromptDescription(Prompt prompt, LintOptions options, List findings) + { + var name = prompt.Name ?? string.Empty; + var description = prompt.Description?.Trim(); + if (string.IsNullOrEmpty(description)) + { + Add(findings, options, LintRules.PromptMissingDescription, name, null, + "Prompt has no description. Say what the prompt does and when to use it.", + LintTargetKind.Prompt); + } + else if (RestatesPromptName(prompt, description) && options.SeverityOf(LintRules.PromptDescriptionRestatesName) != LintSeverity.None) + { + Add(findings, options, LintRules.PromptDescriptionRestatesName, name, null, + "Description only restates the prompt name. Say what the prompt does and when to use it.", + LintTargetKind.Prompt); + } + else if (description.Length < options.MinToolDescriptionLength && + (options.MinToolDescriptionWords == 0 || description.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries).Length < options.MinToolDescriptionWords)) + { + Add(findings, options, LintRules.PromptDescriptionTooShort, name, null, + string.Create(System.Globalization.CultureInfo.InvariantCulture, + $"Description is {description.Length} characters (minimum {options.MinToolDescriptionLength}). Say what the prompt does and when to use it."), + LintTargetKind.Prompt); + } + } + + private static bool RestatesPromptName(Prompt prompt, string description) + { + var normalized = NormalizeName(description); + var name = prompt.Name ?? string.Empty; + return normalized.Length > 0 && + (normalized == NormalizeName(name) || (prompt.Title is { } title && normalized == NormalizeName(title))); + } +} diff --git a/src/McpProbe/Linting/ToolLinter.cs b/src/McpProbe/Linting/ToolLinter.cs index a8ee6d5..bf3bac6 100644 --- a/src/McpProbe/Linting/ToolLinter.cs +++ b/src/McpProbe/Linting/ToolLinter.cs @@ -16,7 +16,7 @@ namespace McpProbe.Linting; /// With , MCPP009-MCPP012 also walk inputSchema and outputSchema for /// portability issues (paths such as inputSchema.properties.city). MCPP016 uses the same walk and paths, but runs by default. /// -public static class ToolLinter +public static partial class ToolLinter { private static readonly HashSet PayloadParameterNames = new(StringComparer.OrdinalIgnoreCase) { @@ -47,7 +47,15 @@ public static LintReport Lint(IEnumerable tools, LintOptions? opt /// The surface. /// Rule options. Defaults to defaults. /// The findings. - public static LintReport Lint(ToolSurface surface, LintOptions? options = null) + public static LintReport Lint(ToolSurface surface, LintOptions? options = null) => + Lint(surface, prompts: null, options); + + /// Lints a captured tool surface and, when provided, the prompts from prompts/list. + /// The tool surface. + /// Prompts to lint. Null means the server's prompts were not listed. + /// Rule options. Defaults to defaults. + /// The findings. + public static LintReport Lint(ToolSurface surface, IEnumerable? prompts, LintOptions? options = null) { ArgumentNullException.ThrowIfNull(surface); options ??= new LintOptions(); @@ -97,6 +105,8 @@ public static LintReport Lint(ToolSurface surface, LintOptions? options = null) options, findings); + LintPrompts(prompts, options, findings); + var (active, suppressed, unused) = LintSuppression.Apply(findings, options.Suppressions, options); var (remaining, baselined, stale) = LintBaseline.Apply(findings, active, options.Baseline, options); return new LintReport(Order(remaining), options.FailOn, Order(suppressed), unused, Order(baselined), stale); @@ -325,7 +335,8 @@ private static void CheckConsistency( LintRule rule, string noun, LintOptions options, - List findings) + List findings, + LintTargetKind kind = LintTargetKind.Tool) { if (options.SeverityOf(rule) == LintSeverity.None) { @@ -360,16 +371,17 @@ private static void CheckConsistency( foreach (var item in classified.Where(i => i.Style != majority)) { Add(findings, options, rule, item.Tool, item.Parameter, - $"{noun} name '{item.Name}' is {NamingStyles.Describe(item.Name, item.Style)}, but most {noun.ToLowerInvariant()} names on this server are {NamingStyles.Label(majority)}."); + $"{noun} name '{item.Name}' is {NamingStyles.Describe(item.Name, item.Style)}, but most {noun.ToLowerInvariant()} names on this server are {NamingStyles.Label(majority)}.", + kind); } } - private static void Add(List findings, LintOptions options, LintRule rule, string tool, string? parameter, string message) + internal static void Add(List findings, LintOptions options, LintRule rule, string tool, string? parameter, string message, LintTargetKind kind = LintTargetKind.Tool) { var severity = options.SeverityOf(rule); if (severity != LintSeverity.None) { - findings.Add(new LintFinding(rule.Id, severity, tool, parameter, message)); + findings.Add(new LintFinding(rule.Id, severity, tool, parameter, message) { Kind = kind }); } } diff --git a/src/McpProbe/McpProbeHost.cs b/src/McpProbe/McpProbeHost.cs index a1bc7c0..9fe4d78 100644 --- a/src/McpProbe/McpProbeHost.cs +++ b/src/McpProbe/McpProbeHost.cs @@ -186,7 +186,7 @@ public Task VerifyToolSnapshotAsync( } /// - /// Lists the server's tools and lints them. + /// Lists the server's tools and lints them, and lints its prompts when the server declares the prompts capability. /// /// Lint options. /// Cancels the request. @@ -194,7 +194,8 @@ public Task VerifyToolSnapshotAsync( public async Task LintToolsAsync(LintOptions? options = null, CancellationToken cancellationToken = default) { var surface = await ToolSurface.CaptureAsync(Client, cancellationToken).ConfigureAwait(false); - return ToolLinter.Lint(surface, options); + var prompts = await ListedContracts.ListPromptsAsync(Client, cancellationToken).ConfigureAwait(false); + return ToolLinter.Lint(surface, prompts, options); } /// diff --git a/src/McpProbe/PublicAPI.Unshipped.txt b/src/McpProbe/PublicAPI.Unshipped.txt index 0b1b063..8ea23b4 100644 --- a/src/McpProbe/PublicAPI.Unshipped.txt +++ b/src/McpProbe/PublicAPI.Unshipped.txt @@ -56,6 +56,8 @@ McpProbe.Linting.LintBaselineEntry McpProbe.Linting.LintBaselineEntry.$() -> McpProbe.Linting.LintBaselineEntry! McpProbe.Linting.LintBaselineEntry.Deconstruct(out string! RuleId, out string! ToolName, out string? ParameterName) -> void McpProbe.Linting.LintBaselineEntry.Equals(McpProbe.Linting.LintBaselineEntry? other) -> bool +McpProbe.Linting.LintBaselineEntry.Kind.get -> McpProbe.Linting.LintTargetKind? +McpProbe.Linting.LintBaselineEntry.Kind.init -> void McpProbe.Linting.LintBaselineEntry.LintBaselineEntry(string! RuleId, string! ToolName, string? ParameterName = null) -> void McpProbe.Linting.LintBaselineEntry.ParameterName.get -> string? McpProbe.Linting.LintBaselineEntry.ParameterName.init -> void @@ -67,6 +69,8 @@ McpProbe.Linting.LintFinding McpProbe.Linting.LintFinding.$() -> McpProbe.Linting.LintFinding! McpProbe.Linting.LintFinding.Deconstruct(out string! RuleId, out McpProbe.Linting.LintSeverity Severity, out string! ToolName, out string? ParameterName, out string! Message) -> void McpProbe.Linting.LintFinding.Equals(McpProbe.Linting.LintFinding? other) -> bool +McpProbe.Linting.LintFinding.Kind.get -> McpProbe.Linting.LintTargetKind +McpProbe.Linting.LintFinding.Kind.init -> void McpProbe.Linting.LintFinding.LintFinding(string! RuleId, McpProbe.Linting.LintSeverity Severity, string! ToolName, string? ParameterName, string! Message) -> void McpProbe.Linting.LintFinding.Message.get -> string! McpProbe.Linting.LintFinding.Message.init -> void @@ -132,6 +136,8 @@ 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.Kind.get -> McpProbe.Linting.LintTargetKind? +McpProbe.Linting.LintSuppression.Kind.init -> void 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 @@ -141,6 +147,11 @@ 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.LintTargetKind +McpProbe.Linting.LintTargetKind.Prompt = 1 -> McpProbe.Linting.LintTargetKind +McpProbe.Linting.LintTargetKind.Resource = 2 -> McpProbe.Linting.LintTargetKind +McpProbe.Linting.LintTargetKind.ResourceTemplate = 3 -> McpProbe.Linting.LintTargetKind +McpProbe.Linting.LintTargetKind.Tool = 0 -> McpProbe.Linting.LintTargetKind McpProbe.Linting.ToolLinter McpProbe.McpAssert McpProbe.McpProbeAssertionException @@ -296,6 +307,7 @@ static McpProbe.Linting.LintRules.All.get -> System.Collections.Generic.IReadOnl 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(McpProbe.Snapshots.ToolSurface! surface, System.Collections.Generic.IEnumerable? prompts, 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! static McpProbe.McpAssert.That(ModelContextProtocol.Client.McpClientTool! tool) -> McpProbe.Assertions.ToolAssertions! @@ -327,9 +339,16 @@ static readonly McpProbe.Linting.LintRules.DescriptionRestatesName -> McpProbe.L static readonly McpProbe.Linting.LintRules.DestructiveHintMismatch -> McpProbe.Linting.LintRule! static readonly McpProbe.Linting.LintRules.EnumWithoutValuesOrType -> McpProbe.Linting.LintRule! static readonly McpProbe.Linting.LintRules.InconsistentParameterNaming -> McpProbe.Linting.LintRule! +static readonly McpProbe.Linting.LintRules.InconsistentPromptArgumentNaming -> McpProbe.Linting.LintRule! +static readonly McpProbe.Linting.LintRules.InconsistentPromptNaming -> McpProbe.Linting.LintRule! static readonly McpProbe.Linting.LintRules.InconsistentToolNaming -> McpProbe.Linting.LintRule! +static readonly McpProbe.Linting.LintRules.InvalidPromptName -> McpProbe.Linting.LintRule! static readonly McpProbe.Linting.LintRules.InvalidToolName -> McpProbe.Linting.LintRule! static readonly McpProbe.Linting.LintRules.ParameterMissingDescription -> McpProbe.Linting.LintRule! +static readonly McpProbe.Linting.LintRules.PromptArgumentMissingDescription -> McpProbe.Linting.LintRule! +static readonly McpProbe.Linting.LintRules.PromptDescriptionRestatesName -> McpProbe.Linting.LintRule! +static readonly McpProbe.Linting.LintRules.PromptDescriptionTooShort -> McpProbe.Linting.LintRule! +static readonly McpProbe.Linting.LintRules.PromptMissingDescription -> McpProbe.Linting.LintRule! static readonly McpProbe.Linting.LintRules.RemoteRef -> McpProbe.Linting.LintRule! static readonly McpProbe.Linting.LintRules.StructuredOutputWithoutSchema -> McpProbe.Linting.LintRule! static readonly McpProbe.Linting.LintRules.ToolDescriptionTooShort -> McpProbe.Linting.LintRule! @@ -337,3 +356,4 @@ static readonly McpProbe.Linting.LintRules.ToolMissingDescription -> McpProbe.Li static readonly McpProbe.Linting.LintRules.TypeUnion -> McpProbe.Linting.LintRule! static readonly McpProbe.Linting.LintRules.UntypedSchema -> McpProbe.Linting.LintRule! static readonly McpProbe.Linting.LintRules.VagueParameterName -> McpProbe.Linting.LintRule! +static readonly McpProbe.Linting.LintRules.VaguePromptArgumentName -> McpProbe.Linting.LintRule! diff --git a/tests/McpProbe.Tests/CliTests.cs b/tests/McpProbe.Tests/CliTests.cs index eb98422..87c9b32 100644 --- a/tests/McpProbe.Tests/CliTests.cs +++ b/tests/McpProbe.Tests/CliTests.cs @@ -340,7 +340,7 @@ public async Task Report_ReplacesAnExistingFile_AndAFailedWriteLeavesNoPartialFi [Theory] [InlineData("MCPP999=none")] - [InlineData("MCPP008=error")] + [InlineData("MCPP999=error")] [InlineData("MCPP002")] [InlineData("MCPP002=loud")] public async Task Lint_InvalidRuleIsAnError(string rule) diff --git a/tests/McpProbe.Tests/LintConfigSchemaTests.cs b/tests/McpProbe.Tests/LintConfigSchemaTests.cs index 74d950a..2d3dfc5 100644 --- a/tests/McpProbe.Tests/LintConfigSchemaTests.cs +++ b/tests/McpProbe.Tests/LintConfigSchemaTests.cs @@ -70,7 +70,8 @@ public void Readme_ConfigExampleParsesWithTheLoader() var config = LintConfig.Parse(example, "mcpprobe.json"); Assert.Equal(LintSeverity.Warning, config.FailOn); - Assert.Equal(2, config.Ignore.Count); + Assert.Equal(3, config.Ignore.Count); + Assert.Equal(LintTargetKind.Prompt, config.Ignore[2].Kind); 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)) diff --git a/tests/McpProbe.Tests/LintConfigTests.cs b/tests/McpProbe.Tests/LintConfigTests.cs index 46db396..c608555 100644 --- a/tests/McpProbe.Tests/LintConfigTests.cs +++ b/tests/McpProbe.Tests/LintConfigTests.cs @@ -121,13 +121,13 @@ public void ApplyTo_OverridesTheDefaultsAndAddsRulesAndSuppressions() [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":{"MCPP999":"none"}}}""", "mcpprobe.json: lint.rules: unknown rule 'MCPP999'.")] [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":"MCPP005","why":"x"}]}}""", "mcpprobe.json: lint.ignore[0]: unknown key 'why'. Keys: rule, tool, parameter, kind, 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.")] diff --git a/tests/McpProbe.Tests/PromptLinterTests.cs b/tests/McpProbe.Tests/PromptLinterTests.cs new file mode 100644 index 0000000..3bcbcf6 --- /dev/null +++ b/tests/McpProbe.Tests/PromptLinterTests.cs @@ -0,0 +1,251 @@ +using McpProbe.Internal; +using McpProbe.Linting; +using McpProbe.Snapshots; +using Microsoft.Extensions.DependencyInjection; +using ModelContextProtocol.Protocol; +using WeatherServer; + +namespace McpProbe.Tests; + +public sealed class PromptLinterTests +{ + private const string GoodDescription = "Asks the model to do a clearly described, useful thing."; + private static readonly ToolSurface Empty = ToolSurface.Parse("""{"formatVersion":1,"tools":[]}"""); + + private static Prompt P(string name, string? description = GoodDescription, string? title = null, params (string Name, string? Description)[] args) => + new() + { + Name = name, + Title = title, + Description = description, + Arguments = args.Length == 0 ? null : args.Select(a => new PromptArgument { Name = a.Name, Description = a.Description }).ToList(), + }; + + private static IReadOnlyList Lint(LintOptions? options, params Prompt[] prompts) => + ToolLinter.Lint(Empty, prompts, options).Findings; + + private static IReadOnlyList Lint(params Prompt[] prompts) => Lint(null, prompts); + + [Fact] + public void NoPromptsListed_NoPromptFindings() + { + Assert.Empty(ToolLinter.Lint(Empty).Findings); + Assert.Empty(ToolLinter.Lint(Empty, prompts: null).Findings); + } + + [Fact] + public void EmptyPromptList_NoFindings() + { + Assert.Empty(Lint()); + } + + [Fact] + public void GoodPrompt_NoFindings() + { + Assert.Empty(Lint(P("plan_trip", args: ("city", "Destination city.")))); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public void MCPP017_MissingDescription(string? description) + { + var finding = Assert.Single(Lint(P("code_review", description))); + + Assert.Equal(("MCPP017", LintSeverity.Warning, "code_review", LintTargetKind.Prompt), (finding.RuleId, finding.Severity, finding.ToolName, finding.Kind)); + } + + [Fact] + public void MCPP018_ShortDescription() + { + var finding = Assert.Single(Lint(P("code_review", "Review code"))); + + Assert.Equal("MCPP018", finding.RuleId); + } + + [Fact] + public void MCPP024_RestatesName_SupersedesShort() + { + var finding = Assert.Single(Lint(P("code_review", "Code review."))); + + Assert.Equal("MCPP024", finding.RuleId); + } + + [Fact] + public void MCPP024_RestatesTitle() + { + var finding = Assert.Single(Lint(P("cr_v2_prompt", "Daily review", title: "Daily Review"))); + + Assert.Equal("MCPP024", finding.RuleId); + } + + [Fact] + public void MCPP024_None_FallsBackToShort() + { + var options = new LintOptions(); + options.Severities["MCPP024"] = LintSeverity.None; + + var finding = Assert.Single(Lint(options, P("code_review", "Code review."))); + + Assert.Equal("MCPP018", finding.RuleId); + } + + [Fact] + public void MCPP019_ArgumentMissingDescription() + { + var finding = Assert.Single(Lint(P("plan_trip", args: ("city", null)))); + + Assert.Equal(("MCPP019", "city", LintTargetKind.Prompt), (finding.RuleId, finding.ParameterName, finding.Kind)); + } + + [Theory] + [InlineData("Code Review")] + [InlineData("")] + [InlineData("emoji😀")] + public void MCPP020_InvalidPromptName(string name) + { + Assert.Contains(Lint(P(name)), f => f.RuleId == "MCPP020" && f.Kind == LintTargetKind.Prompt); + } + + [Fact] + public void MCPP020_LongName() + { + Assert.Contains(Lint(P(new string('a', 129))), f => f.RuleId == "MCPP020"); + } + + [Fact] + public void MCPP021_MixedPromptNameStyles() + { + var findings = Lint(P("plan_trip"), P("plan_day"), P("planWeek")); + + var finding = Assert.Single(findings, f => f.RuleId == "MCPP021"); + Assert.Equal(("planWeek", LintTargetKind.Prompt), (finding.ToolName, finding.Kind)); + } + + [Fact] + public void MCPP021_Tie_NoFinding() + { + Assert.DoesNotContain(Lint(P("plan_trip"), P("planWeek")), f => f.RuleId == "MCPP021"); + } + + [Fact] + public void MCPP021_SinglePrompt_NoFinding() + { + Assert.DoesNotContain(Lint(P("planWeek")), f => f.RuleId == "MCPP021"); + } + + [Fact] + public void MCPP021_PromptStylesDoNotMixWithToolStyles() + { + var tools = ToolSurface.Parse("""{"formatVersion":1,"tools":[{"name":"get_forecast","description":"Gets the forecast for a city."},{"name":"get_alerts","description":"Gets weather alerts for a city."}]}"""); + var findings = ToolLinter.Lint(tools, [P("planTrip"), P("planWeek")]).Findings; + + Assert.Empty(findings); + } + + [Fact] + public void MCPP022_MixedArgumentStyles() + { + var findings = Lint(P("plan_trip", args: [("start_date", "Start."), ("end_date", "End."), ("tripLength", "Days.")])); + + var finding = Assert.Single(findings, f => f.RuleId == "MCPP022"); + Assert.Equal("tripLength", finding.ParameterName); + } + + [Theory] + [InlineData("create_note", "value", false)] + [InlineData("review_note", "value", true)] + public void MCPP023_VagueArgument(string prompt, string arg, bool reported) + { + var findings = Lint(P(prompt, args: (arg, "The note text."))); + + Assert.Equal(reported, findings.Any(f => f.RuleId == "MCPP023")); + Assert.All(findings.Where(f => f.RuleId == "MCPP023"), f => Assert.Equal(LintSeverity.Info, f.Severity)); + } + + [Fact] + public void FindingToString_IncludesPromptKind() + { + var finding = Assert.Single(Lint(P("code_review", null))); + + Assert.StartsWith("warning MCPP017 prompt code_review:", finding.ToString(), StringComparison.Ordinal); + } + + [Fact] + public void HtmlReport_IncludesPromptKind() + { + var report = ToolLinter.Lint(Empty, [P("code_review", null)]); + + Assert.Contains("prompt code_review", report.ToHtml(), StringComparison.Ordinal); + } + + [Fact] + public void IgnoreByKind_HidesOnlyPrompts() + { + var tools = ToolSurface.Parse("""{"formatVersion":1,"tools":[{"name":"search"}]}"""); + var options = new LintOptions(); + options.Suppressions.Add(new LintSuppression(ToolPattern: "search") { Kind = LintTargetKind.Prompt }); + + var report = ToolLinter.Lint(tools, [P("search", null)], options); + + Assert.Contains(report.Findings, f => f.RuleId == "MCPP001" && f.Kind == LintTargetKind.Tool); + Assert.DoesNotContain(report.Findings, f => f.RuleId == "MCPP017"); + } + + [Fact] + public void Baseline_ToolEntryWithoutKind_DoesNotHidePromptFinding_WhenKindIsWritten() + { + var report = ToolLinter.Lint(Empty, [P("search", null)]); + var json = LintBaseline.FromReport(report).ToJson(); + var baseline = LintBaseline.Parse(json); + var entry = Assert.Single(baseline.Entries); + + Assert.Equal(LintTargetKind.Prompt, entry.Kind); + Assert.Contains("\"kind\": \"prompt\"", json, StringComparison.Ordinal); + } + + [Fact] + public void Baseline_OmittedKind_MatchesAnyKind() + { + var baseline = LintBaseline.Parse("""{"formatVersion":1,"findings":[{"rule":"MCPP017","tool":"search"}]}"""); + var options = new LintOptions { Baseline = baseline }; + + var report = ToolLinter.Lint(Empty, [P("search", null)], options); + + Assert.Empty(report.Findings); + Assert.Single(report.BaselinedFindings); + } + + [Fact] + public void Baseline_ToolFindings_DoNotWriteKind() + { + var tools = ToolSurface.Parse("""{"formatVersion":1,"tools":[{"name":"search"}]}"""); + var findings = ToolLinter.Lint(tools).Findings; + + Assert.DoesNotContain("kind", LintBaseline.FromReport(ToolLinter.Lint(tools)).ToJson(), StringComparison.Ordinal); + } + + [Fact] + public async Task Host_ListsPrompts_WhenCapabilityPresent() + { + await using var probe = await McpProbeHost.StartAsync(mcp => mcp.WithPromptsFromAssembly(typeof(WeatherPrompts).Assembly), TestContext.Current.CancellationToken); + + var prompts = await ListedContracts.ListPromptsAsync(probe.Client, TestContext.Current.CancellationToken); + + Assert.NotNull(prompts); + Assert.Contains(prompts, p => p.Name == "plan_trip"); + } + + [Fact] + public async Task Host_NoPromptsCapability_DoesNotListPrompts() + { + await using var probe = await McpProbeHost.StartAsync(mcp => mcp.WithToolsFromAssembly(typeof(WeatherTools).Assembly), TestContext.Current.CancellationToken); + + var prompts = await ListedContracts.ListPromptsAsync(probe.Client, TestContext.Current.CancellationToken); + var report = await probe.LintToolsAsync(cancellationToken: TestContext.Current.CancellationToken); + + Assert.Null(prompts); + Assert.DoesNotContain(report.Findings, f => f.Kind == LintTargetKind.Prompt); + } +} diff --git a/tests/McpProbe.Tests/ToolLinterTests.cs b/tests/McpProbe.Tests/ToolLinterTests.cs index 66a31de..aa5784c 100644 --- a/tests/McpProbe.Tests/ToolLinterTests.cs +++ b/tests/McpProbe.Tests/ToolLinterTests.cs @@ -294,7 +294,7 @@ public void Report_SummarizesCounts() public void Rules_HaveUniqueIds() { Assert.Equal(LintRules.All.Count, LintRules.All.Select(r => r.Id).Distinct().Count()); - Assert.Equal(["MCPP001", "MCPP002", "MCPP003", "MCPP004", "MCPP005", "MCPP006", "MCPP007", "MCPP009", "MCPP010", "MCPP011", "MCPP012", "MCPP013", "MCPP014", "MCPP015", "MCPP016"], LintRules.All.Select(r => r.Id)); + Assert.Equal(["MCPP001", "MCPP002", "MCPP003", "MCPP004", "MCPP005", "MCPP006", "MCPP007", "MCPP009", "MCPP010", "MCPP011", "MCPP012", "MCPP013", "MCPP014", "MCPP015", "MCPP016", "MCPP017", "MCPP018", "MCPP019", "MCPP020", "MCPP021", "MCPP022", "MCPP023", "MCPP024"], LintRules.All.Select(r => r.Id)); Assert.DoesNotContain(LintRules.All, r => r.Id == "MCPP008"); } From 973023c813eebd42d678c1d7e59ee188d0704600 Mon Sep 17 00:00:00 2001 From: Lior Shmueli <48066416+ShmueLior@users.noreply.github.com> Date: Fri, 4 Dec 2026 09:17:02 +0200 Subject: [PATCH 2/6] Don't call prompt ignore or baseline entries unused when prompts weren't listed --- src/McpProbe/Linting/LintBaseline.cs | 5 ++-- src/McpProbe/Linting/LintListedKinds.cs | 24 ++++++++++++++++++ src/McpProbe/Linting/LintSuppression.cs | 13 ++++++++-- src/McpProbe/Linting/ToolLinter.cs | 5 ++-- tests/McpProbe.Tests/PromptLinterTests.cs | 31 +++++++++++++++++++++++ 5 files changed, 72 insertions(+), 6 deletions(-) create mode 100644 src/McpProbe/Linting/LintListedKinds.cs diff --git a/src/McpProbe/Linting/LintBaseline.cs b/src/McpProbe/Linting/LintBaseline.cs index 9520b79..b9bd06b 100644 --- a/src/McpProbe/Linting/LintBaseline.cs +++ b/src/McpProbe/Linting/LintBaseline.cs @@ -153,7 +153,7 @@ 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) { @@ -169,7 +169,8 @@ internal static (List Active, List Baselined, List !all.Any(e.Matches) && 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); } 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/LintSuppression.cs b/src/McpProbe/Linting/LintSuppression.cs index 847e601..cb2156f 100644 --- a/src/McpProbe/Linting/LintSuppression.cs +++ b/src/McpProbe/Linting/LintSuppression.cs @@ -55,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) { @@ -84,7 +93,7 @@ internal static (List Active, List Hidden, List