Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
38 changes: 38 additions & 0 deletions src/Schema/MessageFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand Down Expand Up @@ -179,6 +199,24 @@ private function createMessage(\stdClass|array $message): MessageInterface
}
}

/** @param array<mixed> $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.
*
Expand Down
18 changes: 18 additions & 0 deletions tests/Unit/Client/ProtocolTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down
62 changes: 62 additions & 0 deletions tests/Unit/Schema/MessageFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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"}}}');
Expand Down