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
17 changes: 17 additions & 0 deletions docs/advanced/custom-handlers.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,23 @@ interface RequestHandlerInterface
- `supports()` decides if the handler should process the incoming request
- `handle()` **must** return a `Response` (on success) or an `Error` (on failure)

## Receiving Request Middleware

Register an implementation of `Mcp\Server\Middleware\RequestMiddlewareInterface` with
`Server::builder()->addReceivingMiddleware($middleware)` to wrap built-in and custom request handlers in
both protocol eras. Middleware runs after the SDK parses the request and dispatches its request event,
and before it selects a handler. The first registered middleware runs first and gets the result last.

Call `$next->handle($request, $session)` to continue, or return a `Response` or an `Error` to skip
the inner layers and the handler. A replacement request must preserve its class and ID. Pass the same
session and use the request ID on the response. To add request metadata, pass a copy made with
`$request->withMeta([...($request->getMeta() ?? []), 'com.example/source' => 'middleware'])`.

Use `try` / `finally` to clean up when processing ends. On revision `2026-07-28`, an unanswered gateway
elicitation returns an `InputRequiredResult` through the middleware. On retry the middleware runs again.
Notifications emitted by the handler can stream while it runs. The SDK handles `subscriptions/listen` and
incoming notifications separately.

## Notification Handlers

