[Server] Add support for icons on explicit builder registration and attributes (#142)

* Add support for icons on explicit builder registration and attributes

* Update docs/server-builder.md

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
Christopher Hertel 2025-11-13 22:39:18 +01:00 • committed by GitHub
commit 056c7b6103
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
12 changed files with 173 additions and 39 deletions

View file

@ -72,6 +72,8 @@ class Calculator
- **`name`** (optional): Tool identifier. Defaults to method name if not provided. - **`name`** (optional): Tool identifier. Defaults to method name if not provided.
- **`description`** (optional): Tool description. Defaults to docblock summary if not provided, otherwise uses method name. - **`description`** (optional): Tool description. Defaults to docblock summary if not provided, otherwise uses method name.
- **`annotations`** (optional): `ToolAnnotations` object for additional metadata. - **`annotations`** (optional): `ToolAnnotations` object for additional metadata.
- **`icons`** (optional): Array of `Icon` objects for visual representation.
- **`meta`** (optional): Arbitrary key-value pairs for custom metadata.
**Priority for name/description**: Attribute parameters → DocBlock content → Method name **Priority for name/description**: Attribute parameters → DocBlock content → Method name
@ -217,6 +219,9 @@ class ConfigProvider
- **`description`** (optional): Resource description. Defaults to docblock summary if not provided. - **`description`** (optional): Resource description. Defaults to docblock summary if not provided.
- **`mimeType`** (optional): MIME type of the resource content. - **`mimeType`** (optional): MIME type of the resource content.
- **`size`** (optional): Size in bytes if known. - **`size`** (optional): Size in bytes if known.
- **`annotations`** (optional): Additional metadata.
- **`icons`** (optional): Array of `Icon` objects for visual representation.
- **`meta`** (optional): Arbitrary key-value pairs for custom metadata.
**Standard Protocol URI Schemes**: `https://` (web resources), `file://` (filesystem), `git://` (version control). **Standard Protocol URI Schemes**: `https://` (web resources), `file://` (filesystem), `git://` (version control).
**Custom schemes**: `config://`, `data://`, `db://`, `api://` or any RFC 3986 compliant scheme. **Custom schemes**: `config://`, `data://`, `db://`, `api://` or any RFC 3986 compliant scheme.
@ -399,6 +404,8 @@ class PromptGenerator
- **`name`** (optional): Prompt identifier. Defaults to method name if not provided. - **`name`** (optional): Prompt identifier. Defaults to method name if not provided.
- **`description`** (optional): Prompt description. Defaults to docblock summary if not provided. - **`description`** (optional): Prompt description. Defaults to docblock summary if not provided.
- **`icons`** (optional): Array of `Icon` objects for visual representation.
- **`meta`** (optional): Arbitrary key-value pairs for custom metadata.
### Prompt Return Values ### Prompt Return Values

View file

@ -52,14 +52,25 @@ final `Server` instance ready for use.
Set the server's identity with name, version, and optional description: Set the server's identity with name, version, and optional description:
```php ```php
use Mcp\Schema\Icon;
use Mcp\Server;
$server = Server::builder() $server = Server::builder()
->setServerInfo('Calculator Server', '1.2.0', 'Advanced mathematical calculations'); ->setServerInfo(
name: 'Calculator Server',
version: '1.2.0',
description: 'Advanced mathematical calculations',
icons: [new Icon('https://example.com/icon.png', 'image/png', ['64x64'])],
websiteUrl: 'https://example.com'
');
``` ```
**Parameters:** **Parameters:**
- `$name` (string): The server name - `$name` (string): The server name
- `$version` (string): Version string (semantic versioning recommended) - `$version` (string): Version string (semantic versioning recommended)
- `$description` (string|null): Optional description - `$description` (string|null): Optional description
- `$icons` (Icon[]|null): Optional array of server icons
- `$websiteUrl` (string|null): Optional server website URL
### Pagination Limit ### Pagination Limit
@ -263,6 +274,16 @@ $server = Server::builder()
); );
``` ```
#### Parameters
- `handler` (callable|string): The tool handler
- `name` (string|null): Optional tool name
- `description` (string|null): Optional tool description
- `annotations` (ToolAnnotations|null): Optional annotations for the tool
- `inputSchema` (array|null): Optional input schema for the tool
- `icons` (Icon[]|null): Optional array of icons for the tool
- `meta` (array|null): Optional metadata for the tool
### Manual Resource Registration ### Manual Resource Registration
Register static resources: Register static resources:
@ -278,6 +299,18 @@ $server = Server::builder()
); );
``` ```
#### Parameters
- `handler` (callable|string): The resource handler
- `uri` (string): The resource URI
- `name` (string|null): Optional resource name
- `description` (string|null): Optional resource description
- `mimeType` (string|null): Optional MIME type of the resource
- `size` (int|null): Optional size of the resource in bytes
- `annotations` (Annotations|null): Optional annotations for the resource
- `icons` (Icon[]|null): Optional array of icons for the resource
- `meta` (array|null): Optional metadata for the resource
### Manual Resource Template Registration ### Manual Resource Template Registration
Register dynamic resources with URI templates: Register dynamic resources with URI templates:
@ -293,6 +326,15 @@ $server = Server::builder()
); );
``` ```
#### Parameters
- `handler` (callable|string): The resource template handler
- `uriTemplate` (string): The resource URI template
- `name` (string|null): Optional resource template name
- `description` (string|null): Optional resource template description
- `mimeType` (string|null): Optional MIME type of the resource
- `annotations` (Annotations|null): Optional annotations for the resource template
### Manual Prompt Registration ### Manual Prompt Registration
Register prompt generators: Register prompt generators:
@ -306,6 +348,13 @@ $server = Server::builder()
); );
``` ```
#### Parameters
- `handler` (callable|string): The prompt handler
- `name` (string|null): Optional prompt name
- `description` (string|null): Optional prompt description
- `icons` (Icon[]|null): Optional array of icons for the prompt
**Note:** `name` and `description` are optional for all manual registrations. If not provided, they will be derived from **Note:** `name` and `description` are optional for all manual registrations. If not provided, they will be derived from
the handler's method name and docblock. the handler's method name and docblock.

