[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:
Johannes Wachter 2026-08-14 23:04:25 +02:00 • committed by GitHub
commit bdc9d86671
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
16 changed files with 866 additions and 1 deletions

View file

@ -8,6 +8,7 @@ All notable changes to `mcp/sdk` will be documented in this file.
* Always emit `{}` for empty tool schemas: `Tool` recursively normalizes every empty sub-schema — `properties`, `items`, `additionalProperties`, `$defs`, combinators and the other draft-07 to 2020-12 schema keywords — in the constructor, for both `inputSchema` and `outputSchema`, so an object position is never serialized as `[]`. * Always emit `{}` for empty tool schemas: `Tool` recursively normalizes every empty sub-schema — `properties`, `items`, `additionalProperties`, `$defs`, combinators and the other draft-07 to 2020-12 schema keywords — in the constructor, for both `inputSchema` and `outputSchema`, so an object position is never serialized as `[]`.
* Prompt generators returning content as typed arrays (`['type' => 'text', ...]` etc.) no longer lose the optional fields: `annotations` on every content type, and `_meta` and an explicit `mimeType` on embedded resource contents, now carry through to the resulting `PromptMessage` instead of being silently dropped. A missing resource `mimeType` still defaults to `text/plain`/`application/octet-stream` as before. * Prompt generators returning content as typed arrays (`['type' => 'text', ...]` etc.) no longer lose the optional fields: `annotations` on every content type, and `_meta` and an explicit `mimeType` on embedded resource contents, now carry through to the resulting `PromptMessage` instead of being silently dropped. A missing resource `mimeType` still defaults to `text/plain`/`application/octet-stream` as before.
* Add `annotations` support to `ImageContent` (constructor, `fromArray()`, `fromFile()`, `fromString()`, `jsonSerialize()`), matching `TextContent` and `AudioContent`. * Add `annotations` support to `ImageContent` (constructor, `fromArray()`, `fromFile()`, `fromString()`, `jsonSerialize()`), matching `TextContent` and `AudioContent`.
* Add client-side `roots/list` handler (`ListRootsRequestHandler` + `RootsCallbackInterface`) and `Client::sendRootsListChanged()`, plus server-side `ClientGateway::listRoots()` / `supportsRoots()` and `ListRootsResult::fromArray()`.
0.7.0 0.7.0
----- -----

View file

@ -243,6 +243,15 @@ $client = Client::builder()
->build(); ->build();
``` ```
- **Roots Support**: Expose `file://` workspace folders to the server
```php
$rootsHandler = new ListRootsRequestHandler($myCallback);
$client = Client::builder()
->setCapabilities(new ClientCapabilities(roots: true, rootsListChanged: true))
->addRequestHandler($rootsHandler)
->build();
```
- **Logging Notifications**: Receive server log messages - **Logging Notifications**: Receive server log messages
```php ```php
$loggingHandler = new LoggingNotificationHandler($myCallback); $loggingHandler = new LoggingNotificationHandler($myCallback);

View file

@ -600,6 +600,51 @@ Only the `Accept` action carries content.
See `examples/client/stdio_elicitation.php` for a runnable example against the See `examples/client/stdio_elicitation.php` for a runnable example against the
elicitation demo server. elicitation demo server.
### Roots
Roots let the client expose a list of `file://` "workspace folders" that the server
is allowed to operate on. Advertise the `roots` capability and register a handler
that answers server `roots/list` requests:
```php
use Mcp\Client\Handler\Request\ListRootsRequestHandler;
use Mcp\Client\Handler\Request\RootsCallbackInterface;
use Mcp\Schema\ClientCapabilities;
use Mcp\Schema\Request\ListRootsRequest;
use Mcp\Schema\Result\ListRootsResult;
use Mcp\Schema\Root;
class WorkspaceRootsCallback implements RootsCallbackInterface
{
public function __invoke(ListRootsRequest $request): ListRootsResult
{
return new ListRootsResult([
new Root('file:///home/user/projects/app', 'Application'),
new Root('file:///home/user/projects/library', 'Library'),
]);
}
}
$client = Client::builder()
->setCapabilities(new ClientCapabilities(roots: true, rootsListChanged: true))
->addRequestHandler(new ListRootsRequestHandler(new WorkspaceRootsCallback))
->build();
```
When the client's roots change, notify the server so it can request the updated
list via `roots/list`. This requires advertising the `roots.listChanged`
capability (`rootsListChanged: true` above); otherwise `sendRootsListChanged()`
throws a `RuntimeException`. On a client that is not connected it throws a
`ConnectionException`:
```php
$client->sendRootsListChanged();
```
See `examples/client/stdio_roots.php` for a runnable example: it calls the
`inspect_workspace_roots` tool of the client-communication demo server, which
answers by issuing the `roots/list` request back to the client.
## Error Handling ## Error Handling
The client throws exceptions for various error conditions: The client throws exceptions for various error conditions:

View file

@ -0,0 +1,85 @@
<?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.
*/
/**
* STDIO Roots Example.
*
* This example demonstrates the "roots" client capability:
* - The client advertises the `roots` capability during initialization.
* - It answers server `roots/list` requests via a RootsCallbackInterface,
* exposing a couple of `file://` workspace folders.
* - Calling the server's `inspect_workspace_roots` tool makes the server issue
* a `roots/list` request, so the handler below actually runs.
* - It notifies the server when its list of roots changes.
*
* Usage: php examples/client/stdio_roots.php
*/
require_once __DIR__.'/../../vendor/autoload.php';
use Mcp\Client;
use Mcp\Client\Handler\Request\ListRootsRequestHandler;
use Mcp\Client\Handler\Request\RootsCallbackInterface;
use Mcp\Client\Transport\StdioTransport;
use Mcp\Schema\ClientCapabilities;
use Mcp\Schema\Content\TextContent;
use Mcp\Schema\Request\ListRootsRequest;
use Mcp\Schema\Result\ListRootsResult;
use Mcp\Schema\Root;
$rootsRequestHandler = new ListRootsRequestHandler(new class implements RootsCallbackInterface {
public function __invoke(ListRootsRequest $request): ListRootsResult
{
echo "[ROOTS] Server requested the client's list of roots\n";
return new ListRootsResult([
new Root('file:///home/user/projects/app', 'Application'),
new Root('file:///home/user/projects/library', 'Library'),
]);
}
});
$client = Client::builder()
->setClientInfo('STDIO Roots Test', '1.0.0')
->setInitTimeout(30)
->setRequestTimeout(120)
->setCapabilities(new ClientCapabilities(roots: true, rootsListChanged: true))
->addRequestHandler($rootsRequestHandler)
->build();
$transport = new StdioTransport(
command: 'php',
args: [__DIR__.'/../server/client-communication/server.php'],
);
echo "Connecting to MCP server...\n";
$client->connect($transport);
$serverInfo = $client->getServerInfo();
echo 'Connected to: '.($serverInfo->name ?? 'unknown')."\n\n";
// The server tool asks the client for its roots, which triggers the handler above.
echo "Calling 'inspect_workspace_roots'...\n";
$result = $client->callTool(name: 'inspect_workspace_roots');
echo "\nResult:\n";
foreach ($result->content as $content) {
if ($content instanceof TextContent) {
echo $content->text."\n";
}
}
// Whenever the client's workspace folders change, notify the server so it can
// request an updated list via roots/list.
echo "\nNotifying the server that the roots list changed...\n";
$client->sendRootsListChanged();
$client->disconnect();

View file

@ -25,6 +25,42 @@ final class ClientAwareService
$this->logger->info('SamplingTool instantiated for sampling example.'); $this->logger->info('SamplingTool instantiated for sampling example.');
} }
/**
* Ask the client which workspace folders the server is allowed to operate on.
*
* Demonstrates the server side of the "roots" client capability: the tool
* issues a roots/list request that the client answers from its own handler.
*
* @return array{status: string, message: string, roots?: list<array{uri: string, name: string|null}>}
*/
#[McpTool(name: 'inspect_workspace_roots', description: 'Ask the client for its workspace roots via a roots/list request.')]
public function inspectWorkspaceRoots(RequestContext $context): array
{
$clientGateway = $context->getClientGateway();
if (!$clientGateway->supportsRoots()) {
return [
'status' => 'unsupported',
'message' => 'Client does not expose roots. Advertise the "roots" capability and register a ListRootsRequestHandler to let the server discover your workspace folders.',
];
}
$result = $clientGateway->listRoots();
$roots = [];
foreach ($result->roots as $root) {
$roots[] = ['uri' => $root->uri, 'name' => $root->name];
}
$clientGateway->log(LoggingLevel::Info, \sprintf('Client exposed %d root(s).', \count($roots)));
return [
'status' => 'ok',
'message' => \sprintf('Client exposed %d root(s).', \count($roots)),
'roots' => $roots,
];
}
/** /**
* @return array{incident: string, recommended_actions: string, model: string} * @return array{incident: string, recommended_actions: string, model: string}
*/ */