Handle JSON-RPC notifications (messages without an `id` that don't expect a response). Notification handlers **do not**
Expand Down
15 changes: 15 additions & 0 deletions src/Server/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,9 @@ final class Builder
*/
private ?array $parts = null;

/** @var list<Middleware\RequestMiddlewareInterface> */
private array $receivingMiddleware = [];

/**
* Sets the server's identity. Required.
*
Expand Down Expand Up @@ -533,6 +536,16 @@ public function enableExtension(ExtensionInterface ...$extensions): self
return $this;
}

/**
* The first registered middleware is the outermost layer.
*/
public function addReceivingMiddleware(Middleware\RequestMiddlewareInterface $middleware): self
{
$this->receivingMiddleware[] = $middleware;

return $this;
}

/**
* Register a single custom method handler.
*
Expand Down Expand Up @@ -1050,6 +1063,7 @@ public function build(): Server
fiberScheduler: $this->fiberScheduler,
fiberContext: $this->fiberContext,
sessionless: !$this->sessions,
receivingMiddleware: $this->receivingMiddleware,
);

$modernVersions = $this->modernVersions ?? ProtocolVersion::modernVersions();
Expand Down Expand Up @@ -1102,6 +1116,7 @@ public function buildStateless(array $supportedVersions = [ProtocolVersion::V202
requestStateBinder: $this->requestStateBinder,
fiberScheduler: $this->fiberScheduler,
fiberContext: $this->fiberContext,
receivingMiddleware: $this->receivingMiddleware,
);
}

Expand Down
75 changes: 75 additions & 0 deletions src/Server/Middleware/RequestMiddlewareHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
<?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\Server\Middleware;

use Mcp\Schema\JsonRpc\Error;
use Mcp\Schema\JsonRpc\Request;
use Mcp\Schema\JsonRpc\Response;
use Mcp\Schema\JsonRpc\ResultInterface;
use Mcp\Server\Exception\LogicException;
use Mcp\Server\Handler\Request\RequestHandlerInterface;
use Mcp\Server\Session\SessionInterface;

/**
* @internal
*
* @implements RequestHandlerInterface<ResultInterface|array<string, mixed>>
*
* @author OpenAI
*/
final class RequestMiddlewareHandler implements RequestHandlerInterface
{
/**
* @param \Closure(Request, SessionInterface): (Response<ResultInterface|array<string, mixed>>|Error) $handle
*/
private function __construct(
private readonly Request $original,
private readonly SessionInterface $session,
private readonly \Closure $handle,
) {
}

/**
* @param list<RequestMiddlewareInterface> $middleware
* @param \Closure(Request, SessionInterface): (Response<ResultInterface|array<string, mixed>>|Error) $terminal
*/
public static function wrap(array $middleware, Request $request, SessionInterface $session, \Closure $terminal): self
{
$handler = new self($request, $session, $terminal);
foreach (array_reverse($middleware) as $layer) {
$next = $handler;
$handler = new self($request, $session, static fn (Request $request, SessionInterface $session): Response|Error => $layer->processRequest($request, $session, $next));
}

return $handler;
}

public function supports(Request $request): bool
{
return $this->original::class === $request::class && $request->getId() === $this->original->getId();
}

public function handle(Request $request, SessionInterface $session): Response|Error
{
if (!$this->supports($request) || $session !== $this->session) {
throw new LogicException('Request middleware must preserve the request type, id and session.');
}

$result = ($this->handle)($request, $session);

if ($result->getId() !== $request->getId()) {
throw new LogicException('Request middleware must preserve the response id.');
}

return $result;
}
}
34 changes: 34 additions & 0 deletions src/Server/Middleware/RequestMiddlewareInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?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\Server\Middleware;

use Mcp\Schema\JsonRpc\Error;
use Mcp\Schema\JsonRpc\Request;
use Mcp\Schema\JsonRpc\Response;
use Mcp\Schema\JsonRpc\ResultInterface;
use Mcp\Server\Handler\Request\RequestHandlerInterface;
use Mcp\Server\Session\SessionInterface;

/**
* Wraps a request received by the server and the response it produces.
*
* @author OpenAI
*/
interface RequestMiddlewareInterface
{
/**
* @param RequestHandlerInterface<ResultInterface|array<string, mixed>> $next
*
* @return Response<ResultInterface|array<string, mixed>>|Error
*/
public function processRequest(Request $request, SessionInterface $session, RequestHandlerInterface $next): Response|Error;
}
19 changes: 18 additions & 1 deletion src/Server/Protocol.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@
use Mcp\Server\Fiber\HandlerFibers;
use Mcp\Server\Handler\Notification\NotificationHandlerInterface;
use Mcp\Server\Handler\Request\RequestHandlerInterface;
use Mcp\Server\Middleware\RequestMiddlewareHandler;
use Mcp\Server\Middleware\RequestMiddlewareInterface;
use Mcp\Server\Session\EphemeralSession;
use Mcp\Server\Session\EphemeralSessionInterface;
use Mcp\Server\Session\SessionInterface;
Expand Down Expand Up @@ -139,6 +141,7 @@ class Protocol
/**
* @param array<int, RequestHandlerInterface<ResultInterface|array<string, mixed>>> $requestHandlers
* @param array<int, NotificationHandlerInterface> $notificationHandlers
* @param list<RequestMiddlewareInterface> $receivingMiddleware
* @param bool $sessionless serve each handshake-era request over Streamable HTTP
* on a session of its own, without a `Mcp-Session-Id`
*/
Expand All @@ -155,6 +158,7 @@ public function __construct(
private readonly ?FiberSchedulerInterface $fiberScheduler = null,
private readonly ?FiberContextInterface $fiberContext = null,
private readonly bool $sessionless = false,
private readonly array $receivingMiddleware = [],
) {
$this->sessionLock = null !== $sessionLock && null !== $fiberScheduler ? new EventLoopSessionLock($sessionLock, $fiberScheduler) : $sessionLock;
$this->awaitedRequestIds = new \WeakMap();
Expand Down Expand Up @@ -447,9 +451,22 @@ private function handleRequest(TransportInterface $transport, Request $request,
return;
}

$handlers = $this->requestHandlers;
if ([] !== $this->receivingMiddleware) {
$handlers = [RequestMiddlewareHandler::wrap($this->receivingMiddleware, $request, $session, static function (Request $request, SessionInterface $session) use ($handlers): Response|Error {
foreach ($handlers as $handler) {
if ($handler->supports($request)) {
return $handler->handle($request, $session);
}
}

return Error::forMethodNotFound(\sprintf('No handler found for method "%s".', $request::getMethod()), $request->getId());
})];
}

$handlerFound = false;

foreach ($this->requestHandlers as $handler) {
foreach ($handlers as $handler) {
if (!$handler->supports($request)) {
continue;
}
Expand Down
50 changes: 42 additions & 8 deletions src/Server/Stateless/StatelessProtocol.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,12 @@
use Mcp\Server\Fiber\FiberSchedulerInterface;
use Mcp\Server\Fiber\HandlerFibers;
use Mcp\Server\Handler\Request\RequestHandlerInterface;
use Mcp\Server\Middleware\RequestMiddlewareHandler;
use Mcp\Server\Middleware\RequestMiddlewareInterface;
use Mcp\Server\Protocol;
use Mcp\Server\Session\InMemorySessionStore;
use Mcp\Server\Session\Session;
use Mcp\Server\Session\SessionInterface;
use Mcp\Server\Subscription\NotificationBusInterface;
use Mcp\Server\Suspension\NotificationSuspension;
use Mcp\Server\Suspension\RequestSuspension;
Expand Down Expand Up @@ -104,8 +107,9 @@ final class StatelessProtocol

/**
* @param iterable<RequestHandlerInterface<ResultInterface>> $requestHandlers
* @param list<RequestMiddlewareInterface> $receivingMiddleware
* @param list<ProtocolVersion> $supportedVersions
* @param array<string, string> $extensionMethods RPC method to the extension identifier defining it
* @param array<string, string> $extensionMethods RPC method to the extension identifier defining it
*/
public function __construct(
private readonly iterable $requestHandlers,
Expand All @@ -124,6 +128,7 @@ public function __construct(
private readonly ?RequestStateBinderInterface $requestStateBinder = null,
private readonly ?FiberSchedulerInterface $fiberScheduler = null,
private readonly ?FiberContextInterface $fiberContext = null,
private readonly array $receivingMiddleware = [],
) {
$this->codec = $codec ?? new Rev2026Codec($configuration->serverInfo, $cachePolicy);

Expand Down Expand Up @@ -541,7 +546,28 @@ private function dispatch(string $method, ?array $params, string $body, RequestM

$request = $this->dispatchEvent(new RequestEvent($request, $session))->getRequest();

foreach ($this->requestHandlers as $handler) {
$unhandled = null;
$handlers = $this->requestHandlers;
if ([] !== $this->receivingMiddleware) {
$handlers = [RequestMiddlewareHandler::wrap($this->receivingMiddleware, $request, $session, function (Request $request, SessionInterface $session) use ($meta, $method, $id, &$unhandled): Response|Error {
foreach ($this->requestHandlers as $handler) {
if (!$handler->supports($request)) {
continue;
}

$run = $this->run($handler, $request, $session, $meta);
foreach ($run as $notification) {
HandlerFibers::suspend(new NotificationSuspension($notification, $session->getId()->toRfc4122()));
}

return $run->getReturn();
}

return $unhandled = $this->unknownMethod($method, $id);
})];
}

foreach ($handlers as $handler) {
if (!$handler->supports($request)) {
continue;
}
Expand Down Expand Up @@ -581,7 +607,7 @@ private function dispatch(string $method, ?array $params, string $body, RequestM
}

if ($result instanceof Error) {
return StatelessResult::error($this->dispatchError($result, $request, $session), 400);
return StatelessResult::error($this->dispatchError($result, $request, $session), $result === $unhandled ? 404 : 400);
}

if (null !== $capabilityError = $this->checkInputRequests($result->result, $meta, $method, $id)) {
Expand Down Expand Up @@ -688,11 +714,11 @@ private function unknownMethod(string $method, string|int|null $id): Error
* {@see \Mcp\Server\ClientGateway::elicit()}; see {@see ElicitationReplay}
* for what it costs.
*
* @param RequestHandlerInterface<ResultInterface> $handler
* @param RequestHandlerInterface<ResultInterface|array<string, mixed>> $handler
*
* @return \Generator<int, Notification, null, Response<ResultInterface>|Error>
*/
private function run(RequestHandlerInterface $handler, Request $request, Session $session, RequestMeta $meta): \Generator
private function run(RequestHandlerInterface $handler, Request $request, SessionInterface $session, RequestMeta $meta): \Generator
{
$fiber = HandlerFibers::create(static fn (): mixed => $handler->handle($request, $session), $this->fiberScheduler, logger: $this->logger, context: $this->fiberContext);
$input = $session->get(InputContext::class);
Expand Down Expand Up @@ -731,10 +757,18 @@ private function run(RequestHandlerInterface $handler, Request $request, Session
$suspended = HandlerFibers::resume($fiber);
}

/** @var Response<ResultInterface>|Error $return */
$return = $fiber->getReturn();
$result = $fiber->getReturn();
if ($result instanceof Error) {
return $result;
}
if (!$result->result instanceof ResultInterface) {
throw new LogicException('Stateless request handlers and middleware must return a ResultInterface result.');
}

return $return;
/** @var Response<ResultInterface> $response */
$response = $result;

return $response;
}

/**
Expand Down
Loading