Registry Architecture Refactoring - Enhanced Separation of Concerns (#46)

* refactor: Separate Registry concerns following SOLID principles [WIP]

- Extract ReferenceProvider and ReferenceRegistryInterface interfaces
- Create DefaultToolExecutor with ReferenceHandlerInterface
- Remove execution responsibility from Registry class
- Enable custom handler and executor implementations

* refactor: implement SOLID principles with separated execution concerns

* Create DefaultResourceReader, DefaultPromptGetter
* Refactor JsonRpc Handler and RequestHandlers to use dedicated executors
* Update ServerBuilder to support custom executors via dependency injection

* chore: remove extra comments

* feat: introduce DispatchableRegistry for enhanced tool and resource management

* refactor: use proper interfaces

* refactor: implement HandlerInterface for improved abstraction and flexibility

* test: add unit tests for DispatchableRegistry and Registry classes

* refactor: cover with unit tests Resource reader, Prompt getter and Tool executor

* cs fix

* phpstan fix

* test: add unit tests for CallToolHandler, GetPromptHandler, PingHandler, and ReadResourceHandler

* refactor: revert Handler

* chore: remove style guide for tests

* refactor: remove "Default" prefix from classes

* refactor: remove DispatchableRegistry

* refactor: use package specific exception classes

* refactor: remove DispatchableRegistry

* refactor: add logger support to PromptGetter and ResourceReader classes

* Update src/Capability/Prompt/PromptGetter.php

Co-authored-by: Christopher Hertel <mail@christopher-hertel.de>

* refactor: Use FQN for Resource class to avoid cs-fixer misinterpreting it as `resource`

* refactor: rename ToolExecutor to ToolCaller and related classes for clarity and consistency

* refactor: add missed docblock

* refactor: rename ToolExecutor references to ToolCaller

* refactor: rename ToolCallerTest property and variable references

* cs fix

* ignore some phpstan errors

---------

Co-authored-by: Christopher Hertel <mail@christopher-hertel.de>
This commit is contained in:
Pavel Buchnev 2025-09-14 22:44:18 +04:00 • committed by GitHub
commit 99bf56eef8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 4656 additions and 334 deletions

View file

@ -0,0 +1,294 @@
<?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\Server\RequestHandler;
use Mcp\Capability\Tool\ToolCallerInterface;
use Mcp\Exception\ToolCallException;
use Mcp\Exception\ToolNotFoundException;
use Mcp\Schema\Content\TextContent;
use Mcp\Schema\JsonRpc\Error;
use Mcp\Schema\JsonRpc\Response;
use Mcp\Schema\Request\CallToolRequest;
use Mcp\Schema\Result\CallToolResult;
use Mcp\Server\RequestHandler\CallToolHandler;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
class CallToolHandlerTest extends TestCase
{
private CallToolHandler $handler;
private ToolCallerInterface|MockObject $toolExecutor;
private LoggerInterface|MockObject $logger;
protected function setUp(): void
{
$this->toolExecutor = $this->createMock(ToolCallerInterface::class);
$this->logger = $this->createMock(LoggerInterface::class);
$this->handler = new CallToolHandler(
$this->toolExecutor,
$this->logger,
);
}
public function testSupportsCallToolRequest(): void
{
$request = $this->createCallToolRequest('test_tool', ['param' => 'value']);
$this->assertTrue($this->handler->supports($request));
}
public function testHandleSuccessfulToolCall(): void
{
$request = $this->createCallToolRequest('greet_user', ['name' => 'John']);
$expectedResult = new CallToolResult([new TextContent('Hello, John!')]);
$this->toolExecutor
->expects($this->once())
->method('call')
->with($request)
->willReturn($expectedResult);
$this->logger
->expects($this->never())
->method('error');
$response = $this->handler->handle($request);
$this->assertInstanceOf(Response::class, $response);
$this->assertEquals($request->getId(), $response->id);
$this->assertSame($expectedResult, $response->result);
}
public function testHandleToolCallWithEmptyArguments(): void
{
$request = $this->createCallToolRequest('simple_tool', []);
$expectedResult = new CallToolResult([new TextContent('Simple result')]);
$this->toolExecutor
->expects($this->once())
->method('call')
->with($request)
->willReturn($expectedResult);
$response = $this->handler->handle($request);
$this->assertInstanceOf(Response::class, $response);
$this->assertSame($expectedResult, $response->result);
}
public function testHandleToolCallWithComplexArguments(): void
{
$arguments = [
'string_param' => 'value',
'int_param' => 42,
'bool_param' => true,
'array_param' => ['nested' => 'data'],
'null_param' => null,
];
$request = $this->createCallToolRequest('complex_tool', $arguments);
$expectedResult = new CallToolResult([new TextContent('Complex result')]);
$this->toolExecutor
->expects($this->once())
->method('call')
->with($request)
->willReturn($expectedResult);
$response = $this->handler->handle($request);
$this->assertInstanceOf(Response::class, $response);
$this->assertSame($expectedResult, $response->result);
}
public function testHandleToolNotFoundExceptionReturnsError(): void
{
$request = $this->createCallToolRequest('nonexistent_tool', ['param' => 'value']);
$exception = new ToolNotFoundException($request);
$this->toolExecutor
->expects($this->once())
->method('call')
->with($request)
->willThrowException($exception);
$this->logger
->expects($this->once())
->method('error')
->with(
'Error while executing tool "nonexistent_tool": "Tool not found for call: "nonexistent_tool".".',
[
'tool' => 'nonexistent_tool',
'arguments' => ['param' => 'value'],
],
);
$response = $this->handler->handle($request);
$this->assertInstanceOf(Error::class, $response);
$this->assertEquals($request->getId(), $response->id);
$this->assertEquals(Error::INTERNAL_ERROR, $response->code);
$this->assertEquals('Error while executing tool', $response->message);
}
public function testHandleToolExecutionExceptionReturnsError(): void
{
$request = $this->createCallToolRequest('failing_tool', ['param' => 'value']);
$exception = new ToolCallException($request, new \RuntimeException('Tool execution failed'));
$this->toolExecutor
->expects($this->once())
->method('call')
->with($request)
->willThrowException($exception);
$this->logger
->expects($this->once())
->method('error')
->with(
'Error while executing tool "failing_tool": "Tool call "failing_tool" failed with error: "Tool execution failed".".',
[
'tool' => 'failing_tool',
'arguments' => ['param' => 'value'],
],
);
$response = $this->handler->handle($request);
$this->assertInstanceOf(Error::class, $response);
$this->assertEquals($request->getId(), $response->id);
$this->assertEquals(Error::INTERNAL_ERROR, $response->code);
$this->assertEquals('Error while executing tool', $response->message);
}
public function testHandleWithNullResult(): void
{
$request = $this->createCallToolRequest('null_tool', []);
$expectedResult = new CallToolResult([]);
$this->toolExecutor
->expects($this->once())
->method('call')
->with($request)
->willReturn($expectedResult);
$response = $this->handler->handle($request);
$this->assertInstanceOf(Response::class, $response);
$this->assertSame($expectedResult, $response->result);
}
public function testHandleWithErrorResult(): void
{
$request = $this->createCallToolRequest('error_tool', []);
$expectedResult = CallToolResult::error([new TextContent('Tool error occurred')]);
$this->toolExecutor
->expects($this->once())
->method('call')
->with($request)
->willReturn($expectedResult);
$response = $this->handler->handle($request);
$this->assertInstanceOf(Response::class, $response);
$this->assertSame($expectedResult, $response->result);
$this->assertTrue($response->result->isError);
}
public function testConstructorWithDefaultLogger(): void
{
$handler = new CallToolHandler($this->toolExecutor);
$this->assertInstanceOf(CallToolHandler::class, $handler);
}
public function testHandleLogsErrorWithCorrectParameters(): void
{
$request = $this->createCallToolRequest('test_tool', ['key1' => 'value1', 'key2' => 42]);
$exception = new ToolCallException($request, new \RuntimeException('Custom error message'));
$this->toolExecutor
->expects($this->once())
->method('call')
->willThrowException($exception);
$this->logger
->expects($this->once())
->method('error')
->with(
'Error while executing tool "test_tool": "Tool call "test_tool" failed with error: "Custom error message".".',
[
'tool' => 'test_tool',
'arguments' => ['key1' => 'value1', 'key2' => 42],
],
);
$this->handler->handle($request);
}
public function testHandleWithSpecialCharactersInToolName(): void
{
$request = $this->createCallToolRequest('tool-with_special.chars', []);
$expectedResult = new CallToolResult([new TextContent('Special tool result')]);
$this->toolExecutor
->expects($this->once())
->method('call')
->with($request)
->willReturn($expectedResult);
$response = $this->handler->handle($request);
$this->assertInstanceOf(Response::class, $response);
$this->assertSame($expectedResult, $response->result);
}
public function testHandleWithSpecialCharactersInArguments(): void
{
$arguments = [
'special_chars' => 'äöü ñ 中文 🚀',
'unicode' => '\\u{1F600}',
'quotes' => 'text with "quotes" and \'single quotes\'',
];
$request = $this->createCallToolRequest('unicode_tool', $arguments);
$expectedResult = new CallToolResult([new TextContent('Unicode handled')]);
$this->toolExecutor
->expects($this->once())
->method('call')
->with($request)
->willReturn($expectedResult);
$response = $this->handler->handle($request);
$this->assertInstanceOf(Response::class, $response);
$this->assertSame($expectedResult, $response->result);
}
/**
* @param array<string, mixed> $arguments
*/
private function createCallToolRequest(string $name, array $arguments): CallToolRequest
{
return CallToolRequest::fromArray([
'jsonrpc' => '2.0',
'method' => CallToolRequest::getMethod(),
'id' => 'test-request-'.uniqid(),
'params' => [
'name' => $name,
'arguments' => $arguments,
],
]);
}
}

View file

@ -0,0 +1,342 @@
<?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\Server\RequestHandler;
use Mcp\Capability\Prompt\PromptGetterInterface;
use Mcp\Exception\PromptGetException;
use Mcp\Exception\PromptNotFoundException;
use Mcp\Schema\Content\PromptMessage;
use Mcp\Schema\Content\TextContent;
use Mcp\Schema\Enum\Role;
use Mcp\Schema\JsonRpc\Error;
use Mcp\Schema\JsonRpc\Response;
use Mcp\Schema\Request\GetPromptRequest;
use Mcp\Schema\Result\GetPromptResult;
use Mcp\Server\RequestHandler\GetPromptHandler;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
class GetPromptHandlerTest extends TestCase
{
private GetPromptHandler $handler;
private PromptGetterInterface|MockObject $promptGetter;
protected function setUp(): void
{
$this->promptGetter = $this->createMock(PromptGetterInterface::class);
$this->handler = new GetPromptHandler($this->promptGetter);
}
public function testSupportsGetPromptRequest(): void
{
$request = $this->createGetPromptRequest('test_prompt');
$this->assertTrue($this->handler->supports($request));
}
public function testHandleSuccessfulPromptGet(): void
{
$request = $this->createGetPromptRequest('greeting_prompt');
$expectedMessages = [
new PromptMessage(Role::User, new TextContent('Hello, how can I help you?')),
];
$expectedResult = new GetPromptResult(
description: 'A greeting prompt',
messages: $expectedMessages,
);
$this->promptGetter
->expects($this->once())
->method('get')
->with($request)
->willReturn($expectedResult);
$response = $this->handler->handle($request);
$this->assertInstanceOf(Response::class, $response);
$this->assertEquals($request->getId(), $response->id);
$this->assertSame($expectedResult, $response->result);
}
public function testHandlePromptGetWithArguments(): void
{
$arguments = [
'name' => 'John',
'context' => 'business meeting',
'formality' => 'formal',
];
$request = $this->createGetPromptRequest('personalized_prompt', $arguments);
$expectedMessages = [
new PromptMessage(
Role::User,
new TextContent('Good morning, John. How may I assist you in your business meeting?'),
),
];
$expectedResult = new GetPromptResult(
description: 'A personalized greeting prompt',
messages: $expectedMessages,
);
$this->promptGetter
->expects($this->once())
->method('get')
->with($request)
->willReturn($expectedResult);
$response = $this->handler->handle($request);
$this->assertInstanceOf(Response::class, $response);
$this->assertSame($expectedResult, $response->result);
}
public function testHandlePromptGetWithNullArguments(): void
{
$request = $this->createGetPromptRequest('simple_prompt', null);
$expectedMessages = [
new PromptMessage(Role::Assistant, new TextContent('I am ready to help.')),
];
$expectedResult = new GetPromptResult(
description: 'A simple prompt',
messages: $expectedMessages,
);
$this->promptGetter
->expects($this->once())
->method('get')
->with($request)
->willReturn($expectedResult);
$response = $this->handler->handle($request);
$this->assertInstanceOf(Response::class, $response);
$this->assertSame($expectedResult, $response->result);
}
public function testHandlePromptGetWithEmptyArguments(): void
{
$request = $this->createGetPromptRequest('empty_args_prompt', []);
$expectedMessages = [
new PromptMessage(Role::User, new TextContent('Default message')),
];
$expectedResult = new GetPromptResult(
description: 'A prompt with empty arguments',
messages: $expectedMessages,
);
$this->promptGetter
->expects($this->once())
->method('get')
->with($request)
->willReturn($expectedResult);
$response = $this->handler->handle($request);
$this->assertInstanceOf(Response::class, $response);
$this->assertSame($expectedResult, $response->result);
}
public function testHandlePromptGetWithMultipleMessages(): void
{
$request = $this->createGetPromptRequest('conversation_prompt');
$expectedMessages = [
new PromptMessage(Role::User, new TextContent('Hello')),
new PromptMessage(Role::Assistant, new TextContent('Hi there! How can I help you today?')),
new PromptMessage(Role::User, new TextContent('I need assistance with my project')),
];
$expectedResult = new GetPromptResult(
description: 'A conversation prompt',
messages: $expectedMessages,
);
$this->promptGetter
->expects($this->once())
->method('get')
->with($request)
->willReturn($expectedResult);
$response = $this->handler->handle($request);
$this->assertInstanceOf(Response::class, $response);
$this->assertSame($expectedResult, $response->result);
$this->assertCount(3, $response->result->messages);
}
public function testHandlePromptNotFoundExceptionReturnsError(): void
{
$request = $this->createGetPromptRequest('nonexistent_prompt');
$exception = new PromptNotFoundException($request);
$this->promptGetter
->expects($this->once())
->method('get')
->with($request)
->willThrowException($exception);
$response = $this->handler->handle($request);
$this->assertInstanceOf(Error::class, $response);
$this->assertEquals($request->getId(), $response->id);
$this->assertEquals(Error::INTERNAL_ERROR, $response->code);
$this->assertEquals('Error while handling prompt', $response->message);
}
public function testHandlePromptGetExceptionReturnsError(): void
{
$request = $this->createGetPromptRequest('failing_prompt');
$exception = new PromptGetException($request, new \RuntimeException('Failed to get prompt'));
$this->promptGetter
->expects($this->once())
->method('get')
->with($request)
->willThrowException($exception);
$response = $this->handler->handle($request);
$this->assertInstanceOf(Error::class, $response);
$this->assertEquals($request->getId(), $response->id);
$this->assertEquals(Error::INTERNAL_ERROR, $response->code);
$this->assertEquals('Error while handling prompt', $response->message);
}
public function testHandlePromptGetWithComplexArguments(): void
{
$arguments = [
'user_data' => [
'name' => 'Alice',
'preferences' => ['formal', 'concise'],
'history' => [
'last_interaction' => '2025-01-15',
'topics' => ['technology', 'business'],
],
],
'context' => 'technical consultation',
'metadata' => [
'session_id' => 'sess_123456',
'timestamp' => 1705392000,
],
];
$request = $this->createGetPromptRequest('complex_prompt', $arguments);
$expectedMessages = [
new PromptMessage(Role::User, new TextContent('Complex prompt generated with all parameters')),
];
$expectedResult = new GetPromptResult(
description: 'A complex prompt with nested arguments',
messages: $expectedMessages,
);
$this->promptGetter
->expects($this->once())
->method('get')
->with($request)
->willReturn($expectedResult);
$response = $this->handler->handle($request);
$this->assertInstanceOf(Response::class, $response);
$this->assertSame($expectedResult, $response->result);
}
public function testHandlePromptGetWithSpecialCharacters(): void
{
$arguments = [
'message' => 'Hello 世界! How are you? 😊',
'special' => 'äöü ñ ß',
'quotes' => 'Text with "double" and \'single\' quotes',
];
$request = $this->createGetPromptRequest('unicode_prompt', $arguments);
$expectedMessages = [
new PromptMessage(Role::User, new TextContent('Unicode message processed')),
];
$expectedResult = new GetPromptResult(
description: 'A prompt handling unicode characters',
messages: $expectedMessages,
);
$this->promptGetter
->expects($this->once())
->method('get')
->with($request)
->willReturn($expectedResult);
$response = $this->handler->handle($request);
$this->assertInstanceOf(Response::class, $response);
$this->assertSame($expectedResult, $response->result);
}
public function testHandlePromptGetReturnsEmptyMessages(): void
{
$request = $this->createGetPromptRequest('empty_prompt');
$expectedResult = new GetPromptResult(
description: 'An empty prompt',
messages: [],
);
$this->promptGetter
->expects($this->once())
->method('get')
->with($request)
->willReturn($expectedResult);
$response = $this->handler->handle($request);
$this->assertInstanceOf(Response::class, $response);
$this->assertSame($expectedResult, $response->result);
$this->assertCount(0, $response->result->messages);
}
public function testHandlePromptGetWithLargeNumberOfArguments(): void
{
$arguments = [];
for ($i = 0; $i < 100; ++$i) {
$arguments["arg_{$i}"] = "value_{$i}";
}
$request = $this->createGetPromptRequest('many_args_prompt', $arguments);
$expectedMessages = [
new PromptMessage(Role::User, new TextContent('Processed 100 arguments')),
];
$expectedResult = new GetPromptResult(
description: 'A prompt with many arguments',
messages: $expectedMessages,
);
$this->promptGetter
->expects($this->once())
->method('get')
->with($request)
->willReturn($expectedResult);
$response = $this->handler->handle($request);
$this->assertInstanceOf(Response::class, $response);
$this->assertSame($expectedResult, $response->result);
}
/**
* @param array<string, mixed>|null $arguments
*/
private function createGetPromptRequest(string $name, ?array $arguments = null): GetPromptRequest
{
return GetPromptRequest::fromArray([
'jsonrpc' => '2.0',
'method' => GetPromptRequest::getMethod(),
'id' => 'test-request-'.uniqid(),
'params' => [
'name' => $name,
'arguments' => $arguments,
],
]);
}
}

View file

@ -0,0 +1,147 @@
<?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\Server\RequestHandler;
use Mcp\Schema\JsonRpc\Request;
use Mcp\Schema\JsonRpc\Response;
use Mcp\Schema\Request\PingRequest;
use Mcp\Schema\Result\EmptyResult;
use Mcp\Server\RequestHandler\PingHandler;
use PHPUnit\Framework\TestCase;
class PingHandlerTest extends TestCase
{
private PingHandler $handler;
protected function setUp(): void
{
$this->handler = new PingHandler();
}
public function testSupportsPingRequest(): void
{
$request = $this->createPingRequest();
$this->assertTrue($this->handler->supports($request));
}
public function testHandlePingRequest(): void
{
$request = $this->createPingRequest();
$response = $this->handler->handle($request);
$this->assertInstanceOf(Response::class, $response);
$this->assertEquals($request->getId(), $response->id);
$this->assertInstanceOf(EmptyResult::class, $response->result);
}
public function testHandleMultiplePingRequests(): void
{
$request1 = $this->createPingRequest();
$request2 = $this->createPingRequest();
$response1 = $this->handler->handle($request1);
$response2 = $this->handler->handle($request2);
$this->assertInstanceOf(Response::class, $response1);
$this->assertInstanceOf(Response::class, $response2);
$this->assertInstanceOf(EmptyResult::class, $response1->result);
$this->assertInstanceOf(EmptyResult::class, $response2->result);
$this->assertEquals($request1->getId(), $response1->id);
$this->assertEquals($request2->getId(), $response2->id);
}
public function testHandlerHasNoSideEffects(): void
{
$request = $this->createPingRequest();
// Handle same request multiple times
$response1 = $this->handler->handle($request);
$response2 = $this->handler->handle($request);
// Both responses should be identical
$this->assertEquals($response1->id, $response2->id);
$this->assertEquals(
\get_class($response1->result),
\get_class($response2->result),
);
}
public function testEmptyResultIsCorrectType(): void
{
$request = $this->createPingRequest();
$response = $this->handler->handle($request);
$this->assertInstanceOf(EmptyResult::class, $response->result);
// Verify EmptyResult serializes to empty object
$serialized = json_encode($response->result);
$this->assertEquals('{}', $serialized);
}
public function testHandlerIsStateless(): void
{
$handler1 = new PingHandler();
$handler2 = new PingHandler();
$request = $this->createPingRequest();
$response1 = $handler1->handle($request);
$response2 = $handler2->handle($request);
// Both handlers should produce equivalent results
$this->assertEquals($response1->id, $response2->id);
$this->assertEquals(
\get_class($response1->result),
\get_class($response2->result),
);
}
public function testSupportsMethodIsConsistent(): void
{
$request = $this->createPingRequest();
// Multiple calls to supports should return same result
$this->assertTrue($this->handler->supports($request));
$this->assertTrue($this->handler->supports($request));
$this->assertTrue($this->handler->supports($request));
}
public function testHandlerCanBeReused(): void
{
$requests = [];
$responses = [];
// Create multiple ping requests
for ($i = 0; $i < 5; ++$i) {
$requests[$i] = $this->createPingRequest();
$responses[$i] = $this->handler->handle($requests[$i]);
}
// All responses should be valid
foreach ($responses as $i => $response) {
$this->assertInstanceOf(Response::class, $response);
$this->assertEquals($requests[$i]->getId(), $response->id);
$this->assertInstanceOf(EmptyResult::class, $response->result);
}
}
private function createPingRequest(): Request
{
return PingRequest::fromArray([
'jsonrpc' => '2.0',
'method' => PingRequest::getMethod(),
'id' => 'test-request-'.uniqid(),
]);
}
}

View file

@ -0,0 +1,351 @@
<?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\Server\RequestHandler;
use Mcp\Capability\Resource\ResourceReaderInterface;
use Mcp\Exception\ResourceNotFoundException;
use Mcp\Exception\ResourceReadException;
use Mcp\Schema\Content\BlobResourceContents;
use Mcp\Schema\Content\TextResourceContents;
use Mcp\Schema\JsonRpc\Error;
use Mcp\Schema\JsonRpc\Response;
use Mcp\Schema\Request\ReadResourceRequest;
use Mcp\Schema\Result\ReadResourceResult;
use Mcp\Server\RequestHandler\ReadResourceHandler;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
class ReadResourceHandlerTest extends TestCase
{
private ReadResourceHandler $handler;
private ResourceReaderInterface|MockObject $resourceReader;
protected function setUp(): void
{
$this->resourceReader = $this->createMock(ResourceReaderInterface::class);
$this->handler = new ReadResourceHandler($this->resourceReader);
}
public function testSupportsReadResourceRequest(): void
{
$request = $this->createReadResourceRequest('file://test.txt');
$this->assertTrue($this->handler->supports($request));
}
public function testHandleSuccessfulResourceRead(): void
{
$uri = 'file://documents/readme.txt';
$request = $this->createReadResourceRequest($uri);
$expectedContent = new TextResourceContents(
uri: $uri,
mimeType: 'text/plain',
text: 'This is the content of the readme file.',
);
$expectedResult = new ReadResourceResult([$expectedContent]);
$this->resourceReader
->expects($this->once())
->method('read')
->with($request)
->willReturn($expectedResult);
$response = $this->handler->handle($request);
$this->assertInstanceOf(Response::class, $response);
$this->assertEquals($request->getId(), $response->id);
$this->assertSame($expectedResult, $response->result);
}
public function testHandleResourceReadWithBlobContent(): void
{
$uri = 'file://images/logo.png';
$request = $this->createReadResourceRequest($uri);
$expectedContent = new BlobResourceContents(
uri: $uri,
mimeType: 'image/png',
blob: base64_encode('fake-image-data'),
);
$expectedResult = new ReadResourceResult([$expectedContent]);
$this->resourceReader
->expects($this->once())
->method('read')
->with($request)
->willReturn($expectedResult);
$response = $this->handler->handle($request);
$this->assertInstanceOf(Response::class, $response);
$this->assertSame($expectedResult, $response->result);
}
public function testHandleResourceReadWithMultipleContents(): void
{
$uri = 'app://data/mixed-content';
$request = $this->createReadResourceRequest($uri);
$textContent = new TextResourceContents(
uri: $uri,
mimeType: 'text/plain',
text: 'Text part of the resource',
);
$blobContent = new BlobResourceContents(
uri: $uri,
mimeType: 'application/octet-stream',
blob: base64_encode('binary-data'),
);
$expectedResult = new ReadResourceResult([$textContent, $blobContent]);
$this->resourceReader
->expects($this->once())
->method('read')
->with($request)
->willReturn($expectedResult);
$response = $this->handler->handle($request);
$this->assertInstanceOf(Response::class, $response);
$this->assertSame($expectedResult, $response->result);
$this->assertCount(2, $response->result->contents);
}
public function testHandleResourceNotFoundExceptionReturnsSpecificError(): void
{
$uri = 'file://nonexistent/file.txt';
$request = $this->createReadResourceRequest($uri);
$exception = new ResourceNotFoundException($request);
$this->resourceReader
->expects($this->once())
->method('read')
->with($request)
->willThrowException($exception);
$response = $this->handler->handle($request);
$this->assertInstanceOf(Error::class, $response);
$this->assertEquals($request->getId(), $response->id);
$this->assertEquals(Error::RESOURCE_NOT_FOUND, $response->code);
$this->assertEquals('Resource not found for uri: "'.$uri.'".', $response->message);
}
public function testHandleResourceReadExceptionReturnsGenericError(): void
{
$uri = 'file://corrupted/file.txt';
$request = $this->createReadResourceRequest($uri);
$exception = new ResourceReadException(
$request,
new \RuntimeException('Failed to read resource: corrupted data'),
);
$this->resourceReader
->expects($this->once())
->method('read')
->with($request)
->willThrowException($exception);
$response = $this->handler->handle($request);
$this->assertInstanceOf(Error::class, $response);
$this->assertEquals($request->getId(), $response->id);
$this->assertEquals(Error::INTERNAL_ERROR, $response->code);
$this->assertEquals('Error while reading resource', $response->message);
}
public function testHandleResourceReadWithDifferentUriSchemes(): void
{
$uriSchemes = [
'file://local/path/file.txt',
'http://example.com/resource',
'https://secure.example.com/api/data',
'ftp://files.example.com/document.pdf',
'app://internal/resource/123',
'custom-scheme://special/resource',
];
foreach ($uriSchemes as $uri) {
$request = $this->createReadResourceRequest($uri);
$expectedContent = new TextResourceContents(
uri: $uri,
mimeType: 'text/plain',
text: "Content for {$uri}",
);
$expectedResult = new ReadResourceResult([$expectedContent]);
$this->resourceReader
->expects($this->once())
->method('read')
->with($request)
->willReturn($expectedResult);
$response = $this->handler->handle($request);
$this->assertInstanceOf(Response::class, $response);
$this->assertSame($expectedResult, $response->result);
// Reset the mock for next iteration
$this->resourceReader = $this->createMock(ResourceReaderInterface::class);
$this->handler = new ReadResourceHandler($this->resourceReader);
}
}
public function testHandleResourceReadWithSpecialCharactersInUri(): void
{
$uri = 'file://path/with spaces/äöü-file-ñ.txt';
$request = $this->createReadResourceRequest($uri);
$expectedContent = new TextResourceContents(
uri: $uri,
mimeType: 'text/plain',
text: 'Content with unicode characters: äöü ñ 世界 🚀',
);
$expectedResult = new ReadResourceResult([$expectedContent]);
$this->resourceReader
->expects($this->once())
->method('read')
->with($request)
->willReturn($expectedResult);
$response = $this->handler->handle($request);
$this->assertInstanceOf(Response::class, $response);
$this->assertSame($expectedResult, $response->result);
}
public function testHandleResourceReadWithEmptyContent(): void
{
$uri = 'file://empty/file.txt';
$request = $this->createReadResourceRequest($uri);
$expectedContent = new TextResourceContents(
uri: $uri,
mimeType: 'text/plain',
text: '',
);
$expectedResult = new ReadResourceResult([$expectedContent]);
$this->resourceReader
->expects($this->once())
->method('read')
->with($request)
->willReturn($expectedResult);
$response = $this->handler->handle($request);
$this->assertInstanceOf(Response::class, $response);
$this->assertSame($expectedResult, $response->result);
$this->assertInstanceOf(TextResourceContents::class, $response->result->contents[0]);
$this->assertEquals('', $response->result->contents[0]->text);
}
public function testHandleResourceReadWithDifferentMimeTypes(): void
{
$mimeTypes = [
'text/plain',
'text/html',
'application/json',
'application/xml',
'image/png',
'image/jpeg',
'application/pdf',
'video/mp4',
'audio/mpeg',
'application/octet-stream',
];
foreach ($mimeTypes as $i => $mimeType) {
$uri = "file://test/file{$i}";
$request = $this->createReadResourceRequest($uri);
if (str_starts_with($mimeType, 'text/') || str_starts_with($mimeType, 'application/json')) {
$expectedContent = new TextResourceContents(
uri: $uri,
mimeType: $mimeType,
text: "Content for {$mimeType}",
);
} else {
$expectedContent = new BlobResourceContents(
uri: $uri,
mimeType: $mimeType,
blob: base64_encode("binary-content-for-{$mimeType}"),
);
}
$expectedResult = new ReadResourceResult([$expectedContent]);
$this->resourceReader
->expects($this->once())
->method('read')
->with($request)
->willReturn($expectedResult);
$response = $this->handler->handle($request);
$this->assertInstanceOf(Response::class, $response);
$this->assertSame($expectedResult, $response->result);
$this->assertEquals($mimeType, $response->result->contents[0]->mimeType);
// Reset the mock for next iteration
$this->resourceReader = $this->createMock(ResourceReaderInterface::class);
$this->handler = new ReadResourceHandler($this->resourceReader);
}
}
public function testHandleResourceNotFoundWithCustomMessage(): void
{
$uri = 'file://custom/missing.txt';
$request = $this->createReadResourceRequest($uri);
$exception = new ResourceNotFoundException($request);
$this->resourceReader
->expects($this->once())
->method('read')
->with($request)
->willThrowException($exception);
$response = $this->handler->handle($request);
$this->assertInstanceOf(Error::class, $response);
$this->assertEquals(Error::RESOURCE_NOT_FOUND, $response->code);
$this->assertEquals('Resource not found for uri: "'.$uri.'".', $response->message);
}
public function testHandleResourceReadWithEmptyResult(): void
{
$uri = 'file://empty/resource';
$request = $this->createReadResourceRequest($uri);
$expectedResult = new ReadResourceResult([]);
$this->resourceReader
->expects($this->once())
->method('read')
->with($request)
->willReturn($expectedResult);
$response = $this->handler->handle($request);
$this->assertInstanceOf(Response::class, $response);
$this->assertSame($expectedResult, $response->result);
$this->assertCount(0, $response->result->contents);
}
private function createReadResourceRequest(string $uri): ReadResourceRequest
{
return ReadResourceRequest::fromArray([
'jsonrpc' => '2.0',
'method' => ReadResourceRequest::getMethod(),
'id' => 'test-request-'.uniqid(),
'params' => [
'uri' => $uri,
],
]);
}
}