diff --git a/CHANGELOG.md b/CHANGELOG.md index c977af64..c3c10a29 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,8 @@ All notable changes to `mcp/sdk` will be documented in this file. ### Server +* Generate numeric `exclusiveMinimum` and `exclusiveMaximum` constraints for JSON Schema 2020-12. `#[Schema]` accepts numeric bounds and still supports boolean flags after merging method and parameter settings. +* [BC Break] Reject a `#[Schema]` exclusive-bound flag set to `true` without a corresponding numeric `minimum` or `maximum`. Subclasses redeclaring the two exclusive-bound properties must match their widened `int|float|bool|null` types. * Fix const validation errors always reporting the expected value as null. 0.10.0 diff --git a/docs/servers/schemas.md b/docs/servers/schemas.md index b77f4934..dc9660db 100644 --- a/docs/servers/schemas.md +++ b/docs/servers/schemas.md @@ -90,6 +90,15 @@ public function validateUser( } ``` +For exclusive numeric bounds, use `#[Schema(exclusiveMinimum: 0, exclusiveMaximum: 5)]` to require a value strictly +between 0 and 5. These keywords take numbers in JSON Schema 2020-12, the default dialect in MCP. + +The legacy boolean form is still supported: `#[Schema(minimum: 0, exclusiveMinimum: true)]` generates +`{"minimum": 0, "exclusiveMinimum": 0}`. A `false` flag is omitted from the generated schema, leaving any inclusive +bound in place. Flags are resolved after method-level and parameter-level settings are merged, so a bound can be +inherited from the method. A `true` flag without a corresponding numeric bound raises an `InvalidArgumentException` +during schema generation. Complete `definition` overrides are passed through without this conversion. + ## Method-Level Schema Add validation for complex object structures: diff --git a/src/Server/Capability/Attribute/Schema.php b/src/Server/Capability/Attribute/Schema.php index 15120a28..949276fa 100644 --- a/src/Server/Capability/Attribute/Schema.php +++ b/src/Server/Capability/Attribute/Schema.php @@ -31,8 +31,8 @@ * pattern?: string, * minimum?: int|float, * maximum?: int|float, - * exclusiveMinimum?: bool, - * exclusiveMaximum?: bool, + * exclusiveMinimum?: int|float|bool, + * exclusiveMaximum?: int|float|bool, * multipleOf?: int|float, * items?: array, * minItems?: int, @@ -77,8 +77,8 @@ class Schema // Constraints for number/integer public int|float|null $minimum = null; public int|float|null $maximum = null; - public ?bool $exclusiveMinimum = null; - public ?bool $exclusiveMaximum = null; + public int|float|bool|null $exclusiveMinimum = null; + public int|float|bool|null $exclusiveMaximum = null; public int|float|null $multipleOf = null; // Constraints for array @@ -115,8 +115,8 @@ class Schema * @param ?string $pattern regex pattern for strings * @param int|float|null $minimum minimum value for numbers/integers * @param int|float|null $maximum maximum value for numbers/integers - * @param ?bool $exclusiveMinimum exclusive minimum - * @param ?bool $exclusiveMaximum exclusive maximum + * @param int|float|bool|null $exclusiveMinimum exclusive minimum value, or a legacy flag for $minimum + * @param int|float|bool|null $exclusiveMaximum exclusive maximum value, or a legacy flag for $maximum * @param int|float|null $multipleOf must be a multiple of this value * @param ?array $items JSON Schema for items if type is 'array' * @param ?int $minItems minimum items for an array @@ -137,8 +137,8 @@ public function __construct( ?string $pattern = null, int|float|null $minimum = null, int|float|null $maximum = null, - ?bool $exclusiveMinimum = null, - ?bool $exclusiveMaximum = null, + int|float|bool|null $exclusiveMinimum = null, + int|float|bool|null $exclusiveMaximum = null, int|float|null $multipleOf = null, ?array $items = null, ?int $minItems = null, @@ -174,7 +174,7 @@ public function __construct( } /** - * Converts the attribute's definition to a JSON schema array. + * Extracts the attribute's settings for schema generation. * * @return SchemaAttributeData */ diff --git a/src/Server/Capability/Discovery/SchemaGenerator.php b/src/Server/Capability/Discovery/SchemaGenerator.php index 4b26e7a1..77837606 100644 --- a/src/Server/Capability/Discovery/SchemaGenerator.php +++ b/src/Server/Capability/Discovery/SchemaGenerator.php @@ -205,7 +205,7 @@ private function buildSchemaFromParameters(array $parametersInfo, ?array $method unset($schema['required']); } - return $schema; + return $this->normalizeExclusiveBounds($schema); } /** @@ -244,12 +244,45 @@ private function buildParameterSchema(array $paramInfo, ?array $methodLevelParam } } + if (!isset($parameterLevelSchema['definition'])) { + $mergedSchema = $this->normalizeExclusiveBounds($mergedSchema); + } + // Run after all merges so that when a Schema attribute reshapes the parameter // (e.g. to `object`), the array `items` invariant is only enforced on what is // genuinely still an array. return $this->ensureObjectDefault($this->ensureArrayItems($mergedSchema)); } + /** + * @param array $schema + * + * @return array + */ + private function normalizeExclusiveBounds(array $schema): array + { + foreach (['minimum' => 'exclusiveMinimum', 'maximum' => 'exclusiveMaximum'] as $bound => $exclusive) { + $value = $schema[$exclusive] ?? null; + if (!\is_bool($value)) { + continue; + } + + if (false === $value) { + unset($schema[$exclusive]); + continue; + } + + $limit = $schema[$bound] ?? null; + if (!\is_int($limit) && !\is_float($limit)) { + throw new InvalidArgumentException(\sprintf('Schema keyword "%s" set to true requires a numeric "%s".', $exclusive, $bound)); + } + + $schema[$exclusive] = $limit; + } + + return $schema; + } + /** * An empty PHP array encodes as `[]`, which a client could not send back to an object-only parameter. * @@ -374,6 +407,10 @@ private function buildVariadicParameterSchema(array $paramInfo): array } } + if (!isset($paramInfo['parameter_schema']['definition'])) { + $paramSchema = $this->normalizeExclusiveBounds($paramSchema); + } + return $paramSchema; } diff --git a/tests/Unit/Server/Capability/Discovery/SchemaGeneratorExclusiveBoundsTest.php b/tests/Unit/Server/Capability/Discovery/SchemaGeneratorExclusiveBoundsTest.php new file mode 100644 index 00000000..d36842d7 --- /dev/null +++ b/tests/Unit/Server/Capability/Discovery/SchemaGeneratorExclusiveBoundsTest.php @@ -0,0 +1,185 @@ + $bounds + * @param list $valid + * @param list $invalid + */ + #[DataProvider('bounds')] + public function testGeneratedBoundsValidateStrictly(\Closure $handler, array $bounds, array $valid, array $invalid): void + { + $schema = $this->generate(new \ReflectionFunction($handler)); + + $this->assertSame(['type' => 'number', ...$bounds], $schema['properties']['n']); + + $validator = new Validator(); + $validator->parser()->setOption('allowExclusiveMinMaxAsBool', false); + $decodedSchema = json_decode(json_encode($schema, \JSON_THROW_ON_ERROR), false, 512, \JSON_THROW_ON_ERROR); + + foreach ($valid as $n) { + $this->assertTrue($validator->validate((object) ['n' => $n], $decodedSchema)->isValid(), (string) $n); + } + foreach ($invalid as $n) { + $this->assertFalse($validator->validate((object) ['n' => $n], $decodedSchema)->isValid(), (string) $n); + } + } + + public static function bounds(): iterable + { + yield 'numeric zero lower bound' => [ + static fn (#[Schema(exclusiveMinimum: 0)] float $n): float => $n, + ['exclusiveMinimum' => 0], [0.5, 1], [-1, 0], + ]; + yield 'numeric zero upper bound' => [ + static fn (#[Schema(exclusiveMaximum: 0)] float $n): float => $n, + ['exclusiveMaximum' => 0], [-1, -0.5], [0, 1], + ]; + yield 'fractional bounds' => [ + static fn (#[Schema(exclusiveMinimum: -1.5, exclusiveMaximum: 2.5)] float $n): float => $n, + ['exclusiveMinimum' => -1.5, 'exclusiveMaximum' => 2.5], [-1, 0, 2], [-1.5, 2.5], + ]; + yield 'floating zero' => [ + static fn (#[Schema(exclusiveMinimum: 0.0)] float $n): float => $n, + ['exclusiveMinimum' => 0.0], [0.5], [0], + ]; + yield 'legacy true' => [ + static fn (#[Schema(minimum: 0, maximum: 5, exclusiveMinimum: true, exclusiveMaximum: true)] float $n): float => $n, + ['minimum' => 0, 'maximum' => 5, 'exclusiveMinimum' => 0, 'exclusiveMaximum' => 5], [0.5, 4], [0, 5], + ]; + yield 'legacy fractional bounds' => [ + static fn (#[Schema(minimum: -1.5, maximum: 2.5, exclusiveMinimum: true, exclusiveMaximum: true)] float $n): float => $n, + ['minimum' => -1.5, 'maximum' => 2.5, 'exclusiveMinimum' => -1.5, 'exclusiveMaximum' => 2.5], [-1, 2], [-1.5, 2.5], + ]; + yield 'legacy false keeps inclusive bounds' => [ + static fn (#[Schema(minimum: 0, maximum: 5, exclusiveMinimum: false, exclusiveMaximum: false)] float $n): float => $n, + ['minimum' => 0, 'maximum' => 5], [0, 5], [-1, 6], + ]; + yield 'false without bounds' => [ + static fn (#[Schema(exclusiveMinimum: false, exclusiveMaximum: false)] float $n): float => $n, + [], [-1, 0, 1], [], + ]; + yield 'null without bounds' => [ + static fn (#[Schema(exclusiveMinimum: null, exclusiveMaximum: null)] float $n): float => $n, + [], [-1, 0, 1], [], + ]; + yield 'independent numeric bounds' => [ + static fn (#[Schema(minimum: 2, maximum: 8, exclusiveMinimum: 0, exclusiveMaximum: 10)] float $n): float => $n, + ['minimum' => 2, 'maximum' => 8, 'exclusiveMinimum' => 0, 'exclusiveMaximum' => 10], [2, 8], [1, 9], + ]; + } + + public function testBoundsAreResolvedAfterMerging(): void + { + $handler = new class { + #[Schema(properties: ['n' => ['minimum' => 0, 'maximum' => 5]])] + public function inherit(#[Schema(exclusiveMinimum: true, exclusiveMaximum: true)] float $n): void + { + } + + #[Schema(properties: ['n' => ['minimum' => 0, 'maximum' => 5, 'exclusiveMinimum' => true, 'exclusiveMaximum' => true]])] + public function override(#[Schema(minimum: -2, maximum: 10)] float $n): void + { + } + + #[Schema(properties: ['n' => ['minimum' => 0, 'maximum' => 5, 'exclusiveMinimum' => 1, 'exclusiveMaximum' => 4]])] + public function inclusive(#[Schema(exclusiveMinimum: false, exclusiveMaximum: false)] float $n): void + { + } + }; + + $inherited = $this->generate(new \ReflectionMethod($handler, 'inherit')); + $overridden = $this->generate(new \ReflectionMethod($handler, 'override')); + $inclusive = $this->generate(new \ReflectionMethod($handler, 'inclusive')); + + $this->assertSame(['type' => 'number', 'minimum' => 0, 'maximum' => 5, 'exclusiveMinimum' => 0, 'exclusiveMaximum' => 5], $inherited['properties']['n']); + $this->assertSame(['type' => 'number', 'minimum' => -2, 'maximum' => 10, 'exclusiveMinimum' => -2, 'exclusiveMaximum' => 10], $overridden['properties']['n']); + $this->assertSame(['type' => 'number', 'minimum' => 0, 'maximum' => 5], $inclusive['properties']['n']); + } + + #[DataProvider('missingBounds')] + public function testTrueRequiresACorrespondingBound(\Closure $handler, string $exclusive, string $bound): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage(\sprintf('Schema keyword "%s" set to true requires a numeric "%s".', $exclusive, $bound)); + + $this->generate(new \ReflectionFunction($handler)); + } + + public static function missingBounds(): iterable + { + yield 'minimum' => [static fn (#[Schema(exclusiveMinimum: true)] float $n): float => $n, 'exclusiveMinimum', 'minimum']; + yield 'maximum' => [static fn (#[Schema(exclusiveMaximum: true)] float $n): float => $n, 'exclusiveMaximum', 'maximum']; + } + + public function testMethodLevelAndVariadicSettingsAreNormalized(): void + { + $handler = new class { + #[Schema(minimum: 0, exclusiveMinimum: true, exclusiveMaximum: false)] + public function handle(#[Schema(maximum: 5, exclusiveMaximum: true)] float ...$n): void + { + } + }; + + $schema = $this->generate(new \ReflectionMethod($handler, 'handle')); + + $this->assertSame(0, $schema['exclusiveMinimum']); + $this->assertArrayNotHasKey('exclusiveMaximum', $schema); + $this->assertSame(5, $schema['properties']['n']['exclusiveMaximum']); + $this->assertSame(['type' => 'number'], $schema['properties']['n']['items']); + } + + public function testCompleteDefinitionsAreNotRewritten(): void + { + $handler = new class { + #[Schema(definition: ['type' => 'object', 'exclusiveMinimum' => true])] + public function method(): void + { + } + + #[Schema(properties: ['n' => ['minimum' => 0, 'exclusiveMinimum' => true]])] + public function parameter(#[Schema(definition: ['type' => 'number', 'exclusiveMinimum' => false])] float $n = 1): void + { + } + + public function variadic(#[Schema(definition: ['type' => 'array', 'exclusiveMaximum' => true])] float ...$n): void + { + } + }; + + $this->assertSame(['type' => 'object', 'exclusiveMinimum' => true], $this->generate(new \ReflectionMethod($handler, 'method'))); + $this->assertSame(['type' => 'number', 'exclusiveMinimum' => false, 'default' => 1.0], $this->generate(new \ReflectionMethod($handler, 'parameter'))['properties']['n']); + $this->assertTrue($this->generate(new \ReflectionMethod($handler, 'variadic'))['properties']['n']['exclusiveMaximum']); + } + + /** + * @return array + */ + private function generate(\ReflectionFunctionAbstract $reflection): array + { + return (new SchemaGenerator(new DocBlockParser()))->generate($reflection); + } +} diff --git a/tests/Unit/Server/Capability/Discovery/SchemaGeneratorTest.php b/tests/Unit/Server/Capability/Discovery/SchemaGeneratorTest.php index 90e57d14..abc9672a 100644 --- a/tests/Unit/Server/Capability/Discovery/SchemaGeneratorTest.php +++ b/tests/Unit/Server/Capability/Discovery/SchemaGeneratorTest.php @@ -212,7 +212,7 @@ public function testAppliesNumericConstraintsFromParameterLevelSchemaAttributes( $method = new \ReflectionMethod(SchemaGeneratorFixture::class, 'parameterNumericConstraints'); $schema = $this->schemaGenerator->generate($method); $this->assertEquals(['minimum' => 18, 'maximum' => 120, 'type' => 'integer'], $schema['properties']['age']); - $this->assertEquals(['minimum' => 0, 'maximum' => 5, 'exclusiveMaximum' => true, 'type' => 'number'], $schema['properties']['rating']); + $this->assertEquals(['minimum' => 0, 'maximum' => 5, 'exclusiveMaximum' => 5, 'type' => 'number'], $schema['properties']['rating']); $this->assertEquals(['multipleOf' => 10, 'type' => 'integer'], $schema['properties']['count']); $this->assertEqualsCanonicalizing(['age', 'rating', 'count'], $schema['required']); }