* [Server] feat: allow runtime handlers Adds Mcp\Server\Handler\RunTimeHandlerInterface so integrators (e.g. configuration-driven element sources) can register handlers whose arguments and execution are resolved at runtime rather than via PHP reflection of a callable. ReferenceHandler::handle() dispatches instanceof RunTimeHandler ahead of the callable/array/string branches, calls filterArguments to narrow the argument map, and forwards execute() a ClientGateway built from the active session. The Registry-layer surface (ElementReference and the four *Reference subclasses, RegistryInterface, Registry::register*, ArrayLoader's handler-description helper) is widened to accept the new type. The Builder/ArrayLoader path keeps its narrow callable union; exposing runtime handlers there requires reworking HandlerResolver and is left for a follow-up. * feat(server): add runtime handler metadata API Extend RunTimeHandlerInterface with four nullable metadata accessors (getInputSchema, getOutputSchema, getPromptArguments, getCompletionProviders) so the loader can obtain element metadata without reflection. Add RunTimeHandlerTrait providing null defaults for all four accessors so single-purpose handlers can override only the methods relevant to their element kind. * feat(server): expose runtime handlers via Builder Widen Builder::addTool, addResource, addResourceTemplate, and addPrompt to accept RunTimeHandlerInterface instances alongside the existing closure/array/string handler forms. Branch ArrayLoader::load() on instanceof RunTimeHandlerInterface in each of the four registration loops so runtime handlers skip the reflection-based HandlerResolver/HandlerSchema path and pull metadata from the interface accessors instead. Require explicit name and description for runtime handlers and raise ConfigurationException when missing or when a runtime tool has no input schema source. Replace direct $data['handler'] use in error log context with getHandlerDescription() to avoid serializing large runtime handler object graphs into log records. Document the runtime handler API in docs/server-builder.md with a new Runtime Handlers subsection and add a cross-reference from docs/mcp-elements.md. * test(server): cover runtime handler Builder path Add ArrayLoaderRunTimeHandlerTest covering: - successful tool registration with handler-supplied input schema, with kwarg input schema (precedence over the handler), and the same precedence rule for output schema - ConfigurationException for tools missing name, description, or any input schema source - successful resource registration via Builder kwargs and the matching missing-name failure mode - successful resource template registration with completion providers sourced from the handler and the missing-description failure mode - successful prompt registration with arguments and completion providers sourced from the handler, plus the missing-name failure mode - a trait-only fixture verifying the four metadata accessors return null by default Update existing ReferenceHandlerTest anonymous classes to use RunTimeHandlerTrait so they satisfy the widened interface. * refactor(server): split runtime handler interface Splits RunTimeHandlerInterface into a minimal base contract (only execute()) plus element-specific subtypes: RunTimeToolHandlerInterface, RunTimePromptHandlerInterface, and RunTimeResourceTemplateHandlerInterface. Each subtype declares only the metadata accessors relevant to its element kind, so a tool handler no longer has to no-op out prompt or template methods. Drops the now-redundant RunTimeHandlerTrait and removes filterArguments; execute() receives the full argument map directly. Updates ArrayLoader, ReferenceHandler, and Builder type signatures to use the per-element interfaces, and rewrites the Runtime Handlers documentation accordingly. * refactor(server): rename runtime handler interfaces to Runtime casing Renames RunTimeHandlerInterface and its element-specific subtypes to Runtime casing, adds a dedicated RuntimeResourceHandlerInterface so addResource() rejects mismatched runtime handlers at the type level, and strips _session and _request from arguments forwarded to runtime handlers. Hardens ArrayLoader to re-throw ConfigurationException without wrapping, and extracts inline test fixtures into tests/Fixtures/Runtime/. * chore: please the linting gods * test(server): use Uuid::v4 for symfony/uid 5.4 compatibility Uuid::v7() was added in symfony/uid 6.2 and breaks the Symfony 5.4 matrix job. Match the convention used elsewhere in the suite. * refactor(server): split ArrayLoader registration Extract per-element preparation into dedicated private prepare* methods for tools, resources, templates, and prompts. Factor the shared required-field assertion and reflected name/description resolution into helpers. * refactor(server): non-null runtime handler types Drop nullable return types on RuntimeToolHandlerInterface:: getInputSchema(), RuntimePromptHandlerInterface:: getPromptArguments()/getCompletionProviders(), and RuntimeResourceTemplateHandlerInterface:: getCompletionProviders() in favor of plain arrays. ArrayLoader no longer needs the null-coalescing fallbacks, and NullSchemaToolHandler plus its ConfigurationException test become redundant. * doc: update docs/server-builder.md Co-authored-by: Christopher Hertel <mail@christopher-hertel.de> * feat: peer revie feedback Introduce a new `Builder::add(...)` pattern for a more generic runtime handler. * refactor(server): apply PR 294 review feedback Move per-interface handler dispatch from ReferenceHandler into ExplicitElementLoader by wrapping each ElementHandlerInterface in a Closure that satisfies the existing callable contract, revert the *Reference / Registry handler-type widening PR 294 introduced, throw Mcp\Exception\InvalidArgumentException (not \TypeError) on mismatched Builder::add() pairings, and rename two classes for clarity: * Mcp\Capability\Registry\Loader\ArrayLoader -> ReflectedElementLoader * Mcp\Schema\Resource -> Mcp\Schema\ResourceDefinition (no alias) ReferenceHandler::prepareArguments() now injects ClientGateway by type and binds an `array $arguments` / `array $variables` closure parameter from the leftover inbound arguments. This addresses Antoine's coupling concern (ReferenceHandler no longer knows about the four handler interfaces) and Chris's package-exception preference, and clears the phpdoc reserved-word collision Antoine flagged on the resource schema class. Existing tests are re-targeted to exercise the closure path through ExplicitElementLoader / ReferenceHandler. * doc: address PR 294 review feedback Apply Chris's line-level suggestions on docs/server-builder.md (rewrap to 120 chars, smoothed Drupal mcp module name-drop in the explicit-element registration section, exception name reads Mcp\Exception\InvalidArgumentException), rewrap docs/mcp-elements.md to 120 chars, and add 0.6.0 CHANGELOG entries covering the Builder::add() entry point, the new handler interfaces, the new ExplicitElementLoader, plus three BC breaks (Resource -> ResourceDefinition rename, ArrayLoader -> ReflectedElementLoader rename, mismatched-pairing exception swap). * refactor: address self-review feedback * CHANGELOG: drop spurious [BC Break] entry for the exception type Builder::add() raises (method is new in this PR). * docs/server-builder: revert wrap-only edits to pre-existing main content; keep 120ch wrapping only for new sections. * ExplicitElementLoader: trim verbose class docblock. * ReferenceHandler: rename SPLAT_PARAMETER_NAMES constant to ARGUMENT_BAG_PARAMETERS. * refactor: rename CallableHandler to Handler * style: fix phpdoc param alignment * refactor: inline $reference->handler access * fix: maintainer review feedback docs: mention ExplicitElementLoader in comment docs: move Drupal reference to README list docs: drop implementation-only changelog entry docs: revert rewrap noise from mcp-elements.md * style: fix phpdoc param alignment --------- Co-authored-by: Christopher Hertel <mail@christopher-hertel.de> Co-authored-by: soyuka <soyuka@users.noreply.github.com>
585 lines
22 KiB
PHP
585 lines
22 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;
|
|
|
|
use Mcp\Capability\Completion\EnumCompletionProvider;
|
|
use Mcp\Capability\Registry;
|
|
use Mcp\Capability\Registry\PromptReference;
|
|
use Mcp\Capability\Registry\ResourceReference;
|
|
use Mcp\Capability\Registry\ResourceTemplateReference;
|
|
use Mcp\Capability\Registry\ToolReference;
|
|
use Mcp\Exception\PromptNotFoundException;
|
|
use Mcp\Exception\ResourceNotFoundException;
|
|
use Mcp\Exception\ToolNotFoundException;
|
|
use Mcp\Schema\Prompt;
|
|
use Mcp\Schema\ResourceDefinition;
|
|
use Mcp\Schema\ResourceTemplate;
|
|
use Mcp\Schema\Tool;
|
|
use PHPUnit\Framework\MockObject\MockObject;
|
|
use PHPUnit\Framework\TestCase;
|
|
use Psr\Log\LoggerInterface;
|
|
|
|
class RegistryTest extends TestCase
|
|
{
|
|
private Registry $registry;
|
|
private LoggerInterface|MockObject $logger;
|
|
|
|
protected function setUp(): void
|
|
{
|
|
$this->logger = $this->createMock(LoggerInterface::class);
|
|
$this->registry = new Registry(null, $this->logger);
|
|
}
|
|
|
|
public function testHasserReturnFalseForEmptyRegistry(): void
|
|
{
|
|
$this->assertFalse($this->registry->hasTools());
|
|
$this->assertFalse($this->registry->hasResources());
|
|
$this->assertFalse($this->registry->hasResourceTemplates());
|
|
$this->assertFalse($this->registry->hasPrompts());
|
|
}
|
|
|
|
public function testHasToolsReturnsTrueWhenToolIsRegistered(): void
|
|
{
|
|
$tool = $this->createValidTool('test_tool');
|
|
$this->registry->registerTool($tool, static fn () => 'result');
|
|
|
|
$this->assertTrue($this->registry->hasTools());
|
|
}
|
|
|
|
public function testGetToolsReturnsAllRegisteredTools(): void
|
|
{
|
|
$tool1 = $this->createValidTool('tool1');
|
|
$tool2 = $this->createValidTool('tool2');
|
|
|
|
$this->registry->registerTool($tool1, static fn () => 'result1');
|
|
$this->registry->registerTool($tool2, static fn () => 'result2');
|
|
|
|
$tools = $this->registry->getTools();
|
|
$this->assertCount(2, $tools);
|
|
$this->assertArrayHasKey('tool1', $tools->references);
|
|
$this->assertArrayHasKey('tool2', $tools->references);
|
|
$this->assertInstanceOf(Tool::class, $tools->references['tool1']);
|
|
$this->assertInstanceOf(Tool::class, $tools->references['tool2']);
|
|
}
|
|
|
|
public function testGetToolReturnsRegisteredTool(): void
|
|
{
|
|
$tool = $this->createValidTool('test_tool');
|
|
$handler = static fn () => 'result';
|
|
|
|
$this->registry->registerTool($tool, $handler);
|
|
|
|
$toolRef = $this->registry->getTool('test_tool');
|
|
$this->assertInstanceOf(ToolReference::class, $toolRef);
|
|
$this->assertEquals($tool->name, $toolRef->tool->name);
|
|
$this->assertEquals($handler, $toolRef->handler);
|
|
}
|
|
|
|
public function testRegisterToolOverwritesPriorRegistration(): void
|
|
{
|
|
$first = $this->createValidTool('test_tool');
|
|
$second = $this->createValidTool('test_tool');
|
|
|
|
$this->registry->registerTool($first, static fn () => 'first');
|
|
$this->registry->registerTool($second, static fn () => 'second');
|
|
|
|
$toolRef = $this->registry->getTool('test_tool');
|
|
$this->assertEquals('second', ($toolRef->handler)());
|
|
}
|
|
|
|
public function testGetToolThrowsExceptionForUnregisteredTool(): void
|
|
{
|
|
$this->expectException(ToolNotFoundException::class);
|
|
$this->expectExceptionMessage('Tool not found: "non_existent_tool".');
|
|
|
|
$this->registry->getTool('non_existent_tool');
|
|
}
|
|
|
|
public function testHasResourceReturnsTrueWhenResourceIsRegistered(): void
|
|
{
|
|
$resource = $this->createValidResource('test://resource');
|
|
$this->registry->registerResource($resource, static fn () => 'content');
|
|
|
|
$this->assertTrue($this->registry->hasResources());
|
|
}
|
|
|
|
public function testGetResourcesReturnsAllRegisteredResources(): void
|
|
{
|
|
$resource1 = $this->createValidResource('test://resource1');
|
|
$resource2 = $this->createValidResource('test://resource2');
|
|
|
|
$this->registry->registerResource($resource1, static fn () => 'content1');
|
|
$this->registry->registerResource($resource2, static fn () => 'content2');
|
|
|
|
$resources = $this->registry->getResources();
|
|
$this->assertCount(2, $resources);
|
|
$this->assertArrayHasKey('test://resource1', $resources->references);
|
|
$this->assertArrayHasKey('test://resource2', $resources->references);
|
|
$this->assertInstanceOf(ResourceDefinition::class, $resources->references['test://resource1']);
|
|
$this->assertInstanceOf(ResourceDefinition::class, $resources->references['test://resource2']);
|
|
}
|
|
|
|
public function testGetResourceReturnsRegisteredResource(): void
|
|
{
|
|
$resource = $this->createValidResource('test://resource');
|
|
$handler = static fn () => 'content';
|
|
|
|
$this->registry->registerResource($resource, $handler);
|
|
|
|
$resourceRef = $this->registry->getResource('test://resource');
|
|
$this->assertInstanceOf(ResourceReference::class, $resourceRef);
|
|
$this->assertEquals($resource->uri, $resourceRef->resource->uri);
|
|
$this->assertEquals($handler, $resourceRef->handler);
|
|
}
|
|
|
|
public function testRegisterResourceOverwritesPriorRegistration(): void
|
|
{
|
|
$first = $this->createValidResource('test://resource');
|
|
$second = $this->createValidResource('test://resource');
|
|
|
|
$this->registry->registerResource($first, static fn () => 'first');
|
|
$this->registry->registerResource($second, static fn () => 'second');
|
|
|
|
$resourceRef = $this->registry->getResource('test://resource');
|
|
$this->assertEquals('second', ($resourceRef->handler)());
|
|
}
|
|
|
|
public function testGetResourceThrowsExceptionForUnregisteredResource(): void
|
|
{
|
|
$this->expectException(ResourceNotFoundException::class);
|
|
$this->expectExceptionMessage('Resource not found for uri: "test://non_existent".');
|
|
|
|
$this->registry->getResource('test://non_existent');
|
|
}
|
|
|
|
public function testHasResourceTemplatesReturnsTrueWhenResourceTemplateIsRegistered(): void
|
|
{
|
|
$template = $this->createValidResourceTemplate('test://{id}');
|
|
$this->registry->registerResourceTemplate($template, static fn () => 'content');
|
|
|
|
$this->assertTrue($this->registry->hasResourceTemplates());
|
|
}
|
|
|
|
public function testGetResourceTemplatesReturnsAllRegisteredTemplates(): void
|
|
{
|
|
$template1 = $this->createValidResourceTemplate('test1://{id}');
|
|
$template2 = $this->createValidResourceTemplate('test2://{category}');
|
|
|
|
$this->registry->registerResourceTemplate($template1, static fn () => 'content1');
|
|
$this->registry->registerResourceTemplate($template2, static fn () => 'content2');
|
|
|
|
$templates = $this->registry->getResourceTemplates();
|
|
$this->assertCount(2, $templates);
|
|
$this->assertArrayHasKey('test1://{id}', $templates->references);
|
|
$this->assertArrayHasKey('test2://{category}', $templates->references);
|
|
$this->assertInstanceOf(ResourceTemplate::class, $templates->references['test1://{id}']);
|
|
$this->assertInstanceOf(ResourceTemplate::class, $templates->references['test2://{category}']);
|
|
}
|
|
|
|
public function testGetResourceTemplateReturnsRegisteredTemplate(): void
|
|
{
|
|
$template = $this->createValidResourceTemplate('test://{id}');
|
|
$handler = static fn (string $id) => "content for {$id}";
|
|
|
|
$this->registry->registerResourceTemplate($template, $handler);
|
|
|
|
$templateRef = $this->registry->getResourceTemplate('test://{id}');
|
|
$this->assertInstanceOf(ResourceTemplateReference::class, $templateRef);
|
|
$this->assertEquals($template->uriTemplate, $templateRef->resourceTemplate->uriTemplate);
|
|
$this->assertEquals($handler, $templateRef->handler);
|
|
}
|
|
|
|
public function testGetResourcePrefersDirectResourceOverTemplate(): void
|
|
{
|
|
$resource = $this->createValidResource('test://123');
|
|
$resourceHandler = static fn () => 'direct resource';
|
|
|
|
$template = $this->createValidResourceTemplate('test://{id}');
|
|
$templateHandler = static fn (string $id) => "template for {$id}";
|
|
|
|
$this->registry->registerResource($resource, $resourceHandler);
|
|
$this->registry->registerResourceTemplate($template, $templateHandler);
|
|
|
|
$resourceRef = $this->registry->getResource('test://123');
|
|
$this->assertInstanceOf(ResourceReference::class, $resourceRef);
|
|
$this->assertEquals($resource->uri, $resourceRef->resource->uri);
|
|
}
|
|
|
|
public function testGetResourceMatchesResourceTemplate(): void
|
|
{
|
|
$template = $this->createValidResourceTemplate('test://{id}');
|
|
$handler = static fn (string $id) => "content for {$id}";
|
|
|
|
$this->registry->registerResourceTemplate($template, $handler);
|
|
|
|
$resourceRef = $this->registry->getResource('test://123');
|
|
$this->assertInstanceOf(ResourceTemplateReference::class, $resourceRef);
|
|
$this->assertEquals($template->uriTemplate, $resourceRef->resourceTemplate->uriTemplate);
|
|
$this->assertEquals($handler, $resourceRef->handler);
|
|
}
|
|
|
|
public function testGetResourceWithIncludeTemplatesFalseThrowsException(): void
|
|
{
|
|
$template = $this->createValidResourceTemplate('test://{id}');
|
|
$handler = static fn (string $id) => "content for {$id}";
|
|
|
|
$this->registry->registerResourceTemplate($template, $handler);
|
|
|
|
$this->expectException(ResourceNotFoundException::class);
|
|
$this->expectExceptionMessage('Resource not found for uri: "test://123".');
|
|
|
|
$this->registry->getResource('test://123', false);
|
|
}
|
|
|
|
public function testRegisterResourceTemplateWithCompletionProviders(): void
|
|
{
|
|
$template = $this->createValidResourceTemplate('test://{id}');
|
|
$completionProviders = ['id' => EnumCompletionProvider::class];
|
|
|
|
$this->registry->registerResourceTemplate($template, static fn () => 'content', $completionProviders);
|
|
|
|
$templateRef = $this->registry->getResourceTemplate('test://{id}');
|
|
$this->assertEquals($completionProviders, $templateRef->completionProviders);
|
|
}
|
|
|
|
public function testRegisterResourceTemplateOverwritesPriorRegistration(): void
|
|
{
|
|
$first = $this->createValidResourceTemplate('test://{id}');
|
|
$second = $this->createValidResourceTemplate('test://{id}');
|
|
|
|
$this->registry->registerResourceTemplate($first, static fn () => 'first');
|
|
$this->registry->registerResourceTemplate($second, static fn () => 'second');
|
|
|
|
$templateRef = $this->registry->getResourceTemplate('test://{id}');
|
|
$this->assertEquals('second', ($templateRef->handler)());
|
|
}
|
|
|
|
public function testResourceTemplateMatchingPrefersMoreSpecificMatches(): void
|
|
{
|
|
$specificTemplate = $this->createValidResourceTemplate('test://users/{userId}/profile');
|
|
$genericTemplate = $this->createValidResourceTemplate('test://users/{userId}');
|
|
|
|
$this->registry->registerResourceTemplate($genericTemplate, static fn () => 'generic');
|
|
$this->registry->registerResourceTemplate($specificTemplate, static fn () => 'specific');
|
|
|
|
// Should match the more specific template first
|
|
$resourceRef = $this->registry->getResource('test://users/123/profile');
|
|
$this->assertInstanceOf(ResourceTemplateReference::class, $resourceRef);
|
|
$this->assertEquals('test://users/{userId}/profile', $resourceRef->resourceTemplate->uriTemplate);
|
|
}
|
|
|
|
public function testGetResourceTemplateThrowsExceptionForUnregisteredTemplate(): void
|
|
{
|
|
$this->expectException(ResourceNotFoundException::class);
|
|
$this->expectExceptionMessage('Resource not found for uri: "test://{non_existent}".');
|
|
|
|
$this->registry->getResourceTemplate('test://{non_existent}');
|
|
}
|
|
|
|
public function testHasPromptsReturnsTrueWhenPromptIsRegistered(): void
|
|
{
|
|
$prompt = $this->createValidPrompt('test_prompt');
|
|
$this->registry->registerPrompt($prompt, static fn () => []);
|
|
|
|
$this->assertTrue($this->registry->hasPrompts());
|
|
}
|
|
|
|
public function testGetPromptsReturnsAllRegisteredPrompts(): void
|
|
{
|
|
$prompt1 = $this->createValidPrompt('prompt1');
|
|
$prompt2 = $this->createValidPrompt('prompt2');
|
|
|
|
$this->registry->registerPrompt($prompt1, static fn () => []);
|
|
$this->registry->registerPrompt($prompt2, static fn () => []);
|
|
|
|
$prompts = $this->registry->getPrompts();
|
|
$this->assertCount(2, $prompts);
|
|
$this->assertArrayHasKey('prompt1', $prompts->references);
|
|
$this->assertArrayHasKey('prompt2', $prompts->references);
|
|
$this->assertInstanceOf(Prompt::class, $prompts->references['prompt1']);
|
|
$this->assertInstanceOf(Prompt::class, $prompts->references['prompt2']);
|
|
}
|
|
|
|
public function testGetPromptReturnsRegisteredPrompt(): void
|
|
{
|
|
$prompt = $this->createValidPrompt('test_prompt');
|
|
$handler = static fn () => ['role' => 'user', 'content' => 'test message'];
|
|
|
|
$this->registry->registerPrompt($prompt, $handler);
|
|
|
|
$promptRef = $this->registry->getPrompt('test_prompt');
|
|
$this->assertInstanceOf(PromptReference::class, $promptRef);
|
|
$this->assertEquals($prompt->name, $promptRef->prompt->name);
|
|
$this->assertEquals($handler, $promptRef->handler);
|
|
}
|
|
|
|
public function testRegisterPromptWithCompletionProviders(): void
|
|
{
|
|
$prompt = $this->createValidPrompt('test_prompt');
|
|
$completionProviders = ['param' => EnumCompletionProvider::class];
|
|
|
|
$this->registry->registerPrompt($prompt, static fn () => [], $completionProviders);
|
|
|
|
$promptRef = $this->registry->getPrompt('test_prompt');
|
|
$this->assertEquals($completionProviders, $promptRef->completionProviders);
|
|
}
|
|
|
|
public function testRegisterPromptOverwritesPriorRegistration(): void
|
|
{
|
|
$first = $this->createValidPrompt('test_prompt');
|
|
$second = $this->createValidPrompt('test_prompt');
|
|
|
|
$this->registry->registerPrompt($first, static fn () => 'first');
|
|
$this->registry->registerPrompt($second, static fn () => 'second');
|
|
|
|
$promptRef = $this->registry->getPrompt('test_prompt');
|
|
$this->assertEquals('second', ($promptRef->handler)());
|
|
}
|
|
|
|
public function testGetPromptThrowsExceptionForUnregisteredPrompt(): void
|
|
{
|
|
$this->expectException(PromptNotFoundException::class);
|
|
$this->expectExceptionMessage('Prompt not found: "non_existent_prompt".');
|
|
|
|
$this->registry->getPrompt('non_existent_prompt');
|
|
}
|
|
|
|
public function testUnregisterToolRemovesRegisteredTool(): void
|
|
{
|
|
$tool = $this->createValidTool('test_tool');
|
|
$this->registry->registerTool($tool, static fn () => 'result');
|
|
|
|
$this->registry->unregisterTool('test_tool');
|
|
|
|
$this->expectException(ToolNotFoundException::class);
|
|
$this->registry->getTool('test_tool');
|
|
}
|
|
|
|
public function testUnregisterToolIsIdempotentForAbsentName(): void
|
|
{
|
|
$this->registry->unregisterTool('never_registered');
|
|
|
|
$this->assertFalse($this->registry->hasTools());
|
|
}
|
|
|
|
public function testUnregisterResourceRemovesRegisteredResource(): void
|
|
{
|
|
$resource = $this->createValidResource('test://resource');
|
|
$this->registry->registerResource($resource, static fn () => 'content');
|
|
|
|
$this->registry->unregisterResource('test://resource');
|
|
|
|
$this->expectException(ResourceNotFoundException::class);
|
|
$this->registry->getResource('test://resource', false);
|
|
}
|
|
|
|
public function testUnregisterResourceTemplateRemovesRegisteredTemplate(): void
|
|
{
|
|
$template = $this->createValidResourceTemplate('test://{id}');
|
|
$this->registry->registerResourceTemplate($template, static fn () => 'content');
|
|
|
|
$this->registry->unregisterResourceTemplate('test://{id}');
|
|
|
|
$this->expectException(ResourceNotFoundException::class);
|
|
$this->registry->getResourceTemplate('test://{id}');
|
|
}
|
|
|
|
public function testUnregisterPromptRemovesRegisteredPrompt(): void
|
|
{
|
|
$prompt = $this->createValidPrompt('test_prompt');
|
|
$this->registry->registerPrompt($prompt, static fn () => []);
|
|
|
|
$this->registry->unregisterPrompt('test_prompt');
|
|
|
|
$this->expectException(PromptNotFoundException::class);
|
|
$this->registry->getPrompt('test_prompt');
|
|
}
|
|
|
|
public function testRegisterToolHandlesStringHandler(): void
|
|
{
|
|
$tool = $this->createValidTool('test_tool');
|
|
$handler = 'TestClass::testMethod';
|
|
|
|
$this->registry->registerTool($tool, $handler);
|
|
|
|
$toolRef = $this->registry->getTool('test_tool');
|
|
$this->assertEquals($handler, $toolRef->handler);
|
|
}
|
|
|
|
public function testRegisterToolHandlesArrayHandler(): void
|
|
{
|
|
$tool = $this->createValidTool('test_tool');
|
|
$handler = ['TestClass', 'testMethod'];
|
|
|
|
$this->registry->registerTool($tool, $handler);
|
|
|
|
$toolRef = $this->registry->getTool('test_tool');
|
|
$this->assertEquals($handler, $toolRef->handler);
|
|
}
|
|
|
|
public function testRegisterResourceHandlesCallableHandler(): void
|
|
{
|
|
$resource = $this->createValidResource('test://resource');
|
|
$handler = static fn () => 'content';
|
|
|
|
$this->registry->registerResource($resource, $handler);
|
|
|
|
$resourceRef = $this->registry->getResource('test://resource');
|
|
$this->assertEquals($handler, $resourceRef->handler);
|
|
}
|
|
|
|
public function testMultipleRegistrationsOfSameElementWithSameType(): void
|
|
{
|
|
$tool1 = $this->createValidTool('test_tool');
|
|
$tool2 = $this->createValidTool('test_tool');
|
|
|
|
$this->registry->registerTool($tool1, static fn () => 'first');
|
|
$this->registry->registerTool($tool2, static fn () => 'second');
|
|
|
|
// Second registration should override the first
|
|
$toolRef = $this->registry->getTool('test_tool');
|
|
$this->assertEquals('second', ($toolRef->handler)());
|
|
}
|
|
|
|
public function testExtractStructuredContentReturnsNullWhenOutputSchemaIsNull(): void
|
|
{
|
|
$tool = $this->createValidTool('test_tool', null);
|
|
$this->registry->registerTool($tool, static fn () => 'result');
|
|
|
|
$toolRef = $this->registry->getTool('test_tool');
|
|
$this->assertNull($toolRef->extractStructuredContent('result'));
|
|
}
|
|
|
|
public function testExtractStructuredContentReturnsArrayMatchingSchema(): void
|
|
{
|
|
$tool = $this->createValidTool('test_tool', [
|
|
'type' => 'object',
|
|
'properties' => [
|
|
'param' => ['type' => 'string'],
|
|
],
|
|
'required' => ['param'],
|
|
]);
|
|
$this->registry->registerTool($tool, static fn () => [
|
|
'param' => 'test',
|
|
]);
|
|
|
|
$toolRef = $this->registry->getTool('test_tool');
|
|
$this->assertEquals([
|
|
'param' => 'test',
|
|
], $toolRef->extractStructuredContent([
|
|
'param' => 'test',
|
|
]));
|
|
}
|
|
|
|
public function testExtractStructuredContentReturnsArrayDirectlyForAdditionalProperties(): void
|
|
{
|
|
$tool = $this->createValidTool('test_tool', [
|
|
'type' => 'object',
|
|
'additionalProperties' => true,
|
|
]);
|
|
$this->registry->registerTool($tool, static fn () => ['success' => true, 'message' => 'done']);
|
|
|
|
$toolRef = $this->registry->getTool('test_tool');
|
|
$this->assertEquals(['success' => true, 'message' => 'done'], $toolRef->extractStructuredContent(['success' => true, 'message' => 'done']));
|
|
}
|
|
|
|
public function testExtractStructuredContentReturnsArrayDirectlyForArrayOutputSchema(): void
|
|
{
|
|
// Arrange
|
|
$outputSchema = [
|
|
'type' => 'array',
|
|
'items' => [
|
|
'type' => 'object',
|
|
'properties' => [
|
|
'foo' => [
|
|
'type' => 'string',
|
|
'description' => 'A static value',
|
|
],
|
|
],
|
|
'required' => ['foo'],
|
|
],
|
|
];
|
|
|
|
$tool = $this->createValidTool('list_static_data', $outputSchema);
|
|
$toolReturnValue = [
|
|
['foo' => 'bar'],
|
|
['foo' => 'bar'],
|
|
['foo' => 'bar'],
|
|
['foo' => 'bar'],
|
|
];
|
|
|
|
$this->registry->registerTool($tool, static fn () => $toolReturnValue);
|
|
|
|
// Act
|
|
$toolRef = $this->registry->getTool('list_static_data');
|
|
$structuredContent = $toolRef->extractStructuredContent($toolReturnValue);
|
|
|
|
// Assert
|
|
$this->assertNotNull($structuredContent);
|
|
$this->assertCount(4, $structuredContent);
|
|
$this->assertEquals([
|
|
['foo' => 'bar'],
|
|
['foo' => 'bar'],
|
|
['foo' => 'bar'],
|
|
['foo' => 'bar'],
|
|
], $structuredContent);
|
|
}
|
|
|
|
private function createValidTool(string $name, ?array $outputSchema = null): Tool
|
|
{
|
|
return new Tool(
|
|
name: $name,
|
|
title: null,
|
|
inputSchema: [
|
|
'type' => 'object',
|
|
'properties' => [
|
|
'param' => ['type' => 'string'],
|
|
],
|
|
'required' => null,
|
|
],
|
|
description: "Test tool: {$name}",
|
|
annotations: null,
|
|
icons: null,
|
|
meta: null,
|
|
outputSchema: $outputSchema
|
|
);
|
|
}
|
|
|
|
private function createValidResource(string $uri): ResourceDefinition
|
|
{
|
|
return new ResourceDefinition(
|
|
uri: $uri,
|
|
name: 'test_resource',
|
|
description: 'Test resource',
|
|
mimeType: 'text/plain',
|
|
);
|
|
}
|
|
|
|
private function createValidResourceTemplate(string $uriTemplate): ResourceTemplate
|
|
{
|
|
return new ResourceTemplate(
|
|
uriTemplate: $uriTemplate,
|
|
name: 'test_template',
|
|
description: 'Test resource template',
|
|
mimeType: 'text/plain',
|
|
);
|
|
}
|
|
|
|
private function createValidPrompt(string $name): Prompt
|
|
{
|
|
return new Prompt(
|
|
name: $name,
|
|
description: "Test prompt: {$name}",
|
|
arguments: [],
|
|
);
|
|
}
|
|
}
|