feat(server): add server lifecycle events (#175)

Signed-off-by: Edouard Courty <edouard.courty2@gmail.com>
This commit is contained in:
Edouard Courty 2026-02-23 22:40:43 +01:00 • committed by GitHub
commit 158e64627f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 1008 additions and 0 deletions

61
src/Event/ErrorEvent.php Normal file
View file

@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
/*
* 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\Event;
use Mcp\Schema\JsonRpc\Error;
use Mcp\Schema\JsonRpc\Request;
use Mcp\Server\Session\SessionInterface;
/**
* Event dispatched when an error occurs during request processing.
*
* Listeners can modify the error before it's sent to the client.
*
* @author Edouard Courty <edouard.courty2@gmail.com>
*/
final class ErrorEvent
{
public function __construct(
private Error $error,
private readonly Request $request,
private readonly SessionInterface $session,
private readonly ?\Throwable $throwable,
) {
}
public function getError(): Error
{
return $this->error;
}
public function setError(Error $error): void
{
$this->error = $error;
}
public function getRequest(): Request
{
return $this->request;
}
public function getThrowable(): ?\Throwable
{
return $this->throwable;
}
public function getSession(): SessionInterface
{
return $this->session;
}
}

View file

@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
/*
* 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\Event;
use Mcp\Schema\JsonRpc\Notification;
use Mcp\Server\Session\SessionInterface;
/**
* Event dispatched when any notification is received from the client.
*
* Listeners can modify the notification before it's processed by handlers.
*
* @author Edouard Courty <edouard.courty2@gmail.com>
*/
final class NotificationEvent
{
public function __construct(
private Notification $notification,
private readonly SessionInterface $session,
) {
}
public function getNotification(): Notification
{
return $this->notification;
}
public function setNotification(Notification $notification): void
{
$this->notification = $notification;
}
public function getSession(): SessionInterface
{
return $this->session;
}
public function getMethod(): string
{
return $this->notification::getMethod();
}
}

View file

@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
/*
* 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\Event;
use Mcp\Schema\JsonRpc\Request;
use Mcp\Server\Session\SessionInterface;
/**
* Event dispatched when any request is received from the client.
*
* Listeners can modify the request before it's processed by handlers.
*
* @author Edouard Courty <edouard.courty2@gmail.com>
*/
final class RequestEvent
{
public function __construct(
private Request $request,
private readonly SessionInterface $session,
) {
}
public function getRequest(): Request
{
return $this->request;
}
public function setRequest(Request $request): void
{
$this->request = $request;
}
public function getSession(): SessionInterface
{
return $this->session;
}
public function getMethod(): string
{
return $this->request::getMethod();
}
}

View file

@ -0,0 +1,69 @@
<?php
declare(strict_types=1);
/*
* 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\Event;
use Mcp\Schema\JsonRpc\Request;
use Mcp\Schema\JsonRpc\Response;
use Mcp\Server\Session\SessionInterface;
/**
* Event dispatched when a successful response is ready to be sent to the client.
*
* Listeners can modify the response before it's sent.
*
* @author Edouard Courty <edouard.courty2@gmail.com>
*/
final class ResponseEvent
{
/**
* @param Response<mixed> $response
*/
public function __construct(
private Response $response,
private readonly Request $request,
private readonly SessionInterface $session,
) {
}
/**
* @return Response<mixed>
*/
public function getResponse(): Response
{
return $this->response;
}
/**
* @param Response<mixed> $response
*/
public function setResponse(Response $response): void
{
$this->response = $response;
}
public function getRequest(): Request
{
return $this->request;
}
public function getSession(): SessionInterface
{
return $this->session;
}
public function getMethod(): string
{
return $this->request::getMethod();
}
}

View file

@ -564,6 +564,7 @@ final class Builder
sessionFactory: $sessionFactory,
sessionStore: $sessionStore,
logger: $logger,
eventDispatcher: $this->eventDispatcher,
);
return new Server($protocol, $logger);