View file

@ -14,6 +14,7 @@ namespace Mcp\Example\DiscoveryCalculator;
use Mcp\Capability\Attribute\McpResource; use Mcp\Capability\Attribute\McpResource;
use Mcp\Capability\Attribute\McpTool; use Mcp\Capability\Attribute\McpTool;
use Mcp\Exception\ToolCallException; use Mcp\Exception\ToolCallException;
use Mcp\Schema\Icon;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger; use Psr\Log\NullLogger;
@ -47,7 +48,10 @@ final class McpElements
* *
* @return float the result of the calculation * @return float the result of the calculation
*/ */
#[McpTool(name: 'calculate')] #[McpTool(
name: 'calculate',
icons: [new Icon('https://www.svgrepo.com/show/530644/calculator.svg', 'image/svg+xml', ['any'])],
)]
public function calculate(float $a, float $b, string $operation): float public function calculate(float $a, float $b, string $operation): float
{ {
$this->logger->info(\sprintf('Calculating: %f %s %f', $a, $operation, $b)); $this->logger->info(\sprintf('Calculating: %f %s %f', $a, $operation, $b));
@ -92,6 +96,7 @@ final class McpElements
name: 'calculator_config', name: 'calculator_config',
description: 'Current settings for the calculator tool (precision, allow_negative).', description: 'Current settings for the calculator tool (precision, allow_negative).',
mimeType: 'application/json', mimeType: 'application/json',
icons: [new Icon('https://www.svgrepo.com/show/529867/settings.svg', 'image/svg+xml', ['any'])],
)] )]
public function getConfiguration(): array public function getConfiguration(): array
{ {

View file

@ -11,6 +11,8 @@
namespace Mcp\Capability\Attribute; namespace Mcp\Capability\Attribute;
use Mcp\Schema\Icon;
/** /**
* Marks a PHP method as an MCP Prompt generator. * Marks a PHP method as an MCP Prompt generator.
* The method should return the prompt messages, potentially using arguments for templating. * The method should return the prompt messages, potentially using arguments for templating.
@ -23,11 +25,13 @@ final class McpPrompt
/** /**
* @param ?string $name overrides the prompt name (defaults to method name) * @param ?string $name overrides the prompt name (defaults to method name)
* @param ?string $description Optional description of the prompt. Defaults to method DocBlock summary. * @param ?string $description Optional description of the prompt. Defaults to method DocBlock summary.
* @param ?Icon[] $icons Optional list of icon URLs representing the prompt
* @param ?array<string, mixed> $meta Optional metadata * @param ?array<string, mixed> $meta Optional metadata
*/ */
public function __construct( public function __construct(
public ?string $name = null, public ?string $name = null,
public ?string $description = null, public ?string $description = null,
public ?array $icons = null,
public ?array $meta = null, public ?array $meta = null,
) { ) {
} }

View file

@ -12,6 +12,7 @@
namespace Mcp\Capability\Attribute; namespace Mcp\Capability\Attribute;
use Mcp\Schema\Annotations; use Mcp\Schema\Annotations;
use Mcp\Schema\Icon;
/** /**
* Marks a PHP class as representing or handling a specific MCP Resource instance. * Marks a PHP class as representing or handling a specific MCP Resource instance.
@ -29,6 +30,7 @@ final class McpResource
* @param ?string $mimeType the MIME type, if known and constant for this resource * @param ?string $mimeType the MIME type, if known and constant for this resource
* @param ?int $size the size in bytes, if known and constant * @param ?int $size the size in bytes, if known and constant
* @param Annotations|null $annotations optional annotations describing the resource * @param Annotations|null $annotations optional annotations describing the resource
* @param ?Icon[] $icons Optional list of icon URLs representing the resource
* @param ?array<string, mixed> $meta Optional metadata * @param ?array<string, mixed> $meta Optional metadata
*/ */
public function __construct( public function __construct(
@ -38,6 +40,7 @@ final class McpResource
public ?string $mimeType = null, public ?string $mimeType = null,
public ?int $size = null, public ?int $size = null,
public ?Annotations $annotations = null, public ?Annotations $annotations = null,
public ?array $icons = null,
public ?array $meta = null, public ?array $meta = null,
) { ) {
} }

View file

@ -11,6 +11,7 @@
namespace Mcp\Capability\Attribute; namespace Mcp\Capability\Attribute;
use Mcp\Schema\Icon;
use Mcp\Schema\ToolAnnotations; use Mcp\Schema\ToolAnnotations;
/** /**
@ -23,12 +24,14 @@ class McpTool
* @param string|null $name The name of the tool (defaults to the method name) * @param string|null $name The name of the tool (defaults to the method name)
* @param string|null $description The description of the tool (defaults to the DocBlock/inferred) * @param string|null $description The description of the tool (defaults to the DocBlock/inferred)
* @param ToolAnnotations|null $annotations Optional annotations describing tool behavior * @param ToolAnnotations|null $annotations Optional annotations describing tool behavior
* @param ?Icon[] $icons Optional list of icon URLs representing the tool
* @param ?array<string, mixed> $meta Optional metadata * @param ?array<string, mixed> $meta Optional metadata
*/ */
public function __construct( public function __construct(
public ?string $name = null, public ?string $name = null,
public ?string $description = null, public ?string $description = null,
public ?ToolAnnotations $annotations = null, public ?ToolAnnotations $annotations = null,
public ?array $icons = null,
public ?array $meta = null, public ?array $meta = null,
) { ) {
} }

View file

@ -222,8 +222,14 @@ class Discoverer
$name = $instance->name ?? ('__invoke' === $methodName ? $classShortName : $methodName); $name = $instance->name ?? ('__invoke' === $methodName ? $classShortName : $methodName);
$description = $instance->description ?? $this->docBlockParser->getSummary($docBlock) ?? null; $description = $instance->description ?? $this->docBlockParser->getSummary($docBlock) ?? null;
$inputSchema = $this->schemaGenerator->generate($method); $inputSchema = $this->schemaGenerator->generate($method);
$meta = $instance->meta ?? null; $tool = new Tool(
$tool = new Tool($name, $inputSchema, $description, $instance->annotations, meta: $meta); $name,
$inputSchema,
$description,
$instance->annotations,
$instance->icons,
$instance->meta,
);
$tools[$name] = new ToolReference($tool, [$className, $methodName], false); $tools[$name] = new ToolReference($tool, [$className, $methodName], false);
++$discoveredCount['tools']; ++$discoveredCount['tools'];
break; break;
@ -232,11 +238,16 @@ class Discoverer
$docBlock = $this->docBlockParser->parseDocBlock($method->getDocComment() ?? null); $docBlock = $this->docBlockParser->parseDocBlock($method->getDocComment() ?? null);
$name = $instance->name ?? ('__invoke' === $methodName ? $classShortName : $methodName); $name = $instance->name ?? ('__invoke' === $methodName ? $classShortName : $methodName);
$description = $instance->description ?? $this->docBlockParser->getSummary($docBlock) ?? null; $description = $instance->description ?? $this->docBlockParser->getSummary($docBlock) ?? null;
$mimeType = $instance->mimeType; $resource = new Resource(
$size = $instance->size; $instance->uri,
$annotations = $instance->annotations; $name,
$meta = $instance->meta; $description,
$resource = new Resource($instance->uri, $name, $description, $mimeType, $annotations, $size, $meta); $instance->mimeType,
$instance->annotations,
$instance->size,
$instance->icons,
$instance->meta,
);
$resources[$instance->uri] = new ResourceReference($resource, [$className, $methodName], false); $resources[$instance->uri] = new ResourceReference($resource, [$className, $methodName], false);
++$discoveredCount['resources']; ++$discoveredCount['resources'];
@ -256,8 +267,7 @@ class Discoverer
$paramTag = $paramTags['$'.$param->getName()] ?? null; $paramTag = $paramTags['$'.$param->getName()] ?? null;
$arguments[] = new PromptArgument($param->getName(), $paramTag ? trim((string) $paramTag->getDescription()) : null, !$param->isOptional() && !$param->isDefaultValueAvailable()); $arguments[] = new PromptArgument($param->getName(), $paramTag ? trim((string) $paramTag->getDescription()) : null, !$param->isOptional() && !$param->isDefaultValueAvailable());
} }
$meta = $instance->meta ?? null; $prompt = new Prompt($name, $description, $arguments, $instance->icons, $instance->meta);
$prompt = new Prompt($name, $description, $arguments, $meta);
$completionProviders = $this->getCompletionProviders($method); $completionProviders = $this->getCompletionProviders($method);
$prompts[$name] = new PromptReference($prompt, [$className, $methodName], false, $completionProviders); $prompts[$name] = new PromptReference($prompt, [$className, $methodName], false, $completionProviders);
++$discoveredCount['prompts']; ++$discoveredCount['prompts'];