View file

@ -17,11 +17,13 @@ use Mcp\Client\Protocol;
use Mcp\Client\Transport\TransportInterface; use Mcp\Client\Transport\TransportInterface;
use Mcp\Exception\ConnectionException; use Mcp\Exception\ConnectionException;
use Mcp\Exception\RequestException; use Mcp\Exception\RequestException;
use Mcp\Exception\RuntimeException;
use Mcp\Schema\Enum\LoggingLevel; use Mcp\Schema\Enum\LoggingLevel;
use Mcp\Schema\Implementation; use Mcp\Schema\Implementation;
use Mcp\Schema\JsonRpc\Error; use Mcp\Schema\JsonRpc\Error;
use Mcp\Schema\JsonRpc\Request; use Mcp\Schema\JsonRpc\Request;
use Mcp\Schema\JsonRpc\Response; use Mcp\Schema\JsonRpc\Response;
use Mcp\Schema\Notification\RootsListChangedNotification;
use Mcp\Schema\PromptReference; use Mcp\Schema\PromptReference;
use Mcp\Schema\Request\CallToolRequest; use Mcp\Schema\Request\CallToolRequest;
use Mcp\Schema\Request\CompletionCompleteRequest; use Mcp\Schema\Request\CompletionCompleteRequest;
@ -244,6 +246,27 @@ class Client
$this->sendRequest($request); $this->sendRequest($request);
} }
/**
* Notify the server that the client's list of roots has changed.
*
* The server should react by requesting an updated list via roots/list.
*
* @throws RuntimeException if the client did not advertise the `roots.listChanged` capability
* @throws ConnectionException if the client is not connected
*/
public function sendRootsListChanged(): void
{
if (true !== $this->config->capabilities->rootsListChanged) {
throw new RuntimeException('Cannot send a "roots/list_changed" notification without advertising the "roots.listChanged" capability. Build the client with new ClientCapabilities(roots: true, rootsListChanged: true).');
}
if (!$this->isConnected()) {
throw new ConnectionException('Client is not connected. Call connect() first.');
}
$this->protocol->sendNotification(new RootsListChangedNotification());
}
/** /**
* Send a request to the server and wait for response. * Send a request to the server and wait for response.
* *

View file

@ -0,0 +1,68 @@
<?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\Client\Handler\Request;
use Mcp\Exception\RootsException;
use Mcp\Schema\JsonRpc\Error;
use Mcp\Schema\JsonRpc\Request;
use Mcp\Schema\JsonRpc\Response;
use Mcp\Schema\Request\ListRootsRequest;
use Mcp\Schema\Result\ListRootsResult;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
/**
* Handler for roots/list requests from the server.
*
* The MCP server may ask the client for the list of filesystem roots (its
* "workspace folders"). This handler wraps a user-provided callback that returns
* the roots the client wishes to expose.
*
* @implements RequestHandlerInterface<ListRootsResult>
*
* @author Johannes Wachter <johannes@sulu.io>
*/
class ListRootsRequestHandler implements RequestHandlerInterface
{
public function __construct(
private readonly RootsCallbackInterface $callback,
private readonly LoggerInterface $logger = new NullLogger(),
) {
}
public function supports(Request $request): bool
{
return $request instanceof ListRootsRequest;
}
/**
* @return Response<ListRootsResult>|Error
*/
public function handle(Request $request): Response|Error
{
\assert($request instanceof ListRootsRequest);
try {
$result = $this->callback->__invoke($request);
return new Response($request->getId(), $result);
} catch (RootsException $e) {
$this->logger->error('Listing roots failed: '.$e->getMessage(), ['exception' => $e]);
return Error::forInternalError($e->getMessage(), $request->getId());
} catch (\Throwable $e) {
$this->logger->error('Unexpected error while listing roots', ['exception' => $e]);
return Error::forInternalError('Error while listing roots', $request->getId());
}
}
}

