Skip to content
Merged
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ All notable changes to `mcp/sdk` will be documented in this file.
* Reject a recognized `Mcp-Param-*` header whose mirrored argument is absent from the body with `-32020`, instead of accepting the request (SEP-2243).
* Fix `JwtTokenValidator` with several issuers always fetching the keys of the first one: keys now come from the issuer the token claims, which must be configured.
* Fix `RequestEvent`, `ResponseEvent` and `ErrorEvent` not being dispatched for `2026-07-28` requests.
* [BC Break] Validate a tool result's `structuredContent` against the tool's `outputSchema`, which the specification requires the server to honour. A mismatch is answered with a `CallToolResult` carrying `isError: true` instead of the non-conforming value, matching the TypeScript, Python and Java SDKs. Skipped when the tool declares no `outputSchema`, when the result carries no `structuredContent`, and when the result is already an error.

0.8.0
-----
Expand Down
26 changes: 26 additions & 0 deletions docs/servers/tools.md
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,32 @@ Either way the data reaches the client: a return value with no structured repres
A tool that wants to branch on the revision itself can read it from the injected `RequestContext`, see
[Talking back to the client](../handlers/client-communication.md#clientgateway).

#### Output validation

The specification states that a server **must** produce structured results that conform to the declared schema. The SDK
holds you to it: when a tool declares an `outputSchema` and the result carries `structuredContent`, the SDK validates
that value against the schema before sending it. A mismatch becomes a tool error result, so the model reads the reason
and can retry:

```json
{
"content": [
{
"type": "text",
"text": "Invalid structured output for tool 'get_weather': Missing required properties: `temperature`."
}
],
"isError": true
}
```

The check applies to a `CallToolResult` you build yourself as well as to one the SDK wraps for you. It is skipped in
three cases:

- The tool declares no `outputSchema`.
- The result carries no `structuredContent`, which is the warning case described above.
- The result is already marked `isError: true`, because its content is a failure message and not the declared output.

[sep-2106]: https://modelcontextprotocol.io/specification/2026-07-28/server/tools#structured-content

### Error Handling
Expand Down
4 changes: 0 additions & 4 deletions src/Capability/Discovery/SchemaValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,6 @@ public function __construct(
*/
public function validateAgainstJsonSchema(mixed $data, array|object $schema): array
{
if (\is_array($data) && empty($data)) {
$data = new \stdClass();
}

try {
// --- Schema Preparation ---
if (\is_array($schema)) {
Expand Down
4 changes: 4 additions & 0 deletions src/Capability/Registry/ToolReference.php
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,10 @@ public function extractStructuredContent(mixed $toolExecutionResult, ?ProtocolVe
return $this->acceptsScalarStructuredContent($objectOnly) ? $decoded : null;
}

if ([] === $decoded && '{}' === $jsonResult) {
return new \stdClass();
}

if ($objectOnly && array_is_list($decoded)) {
return null;
}
Expand Down
75 changes: 59 additions & 16 deletions src/Server/Handler/Request/CallToolHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
use Mcp\Schema\Request\CallToolRequest;
use Mcp\Schema\Result\CallToolResult;
use Mcp\Schema\Result\InputRequiredResult;
use Mcp\Schema\Tool;
use Mcp\Server\RequestContext;
use Mcp\Server\Session\SessionInterface;
use Psr\Log\LoggerInterface;
Expand Down Expand Up @@ -79,20 +80,10 @@ public function handle(Request $request, SessionInterface $session): Response|Er
}

$inputSchema = $reference->tool->inputSchema;
$validationErrors = $this->schemaValidator->validateAgainstJsonSchema($arguments, $inputSchema);
// Arguments are always a JSON object, but an empty one decodes to `[]`.
$validationErrors = $this->schemaValidator->validateAgainstJsonSchema([] === $arguments ? new \stdClass() : $arguments, $inputSchema);
if (!empty($validationErrors)) {
$errorMessages = [];

foreach ($validationErrors as $errorDetail) {
$pointer = $errorDetail['pointer'] ?? '';
$message = $errorDetail['message'] ?? 'Unknown validation error';
$errorMessages[] = ('/' !== $pointer && '' !== $pointer ? "Property '{$pointer}': " : '').$message;
}

$summaryMessage = "Invalid parameters for tool '{$toolName}': ".implode('; ', \array_slice($errorMessages, 0, 3));
if (\count($errorMessages) > 3) {
$summaryMessage .= '; ...and more errors.';
}
$summaryMessage = "Invalid parameters for tool '{$toolName}': ".self::summarizeValidationErrors($validationErrors);

return Error::forInvalidParams($summaryMessage, $request->getId(), ['validation_errors' => $validationErrors]);
}
Expand Down Expand Up @@ -126,7 +117,6 @@ public function handle(Request $request, SessionInterface $session): Response|Er
$result = new CallToolResult($reference->formatResult($result), structuredContent: $structuredContent);
} elseif ($protocolVersion->requiresObjectStructuredContent()
&& null !== $result->structuredContent
&& [] !== $result->structuredContent
&& !self::isJsonObject($result->structuredContent)
) {
// A tool building its own `CallToolResult` bypasses the extraction
Expand All @@ -146,7 +136,7 @@ public function handle(Request $request, SessionInterface $session): Response|Er
'structured_content' => $structuredContent,
]);

return new Response($request->getId(), $result);
return new Response($request->getId(), $this->validateStructuredContent($reference->tool, $result) ?? $result);
} catch (MissingRequiredClientCapabilityException $e) {
// Not a tool failure — the request was unservable, and the client
// needs to retry declaring the capability. Rendered as -32021.
Expand All @@ -171,12 +161,65 @@ public function handle(Request $request, SessionInterface $session): Response|Er
}
}

