diff --git a/CHANGELOG.md b/CHANGELOG.md index 02b46d6..f460219 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,17 @@ All notable changes to this project are documented here. The format is based on - `mcpprobe lint --report ` and `mcpprobe diff --report ` also write that page. Stdout and exit codes are unchanged. The file is written on exit 0 and 1, not on a usage or connection error (exit 2). - GitHub Action and Azure Pipelines template inputs `strict`, `transport`, and `report`. All three are off by default, so existing workflows keep the same CLI invocation. `report` is a directory (`lint.html` and `diff.html`); the job summary is unchanged, and artifact upload is left to the workflow (`actions/upload-artifact` / `PublishPipelineArtifact@1`). `report` requires a CLI that has `--report`; the wrapper fails fast if the installed tool does not. +### Changed + +- `lint --strict`: MCPP010 no longer reports the nullable spelling `[T, "null"]` (for example `["integer","null"]`), which the C# and Go SDKs emit for every nullable parameter. Unions of two or more non-null types, and longer unions that include `null`, are still reported, with a shorter message. This differs from Inspector's type-union check. +- MCPP002 also needs fewer than `MinToolDescriptionWords` (default 4) words, so a clear description like "Delete a file share" is not flagged for being one character short. Set `LintOptions.MinToolDescriptionWords = 0` for the old character-only check. +- MCPP007 skips a top-level `value`, `data`, `payload` and similar parameter on tools whose name has a segment like `create`, `set` or `publish`. Configure it with `LintOptions.PayloadContextTokens`. +- MCPP005 and MCPP006 say what is mixed in a name, for example "mixed ('_' and '-')", instead of just "mixed". + +### Fixed + +- MCPP005 and MCPP006 no longer report "most names are X" when two styles tie. With no majority they report nothing. + ## [0.3.0-preview] - 2026-11-28 ### Added diff --git a/README.md b/README.md index b6682ba..fe62a04 100644 --- a/README.md +++ b/README.md @@ -102,14 +102,14 @@ strict.ThrowIfFailed(); | Id | Default | Checks | |---|---|---| | MCPP001 | error | The tool has a description. | -| MCPP002 | warning | The description is at least `MinToolDescriptionLength` (20) characters. | +| MCPP002 | warning | The description is at least `MinToolDescriptionLength` (20) characters, or at least `MinToolDescriptionWords` (4) words. | | MCPP003 | warning | Every parameter has a description. | | MCPP004 | warning | The tool name is 1-128 characters of `A-Z a-z 0-9 _ - .`. | | MCPP005 | warning | All tool names use the same style (snake_case, camelCase, ...). | | MCPP006 | warning | All parameter names use the same style. | -| MCPP007 | info | Parameter names aren't vague (`data`, `value`, `input`, ...). | +| MCPP007 | info | Parameter names aren't vague (`data`, `value`, `input`, ...). A top-level `value` or `data` is fine on a tool named `create_*`, `set_*`, `publish_*` and similar (`PayloadContextTokens`). | | MCPP009 | error | No bare `true`/`false` where a schema object is expected (`--strict`). | -| MCPP010 | warning | `type` is not a union array (`--strict`). | +| MCPP010 | warning | `type` is not a union array (`--strict`). `[T, "null"]`, the nullable spelling the C# and Go SDKs emit, is not reported. | | MCPP011 | warning | Every schema has a constraining keyword (`--strict`). | | MCPP012 | warning | `$ref` does not point outside the document (`--strict`). | | MCPP013 | warning | Hints don't contradict: not read-only and destructive at once, and a `delete_*`-style name isn't marked `destructiveHint: false` or `readOnlyHint: true`. | @@ -119,7 +119,7 @@ strict.ThrowIfFailed(); 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`). They 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. +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. 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. diff --git a/src/McpProbe/Linting/LintOptions.cs b/src/McpProbe/Linting/LintOptions.cs index b3e0979..7bb5d8d 100644 --- a/src/McpProbe/Linting/LintOptions.cs +++ b/src/McpProbe/Linting/LintOptions.cs @@ -6,12 +6,28 @@ public sealed class LintOptions /// Gets or sets the minimum tool description length, in characters, for MCPP002. Defaults to 20. public int MinToolDescriptionLength { get; set; } = 20; + /// + /// Gets or sets how many words a description needs to be exempt from MCPP002 when it is shorter than + /// . Defaults to 4, so "Delete a file share" passes. Set 0 to check length only, as before. + /// + public int MinToolDescriptionWords { get; set; } = 4; + /// Gets the parameter names MCPP007 treats as vague. Compared case-insensitively. public ISet VagueParameterNames { get; } = new HashSet(StringComparer.OrdinalIgnoreCase) { "arg", "args", "data", "input", "item", "obj", "object", "param", "params", "payload", "str", "thing", "val", "value", "x", }; + /// + /// Gets the tool name segments (such as create in keyvault_secret_create) that make MCPP007 skip a top-level + /// value, data, payload or similar parameter, because the tool name says what it is. Names are split + /// on '_', '-', '.' and case changes. Compared case-insensitively. Clear it to check those parameters everywhere. + /// + public ISet PayloadContextTokens { get; } = new HashSet(StringComparer.OrdinalIgnoreCase) + { + "add", "create", "insert", "patch", "post", "publish", "put", "replace", "send", "set", "update", "upsert", "write", + }; + /// /// Gets the name segments MCPP013 treats as destructive, such as delete in delete_file or DeleteFile. /// Names are split on '_', '-', '.' and case changes; a whole segment must match. Compared case-insensitively. diff --git a/src/McpProbe/Linting/NamingStyle.cs b/src/McpProbe/Linting/NamingStyle.cs index 61fcf93..a0484fd 100644 --- a/src/McpProbe/Linting/NamingStyle.cs +++ b/src/McpProbe/Linting/NamingStyle.cs @@ -58,6 +58,43 @@ public static NamingStyle Detect(string name) _ => "mixed", }; + /// Like , but names the markers that make a name . + public static string Describe(string name, NamingStyle style) + { + if (style != NamingStyle.Other) + { + return Label(style); + } + + var markers = new List(); + if (name.Contains('_', StringComparison.Ordinal)) + { + markers.Add("'_'"); + } + + if (name.Contains('-', StringComparison.Ordinal)) + { + markers.Add("'-'"); + } + + if (name.Contains('.', StringComparison.Ordinal)) + { + markers.Add("'.'"); + } + + if (name.Any(char.IsUpper)) + { + markers.Add("uppercase"); + } + + return markers.Count switch + { + 0 => Label(style), + 1 => $"irregular ({markers[0]})", + _ => $"mixed ({string.Join(" and ", markers)})", + }; + } + private static bool IsSeparated(string name, char separator) { var parts = name.Split(separator); diff --git a/src/McpProbe/Linting/SchemaPortabilityLinter.cs b/src/McpProbe/Linting/SchemaPortabilityLinter.cs index d59b6b7..9531be8 100644 --- a/src/McpProbe/Linting/SchemaPortabilityLinter.cs +++ b/src/McpProbe/Linting/SchemaPortabilityLinter.cs @@ -139,14 +139,16 @@ private static void Walk(JsonNode? node, string path, string? keyword, int depth private static void LintNode(JsonObject node, string path, string? keyword, WalkContext ctx) { - if (TryGetPortableTypeUnion(node, out var types) && ctx.Options.IsPortabilityRuleEnabled(LintRules.TypeUnion)) + if (TryGetPortableTypeUnion(node, out var types) && + !IsNullableUnion(types) && + ctx.Options.IsPortabilityRuleEnabled(LintRules.TypeUnion)) { var rendered = string.Join(",", types.Select(t => "{\"type\":\"" + t + "\"}")); var caveat = types.Contains("null", StringComparer.Ordinal) - ? " OpenAPI 3.0 writes nullability as nullable: true, which is not JSON Schema." + ? " A null branch is not the same as an optional property." : ""; Add(ctx, LintRules.TypeUnion, path, - $"`type` is an array ({FormatTypeArray(types)}). This is legal JSON Schema but less portable: a client that expects a single type may reject the tool. Split it into anyOf of single types: {{\"anyOf\":[{rendered}]}}. Optional is a different contract: absent is not null.{caveat}"); + $"`type` is a union array ({FormatTypeArray(types)}). Some clients expect a single type and may reject the tool. Prefer anyOf of single-type schemas: {{\"anyOf\":[{rendered}]}}.{caveat}"); } var reference = JsonSchemaReader.GetString(node, "$ref"); @@ -287,6 +289,10 @@ private static bool TryGetPortableTypeUnion(JsonObject node, out List ty return true; } + // [T,"null"] is how the C# and Go SDKs spell T?, and an author can't change it, so it is not reported. + private static bool IsNullableUnion(List types) => + types.Count == 2 && types.Contains("null", StringComparer.Ordinal); + private static string FormatTypeArray(List types) => "[" + string.Join(",", types.Select(t => "\"" + t + "\"")) + "]"; diff --git a/src/McpProbe/Linting/ToolLinter.cs b/src/McpProbe/Linting/ToolLinter.cs index 618dcd2..8dafe5c 100644 --- a/src/McpProbe/Linting/ToolLinter.cs +++ b/src/McpProbe/Linting/ToolLinter.cs @@ -18,6 +18,11 @@ namespace McpProbe.Linting; /// public static class ToolLinter { + private static readonly HashSet PayloadParameterNames = new(StringComparer.OrdinalIgnoreCase) + { + "arg", "args", "data", "input", "item", "obj", "object", "param", "params", "payload", "val", "value", + }; + /// Lints protocol tools. /// The tools. /// Rule options. Defaults to defaults. @@ -51,6 +56,11 @@ public static LintReport Lint(ToolSurface surface, LintOptions? options = null) throw new ArgumentOutOfRangeException(nameof(options), "MinToolDescriptionLength can't be negative."); } + if (options.MinToolDescriptionWords < 0) + { + throw new ArgumentOutOfRangeException(nameof(options), "MinToolDescriptionWords can't be negative."); + } + var findings = new List(); var parameterNames = new List<(string Tool, string Path, string Name)>(); @@ -130,7 +140,7 @@ private static void LintProperties(Walk walk, JsonNode? schema, string? prefix) $"{noun} '{path}' has no description. Say what it is and what format it expects."); } - if (options.VagueParameterNames.Contains(name)) + if (options.VagueParameterNames.Contains(name) && !IsPayloadOfCreateTool(walk.Tool, prefix, name, options)) { Add(findings, options, LintRules.VagueParameterName, tool, path, $"{noun} name '{path}' is vague. Use a name that says what the value is (for example 'city' instead of 'value')."); @@ -143,6 +153,12 @@ private static void LintProperties(Walk walk, JsonNode? schema, string? prefix) } } + // "value" on set_secret or "data" on publish_events says what it is through the tool name. Top level only. + private static bool IsPayloadOfCreateTool(string tool, string? prefix, string name, LintOptions options) => + prefix is null && + PayloadParameterNames.Contains(name) && + SplitName(tool).Any(options.PayloadContextTokens.Contains); + private static void CheckToolName(string name, LintOptions options, List findings) { if (name.Length is < 1 or > 128 || !name.All(IsAllowedToolNameChar)) @@ -169,7 +185,8 @@ private static void CheckToolDescription(ToolContract tool, LintOptions options, Add(findings, options, LintRules.DescriptionRestatesName, tool.Name, null, "Description only restates the tool name. Say what the tool does, what it returns and when to use it."); } - else if (description.Length < options.MinToolDescriptionLength) + else if (description.Length < options.MinToolDescriptionLength && + (options.MinToolDescriptionWords == 0 || description.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries).Length < options.MinToolDescriptionWords)) { Add(findings, options, LintRules.ToolDescriptionTooShort, tool.Name, null, string.Create(CultureInfo.InvariantCulture, @@ -320,17 +337,19 @@ private static void CheckConsistency( return; } - // Majority wins; ties go to the style used first (inputs are sorted by tool name). - var majority = counts - .OrderByDescending(c => c.Count) - .ThenBy(c => classified.FindIndex(i => i.Style == c.Style)) - .First() - .Style; + // A majority needs strictly more names than every other style. On a tie nothing is "most", so report nothing. + var top = counts.Max(c => c.Count); + var leaders = counts.Where(c => c.Count == top).ToList(); + if (leaders.Count != 1) + { + return; + } + var majority = leaders[0].Style; foreach (var item in classified.Where(i => i.Style != majority)) { Add(findings, options, rule, item.Tool, item.Parameter, - $"{noun} name '{item.Name}' is {NamingStyles.Label(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)}."); } } diff --git a/src/McpProbe/PublicAPI.Unshipped.txt b/src/McpProbe/PublicAPI.Unshipped.txt index cd8c386..fdd0053 100644 --- a/src/McpProbe/PublicAPI.Unshipped.txt +++ b/src/McpProbe/PublicAPI.Unshipped.txt @@ -72,6 +72,9 @@ McpProbe.Linting.LintOptions.FailOn.set -> void McpProbe.Linting.LintOptions.LintOptions() -> void McpProbe.Linting.LintOptions.MinToolDescriptionLength.get -> int McpProbe.Linting.LintOptions.MinToolDescriptionLength.set -> void +McpProbe.Linting.LintOptions.MinToolDescriptionWords.get -> int +McpProbe.Linting.LintOptions.MinToolDescriptionWords.set -> void +McpProbe.Linting.LintOptions.PayloadContextTokens.get -> System.Collections.Generic.ISet! McpProbe.Linting.LintOptions.Severities.get -> System.Collections.Generic.IDictionary! McpProbe.Linting.LintOptions.Strict.get -> bool McpProbe.Linting.LintOptions.Strict.set -> void diff --git a/tests/McpProbe.Tests/CliTests.cs b/tests/McpProbe.Tests/CliTests.cs index 38eaab4..971c2e7 100644 --- a/tests/McpProbe.Tests/CliTests.cs +++ b/tests/McpProbe.Tests/CliTests.cs @@ -164,8 +164,8 @@ public async Task Lint_SampleServerOverStdio_PassesWithStrict() [Fact] public async Task Lint_Strict_IsOptInAndFailsOnlyOnPortabilityErrors() { - var allRules = """{"type":"object","properties":{"city":{"description":"City name.","anyOf":[true,{"type":["null","boolean"]},{},{"$ref":"https://example.com/schema.json"}]}}}"""; - var warningsOnly = """{"type":"object","properties":{"city":{"description":"City name.","type":["null","boolean"]}}}"""; + var allRules = """{"type":"object","properties":{"city":{"description":"City name.","anyOf":[true,{"type":["boolean","integer"]},{},{"$ref":"https://example.com/schema.json"}]}}}"""; + var warningsOnly = """{"type":"object","properties":{"city":{"description":"City name.","type":["boolean","integer"]}}}"""; var allFile = WriteSurface("all.json", Surface(Tool("unportable", allRules, "A tool whose schema exercises each portability rule."))); var warnFile = WriteSurface("warn.json", Surface(Tool("union", warningsOnly, "A tool whose schema uses a type union."))); @@ -177,7 +177,7 @@ public async Task Lint_Strict_IsOptInAndFailsOnlyOnPortabilityErrors() Assert.Equal(ExitCodes.CheckFailed, exit); Assert.Contains("error MCPP009", output, StringComparison.Ordinal); Assert.Contains("warning MCPP010", output, StringComparison.Ordinal); - Assert.Contains("nullable: true", output, StringComparison.Ordinal); + Assert.Contains("`type` is a union array", output, StringComparison.Ordinal); Assert.DoesNotContain("...", output, StringComparison.Ordinal); Assert.Contains("warning MCPP011", output, StringComparison.Ordinal); Assert.Contains("warning MCPP012", output, StringComparison.Ordinal); diff --git a/tests/McpProbe.Tests/ToolLinterNestedTests.cs b/tests/McpProbe.Tests/ToolLinterNestedTests.cs index 0945690..0143cfd 100644 --- a/tests/McpProbe.Tests/ToolLinterNestedTests.cs +++ b/tests/McpProbe.Tests/ToolLinterNestedTests.cs @@ -24,6 +24,16 @@ public void ByDefault_OnlyTopLevelParametersAreChecked() Assert.Equal(["home.zip", "stops[].data", "stops[].data"], Lint(schema).Select(f => f.ParameterName!).Order(StringComparer.Ordinal)); } + [Fact] + public void PayloadSkip_AppliesToTopLevelOnly_SoANestedDataOnACreateToolStillFlags() + { + var schema = """{"type":"object","properties":{"data":{"type":"object","description":"Payload.","properties":{"data":{"type":"string","description":"Inner."}}}}}"""; + var findings = ToolLinter.Lint([Tool("create_item", schema, GoodDescription)], new LintOptions { CheckNestedParameters = true }).Findings; + + var finding = Assert.Single(findings); + Assert.Equal(("MCPP007", "data.data"), (finding.RuleId, finding.ParameterName)); + } + [Fact] public void NestedPropertiesAndArrayItems_AreChecked() { diff --git a/tests/McpProbe.Tests/ToolLinterStrictTests.cs b/tests/McpProbe.Tests/ToolLinterStrictTests.cs index 09197bd..002d6d5 100644 --- a/tests/McpProbe.Tests/ToolLinterStrictTests.cs +++ b/tests/McpProbe.Tests/ToolLinterStrictTests.cs @@ -15,7 +15,7 @@ public sealed class ToolLinterStrictTests private const string GoodDescription = "Does a clearly described, useful thing."; private static readonly string UnportableCity = """ - {"type":"object","properties":{"city":{"description":"City name.","anyOf":[true,{"type":["null","boolean"]},{},{"$ref":"https://example.com/schema.json"}]}}} + {"type":"object","properties":{"city":{"description":"City name.","anyOf":[true,{"type":["boolean","integer"]},{},{"$ref":"https://example.com/schema.json"}]}}} """; private static LintOptions Strict(Action? configure = null) @@ -118,24 +118,58 @@ public void MCPP009_FiresOnOutputSchema_AndSuggestsDifferentFixUnderNot() } [Theory] - [InlineData("""["null","boolean"]""", true)] + [InlineData("""["string","integer"]""", false)] [InlineData("""["string","number","integer"]""", false)] - [InlineData("""["string","null"]""", true)] + [InlineData("""["string","integer","null"]""", true)] [InlineData("""["null","boolean","object","array","number","string","integer"]""", true)] public void MCPP010_FlagsLegalTypeUnions(string type, bool nullCaveat) { var finding = Single(Lint($$"""{"type":{{type}}}"""), "MCPP010"); Assert.Equal((LintSeverity.Warning, "inputSchema"), (finding.Severity, finding.ParameterName)); - Assert.Contains("`type` is an array", finding.Message, StringComparison.Ordinal); + Assert.Contains("`type` is a union array", finding.Message, StringComparison.Ordinal); Assert.Contains("anyOf", finding.Message, StringComparison.Ordinal); - Assert.DoesNotContain("optional", finding.Message.Split("anyOf")[0], StringComparison.Ordinal); - Assert.Equal(nullCaveat, finding.Message.Contains("nullable: true", StringComparison.Ordinal)); + Assert.DoesNotContain("nullable: true", finding.Message, StringComparison.Ordinal); + Assert.Equal(nullCaveat, finding.Message.Contains("null branch", StringComparison.Ordinal)); + Assert.InRange(finding.Message.Length, 1, 400); } [Theory] - [InlineData("""["string","null"]""", true)] - [InlineData("""["null","boolean"]""", true)] + [InlineData("string")] + [InlineData("number")] + [InlineData("integer")] + [InlineData("boolean")] + [InlineData("object")] + [InlineData("array")] + public void MCPP010_IsQuietOnNullableUnion_InEitherOrder_OnInputAndOutput(string type) + { + foreach (var union in new[] { $"[\"{type}\",\"null\"]", $"[\"null\",\"{type}\"]" }) + { + var schema = """{"type":"object","description":"D.","$defs":{"d":{"type":U}},"properties":{"p":{"description":"P.","type":U,"items":{"type":U},"prefixItems":[{"type":U}],"contentSchema":{"type":U}}}}""".Replace("U", union, StringComparison.Ordinal); + Assert.DoesNotContain(Lint(schema, outputSchema: schema), f => f.RuleId == "MCPP010"); + } + } + + [Fact] + public void MCPP010_NullableUnionStaysQuiet_ButAnotherUnionInTheSameSchemaStillFires() + { + var schema = """{"type":"object","properties":{"a":{"description":"A.","type":["string","null"]},"b":{"description":"B.","type":["string","integer"]}}}"""; + var finding = Single(Lint(schema), "MCPP010"); + Assert.Equal("inputSchema.properties.b", finding.ParameterName); + } + + [Fact] + public void MCPP010_Error_StillFailsAUnionButNotANullableUnion() + { + var options = new LintOptions(); + options.Severities["MCPP010"] = LintSeverity.Error; + Assert.True(ToolLinter.Lint(ParseSurface("t", """{"type":["string","integer"]}""", GoodDescription), options).Failed); + Assert.False(ToolLinter.Lint(ParseSurface("t", """{"type":["string","null"]}""", GoodDescription), options).Failed); + } + + [Theory] + [InlineData("""["string","integer"]""", false)] [InlineData("""["string","number","integer"]""", false)] + [InlineData("""["string","integer","null"]""", true)] [InlineData("""["null","boolean","object","array","number","string","integer"]""", true)] public void MCPP010_PrintedReportKeepsTheFullMessage(string type, bool nullCaveat) { @@ -148,8 +182,8 @@ public void MCPP010_PrintedReportKeepsTheFullMessage(string type, bool nullCavea Assert.DoesNotContain("...", printed, StringComparison.Ordinal); Assert.Contains(finding.Message, printed, StringComparison.Ordinal); Assert.Contains(finding.Message, reportText, StringComparison.Ordinal); - Assert.Equal(nullCaveat, printed.Contains("nullable: true", StringComparison.Ordinal)); - Assert.Equal(nullCaveat, reportText.Contains("nullable: true", StringComparison.Ordinal)); + Assert.Equal(nullCaveat, printed.Contains("null branch", StringComparison.Ordinal)); + Assert.Equal(nullCaveat, reportText.Contains("null branch", StringComparison.Ordinal)); } [Theory] @@ -229,7 +263,7 @@ public void MCPP012_SkipsTheDocumentWhenASubschemaIdIsSet_ButNotAnIdInExamples() [Fact] public void Walk_CoversBothSchemas_NestedPaths_AndDefs() { - var input = """{"type":"object","$defs":{"flag":true},"properties":{"city":{"description":"City.","items":{"type":["string","null"]}}}}"""; + var input = """{"type":"object","$defs":{"flag":true},"properties":{"city":{"description":"City.","items":{"type":["string","integer"]}}}}"""; var output = """{"type":"object","properties":{"result":{}}}"""; var findings = Lint(input, outputSchema: output); Assert.Contains(findings, f => f.RuleId == "MCPP009" && f.ParameterName == "inputSchema.$defs.flag"); @@ -238,8 +272,8 @@ public void Walk_CoversBothSchemas_NestedPaths_AndDefs() } [Theory] - [InlineData("""{"type":"array","items":[true,{"type":["string","null"]}]}""", "inputSchema.items[0]", "MCPP009")] - [InlineData("""{"type":"array","items":[true,{"type":["string","null"]}]}""", "inputSchema.items[1]", "MCPP010")] + [InlineData("""{"type":"array","items":[true,{"type":["string","integer"]}]}""", "inputSchema.items[0]", "MCPP009")] + [InlineData("""{"type":"array","items":[true,{"type":["string","integer"]}]}""", "inputSchema.items[1]", "MCPP010")] [InlineData("""{"type":"array","prefixItems":[true,{}]}""", "inputSchema.prefixItems[0]", "MCPP009")] [InlineData("""{"type":"array","prefixItems":[true,{}]}""", "inputSchema.prefixItems[1]", "MCPP011")] [InlineData("""{"type":"string","contentSchema":true}""", "inputSchema.contentSchema", "MCPP009")] @@ -283,7 +317,7 @@ public void RuleOverride_EnablesOneRuleWithoutStrict_AndCanDisableOneWithStrict( [Fact] public void FailOnWarning_DoesNotFailPortabilityWarnings_ButStillFailsMCPP002() { - var union = ParseSurface("warn", """{"type":["string","null"]}""", GoodDescription); + var union = ParseSurface("warn", """{"type":["string","integer"]}""", GoodDescription); var report = ToolLinter.Lint(union, new LintOptions { Strict = true, FailOn = LintSeverity.Warning }); Assert.Contains(report.Findings, f => f.RuleId == "MCPP010"); Assert.False(report.Failed); diff --git a/tests/McpProbe.Tests/ToolLinterTests.cs b/tests/McpProbe.Tests/ToolLinterTests.cs index 26c539a..66a31de 100644 --- a/tests/McpProbe.Tests/ToolLinterTests.cs +++ b/tests/McpProbe.Tests/ToolLinterTests.cs @@ -56,6 +56,27 @@ public void MCPP002_ShortDescription_UsesConfigurableMinimum() Assert.Throws(() => Lint(new LintOptions { MinToolDescriptionLength = -1 }, tool)); } + [Fact] + public void MCPP002_FourWordDescriptionIsFine_ButOneOrTwoWordsStillFlag() + { + // 19 characters, 4 words: a clear description that is one character under the minimum. + Assert.Empty(Lint(Tool("fileshares_fileshare_delete", description: "Delete a file share"))); + Assert.Equal("MCPP002", Assert.Single(Lint(Tool("search", description: "Searches."))).RuleId); + Assert.Equal("MCPP002", Assert.Single(Lint(Tool("search", description: "Search the web"))).RuleId); + Assert.Empty(Lint(Tool("search", description: "Search the web now"))); + } + + [Fact] + public void MCPP002_WordGateIsConfigurable_AndZeroRestoresCharacterOnly() + { + var tool = Tool("fileshares_fileshare_delete", description: "Delete a file share"); + + Assert.Equal("MCPP002", Assert.Single(Lint(new LintOptions { MinToolDescriptionWords = 0 }, tool)).RuleId); + Assert.Equal("MCPP002", Assert.Single(Lint(new LintOptions { MinToolDescriptionWords = 5 }, tool)).RuleId); + Assert.Throws(() => Lint(new LintOptions { MinToolDescriptionWords = -1 }, tool)); + Assert.Empty(Lint(new LintOptions { MinToolDescriptionLength = 0, MinToolDescriptionWords = 0 }, tool)); + } + [Fact] public void MCPP003_ParameterWithoutDescription() { @@ -96,6 +117,42 @@ public void MCPP005_FlagsToolsThatDeviateFromTheMajorityStyle() Assert.Equal("Tool name 'getRadar' is camelCase, but most tool names on this server are snake_case.", finding.Message); } + [Fact] + public void MCPP005_NoMajorityMeansNoFinding() + { + // One snake_case and one PascalCase: neither is "most". + Assert.Empty(Lint(Tool("get_weather", description: GoodDescription), Tool("GetRadar", description: GoodDescription))); + Assert.Empty(Lint( + Tool("a_one", description: GoodDescription), + Tool("b_two", description: GoodDescription), + Tool("CThree", description: GoodDescription), + Tool("DFour", description: GoodDescription), + Tool("e-five_six", description: GoodDescription))); + Assert.Empty(Lint( + Tool("a_one", description: GoodDescription), + Tool("bTwo", description: GoodDescription), + Tool("CThree", description: GoodDescription))); + } + + [Fact] + public void MCPP005_MixedNameSaysWhatIsMixed() + { + var findings = Lint( + Tool("get_weather", description: GoodDescription), + Tool("get_alerts", description: GoodDescription), + Tool("get_radar-map", description: GoodDescription), + Tool("Get_Forecast", description: GoodDescription), + Tool("get.tides", description: GoodDescription)); + + Assert.Equal( + [ + "Tool name 'Get_Forecast' is mixed ('_' and uppercase), but most tool names on this server are snake_case.", + "Tool name 'get.tides' is irregular ('.'), but most tool names on this server are snake_case.", + "Tool name 'get_radar-map' is mixed ('_' and '-'), but most tool names on this server are snake_case.", + ], + findings.Select(f => f.Message).Order(StringComparer.Ordinal)); + } + [Fact] public void MCPP005_LowercaseWordsAndSingleStyleAreFine() { @@ -114,6 +171,48 @@ public void MCPP006_ParameterNamingAcrossTools() Assert.Equal(("MCPP006", "b_tool", "zipCode"), (finding.RuleId, finding.ToolName, finding.ParameterName)); } + [Fact] + public void MCPP006_NoMajorityMeansNoFinding() + { + Assert.Empty(Lint( + Tool("a_tool", Params(("city_name", "City.")), GoodDescription), + Tool("b_tool", Params(("zipCode", "Zip.")), GoodDescription))); + } + + [Theory] + [InlineData("keyvault_secret_create", "value")] + [InlineData("appconfig_kv_set", "value")] + [InlineData("eventgrid_events_publish", "data")] + [InlineData("CreateSecret", "value")] + [InlineData("update-record", "Payload")] + public void MCPP007_SkipsAPayloadParameterWhenTheToolNameSaysWhatItDoes(string toolName, string parameter) + { + Assert.Empty(Lint(Tool(toolName, Params((parameter, "The thing to write.")), GoodDescription))); + } + + [Theory] + [InlineData("get_secret", "value")] + [InlineData("list_items", "data")] + [InlineData("create_secret", "thing")] + [InlineData("create_secret", "x")] + [InlineData("recreate_secret", "value")] + public void MCPP007_StillFlagsOtherToolsAndOtherNames(string toolName, string parameter) + { + var finding = Assert.Single(Lint(Tool(toolName, Params((parameter, "The thing to write.")), GoodDescription))); + Assert.Equal(("MCPP007", parameter), (finding.RuleId, finding.ParameterName)); + } + + [Fact] + public void MCPP007_ClearingPayloadContextTokensChecksEverything() + { + var options = new LintOptions(); + options.PayloadContextTokens.Clear(); + var tool = Tool("create_secret", Params(("value", "The secret.")), GoodDescription); + + Assert.Empty(Lint(tool)); + Assert.Equal("MCPP007", Assert.Single(Lint(options, tool)).RuleId); + } + [Fact] public void MCPP007_VagueParameterNames_AreInfoAndConfigurable() {