php-sdk/tests/Unit/Capability/Discovery/HandlerResolverTest.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

223 lines
8.6 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\Capability\Discovery;
use Mcp\Capability\Discovery\HandlerResolver;
use Mcp\Exception\InvalidArgumentException;
use PHPUnit\Framework\TestCase;
class HandlerResolverTest extends TestCase
{
public function testResolvesClosuresToReflectionFunction(): void
{
$closure = static function (string $input): string {
return "processed: $input";
};
$resolved = HandlerResolver::resolve($closure);
$this->assertInstanceOf(\ReflectionFunction::class, $resolved);
$this->assertEquals(1, $resolved->getNumberOfParameters());
$this->assertInstanceOf(\ReflectionNamedType::class, $returnType = $resolved->getReturnType());
$this->assertEquals('string', $returnType->getName());
}
public function testResolvesValidArrayHandler(): void
{
$handler = [ValidHandlerClass::class, 'publicMethod'];
$resolved = HandlerResolver::resolve($handler);
$this->assertInstanceOf(\ReflectionMethod::class, $resolved);
$this->assertEquals('publicMethod', $resolved->getName());
$this->assertEquals(ValidHandlerClass::class, $resolved->getDeclaringClass()->getName());
}
public function testResolvesValidInstanceArrayHandler(): void
{
$handler = [new ValidHandlerClass(), 'publicMethod'];
$resolved = HandlerResolver::resolve($handler);
$this->assertInstanceOf(\ReflectionMethod::class, $resolved);
$this->assertEquals('publicMethod', $resolved->getName());
$this->assertEquals(ValidHandlerClass::class, $resolved->getDeclaringClass()->getName());
}
public function testResolvesValidInvokableClassStringHandler(): void
{
$handler = ValidInvokableClass::class;
$resolved = HandlerResolver::resolve($handler);
$this->assertInstanceOf(\ReflectionMethod::class, $resolved);
$this->assertEquals('__invoke', $resolved->getName());
$this->assertEquals(ValidInvokableClass::class, $resolved->getDeclaringClass()->getName());
}
public function testResolvesStaticMethodsForManualRegistration(): void
{
$handler = [ValidHandlerClass::class, 'staticMethod'];
$resolved = HandlerResolver::resolve($handler);
$this->assertInstanceOf(\ReflectionMethod::class, $resolved);
$this->assertEquals('staticMethod', $resolved->getName());
$this->assertTrue($resolved->isStatic());
}
public function testThrowsForInvalidArrayHandlerFormatCount(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid array handler format. Expected [ClassName::class, \'methodName\'] or [$instance, \'methodName\'].');
HandlerResolver::resolve([ValidHandlerClass::class]); /* @phpstan-ignore argument.type */
}
public function testThrowsForInvalidArrayHandlerFormatTypes(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid array handler format. Expected [ClassName::class, \'methodName\'] or [$instance, \'methodName\'].');
HandlerResolver::resolve([ValidHandlerClass::class, 123]); /* @phpstan-ignore argument.type */
}
public function testThrowsForClosureInArrayHandler(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid array handler format. Expected [ClassName::class, \'methodName\'] or [$instance, \'methodName\'].');
HandlerResolver::resolve([static fn () => null, 'method']);
}
public function testThrowsForNonExistentClassInArrayHandler(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Handler class "NonExistentClass" not found');
HandlerResolver::resolve(['NonExistentClass', 'method']);
}
public function testThrowsForNonExistentMethodInArrayHandler(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Handler method "nonExistentMethod" not found in class');
HandlerResolver::resolve([ValidHandlerClass::class, 'nonExistentMethod']);
}
public function testThrowsForNonExistentClassInStringHandler(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid handler format. Expected Closure, [ClassName::class, \'methodName\'] or InvokableClassName::class string.');
HandlerResolver::resolve('NonExistentInvokableClass');
}
public function testThrowsForNonInvokableClassStringHandler(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invokable handler class "Mcp\Tests\Unit\Capability\Discovery\NonInvokableClass" must have a public "__invoke" method.');
HandlerResolver::resolve(NonInvokableClass::class);
}
public function testThrowsForProtectedMethodHandler(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('must be public');
HandlerResolver::resolve([ValidHandlerClass::class, 'protectedMethod']);
}
public function testThrowsForPrivateMethodHandler(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('must be public');
HandlerResolver::resolve([ValidHandlerClass::class, 'privateMethod']);
}
public function testThrowsForConstructorAsHandler(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('cannot be a constructor or destructor');
HandlerResolver::resolve([ValidHandlerClass::class, '__construct']);
}
public function testThrowsForDestructorAsHandler(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('cannot be a constructor or destructor');
HandlerResolver::resolve([ValidHandlerClass::class, '__destruct']);
}
public function testThrowsForAbstractMethodHandler(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Handler method "Mcp\Tests\Unit\Capability\Discovery\AbstractHandlerClass::abstractMethod" must not be abstract.');
HandlerResolver::resolve([AbstractHandlerClass::class, 'abstractMethod']);
}
public function testResolvesClosuresWithDifferentSignatures(): void
{
$noParams = static function () {
return 'test';
};
$withParams = static function (int $a, string $b = 'default') {
return $a.$b;
};
$variadic = static function (...$args) {
return $args;
};
$this->assertInstanceOf(\ReflectionFunction::class, HandlerResolver::resolve($noParams));
$this->assertInstanceOf(\ReflectionFunction::class, HandlerResolver::resolve($withParams));
$this->assertInstanceOf(\ReflectionFunction::class, HandlerResolver::resolve($variadic));
$this->assertEquals(0, HandlerResolver::resolve($noParams)->getNumberOfParameters());
$this->assertEquals(2, HandlerResolver::resolve($withParams)->getNumberOfParameters());
$this->assertTrue(HandlerResolver::resolve($variadic)->isVariadic());
}
public function testDistinguishesBetweenClosuresAndCallableArrays(): void
{
$closure = static function () {
return 'closure';
};
$array = [ValidHandlerClass::class, 'publicMethod'];
$string = ValidInvokableClass::class;
$this->assertInstanceOf(\ReflectionFunction::class, HandlerResolver::resolve($closure));
$this->assertInstanceOf(\ReflectionMethod::class, HandlerResolver::resolve($array));
$this->assertInstanceOf(\ReflectionMethod::class, HandlerResolver::resolve($string));
}
}
// Helper classes
class ValidHandlerClass
{
public function publicMethod(): void
{
}
protected function protectedMethod(): void
{
}
private function privateMethod(): void /* @phpstan-ignore method.unused */
{
}
public static function staticMethod(): void
{
}
public function __construct()
{
}
public function __destruct()
{
}
}
class ValidInvokableClass
{
public function __invoke(): void
{
}
}
class NonInvokableClass
{
}
abstract class AbstractHandlerClass
{
abstract public function abstractMethod(): void;
}