diff --git a/CHANGELOG.md b/CHANGELOG.md index c977af64..c1a72cb3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,19 @@ 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()`. +* 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 `_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/client/capabilities.md b/docs/client/capabilities.md index c63e4867..bf46d087 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/run/server-builder.md b/docs/run/server-builder.md index 56cfbdc3..b3900a9f 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/completions.md b/docs/servers/completions.md index 4024da78..f6d5f9b6 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/docs/servers/registration.md b/docs/servers/registration.md index 445114c3..4c465472 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 c6c55235..60841989 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/docs/servers/resources.md b/docs/servers/resources.md index b39d0cee..d0dda725 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/docs/servers/tools.md b/docs/servers/tools.md index ad87b889..3d82be71 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/Client/Client.php b/src/Client/Client.php index d6214a44..3d4d5b84 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/Annotations.php b/src/Schema/Annotations.php index b7dcbffc..d59038e0 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/src/Schema/Content/AudioContent.php b/src/Schema/Content/AudioContent.php index 66ed48e2..76dfb3dc 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 b71ae2ca..dcf27ba1 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 a32d22bd..1d053d38 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 7e0c1d49..a79ab94b 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/src/Schema/Request/CompletionCompleteRequest.php b/src/Schema/Request/CompletionCompleteRequest.php index bcbf0460..5c1a55f9 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/Schema/ResourceTemplate.php b/src/Schema/ResourceTemplate.php index c89d0490..ab446e84 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 aa8a850d..e119c54f 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 f4d802e1..9878ddb2 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/Completion/ContextAwareProviderInterface.php b/src/Server/Capability/Completion/ContextAwareProviderInterface.php new file mode 100644 index 00000000..bb47dfe3 --- /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/Capability/Discovery/Discoverer.php b/src/Server/Capability/Discovery/Discoverer.php index 5e9955ce..d9b27976 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 60fff503..4d9d5c3b 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/src/Server/Handler/Request/CompletionCompleteHandler.php b/src/Server/Handler/Request/CompletionCompleteHandler.php index aa708703..84688dc8 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 0da021a4..9d7dec90 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 cc0ac622..068e89ae 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 00000000..5058c4b9 --- /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/AnnotationsTest.php b/tests/Unit/Schema/AnnotationsTest.php new file mode 100644 index 00000000..af28644d --- /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), + ); + } +} diff --git a/tests/Unit/Schema/Content/ContentMetaTest.php b/tests/Unit/Schema/Content/ContentMetaTest.php new file mode 100644 index 00000000..70ca7db4 --- /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/Request/CompletionCompleteRequestTest.php b/tests/Unit/Schema/Request/CompletionCompleteRequestTest.php index 5000ec36..5c9580c3 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/Schema/ResourceTemplateTest.php b/tests/Unit/Schema/ResourceTemplateTest.php index 4c6edfa1..be777c20 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/Schema/Result/CallToolResultTest.php b/tests/Unit/Schema/Result/CallToolResultTest.php index c22a63b1..c9fbd647 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); diff --git a/tests/Unit/Server/BuilderTest.php b/tests/Unit/Server/BuilderTest.php index 32acdf3a..43b55815 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 571a066f..9e2078b0 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 b5987d81..bc67910f 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 2b84d91a..6781eb76 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 2d280bf2..689db905 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/CompletionCompleteHandlerTest.php b/tests/Unit/Server/Handler/Request/CompletionCompleteHandlerTest.php index 69f92374..21fbead5 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, ]); } } diff --git a/tests/Unit/Server/Handler/Request/ListResourceTemplatesHandlerTest.php b/tests/Unit/Server/Handler/Request/ListResourceTemplatesHandlerTest.php index 397aa329..0d983006 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) {