View file

@ -0,0 +1,28 @@
<?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\Client\Handler\Request;
use Mcp\Schema\Request\ListRootsRequest;
use Mcp\Schema\Result\ListRootsResult;
/**
* Contract for callbacks used by ListRootsRequestHandler.
*
* Implementations return the list of filesystem roots the client exposes when
* requested by the server.
*
* @author Johannes Wachter <johannes@sulu.io>
*/
interface RootsCallbackInterface
{
public function __invoke(ListRootsRequest $request): ListRootsResult;
}

View file

@ -0,0 +1,24 @@
<?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\Exception;
/**
* Exception thrown when listing roots fails.
*
* When thrown from a roots callback, this exception's message will be
* included in the error response sent back to the server.
*
* @author Johannes Wachter <johannes@sulu.io>
*/
final class RootsException extends \RuntimeException implements ExceptionInterface
{
}

View file

@ -11,6 +11,7 @@
namespace Mcp\Schema\Result; namespace Mcp\Schema\Result;
use Mcp\Exception\InvalidArgumentException;
use Mcp\Schema\JsonRpc\ResultInterface; use Mcp\Schema\JsonRpc\ResultInterface;
use Mcp\Schema\Root; use Mcp\Schema\Root;
@ -33,6 +34,32 @@ class ListRootsResult implements ResultInterface
) { ) {
} }
/**
* @param array{
* roots: array<array{uri: string, name?: string}>,
* _meta?: ?array<string, mixed>
* } $data
*/
public static function fromArray(array $data): self
{
if (!isset($data['roots']) || !\is_array($data['roots'])) {
throw new InvalidArgumentException('Missing or invalid "roots" in ListRootsResult data.');
}
$roots = [];
foreach ($data['roots'] as $root) {
if (!\is_array($root)) {
throw new InvalidArgumentException('Invalid root in ListRootsResult data, expected an array.');
}
$roots[] = Root::fromArray($root);
}
$meta = isset($data['_meta']) && \is_array($data['_meta']) ? $data['_meta'] : null;
return new self($roots, $meta);
}
/** /**
* @return array{ * @return array{
* roots: Root[], * roots: Root[],

View file

@ -32,8 +32,10 @@ use Mcp\Schema\Notification\LoggingMessageNotification;
use Mcp\Schema\Notification\ProgressNotification; use Mcp\Schema\Notification\ProgressNotification;
use Mcp\Schema\Request\CreateSamplingMessageRequest; use Mcp\Schema\Request\CreateSamplingMessageRequest;
use Mcp\Schema\Request\ElicitRequest; use Mcp\Schema\Request\ElicitRequest;
use Mcp\Schema\Request\ListRootsRequest;
use Mcp\Schema\Result\CreateSamplingMessageResult; use Mcp\Schema\Result\CreateSamplingMessageResult;
use Mcp\Schema\Result\ElicitResult; use Mcp\Schema\Result\ElicitResult;
use Mcp\Schema\Result\ListRootsResult;
use Mcp\Server\Session\SessionInterface; use Mcp\Server\Session\SessionInterface;
/** /**
@ -188,6 +190,49 @@ class ClientGateway
return ElicitResult::fromArray($response->result); return ElicitResult::fromArray($response->result);
} }
/**
* Request the list of filesystem roots exposed by the client.
*
* Roots are the client's "workspace folders" — the directories or files the
* server is allowed to operate on. The client answers the roots/list request
* with a list of file:// URIs.
*
* @param int $timeout The timeout in seconds
*
* @return ListRootsResult The roots exposed by the client
*
* @throws ClientException if the client request results in an error message
*/
public function listRoots(int $timeout = 120): ListRootsResult
{
$request = new ListRootsRequest();
$response = $this->request($request, $timeout);
if ($response instanceof Error) {
throw new ClientException($response);
}
return ListRootsResult::fromArray($response->result);
}
/**
* Check if the connected client supports roots.
*
* Roots allow servers to ask the client for the set of directories or files
* it is permitted to operate on. This method checks the client's advertised
* capabilities to determine if roots/list requests are supported.
*
* @return bool True if the client supports roots, false otherwise
*/
public function supportsRoots(): bool
{
$capabilities = (array) $this->session->get('client_capabilities', []);
// MCP spec: capability presence indicates support (value is typically {} or [])
return \array_key_exists('roots', $capabilities);
}
/** /**
* Check if the connected client supports elicitation. * Check if the connected client supports elicitation.
* *
@ -199,7 +244,7 @@ class ClientGateway
*/ */
public function supportsElicitation(): bool public function supportsElicitation(): bool
{ {
$capabilities = $this->session->get('client_capabilities', []); $capabilities = (array) $this->session->get('client_capabilities', []);
// MCP spec: capability presence indicates support (value is typically {} or []) // MCP spec: capability presence indicates support (value is typically {} or [])
return \array_key_exists('elicitation', $capabilities); return \array_key_exists('elicitation', $capabilities);

View 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();
}
}

View file

@ -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;
}
};
}
}

View 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);
}
}

View 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));
}
}

View 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);
}
}