Skip to content

Commit 1eaef58

Browse files
committed
[Server] Refuse only tools/call on member names starting with NUL
1 parent ec823d4 commit 1eaef58

6 files changed

Lines changed: 97 additions & 23 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ All notable changes to `mcp/sdk` will be documented in this file.
4343
* [BC Break] Keep the JSON types of `tools/call` arguments, so validation sees what the client sent: `{}` and `{"0":"x"}` are objects, `[]` and `["x"]` are arrays. Nested JSON objects in `CallToolRequest::$arguments` and in the arguments of `ToolHandlerInterface::execute()` are `\stdClass`.
4444
* [BC Break] Tool parameters without a type, or typed `mixed`, receive nested JSON objects as `\stdClass`. Parameters typed `array` still receive arrays at every level. Parameters typed `object` or `\stdClass`, which always failed with a `TypeError`, receive `\stdClass`.
4545
* [BC Break] Reject `tools/call` when `arguments` is not a JSON object with `-32600`, including `"arguments": []`.
46-
* [BC Break] Reject a JSON-RPC message with a member name starting with a NUL byte with `-32600`, as a PHP object cannot hold such a name.
46+
* [BC Break] Reject `tools/call` with `-32600` when its message has a member name starting with a NUL byte, as its arguments cannot keep their JSON types then.
4747
* [BC Break] `array<string, T>` parameters generate `{"type": "object"}` instead of `{"type": "array"}`, and `array<int, T>` parameters accept a JSON array or a JSON object.
4848

4949
### Client

‎src/JsonRpc/MessageFactory.php‎

Lines changed: 12 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -106,17 +106,18 @@ public function create(string $input): MessageInterface
106106
throw $e;
107107
}
108108

109-
throw self::invalidMemberName($input);
109+
// A PHP object cannot hold a property whose name starts with NUL.
110+
$data = json_decode($input, true, flags: \JSON_THROW_ON_ERROR);
110111
}
111112

112-
if (!$data instanceof \stdClass) {
113+
if (!$data instanceof \stdClass && (!\is_array($data) || str_starts_with(ltrim($input), '['))) {
113114
throw new InvalidInputMessageException('A JSON-RPC message must be a single JSON object.');
114115
}
115116

116117
try {
117118
return $this->createMessage($data);
118119
} catch (InvalidInputMessageException $e) {
119-
$id = $data->id ?? null;
120+
$id = ((array) $data)['id'] ?? null;
120121
if (\is_string($id) || \is_int($id)) {
121122
$e->setRequestId($id);
122123
}
@@ -125,29 +126,14 @@ public function create(string $input): MessageInterface
125126
}
126127
}
127128

128-
/**
129-
* Valid JSON, but a PHP object cannot hold a property whose name starts with NUL.
130-
*
131-
* @throws \JsonException when the input is malformed after that name
132-
*/
133-
private static function invalidMemberName(string $input): InvalidInputMessageException
134-
{
135-
$exception = new InvalidInputMessageException('A JSON-RPC message must not have a member name starting with a NUL byte.');
136-
$id = json_decode($input, true, flags: \JSON_THROW_ON_ERROR)['id'] ?? null;
137-
138-
if (\is_string($id) || \is_int($id)) {
139-
$exception->setRequestId($id);
140-
}
141-
142-
return $exception;
143-
}
144-
145129
/**
146130
* Creates a single message object from parsed JSON data.
147131
*
132+
* @param \stdClass|array<string, mixed> $message
133+
*
148134
* @throws InvalidInputMessageException
149135
*/
150-
private function createMessage(\stdClass $message): MessageInterface
136+
private function createMessage(\stdClass|array $message): MessageInterface
151137
{
152138
/** @var array<string, mixed> $data */
153139
$data = Json::objectsToArrays($message);
@@ -171,8 +157,12 @@ private function createMessage(\stdClass $message): MessageInterface
171157

172158
$messageClass = $this->findMessageClassByMethod($data['method']);
173159

160+
if (\is_array($message) && is_subclass_of($messageClass, Request::class) && $messageClass::requiresJsonTypes()) {
161+
throw new InvalidInputMessageException(\sprintf('"%s" cannot be served from a message with a member name starting with a NUL byte.', $data['method']));
162+
}
163+
174164
// Each message knows which of its params are free-form JSON, so it gets them as decoded.
175-
if (isset($message->params)) {
165+
if ($message instanceof \stdClass && isset($message->params)) {
176166
$data['params'] = $message->params;
177167
}
178168

‎src/Schema/JsonRpc/Request.php‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,14 @@ public static function fromArray(array $data): static
7272
return $request;
7373
}
7474

75+
/**
76+
* Whether the request cannot be served from params that lost the difference between `{}` and `[]`.
77+
*/
78+
public static function requiresJsonTypes(): bool
79+
{
80+
return false;
81+
}
82+
7583
/**
7684
* @return array<string, mixed>
7785
*/

‎src/Schema/Request/CallToolRequest.php‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,11 @@ public static function getMethod(): string
3737
return 'tools/call';
3838
}
3939