View file

@ -22,6 +22,7 @@ use Mcp\Capability\Registry\ElementReference;
use Mcp\Capability\Registry\ReferenceRegistryInterface; use Mcp\Capability\Registry\ReferenceRegistryInterface;
use Mcp\Exception\ConfigurationException; use Mcp\Exception\ConfigurationException;
use Mcp\Schema\Annotations; use Mcp\Schema\Annotations;
use Mcp\Schema\Icon;
use Mcp\Schema\Prompt; use Mcp\Schema\Prompt;
use Mcp\Schema\PromptArgument; use Mcp\Schema\PromptArgument;
use Mcp\Schema\Resource; use Mcp\Schema\Resource;
@ -45,7 +46,7 @@ final class ArrayLoader implements LoaderInterface
* name: ?string, * name: ?string,
* description: ?string, * description: ?string,
* annotations: ?ToolAnnotations, * annotations: ?ToolAnnotations,
* icons: ?array<int, \Mcp\Schema\Icon>, * icons: ?Icon[],
* meta: ?array<string, mixed> * meta: ?array<string, mixed>
* }[] $tools * }[] $tools
* @param array{ * @param array{
@ -56,6 +57,7 @@ final class ArrayLoader implements LoaderInterface
* mimeType: ?string, * mimeType: ?string,
* size: int|null, * size: int|null,
* annotations: ?Annotations, * annotations: ?Annotations,
* icons: ?Icon[],
* meta: ?array<string, mixed> * meta: ?array<string, mixed>
* }[] $resources * }[] $resources
* @param array{ * @param array{
@ -71,14 +73,15 @@ final class ArrayLoader implements LoaderInterface
* handler: Handler, * handler: Handler,
* name: ?string, * name: ?string,
* description: ?string, * description: ?string,
* icons: ?Icon[],
* meta: ?array<string, mixed> * meta: ?array<string, mixed>
* }[] $prompts * }[] $prompts
*/ */
public function __construct( public function __construct(
private array $tools = [], private readonly array $tools = [],
private array $resources = [], private readonly array $resources = [],
private array $resourceTemplates = [], private readonly array $resourceTemplates = [],
private array $prompts = [], private readonly array $prompts = [],
private LoggerInterface $logger = new NullLogger(), private LoggerInterface $logger = new NullLogger(),
) { ) {
} }
@ -145,13 +148,16 @@ final class ArrayLoader implements LoaderInterface
$description = $data['description'] ?? $docBlockParser->getSummary($docBlock) ?? null; $description = $data['description'] ?? $docBlockParser->getSummary($docBlock) ?? null;
} }
$uri = $data['uri']; $resource = new Resource(
$mimeType = $data['mimeType']; $data['uri'],
$size = $data['size']; $name,
$annotations = $data['annotations']; $description,
$meta = $data['meta']; $data['mimeType'],
$data['annotations'],
$resource = new Resource($uri, $name, $description, $mimeType, $annotations, $size, $meta); $data['size'],
$data['icons'],
$data['meta'],
);
$registry->registerResource($resource, $data['handler'], true); $registry->registerResource($resource, $data['handler'], true);
$handlerDesc = $this->getHandlerDescription($data['handler']); $handlerDesc = $this->getHandlerDescription($data['handler']);
@ -182,12 +188,14 @@ final class ArrayLoader implements LoaderInterface
$description = $data['description'] ?? $docBlockParser->getSummary($docBlock) ?? null; $description = $data['description'] ?? $docBlockParser->getSummary($docBlock) ?? null;
} }
$uriTemplate = $data['uriTemplate']; $template = new ResourceTemplate(
$mimeType = $data['mimeType']; $data['uriTemplate'],
$annotations = $data['annotations']; $name,
$meta = $data['meta']; $description,
$data['mimeType'],
$template = new ResourceTemplate($uriTemplate, $name, $description, $mimeType, $annotations, $meta); $data['annotations'],
$data['meta'],
);
$completionProviders = $this->getCompletionProviders($reflection); $completionProviders = $this->getCompletionProviders($reflection);
$registry->registerResourceTemplate($template, $data['handler'], $completionProviders, true); $registry->registerResourceTemplate($template, $data['handler'], $completionProviders, true);
@ -238,8 +246,7 @@ final class ArrayLoader implements LoaderInterface
!$param->isOptional() && !$param->isDefaultValueAvailable(), !$param->isOptional() && !$param->isDefaultValueAvailable(),
); );
} }
$meta = $data['meta']; $prompt = new Prompt($name, $description, $arguments, $data['icons'], $data['meta']);
$prompt = new Prompt($name, $description, $arguments, $meta);
$completionProviders = $this->getCompletionProviders($reflection); $completionProviders = $this->getCompletionProviders($reflection);
$registry->registerPrompt($prompt, $data['handler'], $completionProviders, true); $registry->registerPrompt($prompt, $data['handler'], $completionProviders, true);