View file

@ -11,6 +11,10 @@
namespace Mcp\Server;
use Mcp\Event\ErrorEvent;
use Mcp\Event\NotificationEvent;
use Mcp\Event\RequestEvent;
use Mcp\Event\ResponseEvent;
use Mcp\Exception\InvalidInputMessageException;
use Mcp\JsonRpc\MessageFactory;
use Mcp\Schema\JsonRpc\Error;
@ -25,6 +29,7 @@ use Mcp\Server\Session\SessionFactoryInterface;
use Mcp\Server\Session\SessionInterface;
use Mcp\Server\Session\SessionStoreInterface;
use Mcp\Server\Transport\TransportInterface;
use Psr\EventDispatcher\EventDispatcherInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Symfony\Component\Uid\Uuid;
@ -68,6 +73,7 @@ class Protocol
private readonly SessionFactoryInterface $sessionFactory,
private readonly SessionStoreInterface $sessionStore,
private readonly LoggerInterface $logger = new NullLogger(),
private readonly ?EventDispatcherInterface $eventDispatcher = null,
) {
}
@ -151,6 +157,20 @@ class Protocol
$this->sendResponse($transport, $error, $session);
}
/**
* Dispatches an event through the event dispatcher if available.
*
* @template T of object
*
* @param T $event
*
* @return T
*/
private function dispatchEvent(object $event): object
{
return $this->eventDispatcher?->dispatch($event) ?? $event;
}
/**
* Handle a request from the transport.
*
@ -162,6 +182,9 @@ class Protocol
$session->set(self::SESSION_ACTIVE_REQUEST_META, $request->getMeta());
$event = $this->dispatchEvent(new RequestEvent($request, $session));
$request = $event->getRequest();
$handlerFound = false;
foreach ($this->requestHandlers as $handler) {
@ -195,16 +218,30 @@ class Protocol
}
$finalResult = $fiber->getReturn();
if ($finalResult instanceof Response) {
$responseEvent = $this->dispatchEvent(new ResponseEvent($finalResult, $request, $session));
$finalResult = $responseEvent->getResponse();
} elseif ($finalResult instanceof Error) {
$errorEvent = $this->dispatchEvent(new ErrorEvent($finalResult, $request, $session, null));
$finalResult = $errorEvent->getError();
}
$this->sendResponse($transport, $finalResult, $session);
} catch (\InvalidArgumentException $e) {
$this->logger->warning(\sprintf('Invalid argument: %s', $e->getMessage()), ['exception' => $e]);
$error = Error::forInvalidParams($e->getMessage(), $request->getId());
$errorEvent = $this->dispatchEvent(new ErrorEvent($error, $request, $session, $e));
$error = $errorEvent->getError();
$this->sendResponse($transport, $error, $session);
} catch (\Throwable $e) {
$this->logger->error(\sprintf('Uncaught exception: %s', $e->getMessage()), ['exception' => $e]);
$error = Error::forInternalError($e->getMessage(), $request->getId());
$errorEvent = $this->dispatchEvent(new ErrorEvent($error, $request, $session, $e));
$error = $errorEvent->getError();
$this->sendResponse($transport, $error, $session);
}
@ -213,6 +250,9 @@ class Protocol
if (!$handlerFound) {
$error = Error::forMethodNotFound(\sprintf('No handler found for method "%s".', $request::getMethod()), $request->getId());
$errorEvent = $this->dispatchEvent(new ErrorEvent($error, $request, $session, null));
$error = $errorEvent->getError();
$this->sendResponse($transport, $error, $session);
}
}
@ -238,6 +278,9 @@ class Protocol
{
$this->logger->info('Handling notification.', ['notification' => $notification]);
$event = $this->dispatchEvent(new NotificationEvent($notification, $session));
$notification = $event->getNotification();
foreach ($this->notificationHandlers as $handler) {
if (!$handler->supports($notification)) {
continue;