[Client][Server] Add Roots support (#395)
* [Client][Server] Add Roots support Wire up the MCP "roots" capability on both sides: Client (php-sdk as client): - RootsCallbackInterface + ListRootsRequestHandler answer server roots/list requests, mirroring the Sampling handler. - Client::sendRootsListChanged() emits notifications/roots/list_changed. Server (php-sdk as server): - ClientGateway::listRoots() requests the client's roots, and supportsRoots() reports whether the client advertised the capability, normalizing the stored capabilities to an array so an empty capabilities object (\stdClass) doesn't cause a TypeError. - Add ListRootsResult::fromArray() (used by listRoots()). - ListRootsRequestHandler forwards RootsException messages to the server (new Mcp\Exception\RootsException), mirroring SamplingRequestHandler. - Client::sendRootsListChanged() throws when the client did not advertise the roots.listChanged capability. Examples, docs and tests: - examples/README/docs advertise `new ClientCapabilities(roots: true, rootsListChanged: true)` before sending notifications/roots/list_changed. - CHANGELOG entry for Roots (unreleased 0.7.0 section at the time). - Unit tests for capability serialization/round-trip, sendRootsListChanged gating, and RootsException message forwarding. phpunit, php-cs-fixer and phpstan green. * [Client][Server] Address review: schema validation, changelog section, connection guard, working example Responds to chr-hertel's review of the Roots support: - ListRootsResult::fromArray() rejects non-array root elements instead of accepting malformed entries silently. - CHANGELOG entry moved to the next unreleased section as the release train advanced past it (0.7.0 -> 0.8.0). - Client::sendRootsListChanged() went straight to Protocol::sendNotification(), which sends via `$this->transport?->send()` -- on a client that is not connected the notification was silently dropped. It now throws a ConnectionException like sendRequest() does. - The stdio example only advertised the roots capability, so the roots/list handler never actually ran. The client-communication demo server gets an `inspect_workspace_roots` tool that calls ClientGateway::supportsRoots()/listRoots(); the example calls it, so the server actually issues roots/list and the client answers it. Dropped the try/catch wrapper from the example. - ClientTest's connected-client mock now goes through setState() so isConnected() reflects a real handshake instead of a stubbed flag. phpunit, php-cs-fixer and phpstan green.
This commit is contained in:
parent
8bae3c054e
commit
bdc9d86671
5 changed files with 866 additions and 1 deletions
79
tests/Unit/Client/ClientTest.php
Normal file
79
tests/Unit/Client/ClientTest.php
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
<?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;
|
||||
use Mcp\Client\State\ClientStateInterface;
|
||||
use Mcp\Client\Transport\TransportInterface;
|
||||
use Mcp\Exception\ConnectionException;
|
||||
use Mcp\Exception\RuntimeException;
|
||||
use Mcp\Schema\ClientCapabilities;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
final class ClientTest extends TestCase
|
||||
{
|
||||
public function testSendRootsListChangedSendsNotificationWhenCapabilityDeclared(): void
|
||||
{
|
||||
$sent = [];
|
||||
$transport = $this->createMock(TransportInterface::class);
|
||||
$transport->method('send')->willReturnCallback(static function (string $data) use (&$sent): void {
|
||||
$sent[] = $data;
|
||||
});
|
||||
// Stand in for a completed initialize handshake, which the transport drives.
|
||||
$transport->method('setState')->willReturnCallback(static function (ClientStateInterface $state): void {
|
||||
$state->setInitialized(true);
|
||||
});
|
||||
|
||||
$client = Client::builder()
|
||||
->setClientInfo('Roots Test', '1.0.0')
|
||||
->setCapabilities(new ClientCapabilities(roots: true, rootsListChanged: true))
|
||||
->build();
|
||||
|
||||
$client->connect($transport);
|
||||
$client->sendRootsListChanged();
|
||||
|
||||
$this->assertCount(1, $sent);
|
||||
$decoded = json_decode($sent[0], true);
|
||||
$this->assertSame('notifications/roots/list_changed', $decoded['method']);
|
||||
}
|
||||
|
||||
public function testSendRootsListChangedThrowsWhenCapabilityNotDeclared(): void
|
||||
{
|
||||
$transport = $this->createMock(TransportInterface::class);
|
||||
$transport->expects($this->never())->method('send');
|
||||
|
||||
$client = Client::builder()
|
||||
->setClientInfo('Roots Test', '1.0.0')
|
||||
->setCapabilities(new ClientCapabilities(roots: true))
|
||||
->build();
|
||||
|
||||
$client->connect($transport);
|
||||
|
||||
$this->expectException(RuntimeException::class);
|
||||
$this->expectExceptionMessage('roots.listChanged');
|
||||
|
||||
$client->sendRootsListChanged();
|
||||
}
|
||||
|
||||
public function testSendRootsListChangedThrowsWhenNotConnected(): void
|
||||
{
|
||||
$client = Client::builder()
|
||||
->setClientInfo('Roots Test', '1.0.0')
|
||||
->setCapabilities(new ClientCapabilities(roots: true, rootsListChanged: true))
|
||||
->build();
|
||||
|
||||
$this->expectException(ConnectionException::class);
|
||||
$this->expectExceptionMessage('Client is not connected.');
|
||||
|
||||
$client->sendRootsListChanged();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,105 @@
|
|||
<?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\Handler\Request;
|
||||
|
||||
use Mcp\Client\Handler\Request\ListRootsRequestHandler;
|
||||
use Mcp\Client\Handler\Request\RootsCallbackInterface;
|
||||
use Mcp\Exception\RootsException;
|
||||
use Mcp\Schema\JsonRpc\Error;
|
||||
use Mcp\Schema\JsonRpc\Response;
|
||||
use Mcp\Schema\Request\ListRootsRequest;
|
||||
use Mcp\Schema\Request\PingRequest;
|
||||
use Mcp\Schema\Result\ListRootsResult;
|
||||
use Mcp\Schema\Root;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
final class ListRootsRequestHandlerTest extends TestCase
|
||||
{
|
||||
public function testSupportsListRootsRequest(): void
|
||||
{
|
||||
$handler = new ListRootsRequestHandler($this->createCallback(new ListRootsResult([])));
|
||||
|
||||
$this->assertTrue($handler->supports(new ListRootsRequest()));
|
||||
}
|
||||
|
||||
public function testDoesNotSupportOtherRequests(): void
|
||||
{
|
||||
$handler = new ListRootsRequestHandler($this->createCallback(new ListRootsResult([])));
|
||||
|
||||
$this->assertFalse($handler->supports(new PingRequest()));
|
||||
}
|
||||
|
||||
public function testHandleReturnsRootsFromCallback(): void
|
||||
{
|
||||
$result = new ListRootsResult([
|
||||
new Root('file:///home/user/project', 'project'),
|
||||
new Root('file:///tmp'),
|
||||
]);
|
||||
|
||||
$handler = new ListRootsRequestHandler($this->createCallback($result));
|
||||
|
||||
$request = (new ListRootsRequest())->withId('req-1');
|
||||
$response = $handler->handle($request);
|
||||
|
||||
$this->assertInstanceOf(Response::class, $response);
|
||||
$this->assertSame('req-1', $response->getId());
|
||||
$this->assertSame($result, $response->result);
|
||||
}
|
||||
|
||||
public function testHandleReturnsErrorWhenCallbackThrows(): void
|
||||
{
|
||||
$handler = new ListRootsRequestHandler(new class implements RootsCallbackInterface {
|
||||
public function __invoke(ListRootsRequest $request): ListRootsResult
|
||||
{
|
||||
throw new \RuntimeException('boom');
|
||||
}
|
||||
});
|
||||
|
||||
$request = (new ListRootsRequest())->withId('req-2');
|
||||
$response = $handler->handle($request);
|
||||
|
||||
$this->assertInstanceOf(Error::class, $response);
|
||||
$this->assertSame('req-2', $response->getId());
|
||||
$this->assertSame('Error while listing roots', $response->message);
|
||||
}
|
||||
|
||||
public function testHandleForwardsRootsExceptionMessage(): void
|
||||
{
|
||||
$handler = new ListRootsRequestHandler(new class implements RootsCallbackInterface {
|
||||
public function __invoke(ListRootsRequest $request): ListRootsResult
|
||||
{
|
||||
throw new RootsException('permission denied');
|
||||
}
|
||||
});
|
||||
|
||||
$request = (new ListRootsRequest())->withId('req-3');
|
||||
$response = $handler->handle($request);
|
||||
|
||||
$this->assertInstanceOf(Error::class, $response);
|
||||
$this->assertSame('req-3', $response->getId());
|
||||
$this->assertSame('permission denied', $response->message);
|
||||
}
|
||||
|
||||
private function createCallback(ListRootsResult $result): RootsCallbackInterface
|
||||
{
|
||||
return new class($result) implements RootsCallbackInterface {
|
||||
public function __construct(private readonly ListRootsResult $result)
|
||||
{
|
||||
}
|
||||
|
||||
public function __invoke(ListRootsRequest $request): ListRootsResult
|
||||
{
|
||||
return $this->result;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
71
tests/Unit/Schema/ClientCapabilitiesTest.php
Normal file
71
tests/Unit/Schema/ClientCapabilitiesTest.php
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
<?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\Schema;
|
||||
|
||||
use Mcp\Schema\ClientCapabilities;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
class ClientCapabilitiesTest extends TestCase
|
||||
{
|
||||
public function testSerializesRootsWithoutListChanged(): void
|
||||
{
|
||||
$capabilities = new ClientCapabilities(roots: true);
|
||||
|
||||
$data = json_decode(json_encode($capabilities), true);
|
||||
|
||||
$this->assertArrayHasKey('roots', $data);
|
||||
$this->assertSame([], $data['roots']);
|
||||
}
|
||||
|
||||
public function testSerializesRootsWithListChanged(): void
|
||||
{
|
||||
$capabilities = new ClientCapabilities(roots: true, rootsListChanged: true);
|
||||
|
||||
$data = json_decode(json_encode($capabilities), true);
|
||||
|
||||
$this->assertSame(['listChanged' => true], $data['roots']);
|
||||
}
|
||||
|
||||
public function testSerializesEmptyCapabilitiesAsObject(): void
|
||||
{
|
||||
$capabilities = new ClientCapabilities();
|
||||
|
||||
$this->assertSame('{}', json_encode($capabilities));
|
||||
}
|
||||
|
||||
public function testFromArrayReadsRootsListChanged(): void
|
||||
{
|
||||
$capabilities = ClientCapabilities::fromArray(['roots' => ['listChanged' => true]]);
|
||||
|
||||
$this->assertTrue($capabilities->roots);
|
||||
$this->assertTrue($capabilities->rootsListChanged);
|
||||
}
|
||||
|
||||
public function testFromArrayRootsWithoutListChanged(): void
|
||||
{
|
||||
$capabilities = ClientCapabilities::fromArray(['roots' => []]);
|
||||
|
||||
$this->assertTrue($capabilities->roots);
|
||||
$this->assertNull($capabilities->rootsListChanged);
|
||||
}
|
||||
|
||||
public function testRoundTripPreservesRootsListChanged(): void
|
||||
{
|
||||
$capabilities = new ClientCapabilities(roots: true, rootsListChanged: true);
|
||||
|
||||
$data = json_decode(json_encode($capabilities), true);
|
||||
$restored = ClientCapabilities::fromArray($data);
|
||||
|
||||
$this->assertTrue($restored->roots);
|
||||
$this->assertTrue($restored->rootsListChanged);
|
||||
}
|
||||
}
|
||||
110
tests/Unit/Schema/Result/ListRootsResultTest.php
Normal file
110
tests/Unit/Schema/Result/ListRootsResultTest.php
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
<?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\Schema\Result;
|
||||
|
||||
use Mcp\Exception\InvalidArgumentException;
|
||||
use Mcp\Schema\Result\ListRootsResult;
|
||||
use Mcp\Schema\Root;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
final class ListRootsResultTest extends TestCase
|
||||
{
|
||||
public function testConstructor(): void
|
||||
{
|
||||
$roots = [new Root('file:///home/user/project', 'project')];
|
||||
$result = new ListRootsResult($roots);
|
||||
|
||||
$this->assertSame($roots, $result->roots);
|
||||
$this->assertNull($result->meta);
|
||||
}
|
||||
|
||||
public function testFromArray(): void
|
||||
{
|
||||
$result = ListRootsResult::fromArray([
|
||||
'roots' => [
|
||||
['uri' => 'file:///home/user/project', 'name' => 'project'],
|
||||
['uri' => 'file:///tmp'],
|
||||
],
|
||||
]);
|
||||
|
||||
$this->assertCount(2, $result->roots);
|
||||
$this->assertSame('file:///home/user/project', $result->roots[0]->uri);
|
||||
$this->assertSame('project', $result->roots[0]->name);
|
||||
$this->assertSame('file:///tmp', $result->roots[1]->uri);
|
||||
$this->assertNull($result->roots[1]->name);
|
||||
$this->assertNull($result->meta);
|
||||
}
|
||||
|
||||
public function testFromArrayWithMeta(): void
|
||||
{
|
||||
$result = ListRootsResult::fromArray([
|
||||
'roots' => [['uri' => 'file:///tmp']],
|
||||
'_meta' => ['requestId' => 'abc'],
|
||||
]);
|
||||
|
||||
$this->assertSame(['requestId' => 'abc'], $result->meta);
|
||||
}
|
||||
|
||||
public function testFromArrayWithMissingRoots(): void
|
||||
{
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
$this->expectExceptionMessage('Missing or invalid "roots"');
|
||||
|
||||
/* @phpstan-ignore argument.type */
|
||||
ListRootsResult::fromArray([]);
|
||||
}
|
||||
|
||||
public function testFromArrayWithNonArrayRoot(): void
|
||||
{
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
$this->expectExceptionMessage('Invalid root in ListRootsResult data, expected an array.');
|
||||
|
||||
/* @phpstan-ignore argument.type */
|
||||
ListRootsResult::fromArray([
|
||||
'roots' => ['file:///tmp'],
|
||||
]);
|
||||
}
|
||||
|
||||
public function testFromArrayRejectsNonFileUri(): void
|
||||
{
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
$this->expectExceptionMessage('must start with "file://"');
|
||||
|
||||
ListRootsResult::fromArray([
|
||||
'roots' => [['uri' => 'https://example.com']],
|
||||
]);
|
||||
}
|
||||
|
||||
public function testFromArrayRoundTrip(): void
|
||||
{
|
||||
$data = [
|
||||
'roots' => [
|
||||
['uri' => 'file:///home/user/project', 'name' => 'project'],
|
||||
['uri' => 'file:///tmp'],
|
||||
],
|
||||
'_meta' => ['foo' => 'bar'],
|
||||
];
|
||||
|
||||
$result = ListRootsResult::fromArray($data);
|
||||
|
||||
$this->assertSame($data, json_decode(json_encode($result), true));
|
||||
}
|
||||
|
||||
public function testJsonSerializeWithoutMeta(): void
|
||||
{
|
||||
$result = new ListRootsResult([new Root('file:///tmp')]);
|
||||
|
||||
$this->assertSame([
|
||||
'roots' => [['uri' => 'file:///tmp']],
|
||||
], json_decode(json_encode($result), true));
|
||||
}
|
||||
}
|
||||
109
tests/Unit/Server/ClientGatewayTest.php
Normal file
109
tests/Unit/Server/ClientGatewayTest.php
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
<?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;
|
||||
|
||||
use Mcp\Exception\ClientException;
|
||||
use Mcp\Schema\JsonRpc\Error;
|
||||
use Mcp\Schema\JsonRpc\Response;
|
||||
use Mcp\Schema\Request\ListRootsRequest;
|
||||
use Mcp\Schema\Result\ListRootsResult;
|
||||
use Mcp\Server\ClientGateway;
|
||||
use Mcp\Server\Session\SessionInterface;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Symfony\Component\Uid\Uuid;
|
||||
|
||||
final class ClientGatewayTest extends TestCase
|
||||
{
|
||||
public function testSupportsRootsReturnsTrueWhenAdvertised(): void
|
||||
{
|
||||
$session = $this->createMock(SessionInterface::class);
|
||||
$session->method('get')->with('client_capabilities', [])->willReturn(['roots' => []]);
|
||||
|
||||
$gateway = new ClientGateway($session);
|
||||
|
||||
$this->assertTrue($gateway->supportsRoots());
|
||||
}
|
||||
|
||||
public function testSupportsRootsReturnsFalseWhenNotAdvertised(): void
|
||||
{
|
||||
$session = $this->createMock(SessionInterface::class);
|
||||
$session->method('get')->with('client_capabilities', [])->willReturn(['sampling' => []]);
|
||||
|
||||
$gateway = new ClientGateway($session);
|
||||
|
||||
$this->assertFalse($gateway->supportsRoots());
|
||||
}
|
||||
|
||||
public function testListRootsReturnsRootsFromClient(): void
|
||||
{
|
||||
$session = $this->createMock(SessionInterface::class);
|
||||
$session->method('getId')->willReturn(Uuid::v4());
|
||||
|
||||
$gateway = new ClientGateway($session);
|
||||
|
||||
$response = $this->response([
|
||||
'roots' => [
|
||||
['uri' => 'file:///home/user/project', 'name' => 'project'],
|
||||
],
|
||||
]);
|
||||
|
||||
$result = $this->runInFiber(static fn (): ListRootsResult => $gateway->listRoots(), $response);
|
||||
|
||||
$this->assertInstanceOf(ListRootsResult::class, $result);
|
||||
$this->assertCount(1, $result->roots);
|
||||
$this->assertSame('file:///home/user/project', $result->roots[0]->uri);
|
||||
}
|
||||
|
||||
public function testListRootsThrowsClientExceptionOnError(): void
|
||||
{
|
||||
$session = $this->createMock(SessionInterface::class);
|
||||
$session->method('getId')->willReturn(Uuid::v4());
|
||||
|
||||
$gateway = new ClientGateway($session);
|
||||
|
||||
$error = Error::forInternalError('nope', '1');
|
||||
|
||||
$this->expectException(ClientException::class);
|
||||
|
||||
$this->runInFiber(static fn (): ListRootsResult => $gateway->listRoots(), $error);
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the gateway call inside a Fiber, asserts it suspends with a roots/list
|
||||
* request, then resumes it with the given client response.
|
||||
*
|
||||
* @param Response<array<string, mixed>>|Error $response
|
||||
*/
|
||||
private function runInFiber(\Closure $call, Response|Error $response): mixed
|
||||
{
|
||||
$fiber = new \Fiber($call);
|
||||
$suspend = $fiber->start();
|
||||
|
||||
$this->assertIsArray($suspend);
|
||||
$this->assertSame('request', $suspend['type']);
|
||||
$this->assertInstanceOf(ListRootsRequest::class, $suspend['request']);
|
||||
|
||||
$fiber->resume($response);
|
||||
|
||||
return $fiber->getReturn();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $result
|
||||
*
|
||||
* @return Response<array<string, mixed>>
|
||||
*/
|
||||
private function response(array $result): Response
|
||||
{
|
||||
return new Response('1', $result);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue