From 77d6afc79df172ca5b3e581b78e9fd60a38d8ed7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 16:39:45 +0000 Subject: [PATCH 1/2] Implement MCPP008: flag required entries with no matching property A tool's input schema can list a name in `required` that isn't defined in `properties`, usually after a parameter rename that forgot to update `required`. This adds the lint rule for it, running by default like MCPP001-MCPP007; with --nested it also checks nested objects and array items. A property defined through a local $ref counts as defined, and an unresolved $ref is skipped to avoid false positives. Fixes #8 Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01RKdT6qJ3EG6ptrGZ1zEnXX --- CHANGELOG.md | 4 ++ README.md | 5 ++- docs/mcpprobe.schema.json | 1 + src/McpProbe/Linting/LintOptions.cs | 2 +- src/McpProbe/Linting/LintRule.cs | 4 +- src/McpProbe/Linting/ToolLinter.cs | 23 ++++++++++ src/McpProbe/PublicAPI.Unshipped.txt | 1 + tests/McpProbe.Tests/CliTests.cs | 2 +- tests/McpProbe.Tests/LintConfigTests.cs | 2 +- tests/McpProbe.Tests/ToolLinterNestedTests.cs | 45 +++++++++++++++++++ tests/McpProbe.Tests/ToolLinterTests.cs | 31 ++++++++++++- 11 files changed, 112 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4abeeb6..fa418d0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,10 @@ All notable changes to this project are documented here. The format is based on ## [Unreleased] +### Added + +- MCPP008: flags a `required` entry with no matching property (for example after a parameter rename that forgot to update `required`). Runs by default, like MCPP001-MCPP007; with `--nested`, also checks nested objects and array items. + ### Changed - Package tags now include `mcp-server`, `dotnet` and `csharp`. The README opening line describes McpProbe as a .NET test kit for C# MCP server testing. diff --git a/README.md b/README.md index bc32247..12c6682 100644 --- a/README.md +++ b/README.md @@ -132,6 +132,7 @@ strict.ThrowIfFailed(); | 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`, ...). A top-level `value` or `data` is fine on a tool named `create_*`, `set_*`, `publish_*` and similar (`PayloadContextTokens`). | +| MCPP008 | error | Every name in `required` is defined in `properties`. A property defined through a local `$ref` counts as defined; an unresolved `$ref` is skipped to avoid false positives. | | MCPP009 | error | No bare `true`/`false` where a schema object is expected (`--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`). | @@ -141,9 +142,9 @@ strict.ThrowIfFailed(); | MCPP015 | warning | The description says more than the tool name or title. | | MCPP016 | warning | No empty `enum`, and an `enum` declares its `type`. | -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. +Change severities with `LintOptions.Severities["MCPP007"] = LintSeverity.None`, and the threshold with `LintOptions.FailOn`. By default MCPP003, MCPP006, MCPP007 and MCPP008 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. +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`. 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/docs/mcpprobe.schema.json b/docs/mcpprobe.schema.json index a51fac8..9953005 100644 --- a/docs/mcpprobe.schema.json +++ b/docs/mcpprobe.schema.json @@ -112,6 +112,7 @@ "MCPP005", "MCPP006", "MCPP007", + "MCPP008", "MCPP009", "MCPP010", "MCPP011", diff --git a/src/McpProbe/Linting/LintOptions.cs b/src/McpProbe/Linting/LintOptions.cs index a6a2b66..76b3a15 100644 --- a/src/McpProbe/Linting/LintOptions.cs +++ b/src/McpProbe/Linting/LintOptions.cs @@ -62,7 +62,7 @@ public sealed class LintOptions public LintSeverity FailOn { get; set; } = LintSeverity.Warning; /// - /// Gets or sets whether MCPP003, MCPP006 and MCPP007 also check nested object properties and array items + /// Gets or sets whether MCPP003, MCPP006, MCPP007 and MCPP008 also check nested object properties and array items /// (reported as address.zip or stops[].city), following local $refs. Defaults to : /// only top-level parameters are checked. /// diff --git a/src/McpProbe/Linting/LintRule.cs b/src/McpProbe/Linting/LintRule.cs index 5bcbf24..4a86cca 100644 --- a/src/McpProbe/Linting/LintRule.cs +++ b/src/McpProbe/Linting/LintRule.cs @@ -30,7 +30,8 @@ public static class LintRules /// MCPP007: a parameter has a vague name such as data or value. public static readonly LintRule VagueParameterName = new("MCPP007", "Parameter name is vague", LintSeverity.Info); - // MCPP008 is reserved for https://github.com/ShmueLior/mcpprobe/issues/8 (required entry with no property). + /// MCPP008: a required entry has no matching property. + public static readonly LintRule RequiredPropertyNotDefined = new("MCPP008", "Required parameter has no matching property", LintSeverity.Error); /// MCPP009: a bare true or false is used where a schema object is expected. Requires , or a severity override. public static readonly LintRule BooleanSchema = new("MCPP009", "Bare boolean used where a schema object is expected", LintSeverity.Error); @@ -66,6 +67,7 @@ public static class LintRules InconsistentToolNaming, InconsistentParameterNaming, VagueParameterName, + RequiredPropertyNotDefined, BooleanSchema, TypeUnion, UntypedSchema, diff --git a/src/McpProbe/Linting/ToolLinter.cs b/src/McpProbe/Linting/ToolLinter.cs index a8ee6d5..ac9c639 100644 --- a/src/McpProbe/Linting/ToolLinter.cs +++ b/src/McpProbe/Linting/ToolLinter.cs @@ -132,6 +132,7 @@ private static void LintProperties(Walk walk, JsonNode? schema, string? prefix) } var properties = JsonSchemaReader.GetProperties(schema); + CheckRequiredProperties(walk, schema, properties, prefix); if (properties is null) { return; @@ -164,6 +165,28 @@ private static void LintProperties(Walk walk, JsonNode? schema, string? prefix) } } + // A $ref still present on 'schema' means it couldn't be resolved (or wasn't followed because CheckNestedParameters is off): + // either way we can't tell what properties it really has, so skip rather than risk a false positive. + private static void CheckRequiredProperties(Walk walk, JsonNode? schema, JsonObject? properties, string? prefix) + { + var (tool, options, findings) = (walk.Tool, walk.Options, walk.Findings); + if (options.SeverityOf(LintRules.RequiredPropertyNotDefined) == LintSeverity.None || JsonSchemaReader.GetString(schema, "$ref") is not null) + { + return; + } + + foreach (var name in JsonSchemaReader.GetRequired(schema)) + { + if (properties is null || !properties.ContainsKey(name)) + { + var path = prefix is null ? name : $"{prefix}.{name}"; + var noun = prefix is null ? "Parameter" : "Property"; + Add(findings, options, LintRules.RequiredPropertyNotDefined, tool, path, + $"{noun} '{name}' is required but not defined in properties."); + } + } + } + // "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 && diff --git a/src/McpProbe/PublicAPI.Unshipped.txt b/src/McpProbe/PublicAPI.Unshipped.txt index 8e6dc19..a93234f 100644 --- a/src/McpProbe/PublicAPI.Unshipped.txt +++ b/src/McpProbe/PublicAPI.Unshipped.txt @@ -321,6 +321,7 @@ static readonly McpProbe.Linting.LintRules.InconsistentToolNaming -> McpProbe.Li static readonly McpProbe.Linting.LintRules.InvalidToolName -> McpProbe.Linting.LintRule! static readonly McpProbe.Linting.LintRules.ParameterMissingDescription -> McpProbe.Linting.LintRule! static readonly McpProbe.Linting.LintRules.RemoteRef -> McpProbe.Linting.LintRule! +static readonly McpProbe.Linting.LintRules.RequiredPropertyNotDefined -> McpProbe.Linting.LintRule! static readonly McpProbe.Linting.LintRules.StructuredOutputWithoutSchema -> McpProbe.Linting.LintRule! static readonly McpProbe.Linting.LintRules.ToolDescriptionTooShort -> McpProbe.Linting.LintRule! static readonly McpProbe.Linting.LintRules.ToolMissingDescription -> McpProbe.Linting.LintRule! diff --git a/tests/McpProbe.Tests/CliTests.cs b/tests/McpProbe.Tests/CliTests.cs index badc29d..416ed57 100644 --- a/tests/McpProbe.Tests/CliTests.cs +++ b/tests/McpProbe.Tests/CliTests.cs @@ -319,7 +319,7 @@ public async Task Report_ReplacesAnExistingFile_AndAFailedWriteLeavesNoPartialFi [Theory] [InlineData("MCPP999=none")] - [InlineData("MCPP008=error")] + [InlineData("MCPP017=error")] [InlineData("MCPP002")] [InlineData("MCPP002=loud")] public async Task Lint_InvalidRuleIsAnError(string rule) diff --git a/tests/McpProbe.Tests/LintConfigTests.cs b/tests/McpProbe.Tests/LintConfigTests.cs index 46db396..e8bc1db 100644 --- a/tests/McpProbe.Tests/LintConfigTests.cs +++ b/tests/McpProbe.Tests/LintConfigTests.cs @@ -121,7 +121,7 @@ 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":{"MCPP017":"none"}}}""", "mcpprobe.json: lint.rules: unknown rule 'MCPP017'.")] [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.")] diff --git a/tests/McpProbe.Tests/ToolLinterNestedTests.cs b/tests/McpProbe.Tests/ToolLinterNestedTests.cs index 0143cfd..943463b 100644 --- a/tests/McpProbe.Tests/ToolLinterNestedTests.cs +++ b/tests/McpProbe.Tests/ToolLinterNestedTests.cs @@ -110,6 +110,51 @@ public void RefsThatFanOutALot_FinishQuickly() Assert.Empty(findings); } + [Fact] + public void MCPP008_ChecksNestedObjectsAndArrayItems() + { + var findings = Lint(""" + {"type":"object","properties":{ + "home":{"type":"object","description":"Home.","properties":{"zip":{"type":"string","description":"Zip."}},"required":["zip","floor"]}, + "stops":{"type":"array","description":"Stops.","items":{"type":"object","properties":{"city":{"type":"string","description":"City."}},"required":["city","country"]}}}} + """); + + Assert.Equal( + ["home.floor", "stops[].country"], + findings.Where(f => f.RuleId == "MCPP008").Select(f => f.ParameterName!).Order(StringComparer.Ordinal)); + } + + [Fact] + public void MCPP008_ByDefault_OnlyTopLevelIsChecked() + { + var schema = """{"type":"object","properties":{"home":{"type":"object","description":"Home.","properties":{"zip":{"type":"string","description":"Zip."}},"required":["floor"]}}}"""; + + Assert.DoesNotContain(ToolLinter.Lint([Tool("t", schema, GoodDescription)], new LintOptions()).Findings, f => f.RuleId == "MCPP008"); + } + + [Fact] + public void MCPP008_PropertyDefinedThroughLocalRefCountsAsDefined() + { + var findings = Lint(""" + {"type":"object","properties":{ + "home":{"$ref":"#/$defs/address","required":["zip"]}}, + "$defs":{"address":{"type":"object","properties":{"zip":{"type":"string","description":"Zip."}}}}} + """); + + Assert.DoesNotContain(findings, f => f.RuleId == "MCPP008"); + } + + [Fact] + public void MCPP008_UnresolvableRefIsSkipped() + { + var findings = Lint(""" + {"type":"object","properties":{ + "home":{"$ref":"#/$defs/missing","required":["zip"]}}} + """); + + Assert.DoesNotContain(findings, f => f.RuleId == "MCPP008"); + } + [Fact] public void RulesTurnedOff_DoNotReportNestedFindings() { diff --git a/tests/McpProbe.Tests/ToolLinterTests.cs b/tests/McpProbe.Tests/ToolLinterTests.cs index 66a31de..de61ede 100644 --- a/tests/McpProbe.Tests/ToolLinterTests.cs +++ b/tests/McpProbe.Tests/ToolLinterTests.cs @@ -228,6 +228,34 @@ public void MCPP007_VagueParameterNames_AreInfoAndConfigurable() Assert.Single(Lint(options, Tool("store", Params(("Stuff", "Things.")), GoodDescription))); } + [Fact] + public void MCPP008_RequiredPropertyNotDefined() + { + var tool = Tool("get_forecast", """{"type":"object","properties":{"location":{"type":"string","description":"City name."}},"required":["location","city"]}""", GoodDescription); + + var finding = Assert.Single(Lint(tool)); + Assert.Equal(("MCPP008", LintSeverity.Error, "city"), (finding.RuleId, finding.Severity, finding.ParameterName)); + Assert.Equal("error MCPP008 get_forecast.city: Parameter 'city' is required but not defined in properties.", finding.ToString()); + } + + [Fact] + public void MCPP008_NoFindingWhenEveryRequiredNameIsDefined() + { + var tool = Tool("get_forecast", """{"type":"object","properties":{"location":{"type":"string","description":"City name."}},"required":["location"]}""", GoodDescription); + + Assert.Empty(Lint(tool)); + } + + [Fact] + public void MCPP008_CanBeTurnedOff() + { + var tool = Tool("get_forecast", """{"type":"object","properties":{"location":{"type":"string","description":"City name."}},"required":["location","city"]}""", GoodDescription); + var options = new LintOptions(); + options.Severities["MCPP008"] = LintSeverity.None; + + Assert.Empty(Lint(options, tool)); + } + [Fact] public void SeverityOverrides_ChangeOrDisableRules() { @@ -294,8 +322,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.DoesNotContain(LintRules.All, r => r.Id == "MCPP008"); + Assert.Equal(["MCPP001", "MCPP002", "MCPP003", "MCPP004", "MCPP005", "MCPP006", "MCPP007", "MCPP008", "MCPP009", "MCPP010", "MCPP011", "MCPP012", "MCPP013", "MCPP014", "MCPP015", "MCPP016"], LintRules.All.Select(r => r.Id)); } [Theory] From 9cdf8279bfd83614d660d4f5674201718f004250 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 17:53:14 +0000 Subject: [PATCH 2/2] Address review: allOf/anyOf/oneOf, $ref siblings, message path, docs - allOf branches are unioned into the required/properties check (following local $ref inside a branch); anyOf/oneOf are skipped entirely rather than guessing which branch applies, matching the caution MCPP016 already uses for enums under combinators. - A required entry written alongside a $ref is now checked against the ref's resolved properties (via TryResolveRef) instead of being dropped by the walk's plain TryFindTarget swap. This runs for every visited node, including the top level, regardless of CheckNestedParameters. - Nested finding messages now quote the full path ("Property 'home.floor'...") like MCPP003/MCPP007, not the bare name. - README notes MCPP008 only checks inputSchema. - Rebased onto main (#24 merged); kept both CHANGELOG sections. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01RKdT6qJ3EG6ptrGZ1zEnXX --- CHANGELOG.md | 2 +- README.md | 2 +- src/McpProbe/Linting/ToolLinter.cs | 80 ++++++++++++++-- tests/McpProbe.Tests/ToolLinterNestedTests.cs | 14 +++ tests/McpProbe.Tests/ToolLinterTests.cs | 95 +++++++++++++++++++ 5 files changed, 183 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fa418d0..beaef13 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ All notable changes to this project are documented here. The format is based on ### Added -- MCPP008: flags a `required` entry with no matching property (for example after a parameter rename that forgot to update `required`). Runs by default, like MCPP001-MCPP007; with `--nested`, also checks nested objects and array items. +- MCPP008: flags a `required` entry with no matching property (for example after a parameter rename that forgot to update `required`). Runs by default, like MCPP001-MCPP007, on `inputSchema` only; with `--nested`, also checks nested objects and array items. `allOf` branches are unioned into the check (following local `$ref`s); `anyOf`/`oneOf` are skipped, since only one branch has to apply. A `required` written alongside a `$ref` is checked against the ref's resolved properties, not dropped. ### Changed diff --git a/README.md b/README.md index 12c6682..0c53d55 100644 --- a/README.md +++ b/README.md @@ -132,7 +132,7 @@ strict.ThrowIfFailed(); | 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`, ...). A top-level `value` or `data` is fine on a tool named `create_*`, `set_*`, `publish_*` and similar (`PayloadContextTokens`). | -| MCPP008 | error | Every name in `required` is defined in `properties`. A property defined through a local `$ref` counts as defined; an unresolved `$ref` is skipped to avoid false positives. | +| MCPP008 | error | Every name in `required` is defined in `properties` (checks `inputSchema` only, not `outputSchema`). `allOf` branches are unioned into the same check; `anyOf`/`oneOf` are skipped, since only one branch has to apply. A property defined through a local `$ref` counts as defined, including a `required` written alongside a `$ref`; an unresolved `$ref` is skipped to avoid false positives. | | MCPP009 | error | No bare `true`/`false` where a schema object is expected (`--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`). | diff --git a/src/McpProbe/Linting/ToolLinter.cs b/src/McpProbe/Linting/ToolLinter.cs index ac9c639..22e7fd4 100644 --- a/src/McpProbe/Linting/ToolLinter.cs +++ b/src/McpProbe/Linting/ToolLinter.cs @@ -112,6 +112,7 @@ private static List Order(List findings) => findings private static void LintProperties(Walk walk, JsonNode? schema, string? prefix) { var nested = walk.Options.CheckNestedParameters; + var original = schema; // Follow local refs. Each schema is linted once, at the first path that reaches it, so a type used // twice or a recursive type doesn't repeat its findings. @@ -131,8 +132,11 @@ private static void LintProperties(Walk walk, JsonNode? schema, string? prefix) LintProperties(walk, items, prefix + "[]"); } + // Independent of 'nested': this only looks at the current node (plus local $refs and allOf branches + // it names), not at whether we also recurse further down. + CheckRequiredProperties(walk, original, prefix); + var properties = JsonSchemaReader.GetProperties(schema); - CheckRequiredProperties(walk, schema, properties, prefix); if (properties is null) { return; @@ -165,28 +169,88 @@ private static void LintProperties(Walk walk, JsonNode? schema, string? prefix) } } - // A $ref still present on 'schema' means it couldn't be resolved (or wasn't followed because CheckNestedParameters is off): - // either way we can't tell what properties it really has, so skip rather than risk a false positive. - private static void CheckRequiredProperties(Walk walk, JsonNode? schema, JsonObject? properties, string? prefix) + private const int MaxCompositionDepth = 16; + + // 'schema' is the node as written, before any $ref swap the caller made for its own purposes: a sibling + // 'required' next to a $ref describes the same object as the ref's target, so it must be checked against + // the ref's resolved properties, not dropped. Runs regardless of CheckNestedParameters. + private static void CheckRequiredProperties(Walk walk, JsonNode? schema, string? prefix) { var (tool, options, findings) = (walk.Tool, walk.Options, walk.Findings); - if (options.SeverityOf(LintRules.RequiredPropertyNotDefined) == LintSeverity.None || JsonSchemaReader.GetString(schema, "$ref") is not null) + if (options.SeverityOf(LintRules.RequiredPropertyNotDefined) == LintSeverity.None) { return; } - foreach (var name in JsonSchemaReader.GetRequired(schema)) + var required = new HashSet(StringComparer.Ordinal); + var properties = new HashSet(StringComparer.Ordinal); + if (!CollectRequiredAndProperties(schema, walk.Root, required, properties, depth: 0)) { - if (properties is null || !properties.ContainsKey(name)) + return; + } + + foreach (var name in required) + { + if (!properties.Contains(name)) { var path = prefix is null ? name : $"{prefix}.{name}"; var noun = prefix is null ? "Parameter" : "Property"; Add(findings, options, LintRules.RequiredPropertyNotDefined, tool, path, - $"{noun} '{name}' is required but not defined in properties."); + $"{noun} '{path}' is required but not defined in properties."); } } } + // Follows a local $ref (via TryResolveRef, so a sibling keyword like 'required' is merged rather than lost) + // and treats 'allOf' branches as additive: they describe the same instance, so their properties and required + // names are unioned (following refs inside a branch too). 'anyOf'/'oneOf' pick between alternatives that + // can't be resolved statically, so their presence anywhere in the walk makes the whole check bail out rather + // than guess which branch applies; an unresolved $ref bails out for the same reason. + private static bool CollectRequiredAndProperties(JsonNode? schema, JsonNode? root, HashSet required, HashSet properties, int depth) + { + if (depth > MaxCompositionDepth) + { + return false; + } + + if (JsonSchemaReader.GetString(schema, "$ref") is not null) + { + if (!JsonSchemaReader.TryResolveRef(schema, root, out var resolved, out _)) + { + return false; + } + + schema = resolved; + } + + if (schema is not JsonObject obj || obj.ContainsKey("anyOf") || obj.ContainsKey("oneOf")) + { + return false; + } + + required.UnionWith(JsonSchemaReader.GetRequired(obj)); + if (JsonSchemaReader.GetProperties(obj) is { } props) + { + foreach (var (name, _) in props) + { + properties.Add(name); + } + } + + if (JsonSchemaReader.Get(obj, "allOf") is JsonArray allOf) + { + foreach (var branch in allOf) + { + if (!CollectRequiredAndProperties(branch, root, required, properties, depth + 1)) + { + return false; + } + } + } + + return true; + } + // "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 && diff --git a/tests/McpProbe.Tests/ToolLinterNestedTests.cs b/tests/McpProbe.Tests/ToolLinterNestedTests.cs index 943463b..81dd6b4 100644 --- a/tests/McpProbe.Tests/ToolLinterNestedTests.cs +++ b/tests/McpProbe.Tests/ToolLinterNestedTests.cs @@ -144,6 +144,20 @@ public void MCPP008_PropertyDefinedThroughLocalRefCountsAsDefined() Assert.DoesNotContain(findings, f => f.RuleId == "MCPP008"); } + [Fact] + public void MCPP008_RefWithSiblingRequired_NameNotInTheDefStillFlags() + { + var findings = Lint(""" + {"type":"object","properties":{ + "home":{"$ref":"#/$defs/address","required":["zip","floor"]}}, + "$defs":{"address":{"type":"object","properties":{"zip":{"type":"string","description":"Zip."}}}}} + """); + + var finding = Assert.Single(findings, f => f.RuleId == "MCPP008"); + Assert.Equal(("home.floor", "Property 'home.floor' is required but not defined in properties."), (finding.ParameterName, finding.Message)); + Assert.DoesNotContain(findings, f => f.RuleId == "MCPP008" && f.ParameterName == "home.zip"); + } + [Fact] public void MCPP008_UnresolvableRefIsSkipped() { diff --git a/tests/McpProbe.Tests/ToolLinterTests.cs b/tests/McpProbe.Tests/ToolLinterTests.cs index de61ede..48e9667 100644 --- a/tests/McpProbe.Tests/ToolLinterTests.cs +++ b/tests/McpProbe.Tests/ToolLinterTests.cs @@ -256,6 +256,101 @@ public void MCPP008_CanBeTurnedOff() Assert.Empty(Lint(options, tool)); } + [Fact] + public void MCPP008_NoPropertiesKeyAtAll_StillFlagsRequired() + { + var tool = Tool("get_forecast", """{"type":"object","required":["x"]}""", GoodDescription); + + var finding = Assert.Single(Lint(tool)); + Assert.Equal(("MCPP008", "x"), (finding.RuleId, finding.ParameterName)); + } + + [Fact] + public void MCPP008_EmptyPropertiesObject_StillFlagsRequired() + { + var tool = Tool("get_forecast", """{"type":"object","properties":{},"required":["x"]}""", GoodDescription); + + Assert.Equal("MCPP008", Assert.Single(Lint(tool)).RuleId); + } + + [Fact] + public void MCPP008_TwoMissingNames_TwoFindings() + { + var tool = Tool("get_forecast", """{"type":"object","properties":{},"required":["x","y"]}""", GoodDescription); + + Assert.Equal(["x", "y"], Lint(tool).Select(f => f.ParameterName!).Order(StringComparer.Ordinal)); + } + + [Fact] + public void MCPP008_DuplicateRequiredEntries_OneFinding() + { + var tool = Tool("get_forecast", """{"type":"object","properties":{},"required":["x","x"]}""", GoodDescription); + + Assert.Single(Lint(tool)); + } + + [Fact] + public void MCPP008_AllOf_PropertiesAreUnionedAcrossBranches() + { + var tool = Tool("get_forecast", """{"type":"object","allOf":[{"properties":{"location":{"type":"string"}}}],"required":["location"]}""", GoodDescription); + + Assert.Empty(Lint(tool)); + } + + [Fact] + public void MCPP008_AllOf_FollowsALocalRefInABranch() + { + var tool = Tool("get_forecast", + """{"type":"object","allOf":[{"$ref":"#/$defs/loc"}],"required":["location"],"$defs":{"loc":{"properties":{"location":{"type":"string"}}}}}""", + GoodDescription); + + Assert.Empty(Lint(tool)); + } + + [Fact] + public void MCPP008_AllOf_NameMissingAcrossAllBranchesStillFlags() + { + var tool = Tool("get_forecast", + """{"type":"object","allOf":[{"properties":{"a":{"type":"string"}}},{"properties":{"b":{"type":"string"}}}],"required":["a","b","c"]}""", + GoodDescription); + + var finding = Assert.Single(Lint(tool)); + Assert.Equal(("MCPP008", "c"), (finding.RuleId, finding.ParameterName)); + } + + [Fact] + public void MCPP008_AnyOf_SkipsTheCheck() + { + var tool = Tool("get_forecast", """{"type":"object","anyOf":[{"properties":{"location":{"type":"string"}}}],"required":["location","city"]}""", GoodDescription); + + Assert.Empty(Lint(tool)); + } + + [Fact] + public void MCPP008_OneOf_SkipsTheCheck() + { + var tool = Tool("get_forecast", """{"type":"object","oneOf":[{"properties":{"location":{"type":"string"}}}],"required":["location","city"]}""", GoodDescription); + + Assert.Empty(Lint(tool)); + } + + [Fact] + public void MCPP008_RefWithSiblingRequired_RunsEvenWithoutNested() + { + var tool = Tool("get_forecast", """{"type":"object","$ref":"#/$defs/base","required":["x"],"$defs":{"base":{"type":"object","properties":{"y":{"type":"string"}}}}}""", GoodDescription); + + var finding = Assert.Single(Lint(tool)); + Assert.Equal(("MCPP008", "x"), (finding.RuleId, finding.ParameterName)); + } + + [Fact] + public void MCPP008_UnresolvableRefWithSiblingRequired_IsSkipped() + { + var tool = Tool("get_forecast", """{"type":"object","$ref":"#/$defs/missing","required":["x"]}""", GoodDescription); + + Assert.Empty(Lint(tool)); + } + [Fact] public void SeverityOverrides_ChangeOrDisableRules() {