View file

@ -83,7 +83,7 @@ final class Builder
* name: ?string, * name: ?string,
* description: ?string, * description: ?string,
* annotations: ?ToolAnnotations, * annotations: ?ToolAnnotations,
* icons: ?array<int, Icon>, * icons: ?Icon[],
* meta: ?array<string, mixed> * meta: ?array<string, mixed>
* }[] * }[]
*/ */
@ -98,6 +98,7 @@ final class Builder
* mimeType: ?string, * mimeType: ?string,
* size: int|null, * size: int|null,
* annotations: ?Annotations, * annotations: ?Annotations,
* icons: ?Icon[],
* meta: ?array<string, mixed> * meta: ?array<string, mixed>
* }[] * }[]
*/ */
@ -121,6 +122,7 @@ final class Builder
* handler: Handler, * handler: Handler,
* name: ?string, * name: ?string,
* description: ?string, * description: ?string,
* icons: ?Icon[],
* meta: ?array<string, mixed> * meta: ?array<string, mixed>
* }[] * }[]
*/ */
@ -316,7 +318,7 @@ final class Builder
* *
* @param Handler $handler * @param Handler $handler
* @param array<string, mixed>|null $inputSchema * @param array<string, mixed>|null $inputSchema
* @param Icon[]|null $icons * @param ?Icon[] $icons
* @param array<string, mixed>|null $meta * @param array<string, mixed>|null $meta
*/ */
public function addTool( public function addTool(
@ -328,7 +330,15 @@ final class Builder
?array $icons = null, ?array $icons = null,
?array $meta = null, ?array $meta = null,
): self { ): self {
$this->tools[] = compact('handler', 'name', 'description', 'annotations', 'inputSchema', 'icons', 'meta'); $this->tools[] = compact(
'handler',
'name',
'description',
'annotations',
'inputSchema',
'icons',
'meta',
);
return $this; return $this;
} }
@ -337,6 +347,7 @@ final class Builder
* Manually registers a resource handler. * Manually registers a resource handler.
* *
* @param Handler $handler * @param Handler $handler
* @param ?Icon[] $icons
* @param array<string, mixed>|null $meta * @param array<string, mixed>|null $meta
*/ */
public function addResource( public function addResource(
@ -347,9 +358,20 @@ final class Builder
?string $mimeType = null, ?string $mimeType = null,
?int $size = null, ?int $size = null,
?Annotations $annotations = null, ?Annotations $annotations = null,
?array $icons = null,
?array $meta = null, ?array $meta = null,
): self { ): self {
$this->resources[] = compact('handler', 'uri', 'name', 'description', 'mimeType', 'size', 'annotations', 'meta'); $this->resources[] = compact(
'handler',
'uri',
'name',
'description',
'mimeType',
'size',
'annotations',
'icons',
'meta',
);
return $this; return $this;
} }
@ -383,10 +405,15 @@ final class Builder
* Manually registers a prompt handler. * Manually registers a prompt handler.
* *
* @param Handler $handler * @param Handler $handler
* @param ?Icon[] $icons
*/ */
public function addPrompt(\Closure|array|string $handler, ?string $name = null, ?string $description = null): self public function addPrompt(
{ \Closure|array|string $handler,
$this->prompts[] = compact('handler', 'name', 'description'); ?string $name = null,
?string $description = null,
?array $icons = null,
): self {
$this->prompts[] = compact('handler', 'name', 'description', 'icons');
return $this; return $this;
} }

