Skip to content

Commit 0d340e1

Browse files
authored
[Server] Keep JSON types of tool call arguments (#678)
* [Server] Keep JSON types of tool call arguments * [Examples] Show JSON object arguments in complex-tool-schema * [Examples] Send an object carrying data in the complex-tool-schema interop case * [Server] Set empty object defaults after schema merges and keep parse errors * [Capability] Keep a Traversable passed to an iterable parameter * [Server] Refuse only tools/call on member names starting with NUL
1 parent 9604e0e commit 0d340e1

32 files changed

Lines changed: 824 additions & 136 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 `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.
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/examples.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ npx @modelcontextprotocol/inspector php examples/server/discovery-calculator/ser
2525
| [`combined-registration`](https://github.com/modelcontextprotocol/php-sdk/tree/main/examples/server/combined-registration) | Discovery and manual registration combined, and which wins on conflict | [Registering elements](servers/registration.md) |
2626
| [`cached-discovery`](https://github.com/modelcontextprotocol/php-sdk/tree/main/examples/server/cached-discovery) | Caching the discovery scan in a PSR-16 cache | [Server builder](run/server-builder.md#discovery-configuration) |
2727
| [`custom-dependencies`](https://github.com/modelcontextprotocol/php-sdk/tree/main/examples/server/custom-dependencies) | Handlers pulling services from a PSR-11 container | [Server builder](run/server-builder.md#service-dependencies) |
28-
| [`complex-tool-schema`](https://github.com/modelcontextprotocol/php-sdk/tree/main/examples/server/complex-tool-schema) | Rich input schemas from typed parameters, PHP enums and defaults | [Schema generation](servers/schemas.md) |
28+
| [`complex-tool-schema`](https://github.com/modelcontextprotocol/php-sdk/tree/main/examples/server/complex-tool-schema) | Rich input schemas from typed parameters, PHP enums, defaults and JSON objects | [Schema generation](servers/schemas.md) |
2929
| [`schema-showcase`](https://github.com/modelcontextprotocol/php-sdk/tree/main/examples/server/schema-showcase) | `#[Schema]` constraint attributes: formats, patterns, ranges | [Schema generation](servers/schemas.md) |
3030
| [`env-variables`](https://github.com/modelcontextprotocol/php-sdk/tree/main/examples/server/env-variables) | Configuring a server through environment variables | [Server builder](run/server-builder.md) |
3131
| [`client-communication`](https://github.com/modelcontextprotocol/php-sdk/tree/main/examples/server/client-communication) | Sampling, roots, progress and log messages from inside a handler | [Talking back to the client](handlers/client-communication.md) |

‎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

‎examples/server/complex-tool-schema/McpEventScheduler.php‎

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -27,13 +27,15 @@ public function __construct(
2727
* Schedules a new event.
2828
* The inputSchema for this tool will reflect all parameter types and defaults.
2929
*
30-
* @param string $title the title of the event
31-
* @param string $date the date of the event (YYYY-MM-DD)
32-
* @param EventType $type the type of event
33-
* @param string|null $time the time of the event (HH:MM), optional
34-
* @param EventPriority $priority The priority of the event. Defaults to Normal.
35-
* @param string[]|null $attendees an optional list of attendee email addresses
36-
* @param bool $sendInvites send calendar invites to attendees? Defaults to true if attendees are provided
30+
* @param string $title the title of the event
31+
* @param string $date the date of the event (YYYY-MM-DD)
32+
* @param EventType $type the type of event
33+
* @param string|null $time the time of the event (HH:MM), optional
34+
* @param EventPriority $priority The priority of the event. Defaults to Normal.
35+
* @param string[]|null $attendees an optional list of attendee email addresses
36+
* @param bool $sendInvites send calendar invites to attendees? Defaults to true if attendees are provided
37+
* @param array<string, string> $labels labels of the event by name
38+
* @param \stdClass|null $metadata free-form data stored with the event, exactly as sent
3739
*
3840
* @return array<string, mixed> confirmation of the scheduled event
3941
*/
@@ -46,6 +48,8 @@ public function scheduleEvent(
4648
EventPriority $priority = EventPriority::Normal,
4749
?array $attendees = null,
4850
bool $sendInvites = true,
51+
array $labels = [],
52+
?\stdClass $metadata = null,
4953
): array {
5054
$this->logger->info("Tool 'schedule_event' called", compact('title', 'date', 'type', 'time', 'priority', 'attendees', 'sendInvites'));
5155

@@ -60,6 +64,14 @@ public function scheduleEvent(
6064
'invites_will_be_sent' => ($attendees && $sendInvites),
6165
];
6266

67+
if ([] !== $labels) {
68+
$eventDetails['labels'] = $labels;
69+
}
70+
71+
if (null !== $metadata) {
72+
$eventDetails['metadata'] = $metadata;
73+
}
74+
6375
// In a real app, this would interact with a calendar service
6476
$this->logger->info('Event scheduled', ['details' => $eventDetails]);
6577

‎src/Capability/Discovery/SchemaGenerator.php‎

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -247,7 +247,25 @@ private function buildParameterSchema(array $paramInfo, ?array $methodLevelParam
247247
// Run after all merges so that when a Schema attribute reshapes the parameter
248248
// (e.g. to `object`), the array `items` invariant is only enforced on what is
249249
// genuinely still an array.
250-
return $this->ensureArrayItems($mergedSchema);
250+
return $this->ensureObjectDefault($this->ensureArrayItems($mergedSchema));
251+
}
252+
253+
/**
254+
* An empty PHP array encodes as `[]`, which a client could not send back to an object-only parameter.
255+
*
256+
* @param array<string, mixed> $schema
257+
*
258+
* @return array<string, mixed>
259+
*/
260+
private function ensureObjectDefault(array $schema): array
261+
{
262+
$types = (array) ($schema['type'] ?? []);
263+
264+
if ([] === ($schema['default'] ?? null) && \in_array('object', $types, true) && !\in_array('array', $types, true)) {
265+
$schema['default'] = new \stdClass();
266+
}
267+
268+
return $schema;
251269
}
252270

253271
/**
@@ -805,8 +823,8 @@ private function mapPhpTypeToJsonSchemaType(string $phpTypeString): array
805823
return $pseudoTypes;
806824
}
807825

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)) {
826+
// The key type of a generic array decides between a JSON array and a JSON object.
827+
if (preg_match('/^(?:non-empty-)?array\s*<.*>$/s', $normalizedType)) {
810828
return (array) $this->mapTypeToSchema($normalizedType)['type'];
811829
}
812830

‎src/Capability/Registry/ReferenceHandler.php‎

Lines changed: 19 additions & 1 deletion
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
}
@@ -243,13 +248,24 @@ private function castArgumentType(mixed $argument, \ReflectionParameter $paramet
243248
'bool', 'boolean' => $this->castToBoolean($argument),
244249
'float', 'double' => $this->castToFloat($argument),
245250
'array' => $this->castToArray($argument),
251+
'iterable' => $argument instanceof \Traversable ? $argument : $this->castToArray($argument),
246252
default => $argument,
247253
};
248254
} catch (\TypeError $e) {
249255
throw new InvalidArgumentException("Value cannot be cast to required type `{$typeName}`.", 0, $e);
250256
}
251257
}
252258

259+
private static function acceptsOnlyArrays(\ReflectionUnionType $type): bool
260+
{
261+
$names = array_map(
262+
static fn (\ReflectionType $branch): string => $branch instanceof \ReflectionNamedType ? strtolower($branch->getName()) : '',
263+
$type->getTypes(),
264+
);
265+
266+
return [] !== array_intersect($names, ['array', 'iterable']) && [] === array_intersect($names, ['object', 'stdclass']);
267+
}
268+
253269
/**
254270
* Helper to cast strictly to boolean.
255271
*/
@@ -307,10 +323,12 @@ private function castToFloat(mixed $argument): float
307323
/**
308324
* Helper to cast strictly to array.
309325
*
310-
* @return array<int, mixed>
326+
* @return array<int|string, mixed>
311327
*/
312328
private function castToArray(mixed $argument): array
313329
{
330+
$argument = Json::objectsToArrays($argument);
331+
314332
if (\is_array($argument)) {
315333
return $argument;
316334
}

‎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: 28 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -99,18 +99,27 @@ 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+
}
103108

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)) {
109+
// A PHP object cannot hold a property whose name starts with NUL.
110+
$data = json_decode($input, true, flags: \JSON_THROW_ON_ERROR);
111+
}
112+
113+
if (!$data instanceof \stdClass && (!\is_array($data) || str_starts_with(ltrim($input), '['))) {
106114
throw new InvalidInputMessageException('A JSON-RPC message must be a single JSON object.');
107115
}
108116

109117
try {
110118
return $this->createMessage($data);
111119
} catch (InvalidInputMessageException $e) {
112-
if (\is_string($data['id'] ?? null) || \is_int($data['id'] ?? null)) {
113-
$e->setRequestId($data['id']);
120+
$id = ((array) $data)['id'] ?? null;
121+
if (\is_string($id) || \is_int($id)) {
122+
$e->setRequestId($id);
114123
}
115124

116125
throw $e;
@@ -120,12 +129,15 @@ public function create(string $input): MessageInterface
120129
/**
121130
* Creates a single message object from parsed JSON data.
122131
*
123-
* @param array<string, mixed> $data
132+
* @param \stdClass|array<string, mixed> $message
124133
*
125134
* @throws InvalidInputMessageException
126135
*/
127-
private function createMessage(array $data): MessageInterface
136+
private function createMessage(\stdClass|array $message): MessageInterface
128137
{
138+
/** @var array<string, mixed> $data */
139+
$data = Json::objectsToArrays($message);
140+
129141
try {
130142
if (isset($data['error'])) {
131143
return Error::fromArray($data);
@@ -145,6 +157,15 @@ private function createMessage(array $data): MessageInterface
145157

146158
$messageClass = $this->findMessageClassByMethod($data['method']);
147159

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+
164+
// Each message knows which of its params are free-form JSON, so it gets them as decoded.
165+
if ($message instanceof \stdClass && isset($message->params)) {
166+
$data['params'] = $message->params;
167+
}
168+
148169
return $messageClass::fromArray($data);
149170
} catch (InvalidArgumentException $e) {
150171
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;

0 commit comments

Comments
 (0)