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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ All notable changes to `mcp/sdk` will be documented in this file.
-----

* Allow `[$instance, 'methodName']` as an element handler in `Builder::addTool()`, `addResource()`, `addResourceTemplate()`, and `addPrompt()`. Unblocks handlers with constructor dependencies that the container-less `new $className()` fallback cannot build.
* Add client-side `roots/list` handler (`ListRootsRequestHandler` + `RootsCallbackInterface`) and `Client::sendRootsListChanged()`, plus server-side `ClientGateway::listRoots()` / `supportsRoots()` and `ListRootsResult::fromArray()`.

0.6.0
-----
Expand Down
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,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
40 changes: 40 additions & 0 deletions docs/client.md
Original file line number Diff line number Diff line change
Expand Up @@ -534,6 +534,46 @@ $client = Client::builder()
> throw new \RuntimeException('Rate limit exceeded');
> ```

### 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`:

```php
$client->sendRootsListChanged();
```

## Error Handling

The client throws exceptions for various error conditions:
Expand Down
85 changes: 85 additions & 0 deletions examples/client/stdio_roots.php
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.
* - It can notify 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\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'],
);

try {
echo "Connecting to MCP server...\n";
$client->connect($transport);

$serverInfo = $client->getServerInfo();
echo 'Connected to: '.($serverInfo->name ?? 'unknown')."\n\n";

echo "Available tools:\n";
$toolsResult = $client->listTools();
foreach ($toolsResult->tools as $tool) {
echo " - {$tool->name}\n";
}
echo "\n";

// Whenever the client's workspace folders change, notify the server so it can
// request an updated list via roots/list.
echo "Notifying the server that the roots list changed...\n";
$client->sendRootsListChanged();

echo "Client is ready to answer roots/list requests from the server.\n";
} catch (Throwable $e) {
echo "Error: {$e->getMessage()}\n";
echo $e->getTraceAsString()."\n";
} finally {
$client->disconnect();
}
18 changes: 18 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,22 @@ 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
*/
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).');
}

$this->protocol->sendNotification(new RootsListChangedNotification());
}

/**
* 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
{
}
23 changes: 23 additions & 0 deletions src/Schema/Result/ListRootsResult.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace Mcp\Schema\Result;

use Mcp\Exception\InvalidArgumentException;
use Mcp\Schema\JsonRpc\ResultInterface;
use Mcp\Schema\Root;

Expand All @@ -33,6 +34,28 @@ public function __construct(
) {
}

/**
* @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 = array_map(
static fn (array $root): Root => Root::fromArray($root),
array_values($data['roots']),
);
Comment on lines +49 to +52

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.

flaky in case roots doesn't carry an array as element => TypeError


$meta = isset($data['_meta']) && \is_array($data['_meta']) ? $data['_meta'] : null;

return new self($roots, $meta);
}

/**
* @return array{
* roots: Root[],
Expand Down
Loading