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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ All notable changes to `mcp/sdk` will be documented in this file.
### Server

* Fix const validation errors always reporting the expected value as null.
* [BC Break] Answer invalid `tools/call` arguments with a tool result marked `isError` instead of `-32602`, from revision `2025-11-25` on (SEP-1303): arguments that fail the tool's input schema, that cannot be cast to their parameter type, or that are missing. The text is the message the error carried; sessions up to `2025-06-18` keep `-32602`, as do prompts and resources on every revision. Adds `ProtocolVersion::reportsInvalidToolArgumentsAsToolError()`.

0.10.0
------
Expand Down
3 changes: 3 additions & 0 deletions docs/protocol-versions.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,9 @@ The same tool, resource and prompt registrations serve both eras. What changes:
* **[Structured output](servers/tools.md#structured-output)**: from `2026-07-28`, a tool can
send any JSON value as `structuredContent` ([SEP-2106](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/2106)).
Before it, only a JSON object.
* **[Argument validation](servers/schemas.md#argument-validation)**: from `2025-11-25`, arguments a tool's input
schema refuses come back as a tool result marked `isError` ([SEP-1303](https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1303)).
Before it, as a `-32602` error.
* **[Serving both eras](run/protocol-eras.md)** — what a modern request carries, how one
endpoint classifies and routes each request, and how to serve one era only.
* **[Caching](run/caching.md)** — the `ttlMs` / `cacheScope` hints a cacheable result must
Expand Down
31 changes: 26 additions & 5 deletions docs/servers/schemas.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,28 @@ public function getForecast(
## Argument Validation

Before a `tools/call` reaches your method, the SDK validates the arguments against the tool's input schema. If they
don't match, your method is not called and the client gets a JSON-RPC error with code `-32602`:
don't match, your method is not called. What the client gets depends on the negotiated protocol revision.

From `2025-11-25` on, the specification counts an input validation error as a tool execution error, so the answer is a
result with `isError: true`. The client hands it to the model, which can read what was wrong and call the tool again:

```json
{
"jsonrpc": "2.0",
"id": 3,
"result": {
"content": [
{
"type": "text",
"text": "Invalid parameters for tool 'validateUser': Property '/age': Number must be greater than or equal to 18."
}
],
"isError": true
}
}
```

Up to `2025-06-18`, invalid arguments are a protocol error, and the client gets a JSON-RPC error with code `-32602`:

```json
{
Expand All @@ -189,10 +210,10 @@ don't match, your method is not called and the client gets a JSON-RPC error with
}
```

By default, the validator stops at the first error. So the message and `validation_errors` hold one error. If you
configure the validator to report more errors, see
[Customizing the Generator and Validator](#customizing-the-generator-and-validator), the message lists the first three
and `validation_errors` contains all of them.
By default, the validator stops at the first error. So the message holds one error, and so does `validation_errors`
in the protocol error. If you configure the validator to report more errors, see
[Customizing the Generator and Validator](#customizing-the-generator-and-validator), the message lists the first three.
`validation_errors` contains all of them; the tool result has no such field, and the full list goes to the debug log.

After this check, the SDK casts each argument to the type of its parameter. Prompts and resource templates have no input
schema, so this is the only check for them. If a value can't be cast, your method is not called and the client gets a
Expand Down
16 changes: 16 additions & 0 deletions src/Schema/Enum/ProtocolVersion.php
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,22 @@ public function usesInvalidParamsForResourceNotFound(): bool
return $this->isAtLeast(self::V2026_07_28);
}

/**
* Whether this revision answers invalid tool arguments with a tool error.
*
* SEP-1303, part of {@see self::V2025_11_25}, moved input validation errors
* from protocol errors to tool execution errors, reported in the result
* with `isError: true`, so that the model reads what was wrong and can
* retry with adjusted arguments. Earlier revisions list "Invalid arguments"
* under protocol errors, answered with `-32602`.
*
* @see https://modelcontextprotocol.io/specification/2025-11-25/server/tools#error-handling
*/
public function reportsInvalidToolArgumentsAsToolError(): bool
{
return $this->isAtLeast(self::V2025_11_25);
}

/**
* Whether this revision resumes an interrupted SSE stream with `Last-Event-ID`.
*
Expand Down
17 changes: 15 additions & 2 deletions src/Server/Handler/Request/CallToolHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,11 +82,22 @@ public function handle(Request $request, SessionInterface $session): Response|Er
return Error::forInvalidParams($e->getMessage(), $request->getId());
}

$context = new RequestContext($session, $request);

$inputSchema = $reference->tool->inputSchema;
$validationErrors = $this->schemaValidator->validateAgainstJsonSchema((object) $arguments, $inputSchema);
if (!empty($validationErrors)) {
$summaryMessage = "Invalid parameters for tool '{$toolName}': ".self::summarizeValidationErrors($validationErrors);

$this->logger->debug('Tool arguments do not match the input schema', [
'name' => $toolName,
'validation_errors' => $validationErrors,
]);

if ($context->getProtocolVersion()->reportsInvalidToolArgumentsAsToolError()) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

SEP-1303 lists "value out of range" as a tool execution error too, but the RegistryException::isInvalidParams() catch below (cast failure, missing argument) still answers -32602. So {"qty": 0} gets isError and {"qty": 9300000000000000000} doesn't. Can we put it under the same predicate in this PR? I'd rather have the BC break once.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Done, tools only: cast failures and missing arguments are under the same predicate. Prompts and resources keep -32602.

return new Response($request->getId(), CallToolResult::error([new TextContent($summaryMessage)]));
}

return Error::forInvalidParams($summaryMessage, $request->getId(), ['validation_errors' => $validationErrors]);
}

Expand All @@ -95,8 +106,6 @@ public function handle(Request $request, SessionInterface $session): Response|Er
$arguments['_session'] = $session;
$arguments['_request'] = $request;

$context = new RequestContext($session, $request);

try {
$result = $this->referenceHandler->handle($reference, $arguments);

Expand Down Expand Up @@ -165,6 +174,10 @@ public function handle(Request $request, SessionInterface $session): Response|Er
if ($e instanceof RegistryException && $e->isInvalidParams()) {
$this->logger->warning('Invalid arguments for tool', ['name' => $toolName, 'exception' => $e]);

if ($context->getProtocolVersion()->reportsInvalidToolArgumentsAsToolError()) {
return new Response($request->getId(), CallToolResult::error([new TextContent($e->getMessage())]));
}

return Error::forInvalidParams($e->getMessage(), $request->getId());
}

Expand Down
8 changes: 4 additions & 4 deletions tests/Integration/IntArgumentTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,17 +46,17 @@ public function testToolCallOutOfRangeIsAnsweredWithInvalidParams(ProtocolVersio
{
$client = $this->connectOn($era);

$this->assertInvalidParams(static fn () => $client->callTool($tool, $arguments));
$this->assertTrue($client->callTool($tool, $arguments)->isError);
}

#[DataProvider('provideEras')]
public function testToolCallThatIsNotAnIntegerIsAnsweredWithInvalidParams(ProtocolVersion $era): void
{
$client = $this->connectOn($era);

$this->assertInvalidParams(static fn () => $client->callTool('permissive', ['qty' => 'abc']));
$this->assertInvalidParams(static fn () => $client->callTool('permissive', ['qty' => 1.5]));
$this->assertInvalidParams(static fn () => $client->callTool('permissive', ['qty' => '99999999999999999999']));
$this->assertTrue($client->callTool('permissive', ['qty' => 'abc'])->isError);
$this->assertTrue($client->callTool('permissive', ['qty' => 1.5])->isError);
$this->assertTrue($client->callTool('permissive', ['qty' => '99999999999999999999'])->isError);
}

#[DataProvider('provideEras')]
Expand Down
14 changes: 14 additions & 0 deletions tests/Unit/Schema/Enum/ProtocolVersionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,20 @@ public function testUsesInvalidParamsForResourceNotFound(): void
$this->assertTrue(ProtocolVersion::V2026_07_28->usesInvalidParamsForResourceNotFound());
}

#[TestDox('2025-11-25 moves input validation errors from protocol errors to tool execution errors')]
public function testReportsInvalidToolArgumentsAsToolError(): void
{
foreach ([ProtocolVersion::V2024_11_05, ProtocolVersion::V2025_03_26, ProtocolVersion::V2025_06_18] as $version) {
$this->assertFalse(
$version->reportsInvalidToolArgumentsAsToolError(),
\sprintf('%s still lists invalid arguments under protocol errors.', $version->value),
);
}

$this->assertTrue(ProtocolVersion::V2025_11_25->reportsInvalidToolArgumentsAsToolError());
$this->assertTrue(ProtocolVersion::V2026_07_28->reportsInvalidToolArgumentsAsToolError());
}

#[TestDox('SEP-2575 removes SSE stream resumption')]
public function testSupportsSseResumption(): void
{
Expand Down
109 changes: 79 additions & 30 deletions tests/Unit/Server/Handler/Request/CallToolHandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
use Mcp\Server\Exception\ToolNotFoundException;
use Mcp\Server\Handler\Request\CallToolHandler;
use Mcp\Server\Session\SessionInterface;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Psr\Log\AbstractLogger;
Expand Down Expand Up @@ -333,15 +334,15 @@ public function testToolNotFoundIsLoggedAsCalledButNotAsExecuted(): void
{
$this->registry->method('getTool')->willThrowException(new ToolNotFoundException('unknown'));

$this->assertCalledButNotExecuted($this->createCallToolRequest('unknown', []));
$this->assertCalledButNotExecuted($this->createCallToolRequest('unknown', []), Error::class);
}

public function testInvalidArgumentsAreLoggedAsCalledButNotAsExecuted(): void
{
$toolReference = $this->createToolReference('strict', static fn () => 'unused');
$this->registry->method('getTool')->willReturn($toolReference);

$this->assertCalledButNotExecuted($this->createCallToolRequest('strict', ['example' => 123]));
$this->assertCalledButNotExecuted($this->createCallToolRequest('strict', ['example' => 123]), Response::class);
}

public function testHandleWithNullResult(): void
Expand Down Expand Up @@ -458,9 +459,28 @@ public function testHandleGenericExceptionReturnsError(): void
$this->assertEquals('Error while executing tool', $response->message);
}

public function testHandleAnswersInvalidParamsFromReferenceHandlerWithInvalidParams(): void
#[DataProvider('provideRevisionsReportingRefusedArgumentsAsToolErrors')]
public function testArgumentsTheReferenceHandlerRefusesAreReportedAsAToolError(?string $negotiated): void
{
$request = $this->createCallToolRequest('order', ['qty' => 'abc']);
$this->session->method('get')->with('protocol_version')->willReturn($negotiated);
$this->registry->method('getTool')->willReturn($this->createToolReference('order', static fn () => null));
$this->referenceHandler->method('handle')->willThrowException(RegistryException::invalidParams('Cannot cast value to integer.'));

$response = $this->handler->handle($request, $this->session);

$this->assertInstanceOf(Response::class, $response);
$this->assertEquals($request->getId(), $response->id);
$this->assertInstanceOf(CallToolResult::class, $response->result);
$this->assertTrue($response->result->isError);
$this->assertSame('Cannot cast value to integer.', $this->firstText($response->result));
}

#[DataProvider('provideRevisionsReportingRefusedArgumentsAsProtocolErrors')]
public function testHandleAnswersInvalidParamsFromReferenceHandlerWithInvalidParams(string $negotiated): void
{
$request = $this->createCallToolRequest('order', ['qty' => 'abc']);
$this->session->method('get')->with('protocol_version')->willReturn($negotiated);
$this->registry->method('getTool')->willReturn($this->createToolReference('order', static fn () => null));
$this->referenceHandler->method('handle')->willThrowException(RegistryException::invalidParams('Cannot cast value to integer.'));

Expand Down Expand Up @@ -805,41 +825,67 @@ public function testDeclaredOutputSchemaWithoutStructuredContentIsLogged(): void
$this->assertNull($response->result->structuredContent);
}

public function testValidationError(): void
#[DataProvider('provideRevisionsReportingRefusedArgumentsAsToolErrors')]
public function testArgumentsRefusedByTheInputSchemaAreReportedAsAToolError(?string $negotiated): void
{
$schema = [
'type' => 'object',
'properties' => [
'favorite_number' => [
'type' => 'number',
'description' => 'Your favorite number',
],
],
'required' => [
'favorite_number',
],
];
$request = $this->createCallToolRequest('strict', ['example' => 123]);
$toolReference = $this->createToolReference('strict', static fn () => 'unused');

$request = $this->createCallToolRequest('result_tool', ['query' => 'php']);
$toolReference = $this->getMockBuilder(ToolReference::class)
->setConstructorArgs([new Tool('simple_tool', null, $schema, null, null), static function () {}])
->getMock();
$this->session->method('get')->with('protocol_version')->willReturn($negotiated);
$this->registry->method('getTool')->willReturn($toolReference);
$this->referenceHandler->expects($this->never())->method('handle');

$this->registry
->expects($this->once())
->method('getTool')
->with('result_tool')
->willReturn($toolReference);
$response = $this->handler->handle($request, $this->session);

$this->referenceHandler
->expects($this->never())
->method('handle');
$this->assertInstanceOf(Response::class, $response);
$this->assertEquals($request->getId(), $response->id);
$this->assertInstanceOf(CallToolResult::class, $response->result);
$this->assertTrue($response->result->isError);
$this->assertFalse($response->result->hasStructuredContent());
$this->assertSame(
"Invalid parameters for tool 'strict': Property '/example': Invalid type. Expected `string`, but received `integer`.",
$this->firstText($response->result),
);
}

/**
* @return iterable<string, array{?string}>
*/
public static function provideRevisionsReportingRefusedArgumentsAsToolErrors(): iterable
{
yield '2025-11-25' => ['2025-11-25'];
yield '2026-07-28' => ['2026-07-28'];
yield 'no revision negotiated' => [null];
}

#[DataProvider('provideRevisionsReportingRefusedArgumentsAsProtocolErrors')]
public function testValidationError(string $negotiated): void
{
$request = $this->createCallToolRequest('strict', ['example' => 123]);
$toolReference = $this->createToolReference('strict', static fn () => 'unused');

$this->session->method('get')->with('protocol_version')->willReturn($negotiated);
$this->registry->method('getTool')->willReturn($toolReference);
$this->referenceHandler->expects($this->never())->method('handle');

$response = $this->handler->handle($request, $this->session);

$this->assertInstanceOf(Error::class, $response);
$this->assertEquals($request->getId(), $response->id);
$this->assertEquals(Error::INVALID_PARAMS, $response->code);
$this->assertSame("Invalid parameters for tool 'strict': Property '/example': Invalid type. Expected `string`, but received `integer`.", $response->message);
$this->assertIsArray($response->data);
$this->assertArrayHasKey('validation_errors', $response->data);
}

/**
* @return iterable<string, array{string}>
*/
public static function provideRevisionsReportingRefusedArgumentsAsProtocolErrors(): iterable
{
yield '2024-11-05' => ['2024-11-05'];
yield '2025-03-26' => ['2025-03-26'];
yield '2025-06-18' => ['2025-06-18'];
}

public function testStructuredContentMissingARequiredPropertyIsReportedAsAToolError(): void
Expand Down Expand Up @@ -1087,7 +1133,10 @@ private function createCallToolRequest(string $name, array $arguments): CallTool
]);
}

private function assertCalledButNotExecuted(CallToolRequest $request): void
/**
* @param class-string $answer
*/
private function assertCalledButNotExecuted(CallToolRequest $request, string $answer): void
{
$logger = new class extends AbstractLogger {
public array $records = [];
Expand All @@ -1102,7 +1151,7 @@ public function log($level, $message, array $context = []): void

$this->referenceHandler->expects($this->never())->method('handle');

$this->assertInstanceOf(Error::class, $handler->handle($request, $this->session));
$this->assertInstanceOf($answer, $handler->handle($request, $this->session));

$messages = array_column($logger->records, 'message');
$this->assertContains('Calling tool', $messages);
Expand Down
6 changes: 4 additions & 2 deletions tests/Unit/Server/Transport/StdioDualEraTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,8 @@ public function testToolArgumentsKeepTheirJsonType(string $type, string $json, b
if ($accepted) {
$this->assertSame(json_encode(json_decode($json)->value), $answer['result']['content'][0]['text']);
} else {
$this->assertSame(Error::INVALID_PARAMS, $answer['error']['code']);
$this->assertTrue($answer['result']['isError']);
$this->assertStringStartsWith("Invalid parameters for tool 'typed': ", $answer['result']['content'][0]['text']);
}
}
}
Expand Down Expand Up @@ -139,7 +140,8 @@ public function testSchemaKeywordsSeeTheJsonType(array $valueSchema, string $jso
if ($accepted) {
$this->assertSame(json_encode(json_decode($json)->value), $answer['result']['content'][0]['text']);
} else {
$this->assertSame(Error::INVALID_PARAMS, $answer['error']['code']);
$this->assertTrue($answer['result']['isError']);
$this->assertStringStartsWith("Invalid parameters for tool 'typed': ", $answer['result']['content'][0]['text']);
}
}
}
Expand Down