[Schema][Server] Preserve request id in JSON-RPC error responses instead of fabricating id:"" (#379)

* Preserve request id in JSON-RPC error responses instead of fabricating id:""

When the server received input it could not turn into a valid message, the
error response carried a fabricated empty-string id that was never in the
request, breaking JSON-RPC client correlation.

The id default for the error factories was '' and that default reached the
wire unchanged: unrecoverable parse errors emitted id:"", and for invalid-
but-parseable messages MessageFactory discarded the decoded id so it also
fell back to "".

Now unrecoverable parse errors (-32700) return id: null per JSON-RPC 2.0,
and invalid-but-parseable requests (-32600) preserve the original request
id. Error::$id / getId() and the $id parameter of forParseError() /
forInvalidRequest() are widened to string|int|null, and the recoverable id
is threaded through InvalidInputMessageException.

Fixes #333

* Preserve nullable request id consistently across Error factories and fromArray

- Widen the remaining for*() factories (forMethodNotFound, forInvalidParams,
  forInternalError, forServerError, forResourceNotFound) to string|int|null
  defaulting to null, so no error path can fabricate id:"" again. The only
  defaulting call site (ProtocolVersionMiddleware) now emits id:null instead
  of id:"" for a pre-parse rejection, which is the spec-correct value.
- Accept a null id in Error::fromArray(): require the id key to be present
  (JSON-RPC responses must carry it) but allow its value to be null, so a
  spec-compliant id:null error response round-trips and incoming error
  responses with id:null are accepted instead of rejected.
- Widen the @phpstan-type ErrorData id to string|int|null to match the ctor,
  getId(), and jsonSerialize() shape.

* Document intentional id recovery guard in MessageFactory

* Cover id: 0 and string ids in recoverable-id preservation test

* Fixed client handling of null-id error responses
This commit is contained in:
Valeriu Gutu 2026-08-18 16:47:27 +03:00 • committed by GitHub
commit 1961414432
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 130 additions and 2 deletions

View file

@ -112,6 +112,20 @@ final class ProtocolTest extends TestCase
$this->assertCount(1, $logger->warnings);
}
#[TestDox('stores an error response under its id so the pending request can be correlated')]
public function testErrorResponseWithIdIsStoredForItsPendingRequest(): void
{
$protocol = new Protocol();
$protocol->processMessage('{"jsonrpc": "2.0", "id": 7, "error": {"code": -32601, "message": "Method not found"}}');
$response = $protocol->getState()->consumeResponse(7);
$this->assertInstanceOf(Error::class, $response);
$this->assertSame(7, $response->getId());
$this->assertSame(Error::METHOD_NOT_FOUND, $response->code);
}
private function createConfiguration(ProtocolVersion $protocolVersion): Configuration
{
return new Configuration(

View file

@ -29,6 +29,7 @@ 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\DataProvider;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
@ -323,6 +324,40 @@ final class ProtocolTest extends TestCase
);
}
#[TestDox('Unrecoverable parse error does not fabricate an empty-string id')]
public function testParseErrorDoesNotFabricateEmptyStringId(): void
{
$sentPayload = null;
$this->transport->expects($this->once())
->method('send')
->willReturnCallback(static function ($data) use (&$sentPayload) {
$sentPayload = $data;
});
$protocol = new Protocol(
requestHandlers: [],
notificationHandlers: [],
messageFactory: MessageFactory::make(),
sessionManager: $this->sessionManager,
);
// Well-formed JSON nested past PHP's json_decode() depth limit (512), mirroring
// issue #333: json_decode() throws "Maximum stack depth exceeded" so the request
// carries a real numeric id (900512) that cannot be recovered once decoding fails.
$deeplyNested = str_repeat('[', 600).str_repeat(']', 600);
$input = '{"jsonrpc":"2.0","id":900512,"method":"initialize","params":'.$deeplyNested.'}';
$protocol->processInput($this->transport, $input, null);
$this->assertNotNull($sentPayload);
$decoded = json_decode($sentPayload, true);
$this->assertSame(Error::PARSE_ERROR, $decoded['error']['code']);
// The original id is genuinely unrecoverable after a parse failure: it must never be
// fabricated as an empty string, and — per the MCP `RequestId` schema, which never
// allows `null` — the key must be omitted rather than sent as `id: null`.
$this->assertArrayNotHasKey('id', $decoded, 'Unrecoverable parse error must omit id, not fabricate one');
}
#[TestDox('Invalid message structure returns error')]
public function testInvalidMessageStructureReturnsError(): void
{
@ -530,6 +565,66 @@ final class ProtocolTest extends TestCase
$this->assertSame([], $protocol->consumeOutgoingMessages($sessionId));
}
/**
* @return iterable<string, array{string, string|int}>
*/
public static function recoverableIdProvider(): iterable
{
yield 'positive int' => ['{"jsonrpc": "2.0", "id": 42, "params": {}}', 42];
yield 'zero int (truthiness trap)' => ['{"jsonrpc": "2.0", "id": 0, "params": {}}', 0];
yield 'string id' => ['{"jsonrpc": "2.0", "id": "req-1", "params": {}}', 'req-1'];
}
#[DataProvider('recoverableIdProvider')]
#[TestDox('Invalid but parseable message preserves its recoverable id')]
public function testInvalidMessagePreservesRecoverableId(string $input, string|int $expectedId): void
{
$session = $this->createMock(SessionInterface::class);
$this->sessionManager->method('createWithId')->willReturn($session);
$this->sessionManager->method('exists')->willReturn(true);
// Configure session mock for queue operations (mirrors testInvalidMessageStructureReturnsError).
$queue = [];
$session->method('get')->willReturnCallback(static function ($key, $default = null) use (&$queue) {
if ('_mcp.outgoing_queue' === $key) {
return $queue;
}
return $default;
});
$session->method('set')->willReturnCallback(static function ($key, $value) use (&$queue) {
if ('_mcp.outgoing_queue' === $key) {
$queue = $value;
}
});
$protocol = new Protocol(
requestHandlers: [],
notificationHandlers: [],
messageFactory: MessageFactory::make(),
sessionManager: $this->sessionManager,
);
$sessionId = Uuid::v4();
// Valid JSON carrying a real id but missing method/result/error: the message is
// structurally invalid, yet its id IS recoverable from the decoded payload.
$protocol->processInput(
$this->transport,
$input,
$sessionId
);
$outgoing = $protocol->consumeOutgoingMessages($sessionId);
$this->assertCount(1, $outgoing);
$message = json_decode($outgoing[0]['message'], true);
$this->assertArrayHasKey('error', $message);
$this->assertEquals(Error::INVALID_REQUEST, $message['error']['code']);
$this->assertSame($expectedId, $message['id'], 'Invalid-but-parseable message must preserve its recoverable id, not return ""');
}
#[TestDox('Request without handler returns method not found error')]
public function testRequestWithoutHandlerReturnsMethodNotFoundError(): void
{