Repository navigation
[Server] Add outgoing (elicitation, sampling) request and client response events #564
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
chr-hertel
merged 2 commits into
modelcontextprotocol:main
from
chr-hertel:pr-386-elicit-lifecycle-events
Oct 10, 2026
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| <?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\Event; | ||
|
|
||
| use Mcp\Schema\JsonRpc\Error; | ||
| use Mcp\Schema\JsonRpc\Response; | ||
| use Mcp\Server\Session\SessionInterface; | ||
|
|
||
| /** | ||
| * Event dispatched when the server receives a client response to a prior outgoing request. | ||
| * | ||
| * @author Olivier Mouren <mouren.olivier@gmail.com> | ||
| */ | ||
| final class ClientResponseEvent | ||
| { | ||
| /** | ||
| * @param Response<mixed>|Error $response | ||
| */ | ||
| public function __construct( | ||
| private readonly Response|Error $response, | ||
| private readonly SessionInterface $session, | ||
| ) { | ||
| } | ||
|
|
||
| /** | ||
| * @return Response<mixed>|Error | ||
| */ | ||
| public function getResponse(): Response|Error | ||
| { | ||
| return $this->response; | ||
| } | ||
|
|
||
| public function getSession(): SessionInterface | ||
| { | ||
| return $this->session; | ||
| } | ||
|
|
||
| public function getId(): string|int|null | ||
| { | ||
| return $this->response->getId(); | ||
| } | ||
|
|
||
| public function isError(): bool | ||
| { | ||
| return $this->response instanceof Error; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,50 @@ | ||
| <?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\Event; | ||
|
|
||
| use Mcp\Schema\JsonRpc\Request; | ||
| use Mcp\Server\Session\SessionInterface; | ||
|
|
||
| /** | ||
| * Event dispatched when the server sends a request to the client (e.g. elicitation/create, sampling/createMessage). | ||
| * | ||
| * @author Olivier Mouren <mouren.olivier@gmail.com> | ||
| */ | ||
| final class ServerRequestEvent | ||
| { | ||
| public function __construct( | ||
| private readonly Request $request, | ||
| private readonly int $timeout, | ||
| private readonly SessionInterface $session, | ||
| ) { | ||
| } | ||
|
|
||
| public function getRequest(): Request | ||
| { | ||
| return $this->request; | ||
| } | ||
|
|
||
| public function getSession(): SessionInterface | ||
| { | ||
| return $this->session; | ||
| } | ||
|
|
||
| public function getTimeout(): int | ||
| { | ||
| return $this->timeout; | ||
| } | ||
|
|
||
| public function getMethod(): string | ||
| { | ||
| return $this->request::getMethod(); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -11,10 +11,12 @@ | |
|
|
||
| namespace Mcp\Server; | ||
|
|
||
| use Mcp\Event\ClientResponseEvent; | ||
| use Mcp\Event\ErrorEvent; | ||
| use Mcp\Event\NotificationEvent; | ||
| use Mcp\Event\RequestEvent; | ||
| use Mcp\Event\ResponseEvent; | ||
| use Mcp\Event\ServerRequestEvent; | ||
| use Mcp\Exception\InvalidInputMessageException; | ||
| use Mcp\Exception\RuntimeException; | ||
| use Mcp\JsonRpc\MessageFactory; | ||
|
|
@@ -335,14 +337,22 @@ private function handleRequest(TransportInterface $transport, Request $request, | |
| try { | ||
| $shim = $this->inputRequiredShim; | ||
| $codec = $this->requestStateCodec; | ||
| $dispatchResult = $this->dispatchResult(...); | ||
| $errorForThrowable = $this->errorForThrowable(...); | ||
|
|
||
| // One fiber for the whole exchange: with the shim, the handler | ||
| // re-enters inside it each round rather than needing a new one. | ||
| // Handled in the fiber, as the transport resumes it outside the catch below. | ||
| /** @var McpFiber $fiber */ | ||
| $fiber = new \Fiber(static function () use ($handler, $request, $session, $shim, $codec): Response|Error { | ||
| $result = $handler->handle($request, $session); | ||
| $fiber = new \Fiber(static function () use ($handler, $request, $session, $shim, $codec, $dispatchResult, $errorForThrowable): Response|Error { | ||
| try { | ||
| $result = $handler->handle($request, $session); | ||
| $result = $shim?->fulfill($result, $handler, $request, $session, $codec) ?? $result; | ||
| } catch (\Throwable $e) { | ||
| return $errorForThrowable($e, $request, $session); | ||
| } | ||
|
|
||
| return $shim?->fulfill($result, $handler, $request, $session, $codec) ?? $result; | ||
| return $dispatchResult($result, $request, $session); | ||
| }); | ||
|
|
||
| $result = $fiber->start(); | ||
|
|
@@ -379,33 +389,10 @@ private function handleRequest(TransportInterface $transport, Request $request, | |
|
|
||
| return; | ||
| } | ||
| $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); | ||
| $this->sendResponse($transport, $fiber->getReturn(), $session); | ||
| } catch (\Throwable $e) { | ||
| $this->logger->error(\sprintf('Uncaught exception: %s', $e->getMessage()), ['exception' => $e]); | ||
|
|
||
| $error = Error::forInternalError(self::INTERNAL_ERROR_MESSAGE, $request->getId()); | ||
| $errorEvent = $this->dispatchEvent(new ErrorEvent($error, $request, $session, $e)); | ||
| $error = $errorEvent->getError(); | ||
|
|
||
| $this->sendResponse($transport, $error, $session); | ||
| $this->sendResponse($transport, $this->errorForThrowable($e, $request, $session), $session); | ||
| } | ||
|
|
||
| break; | ||
|
|
@@ -435,6 +422,16 @@ private function handleResponse(Response|Error $response, SessionInterface $sess | |
| return; | ||
| } | ||
|
|
||
| // Request IDs are ints: a string ID like "1000" would otherwise match through PHP's key coercion. | ||
| $pending = \is_int($messageId) ? $session->get(self::SESSION_PENDING_REQUESTS, [])[$messageId] ?? null : null; | ||
| if (!\is_array($pending) || $this->hasTimedOut($pending)) { | ||
| $this->logger->warning('Received a client response for an unknown or timed out request ID.', ['message_id' => $messageId]); | ||
|
|
||
| return; | ||
|
Comment on lines
+427
to
+430
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Filed #578 for this |
||
| } | ||
|
|
||
| $this->dispatchEvent(new ClientResponseEvent($response, $session)); | ||
|
|
||
| $session->set(self::SESSION_RESPONSES.".{$messageId}", $response->jsonSerialize()); | ||
| $session->forget(self::SESSION_ACTIVE_REQUEST_META); | ||
|
|
||
|
|
@@ -474,6 +471,8 @@ public function sendRequest(Request $request, int $timeout, SessionInterface $se | |
|
|
||
| $requestWithId = $request->withId($requestId); | ||
|
|
||
| $this->dispatchEvent(new ServerRequestEvent($requestWithId, $timeout, $session)); | ||
|
|
||
| $this->logger->info('Queueing server request to client', [ | ||
| 'request_id' => $requestId, | ||
| 'method' => $request::getMethod(), | ||
|
|
@@ -636,6 +635,14 @@ public function checkResponse(int $requestId, Uuid $sessionId): Response|Error|n | |
| } | ||
| } | ||
|
|
||
| /** | ||
| * @param array<mixed> $pending | ||
| */ | ||
| private function hasTimedOut(array $pending): bool | ||
| { | ||
| return time() - (int) ($pending['timestamp'] ?? 0) >= (int) ($pending['timeout'] ?? 120); | ||
| } | ||
|
|
||
| /** | ||
| * Get pending requests for a session. | ||
| * | ||
|
|
@@ -723,6 +730,45 @@ private function getAwaitedPendingRequests(?TransportInterface $transport, Uuid | |
| return array_intersect_key($this->getPendingRequests($sessionId), [$requestId => true]); | ||
| } | ||
|
|
||
| /** | ||
| * @param Response<mixed>|Error $result | ||
| * | ||
| * @return Response<mixed>|Error | ||
| */ | ||
| private function dispatchResult(Response|Error $result, Request $request, SessionInterface $session): Response|Error | ||
| { | ||
| // A resumed fiber runs this outside handleRequest()'s catch. | ||
| try { | ||
| if ($result instanceof Response) { | ||
| return $this->dispatchEvent(new ResponseEvent($result, $request, $session))->getResponse(); | ||
| } | ||
|
|
||
| return $this->dispatchEvent(new ErrorEvent($result, $request, $session, null))->getError(); | ||
| } catch (\Throwable $e) { | ||
| return $this->errorForThrowable($e, $request, $session); | ||
| } | ||
| } | ||
|
|
||
| private function errorForThrowable(\Throwable $e, Request $request, SessionInterface $session): Error | ||
| { | ||
| if ($e instanceof \InvalidArgumentException) { | ||
| $this->logger->warning(\sprintf('Invalid argument: %s', $e->getMessage()), ['exception' => $e]); | ||
| $error = Error::forInvalidParams($e->getMessage(), $request->getId()); | ||
| } else { | ||
| $this->logger->error(\sprintf('Uncaught exception: %s', $e->getMessage()), ['exception' => $e]); | ||
| $error = Error::forInternalError(self::INTERNAL_ERROR_MESSAGE, $request->getId()); | ||
| } | ||
|
|
||
| try { | ||
| return $this->dispatchEvent(new ErrorEvent($error, $request, $session, $e))->getError(); | ||
| } catch (\Throwable $listenerError) { | ||
| // Last resort: the error still has to reach the client. | ||
| $this->logger->error('Error event listener failed.', ['exception' => $listenerError]); | ||
|
|
||
| return $error; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * @param array<int, mixed> $messages | ||
| */ | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.