[Server] Handle malformed JSON-RPC input graceful (#412)
* Never let a throwable escape Protocol::processInput() * Validate payload types in the schema hydration methods * Stop leaking handler exception messages to the client
This commit is contained in:
parent
9236824b6d
commit
c8ed07bba2
5 changed files with 858 additions and 58 deletions
38
tests/Unit/Fixtures/ThrowingRequest.php
Normal file
38
tests/Unit/Fixtures/ThrowingRequest.php
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the official PHP MCP SDK.
|
||||
*
|
||||
* A collaboration between Symfony and the PHP Foundation.
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Mcp\Tests\Unit\Fixtures;
|
||||
|
||||
use Mcp\Schema\JsonRpc\Request;
|
||||
|
||||
/**
|
||||
* Stands in for a message class that fails with an unexpected throwable instead of a proper
|
||||
* InvalidInputMessageException, e.g. through a PHP TypeError caused by an unvalidated payload.
|
||||
*
|
||||
* @author Christopher Hertel <mail@christopher-hertel.de>
|
||||
*/
|
||||
final class ThrowingRequest extends Request
|
||||
{
|
||||
public static function getMethod(): string
|
||||
{
|
||||
return 'test/throwing';
|
||||
}
|
||||
|
||||
protected static function fromParams(?array $params): static
|
||||
{
|
||||
throw new \TypeError('Internal detail that must not leak to the client.');
|
||||
}
|
||||
|
||||
protected function getParams(): ?array
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
83
tests/Unit/JsonRpc/MalformedInputTest.php
Normal file
83
tests/Unit/JsonRpc/MalformedInputTest.php
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the official PHP MCP SDK.
|
||||
*
|
||||
* A collaboration between Symfony and the PHP Foundation.
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Mcp\Tests\Unit\JsonRpc;
|
||||
|
||||
use Mcp\Exception\InvalidInputMessageException;
|
||||
use Mcp\JsonRpc\MessageFactory;
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use PHPUnit\Framework\Attributes\TestDox;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* Type-confused payloads must be reported as invalid input, never as a PHP TypeError, ValueError or
|
||||
* warning. Those escape every catch on the way out of the protocol and kill the server process.
|
||||
*
|
||||
* @author Christopher Hertel <mail@christopher-hertel.de>
|
||||
*/
|
||||
final class MalformedInputTest extends TestCase
|
||||
{
|
||||
/**
|
||||
* @return iterable<string, array{string}>
|
||||
*/
|
||||
public static function provideMalformedPayloads(): iterable
|
||||
{
|
||||
yield 'method is an object' => ['{"jsonrpc":"2.0","id":1,"method":{"evil":true}}'];
|
||||
yield 'method is an array' => ['{"jsonrpc":"2.0","id":1,"method":[1,2,3]}'];
|
||||
|
||||
yield 'initialize with array protocolVersion' => ['{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":[1],"capabilities":{},"clientInfo":{"name":"x","version":"1"}}}'];
|
||||
yield 'initialize with string capabilities' => ['{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":"x","clientInfo":{"name":"x","version":"1"}}}'];
|
||||
yield 'initialize with string clientInfo' => ['{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":"x"}}'];
|
||||
yield 'initialize with non-array icons entry' => ['{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"x","version":"1","icons":["x"]}}}'];
|
||||
|
||||
yield 'completion ref/prompt with array name' => ['{"jsonrpc":"2.0","id":1,"method":"completion/complete","params":{"ref":{"type":"ref/prompt","name":[1]},"argument":{"name":"x","value":"y"}}}'];
|
||||
yield 'completion ref/prompt without name' => ['{"jsonrpc":"2.0","id":1,"method":"completion/complete","params":{"ref":{"type":"ref/prompt"},"argument":{"name":"x","value":"y"}}}'];
|
||||
yield 'completion ref/resource with object uri' => ['{"jsonrpc":"2.0","id":1,"method":"completion/complete","params":{"ref":{"type":"ref/resource","uri":{}},"argument":{"name":"x","value":"y"}}}'];
|
||||
|
||||
yield 'setLevel with unknown enum value' => ['{"jsonrpc":"2.0","id":1,"method":"logging/setLevel","params":{"level":"not-a-real-level"}}'];
|
||||
yield 'logging notification with unknown enum value' => ['{"jsonrpc":"2.0","method":"notifications/message","params":{"level":"nope","data":"x"}}'];
|
||||
|
||||
yield 'tools/list with array cursor' => ['{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{"cursor":[1]}}'];
|
||||
yield 'cancelled notification with array reason' => ['{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":1,"reason":[1]}}'];
|
||||
yield 'progress notification with array total' => ['{"jsonrpc":"2.0","method":"notifications/progress","params":{"progressToken":"t","progress":1,"total":[1]}}'];
|
||||
|
||||
yield 'sampling with string preferences' => ['{"jsonrpc":"2.0","id":1,"method":"sampling/createMessage","params":{"messages":[],"maxTokens":1,"preferences":"x"}}'];
|
||||
yield 'sampling with array systemPrompt' => ['{"jsonrpc":"2.0","id":1,"method":"sampling/createMessage","params":{"messages":[],"maxTokens":1,"systemPrompt":[1]}}'];
|
||||
yield 'sampling with unknown role' => ['{"jsonrpc":"2.0","id":1,"method":"sampling/createMessage","params":{"messages":[{"role":"nope","content":{"type":"text","text":"x"}}],"maxTokens":1}}'];
|
||||
yield 'sampling with array content type' => ['{"jsonrpc":"2.0","id":1,"method":"sampling/createMessage","params":{"messages":[{"role":"user","content":{"type":[1],"text":"x"}}],"maxTokens":1}}'];
|
||||
yield 'sampling with non-string stopSequence' => ['{"jsonrpc":"2.0","id":1,"method":"sampling/createMessage","params":{"messages":[],"maxTokens":1,"stopSequences":[[]]}}'];
|
||||
|
||||
yield 'elicitation with string required' => ['{"jsonrpc":"2.0","id":1,"method":"elicitation/create","params":{"message":"m","requestedSchema":{"type":"object","properties":{"a":{"type":"string","title":"T"}},"required":"a"}}}'];
|
||||
yield 'elicitation with array in required' => ['{"jsonrpc":"2.0","id":1,"method":"elicitation/create","params":{"message":"m","requestedSchema":{"type":"object","properties":{"a":{"type":"string","title":"T"}},"required":[[]]}}}'];
|
||||
}
|
||||
|
||||
#[DataProvider('provideMalformedPayloads')]
|
||||
#[TestDox('Malformed payload is reported as invalid input: $_dataName')]
|
||||
public function testMalformedPayloadIsReportedAsInvalidInput(string $payload): void
|
||||
{
|
||||
$results = MessageFactory::make()->create($payload);
|
||||
|
||||
$this->assertCount(1, $results);
|
||||
$this->assertInstanceOf(InvalidInputMessageException::class, $results[0]);
|
||||
}
|
||||
|
||||
#[TestDox('A malformed message in a batch does not discard the valid ones')]
|
||||
public function testMalformedMessageInBatchDoesNotDiscardValidMessages(): void
|
||||
{
|
||||
$payload = '[{"jsonrpc":"2.0","id":1,"method":"tools/list"},{"jsonrpc":"2.0","id":2,"method":{}}]';
|
||||
|
||||
$results = MessageFactory::make()->create($payload);
|
||||
|
||||
$this->assertCount(2, $results);
|
||||
$this->assertInstanceOf(\Mcp\Schema\Request\ListToolsRequest::class, $results[0]);
|
||||
$this->assertInstanceOf(InvalidInputMessageException::class, $results[1]);
|
||||
}
|
||||
}
|
||||
|
|
@ -21,6 +21,7 @@ use Mcp\Schema\Notification\InitializedNotification;
|
|||
use Mcp\Schema\Request\ElicitRequest;
|
||||
use Mcp\Schema\Request\GetPromptRequest;
|
||||
use Mcp\Schema\Request\PingRequest;
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
final class MessageFactoryTest extends TestCase
|
||||
|
|
@ -452,6 +453,41 @@ final class MessageFactoryTest extends TestCase
|
|||
$this->assertInstanceOf(InvalidInputMessageException::class, $results[1]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return iterable<string, array{string}>
|
||||
*/
|
||||
public static function provideNonStringMethods(): iterable
|
||||
{
|
||||
yield 'object' => ['{"evil": true}'];
|
||||
yield 'array' => ['[1, 2, 3]'];
|
||||
yield 'int' => ['5'];
|
||||
yield 'bool' => ['true'];
|
||||
}
|
||||
|
||||
#[DataProvider('provideNonStringMethods')]
|
||||
public function testNonStringMethodIsRejected(string $method): void
|
||||
{
|
||||
$results = $this->factory->create(\sprintf('{"jsonrpc": "2.0", "id": 1, "method": %s}', $method));
|
||||
|
||||
$this->assertCount(1, $results);
|
||||
$this->assertInstanceOf(InvalidInputMessageException::class, $results[0]);
|
||||
$this->assertStringContainsString('"method" must be a string', $results[0]->getMessage());
|
||||
}
|
||||
|
||||
public function testBatchWithNonStringMethodStillYieldsTheValidMessages(): void
|
||||
{
|
||||
$json = '[
|
||||
{"jsonrpc": "2.0", "method": "ping", "id": 1},
|
||||
{"jsonrpc": "2.0", "method": {}, "id": 2}
|
||||
]';
|
||||
|
||||
$results = $this->factory->create($json);
|
||||
|
||||
$this->assertCount(2, $results);
|
||||
$this->assertInstanceOf(PingRequest::class, $results[0]);
|
||||
$this->assertInstanceOf(InvalidInputMessageException::class, $results[1]);
|
||||
}
|
||||
|
||||
public function testLeadingWhitespaceObjectIsParsedAsSingleMessage(): void
|
||||
{
|
||||
$json = " \n {\"jsonrpc\": \"2.0\", \"method\": \"ping\", \"id\": 1}";
|
||||
|
|
|
|||
|
|
@ -85,7 +85,8 @@ final class ElicitResultTest extends TestCase
|
|||
|
||||
public function testFromArrayWithInvalidAction(): void
|
||||
{
|
||||
$this->expectException(\ValueError::class);
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
$this->expectExceptionMessage('Invalid "action" value "invalid"');
|
||||
|
||||
ElicitResult::fromArray(['action' => 'invalid']);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,12 +21,14 @@ use Mcp\Schema\JsonRpc\Error;
|
|||
use Mcp\Schema\JsonRpc\Response;
|
||||
use Mcp\Schema\Notification\LoggingMessageNotification;
|
||||
use Mcp\Schema\Request\CallToolRequest;
|
||||
use Mcp\Schema\Request\PingRequest;
|
||||
use Mcp\Server\Handler\Notification\NotificationHandlerInterface;
|
||||
use Mcp\Server\Handler\Request\RequestHandlerInterface;
|
||||
use Mcp\Server\Protocol;
|
||||
use Mcp\Server\Session\SessionInterface;
|
||||
use Mcp\Server\Session\SessionManagerInterface;
|
||||
use Mcp\Server\Transport\TransportInterface;
|
||||
use Mcp\Tests\Unit\Fixtures\ThrowingRequest;
|
||||
use PHPUnit\Framework\Attributes\TestDox;
|
||||
use PHPUnit\Framework\MockObject\MockObject;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
|
@ -349,6 +351,161 @@ final class ProtocolTest extends TestCase
|
|||
$this->assertEquals(Error::INVALID_REQUEST, $message['error']['code']);
|
||||
}
|
||||
|
||||
#[TestDox('An unexpected throwable while creating a message returns an internal error under its id')]
|
||||
public function testUnexpectedThrowableWhileCreatingMessagesReturnsInternalError(): void
|
||||
{
|
||||
$sent = null;
|
||||
$this->transport->expects($this->once())
|
||||
->method('send')
|
||||
->willReturnCallback(static function ($data) use (&$sent) {
|
||||
$sent = $data;
|
||||
});
|
||||
|
||||
$protocol = new Protocol(
|
||||
requestHandlers: [],
|
||||
notificationHandlers: [],
|
||||
messageFactory: new MessageFactory([ThrowingRequest::class]),
|
||||
sessionManager: $this->sessionManager,
|
||||
);
|
||||
|
||||
$protocol->processInput(
|
||||
$this->transport,
|
||||
'{"jsonrpc": "2.0", "id": 1, "method": "test/throwing"}',
|
||||
Uuid::v4()
|
||||
);
|
||||
|
||||
$decoded = json_decode((string) $sent, true);
|
||||
$this->assertSame(Error::INTERNAL_ERROR, $decoded['error']['code']);
|
||||
$this->assertSame(1, $decoded['id'], 'The peer must be able to correlate the failure with its request.');
|
||||
$this->assertStringNotContainsString('must not leak', $decoded['error']['message']);
|
||||
}
|
||||
|
||||
#[TestDox('A batch that fails to hydrate is answered once, under the empty id')]
|
||||
public function testBatchThatFailsToHydrateIsAnsweredOnce(): void
|
||||
{
|
||||
$sent = [];
|
||||
$this->transport->method('send')->willReturnCallback(static function ($data) use (&$sent) {
|
||||
$sent[] = $data;
|
||||
});
|
||||
|
||||
$protocol = new Protocol(
|
||||
requestHandlers: [],
|
||||
notificationHandlers: [],
|
||||
messageFactory: new MessageFactory([PingRequest::class, ThrowingRequest::class]),
|
||||
sessionManager: $this->sessionManager,
|
||||
);
|
||||
|
||||
$protocol->processInput(
|
||||
$this->transport,
|
||||
'[{"jsonrpc": "2.0", "id": 1, "method": "ping"}, {"jsonrpc": "2.0", "id": 2, "method": "test/throwing"}]',
|
||||
Uuid::v4()
|
||||
);
|
||||
|
||||
$this->assertCount(1, $sent);
|
||||
|
||||
$decoded = json_decode($sent[0], true);
|
||||
$this->assertSame(Error::INTERNAL_ERROR, $decoded['error']['code']);
|
||||
$this->assertSame('', $decoded['id'], 'The failure cannot be attributed to one request of the batch.');
|
||||
}
|
||||
|
||||
#[TestDox('A batch holding only notifications is not answered when processing fails')]
|
||||
public function testBatchOfNotificationsIsNotAnsweredWhenProcessingFails(): void
|
||||
{
|
||||
$session = $this->createMock(SessionInterface::class);
|
||||
$session->method('save')->willThrowException(new \RuntimeException('storage is gone'));
|
||||
|
||||
$this->sessionManager->method('createWithId')->willReturn($session);
|
||||
$this->sessionManager->method('exists')->willReturn(true);
|
||||
|
||||
$this->transport->expects($this->never())->method('send');
|
||||
|
||||
$protocol = new Protocol(
|
||||
requestHandlers: [],
|
||||
notificationHandlers: [],
|
||||
messageFactory: MessageFactory::make(),
|
||||
sessionManager: $this->sessionManager,
|
||||
);
|
||||
|
||||
$protocol->processInput(
|
||||
$this->transport,
|
||||
'[{"jsonrpc": "2.0", "method": "notifications/initialized"}]',
|
||||
Uuid::v4()
|
||||
);
|
||||
}
|
||||
|
||||
#[TestDox('An unexpected throwable while saving the session does not answer a notification')]
|
||||
public function testUnexpectedThrowableWhileSavingSessionDoesNotEscape(): void
|
||||
{
|
||||
$session = $this->createMock(SessionInterface::class);
|
||||
$session->method('save')->willThrowException(new \RuntimeException('storage is gone'));
|
||||
|
||||
$this->sessionManager->method('createWithId')->willReturn($session);
|
||||
$this->sessionManager->method('exists')->willReturn(true);
|
||||
|
||||
// JSON-RPC forbids answering a notification, so the failure is only logged.
|
||||
$this->transport->expects($this->never())->method('send');
|
||||
|
||||
$protocol = new Protocol(
|
||||
requestHandlers: [],
|
||||
notificationHandlers: [],
|
||||
messageFactory: MessageFactory::make(),
|
||||
sessionManager: $this->sessionManager,
|
||||
);
|
||||
|
||||
$protocol->processInput(
|
||||
$this->transport,
|
||||
'{"jsonrpc": "2.0", "method": "notifications/initialized"}',
|
||||
Uuid::v4()
|
||||
);
|
||||
}
|
||||
|
||||
#[TestDox('A failing notification event listener does not produce a response')]
|
||||
public function testFailingNotificationListenerDoesNotProduceResponse(): void
|
||||
{
|
||||
$session = $this->createMock(SessionInterface::class);
|
||||
|
||||
$this->sessionManager->method('createWithId')->willReturn($session);
|
||||
$this->sessionManager->method('exists')->willReturn(true);
|
||||
|
||||
$queue = [];
|
||||
$session->method('get')->willReturnCallback(static function ($key, $default = null) use (&$queue) {
|
||||
return '_mcp.outgoing_queue' === $key ? $queue : $default;
|
||||
});
|
||||
$session->method('set')->willReturnCallback(static function ($key, $value) use (&$queue) {
|
||||
if ('_mcp.outgoing_queue' === $key) {
|
||||
$queue = $value;
|
||||
}
|
||||
});
|
||||
|
||||
$dispatcher = $this->createMock(EventDispatcherInterface::class);
|
||||
$dispatcher->method('dispatch')->willReturnCallback(static function ($event) {
|
||||
if ($event instanceof NotificationEvent) {
|
||||
throw new \RuntimeException('listener blew up');
|
||||
}
|
||||
|
||||
return $event;
|
||||
});
|
||||
|
||||
$this->transport->expects($this->never())->method('send');
|
||||
|
||||
$protocol = new Protocol(
|
||||
requestHandlers: [],
|
||||
notificationHandlers: [],
|
||||
messageFactory: MessageFactory::make(),
|
||||
sessionManager: $this->sessionManager,
|
||||
eventDispatcher: $dispatcher,
|
||||
);
|
||||
|
||||
$sessionId = Uuid::v4();
|
||||
$protocol->processInput(
|
||||
$this->transport,
|
||||
'{"jsonrpc": "2.0", "method": "notifications/initialized"}',
|
||||
$sessionId
|
||||
);
|
||||
|
||||
$this->assertSame([], $protocol->consumeOutgoingMessages($sessionId));
|
||||
}
|
||||
|
||||
#[TestDox('Request without handler returns method not found error')]
|
||||
public function testRequestWithoutHandlerReturnsMethodNotFoundError(): void
|
||||
{
|
||||
|
|
@ -513,7 +670,8 @@ final class ProtocolTest extends TestCase
|
|||
$message = json_decode($outgoing[0]['message'], true);
|
||||
$this->assertArrayHasKey('error', $message);
|
||||
$this->assertEquals(Error::INTERNAL_ERROR, $message['error']['code']);
|
||||
$this->assertStringContainsString('Unexpected error', $message['error']['message']);
|
||||
$this->assertSame('Internal server error.', $message['error']['message']);
|
||||
$this->assertStringNotContainsString('Unexpected error', $message['error']['message']);
|
||||
}
|
||||
|
||||
#[TestDox('Notification handler exceptions are caught and logged')]
|
||||
|
|
|
|||
Loading…
Reference in a new issue