View file

@ -109,7 +109,8 @@ abstract class InspectorSnapshotTestCase extends TestCase
$expected = file_get_contents($snapshotFile); $expected = file_get_contents($snapshotFile);
$this->assertJsonStringEqualsJsonString($expected, $normalizedOutput); $message = \sprintf('Output does not match snapshot "%s".', $snapshotFile);
$this->assertJsonStringEqualsJsonString($expected, $normalizedOutput, $message);
} }
protected function normalizeTestOutput(string $output, ?string $testName = null): string protected function normalizeTestOutput(string $output, ?string $testName = null): string

View file

@ -4,6 +4,15 @@
"name": "calculator_config", "name": "calculator_config",
"uri": "config://calculator/settings", "uri": "config://calculator/settings",
"description": "Current settings for the calculator tool (precision, allow_negative).", "description": "Current settings for the calculator tool (precision, allow_negative).",
"icons": [
{
"mimeType": "image/svg+xml",
"sizes": [
"any"
],
"src": "https://www.svgrepo.com/show/529867/settings.svg"
}
],
"mimeType": "application/json" "mimeType": "application/json"
} }
] ]

View file

@ -3,6 +3,15 @@
{ {
"name": "calculate", "name": "calculate",
"description": "Performs a calculation based on the operation.", "description": "Performs a calculation based on the operation.",
"icons": [
{
"mimeType": "image/svg+xml",
"sizes": [
"any"
],
"src": "https://www.svgrepo.com/show/530644/calculator.svg"
}
],
"inputSchema": { "inputSchema": {
"type": "object", "type": "object",
"properties": { "properties": {