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
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
------
Expand Down
82 changes: 76 additions & 6 deletions docs/advanced/extensions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion docs/advanced/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
84 changes: 83 additions & 1 deletion src/Client/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -39,6 +44,15 @@ final class Builder

/** @var array<string, array<string, mixed>> */
private array $extensions = [];

/** @var array<string, string> RPC method to the extension identifier defining it */
private array $extensionMethods = [];

/** @var list<class-string<Request>|class-string<Notification>> */
private array $extensionMessages = [];

/** @var array<string, list<string>> 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;
Expand Down Expand Up @@ -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
{
Expand All @@ -111,7 +135,56 @@ public function enableExtension(ExtensionInterface ...$extensions): self
throw new LogicException(\sprintf('Extension "%s" is already enabled.', $id));
}

/** @var array<string, class-string<Request>|class-string<Notification>> $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;
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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,
);

Expand Down
20 changes: 19 additions & 1 deletion src/Client/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<mixed>
*
* @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()) {
Expand Down
40 changes: 40 additions & 0 deletions src/Client/Extension/ClientExtensionInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?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\Extension;

use Mcp\Client\Handler\Notification\NotificationHandlerInterface;
use Mcp\Client\Handler\Request\RequestHandlerInterface;
use Mcp\Schema\Extension\ExtensionInterface;
use Mcp\Schema\JsonRpc\ResultInterface;

/**
* An extension that answers the requests and receives the notifications it
* defines when enabled on a client.
*
* @author Antoine Bluchet <soyuka@gmail.com>
*/
interface ClientExtensionInterface extends ExtensionInterface
{
/**
* The handlers answering the server requests of {@see self::getMessages()}.
*
* @return iterable<RequestHandlerInterface<ResultInterface>>
*/
public function getRequestHandlers(): iterable;

/**
* The handlers receiving the server notifications of {@see self::getMessages()}.
*
* @return iterable<NotificationHandlerInterface>
*/
public function getNotificationHandlers(): iterable;
}
29 changes: 29 additions & 0 deletions src/Schema/Extension/DependentExtensionInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?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\Schema\Extension;

/**
* An extension that only works alongside other extensions enabled on the same
* client or server.
*
* The requirement is local: it is checked when the client or server is built,
* whatever order the extensions were enabled in, and is never sent to the peer.
*
* @author Antoine Bluchet <soyuka@gmail.com>
*/
interface DependentExtensionInterface extends ExtensionInterface
{
/**
* @return list<ExtensionIdentifier>
*/
public function getRequiredExtensions(): array;
}
Loading