Skip to content

Commit 4ded5c4

Browse files
committed
[Server] Keep JSON types of tool call arguments
1 parent 9604e0e commit 4ded5c4

27 files changed

Lines changed: 601 additions & 129 deletions

‎CHANGELOG.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,11 @@ All notable changes to `mcp/sdk` will be documented in this file.
4242
* Fix a handler still running after its request was answered, e.g. without a fiber scheduler: it no longer fires `ResponseEvent` or `ErrorEvent`, what it throws is logged, and calling the `ClientGateway` throws.
4343
* [BC Break] Bind handshake-era sessions to the principal that opened them: `AccessToken::getPrincipal()`, or the `StreamableHttpTransport::PRINCIPAL_ATTRIBUTE` request attribute when set. Requests of another principal, and to sessions opened before the upgrade, are answered with `404`, and to a session the store cannot read with `503`. `Protocol::processInput()`, the transports' `handleMessage()`, `handleSessionEnd()`, `handlePostRequest()` and `handleDeleteRequest()`, and the `onMessage()` and `onSessionEnd()` listeners take a `?string $principal` as last argument.
4444
* [BC Break] Answer malformed JSON and an `initialize` sent with a session id with HTTP `400`, and a failure before the session is checked with `500`, instead of `200`. Such an answer no longer carries, or removes, the messages queued for the session in `Mcp-Session-Id`.
45+
* [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`.
46+
* [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`.
47+
* [BC Break] Reject `tools/call` when `arguments` is not a JSON object with `-32600`, including `"arguments": []`.
48+
* [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.
49+
* [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.
4550

4651
### Client
4752

‎docs/servers/schemas.md‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,37 @@ and `validation_errors` contains all of them.
184184
The SDK also validates structured tool output against the tool's `outputSchema`, see
185185
[Output validation](tools.md#output-validation).
186186

187+
## Object and Array Arguments
188+
189+
The type of a parameter decides how your method receives a JSON object:
190+
191+
```php
192+
#[McpTool]
193+
public function searchOrders(
194+
array $filters, // JSON objects arrive as arrays, at every level
195+
\stdClass $options, // JSON objects arrive as \stdClass, JSON arrays as lists
196+
mixed $metadata, // same as \stdClass; also applies to an untyped parameter
197+
): array
198+
{
199+
// ...
200+
}
201+
```
202+
203+
The `array` type has no distinction between `{}` and `[]`, because both arrive as an empty array. Use `\stdClass` or
204+
`object` if your method needs to tell them apart. The `execute()` method of `ToolHandlerInterface` receives the arguments
205+
as an array, and the nested values follow the same rule as a `\stdClass` parameter.
206+
207+
The docblock decides which JSON type the client can send to an `array` parameter:
208+
209+
```php
210+
/**
211+
* @param array<string, int> $stock a JSON object
212+
* @param string[] $labels a JSON array
213+
* @param array<int, string> $names a JSON array or a JSON object
214+
* @param array $values a JSON array
215+
*/
216+
```
217+
187218
## Customizing the Generator and Validator
188219

189220
The SDK validates with [opis/json-schema](https://opis.io/json-schema/). To configure it, for example to resolve

‎src/Capability/Discovery/SchemaGenerator.php‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -308,6 +308,12 @@ private function buildInferredParameterSchema(array $paramInfo): array
308308
// Add default value only if parameter actually has a default
309309
if ($paramInfo['has_default']) {
310310
$paramSchema['default'] = $paramInfo['default_value'];
311+
312+
// An empty PHP array encodes as `[]`, which a client could not send back to an object-only parameter.
313+
$types = (array) ($paramSchema['type'] ?? []);
314+
if ([] === $paramSchema['default'] && \in_array('object', $types, true) && !\in_array('array', $types, true)) {
315+
$paramSchema['default'] = new \stdClass();
316+
}
311317
}
312318

313319
// Handle enums
@@ -805,8 +811,8 @@ private function mapPhpTypeToJsonSchemaType(string $phpTypeString): array
805811
return $pseudoTypes;
806812
}
807813

808-
// A non-empty map with string keys is a JSON object; it cannot be the `[]` that an empty `{}` decodes to.
809-
if (preg_match('/^non-empty-array\s*</', $normalizedType)) {
814+
// The key type of a generic array decides between a JSON array and a JSON object.
815+
if (preg_match('/^(?:non-empty-)?array\s*<.*>$/s', $normalizedType)) {
810816
return (array) $this->mapTypeToSchema($normalizedType)['type'];
811817
}
812818

‎src/Capability/Registry/ReferenceHandler.php‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
use Mcp\Exception\InvalidArgumentException;
1515
use Mcp\Exception\RegistryException;
16+
use Mcp\JsonRpc\Json;
1617
use Mcp\Server\Session\SessionInterface;
1718
use Psr\Container\ContainerInterface;
1819

@@ -205,6 +206,10 @@ private function castArgumentType(mixed $argument, \ReflectionParameter $paramet
205206
}
206207
}
207208

209+
if ($type instanceof \ReflectionUnionType) {
210+
return self::acceptsOnlyArrays($type) ? Json::objectsToArrays($argument) : $argument;
211+
}
212+
208213
if (!$type instanceof \ReflectionNamedType) {
209214
return $argument;
210215
}
@@ -242,14 +247,24 @@ private function castArgumentType(mixed $argument, \ReflectionParameter $paramet
242247
'string' => (string) $argument,
243248
'bool', 'boolean' => $this->castToBoolean($argument),
244249
'float', 'double' => $this->castToFloat($argument),
245-
'array' => $this->castToArray($argument),
250+
'array', 'iterable' => $this->castToArray($argument),
246251
default => $argument,
247252
};
248253
} catch (\TypeError $e) {
249254
throw new InvalidArgumentException("Value cannot be cast to required type `{$typeName}`.", 0, $e);
250255
}
251256
}
252257

258+
private static function acceptsOnlyArrays(\ReflectionUnionType $type): bool
259+
{
260+
$names = array_map(
261+
static fn (\ReflectionType $branch): string => $branch instanceof \ReflectionNamedType ? strtolower($branch->getName()) : '',
262+
$type->getTypes(),
263+
);
264+
265+
return [] !== array_intersect($names, ['array', 'iterable']) && [] === array_intersect($names, ['object', 'stdclass']);
266+
}
267+
253268
/**
254269
* Helper to cast strictly to boolean.
255270
*/
@@ -307,10 +322,12 @@ private function castToFloat(mixed $argument): float
307322
/**
308323
* Helper to cast strictly to array.
309324
*
310-
* @return array<int, mixed>
325+
* @return array<int|string, mixed>
311326
*/
312327
private function castToArray(mixed $argument): array
313328
{
329+
$argument = Json::objectsToArrays($argument);
330+
314331
if (\is_array($argument)) {
315332
return $argument;
316333
}

‎src/JsonRpc/Json.php‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
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\JsonRpc;
13+
14+
/**
15+
* @internal
16+
*
17+
* @author Christopher Hertel <mail@christopher-hertel.de>
18+
*/
19+
final class Json
20+
{
21+
public static function objectsToArrays(mixed $value): mixed
22+
{
23+
if ($value instanceof \stdClass) {
24+
$value = get_object_vars($value);
25+
}
26+
27+
if (!\is_array($value)) {
28+
return $value;
29+
}
30+
31+
foreach ($value as $key => $member) {
32+
$value[$key] = self::objectsToArrays($member);
33+
}
34+
35+
return $value;
36+
}
37+
}

‎src/JsonRpc/MessageFactory.php‎

Lines changed: 37 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -99,33 +99,57 @@ public static function make(array $additional = []): self
9999
*/
100100
public function create(string $input): MessageInterface
101101
{
102-
$data = json_decode($input, true, flags: \JSON_THROW_ON_ERROR);
102+
try {
103+
$data = json_decode($input, false, flags: \JSON_THROW_ON_ERROR);
104+
} catch (\JsonException $e) {
105+
if (\JSON_ERROR_INVALID_PROPERTY_NAME !== $e->getCode()) {
106+
throw $e;
107+
}
108+
109+
throw self::invalidMemberName($input);
110+
}
103111

104-
// json_decode(assoc: true) maps objects and arrays alike to PHP arrays, so {} reads as a list too.
105-
if (!\is_array($data) || array_is_list($data)) {
112+
if (!$data instanceof \stdClass) {
106113
throw new InvalidInputMessageException('A JSON-RPC message must be a single JSON object.');
107114
}
108115

109116
try {
110117
return $this->createMessage($data);
111118
} catch (InvalidInputMessageException $e) {
112-
if (\is_string($data['id'] ?? null) || \is_int($data['id'] ?? null)) {
113-
$e->setRequestId($data['id']);
119+
$id = $data->id ?? null;
120+
if (\is_string($id) || \is_int($id)) {
121+
$e->setRequestId($id);
114122
}
115123

116124
throw $e;
117125
}
118126
}
119127

128+
/**
129+
* Valid JSON, but a PHP object cannot hold a property whose name starts with NUL.
130+
*/
131+
private static function invalidMemberName(string $input): InvalidInputMessageException
132+
{
133+
$exception = new InvalidInputMessageException('A JSON-RPC message must not have a member name starting with a NUL byte.');
134+
$id = json_decode($input, true)['id'] ?? null;
135+
136+
if (\is_string($id) || \is_int($id)) {
137+
$exception->setRequestId($id);
138+
}
139+
140+
return $exception;
141+
}
142+
120143
/**
121144
* Creates a single message object from parsed JSON data.
122145
*
123-
* @param array<string, mixed> $data
124-
*
125146
* @throws InvalidInputMessageException
126147
*/
127-
private function createMessage(array $data): MessageInterface
148+
private function createMessage(\stdClass $message): MessageInterface
128149
{
150+
/** @var array<string, mixed> $data */
151+
$data = Json::objectsToArrays($message);
152+
129153
try {
130154
if (isset($data['error'])) {
131155
return Error::fromArray($data);
@@ -145,6 +169,11 @@ private function createMessage(array $data): MessageInterface
145169

146170
$messageClass = $this->findMessageClassByMethod($data['method']);
147171

172+
// Each message knows which of its params are free-form JSON, so it gets them as decoded.
173+
if (isset($message->params)) {
174+
$data['params'] = $message->params;
175+
}
176+
148177
return $messageClass::fromArray($data);
149178
} catch (InvalidArgumentException $e) {
150179
throw new InvalidInputMessageException($e->getMessage(), 0, $e);

‎src/Schema/JsonRpc/Notification.php‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,13 @@
1212
namespace Mcp\Schema\JsonRpc;
1313

1414
use Mcp\Exception\InvalidArgumentException;
15+
use Mcp\JsonRpc\Json;
1516

1617
/**
1718
* @phpstan-type NotificationData array{
1819
* jsonrpc: string,
1920
* method: string,
20-
* params?: array<string, mixed>|null
21+
* params?: array<string, mixed>|\stdClass|null
2122
* }
2223
*
2324
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
@@ -42,15 +43,15 @@ public static function fromArray(array $data): self
4243
if (!isset($data['method']) || !\is_string($data['method'])) {
4344
throw new InvalidArgumentException('Invalid or missing "method" for Notification.');
4445
}
45-
$params = $data['params'] ?? null;
46+
$params = Json::objectsToArrays($data['params'] ?? null);
4647
if (null !== $params && !\is_array($params)) {
4748
throw new InvalidArgumentException('"params" for Notification must be an array/object or null.');
4849
}
4950

5051
$notification = static::fromParams($params);
5152

52-
if (isset($data['params']['_meta'])) {
53-
$notification->meta = $data['params']['_meta'];
53+
if (isset($params['_meta'])) {
54+
$notification->meta = $params['_meta'];
5455
}
5556

5657
return $notification;

‎src/Schema/JsonRpc/Request.php‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,14 @@
1212
namespace Mcp\Schema\JsonRpc;
1313

1414
use Mcp\Exception\InvalidArgumentException;
15+
use Mcp\JsonRpc\Json;
1516

1617
/**
1718
* @phpstan-type RequestData array{
1819
* jsonrpc: string,
1920
* id: string|int,
2021
* method: string,
21-
* params?: array<string, mixed>,
22+
* params?: array<string, mixed>|\stdClass,
2223
* }
2324
*
2425
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
@@ -49,7 +50,7 @@ public static function fromArray(array $data): static
4950
}
5051
$params = $data['params'] ?? null;
5152
if ($params instanceof \stdClass) {
52-
$params = (array) $params;
53+
$params = static::paramsToArray($params);
5354
}
5455
if (null !== $params && !\is_array($params)) {
5556
throw new InvalidArgumentException('"params" for Request must be an array/object or null.');
@@ -58,8 +59,8 @@ public static function fromArray(array $data): static
5859
$request = static::fromParams($params);
5960
$request->id = $data['id'];
6061

61-
if (isset($data['params']['_meta'])) {
62-
$meta = $data['params']['_meta'];
62+
if (isset($params['_meta'])) {
63+
$meta = $params['_meta'];
6364
if ($meta instanceof \stdClass) {
6465
$meta = (array) $meta;
6566
}
@@ -71,6 +72,15 @@ public static function fromArray(array $data): static
7172
return $request;
7273
}
7374

75+
/**
76+
* @return array<string, mixed>
77+
*/
78+
protected static function paramsToArray(\stdClass $params): array
79+
{
80+
/* @var array<string, mixed> */
81+
return Json::objectsToArrays($params);
82+
}
83+
7484
/**
7585
* @param array<string, mixed>|null $params
7686
*/

‎src/Schema/Request/CallToolRequest.php‎

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,8 @@ final class CallToolRequest extends Request
2323
{
2424
/**
2525
* @param string $name the name of the tool to invoke
26-
* @param array<string, mixed> $arguments the arguments to pass to the tool
26+
* @param array<string, mixed> $arguments the arguments to pass to the tool; when decoded from JSON,
27+
* nested objects are `\stdClass` and nested arrays are lists
2728
*/
2829
public function __construct(
2930
public readonly string $name,
@@ -36,36 +37,44 @@ public static function getMethod(): string
3637
return 'tools/call';
3738
}
3839

40+
protected static function paramsToArray(\stdClass $params): array
41+
{
42+
$array = parent::paramsToArray($params);
43+
44+
// Arguments are free-form JSON validated against a schema, so `{}` and `[]` must stay apart.
45+
if (isset($params->arguments)) {
46+
$array['arguments'] = $params->arguments;
47+
}
48+
49+
return $array;
50+
}
51+
3952
protected static function fromParams(?array $params): static
4053
{
4154
if (!isset($params['name']) || !\is_string($params['name'])) {
4255
throw new InvalidArgumentException('Missing or invalid "name" parameter for tools/call.');
4356
}
4457

45-
$arguments = $params['arguments'] ?? [];
46-
47-
if ($arguments instanceof \stdClass) {
48-
$arguments = (array) $arguments;
49-
}
58+
$arguments = \array_key_exists('arguments', $params) ? $params['arguments'] : new \stdClass();
5059

51-
if (!\is_array($arguments)) {
52-
throw new InvalidArgumentException('Parameter "arguments" must be an array.');
60+
if (\is_array($arguments) && array_is_list($arguments) || !\is_array($arguments) && !$arguments instanceof \stdClass) {
61+
throw new InvalidArgumentException('Parameter "arguments" must be an object.');
5362
}
5463

5564
return new self(
5665
$params['name'],
57-
$arguments,
66+
(array) $arguments,
5867
);
5968
}
6069

6170
/**
62-
* @return array{name: string, arguments: array<string, mixed>|\stdClass}
71+
* @return array{name: string, arguments: \stdClass}
6372
*/
6473
protected function getParams(): array
6574
{
6675
return [
6776
'name' => $this->name,
68-
'arguments' => $this->arguments ?: new \stdClass(),
77+
'arguments' => (object) $this->arguments,
6978
];
7079
}
7180
}

0 commit comments

Comments
 (0)