Add missing handler for resource subscribe and unsubscribe (#220)

This commit is contained in:
Sule-Balogun Olanrewaju 2026-02-17 23:11:35 +00:00 • committed by GitHub
commit 2166b38d56
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 781 additions and 9 deletions

View file

@ -0,0 +1,142 @@
<?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\Tests\Unit\Server\Handler\Request;
use Mcp\Capability\Registry\ResourceReference;
use Mcp\Capability\RegistryInterface;
use Mcp\Exception\InvalidArgumentException;
use Mcp\Exception\ResourceNotFoundException;
use Mcp\Schema\JsonRpc\Error;
use Mcp\Schema\JsonRpc\Response;
use Mcp\Schema\Request\ResourceSubscribeRequest;
use Mcp\Schema\Resource;
use Mcp\Schema\Result\EmptyResult;
use Mcp\Server\Handler\Request\ResourceSubscribeHandler;
use Mcp\Server\Resource\SubscriptionManagerInterface;
use Mcp\Server\Session\SessionInterface;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
class ResourceSubscribeTest extends TestCase
{
private ResourceSubscribeHandler $handler;
private RegistryInterface&MockObject $registry;
private SessionInterface&MockObject $session;
private SubscriptionManagerInterface&MockObject $subscriptionManager;
protected function setUp(): void
{
$this->registry = $this->createMock(RegistryInterface::class);
$this->subscriptionManager = $this->createMock(SubscriptionManagerInterface::class);
$this->session = $this->createMock(SessionInterface::class);
$this->handler = new ResourceSubscribeHandler($this->registry, $this->subscriptionManager);
}
#[TestDox('Client can successfully subscribe to a resource')]
public function testClientCanSuccessfulSubscribeToAResource(): void
{
$uri = 'file://documents/readme.txt';
$request = $this->createResourceSubscribeRequest($uri);
$resourceReference = $this->getMockBuilder(ResourceReference::class)
->setConstructorArgs([new Resource($uri, 'test', mimeType: 'text/plain'), []])
->getMock();
$this->registry
->expects($this->once())
->method('getResource')
->with($uri)
->willReturn($resourceReference);
$this->subscriptionManager->expects($this->once())
->method('subscribe')
->with($this->session, $uri);
$response = $this->handler->handle($request, $this->session);
$this->assertInstanceOf(Response::class, $response);
$this->assertEquals($request->getId(), $response->id);
$this->assertInstanceOf(EmptyResult::class, $response->result);
}
#[TestDox('Gracefully handle duplicate subscription to a resource')]
public function testDuplicateSubscriptionIsGracefullyHandled(): void
{
$uri = 'file://documents/readme.txt';
$request = $this->createResourceSubscribeRequest($uri);
$resourceReference = $this->getMockBuilder(ResourceReference::class)
->setConstructorArgs([new Resource($uri, 'test', mimeType: 'text/plain'), []])
->getMock();
$this->registry
->expects($this->exactly(2))
->method('getResource')
->with($uri)
->willReturn($resourceReference);
$this->subscriptionManager
->expects($this->exactly(2))
->method('subscribe')
->with($this->session, $uri);
$response1 = $this->handler->handle($request, $this->session);
$response2 = $this->handler->handle($request, $this->session);
$this->assertInstanceOf(Response::class, $response1);
$this->assertInstanceOf(Response::class, $response2);
$this->assertEquals($request->getId(), $response1->id);
$this->assertEquals($request->getId(), $response2->id);
$this->assertInstanceOf(EmptyResult::class, $response1->result);
$this->assertInstanceOf(EmptyResult::class, $response2->result);
}
#[TestDox('Subscription to a resource with an empty uri throws InvalidArgumentException')]
public function testSubscribeWithEmptyUriThrowsError(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Missing or invalid "uri" parameter for resources/subscribe.');
$this->createResourceSubscribeRequest('');
}
#[TestDox('Subscription to a resource with an invalid uri throws ResourceNotException')]
public function testHandleSubscribeResourceNotFoundException(): void
{
$uri = 'file://missing/file.txt';
$request = $this->createResourceSubscribeRequest($uri);
$exception = new ResourceNotFoundException($uri);
$this->registry
->expects($this->once())
->method('getResource')
->with($uri)
->willThrowException($exception);
$response = $this->handler->handle($request, $this->session);
$this->assertInstanceOf(Error::class, $response);
$this->assertEquals(Error::RESOURCE_NOT_FOUND, $response->code);
$this->assertEquals(\sprintf('Resource not found for uri: "%s".', $uri), $response->message);
}
private function createResourceSubscribeRequest(string $uri): ResourceSubscribeRequest
{
return ResourceSubscribeRequest::fromArray([
'jsonrpc' => '2.0',
'method' => ResourceSubscribeRequest::getMethod(),
'id' => 'test-request-'.uniqid(),
'params' => [
'uri' => $uri,
],
]);
}
}

View file

@ -0,0 +1,149 @@
<?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\Tests\Unit\Server\Handler\Request;
use Mcp\Capability\Registry\ResourceReference;
use Mcp\Capability\RegistryInterface;
use Mcp\Exception\InvalidArgumentException;
use Mcp\Exception\ResourceNotFoundException;
use Mcp\Schema\JsonRpc\Error;
use Mcp\Schema\JsonRpc\Response;
use Mcp\Schema\Request\ResourceUnsubscribeRequest;
use Mcp\Schema\Resource;
use Mcp\Schema\Result\EmptyResult;
use Mcp\Server\Handler\Request\ResourceUnsubscribeHandler;
use Mcp\Server\Resource\SubscriptionManagerInterface;
use Mcp\Server\Session\SessionInterface;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
class ResourceUnsubscribeTest extends TestCase
{
private ResourceUnsubscribeHandler $handler;
private RegistryInterface&MockObject $registry;
private SessionInterface&MockObject $session;
private SubscriptionManagerInterface&MockObject $subscriptionManager;
protected function setUp(): void
{
$this->registry = $this->createMock(RegistryInterface::class);
$this->subscriptionManager = $this->createMock(SubscriptionManagerInterface::class);
$this->session = $this->createMock(SessionInterface::class);
$this->handler = new ResourceUnsubscribeHandler($this->registry, $this->subscriptionManager);
}
#[TestDox('Client can unsubscribe from a resource')]
public function testClientCanUnsubscribeFromAResource(): void
{
// Arrange
$uri = 'file://documents/readme.txt';
$request = $this->createResourceUnsubscribeRequest($uri);
$resourceReference = $this->getMockBuilder(ResourceReference::class)
->setConstructorArgs([new Resource($uri, 'test', mimeType: 'text/plain'), []])
->getMock();
$this->registry
->expects($this->once())
->method('getResource')
->with($uri)
->willReturn($resourceReference);
$this->subscriptionManager->expects($this->once())
->method('unsubscribe')
->with($this->session, $uri);
// Act
$response = $this->handler->handle($request, $this->session);
// Assert
$this->assertInstanceOf(Response::class, $response);
$this->assertEquals($request->getId(), $response->id);
$this->assertInstanceOf(EmptyResult::class, $response->result);
}
#[TestDox('Gracefully handle duplicate unsubscription from a resource')]
public function testDuplicateUnSubscriptionIsGracefullyHandled(): void
{
// Arrange
$uri = 'file://documents/readme.txt';
$request = $this->createResourceUnsubscribeRequest($uri);
$resourceReference = $this->getMockBuilder(ResourceReference::class)
->setConstructorArgs([new Resource($uri, 'test', mimeType: 'text/plain'), []])
->getMock();
$this->registry
->expects($this->exactly(2))
->method('getResource')
->with($uri)
->willReturn($resourceReference);
$this->subscriptionManager
->expects($this->exactly(2))
->method('unsubscribe')
->with($this->session, $uri);
// Act
$response1 = $this->handler->handle($request, $this->session);
$response2 = $this->handler->handle($request, $this->session);
// Assert
$this->assertInstanceOf(Response::class, $response1);
$this->assertInstanceOf(Response::class, $response2);
$this->assertEquals($request->getId(), $response1->id);
$this->assertEquals($request->getId(), $response2->id);
$this->assertInstanceOf(EmptyResult::class, $response1->result);
$this->assertInstanceOf(EmptyResult::class, $response2->result);
}
#[TestDox('Unsubscription from a resource with an invalid uri throws ResourceNotException')]
public function testHandleUnsubscribeResourceNotFoundException(): void
{
$uri = 'file://missing/file.txt';
$request = $this->createResourceUnsubscribeRequest($uri);
$exception = new ResourceNotFoundException($uri);
$this->registry
->expects($this->once())
->method('getResource')
->with($uri)
->willThrowException($exception);
$response = $this->handler->handle($request, $this->session);
$this->assertInstanceOf(Error::class, $response);
$this->assertEquals(Error::RESOURCE_NOT_FOUND, $response->code);
$this->assertEquals(\sprintf('Resource not found for uri: "%s".', $uri), $response->message);
}
#[TestDox('Unsubscription from a resource with an empty uri throws InvalidArgumentException')]
public function testUnsubscribeWithEmptyUriThrowsError(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Missing or invalid "uri" parameter for resources/unsubscribe.');
$this->createResourceUnsubscribeRequest('');
}
private function createResourceUnsubscribeRequest(string $uri): ResourceUnsubscribeRequest
{
return ResourceUnsubscribeRequest::fromArray([
'jsonrpc' => '2.0',
'method' => ResourceUnsubscribeRequest::getMethod(),
'id' => 'test-request-'.uniqid(),
'params' => [
'uri' => $uri,
],
]);
}
}

View file

@ -0,0 +1,176 @@
<?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\Tests\Unit\Server;
use Mcp\Schema\Notification\ResourceUpdatedNotification;
use Mcp\Server\Protocol;
use Mcp\Server\Resource\SessionSubscriptionManager;
use Mcp\Server\Session\SessionInterface;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Psr\SimpleCache\InvalidArgumentException;
use Symfony\Component\Uid\Uuid;
class SessionSubscriptionManagerTest extends TestCase
{
private SessionSubscriptionManager $subscriptionManager;
private LoggerInterface&MockObject $logger;
private Protocol&MockObject $protocol;
protected function setUp(): void
{
$this->logger = $this->createMock(LoggerInterface::class);
$this->protocol = $this->createMock(Protocol::class);
$this->subscriptionManager = new SessionSubscriptionManager($this->logger);
}
#[TestDox('Subscribing to a resource sends update notifications')]
public function testSubscribeAndSendsNotification(): void
{
// Arrange
$session = $this->createMock(SessionInterface::class);
$session->method('getId')->willReturn(Uuid::v4());
$uri = 'test://resource';
$session->method('get')
->with('resource_subscriptions', [])
->willReturnOnConsecutiveCalls(
[],
[$uri => true]
);
$session->expects($this->once())->method('set')->with('resource_subscriptions', [$uri => true]);
$session->expects($this->once())->method('save');
// Act
$this->subscriptionManager->subscribe($session, $uri);
// Assert
$this->protocol->expects($this->once())
->method('sendNotification')
->with($this->isInstanceOf(ResourceUpdatedNotification::class));
$this->subscriptionManager->notifyResourceChanged($this->protocol, $session, $uri);
}
#[TestDox('Unsubscribe from a resource')]
public function testUnsubscribeFromAResource(): void
{
// Arrange
$session = $this->createMock(SessionInterface::class);
$session->method('getId')->willReturn(Uuid::v4());
$uri = 'test://resource';
$session->method('get')
->with('resource_subscriptions', [])
->willReturnOnConsecutiveCalls(
[],
[$uri => true],
[$uri => true],
);
$session->expects($this->exactly(2))->method('set');
$session->expects($this->exactly(2))->method('save');
// Act
$this->subscriptionManager->subscribe($session, $uri);
$this->protocol->expects($this->once())->method('sendNotification');
$this->subscriptionManager->notifyResourceChanged($this->protocol, $session, $uri);
$this->subscriptionManager->unsubscribe($session, $uri);
}
#[TestDox('Unsubscribing from a resource verifies that no notification is sent')]
public function testUnsubscribeDoesNotSendNotifications(): void
{
// Arrange
$protocol = $this->createMock(Protocol::class);
$session = $this->createMock(SessionInterface::class);
$session->method('getId')->willReturn(Uuid::v4());
$uri = 'test://resource';
$session->method('get')
->with('resource_subscriptions', [])
->willReturnOnConsecutiveCalls(
[],
[$uri => true],
[]
);
$session->expects($this->exactly(2))->method('set');
$session->expects($this->exactly(2))->method('save');
// Act
$this->subscriptionManager->subscribe($session, $uri);
$this->subscriptionManager->unsubscribe($session, $uri);
// Assert
$protocol->expects($this->never())->method('sendNotification');
$this->subscriptionManager->notifyResourceChanged($protocol, $session, $uri);
}
#[TestDox('Logs error when notification fails to send')]
public function testLogsErrorWhenNotificationFails(): void
{
// Arrange
$protocol = $this->createMock(Protocol::class);
$session = $this->createMock(SessionInterface::class);
$uuid = Uuid::v4();
$session->method('getId')->willReturn($uuid);
$uri = 'test://resource';
$session->method('get')
->with('resource_subscriptions', [])
->willReturnOnConsecutiveCalls(
[],
[$uri => true]
);
$session->expects($this->once())->method('set')->with('resource_subscriptions', [$uri => true]);
$session->expects($this->once())->method('save');
$this->subscriptionManager->subscribe($session, $uri);
// Create a concrete exception that implements InvalidArgumentException
$exception = new class('Cache error') extends \Exception implements InvalidArgumentException {};
$protocol->expects($this->once())
->method('sendNotification')
->willThrowException($exception);
$this->logger->expects($this->once())
->method('error')
->with(
'Error sending resource notification to session',
$this->callback(static function ($context) use ($uuid, $uri, $exception) {
return $context['session_id'] === (string) $uuid
&& $context['uri'] === $uri
&& $context['exception'] === $exception;
})
);
try {
// Act
$this->subscriptionManager->notifyResourceChanged($protocol, $session, $uri);
$this->fail('Expected an exception to be thrown.');
} catch (InvalidArgumentException $e) {
// Assert
$this->assertSame($exception, $e);
return;
}
}
}