From af9bf5fc774953cdc6cbe4af3ce5e5b322303416 Mon Sep 17 00:00:00 2001 From: soyuka Date: Thu, 26 Nov 2026 17:33:14 +0100 Subject: [PATCH] [Server][Client] Check extension methods and dependencies SEP-3371: reject extensions defining core methods, install an extension whole or not at all, let extensions contribute notification handlers (server, BC break on ServerExtensionInterface) and request/notification handlers (client), let an extension require others, checked on build, and expose sending custom requests and notifications on both sides. --- CHANGELOG.md | 16 +++ docs/advanced/extensions.md | 82 ++++++++++++- docs/advanced/index.md | 4 +- src/Client/Builder.php | 84 +++++++++++++- src/Client/Client.php | 20 +++- .../Extension/ClientExtensionInterface.php | 40 +++++++ .../Extension/DependentExtensionInterface.php | 29 +++++ src/Schema/MessageFactory.php | 33 ++++++ src/Server/Builder.php | 82 ++++++++++--- src/Server/ClientGateway.php | 12 +- .../Extension/ServerExtensionInterface.php | 11 +- tests/Unit/Client/BuilderTest.php | 108 ++++++++++++++++++ tests/Unit/Client/ClientTest.php | 40 +++++++ .../Unit/Client/Extension/ThingExtension.php | 72 ++++++++++++ .../Client/Extension/ThingListHandler.php | 36 ++++++ .../Client/Extension/ThingSeenHandler.php | 31 +++++ tests/Unit/Schema/MessageFactoryTest.php | 15 +++ tests/Unit/Server/BuilderTest.php | 84 ++++++++++++++ tests/Unit/Server/ClientGatewayTest.php | 21 ++++ .../Unit/Server/Extension/ThingExtension.php | 30 ++++- .../Server/Extension/ThingSeenHandler.php | 31 +++++ .../Extension/ThingSeenNotification.php | 35 ++++++ 22 files changed, 882 insertions(+), 34 deletions(-) create mode 100644 src/Client/Extension/ClientExtensionInterface.php create mode 100644 src/Schema/Extension/DependentExtensionInterface.php create mode 100644 tests/Unit/Client/Extension/ThingExtension.php create mode 100644 tests/Unit/Client/Extension/ThingListHandler.php create mode 100644 tests/Unit/Client/Extension/ThingSeenHandler.php create mode 100644 tests/Unit/Server/Extension/ThingSeenHandler.php create mode 100644 tests/Unit/Server/Extension/ThingSeenNotification.php diff --git a/CHANGELOG.md b/CHANGELOG.md index c977af64c..228916378 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,23 @@ All notable changes to `mcp/sdk` will be documented in this file. ### Server +* [BC Break] Add `ServerExtensionInterface::getNotificationHandlers()`, through which an extension contributes notification handlers. Implementers must add it; return `[]` when the extension handles no notifications. * Fix const validation errors always reporting the expected value as null. +* `Builder::enableExtension()` rejects an extension defining a core MCP method, and installs an extension whole or not at all. +* `Builder::build()` rejects an extension whose required extensions are not enabled. +* `ClientGateway::request()` is no longer internal, to send requests the typed methods do not cover, such as an extension's. + +### Client + +* `Client::sendRequest()` is public, and `Client::notify()` is added, to send requests and notifications the typed API does not cover, such as an extension's. +* Add `Mcp\Client\Extension\ClientExtensionInterface`, through which an extension contributes request and notification handlers. +* `Builder::enableExtension()` registers an extension's message classes, so the client decodes its methods, and rejects an extension defining a core MCP method or a method another extension defines. +* `Builder::build()` rejects an extension whose required extensions are not enabled. + +### Schema + +* Add `Mcp\Schema\Extension\DependentExtensionInterface`, through which an extension requires other extensions on the same client or server (SEP-3371). +* Add `MessageFactory::isCoreMethod()`. 0.10.0 ------ diff --git a/docs/advanced/extensions.md b/docs/advanced/extensions.md index 989926d76..0ce08ddfd 100644 --- a/docs/advanced/extensions.md +++ b/docs/advanced/extensions.md @@ -82,15 +82,85 @@ Enable it with `Builder::enableExtension(new AuditExtension())`. A prefix whose second label is `modelcontextprotocol` or `mcp` (e.g. `io.modelcontextprotocol/`) is reserved for official extensions. The SDK doesn't refuse such an identifier, so choose a prefix of your own. +### Custom methods + An extension that adds JSON-RPC methods also implements `getMessages()`, which returns the -request and notification classes of the new methods, so the SDK can parse them. To answer -those methods on a server, it implements `Mcp\Server\Extension\ServerExtensionInterface`, -whose `getRequestHandlers()` returns the [request handlers](custom-handlers.md) that answer -them. If two enabled extensions define -the same method, `enableExtension()` throws a `LogicException`. Extensions bring no -notification handlers: add those with `Builder::addNotificationHandler()`. They +request and notification classes of the new methods, so the SDK can parse them. Its handlers +come from the interfaces of the side it is enabled on: + +| Side | Interface | Contributes | +| --- | --- | --- | +| Server | `Mcp\Server\Extension\ServerExtensionInterface` | `getRequestHandlers()` and `getNotificationHandlers()`: [handlers](custom-handlers.md) for the client's requests and notifications | +| Client | `Mcp\Client\Extension\ClientExtensionInterface` | `getRequestHandlers()` and `getNotificationHandlers()` for the server's requests and notifications | + +Handlers differ per side, so an extension with methods for both sides ships one class per +side, sharing the message classes. +Server notification handlers [don't run on revision `2026-07-28`](custom-handlers.md#protocol-2026-07-28). +A method name belongs to one message class. `enableExtension()` throws a `LogicException` +when an extension defines a core MCP method, such as `tools/call` or `notifications/cancelled`, +or a method another enabled extension already defines. Replacing what a core method does +stays possible with a [custom handler](custom-handlers.md), which keeps the method's types. + +### Requiring another extension + +An extension that only works alongside another one implements +`Mcp\Schema\Extension\DependentExtensionInterface`: + +```php +use Mcp\Schema\Extension\DependentExtensionInterface; +use Mcp\Schema\Extension\ExtensionIdentifier; + +final class SearchExtension implements DependentExtensionInterface +{ + // getId(), getCapabilities(), getMessages()... + + public function getRequiredExtensions(): array + { + return [new ExtensionIdentifier('com.example/catalog')]; + } +} +``` + +The requirement is local and never sent to the peer. `build()` checks it, so the required +extension can be enabled before or after the one requiring it. When it is missing, `build()` +throws a `LogicException` naming both extensions, and no client or server is created. + +## Extension points (SEP-3371) + +[SEP-3371](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/3371) defines +the extension points an SDK offers so that an extension can ship as its own package. This +SDK implements SEP-3371 for server and client: registration and custom methods; middleware not yet. + +| Extension point | Server | Client | +| --- | --- | --- | +| Registration | `Server\Builder::enableExtension()` | `Client\Builder::enableExtension()` | +| Capabilities | `ExtensionInterface::getCapabilities()`, read back with `ClientGateway::supportsExtension()` | `ExtensionInterface::getCapabilities()`, read back with `Client::getServerCapabilities()` | +| Dependencies | `DependentExtensionInterface` | `DependentExtensionInterface` | +| Receiving custom methods | `getMessages()`, `ServerExtensionInterface` | `getMessages()`, `ClientExtensionInterface` | +| Sending custom methods | `ClientGateway::request()` and `ClientGateway::notify()`, from the `RequestContext` of a handler | `Client::sendRequest()` and `Client::notify()` | +| Middleware | not available yet | not available yet | + +Registration happens on the builder, before any message is processed: + +* Each extension is installed whole or not at all. When `enableExtension()` throws, none + of the rejected extension's capabilities, messages or handlers are kept. +* Enabling the same identifier twice, a core method name, or a method another extension + defines throws a `LogicException`. +* Dependencies are checked by `build()`, whatever order the extensions were enabled in. + +`ClientGateway::request()` needs a session, since the client answers in a request of its +own, and revision `2026-07-28` has no server-initiated requests: a handler returns an +`InputRequiredResult` there instead. + +Handlers run in the order they were registered, whether they come from an extension or +from `addRequestHandler()`/`addNotificationHandler()`. A request goes to the first handler +that supports it. On the server, these handlers run before the SDK's built-in ones, and +every notification handler that supports a notification runs. On the client, the built-in +`notifications/progress` handler runs first, and a notification reaches only the first +handler that supports it. + ## MCP Apps (`io.modelcontextprotocol/ui`) The [MCP Apps extension][ext-apps] lets servers expose interactive HTML UIs as diff --git a/docs/advanced/index.md b/docs/advanced/index.md index acaba073b..82f8af9d3 100644 --- a/docs/advanced/index.md +++ b/docs/advanced/index.md @@ -5,7 +5,9 @@ Everything here is optional. A working server needs none of it. * **[Events](events.md)** — PSR-14 events dispatched around requests, responses, errors and notifications. Useful for metrics, audit logs and debugging. * **[Protocol extensions](extensions.md)** — opt-in extensions announced during - capability negotiation, including MCP Apps (HTML UI resources). + capability negotiation, their custom methods and dependencies, the + [SEP-3371 extension points](extensions.md#extension-points-sep-3371), and MCP Apps + (HTML UI resources). * **[Custom message handlers](custom-handlers.md)** — taking over a JSON-RPC method the SDK knows, for example `tools/list`. A new method needs an [extension](extensions.md#writing-your-own-extension). diff --git a/src/Client/Builder.php b/src/Client/Builder.php index 745070085..7ba99b7dc 100644 --- a/src/Client/Builder.php +++ b/src/Client/Builder.php @@ -13,12 +13,17 @@ use Mcp\Client\Exception\InvalidArgumentException; use Mcp\Client\Exception\LogicException; +use Mcp\Client\Extension\ClientExtensionInterface; use Mcp\Client\Handler\Notification\NotificationHandlerInterface; use Mcp\Client\Handler\Request\RequestHandlerInterface; use Mcp\Schema\ClientCapabilities; use Mcp\Schema\Enum\ProtocolVersion; +use Mcp\Schema\Extension\DependentExtensionInterface; use Mcp\Schema\Extension\ExtensionInterface; use Mcp\Schema\Implementation; +use Mcp\Schema\JsonRpc\Notification; +use Mcp\Schema\JsonRpc\Request; +use Mcp\Schema\MessageFactory; use Psr\Log\LoggerInterface; use Psr\Log\NullLogger; @@ -39,6 +44,15 @@ final class Builder /** @var array> */ private array $extensions = []; + + /** @var array RPC method to the extension identifier defining it */ + private array $extensionMethods = []; + + /** @var list|class-string> */ + private array $extensionMessages = []; + + /** @var array> extension identifier to the identifiers of the extensions it requires */ + private array $extensionRequirements = []; private int $initTimeout = 30; private int $requestTimeout = 120; private int $maxRetries = 3; @@ -99,8 +113,18 @@ public function setCapabilities(ClientCapabilities $capabilities): self * Enable one or more MCP protocol extensions, announced to the server under * `capabilities.extensions` in the initialize request. * + * An extension also contributes the message classes its methods decode + * into, a {@see ClientExtensionInterface} the handlers answering them, and a + * {@see DependentExtensionInterface} the extensions it requires, checked on + * build. + * + * An extension is installed whole or not at all: when it is rejected, none + * of its contributions are kept. + * * @throws InvalidArgumentException if the identifier is not a valid `_meta` prefix - * @throws LogicException if the same extension is enabled more than once + * @throws LogicException if the same extension is enabled more than once, an + * extension defines a core method, or two enabled + * extensions define the same RPC method */ public function enableExtension(ExtensionInterface ...$extensions): self { @@ -111,7 +135,56 @@ public function enableExtension(ExtensionInterface ...$extensions): self throw new LogicException(\sprintf('Extension "%s" is already enabled.', $id)); } + /** @var array|class-string> $messages */ + $messages = []; + foreach ($extension->getMessages() as $message) { + $method = $message::getMethod(); + + if (MessageFactory::isCoreMethod($method)) { + throw new LogicException(\sprintf('Extension "%s" cannot define "%s": it is a core MCP method.', $id, $method)); + } + + // The message factory resolves a method to whichever class was + // registered first, so a second owner would silently never be reached. + if (isset($this->extensionMethods[$method]) || isset($messages[$method])) { + throw new LogicException(\sprintf('Method "%s" is already claimed by extension "%s", so extension "%s" cannot also define it.', $method, $this->extensionMethods[$method] ?? $id, $id)); + } + + $messages[$method] = $message; + } + + $requestHandlers = []; + $notificationHandlers = []; + if ($extension instanceof ClientExtensionInterface) { + foreach ($extension->getRequestHandlers() as $handler) { + $requestHandlers[] = $handler; + } + + foreach ($extension->getNotificationHandlers() as $handler) { + $notificationHandlers[] = $handler; + } + } + + $requirements = []; + if ($extension instanceof DependentExtensionInterface) { + foreach ($extension->getRequiredExtensions() as $required) { + $requirements[] = (string) $required; + } + } + $this->extensions[$id] = $extension->getCapabilities(); + + foreach ($messages as $method => $message) { + $this->extensionMessages[] = $message; + $this->extensionMethods[$method] = $id; + } + + array_push($this->requestHandlers, ...$requestHandlers); + array_push($this->notificationHandlers, ...$notificationHandlers); + + if ([] !== $requirements) { + $this->extensionRequirements[$id] = $requirements; + } } return $this; @@ -188,6 +261,14 @@ public function addRequestHandler(RequestHandlerInterface $handler): self */ public function build(): Client { + foreach ($this->extensionRequirements as $id => $requirements) { + foreach ($requirements as $required) { + if (!isset($this->extensions[$required])) { + throw new LogicException(\sprintf('Extension "%s" requires extension "%s", which is not enabled.', $id, $required)); + } + } + } + $logger = $this->logger ?? new NullLogger(); $clientInfo = new Implementation( @@ -218,6 +299,7 @@ public function build(): Client $protocol = new Protocol( requestHandlers: $this->requestHandlers, notificationHandlers: $this->notificationHandlers, + messageFactory: MessageFactory::make(additional: $this->extensionMessages), logger: $logger, ); diff --git a/src/Client/Client.php b/src/Client/Client.php index d6214a44b..86302fc2d 100644 --- a/src/Client/Client.php +++ b/src/Client/Client.php @@ -24,6 +24,7 @@ use Mcp\Schema\Exception\ExceptionInterface; use Mcp\Schema\Implementation; use Mcp\Schema\JsonRpc\Error; +use Mcp\Schema\JsonRpc\Notification; use Mcp\Schema\JsonRpc\Request; use Mcp\Schema\JsonRpc\Response; use Mcp\Schema\Notification\RootsListChangedNotification; @@ -402,16 +403,33 @@ public function sendRootsListChanged(): void $this->protocol->sendNotification(new RootsListChangedNotification()); } + /** + * Send a notification the typed API does not cover, such as one an extension defines. + * + * @throws ConnectionException if the client is not connected + * @throws AuthorizationException if the server answers with HTTP 401 or 403 + */ + public function notify(Notification $notification): void + { + if (!$this->isConnected()) { + throw new ConnectionException('Client is not connected. Call connect() first.'); + } + + $this->protocol->sendNotification($notification); + } + /** * Send a request to the server and wait for response. * + * Public to send requests the typed API does not cover, such as one an extension defines. + * * @param (callable(float $progress, ?float $total, ?string $message): void)|null $onProgress * * @return Response * * @throws AuthorizationException|RequestException|ConnectionException|InvalidArgumentException */ - private function sendRequest(Request $request, ?callable $onProgress = null, ?CancellationTokenInterface $cancellation = null, ?float $timeoutSeconds = null): Response + public function sendRequest(Request $request, ?callable $onProgress = null, ?CancellationTokenInterface $cancellation = null, ?float $timeoutSeconds = null): Response { $transport = $this->transport; if (null === $transport || !$this->protocol->getState()->isInitialized()) { diff --git a/src/Client/Extension/ClientExtensionInterface.php b/src/Client/Extension/ClientExtensionInterface.php new file mode 100644 index 000000000..2b44d194c --- /dev/null +++ b/src/Client/Extension/ClientExtensionInterface.php @@ -0,0 +1,40 @@ + + */ +interface ClientExtensionInterface extends ExtensionInterface +{ + /** + * The handlers answering the server requests of {@see self::getMessages()}. + * + * @return iterable> + */ + public function getRequestHandlers(): iterable; + + /** + * The handlers receiving the server notifications of {@see self::getMessages()}. + * + * @return iterable + */ + public function getNotificationHandlers(): iterable; +} diff --git a/src/Schema/Extension/DependentExtensionInterface.php b/src/Schema/Extension/DependentExtensionInterface.php new file mode 100644 index 000000000..39706ac38 --- /dev/null +++ b/src/Schema/Extension/DependentExtensionInterface.php @@ -0,0 +1,29 @@ + + */ +interface DependentExtensionInterface extends ExtensionInterface +{ + /** + * @return list + */ + public function getRequiredExtensions(): array; +} diff --git a/src/Schema/MessageFactory.php b/src/Schema/MessageFactory.php index ce9377730..490ca563b 100644 --- a/src/Schema/MessageFactory.php +++ b/src/Schema/MessageFactory.php @@ -70,6 +70,22 @@ final class MessageFactory Schema\Request\SetLogLevelRequest::class, ]; + /** + * Core methods with no message class: the server answers the subscription + * stream before decoding. + */ + private const UNMODELLED_CORE_METHODS = [ + 'subscriptions/listen' => true, + 'notifications/subscriptions/acknowledged' => true, + ]; + + /** + * Derived from constants only, so it is the same for every request a worker serves. + * + * @var array|null + */ + private static ?array $coreMethods = null; + /** * @param list|class-string> $registeredMessages */ @@ -93,6 +109,23 @@ public static function make(array $additional = []): self return new self([...self::REGISTERED_MESSAGES, ...$additional]); } + /** + * Whether $method is defined by the MCP specification rather than by an extension. + */ + public static function isCoreMethod(string $method): bool + { + if (null === self::$coreMethods) { + $coreMethods = self::UNMODELLED_CORE_METHODS; + // `server/discover` is left out of the default registry because only the modern era decodes it. + foreach ([...self::REGISTERED_MESSAGES, Schema\Request\DiscoverRequest::class] as $messageClass) { + $coreMethods[$messageClass::getMethod()] = true; + } + self::$coreMethods = $coreMethods; + } + + return isset(self::$coreMethods[$method]); + } + /** * Creates a message object from JSON input. * diff --git a/src/Server/Builder.php b/src/Server/Builder.php index aa8a850da..159a85f54 100644 --- a/src/Server/Builder.php +++ b/src/Server/Builder.php @@ -14,9 +14,12 @@ use Mcp\Schema\Annotations; use Mcp\Schema\Enum\ProtocolVersion; use Mcp\Schema\Extension\AbstractExtension; +use Mcp\Schema\Extension\DependentExtensionInterface; use Mcp\Schema\Extension\ExtensionInterface; use Mcp\Schema\Icon; use Mcp\Schema\Implementation; +use Mcp\Schema\JsonRpc\Notification; +use Mcp\Schema\JsonRpc\Request; use Mcp\Schema\MessageFactory; use Mcp\Schema\Prompt; use Mcp\Schema\Request\DiscoverRequest; @@ -148,9 +151,12 @@ final class Builder /** @var array RPC method to the extension identifier defining it */ private array $extensionMethods = []; - /** @var list|class-string<\Mcp\Schema\JsonRpc\Notification>> */ + /** @var list|class-string> */ private array $extensionMessages = []; + /** @var array> extension identifier to the identifiers of the extensions it requires */ + private array $extensionRequirements = []; + /** @var string|list|null */ private string|array|null $requestStateKey = null; @@ -487,12 +493,18 @@ public function setCapabilities(ServerCapabilities $serverCapabilities): self * `capabilities.extensions` during the initialize handshake. * * An extension also contributes the message classes its methods decode - * into, and a {@see ServerExtensionInterface} the handlers serving them — see - * {@see AbstractExtension} for extensions that only announce a capability. + * into, a {@see ServerExtensionInterface} the request and notification + * handlers serving them, and a {@see DependentExtensionInterface} the + * extensions it requires, checked on build — see {@see AbstractExtension} + * for extensions that only announce a capability. + * + * An extension is installed whole or not at all: when it is rejected, none + * of its contributions are kept. * * @throws InvalidArgumentException if the identifier is not a valid `_meta` prefix - * @throws LogicException if the same extension is enabled more than once, or - * two enabled extensions define the same RPC method + * @throws LogicException if the same extension is enabled more than once, an + * extension defines a core method, or two enabled + * extensions define the same RPC method */ public function enableExtension(ExtensionInterface ...$extensions): self { @@ -503,31 +515,61 @@ public function enableExtension(ExtensionInterface ...$extensions): self throw new LogicException(\sprintf('Extension "%s" is already enabled.', $id)); } - $this->extensions[$id] = $extension->getCapabilities(); - - // Without this the method cannot be decoded at all, so nothing - // downstream ever sees it. + /** @var array|class-string> $messages */ + $messages = []; foreach ($extension->getMessages() as $message) { $method = $message::getMethod(); + if (MessageFactory::isCoreMethod($method)) { + throw new LogicException(\sprintf('Extension "%s" cannot define "%s": it is a core MCP method.', $id, $method)); + } + // The message factory resolves a method to whichever class was // registered first, so a second owner here would silently lose // the dispatch race while still being named in error messages. - if (isset($this->extensionMethods[$method]) && $this->extensionMethods[$method] !== $id) { - throw new LogicException(\sprintf('Method "%s" is already claimed by extension "%s", so extension "%s" cannot also define it.', $method, $this->extensionMethods[$method], $id)); + if (isset($this->extensionMethods[$method]) || isset($messages[$method])) { + throw new LogicException(\sprintf('Method "%s" is already claimed by extension "%s", so extension "%s" cannot also define it.', $method, $this->extensionMethods[$method] ?? $id, $id)); } - $this->extensionMessages[] = $message; - // Recorded even though the handler answers it, so a server with - // the extension *off* can say so instead of "no such method". - $this->extensionMethods[$method] = $id; + $messages[$method] = $message; } + $requestHandlers = []; + $notificationHandlers = []; if ($extension instanceof ServerExtensionInterface) { foreach ($extension->getRequestHandlers() as $handler) { - $this->requestHandlers[] = $handler; + $requestHandlers[] = $handler; + } + + foreach ($extension->getNotificationHandlers() as $handler) { + $notificationHandlers[] = $handler; + } + } + + $requirements = []; + if ($extension instanceof DependentExtensionInterface) { + foreach ($extension->getRequiredExtensions() as $required) { + $requirements[] = (string) $required; } } + + $this->extensions[$id] = $extension->getCapabilities(); + + // Without this the method cannot be decoded at all, so nothing + // downstream ever sees it. Recorded even though the handler answers + // it, so a server with the extension *off* can say so instead of + // "no such method". + foreach ($messages as $method => $message) { + $this->extensionMessages[] = $message; + $this->extensionMethods[$method] = $id; + } + + array_push($this->requestHandlers, ...$requestHandlers); + array_push($this->notificationHandlers, ...$notificationHandlers); + + if ([] !== $requirements) { + $this->extensionRequirements[$id] = $requirements; + } } return $this; @@ -1124,6 +1166,14 @@ private function assemble(): array */ private function resolve(): array { + foreach ($this->extensionRequirements as $id => $requirements) { + foreach ($requirements as $required) { + if (!isset($this->extensions[$required])) { + throw new LogicException(\sprintf('Extension "%s" requires extension "%s", which is not enabled.', $id, $required)); + } + } + } + $logger = $this->logger ?? new NullLogger(); $container = $this->container ?? new Container(); diff --git a/src/Server/ClientGateway.php b/src/Server/ClientGateway.php index 86bcb1d84..1a5e91c6c 100644 --- a/src/Server/ClientGateway.php +++ b/src/Server/ClientGateway.php @@ -455,9 +455,13 @@ private function sendElicitation(ElicitRequest $request, int $timeout, ?string $ * This suspends the Fiber and waits for the client to respond. The transport * handles polling the session for the response and resuming the Fiber when ready. * - * Public for {@see InputRequiredShim}, which sends the requests a handler - * embedded in an {@see \Mcp\Schema\Result\InputRequiredResult} and knows - * nothing about their kinds. Prefer the typed methods above. + * Sends requests the typed methods above do not cover, such as one an + * extension defines, to the client of this gateway's session. Prefer the + * typed methods for core requests. + * + * The client answers in a POST of its own, so this needs a session, and + * the `2026-07-28` revision has no server-initiated requests: there a + * handler returns an {@see \Mcp\Schema\Result\InputRequiredResult} instead. * * @param Request $request The request to send * @param int $timeout Maximum time to wait for response (seconds) @@ -466,8 +470,6 @@ private function sendElicitation(ElicitRequest $request, int $timeout, ?string $ * * @throws RuntimeException If Fiber support is not available * @throws SessionRequiredException if the server runs without sessions - * - * @internal */ public function request(Request $request, int $timeout = 120): Response|Error { diff --git a/src/Server/Extension/ServerExtensionInterface.php b/src/Server/Extension/ServerExtensionInterface.php index e0140a2ff..88c4d20db 100644 --- a/src/Server/Extension/ServerExtensionInterface.php +++ b/src/Server/Extension/ServerExtensionInterface.php @@ -13,10 +13,12 @@ use Mcp\Schema\Extension\ExtensionInterface; use Mcp\Schema\JsonRpc\ResultInterface; +use Mcp\Server\Handler\Notification\NotificationHandlerInterface; use Mcp\Server\Handler\Request\RequestHandlerInterface; /** - * An extension that answers the methods it defines when enabled on a server. + * An extension that answers the requests and receives the notifications it + * defines when enabled on a server. * * @author Christopher Hertel */ @@ -28,4 +30,11 @@ interface ServerExtensionInterface extends ExtensionInterface * @return iterable> */ public function getRequestHandlers(): iterable; + + /** + * The handlers receiving the notifications of {@see self::getMessages()}. + * + * @return iterable + */ + public function getNotificationHandlers(): iterable; } diff --git a/tests/Unit/Client/BuilderTest.php b/tests/Unit/Client/BuilderTest.php index 682e6a586..b4e16590b 100644 --- a/tests/Unit/Client/BuilderTest.php +++ b/tests/Unit/Client/BuilderTest.php @@ -11,11 +11,25 @@ namespace Mcp\Tests\Unit\Client; +use Mcp\Client\Builder; use Mcp\Client\Client; use Mcp\Client\Configuration; use Mcp\Client\Exception\LogicException; +use Mcp\Client\Protocol; use Mcp\Schema\ClientCapabilities; +use Mcp\Schema\Exception\UnknownMethodException; use Mcp\Schema\Extension\Apps\McpApps; +use Mcp\Schema\JsonRpc\Notification; +use Mcp\Schema\JsonRpc\Request; +use Mcp\Schema\MessageFactory; +use Mcp\Schema\Notification\CancelledNotification; +use Mcp\Schema\Request\CreateSamplingMessageRequest; +use Mcp\Tests\Unit\Client\Extension\ThingExtension; +use Mcp\Tests\Unit\Client\Extension\ThingListHandler; +use Mcp\Tests\Unit\Client\Extension\ThingSeenHandler; +use Mcp\Tests\Unit\Server\Extension\ThingListRequest; +use Mcp\Tests\Unit\Server\Extension\ThingSeenNotification; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestDox; use PHPUnit\Framework\TestCase; @@ -81,6 +95,100 @@ public function testEnableExtensionRejectsDuplicate(): void Client::builder()->enableExtension(new McpApps(), new McpApps()); } + #[TestDox('An extension contributes the message classes its methods decode into')] + public function testEnableExtensionRegistersItsMessages(): void + { + $client = Client::builder()->enableExtension(new ThingExtension())->build(); + + $this->assertInstanceOf(ThingListRequest::class, $this->messageFactory($client)->create('{"jsonrpc":"2.0","id":1,"method":"com.example/things.list"}')); + } + + #[TestDox('A client extension contributes the handlers its requests and notifications reach')] + public function testEnableExtensionRegistersItsHandlers(): void + { + $builder = Client::builder()->enableExtension(new ThingExtension()); + + $this->assertEquals([new ThingListHandler()], (new \ReflectionProperty(Builder::class, 'requestHandlers'))->getValue($builder)); + $this->assertEquals([new ThingSeenHandler()], (new \ReflectionProperty(Builder::class, 'notificationHandlers'))->getValue($builder)); + } + + /** + * @param class-string|class-string $message + */ + #[DataProvider('provideCoreMessages')] + #[TestDox('enableExtension() throws when an extension defines a core method')] + public function testEnableExtensionRejectsCoreMethod(string $message): void + { + $this->expectException(LogicException::class); + $this->expectExceptionMessage(\sprintf('Extension "com.example/things" cannot define "%s"', $message::getMethod())); + + Client::builder()->enableExtension(new ThingExtension(messages: [$message])); + } + + public static function provideCoreMessages(): iterable + { + yield 'request' => [CreateSamplingMessageRequest::class]; + yield 'notification' => [CancelledNotification::class]; + } + + #[TestDox('enableExtension() throws when two enabled extensions define the same RPC method')] + public function testEnableExtensionRejectsClaimedMethod(): void + { + $this->expectException(LogicException::class); + $this->expectExceptionMessage('com.example/things.list'); + + Client::builder()->enableExtension(new ThingExtension('com.example/things-a'), new ThingExtension('com.example/things-b')); + } + + #[TestDox('A rejected extension leaves none of its contributions installed')] + public function testRejectedExtensionLeavesNothingInstalled(): void + { + $builder = Client::builder()->enableExtension(new ThingExtension('com.example/seen', [ThingSeenNotification::class])); + + try { + $builder->enableExtension(new ThingExtension('com.example/things', [ThingListRequest::class, ThingSeenNotification::class])); + $this->fail('The extension should have been rejected.'); + } catch (LogicException) { + } + + $client = $builder->build(); + + $this->assertSame(['com.example/seen'], array_keys($this->extractConfiguration($client)->capabilities->extensions ?? [])); + $this->assertCount(1, (new \ReflectionProperty(Builder::class, 'requestHandlers'))->getValue($builder)); + + $this->expectException(UnknownMethodException::class); + $this->messageFactory($client)->create('{"jsonrpc":"2.0","id":1,"method":"com.example/things.list"}'); + } + + #[TestDox('build() throws when an enabled extension requires one that is not enabled')] + public function testBuildRejectsExtensionWithMissingDependency(): void + { + $builder = Client::builder()->enableExtension(new ThingExtension(requires: ['com.example/catalog'])); + + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Extension "com.example/things" requires extension "com.example/catalog", which is not enabled.'); + + $builder->build(); + } + + #[TestDox('An extension may be enabled after the extension that requires it')] + public function testDependencyMayBeEnabledAfterTheDependent(): void + { + $client = Client::builder() + ->enableExtension(new ThingExtension(requires: ['com.example/catalog'])) + ->enableExtension(new ThingExtension('com.example/catalog', [])) + ->build(); + + $this->assertSame(['com.example/things', 'com.example/catalog'], array_keys($this->extractConfiguration($client)->capabilities->extensions ?? [])); + } + + private function messageFactory(Client $client): MessageFactory + { + $protocol = (new \ReflectionProperty(Client::class, 'protocol'))->getValue($client); + + return (new \ReflectionProperty(Protocol::class, 'messageFactory'))->getValue($protocol); + } + private function extractConfiguration(Client $client): Configuration { $config = (new \ReflectionClass($client))->getProperty('config')->getValue($client); diff --git a/tests/Unit/Client/ClientTest.php b/tests/Unit/Client/ClientTest.php index 96b669d55..3808044e7 100644 --- a/tests/Unit/Client/ClientTest.php +++ b/tests/Unit/Client/ClientTest.php @@ -25,6 +25,8 @@ use Mcp\Schema\Exception\InvalidArgumentException as SchemaInvalidArgumentException; use Mcp\Schema\JsonRpc\Error; use Mcp\Schema\JsonRpc\Response; +use Mcp\Tests\Unit\Server\Extension\ThingListRequest; +use Mcp\Tests\Unit\Server\Extension\ThingSeenNotification; use PHPUnit\Framework\Attributes\TestDox; use PHPUnit\Framework\TestCase; @@ -259,6 +261,40 @@ public function testSendRootsListChangedThrowsWhenCapabilityNotDeclared(): void $client->sendRootsListChanged(); } + #[TestDox('sendRequest() sends a request the typed API does not cover and returns the answer')] + public function testSendRequestSendsACustomRequest(): void + { + $transport = new FakeTransport(); + $client = Client::builder()->setProtocolVersion(ProtocolVersion::V2025_11_25)->build(); + $client->connect($transport); + + $response = $client->sendRequest(new ThingListRequest()); + + $this->assertSame(['com.example/things.list'], \array_slice($transport->sentMethods, -1)); + $this->assertSame('Test Server', $response->result['serverInfo']['name']); + } + + #[TestDox('notify() sends a notification to the server')] + public function testNotifySendsANotification(): void + { + $transport = new FakeTransport(); + $client = Client::builder()->setProtocolVersion(ProtocolVersion::V2025_11_25)->build(); + $client->connect($transport); + + $client->notify(new ThingSeenNotification()); + + $this->assertSame(['com.example/things.seen'], \array_slice($transport->sentMethods, -1)); + } + + #[TestDox('notify() throws when the client is not connected')] + public function testNotifyThrowsWhenNotConnected(): void + { + $this->expectException(ConnectionException::class); + $this->expectExceptionMessage('Client is not connected.'); + + Client::builder()->build()->notify(new ThingSeenNotification()); + } + public function testSendRootsListChangedThrowsWhenNotConnected(): void { $client = Client::builder() @@ -305,6 +341,9 @@ final class FakeTransport extends BaseTransport public int $connectCalls = 0; public int $closeCalls = 0; + /** @var list */ + public array $sentMethods = []; + private string $outcome = self::ACCEPT; /** @var list Answers not yet delivered to the client */ @@ -337,6 +376,7 @@ public function send(string $data): void } $message = json_decode($data, true, 512, \JSON_THROW_ON_ERROR); + $this->sentMethods[] = $message['method'] ?? null; if (!isset($message['id'])) { if (self::BREAK_AFTER_ACCEPT === $this->outcome) { diff --git a/tests/Unit/Client/Extension/ThingExtension.php b/tests/Unit/Client/Extension/ThingExtension.php new file mode 100644 index 000000000..d01f86b56 --- /dev/null +++ b/tests/Unit/Client/Extension/ThingExtension.php @@ -0,0 +1,72 @@ + + */ +final class ThingExtension implements ClientExtensionInterface, DependentExtensionInterface +{ + /** + * @param list|class-string> $messages + * @param list $requires + */ + public function __construct( + private readonly string $id = 'com.example/things', + private readonly array $messages = [ThingListRequest::class, ThingSeenNotification::class], + private readonly array $requires = [], + ) { + } + + public function getId(): ExtensionIdentifier + { + return new ExtensionIdentifier($this->id); + } + + public function getCapabilities(): array + { + return []; + } + + public function getMessages(): array + { + return $this->messages; + } + + public function getRequestHandlers(): iterable + { + yield new ThingListHandler(); + } + + public function getNotificationHandlers(): iterable + { + yield new ThingSeenHandler(); + } + + public function getRequiredExtensions(): array + { + $required = []; + foreach ($this->requires as $id) { + $required[] = new ExtensionIdentifier($id); + } + + return $required; + } +} diff --git a/tests/Unit/Client/Extension/ThingListHandler.php b/tests/Unit/Client/Extension/ThingListHandler.php new file mode 100644 index 000000000..e8e3a1535 --- /dev/null +++ b/tests/Unit/Client/Extension/ThingListHandler.php @@ -0,0 +1,36 @@ + + * + * @author Antoine Bluchet + */ +final class ThingListHandler implements RequestHandlerInterface +{ + public function supports(Request $request): bool + { + return $request instanceof ThingListRequest; + } + + public function handle(Request $request): Response + { + return new Response($request->getId(), new ThingListResult(['a', 'b'])); + } +} diff --git a/tests/Unit/Client/Extension/ThingSeenHandler.php b/tests/Unit/Client/Extension/ThingSeenHandler.php new file mode 100644 index 000000000..a09ee0a2f --- /dev/null +++ b/tests/Unit/Client/Extension/ThingSeenHandler.php @@ -0,0 +1,31 @@ + + */ +final class ThingSeenHandler implements NotificationHandlerInterface +{ + public function supports(Notification $notification): bool + { + return $notification instanceof ThingSeenNotification; + } + + public function handle(Notification $notification): void + { + } +} diff --git a/tests/Unit/Schema/MessageFactoryTest.php b/tests/Unit/Schema/MessageFactoryTest.php index 2c92eb17e..632b5d5d9 100644 --- a/tests/Unit/Schema/MessageFactoryTest.php +++ b/tests/Unit/Schema/MessageFactoryTest.php @@ -551,6 +551,21 @@ public function testLeadingWhitespaceObjectIsParsedAsSingleMessage(): void $this->assertInstanceOf(PingRequest::class, $result); } + #[DataProvider('provideMethods')] + public function testIsCoreMethod(string $method, bool $expected): void + { + $this->assertSame($expected, MessageFactory::isCoreMethod($method)); + } + + public static function provideMethods(): iterable + { + yield 'request' => ['tools/call', true]; + yield 'notification' => ['notifications/cancelled', true]; + yield 'modern-only request' => ['server/discover', true]; + yield 'method without a message class' => ['subscriptions/listen', true]; + yield 'extension method' => ['com.example/things.list', false]; + } + private function invalidInput(string $json): InvalidInputMessageException { try { diff --git a/tests/Unit/Server/BuilderTest.php b/tests/Unit/Server/BuilderTest.php index 32acdf3a1..f267e5eb8 100644 --- a/tests/Unit/Server/BuilderTest.php +++ b/tests/Unit/Server/BuilderTest.php @@ -15,9 +15,13 @@ use Mcp\Schema\Content\TextContent; use Mcp\Schema\Enum\ProtocolVersion; use Mcp\Schema\Exception\InvalidArgumentException as SchemaInvalidArgumentException; +use Mcp\Schema\Exception\UnknownMethodException; use Mcp\Schema\Extension\Apps\McpApps; use Mcp\Schema\Implementation; +use Mcp\Schema\JsonRpc\Notification; +use Mcp\Schema\JsonRpc\Request; use Mcp\Schema\JsonRpc\Response; +use Mcp\Schema\Notification\CancelledNotification; use Mcp\Schema\Request\CallToolRequest; use Mcp\Schema\ServerCapabilities; use Mcp\Schema\Tool; @@ -43,8 +47,11 @@ use Mcp\Tests\Unit\Server\Extension\ThingExtension; use Mcp\Tests\Unit\Server\Extension\ThingListHandler; use Mcp\Tests\Unit\Server\Extension\ThingListRequest; +use Mcp\Tests\Unit\Server\Extension\ThingSeenHandler; +use Mcp\Tests\Unit\Server\Extension\ThingSeenNotification; use Mcp\Tests\Unit\Server\Session\Fixture\RecordingSessionLock; use Mcp\Tests\Unit\Server\Session\Fixture\RecordingSessionStore; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\RunInSeparateProcess; use PHPUnit\Framework\Attributes\TestDox; use PHPUnit\Framework\TestCase; @@ -466,6 +473,83 @@ public function testEnableExtensionRegistersItsHandlers(): void $this->assertContainsOnlyInstancesOf(ThingListHandler::class, $handlers); } + #[TestDox('A notification-handling extension contributes the handlers its notifications reach')] + public function testEnableExtensionRegistersItsNotificationHandlers(): void + { + $builder = Server::builder()->enableExtension(new ThingExtension()); + + $handlers = (new \ReflectionProperty(Builder::class, 'notificationHandlers'))->getValue($builder); + + $this->assertEquals([new ThingSeenHandler()], $handlers); + } + + /** + * @param class-string|class-string $message + */ + #[DataProvider('provideCoreMessages')] + #[TestDox('enableExtension() throws when an extension defines a core method')] + public function testEnableExtensionRejectsCoreMethod(string $message): void + { + $this->expectException(LogicException::class); + $this->expectExceptionMessage(\sprintf('Extension "com.example/things" cannot define "%s"', $message::getMethod())); + + Server::builder()->enableExtension(new ThingExtension(messages: [$message])); + } + + public static function provideCoreMessages(): iterable + { + yield 'request' => [CallToolRequest::class]; + yield 'notification' => [CancelledNotification::class]; + } + + #[TestDox('A rejected extension leaves none of its contributions installed')] + public function testRejectedExtensionLeavesNothingInstalled(): void + { + $builder = Server::builder() + ->setServerInfo('test', '1.0.0') + ->enableExtension(new ThingExtension('com.example/seen', [ThingSeenNotification::class])); + + try { + $builder->enableExtension(new ThingExtension('com.example/things', [ThingListRequest::class, ThingSeenNotification::class])); + $this->fail('The extension should have been rejected.'); + } catch (LogicException) { + } + + $server = $builder->build(); + + $this->assertSame(['com.example/seen'], array_keys($this->extractServerCapabilities($server)->extensions ?? [])); + $this->assertCount(1, (new \ReflectionProperty(Builder::class, 'requestHandlers'))->getValue($builder)); + + $factory = (new \ReflectionProperty(Protocol::class, 'messageFactory')) + ->getValue((new \ReflectionProperty(Server::class, 'protocol'))->getValue($server)); + + $this->expectException(UnknownMethodException::class); + $factory->create('{"jsonrpc":"2.0","id":1,"method":"com.example/things.list"}'); + } + + #[TestDox('build() throws when an enabled extension requires one that is not enabled')] + public function testBuildRejectsExtensionWithMissingDependency(): void + { + $builder = Server::builder()->enableExtension(new ThingExtension(requires: ['com.example/catalog'])); + + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Extension "com.example/things" requires extension "com.example/catalog", which is not enabled.'); + + $builder->build(); + } + + #[TestDox('An extension may be enabled after the extension that requires it')] + public function testDependencyMayBeEnabledAfterTheDependent(): void + { + $server = Server::builder() + ->setServerInfo('test', '1.0.0') + ->enableExtension(new ThingExtension(requires: ['com.example/catalog'])) + ->enableExtension(new ThingExtension('com.example/catalog', [])) + ->build(); + + $this->assertSame(['com.example/things', 'com.example/catalog'], array_keys($this->extractServerCapabilities($server)->extensions ?? [])); + } + #[TestDox('Lazy loading (default) advertises tools from configured sources without running loaders')] public function testLazyLoadingAdvertisesFromConfiguredSourcesWithoutLoading(): void { diff --git a/tests/Unit/Server/ClientGatewayTest.php b/tests/Unit/Server/ClientGatewayTest.php index 3d4453d94..f818ae003 100644 --- a/tests/Unit/Server/ClientGatewayTest.php +++ b/tests/Unit/Server/ClientGatewayTest.php @@ -35,6 +35,7 @@ use Mcp\Server\Session\SessionInterface; use Mcp\Server\Suspension\NotificationSuspension; use Mcp\Server\Suspension\RequestSuspension; +use Mcp\Tests\Unit\Server\Extension\ThingListRequest; use PHPUnit\Framework\TestCase; use Symfony\Component\Uid\Uuid; @@ -113,6 +114,26 @@ public function testSupportsElicitationUrlReflectsTheSubCapability(): void $this->assertFalse($this->gatewayFor(['elicitation' => ['form' => []]])->supportsElicitationUrl()); } + public function testRequestSendsACustomRequestToItsSessionAndReturnsTheAnswer(): void + { + $id = Uuid::v4(); + $session = $this->createMock(SessionInterface::class); + $session->method('getId')->willReturn($id); + $gateway = new ClientGateway($session); + $answer = $this->response(['things' => ['a']]); + + $fiber = new \Fiber(static fn (): Response|Error => $gateway->request(new ThingListRequest(), 5)); + $suspend = $fiber->start(); + + $this->assertInstanceOf(RequestSuspension::class, $suspend); + $this->assertInstanceOf(ThingListRequest::class, $suspend->request); + $this->assertSame($id->toRfc4122(), $suspend->sessionId); + + $fiber->resume($answer); + + $this->assertSame($answer, $fiber->getReturn()); + } + public function testElicitUrlSendsAUrlModeRequest(): void { $gateway = $this->gatewayFor(['elicitation' => ['url' => []]]); diff --git a/tests/Unit/Server/Extension/ThingExtension.php b/tests/Unit/Server/Extension/ThingExtension.php index 102a6f09e..7092fda25 100644 --- a/tests/Unit/Server/Extension/ThingExtension.php +++ b/tests/Unit/Server/Extension/ThingExtension.php @@ -11,17 +11,26 @@ namespace Mcp\Tests\Unit\Server\Extension; +use Mcp\Schema\Extension\DependentExtensionInterface; use Mcp\Schema\Extension\ExtensionIdentifier; +use Mcp\Schema\JsonRpc\Notification; +use Mcp\Schema\JsonRpc\Request; use Mcp\Server\Extension\ServerExtensionInterface; /** - * A minimal extension: an identifier, a capability payload, and one method it + * A minimal extension: an identifier, a capability payload, and the methods it * defines and serves. */ -final class ThingExtension implements ServerExtensionInterface +final class ThingExtension implements ServerExtensionInterface, DependentExtensionInterface { + /** + * @param list|class-string> $messages + * @param list $requires + */ public function __construct( private readonly string $id = 'com.example/things', + private readonly array $messages = [ThingListRequest::class, ThingSeenNotification::class], + private readonly array $requires = [], ) { } @@ -37,11 +46,26 @@ public function getCapabilities(): array public function getMessages(): array { - return [ThingListRequest::class]; + return $this->messages; } public function getRequestHandlers(): iterable { yield new ThingListHandler(); } + + public function getNotificationHandlers(): iterable + { + yield new ThingSeenHandler(); + } + + public function getRequiredExtensions(): array + { + $required = []; + foreach ($this->requires as $id) { + $required[] = new ExtensionIdentifier($id); + } + + return $required; + } } diff --git a/tests/Unit/Server/Extension/ThingSeenHandler.php b/tests/Unit/Server/Extension/ThingSeenHandler.php new file mode 100644 index 000000000..7cd2b7710 --- /dev/null +++ b/tests/Unit/Server/Extension/ThingSeenHandler.php @@ -0,0 +1,31 @@ + + */ +final class ThingSeenHandler implements NotificationHandlerInterface +{ + public function supports(Notification $notification): bool + { + return $notification instanceof ThingSeenNotification; + } + + public function handle(Notification $notification, SessionInterface $session): void + { + } +} diff --git a/tests/Unit/Server/Extension/ThingSeenNotification.php b/tests/Unit/Server/Extension/ThingSeenNotification.php new file mode 100644 index 000000000..114c7be87 --- /dev/null +++ b/tests/Unit/Server/Extension/ThingSeenNotification.php @@ -0,0 +1,35 @@ + + */ +final class ThingSeenNotification extends Notification +{ + public static function getMethod(): string + { + return 'com.example/things.seen'; + } + + protected static function fromParams(?array $params): static + { + return new self(); + } + + protected function getParams(): ?array + { + return null; + } +}