/**
* A tool declaring an `outputSchema` promises every `structuredContent` it sends
* conforms to it, in every revision. A mismatch is the server's own bug, but it
* is reported as a tool execution error rather than a protocol error so that the
* model sees it and can fall back to `content`.
*
* @return CallToolResult|null the error result to send instead, or null when there is nothing to report
*/
private function validateStructuredContent(Tool $tool, CallToolResult $result): ?CallToolResult
{
// An error result carries a failure message, not the tool's declared output.
// A null `structuredContent` is absent from the wire, and the caller has
// already warned about it.
if (null === $tool->outputSchema || $result->isError || null === $result->structuredContent) {
return null;
}

$validationErrors = $this->schemaValidator->validateAgainstJsonSchema($result->structuredContent, $tool->outputSchema);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

$result->structuredContent could also be an empty list - which is valid as result, but validateAgainstJsonSchema turns that into new \stdClass()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

or does that work against an array schema still 🤔 shouldn't right?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

good catch, the coercion now only applies to arguments (always an object), [] is validated as an array. While at it an empty object result was sent as [] on the wire, it's now kept as {}.

if ([] === $validationErrors) {
return null;
}

$summaryMessage = "Invalid structured output for tool '{$tool->name}': ".self::summarizeValidationErrors($validationErrors);

$this->logger->error($summaryMessage, [
'name' => $tool->name,
'validation_errors' => $validationErrors,
]);

return CallToolResult::error([new TextContent($summaryMessage)]);
}

/**
* @param list<array{pointer: string, keyword: string, message: string}> $validationErrors
*/
private static function summarizeValidationErrors(array $validationErrors): string
{
$errorMessages = [];

foreach ($validationErrors as $errorDetail) {
$pointer = $errorDetail['pointer'] ?? '';
$message = $errorDetail['message'] ?? 'Unknown validation error';
$errorMessages[] = ('/' !== $pointer && '' !== $pointer ? "Property '{$pointer}': " : '').$message;
}

$summary = implode('; ', \array_slice($errorMessages, 0, 3));
if (\count($errorMessages) > 3) {
$summary .= '; ...and more errors.';
}

return $summary;
}

/**
* Whether a `structuredContent` value encodes as a JSON object — the only shape
* revisions predating SEP-2106 accept.
*/
private static function isJsonObject(mixed $value): bool
{
return \is_array($value) && !array_is_list($value);
return $value instanceof \stdClass || (\is_array($value) && !array_is_list($value));
}
}
20 changes: 19 additions & 1 deletion tests/Unit/Capability/Discovery/SchemaValidatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -221,14 +221,32 @@ public function testHandlesInvalidSchemaStructureGracefully(): void
public function testHandlesEmptyDataObjectAgainstSchemaRequiringProperties(): void
{
$schema = $this->getSimpleSchema(); // Requires name, age etc.
$data = []; // Empty data
$data = new \stdClass(); // Empty data

$errors = $this->validator->validateAgainstJsonSchema($data, $schema);

$this->assertNotEmpty($errors);
$this->assertEquals('required', $errors[0]['keyword']);
}

public function testEmptyArrayValidatesAgainstArraySchema(): void
{
$this->assertSame([], $this->validator->validateAgainstJsonSchema([], ['type' => 'array']));
}

public function testEmptyArrayIsNotAnObject(): void
{
$errors = $this->validator->validateAgainstJsonSchema([], ['type' => 'object']);

$this->assertNotEmpty($errors);
$this->assertSame('type', $errors[0]['keyword']);
}

public function testEmptyStdClassValidatesAgainstObjectSchema(): void
{
$this->assertSame([], $this->validator->validateAgainstJsonSchema(new \stdClass(), ['type' => 'object']));
}

public function testHandlesEmptySchemaAllowsAnything(): void
{
$schema = []; // Empty schema object/array implies no constraints
Expand Down
12 changes: 12 additions & 0 deletions tests/Unit/Capability/RegistryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
use Mcp\Schema\Prompt;
use Mcp\Schema\ResourceDefinition;
use Mcp\Schema\ResourceTemplate;
use Mcp\Schema\Result\CallToolResult;
use Mcp\Schema\Tool;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
Expand Down Expand Up @@ -499,6 +500,17 @@ public function testExtractStructuredContentReturnsArrayDirectlyForAdditionalPro
$this->assertEquals(['success' => true, 'message' => 'done'], $toolRef->extractStructuredContent(['success' => true, 'message' => 'done']));
}

public function testExtractStructuredContentKeepsAnEmptyObjectAsAnObject(): void
{
$tool = $this->createValidTool('test_tool', ['type' => 'object']);
$this->registry->registerTool($tool, static fn () => new \stdClass());

$structuredContent = $this->registry->getTool('test_tool')->extractStructuredContent(new \stdClass());

$this->assertInstanceOf(\stdClass::class, $structuredContent);
$this->assertStringContainsString('"structuredContent":{}', json_encode(new CallToolResult([], structuredContent: $structuredContent)));
}

/**
* @dataProvider provideHandshakeVersions
*/
Expand Down
Loading
Loading