php-sdk/tests/Unit/Server/Transport/StatelessHttpTransportTest.php
Christopher Hertel 5e73683079
[Server] Close the conformance gaps in the modern lifecycle (#447)
* [Server] Let the client gateway see modern-era capabilities

The six supports*() probes read session state only InitializeHandler wrote,
so every request served statelessly reported no client capabilities at all —
a tool guarding on them took the unsupported branch without a signal.
StatelessProtocol now writes the request's declaration under the same keys.

* [Server] Reject the RPCs 2026-07-28 removed

resources/subscribe and resources/unsubscribe were still dispatched and
answered 200 OK, recording subscriptions the modern era never reads. They
join initialize, ping and logging/setLevel in the era guard; the handlers
stay registered because the handshake era still serves them.

* [Server] Decode a wrapped Mcp-Name before comparing it

The Base64 sentinel was only unwrapped for Mcp-Param-*, so any resource URI
or tool name outside the header-safe ASCII set — which the spec explicitly
tells clients to wrap — was compared encoded and refused with -32020.

* [Server] Require the MCP-Protocol-Version header

It was only checked for contradicting the body, so omitting it entirely
passed — leaving the value intermediaries route on unenforced. Tied to the
header validator's presence, since that is what a header-bearing transport
installs and stdio carries its metadata inline.

* [Server] Read the modern-era request body whole

A single read() takes whatever the stream cares to give — 64 bytes from a
chunked transfer is legal — so an oversized-but-valid POST came back as a
parse error. Shares the legacy transport's incremental read as a trait.

* [Schema][Server] Answer a notification with a status, not a response

A body with no id was dispatched as a request and came back as a JSON-RPC
error carrying "id": "" — an id nobody issued, and on a path a client uses
to tell a modern server from a legacy one. Notifications now get 202 and no
body, and Error omits an id it could not read instead of emptying it.

* [Server] Stop emitting the error codes 2026-07-28 reserved

resources/read answered -32002, which this revision forbids; prompts/get
and completion/complete answered it for an unknown *name*, which it never
meant; tools/call answered -32601, which belongs to an unknown method.
Only the resources/read code is revision-gated — older peers expect -32002
there, and nowhere else. Also routes the -32021 capability exception out of
the prompt and resource handlers, which were swallowing it into -32603.
2026-08-18 23:09:34 +02:00

140 lines
5.1 KiB
PHP

<?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\Server\Transport;
use Mcp\Schema\Enum\ProtocolVersion;
use Mcp\Server;
use Mcp\Server\Stateless\RequestMeta;
use Mcp\Server\Stateless\StatelessProtocol;
use Mcp\Server\Transport\StatelessHttpTransport;
use Mcp\Tests\Unit\Server\Transport\Fixture\ShortReadStream;
use Nyholm\Psr7\Factory\Psr17Factory;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\ServerRequestInterface;
final class StatelessHttpTransportTest extends TestCase
{
private Psr17Factory $factory;
protected function setUp(): void
{
$this->factory = new Psr17Factory();
}
private function protocol(): StatelessProtocol
{
return Server::builder()
->setServerInfo('test-server', '1.0.0')
->addTool(static fn (string $text = ''): string => 'echo:'.$text, name: 'echo_tool', description: 'Echoes its argument')
->buildStateless([ProtocolVersion::V2026_07_28]);
}
/**
* A `tools/call` body padded so it comfortably exceeds one 8 KiB read.
*/
private function callBody(int $padding = 0): string
{
return json_encode([
'jsonrpc' => '2.0',
'id' => 1,
'method' => 'tools/call',
'params' => [
'name' => 'echo_tool',
'arguments' => ['text' => str_repeat('x', $padding)],
'_meta' => [
RequestMeta::PROTOCOL_VERSION => ProtocolVersion::V2026_07_28->value,
RequestMeta::CLIENT_CAPABILITIES => new \stdClass(),
],
],
], \JSON_THROW_ON_ERROR);
}
private function post(string $body): ServerRequestInterface
{
return $this->factory
->createServerRequest('POST', 'http://localhost/mcp')
->withHeader('Host', 'localhost')
->withHeader('MCP-Protocol-Version', ProtocolVersion::V2026_07_28->value)
->withHeader('Mcp-Method', 'tools/call')
->withHeader('Mcp-Name', 'echo_tool')
->withBody($this->factory->createStream($body));
}
#[TestDox('a body arriving in short reads is assembled whole, not truncated')]
public function testShortReadsDoNotTruncateTheBody(): void
{
$body = $this->callBody(20_000);
// PSR-7 promises only *up to* the requested length; a stream over
// php://input or a chunked transfer routinely returns less.
$request = $this->post('')->withBody(new ShortReadStream($body, 64));
$response = (new StatelessHttpTransport($this->protocol(), $this->factory, $this->factory))->handle($request);
$this->assertSame(200, $response->getStatusCode());
$decoded = json_decode((string) $response->getBody(), true, flags: \JSON_THROW_ON_ERROR);
$this->assertSame('echo:'.str_repeat('x', 20_000), $decoded['result']['content'][0]['text']);
}
#[TestDox('a body over the cap is refused with 413')]
public function testOversizedBodyIsRefused(): void
{
$request = $this->post($this->callBody(2048));
$response = (new StatelessHttpTransport($this->protocol(), $this->factory, $this->factory, maxBodyBytes: 256))->handle($request);
$this->assertSame(413, $response->getStatusCode());
}
#[TestDox('an oversized body is refused even when its size is not advertised')]
public function testOversizedUnsizedBodyIsRefused(): void
{
$request = $this->post('')->withBody(new ShortReadStream($this->callBody(2048), 64, advertiseSize: false));
$response = (new StatelessHttpTransport($this->protocol(), $this->factory, $this->factory, maxBodyBytes: 256))->handle($request);
$this->assertSame(413, $response->getStatusCode());
}
#[TestDox('a notification POST is acknowledged with 202 and no body')]
public function testNotificationPostIsAccepted(): void
{
$body = json_encode([
'jsonrpc' => '2.0',
'method' => 'notifications/something',
'params' => [],
], \JSON_THROW_ON_ERROR);
$request = $this->post($body)->withHeader('Mcp-Method', 'notifications/something');
$response = (new StatelessHttpTransport($this->protocol(), $this->factory, $this->factory))->handle($request);
$this->assertSame(202, $response->getStatusCode());
$this->assertSame('', (string) $response->getBody());
}
#[TestDox('GET and DELETE are refused: there is no session to address')]
public function testOnlyPostIsAccepted(): void
{
$transport = new StatelessHttpTransport($this->protocol(), $this->factory, $this->factory);
foreach (['GET', 'DELETE', 'PUT'] as $method) {
$request = $this->factory
->createServerRequest($method, 'http://localhost/mcp')
->withHeader('Host', 'localhost');
$this->assertSame(405, $transport->handle($request)->getStatusCode(), $method);
}
}
}