40+
public static function requiresJsonTypes(): bool
41+
{
42+
return true;
43+
}
44+
4045
protected static function paramsToArray(\stdClass $params): array
4146
{
4247
$array = parent::paramsToArray($params);

‎tests/Unit/JsonRpc/MessageFactoryTest.php‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,55 @@ public function testMalformedJsonAfterAMemberNameStartingWithNulIsAParseError():
8080
$this->factory->create('{"id":1,"\u0000x":1,}');
8181
}
8282

83+
/**
84+
* @param class-string $expected
85+
*/
86+
#[DataProvider('provideMessagesWithAMemberNameStartingWithNul')]
87+
public function testMemberNameStartingWithNulKeepsTheMessage(string $json, string $expected): void
88+
{
89+
$this->assertInstanceOf($expected, $this->factory->create($json));
90+
}
91+
92+
/**
93+
* @return iterable<string, array{string, class-string}>
94+
*/
95+
public static function provideMessagesWithAMemberNameStartingWithNul(): iterable
96+
{
97+
yield 'request' => ['{"jsonrpc":"2.0","id":1,"method":"ping","params":{"_meta":{"\u0000x":1}}}', PingRequest::class];
98+
yield 'notification' => ['{"jsonrpc":"2.0","method":"notifications/initialized","params":{"_meta":{"\u0000x":1}}}', InitializedNotification::class];
99+
yield 'response' => ['{"jsonrpc":"2.0","id":1,"result":{"content":{"\u0000x":1}}}', Response::class];
100+
yield 'error' => ['{"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"m","data":{"\u0000x":1}}}', Error::class];
101+
}
102+
103+
public function testMemberNameStartingWithNulRefusesAToolCall(): void
104+
{
105+
try {
106+
$this->factory->create('{"jsonrpc":"2.0","id":7,"method":"tools/call","params":{"name":"t","arguments":{"a":{"\u0000x":1}}}}');
107+
} catch (InvalidInputMessageException $e) {
108+
$this->assertSame(7, $e->getRequestId());
109+
110+
return;
111+
}
112+
113+
$this->fail('The tool call should have been refused.');
114+
}
115+
116+
public function testBatchWithAMemberNameStartingWithNulIsRejected(): void
117+
{
118+
$this->expectException(InvalidInputMessageException::class);
119+
$this->expectExceptionMessage('must be a single JSON object');
120+
121+
$this->factory->create(' [{"jsonrpc":"2.0","id":1,"method":"ping","params":{"_meta":{"\u0000x":1}}}]');
122+
}
123+
124+
public function testAnObjectWithNumericKeysAndAMemberNameStartingWithNulIsNotABatch(): void
125+
{
126+
$this->expectException(InvalidInputMessageException::class);
127+
$this->expectExceptionMessage('missing "method"');
128+
129+
$this->factory->create('{"0":{"\u0000x":1}}');
130+
}
131+
83132
public function testAnObjectWithNumericKeysIsNotABatch(): void
84133
{
85134
$this->expectException(InvalidInputMessageException::class);

‎tests/Unit/Server/Transport/StdioDualEraTest.php‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,28 @@ public static function nonObjectArguments(): iterable
199199
yield 'null' => ['null'];
200200
}
201201

202+
public function testMemberNameStartingWithANulByteKeepsOtherRequests(): void
203+
{
204+
$params = ['_probe' => ["\0x" => 1]];
205+
$openings = [
206+
'handshake' => [
207+
self::initialize(1),
208+
['jsonrpc' => '2.0', 'method' => 'notifications/initialized'],
209+
['jsonrpc' => '2.0', 'id' => 2, 'method' => 'tools/list', 'params' => $params],
210+
],
211+
'modern' => [self::modern(2, 'tools/list', $params)],
212+
];
213+
214+
foreach ($openings as $messages) {
215+
$lines = $this->exchange(self::builder(), $messages);
216+
217+
$answer = $lines[\count($lines) - 1];
218+
219+
$this->assertSame(2, $answer['id']);
220+
$this->assertArrayHasKey('tools', $answer['result']);
221+
}
222+
}
223+
202224
public function testMemberNameStartingWithANulByteIsRefused(): void
203225
{
204226
$params = ['name' => 'echo', 'arguments' => ["\0text" => 'hi']];

0 commit comments

Comments
 (0)