Skip to content

Commit ed8098c

Browse files
Revinandchr-hertel
andauthored
[Capability] Keep a nullable or union key of an array shape inside the shape (#613)
* [Capability] Keep a nullable or union key of an array shape inside the shape * [Capability] Map unions inside array shape keys and generics recursively --------- Co-authored-by: Christopher Hertel <mail@christopher-hertel.de>
1 parent e4cb825 commit ed8098c

6 files changed

Lines changed: 235 additions & 32 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ All notable changes to `mcp/sdk` will be documented in this file.
88
### Server
99

1010
* [BC Break] `DocBlockParser::parseDocBlock()` no longer accepts `null`; pass `ReflectionMethod::getDocComment()` as is
11+
* Fix tools with an array shape parameter whose keys are nullable or unions (e.g. `array{name: string, nickname: string|null}`) rejecting valid arguments with `-32602`: a `null` inside the shape no longer turns the parameter into `array|null`, and such keys get their own types instead of `object`, including lists and nested shapes (`string[]|null`, `array{x: int}|null`).
12+
* Fix `array<string|null>` and other generics with a union element getting `items` of type `object`. A `null` inside a generic no longer makes the parameter nullable, and neither does a DocBlock class whose name contains `null`.
1113

1214
0.9.0
1315
-----

‎src/Capability/Discovery/SchemaGenerator.php‎

Lines changed: 59 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -555,7 +555,7 @@ private function parseParametersInfo(\ReflectionMethod|\ReflectionFunction $refl
555555
$allowsNull = true;
556556
} elseif ($hasDefault && null === $defaultValue) {
557557
$allowsNull = true;
558-
} elseif (str_contains($typeString, 'null') || 'mixed' === strtolower($typeString)) {
558+
} elseif (self::hasNullBranch($typeString) || 'mixed' === strtolower($typeString)) {
559559
$allowsNull = true;
560560
}
561561

@@ -608,7 +608,7 @@ private function getParameterTypeString(\ReflectionParameter $rp, ?Param $paramT
608608
// Otherwise, use the DocBlock type if it was valid and non-generic
609609
if (null !== $docBlockType && !$isDocBlockTypeGeneric) {
610610
// Consider if DocBlock adds nullability missing from reflection
611-
if (false !== stripos($docBlockType, 'null') && $reflectionTypeString && false === stripos($reflectionTypeString, 'null') && !str_ends_with($reflectionTypeString, '|null')) {
611+
if (self::hasNullBranch($docBlockType) && $reflectionTypeString && false === stripos($reflectionTypeString, 'null') && !str_ends_with($reflectionTypeString, '|null')) {
612612
// If reflection didn't capture null, but docblock did, append |null (if not already mixed)
613613
if ('mixed' !== $reflectionTypeString) {
614614
return $reflectionTypeString.'|null';
@@ -732,6 +732,17 @@ public static function splitUnion(string $type): array
732732
return array_values(array_filter($branches, static fn (string $branch): bool => '' !== $branch));
733733
}
734734

735+
/**
736+
* Whether `null` is one of the top-level alternatives of a type, as in
737+
* `string|null`. A `null` inside a generic or a shape, as in
738+
* `array{name: string|null}`, belongs to that inner type and does not
739+
* make the whole type nullable.
740+
*/
741+
private static function hasNullBranch(string $type): bool
742+
{
743+
return \in_array('null', array_map(strtolower(...), self::splitUnion($type)), true);
744+
}
745+
735746
/**
736747
* Maps a PHP type string (potentially a union) to an array of JSON Schema type names.
737748
*
@@ -819,25 +830,21 @@ private function inferArrayItemsType(string $phpTypeString): string|array
819830
}
820831

821832
// Case 2: Generic array<T> syntax (e.g., array<string>, array<int>, etc.)
822-
if (preg_match('/^(\\??)array\s*<\s*([\w\\\\|]+)\s*>$/i', $normalizedType, $matches)) {
823-
$itemType = strtolower($matches[2]);
833+
if (preg_match('/^(\\??)array\s*<\s*([\w\\\\|?]+)\s*>$/i', $normalizedType, $matches)) {
834+
$itemSchema = $this->mapTypeToSchema(strtolower($matches[2]));
824835

825-
return $this->mapSimpleTypeToJsonSchema($itemType);
836+
return \is_string($itemSchema['type']) && 1 === \count($itemSchema) ? $itemSchema['type'] : $itemSchema;
826837
}
827838

828839
// Case 3: Nested array<array<T>> syntax or T[][] syntax
829840
if (
830-
preg_match('/^(\\??)array\s*<\s*array\s*<\s*([\w\\\\|]+)\s*>\s*>$/i', $normalizedType, $matches)
841+
preg_match('/^(\\??)array\s*<\s*array\s*<\s*([\w\\\\|?]+)\s*>\s*>$/i', $normalizedType, $matches)
831842
|| preg_match('/^(\\??)([\w\\\\]+)\s*\[\]\[\]$/i', $normalizedType, $matches)
832843
) {
833-
$innerType = $this->mapSimpleTypeToJsonSchema(isset($matches[2]) ? strtolower($matches[2]) : 'any'); /* @phpstan-ignore isset.offset */
834-
835844
// Return a schema for array with items being arrays
836845
return [
837846
'type' => 'array',
838-
'items' => [
839-
'type' => $innerType,
840-
],
847+
'items' => $this->mapTypeToSchema(strtolower($matches[2])),
841848
];
842849
}
843850

@@ -917,29 +924,49 @@ private function parsePropertyDefinition(string $propDefinition, array &$propert
917924
// Add to required properties
918925
$required[] = $propName;
919926

920-
// Check for nested array{} syntax
921-
if (preg_match('/^array\s*\{(.+)\}$/is', $propType, $nestedMatches)) {
922-
$nestedSchema = $this->parseObjectLikeArray($nestedMatches[1]);
923-
$properties[$propName] = $nestedSchema;
924-
}
925-
// Check for array<T> or T[] syntax
926-
elseif (
927-
preg_match('/^array\s*<\s*([\w\\\\|]+)\s*>$/i', $propType, $arrayMatches)
928-
|| preg_match('/^([\w\\\\]+)\s*\[\]$/i', $propType, $arrayMatches)
929-
) {
930-
$itemType = $arrayMatches[1] ?? 'any'; /* @phpstan-ignore nullCoalesce.offset */
931-
$properties[$propName] = [
932-
'type' => 'array',
933-
'items' => [
934-
'type' => $this->mapSimpleTypeToJsonSchema($itemType),
935-
],
936-
];
937-
}
938-
// Simple type
939-
else {
940-
$properties[$propName] = ['type' => $this->mapSimpleTypeToJsonSchema($propType)];
927+
$properties[$propName] = $this->mapTypeToSchema($propType);
928+
}
929+
}
930+
931+
/**
932+
* Maps a type inside a shape or generic, e.g. `string`, `int[]|null` or `array{x: int}`, to a JSON Schema.
933+
*
934+
* @return array<string, mixed>
935+
*/
936+
private function mapTypeToSchema(string $type): array
937+
{
938+
if (str_starts_with($type, '?')) {
939+
$type = 'null|'.substr($type, 1);
940+
}
941+
942+
$branches = self::splitUnion($type);
943+
if (\count($branches) > 1) {
944+
$nonNull = array_values(array_filter($branches, static fn (string $branch): bool => 'null' !== strtolower($branch)));
945+
$schemas = array_map($this->mapTypeToSchema(...), $nonNull);
946+
$types = array_values(array_unique(array_merge(...array_map(static fn (array $schema): array => (array) $schema['type'], $schemas))));
947+
if (\count($nonNull) < \count($branches)) {
948+
$types[] = 'null';
941949
}
950+
951+
// Constraints of several branches could reject what another accepts, so only a lone non-null branch keeps them.
952+
$schema = 1 === \count($schemas) ? $schemas[0] : [];
953+
$schema['type'] = 1 === \count($types) ? $types[0] : $types;
954+
955+
return $schema;
942956
}
957+
958+
if (preg_match('/^array\s*\{(.+)\}$/is', $type, $matches)) {
959+
return $this->parseObjectLikeArray($matches[1]);
960+
}
961+
962+
if (
963+
preg_match('/^array\s*<\s*([\w\\\\|?]+)\s*>$/i', $type, $matches)
964+
|| preg_match('/^([\w\\\\]+)\s*\[\]$/i', $type, $matches)
965+
) {
966+
return ['type' => 'array', 'items' => $this->mapTypeToSchema($matches[1])];
967+
}
968+
969+
return ['type' => 'null' === strtolower($type) ? 'null' : $this->mapSimpleTypeToJsonSchema($type)];
943970
}
944971

945972
/**
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the official PHP MCP SDK.
5+
*
6+
* A collaboration between Symfony and the PHP Foundation.
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Mcp\Tests\Unit\Capability\Discovery;
13+
14+
use Psr\Log\LoggerInterface;
15+
use Psr\Log\NullLogger;
16+
17+
class NullableMemberFixture
18+
{
19+
/**
20+
* @param array<string|null> $values a generic whose element may be null
21+
*/
22+
public function genericWithNullElement(array $values): void
23+
{
24+
}
25+
26+
/**
27+
* @param array{tags: string[]|null} $filter a shape key that is a nullable list
28+
*/
29+
public function shapeWithNullableList(array $filter): void
30+
{
31+
}
32+
33+
/**
34+
* @param array{point: array{x: int}|null} $input a shape key that is a nullable nested shape
35+
*/
36+
public function shapeWithNullableShape(array $input): void
37+
{
38+
}
39+
40+
/**
41+
* @param NullLogger $logger a class whose name contains "null"
42+
*/
43+
public function classNamedNull(LoggerInterface $logger): void
44+
{
45+
}
46+
}

‎tests/Unit/Capability/Discovery/SchemaGeneratorFixture.php‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -319,6 +319,22 @@ public function nullableTypedArrays(
319319
): void {
320320
}
321321

322+
/**
323+
* A `null` or `|` inside an array shape belongs to one of its keys.
324+
*
325+
* @param array{name: string, nickname: string|null} $nullUnionMember Shape with a nullable key
326+
* @param array{name: string, nickname: ?string} $nullableMember Shape with a nullable key
327+
* @param array{id: int|string} $unionMember Shape with a union key
328+
* @param array{id: int}|null $nullableShape Nullable shape
329+
*/
330+
public function arrayShapesWithUnionMembers(
331+
array $nullUnionMember,
332+
array $nullableMember,
333+
array $unionMember,
334+
$nullableShape,
335+
): void {
336+
}
337+
322338
// ===== NULLABLE AND OPTIONAL SCENARIOS =====
323339

324340
/**
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the official PHP MCP SDK.
5+
*
6+
* A collaboration between Symfony and the PHP Foundation.
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Mcp\Tests\Unit\Capability\Discovery;
13+
14+
use Mcp\Capability\Discovery\DocBlockParser;
15+
use Mcp\Capability\Discovery\SchemaGenerator;
16+
use Mcp\Capability\Discovery\SchemaValidator;
17+
use PHPUnit\Framework\TestCase;
18+
19+
final class SchemaGeneratorNullableMemberTest extends TestCase
20+
{
21+
public function testGenericWithNullElementAcceptsItsElements(): void
22+
{
23+
$schema = $this->schema('genericWithNullElement');
24+
25+
$this->assertSame([], $this->validate(['values' => ['a', null]], $schema));
26+
$this->assertSame([], $this->validate(['values' => ['a']], $schema));
27+
}
28+
29+
public function testGenericWithNullElementIsNotNullable(): void
30+
{
31+
$schema = $this->schema('genericWithNullElement');
32+
33+
$this->assertSame('array', $schema['properties']['values']['type']);
34+
$this->assertNotSame([], $this->validate(['values' => null], $schema));
35+
}
36+
37+
public function testShapeKeyWithNullableListAcceptsAList(): void
38+
{
39+
$schema = $this->schema('shapeWithNullableList');
40+
41+
$this->assertSame([], $this->validate(['filter' => ['tags' => null]], $schema));
42+
$this->assertSame([], $this->validate(['filter' => ['tags' => ['a', 'b']]], $schema));
43+
}
44+
45+
public function testShapeKeyWithNullableShapeKeepsTheInnerShape(): void
46+
{
47+
$schema = $this->schema('shapeWithNullableShape');
48+
49+
$this->assertSame([], $this->validate(['input' => ['point' => null]], $schema));
50+
$this->assertSame([], $this->validate(['input' => ['point' => ['x' => 1]]], $schema));
51+
$this->assertNotSame([], $this->validate(['input' => ['point' => ['x' => 'not an int']]], $schema));
52+
}
53+
54+
public function testClassNamedNullIsNotNullable(): void
55+
{
56+
$schema = $this->schema('classNamedNull');
57+
58+
$this->assertNotContains('null', (array) $schema['properties']['logger']['type']);
59+
}
60+
61+
/**
62+
* @return array<string, mixed>
63+
*/
64+
private function schema(string $method): array
65+
{
66+
return (new SchemaGenerator(new DocBlockParser()))
67+
->generate(new \ReflectionMethod(NullableMemberFixture::class, $method));
68+
}
69+
70+
/**
71+
* @param array<string, mixed> $schema
72+
*
73+
* @return list<array<string, mixed>>
74+
*/
75+
private function validate(mixed $data, array $schema): array
76+
{
77+
return (new SchemaValidator())->validateAgainstJsonSchema($data, $schema);
78+
}
79+
}

‎tests/Unit/Capability/Discovery/SchemaGeneratorTest.php‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -293,6 +293,39 @@ public function testRecoversItemsTypeForNullableTypedArrays(): void
293293
$this->assertEqualsCanonicalizing(['nullableStrings'], $schema['required']);
294294
}
295295

296+
public function testKeepsNullableAndUnionKeysOfArrayShapesInsideTheShape(): void
297+
{
298+
$method = new \ReflectionMethod(SchemaGeneratorFixture::class, 'arrayShapesWithUnionMembers');
299+
$schema = $this->schemaGenerator->generate($method);
300+
// The `null` of a key must neither make the parameter nullable nor turn it back into a plain array.
301+
$this->assertEquals([
302+
'type' => 'object',
303+
'description' => 'Shape with a nullable key',
304+
'properties' => ['name' => ['type' => 'string'], 'nickname' => ['type' => ['string', 'null']]],
305+
'required' => ['name', 'nickname'],
306+
], $schema['properties']['nullUnionMember']);
307+
$this->assertEquals([
308+
'type' => 'object',
309+
'description' => 'Shape with a nullable key',
310+
'properties' => ['name' => ['type' => 'string'], 'nickname' => ['type' => ['string', 'null']]],
311+
'required' => ['name', 'nickname'],
312+
], $schema['properties']['nullableMember']);
313+
$this->assertEquals([
314+
'type' => 'object',
315+
'description' => 'Shape with a union key',
316+
'properties' => ['id' => ['type' => ['integer', 'string']]],
317+
'required' => ['id'],
318+
], $schema['properties']['unionMember']);
319+
// A top-level `|null` still makes the shape nullable.
320+
$this->assertEquals([
321+
'type' => ['object', 'null'],
322+
'description' => 'Nullable shape',
323+
'properties' => ['id' => ['type' => 'integer']],
324+
'required' => ['id'],
325+
], $schema['properties']['nullableShape']);
326+
$this->assertEqualsCanonicalizing(['nullUnionMember', 'nullableMember', 'unionMember', 'nullableShape'], $schema['required']);
327+
}
328+
296329
public function testHandlesNullableTypeHintsAndOptionalParameters(): void
297330
{
298331
$method = new \ReflectionMethod(SchemaGeneratorFixture::class, 'nullableAndOptional');

0 commit comments

Comments
 (0)