From 1051ca9e4b7f68cf2de0cdcee31c75bbb426968a Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Sat, 21 Nov 2026 03:55:18 +0100 Subject: [PATCH 1/4] [Schema][Server] Add icons to resource templates ResourceTemplate extends Icons since protocol revision 2025-11-25, like Resource, Tool and Prompt. The template now parses and serializes the field, and #[McpResourceTemplate] and Builder::addResourceTemplate() accept it, so resources/templates/list can carry icons. The new parameter comes last to keep positional calls working. --- CHANGELOG.md | 5 ++ docs/run/server-builder.md | 2 +- docs/servers/registration.md | 1 + docs/servers/resource-templates.md | 1 + src/Schema/ResourceTemplate.php | 11 +++- src/Server/Builder.php | 6 ++- .../Attribute/McpResourceTemplate.php | 3 ++ .../Capability/Discovery/Discoverer.php | 2 +- .../Loader/ReflectedElementLoader.php | 4 +- tests/Unit/Schema/ResourceTemplateTest.php | 52 +++++++++++++++++++ tests/Unit/Server/BuilderTest.php | 14 +++++ .../Attribute/McpResourceTemplateTest.php | 11 ++++ .../Capability/Discovery/DiscoveryTest.php | 4 ++ .../Fixtures/DiscoverableTemplateHandler.php | 4 +- ...eflectedElementLoaderResourceTitleTest.php | 27 ++++++++++ .../ListResourceTemplatesHandlerTest.php | 20 +++++++ 16 files changed, 161 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c977af64c..5e5a5a172 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,11 @@ All notable changes to `mcp/sdk` will be documented in this file. ### Server * Fix const validation errors always reporting the expected value as null. +* Add `icons` to `#[McpResourceTemplate]` and `Builder::addResourceTemplate()`. + +### Schema + +* Add `icons` to `ResourceTemplate`, so `resources/templates/list` carries them. 0.10.0 ------ diff --git a/docs/run/server-builder.md b/docs/run/server-builder.md index 56cfbdc34..b3900a9ff 100644 --- a/docs/run/server-builder.md +++ b/docs/run/server-builder.md @@ -516,7 +516,7 @@ $server = Server::builder() | `addNotificationHandlers()` | handlers | Prepend multiple custom notification handlers | | `addTool()` | handler, name?, title?, description?, annotations?, inputSchema?, icons?, meta?, outputSchema? | Register tool | | `addResource()` | handler, uri, name?, title?, description?, mimeType?, size?, annotations?, icons?, meta? | Register resource | -| `addResourceTemplate()` | handler, uriTemplate, name?, title?, description?, mimeType?, annotations?, meta? | Register resource template | +| `addResourceTemplate()` | handler, uriTemplate, name?, title?, description?, mimeType?, annotations?, meta?, icons? | Register resource template | | `addPrompt()` | handler, name?, title?, description?, icons?, meta? | Register prompt | | `add()` | definition, handler, completionProviders? | Register an element from a schema VO + handler pair, see [Explicit element registration](../servers/registration.md#explicit-element-registration) | | `build()` | - | Create the server instance | diff --git a/docs/servers/registration.md b/docs/servers/registration.md index 445114c31..4c4654720 100644 --- a/docs/servers/registration.md +++ b/docs/servers/registration.md @@ -162,6 +162,7 @@ $server = Server::builder() - `mimeType` (string|null): Optional MIME type of the resource - `annotations` (Annotations|null): Optional annotations for the resource template - `meta` (array|null): Optional metadata for the resource template +- `icons` (Icon[]|null): Optional array of icons for the resource template ### Manual Prompt Registration diff --git a/docs/servers/resource-templates.md b/docs/servers/resource-templates.md index c6c552359..608419896 100644 --- a/docs/servers/resource-templates.md +++ b/docs/servers/resource-templates.md @@ -40,6 +40,7 @@ class UserProvider - **`mimeType`** (optional): MIME type of the resource content. - **`annotations`** (optional): Additional metadata. - **`meta`** (optional): Arbitrary key-value pairs for custom metadata. +- **`icons`** (optional): Array of `Icon` objects for visual representation. ## Variable Rules diff --git a/src/Schema/ResourceTemplate.php b/src/Schema/ResourceTemplate.php index c89d04906..ab446e84a 100644 --- a/src/Schema/ResourceTemplate.php +++ b/src/Schema/ResourceTemplate.php @@ -17,6 +17,7 @@ * A template description for resources available on the server. * * @phpstan-import-type AnnotationsData from Annotations + * @phpstan-import-type IconData from Icon * * @phpstan-type ResourceTemplateData array{ * uriTemplate: string, @@ -25,6 +26,7 @@ * description?: string|null, * mimeType?: string|null, * annotations?: AnnotationsData|null, + * icons?: IconData[], * _meta?: array * } * @@ -46,6 +48,7 @@ class ResourceTemplate implements \JsonSerializable * @param ?string $mimeType the MIME type for all resources that match this template, if uniform * @param ?Annotations $annotations optional annotations for the client * @param ?array $meta optional metadata + * @param ?Icon[] $icons optional icons representing the resource template */ public function __construct( public readonly string $uriTemplate, @@ -55,6 +58,7 @@ public function __construct( public readonly ?string $mimeType = null, public readonly ?Annotations $annotations = null, public readonly ?array $meta = null, + public readonly ?array $icons = null, ) { if (!preg_match(self::URI_TEMPLATE_PATTERN, $uriTemplate)) { throw new InvalidArgumentException(\sprintf('Invalid URI template : "%s" must be a valid URI template with at least one placeholder.', $uriTemplate)); @@ -90,7 +94,8 @@ public static function fromArray(array $data): self description: $data['description'] ?? null, mimeType: $data['mimeType'] ?? null, annotations: Annotations::tryFromArray($data['annotations'] ?? null, 'ResourceTemplate'), - meta: isset($data['_meta']) ? $data['_meta'] : null + meta: isset($data['_meta']) ? $data['_meta'] : null, + icons: isset($data['icons']) && \is_array($data['icons']) ? Icon::listFromArray($data['icons'], 'ResourceTemplate') : null, ); } @@ -102,6 +107,7 @@ public static function fromArray(array $data): self * description?: string, * mimeType?: string, * annotations?: Annotations, + * icons?: Icon[], * _meta?: array * } */ @@ -123,6 +129,9 @@ public function jsonSerialize(): array if (null !== $this->annotations) { $data['annotations'] = $this->annotations; } + if (null !== $this->icons) { + $data['icons'] = $this->icons; + } if (null !== $this->meta) { $data['_meta'] = $this->meta; } diff --git a/src/Server/Builder.php b/src/Server/Builder.php index aa8a850da..e119c54f8 100644 --- a/src/Server/Builder.php +++ b/src/Server/Builder.php @@ -208,7 +208,8 @@ final class Builder * description: ?string, * mimeType: ?string, * annotations: ?Annotations, - * meta: ?array + * meta: ?array, + * icons: ?Icon[] * }[] */ private array $resourceTemplates = []; @@ -834,6 +835,7 @@ public function addResource( * @param Handler $handler * @param ?string $title Optional human-readable title for display in UI * @param array|null $meta + * @param ?Icon[] $icons */ public function addResourceTemplate( \Closure|array|string $handler, @@ -844,6 +846,7 @@ public function addResourceTemplate( ?string $mimeType = null, ?Annotations $annotations = null, ?array $meta = null, + ?array $icons = null, ): self { $this->resourceTemplates[] = compact( 'handler', @@ -854,6 +857,7 @@ public function addResourceTemplate( 'mimeType', 'annotations', 'meta', + 'icons', ); return $this; diff --git a/src/Server/Capability/Attribute/McpResourceTemplate.php b/src/Server/Capability/Attribute/McpResourceTemplate.php index f4d802e1b..9878ddb2f 100644 --- a/src/Server/Capability/Attribute/McpResourceTemplate.php +++ b/src/Server/Capability/Attribute/McpResourceTemplate.php @@ -12,6 +12,7 @@ namespace Mcp\Server\Capability\Attribute; use Mcp\Schema\Annotations; +use Mcp\Schema\Icon; /** * Marks a PHP class definition as representing an MCP Resource Template. @@ -30,6 +31,7 @@ class McpResourceTemplate * @param ?string $mimeType optional default MIME type for matching resources * @param ?Annotations $annotations optional annotations describing the resource template * @param ?array $meta optional metadata + * @param ?Icon[] $icons optional icons representing the resource template */ public function __construct( public string $uriTemplate, @@ -39,6 +41,7 @@ public function __construct( public ?string $mimeType = null, public ?Annotations $annotations = null, public ?array $meta = null, + public ?array $icons = null, ) { } } diff --git a/src/Server/Capability/Discovery/Discoverer.php b/src/Server/Capability/Discovery/Discoverer.php index 5e9955ced..d9b279766 100644 --- a/src/Server/Capability/Discovery/Discoverer.php +++ b/src/Server/Capability/Discovery/Discoverer.php @@ -281,7 +281,7 @@ private function processMethod(\ReflectionMethod $method, array &$discoveredCoun } elseif ($instance instanceof McpResourceTemplate) { $name = ElementMetadataResolver::resolveName($method, $instance->name); $description = ElementMetadataResolver::resolveDescription($method, $instance->description, $this->docBlockParser); - $resourceTemplate = new ResourceTemplate($instance->uriTemplate, $name, $instance->title, $description, $instance->mimeType, $instance->annotations, $instance->meta); + $resourceTemplate = new ResourceTemplate($instance->uriTemplate, $name, $instance->title, $description, $instance->mimeType, $instance->annotations, $instance->meta, $instance->icons); $completionProviders = $this->getCompletionProviders($method); $resourceTemplates[$instance->uriTemplate] = new ResourceTemplateReference($resourceTemplate, [$className, $methodName], $completionProviders); ++$discoveredCount['resourceTemplates']; diff --git a/src/Server/Capability/Registry/Loader/ReflectedElementLoader.php b/src/Server/Capability/Registry/Loader/ReflectedElementLoader.php index 60fff503e..4d9d5c3bf 100644 --- a/src/Server/Capability/Registry/Loader/ReflectedElementLoader.php +++ b/src/Server/Capability/Registry/Loader/ReflectedElementLoader.php @@ -73,7 +73,8 @@ final class ReflectedElementLoader implements LoaderInterface * description: ?string, * mimeType: ?string, * annotations: ?Annotations, - * meta: ?array + * meta: ?array, + * icons?: ?Icon[] * }[] $resourceTemplates * @param array{ * handler: Handler, @@ -197,6 +198,7 @@ public function load(RegistryInterface $registry): void mimeType: $data['mimeType'] ?? null, annotations: $data['annotations'] ?? null, meta: $data['meta'] ?? null, + icons: $data['icons'] ?? null, ); $completionProviders = $this->getCompletionProviders($reflection); $registry->registerResourceTemplate($template, $data['handler'], $completionProviders); diff --git a/tests/Unit/Schema/ResourceTemplateTest.php b/tests/Unit/Schema/ResourceTemplateTest.php index 4c6edfa1e..be777c20e 100644 --- a/tests/Unit/Schema/ResourceTemplateTest.php +++ b/tests/Unit/Schema/ResourceTemplateTest.php @@ -12,6 +12,7 @@ namespace Mcp\Tests\Unit\Schema; use Mcp\Schema\Exception\InvalidArgumentException; +use Mcp\Schema\Icon; use Mcp\Schema\ResourceTemplate; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; @@ -78,6 +79,49 @@ public function testFromArrayValid(): void $this->assertNull($resource->title); $this->assertNull($resource->description); $this->assertNull($resource->meta); + $this->assertNull($resource->icons); + } + + public function testIconsFromArray(): void + { + $resource = ResourceTemplate::fromArray([ + 'uriTemplate' => self::VALID_URI, + 'name' => 'list-books', + 'icons' => [ + ['src' => 'https://example.com/books.png', 'mimeType' => 'image/png', 'sizes' => ['48x48']], + ], + ]); + + $this->assertIsArray($resource->icons); + $this->assertCount(1, $resource->icons); + $this->assertInstanceOf(Icon::class, $resource->icons[0]); + $this->assertSame('https://example.com/books.png', $resource->icons[0]->src); + $this->assertSame('image/png', $resource->icons[0]->mimeType); + $this->assertSame(['48x48'], $resource->icons[0]->sizes); + } + + public function testIconsSerialization(): void + { + $resource = new ResourceTemplate( + uriTemplate: self::VALID_URI, + name: 'list-books', + icons: [new Icon('https://example.com/books.png', 'image/png', ['48x48'])], + ); + + $this->assertSame( + '{"uriTemplate":"https:\\/\\/example.com\\/list-books\\/{id}","name":"list-books","icons":[{"src":"https:\\/\\/example.com\\/books.png","mimeType":"image\\/png","sizes":["48x48"]}]}', + json_encode($resource), + ); + } + + public function testIconsOmittedWhenNull(): void + { + $resource = new ResourceTemplate( + uriTemplate: self::VALID_URI, + name: 'list-books', + ); + + $this->assertArrayNotHasKey('icons', $resource->jsonSerialize()); } public function testTitleFromArray(): void @@ -162,5 +206,13 @@ public static function provideInvalidResources(): iterable ], 'Invalid "_meta" in ResourceTemplate data.', ]; + yield 'icons entry that is not an object' => [ + [ + 'uriTemplate' => self::VALID_URI, + 'name' => 'list-books', + 'icons' => ['https://example.com/books.png'], + ], + 'Each entry in "icons" of ResourceTemplate data must be an array.', + ]; } } diff --git a/tests/Unit/Server/BuilderTest.php b/tests/Unit/Server/BuilderTest.php index 32acdf3a1..43b55815d 100644 --- a/tests/Unit/Server/BuilderTest.php +++ b/tests/Unit/Server/BuilderTest.php @@ -16,6 +16,7 @@ use Mcp\Schema\Enum\ProtocolVersion; use Mcp\Schema\Exception\InvalidArgumentException as SchemaInvalidArgumentException; use Mcp\Schema\Extension\Apps\McpApps; +use Mcp\Schema\Icon; use Mcp\Schema\Implementation; use Mcp\Schema\JsonRpc\Response; use Mcp\Schema\Request\CallToolRequest; @@ -623,6 +624,19 @@ public function testAThirdPartyRegistryIsStillLoadedThroughThePlainLoader(): voi ->addTool(static fn (): string => 'ok', 'alpha') ->build(); } + + public function testAddResourceTemplateForwardsIcons(): void + { + $icons = [new Icon('https://example.com/user.png', 'image/png', ['48x48'])]; + $registry = new Registry(); + + Server::builder() + ->setRegistry($registry) + ->addResourceTemplate(static fn (string $userId): string => $userId, 'user://{userId}/avatar', 'user_avatar', icons: $icons) + ->build(); + + $this->assertSame($icons, $registry->getResourceTemplate('user://{userId}/avatar')->resourceTemplate->icons); + } } /** diff --git a/tests/Unit/Server/Capability/Attribute/McpResourceTemplateTest.php b/tests/Unit/Server/Capability/Attribute/McpResourceTemplateTest.php index 571a066fa..9e2078b01 100644 --- a/tests/Unit/Server/Capability/Attribute/McpResourceTemplateTest.php +++ b/tests/Unit/Server/Capability/Attribute/McpResourceTemplateTest.php @@ -11,6 +11,7 @@ namespace Mcp\Tests\Unit\Server\Capability\Attribute; +use Mcp\Schema\Icon; use Mcp\Server\Capability\Attribute\McpResourceTemplate; use PHPUnit\Framework\TestCase; @@ -67,5 +68,15 @@ public function testInstantiatesWithMissingOptionalArguments(): void $this->assertNull($attribute->name); $this->assertNull($attribute->description); $this->assertNull($attribute->mimeType); + $this->assertNull($attribute->icons); + } + + public function testInstantiatesWithIcons(): void + { + $icons = [new Icon('https://example.com/icon.png', 'image/png', ['48x48'])]; + + $attribute = new McpResourceTemplate(uriTemplate: 'tmpl://{key}', icons: $icons); + + $this->assertSame($icons, $attribute->icons); } } diff --git a/tests/Unit/Server/Capability/Discovery/DiscoveryTest.php b/tests/Unit/Server/Capability/Discovery/DiscoveryTest.php index b5987d812..bc67910f7 100644 --- a/tests/Unit/Server/Capability/Discovery/DiscoveryTest.php +++ b/tests/Unit/Server/Capability/Discovery/DiscoveryTest.php @@ -133,6 +133,10 @@ public function testDiscoversAllElementTypesCorrectlyFromFixtureFiles(): void $this->assertEquals('product_details_template', $templates['product://{region}/details/{productId}']->resourceTemplate->name); $this->assertEquals(CompletionProviderFixture::class, $templates['product://{region}/details/{productId}']->completionProviders['region']); $this->assertEqualsCanonicalizing(['region', 'productId'], $templates['product://{region}/details/{productId}']->getVariableNames()); + $this->assertJsonStringEqualsJsonString( + '[{"src":"https://example.com/product.png","mimeType":"image/png","sizes":["48x48"]}]', + json_encode($templates['product://{region}/details/{productId}']->resourceTemplate->icons, \JSON_THROW_ON_ERROR), + ); $this->assertArrayHasKey('invokable://user-profile/{userId}', $templates); $this->assertEquals([InvocableResourceTemplateFixture::class, '__invoke'], $templates['invokable://user-profile/{userId}']->handler); diff --git a/tests/Unit/Server/Capability/Discovery/Fixtures/DiscoverableTemplateHandler.php b/tests/Unit/Server/Capability/Discovery/Fixtures/DiscoverableTemplateHandler.php index 2b84d91a9..6781eb765 100644 --- a/tests/Unit/Server/Capability/Discovery/Fixtures/DiscoverableTemplateHandler.php +++ b/tests/Unit/Server/Capability/Discovery/Fixtures/DiscoverableTemplateHandler.php @@ -11,6 +11,7 @@ namespace Mcp\Tests\Unit\Server\Capability\Discovery\Fixtures; +use Mcp\Schema\Icon; use Mcp\Server\Capability\Attribute\CompletionProvider; use Mcp\Server\Capability\Attribute\McpResourceTemplate; use Mcp\Tests\Unit\Server\Capability\Attribute\CompletionProviderFixture; @@ -28,7 +29,8 @@ class DiscoverableTemplateHandler #[McpResourceTemplate( uriTemplate: 'product://{region}/details/{productId}', name: 'product_details_template', - mimeType: 'application/json' + mimeType: 'application/json', + icons: [new Icon('https://example.com/product.png', 'image/png', ['48x48'])], )] public function getProductDetails( string $productId, diff --git a/tests/Unit/Server/Capability/Registry/Loader/ReflectedElementLoaderResourceTitleTest.php b/tests/Unit/Server/Capability/Registry/Loader/ReflectedElementLoaderResourceTitleTest.php index 2d280bf29..689db9052 100644 --- a/tests/Unit/Server/Capability/Registry/Loader/ReflectedElementLoaderResourceTitleTest.php +++ b/tests/Unit/Server/Capability/Registry/Loader/ReflectedElementLoaderResourceTitleTest.php @@ -11,6 +11,7 @@ namespace Mcp\Tests\Unit\Server\Capability\Registry\Loader; +use Mcp\Schema\Icon; use Mcp\Server\Capability\Registry; use Mcp\Server\Capability\Registry\Loader\ReflectedElementLoader; use Mcp\Server\Capability\Registry\ResourceReference; @@ -68,4 +69,30 @@ public function testLoadPropagatesResourceTemplateTitleToRegisteredTemplate(): v $templateRef = $registry->getResourceTemplate('user://{userId}/profile'); $this->assertSame('User Profile', $templateRef->resourceTemplate->title); } + + public function testLoadPropagatesResourceTemplateIconsToRegisteredTemplate(): void + { + $icons = [new Icon('https://example.com/user.png', 'image/png', ['48x48'])]; + $resourceTemplates = [ + [ + 'handler' => static fn (): string => 'ok', + 'uriTemplate' => 'user://{userId}/avatar', + 'name' => 'user_avatar', + 'title' => null, + 'description' => null, + 'mimeType' => null, + 'annotations' => null, + 'meta' => null, + 'icons' => $icons, + ], + ]; + + $loader = new ReflectedElementLoader([], [], $resourceTemplates); + $registry = new Registry(); + + $loader->load($registry); + + $templateRef = $registry->getResourceTemplate('user://{userId}/avatar'); + $this->assertSame($icons, $templateRef->resourceTemplate->icons); + } } diff --git a/tests/Unit/Server/Handler/Request/ListResourceTemplatesHandlerTest.php b/tests/Unit/Server/Handler/Request/ListResourceTemplatesHandlerTest.php index 397aa329f..0d9830064 100644 --- a/tests/Unit/Server/Handler/Request/ListResourceTemplatesHandlerTest.php +++ b/tests/Unit/Server/Handler/Request/ListResourceTemplatesHandlerTest.php @@ -11,6 +11,7 @@ namespace Mcp\Tests\Unit\Server\Handler\Request; +use Mcp\Schema\Icon; use Mcp\Schema\Request\ListResourceTemplatesRequest; use Mcp\Schema\ResourceTemplate; use Mcp\Schema\Result\ListResourceTemplatesResult; @@ -187,6 +188,25 @@ public function testMaintainsStableCursorsAcrossCalls(): void $this->assertEquals($result1->resourceTemplates, $result2->resourceTemplates); } + public function testListsTemplateIcons(): void + { + $this->registry->registerResourceTemplate( + new ResourceTemplate( + uriTemplate: 'file:///{path}', + name: 'project_files', + icons: [new Icon('https://example.com/folder-icon.png', 'image/png', ['48x48'])], + ), + static fn () => null, + ); + + $response = $this->handler->handle($this->createListResourcesRequest(), $this->session); + + $this->assertJsonStringEqualsJsonString( + '{"resourceTemplates":[{"uriTemplate":"file:///{path}","name":"project_files","icons":[{"src":"https://example.com/folder-icon.png","mimeType":"image/png","sizes":["48x48"]}]}]}', + json_encode($response->result, \JSON_THROW_ON_ERROR), + ); + } + private function addResourcesToRegistry(int $count): void { for ($i = 0; $i < $count; ++$i) { From 55f3769b2494c0738c7dd6ea7a01cad02c186565 Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Sat, 21 Nov 2026 03:58:17 +0100 Subject: [PATCH 2/4] [Schema][Server][Client] Pass completion context to providers Since protocol revision 2025-06-18, completion/complete carries an optional context.arguments with the arguments the user already resolved for the prompt or URI template. CompletionCompleteRequest now parses and serializes it, Client::complete() can send it, and a provider that implements the new ContextAwareProviderInterface receives the arguments. Existing ProviderInterface implementations keep working unchanged. --- CHANGELOG.md | 6 ++ docs/client/capabilities.md | 11 +++ docs/servers/completions.md | 29 ++++++ src/Client/Client.php | 9 +- .../Request/CompletionCompleteRequest.php | 54 +++++++++- .../ContextAwareProviderInterface.php | 31 ++++++ .../Request/CompletionCompleteHandler.php | 7 +- tests/Integration/CompletionTest.php | 24 +++++ .../Fixture/Completion/BookingElements.php | 19 ++++ .../CabinSeatCompletionProvider.php | 42 ++++++++ .../Request/CompletionCompleteRequestTest.php | 81 +++++++++++++++ .../Request/CompletionCompleteHandlerTest.php | 98 +++++++++++++++++-- 12 files changed, 395 insertions(+), 16 deletions(-) create mode 100644 src/Server/Capability/Completion/ContextAwareProviderInterface.php create mode 100644 tests/Integration/Fixture/Completion/CabinSeatCompletionProvider.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 5e5a5a172..14d06e4ec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,10 +9,16 @@ All notable changes to `mcp/sdk` will be documented in this file. * Fix const validation errors always reporting the expected value as null. * Add `icons` to `#[McpResourceTemplate]` and `Builder::addResourceTemplate()`. +* Add `ContextAwareProviderInterface`, a completion provider that receives the arguments the client sent in `context.arguments` of `completion/complete`. + +### Client + +* Add an optional `$context` argument to `Client::complete()`, sent as `context` of `completion/complete`. ### Schema * Add `icons` to `ResourceTemplate`, so `resources/templates/list` carries them. +* Add `context` to `CompletionCompleteRequest`. A `context` or `context.arguments` that is not an object, or an argument value that is not a string, is rejected with `-32602`. 0.10.0 ------ diff --git a/docs/client/capabilities.md b/docs/client/capabilities.md index c63e48676..bf46d087c 100644 --- a/docs/client/capabilities.md +++ b/docs/client/capabilities.md @@ -166,3 +166,14 @@ foreach ($completionResult->values as $value) { echo "Suggestion: {$value}\n"; } ``` + +When the prompt or URI template has several arguments, pass the ones already filled in as `context`, so the server can +narrow its suggestions: + +```php +$completionResult = $client->complete( + ref: new PromptReference('code_review'), + argument: ['name' => 'framework', 'value' => 'fla'], + context: ['arguments' => ['language' => 'python']], +); +``` diff --git a/docs/servers/completions.md b/docs/servers/completions.md index 4024da783..f6d5f9b6b 100644 --- a/docs/servers/completions.md +++ b/docs/servers/completions.md @@ -104,6 +104,35 @@ public function getUserProfile( } ``` +A provider whose suggestions depend on the other arguments implements `ContextAwareProviderInterface` instead. It +receives the arguments the client already resolved, from the request's `context.arguments`: + +```php +use Mcp\Server\Capability\Completion\ContextAwareProviderInterface; + +class FrameworkCompletionProvider implements ContextAwareProviderInterface +{ + private const FRAMEWORKS = [ + 'python' => ['flask', 'django', 'fastapi'], + 'php' => ['symfony', 'laravel'], + ]; + + public function getCompletions(string $currentValue): array + { + return $this->getCompletionsWithContext($currentValue, []); + } + + public function getCompletionsWithContext(string $currentValue, array $arguments): array + { + $frameworks = self::FRAMEWORKS[$arguments['language'] ?? ''] ?? array_merge(...array_values(self::FRAMEWORKS)); + + return array_values(array_filter($frameworks, static fn (string $f): bool => str_starts_with($f, $currentValue))); + } +} +``` + +The context is optional, so the arguments can be empty or miss the ones you look for. + **Provider Resolution:** - **Class strings** (`Provider::class`) → Resolved from the PSR-11 container, or created with `new Provider()` if the container doesn't have it diff --git a/src/Client/Client.php b/src/Client/Client.php index d6214a44b..3d4d5b84d 100644 --- a/src/Client/Client.php +++ b/src/Client/Client.php @@ -340,14 +340,15 @@ public function getPrompt(string $name, array $arguments = [], ?callable $onProg /** * Request completion suggestions for a prompt or resource argument. * - * @param PromptReference|ResourceReference $ref The prompt or resource reference - * @param array{name: string, value: string} $argument The argument to complete + * @param PromptReference|ResourceReference $ref The prompt or resource reference + * @param array{name: string, value: string} $argument The argument to complete + * @param array{arguments?: array}|null $context Previously resolved arguments, sent as `context` * * @throws AuthorizationException|RequestException|ConnectionException|InvalidArgumentException */ - public function complete(PromptReference|ResourceReference $ref, array $argument): CompletionCompleteResult + public function complete(PromptReference|ResourceReference $ref, array $argument, ?array $context = null): CompletionCompleteResult { - $request = new CompletionCompleteRequest($ref, $argument); + $request = new CompletionCompleteRequest($ref, $argument, $context); $response = $this->sendRequest($request); diff --git a/src/Schema/Request/CompletionCompleteRequest.php b/src/Schema/Request/CompletionCompleteRequest.php index bcbf04608..5c1a55f93 100644 --- a/src/Schema/Request/CompletionCompleteRequest.php +++ b/src/Schema/Request/CompletionCompleteRequest.php @@ -24,12 +24,14 @@ final class CompletionCompleteRequest extends Request { /** - * @param PromptReference|ResourceReference $ref the prompt or resource to complete - * @param array{ name: string, value: string } $argument the argument to complete + * @param PromptReference|ResourceReference $ref the prompt or resource to complete + * @param array{ name: string, value: string } $argument the argument to complete + * @param array{ arguments?: array }|null $context previously resolved arguments of the prompt or URI template */ public function __construct( public readonly PromptReference|ResourceReference $ref, public readonly array $argument, + public readonly ?array $context = null, ) { } @@ -57,7 +59,38 @@ protected static function fromParams(?array $params): static return new self($ref, [ 'name' => self::stringMember($params['argument'], 'argument', 'name'), 'value' => self::stringMember($params['argument'], 'argument', 'value'), - ]); + ], self::context($params)); + } + + /** + * @param array $params + * + * @return array{ arguments?: array }|null + */ + private static function context(array $params): ?array + { + if (!isset($params['context'])) { + return null; + } + if (!\is_array($params['context'])) { + throw new InvalidArgumentException('Invalid "context" parameter for completion/complete.'); + } + if (!isset($params['context']['arguments'])) { + return []; + } + if (!\is_array($params['context']['arguments'])) { + throw new InvalidArgumentException('Invalid "context.arguments" parameter for completion/complete.'); + } + + $arguments = []; + foreach ($params['context']['arguments'] as $name => $value) { + if (!\is_string($value)) { + throw new InvalidArgumentException(\sprintf('Invalid "context.arguments.%s" parameter for completion/complete.', $name)); + } + $arguments[(string) $name] = $value; + } + + return ['arguments' => $arguments]; } /** @@ -75,14 +108,25 @@ private static function stringMember(array $data, string $member, string $key): /** * @return array{ * ref: PromptReference|ResourceReference, - * argument: array{ name: string, value: string } + * argument: array{ name: string, value: string }, + * context?: object * } */ protected function getParams(): array { - return [ + $params = [ 'ref' => $this->ref, 'argument' => $this->argument, ]; + + if (null !== $this->context) { + $context = new \stdClass(); + if (isset($this->context['arguments'])) { + $context->arguments = (object) $this->context['arguments']; + } + $params['context'] = $context; + } + + return $params; } } diff --git a/src/Server/Capability/Completion/ContextAwareProviderInterface.php b/src/Server/Capability/Completion/ContextAwareProviderInterface.php new file mode 100644 index 000000000..bb47dfe30 --- /dev/null +++ b/src/Server/Capability/Completion/ContextAwareProviderInterface.php @@ -0,0 +1,31 @@ + + */ +interface ContextAwareProviderInterface extends ProviderInterface +{ + /** + * @param string $currentValue the current value to get completions for + * @param array $arguments previously resolved arguments of the prompt or URI template, by name + * + * @return string[] the completions + */ + public function getCompletionsWithContext(string $currentValue, array $arguments): array; +} diff --git a/src/Server/Handler/Request/CompletionCompleteHandler.php b/src/Server/Handler/Request/CompletionCompleteHandler.php index aa708703b..84688dc88 100644 --- a/src/Server/Handler/Request/CompletionCompleteHandler.php +++ b/src/Server/Handler/Request/CompletionCompleteHandler.php @@ -18,6 +18,7 @@ use Mcp\Schema\Request\CompletionCompleteRequest; use Mcp\Schema\ResourceReference; use Mcp\Schema\Result\CompletionCompleteResult; +use Mcp\Server\Capability\Completion\ContextAwareProviderInterface; use Mcp\Server\Capability\Completion\ProviderInterface; use Mcp\Server\Capability\Registry\ResourceTemplateReference; use Mcp\Server\Capability\RegistryInterface; @@ -81,7 +82,11 @@ public function handle(Request $request, SessionInterface $session): Response|Er return Error::forInternalError('Invalid completion provider type', $request->getId()); } - $completions = $provider->getCompletions($value); + if ($provider instanceof ContextAwareProviderInterface) { + $completions = $provider->getCompletionsWithContext($value, $request->context['arguments'] ?? []); + } else { + $completions = $provider->getCompletions($value); + } $total = \count($completions); $hasMore = $total > 100; $paged = \array_slice($completions, 0, 100); diff --git a/tests/Integration/CompletionTest.php b/tests/Integration/CompletionTest.php index 0da021a42..9d7dec90b 100644 --- a/tests/Integration/CompletionTest.php +++ b/tests/Integration/CompletionTest.php @@ -45,6 +45,30 @@ public function testEmptyValueOffersEveryCompletion(): void $this->assertSame(['12A', '12B', '14C'], $result->values); } + #[TestDox('a context-aware provider narrows its completions to the arguments sent as context')] + public function testContextArgumentsReachTheProvider(): void + { + $client = $this->connect('completion'); + + $result = $client->complete( + new PromptReference('book_cabin_seat'), + ['name' => 'seat', 'value' => '1'], + ['arguments' => ['cabin' => 'business']], + ); + + $this->assertSame(['1A', '1C'], $result->values); + } + + #[TestDox('a context-aware provider without context completes from everything it knows')] + public function testContextAwareProviderWithoutContext(): void + { + $client = $this->connect('completion'); + + $result = $client->complete(new PromptReference('book_cabin_seat'), ['name' => 'seat', 'value' => '1']); + + $this->assertSame(['1A', '1C', '12A', '12B', '14C'], $result->values); + } + #[TestDox('an argument the prompt does not declare completes to nothing')] public function testUnknownArgumentCompletesToNothing(): void { diff --git a/tests/Integration/Fixture/Completion/BookingElements.php b/tests/Integration/Fixture/Completion/BookingElements.php index cc0ac622e..068e89ae0 100644 --- a/tests/Integration/Fixture/Completion/BookingElements.php +++ b/tests/Integration/Fixture/Completion/BookingElements.php @@ -35,4 +35,23 @@ public function bookSeat( ['role' => 'user', 'content' => \sprintf('Book seat %s for me.', $seat)], ]; } + + /** + * Confirms a seat booking in a given cabin. + * + * @param string $cabin the cabin to book in + * @param string $seat the seat to book + * + * @return array the prompt messages + */ + #[McpPrompt(name: 'book_cabin_seat')] + public function bookCabinSeat( + string $cabin, + #[CompletionProvider(provider: CabinSeatCompletionProvider::class)] + string $seat, + ): array { + return [ + ['role' => 'user', 'content' => \sprintf('Book seat %s in %s for me.', $seat, $cabin)], + ]; + } } diff --git a/tests/Integration/Fixture/Completion/CabinSeatCompletionProvider.php b/tests/Integration/Fixture/Completion/CabinSeatCompletionProvider.php new file mode 100644 index 000000000..5058c4b9a --- /dev/null +++ b/tests/Integration/Fixture/Completion/CabinSeatCompletionProvider.php @@ -0,0 +1,42 @@ + + */ +final class CabinSeatCompletionProvider implements ContextAwareProviderInterface +{ + private const SEATS = [ + 'business' => ['1A', '1C', '2A'], + 'economy' => ['12A', '12B', '14C'], + ]; + + public function getCompletions(string $currentValue): array + { + return $this->getCompletionsWithContext($currentValue, []); + } + + public function getCompletionsWithContext(string $currentValue, array $arguments): array + { + $seats = self::SEATS[$arguments['cabin'] ?? ''] ?? array_merge(...array_values(self::SEATS)); + + return array_values(array_filter( + $seats, + static fn (string $seat): bool => str_starts_with($seat, $currentValue), + )); + } +} diff --git a/tests/Unit/Schema/Request/CompletionCompleteRequestTest.php b/tests/Unit/Schema/Request/CompletionCompleteRequestTest.php index 5000ec36c..5c9580c3c 100644 --- a/tests/Unit/Schema/Request/CompletionCompleteRequestTest.php +++ b/tests/Unit/Schema/Request/CompletionCompleteRequestTest.php @@ -57,6 +57,72 @@ public function testEmptyArgumentValueIsAccepted(): void $this->assertSame(['name' => 'seat', 'value' => ''], $request->argument); } + public function testContextIsAbsentWhenNotSent(): void + { + $request = self::fromParams([ + 'ref' => ['type' => 'ref/prompt', 'name' => 'code_review'], + 'argument' => ['name' => 'framework', 'value' => 'fla'], + ]); + + $this->assertNull($request->context); + } + + public function testFromArrayReadsContextArguments(): void + { + $request = self::fromParams([ + 'ref' => ['type' => 'ref/prompt', 'name' => 'code_review'], + 'argument' => ['name' => 'framework', 'value' => 'fla'], + 'context' => ['arguments' => ['language' => 'python']], + ]); + + $this->assertSame(['arguments' => ['language' => 'python']], $request->context); + } + + public function testContextWithoutArgumentsIsEmpty(): void + { + $request = self::fromParams([ + 'ref' => ['type' => 'ref/prompt', 'name' => 'code_review'], + 'argument' => ['name' => 'framework', 'value' => 'fla'], + 'context' => [], + ]); + + $this->assertSame([], $request->context); + } + + public function testContextIsSerialized(): void + { + $request = (new CompletionCompleteRequest( + new PromptReference('code_review'), + ['name' => 'framework', 'value' => 'fla'], + ['arguments' => ['language' => 'python']], + ))->withId(1); + + $params = json_decode(json_encode($request, \JSON_THROW_ON_ERROR), true, flags: \JSON_THROW_ON_ERROR)['params']; + + $this->assertSame(['arguments' => ['language' => 'python']], $params['context']); + } + + public function testEmptyContextIsSerializedAsObjects(): void + { + $request = (new CompletionCompleteRequest( + new PromptReference('code_review'), + ['name' => 'framework', 'value' => 'fla'], + ['arguments' => []], + ))->withId(1); + + $this->assertStringContainsString('"context":{"arguments":{}}', json_encode($request, \JSON_THROW_ON_ERROR)); + } + + public function testContextIsOmittedWhenNull(): void + { + $request = (new CompletionCompleteRequest( + new PromptReference('code_review'), + ['name' => 'framework', 'value' => 'fla'], + ))->withId(1); + + $this->assertStringNotContainsString('"context"', json_encode($request, \JSON_THROW_ON_ERROR)); + } + /** * @param array $params */ @@ -116,6 +182,21 @@ public static function provideMalformedParams(): iterable ['ref' => $ref, 'argument' => ['name' => 'seat', 'value' => 12]], 'Missing or invalid "argument.value" parameter for completion/complete.', ]; + + yield 'context that is not an object' => [ + ['ref' => $ref, 'argument' => $argument, 'context' => 'row=12'], + 'Invalid "context" parameter for completion/complete.', + ]; + + yield 'context arguments that are not an object' => [ + ['ref' => $ref, 'argument' => $argument, 'context' => ['arguments' => 'row=12']], + 'Invalid "context.arguments" parameter for completion/complete.', + ]; + + yield 'context argument value that is not a string' => [ + ['ref' => $ref, 'argument' => $argument, 'context' => ['arguments' => ['row' => 12]]], + 'Invalid "context.arguments.row" parameter for completion/complete.', + ]; } /** diff --git a/tests/Unit/Server/Handler/Request/CompletionCompleteHandlerTest.php b/tests/Unit/Server/Handler/Request/CompletionCompleteHandlerTest.php index 69f923744..21fbead56 100644 --- a/tests/Unit/Server/Handler/Request/CompletionCompleteHandlerTest.php +++ b/tests/Unit/Server/Handler/Request/CompletionCompleteHandlerTest.php @@ -16,6 +16,7 @@ use Mcp\Schema\Request\CompletionCompleteRequest; use Mcp\Schema\ResourceTemplate; use Mcp\Schema\Result\CompletionCompleteResult; +use Mcp\Server\Capability\Completion\ContextAwareProviderInterface; use Mcp\Server\Capability\Completion\ProviderInterface; use Mcp\Server\Capability\Registry\ResourceReference; use Mcp\Server\Capability\Registry\ResourceTemplateReference; @@ -82,6 +83,73 @@ public function testReturnsCompletionsForResourceTemplate(): void $this->assertEquals(new CompletionCompleteResult(['alpha'], 1, false), $response->result); } + public function testPassesContextArgumentsToAContextAwareProvider(): void + { + $uri = 'file://users/alice/repos/sdk'; + $request = $this->createCompletionRequest($uri, ['name' => 'repo', 'value' => 's'], ['arguments' => ['owner' => 'alice']]); + + $provider = $this->createMock(ContextAwareProviderInterface::class); + $provider->expects($this->never())->method('getCompletions'); + $provider->expects($this->once()) + ->method('getCompletionsWithContext') + ->with('s', ['owner' => 'alice']) + ->willReturn(['sdk', 'site']); + + $this->registry + ->method('getResource') + ->with($uri) + ->willReturn($this->templateReference(['repo' => $provider])); + + $response = $this->handler->handle($request, $this->session); + + $this->assertInstanceOf(Response::class, $response); + $this->assertEquals(new CompletionCompleteResult(['sdk', 'site'], 2, false), $response->result); + } + + public function testPassesNoArgumentsToAContextAwareProviderWithoutContext(): void + { + $uri = 'file://users/alice/repos/sdk'; + $request = $this->createCompletionRequest($uri, ['name' => 'repo', 'value' => 's']); + + $provider = $this->createMock(ContextAwareProviderInterface::class); + $provider->expects($this->once()) + ->method('getCompletionsWithContext') + ->with('s', []) + ->willReturn(['sdk']); + + $this->registry + ->method('getResource') + ->with($uri) + ->willReturn($this->templateReference(['repo' => $provider])); + + $response = $this->handler->handle($request, $this->session); + + $this->assertInstanceOf(Response::class, $response); + $this->assertEquals(new CompletionCompleteResult(['sdk'], 1, false), $response->result); + } + + public function testPlainProviderIgnoresContext(): void + { + $uri = 'file://users/alice/repos/sdk'; + $request = $this->createCompletionRequest($uri, ['name' => 'repo', 'value' => 's'], ['arguments' => ['owner' => 'alice']]); + + $provider = $this->createMock(ProviderInterface::class); + $provider->expects($this->once()) + ->method('getCompletions') + ->with('s') + ->willReturn(['sdk']); + + $this->registry + ->method('getResource') + ->with($uri) + ->willReturn($this->templateReference(['repo' => $provider])); + + $response = $this->handler->handle($request, $this->session); + + $this->assertInstanceOf(Response::class, $response); + $this->assertEquals(new CompletionCompleteResult(['sdk'], 1, false), $response->result); + } + public function testLogsProviderFailureBeforeReturningInternalError(): void { $uri = 'file://users/alice'; @@ -119,18 +187,36 @@ public function testLogsProviderFailureBeforeReturningInternalError(): void } /** - * @param array{ name: string, value: string } $argument + * @param array $providers */ - private function createCompletionRequest(string $uri, array $argument): CompletionCompleteRequest + private function templateReference(array $providers): ResourceTemplateReference { + return new ResourceTemplateReference( + new ResourceTemplate('file://users/{owner}/repos/{repo}', 'repository'), + static fn () => null, + $providers, + ); + } + + /** + * @param array{ name: string, value: string } $argument + * @param array{ arguments?: array }|null $context + */ + private function createCompletionRequest(string $uri, array $argument, ?array $context = null): CompletionCompleteRequest + { + $params = [ + 'ref' => ['type' => 'ref/resource', 'uri' => $uri], + 'argument' => $argument, + ]; + if (null !== $context) { + $params['context'] = $context; + } + return CompletionCompleteRequest::fromArray([ 'jsonrpc' => '2.0', 'method' => CompletionCompleteRequest::getMethod(), 'id' => 'test-completion-'.uniqid(), - 'params' => [ - 'ref' => ['type' => 'ref/resource', 'uri' => $uri], - 'argument' => $argument, - ], + 'params' => $params, ]); } } From 2ea43eb6492f38cc362ba574f63e75872eb94b61 Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Sat, 21 Nov 2026 03:59:49 +0100 Subject: [PATCH 3/4] [Schema] Add _meta to text, image, audio and embedded resource content Since protocol revision 2025-06-18, every content block can carry its own _meta. ResourceLink already had it; TextContent, ImageContent, AudioContent and EmbeddedResource now take an optional $meta, parse a _meta object and serialize it. The _meta of an EmbeddedResource is the block's own, separate from the one of its resource contents. --- CHANGELOG.md | 1 + docs/servers/tools.md | 6 + src/Schema/Content/AudioContent.php | 18 ++- src/Schema/Content/EmbeddedResource.php | 15 ++- src/Schema/Content/ImageContent.php | 19 ++- src/Schema/Content/TextContent.php | 17 ++- tests/Unit/Schema/Content/ContentMetaTest.php | 116 ++++++++++++++++++ .../Unit/Schema/Result/CallToolResultTest.php | 21 ++++ 8 files changed, 204 insertions(+), 9 deletions(-) create mode 100644 tests/Unit/Schema/Content/ContentMetaTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 14d06e4ec..af625d5c0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,7 @@ All notable changes to `mcp/sdk` will be documented in this file. ### Schema * Add `icons` to `ResourceTemplate`, so `resources/templates/list` carries them. +* Add `_meta` to `TextContent`, `ImageContent`, `AudioContent` and `EmbeddedResource`, as `$meta` constructor argument and property. * Add `context` to `CompletionCompleteRequest`. A `context` or `context.arguments` that is not an object, or an argument value that is not a string, is rejected with `-32602`. 0.10.0 diff --git a/docs/servers/tools.md b/docs/servers/tools.md index ad87b8891..3d82be718 100644 --- a/docs/servers/tools.md +++ b/docs/servers/tools.md @@ -112,6 +112,12 @@ public function getResourceLink(): ResourceLink } ``` +Every content type also takes optional `annotations` and `meta`; the latter is sent as the block's `_meta`: + +```php +new TextContent('Found 3 matches', meta: ['com.example/query-id' => 'q-42']); +``` + ### Multiple Content Items Return an array of content items: diff --git a/src/Schema/Content/AudioContent.php b/src/Schema/Content/AudioContent.php index 66ed48e27..76dfb3dc5 100644 --- a/src/Schema/Content/AudioContent.php +++ b/src/Schema/Content/AudioContent.php @@ -25,16 +25,24 @@ * data: string, * mimeType: string, * annotations?: AnnotationsData, + * _meta?: array, * } * * @author Kyrian Obikwelu */ class AudioContent extends Content { + /** + * @param string $data Base64-encoded audio data + * @param string $mimeType The MIME type of the audio + * @param ?Annotations $annotations Optional annotations describing the content + * @param ?array $meta Optional metadata + */ public function __construct( public readonly string $data, public readonly string $mimeType, public readonly ?Annotations $annotations = null, + public readonly ?array $meta = null, ) { parent::__construct('audio'); } @@ -50,11 +58,15 @@ public static function fromArray(array $data): self if (!isset($data['mimeType']) || !\is_string($data['mimeType'])) { throw new InvalidArgumentException('Missing or invalid "mimeType" in AudioContent data.'); } + if (isset($data['_meta']) && !\is_array($data['_meta'])) { + throw new InvalidArgumentException('Invalid "_meta" in AudioContent data.'); + } return new self( $data['data'], $data['mimeType'], - Annotations::tryFromArray($data['annotations'] ?? null, 'AudioContent') + Annotations::tryFromArray($data['annotations'] ?? null, 'AudioContent'), + $data['_meta'] ?? null, ); } @@ -101,6 +113,7 @@ public static function fromString(string $data, string $mimeType, ?Annotations $ * data: string, * mimeType: string, * annotations?: Annotations, + * _meta?: array, * } */ public function jsonSerialize(): array @@ -114,6 +127,9 @@ public function jsonSerialize(): array if (null !== $this->annotations) { $result['annotations'] = $this->annotations; } + if (null !== $this->meta) { + $result['_meta'] = $this->meta; + } return $result; } diff --git a/src/Schema/Content/EmbeddedResource.php b/src/Schema/Content/EmbeddedResource.php index b71ae2ca9..dcf27ba15 100644 --- a/src/Schema/Content/EmbeddedResource.php +++ b/src/Schema/Content/EmbeddedResource.php @@ -25,16 +25,21 @@ * @phpstan-type EmbeddedResourceData = array{ * type: 'resource', * resource: TextResourceContentsData|BlobResourceContentsData, - * annotations?: AnnotationsData + * annotations?: AnnotationsData, + * _meta?: array * } * * @author Kyrian Obikwelu */ class EmbeddedResource extends Content { + /** + * @param ?array $meta optional metadata of the content block, unlike the `_meta` of the resource contents + */ public function __construct( public readonly TextResourceContents|BlobResourceContents $resource, public readonly ?Annotations $annotations = null, + public readonly ?array $meta = null, ) { parent::__construct('resource'); } @@ -50,6 +55,9 @@ public static function fromArray(array $data): self if (!isset($data['resource']) || !\is_array($data['resource'])) { throw new InvalidArgumentException('Missing or invalid "resource" field for EmbeddedResource.'); } + if (isset($data['_meta']) && !\is_array($data['_meta'])) { + throw new InvalidArgumentException('Invalid "_meta" field for EmbeddedResource.'); + } $resourceData = $data['resource']; if (isset($resourceData['text'])) { @@ -63,6 +71,7 @@ public static function fromArray(array $data): self return new self( $resourceInstance, Annotations::tryFromArray($data['annotations'] ?? null, 'EmbeddedResource'), + $data['_meta'] ?? null, ); } @@ -129,6 +138,7 @@ public static function fromSplFileInfo(string $uri, \SplFileInfo $file, ?string * type: 'resource', * resource: TextResourceContents|BlobResourceContents, * annotations?: Annotations, + * _meta?: array, * } */ public function jsonSerialize(): array @@ -140,6 +150,9 @@ public function jsonSerialize(): array if (null !== $this->annotations) { $data['annotations'] = $this->annotations; } + if (null !== $this->meta) { + $data['_meta'] = $this->meta; + } return $data; } diff --git a/src/Schema/Content/ImageContent.php b/src/Schema/Content/ImageContent.php index a32d22bd8..1d053d38c 100644 --- a/src/Schema/Content/ImageContent.php +++ b/src/Schema/Content/ImageContent.php @@ -22,6 +22,7 @@ * data: string, * mimeType: string, * annotations?: AnnotationsData, + * _meta?: array, * } * * @author Kyrian Obikwelu @@ -31,14 +32,16 @@ class ImageContent extends Content /** * Create a new ImageContent instance. * - * @param string $data Base64-encoded image data - * @param string $mimeType The MIME type of the image - * @param ?Annotations $annotations Optional annotations describing the content + * @param string $data Base64-encoded image data + * @param string $mimeType The MIME type of the image + * @param ?Annotations $annotations Optional annotations describing the content + * @param ?array $meta Optional metadata */ public function __construct( public readonly string $data, public readonly string $mimeType, public readonly ?Annotations $annotations = null, + public readonly ?array $meta = null, ) { parent::__construct('image'); } @@ -54,11 +57,15 @@ public static function fromArray(array $data): self if (!isset($data['mimeType']) || !\is_string($data['mimeType'])) { throw new InvalidArgumentException('Missing or invalid "mimeType" in ImageContent data.'); } + if (isset($data['_meta']) && !\is_array($data['_meta'])) { + throw new InvalidArgumentException('Invalid "_meta" in ImageContent data.'); + } return new self( $data['data'], $data['mimeType'], - isset($data['annotations']) ? Annotations::fromArray($data['annotations']) : null + isset($data['annotations']) ? Annotations::fromArray($data['annotations']) : null, + $data['_meta'] ?? null, ); } @@ -101,6 +108,7 @@ public static function fromString(string $data, string $mimeType, ?Annotations $ * data: string, * mimeType: string, * annotations?: Annotations, + * _meta?: array, * } */ public function jsonSerialize(): array @@ -114,6 +122,9 @@ public function jsonSerialize(): array if (null !== $this->annotations) { $result['annotations'] = $this->annotations; } + if (null !== $this->meta) { + $result['_meta'] = $this->meta; + } return $result; } diff --git a/src/Schema/Content/TextContent.php b/src/Schema/Content/TextContent.php index 7e0c1d49f..a79ab94ba 100644 --- a/src/Schema/Content/TextContent.php +++ b/src/Schema/Content/TextContent.php @@ -23,6 +23,7 @@ * type: 'text', * text: string, * annotations?: AnnotationsData, + * _meta?: array, * } * * @author Kyrian Obikwelu @@ -32,12 +33,14 @@ class TextContent extends Content /** * Create a new TextContent instance from any value. * - * @param mixed $text The value to convert to text - * @param ?Annotations $annotations Optional annotations describing the content + * @param mixed $text The value to convert to text + * @param ?Annotations $annotations Optional annotations describing the content + * @param ?array $meta Optional metadata */ public function __construct( public mixed $text, public readonly ?Annotations $annotations = null, + public readonly ?array $meta = null, ) { $this->text = (\is_array($text) || \is_object($text)) ? json_encode($text) : (string) $text; @@ -53,10 +56,14 @@ public static function fromArray(array $data): self if (!isset($data['text']) || !\is_string($data['text'])) { throw new InvalidArgumentException('Missing or invalid "text" in TextContent data.'); } + if (isset($data['_meta']) && !\is_array($data['_meta'])) { + throw new InvalidArgumentException('Invalid "_meta" in TextContent data.'); + } return new self( $data['text'], - Annotations::tryFromArray($data['annotations'] ?? null, 'TextContent') + Annotations::tryFromArray($data['annotations'] ?? null, 'TextContent'), + $data['_meta'] ?? null, ); } @@ -78,6 +85,7 @@ public static function code(string $code, string $language = '', ?Annotations $a * type: 'text', * text: string, * annotations?: Annotations, + * _meta?: array, * } */ public function jsonSerialize(): array @@ -90,6 +98,9 @@ public function jsonSerialize(): array if (null !== $this->annotations) { $result['annotations'] = $this->annotations; } + if (null !== $this->meta) { + $result['_meta'] = $this->meta; + } return $result; } diff --git a/tests/Unit/Schema/Content/ContentMetaTest.php b/tests/Unit/Schema/Content/ContentMetaTest.php new file mode 100644 index 000000000..70ca7db46 --- /dev/null +++ b/tests/Unit/Schema/Content/ContentMetaTest.php @@ -0,0 +1,116 @@ + 'abc-123']; + + /** + * @param class-string $class + * @param array $data + */ + #[DataProvider('provideContentBlocks')] + public function testFromArrayReadsMeta(string $class, array $data): void + { + $content = $class::fromArray($data + ['_meta' => self::META]); + + $this->assertSame(self::META, $content->meta); + } + + /** + * @param class-string $class + * @param array $data + */ + #[DataProvider('provideContentBlocks')] + public function testMetaIsNullWhenAbsent(string $class, array $data): void + { + $content = $class::fromArray($data); + + $this->assertNull($content->meta); + $this->assertArrayNotHasKey('_meta', $content->jsonSerialize()); + } + + /** + * @param class-string $class + * @param array $data + */ + #[DataProvider('provideContentBlocks')] + public function testMetaRoundTrips(string $class, array $data): void + { + $content = $class::fromArray($data + ['_meta' => self::META]); + + $encoded = json_decode(json_encode($content, \JSON_THROW_ON_ERROR), true, flags: \JSON_THROW_ON_ERROR); + + $this->assertSame(self::META, $encoded['_meta']); + $this->assertEquals($content, $class::fromArray($encoded)); + } + + /** + * @param class-string $class + * @param array $data + */ + #[DataProvider('provideContentBlocks')] + public function testFromArrayRejectsMetaThatIsNotAnObject(string $class, array $data): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Invalid "_meta"'); + + $class::fromArray($data + ['_meta' => 'abc-123']); + } + + /** + * @return iterable, array}> + */ + public static function provideContentBlocks(): iterable + { + yield 'text' => [TextContent::class, ['type' => 'text', 'text' => 'Hello']]; + yield 'image' => [ImageContent::class, ['type' => 'image', 'data' => base64_encode('png'), 'mimeType' => 'image/png']]; + yield 'audio' => [AudioContent::class, ['type' => 'audio', 'data' => base64_encode('wav'), 'mimeType' => 'audio/wav']]; + yield 'embedded resource' => [EmbeddedResource::class, ['type' => 'resource', 'resource' => ['uri' => 'file:///notes.txt', 'mimeType' => 'text/plain', 'text' => 'Notes']]]; + yield 'resource link' => [ResourceLink::class, ['type' => 'resource_link', 'uri' => 'file:///notes.txt', 'name' => 'notes.txt']]; + } + + public function testConstructorsAcceptMeta(): void + { + $this->assertSame(self::META, (new TextContent('Hello', meta: self::META))->jsonSerialize()['_meta'] ?? null); + $this->assertSame(self::META, (new ImageContent(base64_encode('png'), 'image/png', meta: self::META))->jsonSerialize()['_meta'] ?? null); + $this->assertSame(self::META, (new AudioContent(base64_encode('wav'), 'audio/wav', meta: self::META))->jsonSerialize()['_meta'] ?? null); + $this->assertSame(self::META, (new EmbeddedResource(new TextResourceContents('file:///notes.txt', 'text/plain', 'Notes'), meta: self::META))->jsonSerialize()['_meta'] ?? null); + } + + /** + * The `_meta` of the content block and the one of its resource are distinct fields. + */ + public function testEmbeddedResourceKeepsBlockMetaApartFromResourceMeta(): void + { + $content = EmbeddedResource::fromArray([ + 'type' => 'resource', + 'resource' => ['uri' => 'file:///notes.txt', 'text' => 'Notes', '_meta' => ['com.example/source' => 'disk']], + '_meta' => self::META, + ]); + + $this->assertSame(self::META, $content->meta); + $this->assertSame(['com.example/source' => 'disk'], $content->resource->meta); + } +} diff --git a/tests/Unit/Schema/Result/CallToolResultTest.php b/tests/Unit/Schema/Result/CallToolResultTest.php index c22a63b10..c9fbd6470 100644 --- a/tests/Unit/Schema/Result/CallToolResultTest.php +++ b/tests/Unit/Schema/Result/CallToolResultTest.php @@ -136,6 +136,27 @@ public function testFromArrayDeserializesMixedContentTypes(): void $this->assertInstanceOf(ResourceLink::class, $result->content[2]); } + public function testFromArrayKeepsTheMetaOfEachContentBlock(): void + { + $result = CallToolResult::fromArray([ + 'content' => [ + ['type' => 'text', 'text' => 'search results', '_meta' => ['com.example/rank' => 1]], + ['type' => 'image', 'data' => base64_encode('png'), 'mimeType' => 'image/png', '_meta' => ['com.example/rank' => 2]], + ['type' => 'audio', 'data' => base64_encode('wav'), 'mimeType' => 'audio/wav', '_meta' => ['com.example/rank' => 3]], + ['type' => 'resource', 'resource' => ['uri' => 'file:///a.txt', 'text' => 'a'], '_meta' => ['com.example/rank' => 4]], + ], + ]); + + $this->assertInstanceOf(TextContent::class, $result->content[0]); + $this->assertSame(['com.example/rank' => 1], $result->content[0]->meta); + $this->assertInstanceOf(ImageContent::class, $result->content[1]); + $this->assertSame(['com.example/rank' => 2], $result->content[1]->meta); + $this->assertInstanceOf(AudioContent::class, $result->content[2]); + $this->assertSame(['com.example/rank' => 3], $result->content[2]->meta); + $this->assertInstanceOf(EmbeddedResource::class, $result->content[3]); + $this->assertSame(['com.example/rank' => 4], $result->content[3]->meta); + } + public function testFromArrayRejectsUnknownContentType(): void { $this->expectException(InvalidArgumentException::class); From 5d9368e3caabb165cf93f0ec422f677d6aea4ef5 Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Sat, 21 Nov 2026 04:00:32 +0100 Subject: [PATCH 4/4] [Schema] Add the lastModified annotation Annotations gained lastModified in protocol revision 2025-06-18: the moment a resource or content block was last modified, as an ISO 8601 string. Annotations now takes it as an optional third argument, parses it and serializes it, so it reaches resources, resource templates, resource links and content blocks alike. --- CHANGELOG.md | 1 + docs/servers/resources.md | 3 +- src/Schema/Annotations.php | 14 ++++- tests/Unit/Schema/AnnotationsTest.php | 84 +++++++++++++++++++++++++++ 4 files changed, 99 insertions(+), 3 deletions(-) create mode 100644 tests/Unit/Schema/AnnotationsTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index af625d5c0..c1a72cb35 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,7 @@ All notable changes to `mcp/sdk` will be documented in this file. * Add `icons` to `ResourceTemplate`, so `resources/templates/list` carries them. * Add `_meta` to `TextContent`, `ImageContent`, `AudioContent` and `EmbeddedResource`, as `$meta` constructor argument and property. +* Add `lastModified` to `Annotations`, the ISO 8601 moment a resource or content block was last modified. * Add `context` to `CompletionCompleteRequest`. A `context` or `context.arguments` that is not an object, or an argument value that is not a string, is rejected with `-32602`. 0.10.0 diff --git a/docs/servers/resources.md b/docs/servers/resources.md index b39d0cee1..d0dda7250 100644 --- a/docs/servers/resources.md +++ b/docs/servers/resources.md @@ -30,7 +30,8 @@ class ConfigProvider - **`description`** (optional): Resource description. Falls back to the docblock (summary plus long description). - **`mimeType`** (optional): MIME type of the resource content. - **`size`** (optional): Size in bytes if known. -- **`annotations`** (optional): Additional metadata. +- **`annotations`** (optional): An `Annotations` object with hints for the client: `audience`, `priority` and + `lastModified` (an ISO 8601 timestamp such as `2025-01-12T15:00:58Z`). - **`icons`** (optional): Array of `Icon` objects for visual representation. - **`meta`** (optional): Arbitrary key-value pairs for custom metadata. diff --git a/src/Schema/Annotations.php b/src/Schema/Annotations.php index b7dcbffc6..d59038e01 100644 --- a/src/Schema/Annotations.php +++ b/src/Schema/Annotations.php @@ -20,7 +20,8 @@ * * @phpstan-type AnnotationsData array{ * audience?: string[], - * priority?: float + * priority?: float, + * lastModified?: string * } * * @author Kyrian Obikwelu @@ -36,10 +37,12 @@ class Annotations implements \JsonSerializable * A value of 1 means "most important," and indicates that the data is * effectively required, while 0 means "least important," and indicates that * the data is entirely optional. + * @param string|null $lastModified the moment the resource was last modified, as an ISO 8601 formatted string (e.g. "2025-01-12T15:00:58Z") */ public function __construct( public readonly ?array $audience = null, public readonly ?float $priority = null, + public readonly ?string $lastModified = null, ) { if (null !== $this->priority && ($this->priority < 0 || $this->priority > 1)) { throw new InvalidArgumentException('Annotation priority must be between 0 and 1.'); @@ -75,10 +78,14 @@ static function (mixed $role): Role { if (isset($data['priority']) && !\is_float($data['priority']) && !\is_int($data['priority'])) { throw new InvalidArgumentException('Invalid "priority" in Annotations data; expected a number.'); } + if (isset($data['lastModified']) && !\is_string($data['lastModified'])) { + throw new InvalidArgumentException('Invalid "lastModified" in Annotations data; expected a string.'); + } return new self( $audience, - isset($data['priority']) ? (float) $data['priority'] : null + isset($data['priority']) ? (float) $data['priority'] : null, + $data['lastModified'] ?? null, ); } @@ -112,6 +119,9 @@ public function jsonSerialize(): array if (null !== $this->priority) { $data['priority'] = $this->priority; } + if (null !== $this->lastModified) { + $data['lastModified'] = $this->lastModified; + } return $data; } diff --git a/tests/Unit/Schema/AnnotationsTest.php b/tests/Unit/Schema/AnnotationsTest.php new file mode 100644 index 000000000..af28644dc --- /dev/null +++ b/tests/Unit/Schema/AnnotationsTest.php @@ -0,0 +1,84 @@ +assertNull($annotations->lastModified); + $this->assertArrayNotHasKey('lastModified', $annotations->jsonSerialize()); + } + + public function testLastModifiedIsSerialized(): void + { + $annotations = new Annotations([Role::User], 0.8, '2025-01-12T15:00:58Z'); + + $this->assertSame( + '{"audience":["user"],"priority":0.8,"lastModified":"2025-01-12T15:00:58Z"}', + json_encode($annotations, \JSON_THROW_ON_ERROR), + ); + } + + public function testFromArrayReadsLastModified(): void + { + $annotations = Annotations::fromArray(['lastModified' => '2025-01-12T15:00:58Z']); + + $this->assertSame('2025-01-12T15:00:58Z', $annotations->lastModified); + $this->assertNull($annotations->audience); + $this->assertNull($annotations->priority); + } + + public function testFromArrayRejectsLastModifiedThatIsNotAString(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Invalid "lastModified" in Annotations data; expected a string.'); + + Annotations::tryFromArray(['lastModified' => 1736694058], 'Test'); + } + + public function testResourceCarriesLastModified(): void + { + $resource = ResourceDefinition::fromArray([ + 'uri' => 'file:///project/README.md', + 'name' => 'README.md', + 'annotations' => ['audience' => ['user'], 'priority' => 0.8, 'lastModified' => '2025-01-12T15:00:58Z'], + ]); + + $this->assertSame('2025-01-12T15:00:58Z', $resource->annotations?->lastModified); + $this->assertStringContainsString('"lastModified":"2025-01-12T15:00:58Z"', json_encode($resource, \JSON_THROW_ON_ERROR)); + } + + public function testContentBlockCarriesLastModified(): void + { + $content = TextContent::fromArray([ + 'type' => 'text', + 'text' => 'Notes', + 'annotations' => ['lastModified' => '2025-01-12T15:00:58Z'], + ]); + + $this->assertSame('2025-01-12T15:00:58Z', $content->annotations?->lastModified); + $this->assertSame( + '{"type":"text","text":"Notes","annotations":{"lastModified":"2025-01-12T15:00:58Z"}}', + json_encode($content, \JSON_THROW_ON_ERROR), + ); + } +}