php-sdk/tests/Unit/Client/ProtocolTest.php
Christopher Hertel eb20453f49
[Client][Schema][Server] Implement protocol version negotiation (#403)
* [Client][Docs][Schema][Server] Implement protocol version negotiation

The `initialize` handler never looked at the version the client asked for:
it always answered with the server's configured version (or the SDK default),
so a client offering a revision the server supports could still be told to
speak a different one. The spec requires echoing back a supported request and
only counter-offering when the requested version cannot be honoured.

Turns ProtocolVersion into the registry the other SDKs converged on
(typescript-sdk's protocolEras.ts, python-sdk's mcp_types/version.py):
`latestHandshake()`, `handshakeVersions()`, `modernVersions()` and ordered
comparison through `isAtLeast()`. Comparison goes through declaration order
rather than string collation, so an unrecognized peer string compares
conservatively instead of accidentally sorting above a known revision. The
one throw the enum can produce is the SDK's own LogicException, so a consumer
catching `Mcp\Exception\ExceptionInterface` does not miss it.

Adds 2026-07-28 as a known revision and splits the set into two eras:
handshake (2025-11-25 and earlier, negotiated via `initialize`) and modern
(2026-07-28+, per-request `_meta`). The lists are kept apart so a modern
revision can never leak into an `initialize` exchange, which has no
`initialize` at all. Serving the modern era is follow-up work; this only
teaches the SDK that the revision exists and must not be mis-negotiated.
Deliberately absent is any "newest revision in any era" accessor, which
would hand back the one revision the handshake must never offer.

Server: negotiates and stores the result on the session. A version pinned in
Configuration still pins the handshake to exactly that revision.
Client: validates the counter-offer and fails the handshake instead of
continuing on a revision it cannot speak; records the negotiated version on
the client state, readable through the new Client::getProtocolVersion().

The HTTP middleware now defaults to the handshake versions rather than every
declared case, so it stops accepting a modern version the server cannot yet
serve. When the header is absent it falls back to
ProtocolVersion::DEFAULT_NEGOTIATED_VERSION (2025-03-26), the revision that
introduced both Streamable HTTP and the header itself.

The negotiation behaviour is one provideNegotiationTable() data provider
whose rows are the documented table -- supported revision echoed back,
unknown or malformed counter-offered, modern counter-offered -- so the docs
and the suite cannot drift apart. The supported-revision rows iterate
handshakeVersions() rather than a literal list, so declaring a new handshake
revision extends the table automatically, and the "never answer with a modern
revision" assertion runs on every row.

Documented in server-builder.md (the enum registry, how the server answers a
handshake, what pinning changes), transports.md (the header check) and
client.md (the client's side), all linking the spec's versioning section.

* [Client][Docs][Schema][Server] Warn when the configured protocol version cannot be negotiated

* Log a warning instead of silently falling back when a modern revision is
  configured on the client or pinned on the server builder.
* Document that setProtocolVersion() does not restrict the MCP-Protocol-Version
  header check, which validates against a fixed set.
* Pin every revision's era in a test, so a new case declared past the modern
  boundary fails instead of dropping out of the handshake set.
* Add CHANGELOG entry.

* [Client][Docs][Schema][Server] Rename version fallback constant and trim comments
2026-08-15 01:41:19 +02:00

202 lines
6.6 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\Client;
use Mcp\Client\Configuration;
use Mcp\Client\Protocol;
use Mcp\Client\State\ClientStateInterface;
use Mcp\Client\Transport\TransportInterface;
use Mcp\Exception\LogicException;
use Mcp\Schema\ClientCapabilities;
use Mcp\Schema\Enum\ProtocolVersion;
use Mcp\Schema\Implementation;
use Mcp\Schema\JsonRpc\Error;
use Mcp\Schema\JsonRpc\MessageInterface;
use Mcp\Schema\JsonRpc\Response;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase;
use Psr\Log\AbstractLogger;
use Psr\Log\LogLevel;
final class ProtocolTest extends TestCase
{
#[TestDox('offers the configured protocol version in the handshake')]
public function testOffersConfiguredVersion(): void
{
$transport = new RecordingTransport(ProtocolVersion::V2025_06_18->value);
$protocol = new Protocol();
$protocol->connect($transport, $config = $this->createConfiguration(ProtocolVersion::V2025_06_18));
$protocol->initialize($config);
$this->assertSame(ProtocolVersion::V2025_06_18->value, $transport->offeredVersion);
}
#[TestDox('never offers a modern version over the initialize handshake, and warns about it')]
public function testDoesNotOfferModernVersionOverHandshake(): void
{
$transport = new RecordingTransport(ProtocolVersion::latestHandshake()->value);
$protocol = new Protocol(logger: $logger = new CollectingLogger());
$protocol->connect($transport, $config = $this->createConfiguration(ProtocolVersion::V2026_07_28));
$protocol->initialize($config);
$this->assertSame(ProtocolVersion::latestHandshake()->value, $transport->offeredVersion);
$this->assertSame([[
'configured' => ProtocolVersion::V2026_07_28->value,
'offered' => ProtocolVersion::latestHandshake()->value,
]], $logger->warnings);
}
#[TestDox('accepts a counter-offer the SDK can speak and records it as negotiated')]
public function testAcceptsHandshakeCounterOffer(): void
{
$transport = new RecordingTransport(ProtocolVersion::V2024_11_05->value);
$protocol = new Protocol();
$protocol->connect($transport, $config = $this->createConfiguration(ProtocolVersion::V2025_11_25));
$result = $protocol->initialize($config);
$this->assertInstanceOf(Response::class, $result);
$this->assertSame(ProtocolVersion::V2024_11_05, $protocol->getState()->getProtocolVersion());
$this->assertTrue($protocol->getState()->isInitialized());
}
#[TestDox('fails the handshake when the server answers with a version the SDK cannot speak')]
#[DataProvider('provideUnusableCounterOffers')]
public function testRejectsUnusableCounterOffer(string $counterOffer): void
{
$transport = new RecordingTransport($counterOffer);
$protocol = new Protocol();
$protocol->connect($transport, $config = $this->createConfiguration(ProtocolVersion::V2025_11_25));
$result = $protocol->initialize($config);
$this->assertInstanceOf(Error::class, $result);
$this->assertStringContainsString($counterOffer, $result->message);
$this->assertNull($protocol->getState()->getProtocolVersion());
$this->assertFalse($protocol->getState()->isInitialized());
}
/**
* @return iterable<string, array{string}>
*/
public static function provideUnusableCounterOffers(): iterable
{
yield 'unknown revision' => ['2099-01-01'];
// The modern era has no `initialize`, so a server answering the handshake
// with one has produced a connection neither side can actually use.
yield 'modern revision' => [ProtocolVersion::V2026_07_28->value];
}
private function createConfiguration(ProtocolVersion $protocolVersion): Configuration
{
return new Configuration(
clientInfo: new Implementation('client-app', '1.0.0'),
capabilities: new ClientCapabilities(),
protocolVersion: $protocolVersion,
);
}
}
/**
* Transport that answers the `initialize` request inline with a canned
* `protocolVersion`, so the handshake resolves without a Fiber round-trip.
*/
final class RecordingTransport implements TransportInterface
{
public ?string $offeredVersion = null;
private ClientStateInterface $state;
public function __construct(private readonly string $counterOffer)
{
}
public function send(string $data): void
{
/** @var array{id: int|string, method: string, params?: array{protocolVersion?: string}} $message */
$message = json_decode($data, true);
if ('initialize' !== ($message['method'] ?? null)) {
return;
}
$this->offeredVersion = $message['params']['protocolVersion'] ?? null;
$this->state->storeResponse($message['id'], [
'jsonrpc' => MessageInterface::JSONRPC_VERSION,
'id' => $message['id'],
'result' => [
'protocolVersion' => $this->counterOffer,
'capabilities' => [],
'serverInfo' => ['name' => 'server', 'version' => '1.2.3'],
],
]);
}
public function setState(ClientStateInterface $state): void
{
$this->state = $state;
}
public function connect(): void
{
}
public function close(): void
{
}
public function runRequest(\Fiber $fiber, ?callable $onProgress = null): Response|Error
{
throw new LogicException('Not used in these tests.');
}
public function onInitialize(callable $callback): void
{
}
public function onMessage(callable $callback): void
{
}
public function onError(callable $callback): void
{
}
public function onClose(callable $callback): void
{
}
}
/**
* Logger that keeps the context of every warning, so a silent fallback can be
* told apart from one the caller was told about.
*/
final class CollectingLogger extends AbstractLogger
{
/** @var list<array<string, mixed>> */
public array $warnings = [];
/**
* @param string|\Stringable $message
* @param array<string, mixed> $context
*/
public function log($level, $message, array $context = []): void
{
if (LogLevel::WARNING === $level) {
$this->warnings[] = $context;
}
}
}