|
25 | 25 | use Mcp\Exception\PromptNotFoundException; |
26 | 26 | use Mcp\Exception\ResourceNotFoundException; |
27 | 27 | use Mcp\Exception\ToolNotFoundException; |
| 28 | +use Mcp\Schema\Notification\ResourceUpdatedNotification; |
28 | 29 | use Mcp\Schema\Page; |
29 | 30 | use Mcp\Schema\Prompt; |
30 | 31 | use Mcp\Schema\Resource; |
31 | 32 | use Mcp\Schema\ResourceTemplate; |
32 | 33 | use Mcp\Schema\Tool; |
| 34 | +use Mcp\Server\Protocol; |
| 35 | +use Mcp\Server\Session\SessionInterface; |
33 | 36 | use Psr\EventDispatcher\EventDispatcherInterface; |
34 | 37 | use Psr\Log\LoggerInterface; |
35 | 38 | use Psr\Log\NullLogger; |
@@ -61,6 +64,11 @@ final class Registry implements RegistryInterface |
61 | 64 | */ |
62 | 65 | private array $resourceTemplates = []; |
63 | 66 |
|
| 67 | + /** |
| 68 | + * @var array<string, array<string, SessionInterface>> |
| 69 | + */ |
| 70 | + private array $resourceSubscriptions = []; |
| 71 | + |
64 | 72 | public function __construct( |
65 | 73 | private readonly ?EventDispatcherInterface $eventDispatcher = null, |
66 | 74 | private readonly LoggerInterface $logger = new NullLogger(), |
@@ -449,4 +457,40 @@ private function paginateResults(array $items, int $limit, ?string $cursor = nul |
449 | 457 |
|
450 | 458 | return array_values(\array_slice($items, $offset, $limit)); |
451 | 459 | } |
| 460 | + |
| 461 | + public function subscribe(SessionInterface $session, string $uri): void |
| 462 | + { |
| 463 | + if (!isset($this->resourceSubscriptions[$uri])) { |
| 464 | + $this->resourceSubscriptions[$uri] = []; |
| 465 | + } |
| 466 | + |
| 467 | + $sessionId = $session->getId()->toRfc4122(); |
| 468 | + $this->resourceSubscriptions[$uri][$sessionId] = $session; |
| 469 | + } |
| 470 | + |
| 471 | + public function unsubscribe(SessionInterface $session, string $uri): void |
| 472 | + { |
| 473 | + if (!isset($this->resourceSubscriptions[$uri])) { |
| 474 | + return; |
| 475 | + } |
| 476 | + |
| 477 | + $sessionId = $session->getId()->toRfc4122(); |
| 478 | + |
| 479 | + unset($this->resourceSubscriptions[$uri][$sessionId]); |
| 480 | + |
| 481 | + if ([] === $this->resourceSubscriptions[$uri]) { |
| 482 | + unset($this->resourceSubscriptions[$uri]); |
| 483 | + } |
| 484 | + } |
| 485 | + |
| 486 | + public function notifyResourceChanged(Protocol $protocol, string $uri): void |
| 487 | + { |
| 488 | + if (!isset($this->resourceSubscriptions[$uri])) { |
| 489 | + return; |
| 490 | + } |
| 491 | + |
| 492 | + foreach ($this->resourceSubscriptions[$uri] as $session) { |
| 493 | + $protocol->sendNotification(new ResourceUpdatedNotification($uri), $session); |
| 494 | + } |
| 495 | + } |
452 | 496 | } |
0 commit comments