-
-
Notifications
You must be signed in to change notification settings - Fork 968
fix(mcp): make tools/list resilient to an empty registry #8371
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
soyuka
wants to merge
2
commits into
api-platform:4.3
Choose a base branch
from
soyuka:fix-mcp-tools-list-8370
base: 4.3
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+235
−0
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,82 @@ | ||
| <?php | ||
|
|
||
| /* | ||
| * This file is part of the API Platform project. | ||
| * | ||
| * (c) Kévin Dunglas <dunglas@gmail.com> | ||
| * | ||
| * For the full copyright and license information, please view the LICENSE | ||
| * file that was distributed with this source code. | ||
| */ | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace ApiPlatform\Mcp\Server; | ||
|
|
||
| use Mcp\Capability\Registry\Loader\LoaderInterface; | ||
| use Mcp\Capability\RegistryInterface; | ||
| use Mcp\Schema\JsonRpc\Request; | ||
| use Mcp\Schema\JsonRpc\Response; | ||
| use Mcp\Schema\Request\ListResourcesRequest; | ||
| use Mcp\Schema\Request\ListToolsRequest; | ||
| use Mcp\Schema\Result\ListResourcesResult; | ||
| use Mcp\Schema\Result\ListToolsResult; | ||
| use Mcp\Server\Handler\Request\RequestHandlerInterface; | ||
| use Mcp\Server\Session\SessionInterface; | ||
|
|
||
| /** | ||
| * Serves tools/list and resources/list from the MCP registry, loading API Platform elements | ||
| * into it on first use. | ||
| * | ||
| * The SDK populates the registry once, when mcp.server is built. Under a persistent runtime | ||
| * (e.g. FrankenPHP worker mode) that single build can capture an empty registry (cold metadata | ||
| * cache) and stays empty for the whole process, so tools/list returns [] while tools/call keeps | ||
| * working through the request-time {@see Handler}. Loading the API Platform elements lazily here | ||
| * heals that: it runs once per process (registrations are idempotent by name) and reads back | ||
| * through the shared registry, so runtime registrations and registry decorators are preserved. | ||
| * | ||
| * Tagged mcp.request_handler, it takes precedence over the SDK's registry-backed list handlers. | ||
| * | ||
| * @experimental | ||
| * TODO: remove once php-sdk:^0.7 has https://github.com/modelcontextprotocol/php-sdk/pull/389/changes | ||
| * | ||
| * @implements RequestHandlerInterface<ListToolsResult|ListResourcesResult> | ||
| */ | ||
| final class ListHandler implements RequestHandlerInterface | ||
| { | ||
| private bool $loaded = false; | ||
|
|
||
| public function __construct( | ||
| private readonly RegistryInterface $registry, | ||
| private readonly LoaderInterface $loader, | ||
| private readonly int $pageSize = 20, | ||
| ) { | ||
| } | ||
|
|
||
| public function supports(Request $request): bool | ||
| { | ||
| return $request instanceof ListToolsRequest || $request instanceof ListResourcesRequest; | ||
| } | ||
|
|
||
| /** | ||
| * @return Response<ListToolsResult|ListResourcesResult> | ||
| */ | ||
| public function handle(Request $request, SessionInterface $session): Response | ||
| { | ||
| if (!$this->loaded) { | ||
| $this->loader->load($this->registry); | ||
| $this->loaded = true; | ||
| } | ||
|
|
||
| if ($request instanceof ListResourcesRequest) { | ||
| $page = $this->registry->getResources($this->pageSize, $request->cursor); | ||
| $result = new ListResourcesResult($page->references, $page->nextCursor); | ||
| } else { | ||
| \assert($request instanceof ListToolsRequest); | ||
| $page = $this->registry->getTools($this->pageSize, $request->cursor); | ||
| $result = new ListToolsResult($page->references, $page->nextCursor); | ||
| } | ||
|
|
||
| return new Response($request->getId(), $result); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,140 @@ | ||
| <?php | ||
|
|
||
| /* | ||
| * This file is part of the API Platform project. | ||
| * | ||
| * (c) Kévin Dunglas <dunglas@gmail.com> | ||
| * | ||
| * For the full copyright and license information, please view the LICENSE | ||
| * file that was distributed with this source code. | ||
| */ | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace ApiPlatform\Mcp\Tests\Server; | ||
|
|
||
| use ApiPlatform\JsonSchema\Schema; | ||
| use ApiPlatform\JsonSchema\SchemaFactoryInterface; | ||
| use ApiPlatform\Mcp\Capability\Registry\Loader; | ||
| use ApiPlatform\Mcp\Server\ListHandler; | ||
| use ApiPlatform\Metadata\ApiResource; | ||
| use ApiPlatform\Metadata\McpResource; | ||
| use ApiPlatform\Metadata\McpTool; | ||
| use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface; | ||
| use ApiPlatform\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface; | ||
| use ApiPlatform\Metadata\Resource\ResourceMetadataCollection; | ||
| use ApiPlatform\Metadata\Resource\ResourceNameCollection; | ||
| use Mcp\Capability\Registry; | ||
| use Mcp\Capability\Registry\Loader\LoaderInterface; | ||
| use Mcp\Capability\RegistryInterface; | ||
| use Mcp\Schema\Request\ListResourcesRequest; | ||
| use Mcp\Schema\Request\ListToolsRequest; | ||
| use Mcp\Schema\Result\ListResourcesResult; | ||
| use Mcp\Schema\Result\ListToolsResult; | ||
| use Mcp\Schema\Tool; | ||
| use Mcp\Server\Session\SessionInterface; | ||
| use PHPUnit\Framework\TestCase; | ||
|
|
||
| class ListHandlerTest extends TestCase | ||
| { | ||
| public function testListToolsLoadsApiPlatformElementsIntoTheRegistry(): void | ||
| { | ||
| $inputSchema = new Schema(Schema::VERSION_JSON_SCHEMA); | ||
| unset($inputSchema['$schema']); | ||
| $inputSchema['type'] = 'object'; | ||
| $inputSchema['properties'] = ['query' => ['type' => 'string']]; | ||
|
|
||
| $schemaFactory = $this->createMock(SchemaFactoryInterface::class); | ||
| $schemaFactory->method('buildSchema')->willReturn($inputSchema); | ||
|
|
||
| $mcpTool = new McpTool( | ||
| name: 'search', | ||
| description: 'Search things', | ||
| structuredContent: false, | ||
| class: \stdClass::class, | ||
| ); | ||
|
|
||
| $resource = (new ApiResource(class: \stdClass::class))->withMcp(['search' => $mcpTool]); | ||
|
|
||
| $registry = new Registry(); | ||
| $handler = new ListHandler($registry, $this->createLoader($resource, $schemaFactory)); | ||
|
|
||
| $result = $handler->handle((new ListToolsRequest())->withId(1), $this->createMock(SessionInterface::class))->result; | ||
|
|
||
| $this->assertInstanceOf(ListToolsResult::class, $result); | ||
| $this->assertCount(1, $result->tools); | ||
| $this->assertSame('search', $result->tools[0]->name); | ||
| } | ||
|
|
||
| public function testListResourcesLoadsApiPlatformElementsIntoTheRegistry(): void | ||
| { | ||
| $mcpResource = new McpResource( | ||
| uri: 'dummy://docs', | ||
| name: 'docs', | ||
| description: 'Documentation resource', | ||
| mimeType: 'text/plain', | ||
| class: \stdClass::class, | ||
| ); | ||
|
|
||
| $resource = (new ApiResource(class: \stdClass::class))->withMcp(['docs' => $mcpResource]); | ||
|
|
||
| $registry = new Registry(); | ||
| $handler = new ListHandler($registry, $this->createLoader($resource, $this->createMock(SchemaFactoryInterface::class))); | ||
|
|
||
| $result = $handler->handle((new ListResourcesRequest())->withId(1), $this->createMock(SessionInterface::class))->result; | ||
|
|
||
| $this->assertInstanceOf(ListResourcesResult::class, $result); | ||
| $this->assertCount(1, $result->resources); | ||
| $this->assertSame('dummy://docs', $result->resources[0]->uri); | ||
| } | ||
|
|
||
| /** | ||
| * Reading through the shared registry (rather than a private one) keeps tools registered at | ||
| * runtime — e.g. dynamically discovered affordances — visible in tools/list. | ||
| */ | ||
| public function testListToolsIncludesToolsRegisteredAtRuntime(): void | ||
| { | ||
| $registry = new Registry(); | ||
| $registry->registerTool(new Tool(name: 'runtime_tool', title: null, inputSchema: ['type' => 'object', 'properties' => [], 'required' => null], description: null, annotations: null), 'runtime_handler'); | ||
|
|
||
| $loader = $this->createMock(LoaderInterface::class); | ||
| $handler = new ListHandler($registry, $loader); | ||
|
|
||
| $result = $handler->handle((new ListToolsRequest())->withId(1), $this->createMock(SessionInterface::class))->result; | ||
|
|
||
| $names = array_map(static fn (Tool $t): string => $t->name, $result->tools); | ||
| $this->assertContains('runtime_tool', $names); | ||
| } | ||
|
|
||
| public function testElementsAreLoadedOncePerProcess(): void | ||
| { | ||
| $registry = $this->createMock(RegistryInterface::class); | ||
| $registry->method('getTools')->willReturn(new \Mcp\Schema\Page([], null)); | ||
|
|
||
| $loader = $this->createMock(LoaderInterface::class); | ||
| $loader->expects($this->once())->method('load'); | ||
|
|
||
| $handler = new ListHandler($registry, $loader); | ||
| $handler->handle((new ListToolsRequest())->withId(1), $this->createMock(SessionInterface::class)); | ||
| $handler->handle((new ListToolsRequest())->withId(2), $this->createMock(SessionInterface::class)); | ||
| } | ||
|
|
||
| public function testSupportsListRequests(): void | ||
| { | ||
| $handler = new ListHandler($this->createMock(RegistryInterface::class), $this->createMock(LoaderInterface::class)); | ||
|
|
||
| $this->assertTrue($handler->supports(new ListToolsRequest())); | ||
| $this->assertTrue($handler->supports(new ListResourcesRequest())); | ||
| } | ||
|
|
||
| private function createLoader(ApiResource $resource, SchemaFactoryInterface $schemaFactory): Loader | ||
| { | ||
| $nameCollectionFactory = $this->createMock(ResourceNameCollectionFactoryInterface::class); | ||
| $nameCollectionFactory->method('create')->willReturn(new ResourceNameCollection([\stdClass::class])); | ||
|
|
||
| $metadataCollectionFactory = $this->createMock(ResourceMetadataCollectionFactoryInterface::class); | ||
| $metadataCollectionFactory->method('create')->willReturn(new ResourceMetadataCollection(\stdClass::class, [$resource])); | ||
|
|
||
| return new Loader($nameCollectionFactory, $metadataCollectionFactory, $schemaFactory); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.