php-sdk/tests/Unit/Server/BuilderTest.php
Valery Gutu 55f7884368
[Server] Allow pre-built instance handlers in element registration (#375)
* Allow pre-built instance handlers in element registration

`HandlerResolver::resolve()` rejected `[$instance, 'methodName']` array
handlers even though the `Handler` type alias and the runtime invoker
already support them, so `Server::builder()->addTool(handler: [$obj, 'bar'])`
threw "Invalid array handler format" at build time.

Relax the array-shape guard to accept an object in slot 0 and normalize it
to its class name for reflection (the same idiom getHandlerDescription()
already uses). This unblocks dependency-injected handler objects that the
container-less `new $className()` fallback cannot build.

Fixes #369

* Use 0.6.1 changelog heading and test instance handler end-to-end

This is a bugfix with no new public API or BC break, so the changelog
entry belongs under 0.6.1 rather than a new 0.7.0 section.

Add an end-to-end test that registers a pre-built instance handler with a
constructor dependency the container-less new $className() fallback cannot
satisfy, then drives a real tools/call through CallToolHandler and asserts
the injected instance is the one invoked.

* Address review: reject Closure array handlers, fix abstract-method message

- HandlerResolver: extract the array-handler guard into a readable
  $hasValidTarget check that accepts strings and objects but excludes
  \Closure, so [$closure, 'method'] falls through to the format error
  instead of the misleading "method not found in class Closure".
- Fix the abstract-method rejection message ("must be abstract" ->
  "must not be abstract"), a pre-existing typo in the same branch.
- Tighten the CHANGELOG entry wording.
- Cover Closure rejection with a regression test.

* Move instance-handler entry under 0.7.0 changelog heading

Per review: registering pre-built instance handlers is a feature, not a
patch, so it belongs in a minor release heading.
2026-07-06 01:13:41 +02:00

204 lines
7.4 KiB
PHP

<?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\Capability\Registry\ElementReference;
use Mcp\Capability\Registry\ReferenceHandlerInterface;
use Mcp\Exception\LogicException;
use Mcp\Schema\Content\TextContent;
use Mcp\Schema\Extension\Apps\McpApps;
use Mcp\Schema\JsonRpc\Response;
use Mcp\Schema\Request\CallToolRequest;
use Mcp\Schema\ServerCapabilities;
use Mcp\Server;
use Mcp\Server\Handler\Request\CallToolHandler;
use Mcp\Server\Handler\Request\InitializeHandler;
use Mcp\Server\Session\SessionInterface;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase;
final class BuilderTest extends TestCase
{
#[TestDox('setReferenceHandler() returns the builder for fluent chaining')]
public function testSetReferenceHandlerReturnsSelf(): void
{
$referenceHandler = $this->createStub(ReferenceHandlerInterface::class);
$builder = Server::builder();
$result = $builder->setReferenceHandler($referenceHandler);
$this->assertSame($builder, $result);
}
#[TestDox('build() succeeds with a custom ReferenceHandler')]
public function testBuildWithCustomReferenceHandler(): void
{
$referenceHandler = $this->createStub(ReferenceHandlerInterface::class);
$server = Server::builder()
->setServerInfo('test', '1.0.0')
->setReferenceHandler($referenceHandler)
->build();
$this->assertInstanceOf(Server::class, $server);
}
#[TestDox('build() succeeds without a custom ReferenceHandler (uses default)')]
public function testBuildWithoutCustomReferenceHandler(): void
{
$server = Server::builder()
->setServerInfo('test', '1.0.0')
->build();
$this->assertInstanceOf(Server::class, $server);
}
#[TestDox('Custom ReferenceHandler is used when calling a tool')]
public function testCustomReferenceHandlerIsUsedForToolCalls(): void
{
$referenceHandler = $this->createMock(ReferenceHandlerInterface::class);
$referenceHandler->expects($this->once())
->method('handle')
->willReturnCallback(static function (ElementReference $reference, array $arguments): string {
return 'intercepted';
});
$server = Server::builder()
->setServerInfo('test', '1.0.0')
->setReferenceHandler($referenceHandler)
->addTool(static fn (): string => 'original', name: 'test_tool', description: 'A test tool')
->build();
$result = $this->callTool($server, 'test_tool');
$this->assertSame('intercepted', $result);
}
#[TestDox('A pre-built instance handler with constructor dependencies is registered and invoked on that instance')]
public function testPreBuiltInstanceHandlerIsInvokedOnTheGivenInstance(): void
{
// The handler's constructor requires an argument the container-less
// `new $className()` fallback can never satisfy. If the tool call
// succeeds, it can only be because the pre-built instance — carrying
// its injected dependency — was the one invoked.
$handler = new GreetingService('World');
$server = Server::builder()
->setServerInfo('test', '1.0.0')
->addTool(handler: [$handler, 'greet'], name: 'greet', description: 'Greets using the injected name')
->build();
$result = $this->callTool($server, 'greet');
$this->assertSame('Hello, World', $result);
}
#[TestDox('enableExtension() registers an extension and announces its capability payload')]
public function testEnableExtensionRegistersExtension(): void
{
$server = Server::builder()
->setServerInfo('test', '1.0.0')
->enableExtension(new McpApps())
->build();
$capabilities = $this->extractServerCapabilities($server);
$this->assertNotNull($capabilities->extensions);
$this->assertArrayHasKey(McpApps::EXTENSION_ID, $capabilities->extensions);
$this->assertSame(['mimeTypes' => [McpApps::MIME_TYPE]], $capabilities->extensions[McpApps::EXTENSION_ID]);
}
#[TestDox('enableExtension() throws when the same extension is enabled twice')]
public function testEnableExtensionRejectsDuplicate(): void
{
$this->expectException(LogicException::class);
$this->expectExceptionMessage(McpApps::EXTENSION_ID);
Server::builder()->enableExtension(new McpApps(), new McpApps());
}
#[TestDox('enableExtension() extensions are merged into capabilities set via setCapabilities()')]
public function testEnableExtensionMergesIntoCustomCapabilities(): void
{
$server = Server::builder()
->setServerInfo('test', '1.0.0')
->setCapabilities(new ServerCapabilities(tools: true))
->enableExtension(new McpApps())
->build();
$capabilities = $this->extractServerCapabilities($server);
$this->assertNotNull($capabilities->extensions);
$this->assertArrayHasKey(McpApps::EXTENSION_ID, $capabilities->extensions);
}
private function extractServerCapabilities(Server $server): ServerCapabilities
{
$protocol = (new \ReflectionClass($server))->getProperty('protocol')->getValue($server);
$requestHandlers = (new \ReflectionClass($protocol))->getProperty('requestHandlers')->getValue($protocol);
foreach ($requestHandlers as $handler) {
if ($handler instanceof InitializeHandler) {
return $handler->configuration->capabilities;
}
}
$this->fail('InitializeHandler not found in request handlers');
}
private function callTool(Server $server, string $toolName): mixed
{
$protocol = (new \ReflectionClass($server))->getProperty('protocol')->getValue($server);
$requestHandlers = (new \ReflectionClass($protocol))->getProperty('requestHandlers')->getValue($protocol);
foreach ($requestHandlers as $handler) {
if ($handler instanceof CallToolHandler) {
$request = CallToolRequest::fromArray([
'jsonrpc' => '2.0',
'method' => 'tools/call',
'id' => 'test-1',
'params' => ['name' => $toolName, 'arguments' => []],
]);
$session = $this->createStub(SessionInterface::class);
$response = $handler->handle($request, $session);
if ($response instanceof Response) {
$content = $response->result->content[0] ?? null;
return $content instanceof TextContent ? $content->text : null;
}
$this->fail('Expected Response, got '.$response::class);
}
}
$this->fail('CallToolHandler not found in request handlers');
}
}
/**
* A handler whose constructor dependency cannot be satisfied by the
* container-less `new $className()` fallback, so it must be registered as a
* pre-built instance.
*/
final class GreetingService
{
public function __construct(private string $name)
{
}
public function greet(): string
{
return 'Hello, '.$this->name;
}
}