Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@

All notable changes to `mcp/sdk` will be documented in this file.

0.8.0
-----

* Add client-side `roots/list` handler (`ListRootsRequestHandler` + `RootsCallbackInterface`) and `Client::sendRootsListChanged()`, plus server-side `ClientGateway::listRoots()` / `supportsRoots()` and `ListRootsResult::fromArray()`.

0.7.0
-----

Expand Down
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,15 @@ $client = Client::builder()
->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
```php
$loggingHandler = new LoggingNotificationHandler($myCallback);
Expand Down
45 changes: 45 additions & 0 deletions docs/client.md
Original file line number Diff line number Diff line change
Expand Up @@ -600,6 +600,51 @@ Only the `Accept` action carries content.
See `examples/client/stdio_elicitation.php` for a runnable example against the
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

The client throws exceptions for various error conditions:
Expand Down
85 changes: 85 additions & 0 deletions examples/client/stdio_roots.php

@chr-hertel chr-hertel Jul 27, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i don't think we need the try-catch block here

and, not sure, but can we demo it the other way around so that the list roots request actually is executed?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both done in 5d278a9. try/catch is gone, and the demo is turned around: the client-communication server now has an inspect_workspace_roots tool using ClientGateway::supportsRoots()/listRoots(), and the example calls it — so the server really issues roots/list and the client's handler answers. Output when run:

Calling 'inspect_workspace_roots'...
[ROOTS] Server requested the client's list of roots

Result:
{
    "status": "ok",
    "message": "Client exposed 2 root(s).",
    "roots": [
        {"uri": "file:///home/user/projects/app", "name": "Application"},
        {"uri": "file:///home/user/projects/library", "name": "Library"}
    ]
}

The sendRootsListChanged() notification is kept at the end as a secondary demo.

Original file line number Diff line number Diff line change
@@ -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();
36 changes: 36 additions & 0 deletions examples/server/client-communication/ClientAwareService.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,42 @@ public function __construct(
$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}
*/
Expand Down
23 changes: 23 additions & 0 deletions src/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,13 @@
use Mcp\Client\Transport\TransportInterface;
use Mcp\Exception\ConnectionException;
use Mcp\Exception\RequestException;
use Mcp\Exception\RuntimeException;
use Mcp\Schema\Enum\LoggingLevel;
use Mcp\Schema\Implementation;
use Mcp\Schema\JsonRpc\Error;
use Mcp\Schema\JsonRpc\Request;
use Mcp\Schema\JsonRpc\Response;
use Mcp\Schema\Notification\RootsListChangedNotification;
use Mcp\Schema\PromptReference;
use Mcp\Schema\Request\CallToolRequest;
use Mcp\Schema\Request\CompletionCompleteRequest;
Expand Down Expand Up @@ -244,6 +246,27 @@ public function setLoggingLevel(LoggingLevel $level): void
$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());

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i get why you're not using sendRequest - it's just a notification, but is this sufficient - we're skipping isConnected check here

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch — it was worse than just skipping the check: Protocol::sendNotification() sends via $this->transport?->send(), so on a disconnected client the notification was silently dropped instead of failing. It now throws a ConnectionException like sendRequest() does (capability check stays first), with a test for it. 5d278a9

}

/**
* Send a request to the server and wait for response.
*
Expand Down
68 changes: 68 additions & 0 deletions src/Client/Handler/Request/ListRootsRequestHandler.php
Original file line number Diff line number Diff line change
@@ -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());
}
}
}
28 changes: 28 additions & 0 deletions src/Client/Handler/Request/RootsCallbackInterface.php
Original file line number Diff line number Diff line change
@@ -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;
}
24 changes: 24 additions & 0 deletions src/Exception/RootsException.php
Original file line number Diff line number Diff line change
@@ -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
{
}
Loading