From 0ec2028a5e353e5b61f67c079778df423dbf9e12 Mon Sep 17 00:00:00 2001 From: Illia Vasylevskyi Date: Sun, 22 Nov 2026 20:21:15 -0500 Subject: [PATCH] Preserve JSON types in client tool results and output schemas --- CHANGELOG.md | 5 ++ src/Schema/MessageFactory.php | 38 +++++++++++++++ tests/Unit/Client/ProtocolTest.php | 18 +++++++ tests/Unit/Schema/MessageFactoryTest.php | 62 ++++++++++++++++++++++++ 4 files changed, 123 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c977af64..1172aa90 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,11 @@ All notable changes to `mcp/sdk` will be documented in this file. 0.11.0 ------ +### Client + +* Preserve JSON types in tool results' `structuredContent`: JSON objects now decode to `stdClass` instead of associative arrays, including nested objects. JSON arrays remain PHP arrays. The response envelope and content blocks are unchanged; `hasStructuredContent()` still distinguishes explicit `null` from an omitted field. +* Preserve nested JSON types in discovered `outputSchema` definitions; the public schema root remains a PHP array. If a NUL-prefixed member forces associative decoding, reject responses with shape-sensitive tool data instead of returning ambiguous values. + ### Server * Fix const validation errors always reporting the expected value as null. diff --git a/src/Schema/MessageFactory.php b/src/Schema/MessageFactory.php index ce937773..04464fa2 100644 --- a/src/Schema/MessageFactory.php +++ b/src/Schema/MessageFactory.php @@ -147,6 +147,26 @@ private function createMessage(\stdClass|array $message): MessageInterface } if (isset($data['result'])) { + if (\is_array($message) && \is_array($data['result']) && self::hasShapeSensitiveToolData($data['result'])) { + // Correlate the refusal to the pending call instead of dropping the response. + return Error::forInvalidRequest('Cannot preserve tool response JSON types in a message with a member name starting with a NUL byte.', Response::fromArray($data)->getId()); + } + + // Retain only the shape-sensitive fields; envelope DTOs still expect arrays. + if ($message instanceof \stdClass && ($message->result ?? null) instanceof \stdClass) { + $result = $message->result; + if (property_exists($result, 'structuredContent')) { + $data['result']['structuredContent'] = $result->structuredContent; + } + if (\is_array($result->tools ?? null)) { + foreach ($result->tools as $index => $tool) { + if ($tool instanceof \stdClass && ($tool->outputSchema ?? null) instanceof \stdClass) { + $data['result']['tools'][$index]['outputSchema'] = (array) $tool->outputSchema; + } + } + } + } + return Response::fromArray($data); } @@ -179,6 +199,24 @@ private function createMessage(\stdClass|array $message): MessageInterface } } + /** @param array $result */ + private static function hasShapeSensitiveToolData(array $result): bool + { + if (\is_array($result['structuredContent'] ?? null)) { + return true; + } + + if (\is_array($result['tools'] ?? null)) { + foreach ($result['tools'] as $tool) { + if (\is_array($tool) && \is_array($tool['outputSchema'] ?? null)) { + return true; + } + } + } + + return false; + } + /** * Finds the registered message class for a given method name. * diff --git a/tests/Unit/Client/ProtocolTest.php b/tests/Unit/Client/ProtocolTest.php index 5ebc8dcd..8a0594af 100644 --- a/tests/Unit/Client/ProtocolTest.php +++ b/tests/Unit/Client/ProtocolTest.php @@ -329,6 +329,24 @@ public function testErrorResponseWithIdIsStoredForItsPendingRequest(): void $this->assertSame(Error::METHOD_NOT_FOUND, $response->code); } + public function testLossyToolResponseCompletesThePendingRequestWithAnError(): void + { + $protocol = new Protocol(); + foreach ([ + '{"content":[],"structuredContent":{"\u0000key":{},"list":[]}}', + '{"tools":[{"name":"t","inputSchema":{},"outputSchema":{"const":{"\u0000key":{}}}}]}', + ] as $result) { + $protocol->getState()->addPendingRequest(7, 30); + $protocol->processMessage('{"jsonrpc":"2.0","id":7,"result":'.$result.'}'); + + $response = $protocol->getState()->consumeResponse(7); + $this->assertInstanceOf(Error::class, $response); + $this->assertSame(7, $response->getId()); + $this->assertSame(Error::INVALID_REQUEST, $response->code); + $protocol->getState()->removePendingRequest(7); + } + } + #[TestDox('a response for a cancelled request cannot accumulate in state')] public function testIgnoresResponseForNoLongerPendingRequest(): void { diff --git a/tests/Unit/Schema/MessageFactoryTest.php b/tests/Unit/Schema/MessageFactoryTest.php index 2c92eb17..1f316dd6 100644 --- a/tests/Unit/Schema/MessageFactoryTest.php +++ b/tests/Unit/Schema/MessageFactoryTest.php @@ -23,6 +23,9 @@ use Mcp\Schema\Request\GetPromptRequest; use Mcp\Schema\Request\InitializeRequest; use Mcp\Schema\Request\PingRequest; +use Mcp\Schema\Result\CallToolResult; +use Mcp\Schema\Result\ListToolsResult; +use Mcp\Server\Capability\Discovery\SchemaValidator; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; @@ -59,6 +62,65 @@ public function testRootArgumentsWithNumericKeysStayAnObjectOnTheWire(): void $this->assertStringContainsString('"arguments":{"0":"x"}', json_encode($message, \JSON_THROW_ON_ERROR)); } + #[DataProvider('provideStructuredContent')] + public function testToolResultKeepsStructuredJsonTypes(?string $json): void + { + $content = '[{"type":"text","text":"legacy"}]'; + $message = $this->factory->create('{"jsonrpc":"2.0","id":1,"result":{"content":'.$content.(null === $json ? '' : ',"structuredContent":'.$json).'}}'); + + $this->assertInstanceOf(Response::class, $message); + $this->assertSame([['type' => 'text', 'text' => 'legacy']], $message->result['content']); + $result = CallToolResult::fromArray($message->result); + $this->assertSame(null !== $json, $result->hasStructuredContent()); + $serialized = $result->jsonSerialize(); + if (null !== $json) { + $this->assertArrayHasKey('structuredContent', $serialized); + $this->assertSame($json, json_encode($result->structuredContent, \JSON_THROW_ON_ERROR)); + $this->assertSame($json, json_encode($serialized['structuredContent'] ?? null, \JSON_THROW_ON_ERROR)); + } else { + $this->assertArrayNotHasKey('structuredContent', $serialized); + } + } + + public static function provideStructuredContent(): iterable + { + yield 'absent' => [null]; + yield 'explicit null' => ['null']; + yield 'false' => ['false']; + yield 'zero' => ['0']; + yield 'empty string' => ['""']; + yield 'empty list' => ['[]']; + yield 'empty object' => ['{}']; + yield 'nested shapes' => ['{"object":{},"list":[],"numeric":{"0":"x"},"nested":[{},[]]}']; + } + + public function testParsedEmptyToolObjectSatisfiesObjectSchema(): void + { + $message = $this->factory->create('{"jsonrpc":"2.0","id":1,"result":{"content":[],"structuredContent":{}}}'); + + $this->assertInstanceOf(Response::class, $message); + $result = CallToolResult::fromArray($message->result); + $this->assertInstanceOf(\stdClass::class, $result->structuredContent); + $this->assertSame([], (new SchemaValidator())->validateAgainstJsonSchema($result->structuredContent, ['type' => 'object'])); + } + + public function testDiscoveredOutputSchemaKeepsJsonShapes(): void + { + $schema = '{"type":"object","properties":{"object":{"const":{}},"list":{"const":[]},"literal":{"enum":[{},[],{"0":"x"}]},"empty":{}}}'; + $response = $this->factory->create('{"jsonrpc":"2.0","id":1,"result":{"tools":[{"name":"t","inputSchema":{"type":"object","properties":{}},"outputSchema":'.$schema.'}]}}'); + + $this->assertInstanceOf(Response::class, $response); + $this->assertSame([], $response->result['tools'][0]['inputSchema']['properties']); + $tool = ListToolsResult::fromArray($response->result)->tools[0]; + $this->assertIsArray($tool->outputSchema); + $this->assertSame($schema, json_encode($tool->jsonSerialize()['outputSchema'] ?? null, \JSON_THROW_ON_ERROR)); + + $validator = new SchemaValidator(); + $this->assertSame([], $validator->validateAgainstJsonSchema((object) ['object' => new \stdClass(), 'list' => []], $tool->outputSchema)); + $this->assertNotEmpty($validator->validateAgainstJsonSchema((object) ['object' => [], 'list' => []], $tool->outputSchema)); + $this->assertNotEmpty($validator->validateAgainstJsonSchema((object) ['object' => new \stdClass(), 'list' => new \stdClass()], $tool->outputSchema)); + } + public function testOtherParamsAreDecodedToArrays(): void { $message = MessageFactory::make()->create('{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"x","version":"1"}}}');