Adopt server examples

This commit is contained in:
Christopher Hertel 2025-08-17 02:46:01 +02:00
commit 2ef051a355
No known key found for this signature in database
GPG key ID: 111F6BFF7B6B5AA3
35 changed files with 3639 additions and 756 deletions

View file

@ -11,56 +11,81 @@
namespace Mcp\Capability;
use Mcp\Capability\Registry\RegisteredElement;
use Mcp\Capability\Registry\RegisteredPrompt;
use Mcp\Capability\Registry\RegisteredResource;
use Mcp\Capability\Registry\RegisteredResourceTemplate;
use Mcp\Capability\Registry\RegisteredTool;
use Mcp\Capability\Registry\ElementReference;
use Mcp\Capability\Registry\PromptReference;
use Mcp\Capability\Registry\ReferenceHandler;
use Mcp\Capability\Registry\ResourceReference;
use Mcp\Capability\Registry\ResourceTemplateReference;
use Mcp\Capability\Registry\ToolReference;
use Mcp\Event\PromptListChangedEvent;
use Mcp\Event\ResourceListChangedEvent;
use Mcp\Event\ResourceTemplateListChangedEvent;
use Mcp\Event\ToolListChangedEvent;
use Mcp\Exception\InvalidArgumentException;
use Mcp\Schema\Content\PromptMessage;
use Mcp\Schema\Content\ResourceContents;
use Mcp\Schema\Prompt;
use Mcp\Schema\Resource;
use Mcp\Schema\ResourceTemplate;
use Mcp\Schema\ServerCapabilities;
use Mcp\Schema\Tool;
use Psr\EventDispatcher\EventDispatcherInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
/**
* @phpstan-import-type CallableArray from RegisteredElement
* @phpstan-import-type CallableArray from ElementReference
*
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
*/
class Registry
{
/**
* @var array<string, RegisteredTool>
* @var array<string, ToolReference>
*/
private array $tools = [];
/**
* @var array<string, RegisteredResource>
* @var array<string, ResourceReference>
*/
private array $resources = [];
/**
* @var array<string, RegisteredPrompt>
* @var array<string, PromptReference>
*/
private array $prompts = [];
/**
* @var array<string, RegisteredResourceTemplate>
* @var array<string, ResourceTemplateReference>
*/
private array $resourceTemplates = [];
public function __construct(
private readonly ReferenceHandler $referenceHandler = new ReferenceHandler(),
private readonly ?EventDispatcherInterface $eventDispatcher = null,
private readonly LoggerInterface $logger = new NullLogger(),
) {
}
public function getCapabilities(): ServerCapabilities
{
if (!$this->hasElements()) {
$this->logger->info('No capabilities registered on server.');
}
return new ServerCapabilities(
tools: true, // [] !== $this->tools,
toolsListChanged: $this->eventDispatcher instanceof EventDispatcherInterface,
resources: [] !== $this->resources || [] !== $this->resourceTemplates,
resourcesSubscribe: false,
resourcesListChanged: $this->eventDispatcher instanceof EventDispatcherInterface,
prompts: [] !== $this->prompts,
promptsListChanged: $this->eventDispatcher instanceof EventDispatcherInterface,
logging: false, // true,
completions: true,
);
}
/**
* @param callable|CallableArray|string $handler
*/
@ -75,7 +100,7 @@ class Registry
return;
}
$this->tools[$toolName] = new RegisteredTool($tool, $handler, $isManual);
$this->tools[$toolName] = new ToolReference($tool, $handler, $isManual);
$this->eventDispatcher?->dispatch(new ToolListChangedEvent());
}
@ -94,7 +119,7 @@ class Registry
return;
}
$this->resources[$uri] = new RegisteredResource($resource, $handler, $isManual);
$this->resources[$uri] = new ResourceReference($resource, $handler, $isManual);
$this->eventDispatcher?->dispatch(new ResourceListChangedEvent());
}
@ -118,7 +143,7 @@ class Registry
return;
}
$this->resourceTemplates[$uriTemplate] = new RegisteredResourceTemplate($template, $handler, $isManual, $completionProviders);
$this->resourceTemplates[$uriTemplate] = new ResourceTemplateReference($template, $handler, $isManual, $completionProviders);
$this->eventDispatcher?->dispatch(new ResourceTemplateListChangedEvent());
}
@ -142,12 +167,14 @@ class Registry
return;
}
$this->prompts[$promptName] = new RegisteredPrompt($prompt, $handler, $isManual, $completionProviders);
$this->prompts[$promptName] = new PromptReference($prompt, $handler, $isManual, $completionProviders);
$this->eventDispatcher?->dispatch(new PromptListChangedEvent());
}
/** Checks if any elements (manual or discovered) are currently registered. */
/**
* Checks if any elements (manual or discovered) are currently registered.
*/
public function hasElements(): bool
{
return !empty($this->tools)
@ -193,12 +220,42 @@ class Registry
}
}
public function getTool(string $name): ?RegisteredTool
public function handleCallTool(string $name, array $arguments): array
{
$reference = $this->getTool($name);
if (null === $reference) {
throw new InvalidArgumentException(\sprintf('Tool "%s" is not registered.', $name));
}
return $reference->formatResult(
$this->referenceHandler->handle($reference, $arguments)
);
}
public function getTool(string $name): ?ToolReference
{
return $this->tools[$name] ?? null;
}
public function getResource(string $uri, bool $includeTemplates = true): RegisteredResource|RegisteredResourceTemplate|null
/**
* @return ResourceContents[]
*/
public function handleReadResource(string $uri): array
{
$reference = $this->getResource($uri);
if (null === $reference) {
throw new InvalidArgumentException(\sprintf('Resource "%s" is not registered.', $uri));
}
return $reference->formatResult(
$this->referenceHandler->handle($reference, ['uri' => $uri]),
$uri,
);
}
public function getResource(string $uri, bool $includeTemplates = true): ResourceReference|ResourceTemplateReference|null
{
$registration = $this->resources[$uri] ?? null;
if ($registration) {
@ -220,32 +277,54 @@ class Registry
return null;
}
public function getResourceTemplate(string $uriTemplate): ?RegisteredResourceTemplate
public function getResourceTemplate(string $uriTemplate): ?ResourceTemplateReference
{
return $this->resourceTemplates[$uriTemplate] ?? null;
}
public function getPrompt(string $name): ?RegisteredPrompt
/**
* @return PromptMessage[]
*/
public function handleGetPrompt(string $name, ?array $arguments): array
{
$reference = $this->getPrompt($name);
if (null === $reference) {
throw new InvalidArgumentException(\sprintf('Prompt "%s" is not registered.', $name));
}
return $reference->formatResult(
$this->referenceHandler->handle($reference, $arguments)
);
}
public function getPrompt(string $name): ?PromptReference
{
return $this->prompts[$name] ?? null;
}
/** @return array<string, Tool> */
/**
* @return array<string, Tool>
*/
public function getTools(): array
{
return array_map(fn ($tool) => $tool->tool, $this->tools);
return array_map(fn (ToolReference $tool) => $tool->tool, $this->tools);
}
/** @return array<string, resource> */
/**
* @return array<string, resource>
*/
public function getResources(): array
{
return array_map(fn ($resource) => $resource->schema, $this->resources);
return array_map(fn (ResourceReference $resource) => $resource->schema, $this->resources);
}
/** @return array<string, Prompt> */
/**
* @return array<string, Prompt>
*/
public function getPrompts(): array
{
return array_map(fn ($prompt) => $prompt->prompt, $this->prompts);
return array_map(fn (PromptReference $prompt) => $prompt->prompt, $this->prompts);
}
/** @return array<string, ResourceTemplate> */

View file

@ -0,0 +1,188 @@
<?php
/*
* This file is part of the official PHP MCP SDK.
*
* A collaboration between Symfony and the PHP Foundation.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mcp\Capability\Registry;
use Mcp\Exception\ContainerException;
use Mcp\Exception\ServiceNotFoundException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
/**
* A basic PSR-11 container implementation with simple constructor auto-wiring.
*
* Supports instantiating classes with parameterless constructors or constructors
* where all parameters are type-hinted classes/interfaces known to the container,
* or have default values. Does NOT support scalar/built-in type injection without defaults.
*
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
*/
final class Container implements ContainerInterface
{
/**
* @var array<string, object> Cache for already created instances (shared singletons)
*/
private array $instances = [];
/**
* @var array<string, bool> Track classes currently being resolved to detect circular dependencies
*/
private array $resolving = [];
/**
* Finds an entry of the container by its identifier and returns it.
*
* @param string $id identifier of the entry to look for (usually a FQCN)
*
* @return mixed entry
*
* @throws NotFoundExceptionInterface no entry was found for **this** identifier
* @throws ContainerExceptionInterface Error while retrieving the entry (e.g., dependency resolution failure, circular dependency).
*/
public function get(string $id): mixed
{
// 1. Check instance cache
if (isset($this->instances[$id])) {
return $this->instances[$id];
}
// 2. Check if class exists
if (!class_exists($id) && !interface_exists($id)) { // Also check interface for bindings
throw new ServiceNotFoundException(\sprintf('Class, interface, or entry "%s" not found.', $id));
}
// 7. Circular Dependency Check
if (isset($this->resolving[$id])) {
throw new ContainerException("Circular dependency detected while resolving '{$id}'. Resolution path: ".implode(' -> ', array_keys($this->resolving))." -> {$id}");
}
$this->resolving[$id] = true; // Mark as currently resolving
try {
// 3. Reflect on the class
$reflector = new \ReflectionClass($id);
// Check if class is instantiable (abstract classes, interfaces cannot be directly instantiated)
if (!$reflector->isInstantiable()) {
// We might have an interface bound to a concrete class via set()
// This check is slightly redundant due to class_exists but good practice
throw new ContainerException("Class '{$id}' is not instantiable (e.g., abstract class or interface without explicit binding).");
}
// 4. Get the constructor
$constructor = $reflector->getConstructor();
// 5. If no constructor or constructor has no parameters, instantiate directly
if (null === $constructor || 0 === $constructor->getNumberOfParameters()) {
$instance = $reflector->newInstance();
} else {
// 6. Constructor has parameters, attempt to resolve them
$parameters = $constructor->getParameters();
$resolvedArgs = [];
foreach ($parameters as $parameter) {
$resolvedArgs[] = $this->resolveParameter($parameter, $id);
}
// Instantiate with resolved arguments
$instance = $reflector->newInstanceArgs($resolvedArgs);
}
// Cache the instance
$this->instances[$id] = $instance;
return $instance;
} catch (\ReflectionException $e) {
throw new ContainerException(\sprintf('Reflection failed for %s.', $id), 0, $e);
} catch (ContainerExceptionInterface $e) { // Re-throw container exceptions directly
throw $e;
} catch (\Throwable $e) { // Catch other instantiation errors
throw new ContainerException("Failed to instantiate or resolve dependencies for '{$id}': ".$e->getMessage(), (int) $e->getCode(), $e);
} finally {
// 7. Remove from resolving stack once done (success or failure)
unset($this->resolving[$id]);
}
}
/**
* Attempts to resolve a single constructor parameter.
*
* @throws ContainerExceptionInterface if a required dependency cannot be resolved
*/
private function resolveParameter(\ReflectionParameter $parameter, string $consumerClassId): mixed
{
// Check for type hint
$type = $parameter->getType();
if ($type instanceof \ReflectionNamedType && !$type->isBuiltin()) {
// Type hint is a class or interface name
$typeName = $type->getName();
try {
// Recursively get the dependency
return $this->get($typeName);
} catch (NotFoundExceptionInterface $e) {
// Dependency class not found, fail ONLY if required
if (!$parameter->isOptional() && !$parameter->allowsNull()) {
throw new ContainerException("Unresolvable dependency '{$typeName}' required by '{$consumerClassId}' constructor parameter \${$parameter->getName()}.", 0, $e);
}
// If optional or nullable, proceed (will check allowsNull/Default below)
} catch (ContainerExceptionInterface $e) {
// Dependency itself failed to resolve (e.g., its own deps, circular)
throw new ContainerException("Failed to resolve dependency '{$typeName}' for '{$consumerClassId}' parameter \${$parameter->getName()}: ".$e->getMessage(), 0, $e);
}
}
// Check if parameter has a default value
if ($parameter->isDefaultValueAvailable()) {
return $parameter->getDefaultValue();
}
// Check if parameter allows null (and wasn't resolved above)
if ($parameter->allowsNull()) {
return null;
}
// Check if it was a built-in type without a default (unresolvable by this basic container)
if ($type instanceof \ReflectionNamedType && $type->isBuiltin()) {
throw new ContainerException("Cannot auto-wire built-in type '{$type->getName()}' for required parameter \${$parameter->getName()} in '{$consumerClassId}' constructor. Provide a default value or use a more advanced container.");
}
// Check if it was a union/intersection type without a default (also unresolvable)
if (null !== $type && !$type instanceof \ReflectionNamedType) {
throw new ContainerException("Cannot auto-wire complex type (union/intersection) for required parameter \${$parameter->getName()} in '{$consumerClassId}' constructor. Provide a default value or use a more advanced container.");
}
// If we reach here, it's an untyped, required parameter without a default.
// Or potentially an unresolvable optional class dependency where null is not allowed (edge case).
throw new ContainerException("Cannot resolve required parameter \${$parameter->getName()} for '{$consumerClassId}' constructor (untyped or unresolvable complex type).");
}
/**
* Returns true if the container can return an entry for the given identifier.
* Checks explicitly set instances and if the class/interface exists.
* Does not guarantee `get()` will succeed if auto-wiring fails.
*/
public function has(string $id): bool
{
return isset($this->instances[$id]) || class_exists($id) || interface_exists($id);
}
/**
* Adds a pre-built instance or a factory/binding to the container.
* This basic version only supports pre-built instances (singletons).
*/
public function set(string $id, object $instance): void
{
// Could add support for closures/factories later if needed
$this->instances[$id] = $instance;
}
}

View file

@ -0,0 +1,29 @@
<?php
/*
* This file is part of the official PHP MCP SDK.
*
* A collaboration between Symfony and the PHP Foundation.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mcp\Capability\Registry;
/**
* @phpstan-type Handler \Closure|array{0: object|string, 1: string}|string
*
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
*/
class ElementReference
{
/**
* @param Handler $handler
*/
public function __construct(
public readonly \Closure|array|string $handler,
public readonly bool $isManual = false,
) {
}
}

View file

@ -0,0 +1,311 @@
<?php
/*
* This file is part of the official PHP MCP SDK.
*
* A collaboration between Symfony and the PHP Foundation.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mcp\Capability\Registry;
use Mcp\Exception\RuntimeException;
use Mcp\Schema\Content\AudioContent;
use Mcp\Schema\Content\BlobResourceContents;
use Mcp\Schema\Content\Content;
use Mcp\Schema\Content\EmbeddedResource;
use Mcp\Schema\Content\ImageContent;
use Mcp\Schema\Content\PromptMessage;
use Mcp\Schema\Content\TextContent;
use Mcp\Schema\Content\TextResourceContents;
use Mcp\Schema\Enum\Role;
use Mcp\Schema\Prompt;
use Mcp\Schema\Result\CompletionCompleteResult;
use Psr\Container\ContainerInterface;
/**
* @phpstan-import-type Handler from ElementReference
*
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
*/
class PromptReference extends ElementReference
{
/**
* @param Handler $handler
* @param array<string, class-string|object> $completionProviders
*/
public function __construct(
public readonly Prompt $prompt,
\Closure|array|string $handler,
bool $isManual = false,
public readonly array $completionProviders = [],
) {
parent::__construct($handler, $isManual);
}
public function complete(ContainerInterface $container, string $argument, string $value): CompletionCompleteResult
{
$providerClassOrInstance = $this->completionProviders[$argument] ?? null;
if (null === $providerClassOrInstance) {
return new CompletionCompleteResult([]);
}
if (\is_string($providerClassOrInstance)) {
if (!class_exists($providerClassOrInstance)) {
throw new RuntimeException("Completion provider class '{$providerClassOrInstance}' does not exist.");
}
$provider = $container->get($providerClassOrInstance);
} else {
$provider = $providerClassOrInstance;
}
$completions = $provider->getCompletions($value);
$total = \count($completions);
$hasMore = $total > 100;
$pagedCompletions = \array_slice($completions, 0, 100);
return new CompletionCompleteResult($pagedCompletions, $total, $hasMore);
}
/**
* Formats the raw result of a prompt generator into an array of MCP PromptMessages.
*
* @param mixed $promptGenerationResult expected: array of message structures
*
* @return PromptMessage[] array of PromptMessage objects
*
* @throws \RuntimeException if the result cannot be formatted
* @throws \JsonException if JSON encoding fails
*/
public function formatResult(mixed $promptGenerationResult): array
{
if ($promptGenerationResult instanceof PromptMessage) {
return [$promptGenerationResult];
}
if (!\is_array($promptGenerationResult)) {
throw new RuntimeException('Prompt generator method must return an array of messages.');
}
if (empty($promptGenerationResult)) {
return [];
}
if (\is_array($promptGenerationResult)) {
$allArePromptMessages = true;
$hasPromptMessages = false;
foreach ($promptGenerationResult as $item) {
if ($item instanceof PromptMessage) {
$hasPromptMessages = true;
} else {
$allArePromptMessages = false;
}
}
if ($allArePromptMessages && $hasPromptMessages) {
return $promptGenerationResult;
}
if ($hasPromptMessages) {
$result = [];
foreach ($promptGenerationResult as $index => $item) {
if ($item instanceof PromptMessage) {
$result[] = $item;
} else {
$result = array_merge($result, $this->formatResult($item));
}
}
return $result;
}
if (!array_is_list($promptGenerationResult)) {
if (isset($promptGenerationResult['user']) || isset($promptGenerationResult['assistant'])) {
$result = [];
if (isset($promptGenerationResult['user'])) {
$userContent = $this->formatContent($promptGenerationResult['user']);
$result[] = new PromptMessage(Role::User, $userContent);
}
if (isset($promptGenerationResult['assistant'])) {
$assistantContent = $this->formatContent($promptGenerationResult['assistant']);
$result[] = new PromptMessage(Role::Assistant, $assistantContent);
}
return $result;
}
if (isset($promptGenerationResult['role']) && isset($promptGenerationResult['content'])) {
return [$this->formatMessage($promptGenerationResult)];
}
throw new RuntimeException('Associative array must contain either role/content keys or user/assistant keys.');
}
$formattedMessages = [];
foreach ($promptGenerationResult as $index => $message) {
if ($message instanceof PromptMessage) {
$formattedMessages[] = $message;
} else {
$formattedMessages[] = $this->formatMessage($message, $index);
}
}
return $formattedMessages;
}
throw new RuntimeException('Invalid prompt generation result format.');
}
/**
* Formats a single message into a PromptMessage.
*/
private function formatMessage(mixed $message, ?int $index = null): PromptMessage
{
$indexStr = null !== $index ? " at index {$index}" : '';
if (!\is_array($message) || !\array_key_exists('role', $message) || !\array_key_exists('content', $message)) {
throw new RuntimeException("Invalid message format{$indexStr}. Expected an array with 'role' and 'content' keys.");
}
$role = $message['role'] instanceof Role ? $message['role'] : Role::tryFrom($message['role']);
if (null === $role) {
throw new RuntimeException("Invalid role '{$message['role']}' in prompt message{$indexStr}. Only 'user' or 'assistant' are supported.");
}
$content = $this->formatContent($message['content'], $index);
return new PromptMessage($role, $content);
}
/**
* Formats content into a proper Content object.
*/
private function formatContent(mixed $content, ?int $index = null): TextContent|ImageContent|AudioContent|EmbeddedResource
{
$indexStr = null !== $index ? " at index {$index}" : '';
if ($content instanceof Content) {
if (
$content instanceof TextContent || $content instanceof ImageContent
|| $content instanceof AudioContent || $content instanceof EmbeddedResource
) {
return $content;
}
throw new RuntimeException("Invalid Content type{$indexStr}. PromptMessage only supports TextContent, ImageContent, AudioContent, or EmbeddedResource.");
}
if (\is_string($content)) {
return new TextContent($content);
}
if (\is_array($content) && isset($content['type'])) {
return $this->formatTypedContent($content, $index);
}
if (\is_scalar($content) || null === $content) {
$stringContent = null === $content ? '(null)' : (\is_bool($content) ? ($content ? 'true' : 'false') : (string) $content);
return new TextContent($stringContent);
}
$jsonContent = json_encode($content, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE | \JSON_THROW_ON_ERROR);
return new TextContent($jsonContent);
}
/**
* Formats typed content arrays into Content objects.
*
* @param array<string, mixed> $content
*/
private function formatTypedContent(array $content, ?int $index = null): TextContent|ImageContent|AudioContent|EmbeddedResource
{
$indexStr = null !== $index ? " at index {$index}" : '';
$type = $content['type'];
return match ($type) {
'text' => $this->formatTextContent($content, $indexStr),
'image' => $this->formatImageContent($content, $indexStr),
'audio' => $this->formatAudioContent($content, $indexStr),
'resource' => $this->formatResourceContent($content, $indexStr),
default => throw new RuntimeException("Invalid content type '{$type}'{$indexStr}."),
};
}
/**
* @param array<string, mixed> $content
*/
private function formatTextContent(array $content, string $indexStr): TextContent
{
if (!isset($content['text']) || !\is_string($content['text'])) {
throw new RuntimeException(\sprintf('Invalid "text" content%s: Missing or invalid "text" string.', $indexStr));
}
return new TextContent($content['text']);
}
/**
* @param array<string, mixed> $content
*/
private function formatImageContent(array $content, string $indexStr): ImageContent
{
if (!isset($content['data']) || !\is_string($content['data'])) {
throw new RuntimeException("Invalid 'image' content{$indexStr}: Missing or invalid 'data' string (base64).");
}
if (!isset($content['mimeType']) || !\is_string($content['mimeType'])) {
throw new RuntimeException("Invalid 'image' content{$indexStr}: Missing or invalid 'mimeType' string.");
}
return new ImageContent($content['data'], $content['mimeType']);
}
/**
* @param array<string, mixed> $content
*/
private function formatAudioContent(array $content, string $indexStr): AudioContent
{
if (!isset($content['data']) || !\is_string($content['data'])) {
throw new RuntimeException("Invalid 'audio' content{$indexStr}: Missing or invalid 'data' string (base64).");
}
if (!isset($content['mimeType']) || !\is_string($content['mimeType'])) {
throw new RuntimeException("Invalid 'audio' content{$indexStr}: Missing or invalid 'mimeType' string.");
}
return new AudioContent($content['data'], $content['mimeType']);
}
/**
* @param array<string, mixed> $content
*/
private function formatResourceContent(array $content, string $indexStr): EmbeddedResource
{
if (!isset($content['resource']) || !\is_array($content['resource'])) {
throw new RuntimeException("Invalid 'resource' content{$indexStr}: Missing or invalid 'resource' object.");
}
$resource = $content['resource'];
if (!isset($resource['uri']) || !\is_string($resource['uri'])) {
throw new RuntimeException("Invalid resource{$indexStr}: Missing or invalid 'uri'.");
}
if (isset($resource['text']) && \is_string($resource['text'])) {
$resourceObj = new TextResourceContents($resource['uri'], $resource['mimeType'] ?? 'text/plain', $resource['text']);
} elseif (isset($resource['blob']) && \is_string($resource['blob'])) {
$resourceObj = new BlobResourceContents(
$resource['uri'],
$resource['mimeType'] ?? 'application/octet-stream',
$resource['blob']
);
} else {
throw new RuntimeException("Invalid resource{$indexStr}: Must contain 'text' or 'blob'.");
}
return new EmbeddedResource($resourceObj);
}
}

View file

@ -0,0 +1,269 @@
<?php
/*
* This file is part of the official PHP MCP SDK.
*
* A collaboration between Symfony and the PHP Foundation.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mcp\Capability\Registry;
use Mcp\Exception\InvalidArgumentException;
use Mcp\Exception\RegistryException;
use Psr\Container\ContainerInterface;
/**
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
*/
class ReferenceHandler
{
public function __construct(
private readonly ?ContainerInterface $container = null,
) {
}
/**
* @param array<string, mixed> $arguments
*/
public function handle(ElementReference $reference, array $arguments): mixed
{
if (\is_string($reference->handler)) {
if (class_exists($reference->handler) && method_exists($reference->handler, '__invoke')) {
$reflection = new \ReflectionMethod($reference->handler, '__invoke');
$instance = $this->getClassInstance($reference->handler);
$arguments = $this->prepareArguments($reflection, $arguments);
return \call_user_func($instance, ...$arguments);
}
if (\function_exists($reference->handler)) {
$reflection = new \ReflectionFunction($reference->handler);
$arguments = $this->prepareArguments($reflection, $arguments);
return \call_user_func($reference->handler, ...$arguments);
}
}
if (\is_callable($reference->handler)) {
$reflection = $this->getReflectionForCallable($reference->handler);
$arguments = $this->prepareArguments($reflection, $arguments);
return \call_user_func($reference->handler, ...$arguments);
}
if (\is_array($reference->handler)) {
[$className, $methodName] = $reference->handler;
$reflection = new \ReflectionMethod($className, $methodName);
$instance = $this->getClassInstance($className);
$arguments = $this->prepareArguments($reflection, $arguments);
return \call_user_func([$instance, $methodName], ...$arguments);
}
throw new InvalidArgumentException('Invalid handler type');
}
private function getClassInstance(string $className): object
{
if (null !== $this->container && $this->container->has($className)) {
return $this->container->get($className);
}
return new $className();
}
/**
* @param array<string, mixed> $arguments
*
* @return array<int, mixed>
*/
private function prepareArguments(\ReflectionFunctionAbstract $reflection, array $arguments): array
{
$finalArgs = [];
foreach ($reflection->getParameters() as $parameter) {
// TODO: Handle variadic parameters.
$paramName = $parameter->getName();
$paramPosition = $parameter->getPosition();
if (isset($arguments[$paramName])) {
$argument = $arguments[$paramName];
try {
$finalArgs[$paramPosition] = $this->castArgumentType($argument, $parameter);
} catch (InvalidArgumentException $e) {
throw RegistryException::invalidParams($e->getMessage(), $e);
} catch (\Throwable $e) {
throw RegistryException::internalError("Error processing parameter `{$paramName}`: {$e->getMessage()}", $e);
}
} elseif ($parameter->isDefaultValueAvailable()) {
$finalArgs[$paramPosition] = $parameter->getDefaultValue();
} elseif ($parameter->allowsNull()) {
$finalArgs[$paramPosition] = null;
} elseif ($parameter->isOptional()) {
continue;
} else {
$reflectionName = $reflection instanceof \ReflectionMethod
? $reflection->class.'::'.$reflection->name
: 'Closure';
throw RegistryException::internalError("Missing required argument `{$paramName}` for {$reflectionName}.");
}
}
return array_values($finalArgs);
}
/**
* Gets a ReflectionMethod or ReflectionFunction for a callable.
*/
private function getReflectionForCallable(callable $handler): \ReflectionMethod|\ReflectionFunction
{
if (\is_string($handler)) {
return new \ReflectionFunction($handler);
}
if ($handler instanceof \Closure) {
return new \ReflectionFunction($handler);
}
if (\is_array($handler) && 2 === \count($handler)) {
[$class, $method] = $handler;
return new \ReflectionMethod($class, $method);
}
throw new InvalidArgumentException('Cannot create reflection for this callable type');
}
/**
* Attempts type casting based on ReflectionParameter type hints.
*
* @throws InvalidArgumentException if casting is impossible for the required type
*/
private function castArgumentType(mixed $argument, \ReflectionParameter $parameter): mixed
{
$type = $parameter->getType();
if (null === $argument) {
if ($type && $type->allowsNull()) {
return null;
}
}
if (!$type instanceof \ReflectionNamedType) {
return $argument;
}
$typeName = $type->getName();
if (enum_exists($typeName)) {
if (\is_object($argument) && $argument instanceof $typeName) {
return $argument;
}
if (is_subclass_of($typeName, \BackedEnum::class)) {
$value = $typeName::tryFrom($argument);
if (null === $value) {
throw new InvalidArgumentException("Invalid value '{$argument}' for backed enum {$typeName}. Expected one of its backing values.");
}
return $value;
} else {
if (\is_string($argument)) {
foreach ($typeName::cases() as $case) {
if ($case->name === $argument) {
return $case;
}
}
$validNames = array_map(fn ($c) => $c->name, $typeName::cases());
throw new InvalidArgumentException("Invalid value '{$argument}' for unit enum {$typeName}. Expected one of: ".implode(', ', $validNames).'.');
} else {
throw new InvalidArgumentException("Invalid value type '{$argument}' for unit enum {$typeName}. Expected a string matching a case name.");
}
}
}
try {
return match (strtolower($typeName)) {
'int', 'integer' => $this->castToInt($argument),
'string' => (string) $argument,
'bool', 'boolean' => $this->castToBoolean($argument),
'float', 'double' => $this->castToFloat($argument),
'array' => $this->castToArray($argument),
default => $argument,
};
} catch (\TypeError $e) {
throw new InvalidArgumentException("Value cannot be cast to required type `{$typeName}`.", 0, $e);
}
}
/**
* Helper to cast strictly to boolean.
*/
private function castToBoolean(mixed $argument): bool
{
if (\is_bool($argument)) {
return $argument;
}
if (1 === $argument || '1' === $argument || 'true' === strtolower((string) $argument)) {
return true;
}
if (0 === $argument || '0' === $argument || 'false' === strtolower((string) $argument)) {
return false;
}
throw new InvalidArgumentException('Cannot cast value to boolean. Use true/false/1/0.');
}
/**
* Helper to cast strictly to integer.
*/
private function castToInt(mixed $argument): int
{
if (\is_int($argument)) {
return $argument;
}
if (is_numeric($argument) && floor((float) $argument) == $argument && !\is_string($argument)) {
return (int) $argument;
}
if (\is_string($argument) && ctype_digit(ltrim($argument, '-'))) {
return (int) $argument;
}
throw new InvalidArgumentException('Cannot cast value to integer. Expected integer representation.');
}
/**
* Helper to cast strictly to float.
*/
private function castToFloat(mixed $argument): float
{
if (\is_float($argument)) {
return $argument;
}
if (\is_int($argument)) {
return (float) $argument;
}
if (is_numeric($argument)) {
return (float) $argument;
}
throw new InvalidArgumentException('Cannot cast value to float. Expected numeric representation.');
}
/**
* Helper to cast strictly to array.
*
* @return array<int, mixed>
*/
private function castToArray(mixed $argument): array
{
if (\is_array($argument)) {
return $argument;
}
throw new InvalidArgumentException('Cannot cast value to array. Expected array.');
}
}

View file

@ -0,0 +1,207 @@
<?php
/*
* This file is part of the official PHP MCP SDK.
*
* A collaboration between Symfony and the PHP Foundation.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mcp\Capability\Registry;
use Mcp\Exception\RuntimeException;
use Mcp\Schema\Content\BlobResourceContents;
use Mcp\Schema\Content\EmbeddedResource;
use Mcp\Schema\Content\ResourceContents;
use Mcp\Schema\Content\TextResourceContents;
use Mcp\Schema\Resource;
/**
* @phpstan-import-type Handler from ElementReference
*
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
*/
class ResourceReference extends ElementReference
{
/**
* @param Handler $handler
*/
public function __construct(
public readonly Resource $schema,
callable|array|string $handler,
bool $isManual = false,
) {
parent::__construct($handler, $isManual);
}
/**
* Formats the raw result of a resource read operation into MCP ResourceContent items.
*
* @param mixed $readResult the raw result from the resource handler method
* @param string $uri the URI of the resource that was read
* @param ?string $mimeType the MIME type from the ResourceDefinition
*
* @return ResourceContents[] array of ResourceContents objects
*
* @throws RuntimeException If the result cannot be formatted.
*
* Supported result types:
* - ResourceContent: Used as-is
* - EmbeddedResource: Resource is extracted from the EmbeddedResource
* - string: Converted to text content with guessed or provided MIME type
* - stream resource: Read and converted to blob with provided MIME type
* - array with 'blob' key: Used as blob content
* - array with 'text' key: Used as text content
* - SplFileInfo: Read and converted to blob
* - array: Converted to JSON if MIME type is application/json or contains 'json'
* For other MIME types, will try to convert to JSON with a warning
*/
public function formatResult(mixed $readResult, string $uri, ?string $mimeType = null): array
{
if ($readResult instanceof ResourceContents) {
return [$readResult];
}
if ($readResult instanceof EmbeddedResource) {
return [$readResult->resource];
}
if (\is_array($readResult)) {
if (empty($readResult)) {
return [new TextResourceContents($uri, 'application/json', '[]')];
}
$allAreResourceContents = true;
$hasResourceContents = false;
$allAreEmbeddedResource = true;
$hasEmbeddedResource = false;
foreach ($readResult as $item) {
if ($item instanceof ResourceContents) {
$hasResourceContents = true;
$allAreEmbeddedResource = false;
} elseif ($item instanceof EmbeddedResource) {
$hasEmbeddedResource = true;
$allAreResourceContents = false;
} else {
$allAreResourceContents = false;
$allAreEmbeddedResource = false;
}
}
if ($allAreResourceContents && $hasResourceContents) {
return $readResult;
}
if ($allAreEmbeddedResource && $hasEmbeddedResource) {
return array_map(fn ($item) => $item->resource, $readResult);
}
if ($hasResourceContents || $hasEmbeddedResource) {
$result = [];
foreach ($readResult as $item) {
if ($item instanceof ResourceContents) {
$result[] = $item;
} elseif ($item instanceof EmbeddedResource) {
$result[] = $item->resource;
} else {
$result = array_merge($result, $this->formatResult($item, $uri, $mimeType));
}
}
return $result;
}
}
if (\is_string($readResult)) {
$mimeType = $mimeType ?? $this->guessMimeTypeFromString($readResult);
return [new TextResourceContents($uri, $mimeType, $readResult)];
}
if (\is_resource($readResult) && 'stream' === get_resource_type($readResult)) {
$result = BlobResourceContents::fromStream(
$uri,
$readResult,
$mimeType ?? 'application/octet-stream'
);
@fclose($readResult);
return [$result];
}
if (\is_array($readResult) && isset($readResult['blob']) && \is_string($readResult['blob'])) {
$mimeType = $readResult['mimeType'] ?? $mimeType ?? 'application/octet-stream';
return [new BlobResourceContents($uri, $mimeType, $readResult['blob'])];
}
if (\is_array($readResult) && isset($readResult['text']) && \is_string($readResult['text'])) {
$mimeType = $readResult['mimeType'] ?? $mimeType ?? 'text/plain';
return [new TextResourceContents($uri, $mimeType, $readResult['text'])];
}
if ($readResult instanceof \SplFileInfo && $readResult->isFile() && $readResult->isReadable()) {
if ($mimeType && str_contains(strtolower($mimeType), 'text')) {
return [new TextResourceContents($uri, $mimeType, file_get_contents($readResult->getPathname()))];
}
return [BlobResourceContents::fromSplFileInfo($uri, $readResult, $mimeType)];
}
if (\is_array($readResult)) {
if ($mimeType && (str_contains(strtolower($mimeType), 'json')
|| 'application/json' === $mimeType)) {
try {
$jsonString = json_encode($readResult, \JSON_THROW_ON_ERROR | \JSON_PRETTY_PRINT);
return [new TextResourceContents($uri, $mimeType, $jsonString)];
} catch (\JsonException $e) {
throw new RuntimeException(\sprintf('Failed to encode array as JSON for URI "%s": %s', $uri, $e->getMessage()));
}
}
try {
$jsonString = json_encode($readResult, \JSON_THROW_ON_ERROR | \JSON_PRETTY_PRINT);
$mimeType = $mimeType ?? 'application/json';
return [new TextResourceContents($uri, $mimeType, $jsonString)];
} catch (\JsonException $e) {
throw new RuntimeException(\sprintf('Failed to encode array as JSON for URI "%s": %s', $uri, $e->getMessage()));
}
}
throw new RuntimeException(\sprintf('Cannot format resource read result for URI "%s". Handler method returned unhandled type: ', $uri).\gettype($readResult));
}
/** Guesses MIME type from string content (very basic) */
private function guessMimeTypeFromString(string $content): string
{
$trimmed = ltrim($content);
if (str_starts_with($trimmed, '<') && str_ends_with(rtrim($content), '>')) {
if (str_contains($trimmed, '<html')) {
return 'text/html';
}
if (str_contains($trimmed, '<?xml')) {
return 'application/xml';
}
return 'text/plain';
}
if (str_starts_with($trimmed, '{') && str_ends_with(rtrim($content), '}')) {
return 'application/json';
}
if (str_starts_with($trimmed, '[') && str_ends_with(rtrim($content), ']')) {
return 'application/json';
}
return 'text/plain';
}
}

View file

@ -0,0 +1,311 @@
<?php
/*
* This file is part of the official PHP MCP SDK.
*
* A collaboration between Symfony and the PHP Foundation.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mcp\Capability\Registry;
use Mcp\Exception\RuntimeException;
use Mcp\Schema\Content\BlobResourceContents;
use Mcp\Schema\Content\EmbeddedResource;
use Mcp\Schema\Content\ResourceContents;
use Mcp\Schema\Content\TextResourceContents;
use Mcp\Schema\ResourceTemplate;
use Mcp\Schema\Result\CompletionCompleteResult;
use Psr\Container\ContainerInterface;
/**
* @phpstan-import-type Handler from ElementReference
*
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
*/
class ResourceTemplateReference extends ElementReference
{
/**
* @var array<int, string>
*/
private array $variableNames;
/**
* @var array<string, string>
*/
private array $uriVariables;
private string $uriTemplateRegex;
/**
* @param Handler $handler
* @param array<string, class-string|object> $completionProviders
*/
public function __construct(
public readonly ResourceTemplate $resourceTemplate,
callable|array|string $handler,
bool $isManual = false,
public readonly array $completionProviders = [],
) {
parent::__construct($handler, $isManual);
$this->compileTemplate();
}
/**
* Gets the resource template.
*
* @return array<int, ResourceContents> array of ResourceContents objects
*/
public function read(ContainerInterface $container, string $uri): array
{
$arguments = array_merge($this->uriVariables, ['uri' => $uri]);
$result = $this->handle($container, $arguments);
return $this->formatResult($result, $uri, $this->resourceTemplate->mimeType);
}
public function complete(ContainerInterface $container, string $argument, string $value): CompletionCompleteResult
{
$providerClassOrInstance = $this->completionProviders[$argument] ?? null;
if (null === $providerClassOrInstance) {
return new CompletionCompleteResult([]);
}
if (\is_string($providerClassOrInstance)) {
if (!class_exists($providerClassOrInstance)) {
throw new RuntimeException(\sprintf('Completion provider class "%s" does not exist.', $providerClassOrInstance));
}
$provider = $container->get($providerClassOrInstance);
} else {
$provider = $providerClassOrInstance;
}
$completions = $provider->getCompletions($value);
$total = \count($completions);
$hasMore = $total > 100;
$pagedCompletions = \array_slice($completions, 0, 100);
return new CompletionCompleteResult($pagedCompletions, $total, $hasMore);
}
/**
* @return array<int, string>
*/
public function getVariableNames(): array
{
return $this->variableNames;
}
public function matches(string $uri): bool
{
if (preg_match($this->uriTemplateRegex, $uri, $matches)) {
$variables = [];
foreach ($this->variableNames as $varName) {
if (isset($matches[$varName])) {
$variables[$varName] = $matches[$varName];
}
}
$this->uriVariables = $variables;
return true;
}
return false;
}
private function compileTemplate(): void
{
$this->variableNames = [];
$regexParts = [];
$segments = preg_split('/(\{\w+\})/', $this->resourceTemplate->uriTemplate, -1, \PREG_SPLIT_DELIM_CAPTURE | \PREG_SPLIT_NO_EMPTY);
foreach ($segments as $segment) {
if (preg_match('/^\{(\w+)\}$/', $segment, $matches)) {
$varName = $matches[1];
$this->variableNames[] = $varName;
$regexParts[] = '(?P<'.$varName.'>[^/]+)';
} else {
$regexParts[] = preg_quote($segment, '#');
}
}
$this->uriTemplateRegex = '#^'.implode('', $regexParts).'$#';
}
/**
* Formats the raw result of a resource read operation into MCP ResourceContent items.
*
* @param mixed $readResult the raw result from the resource handler method
* @param string $uri the URI of the resource that was read
*
* @return array<int, ResourceContents> array of ResourceContents objects
*
* @throws \RuntimeException If the result cannot be formatted.
*
* Supported result types:
* - ResourceContent: Used as-is
* - EmbeddedResource: Resource is extracted from the EmbeddedResource
* - string: Converted to text content with guessed or provided MIME type
* - stream resource: Read and converted to blob with provided MIME type
* - array with 'blob' key: Used as blob content
* - array with 'text' key: Used as text content
* - SplFileInfo: Read and converted to blob
* - array: Converted to JSON if MIME type is application/json or contains 'json'
* For other MIME types, will try to convert to JSON with a warning
*/
protected function formatResult(mixed $readResult, string $uri, ?string $mimeType = null): array
{
if ($readResult instanceof ResourceContents) {
return [$readResult];
}
if ($readResult instanceof EmbeddedResource) {
return [$readResult->resource];
}
if (\is_array($readResult)) {
if (empty($readResult)) {
return [new TextResourceContents($uri, 'application/json', '[]')];
}
$allAreResourceContents = true;
$hasResourceContents = false;
$allAreEmbeddedResource = true;
$hasEmbeddedResource = false;
foreach ($readResult as $item) {
if ($item instanceof ResourceContents) {
$hasResourceContents = true;
$allAreEmbeddedResource = false;
} elseif ($item instanceof EmbeddedResource) {
$hasEmbeddedResource = true;
$allAreResourceContents = false;
} else {
$allAreResourceContents = false;
$allAreEmbeddedResource = false;
}
}
if ($allAreResourceContents && $hasResourceContents) {
return $readResult;
}
if ($allAreEmbeddedResource && $hasEmbeddedResource) {
return array_map(fn ($item) => $item->resource, $readResult);
}
if ($hasResourceContents || $hasEmbeddedResource) {
$result = [];
foreach ($readResult as $item) {
if ($item instanceof ResourceContents) {
$result[] = $item;
} elseif ($item instanceof EmbeddedResource) {
$result[] = $item->resource;
} else {
$result = array_merge($result, $this->formatResult($item, $uri, $mimeType));
}
}
return $result;
}
}
if (\is_string($readResult)) {
$mimeType = $mimeType ?? $this->guessMimeTypeFromString($readResult);
return [new TextResourceContents($uri, $mimeType, $readResult)];
}
if (\is_resource($readResult) && 'stream' === get_resource_type($readResult)) {
$result = BlobResourceContents::fromStream(
$uri,
$readResult,
$mimeType ?? 'application/octet-stream'
);
@fclose($readResult);
return [$result];
}
if (\is_array($readResult) && isset($readResult['blob']) && \is_string($readResult['blob'])) {
$mimeType = $readResult['mimeType'] ?? $mimeType ?? 'application/octet-stream';
return [new BlobResourceContents($uri, $mimeType, $readResult['blob'])];
}
if (\is_array($readResult) && isset($readResult['text']) && \is_string($readResult['text'])) {
$mimeType = $readResult['mimeType'] ?? $mimeType ?? 'text/plain';
return [new TextResourceContents($uri, $mimeType, $readResult['text'])];
}
if ($readResult instanceof \SplFileInfo && $readResult->isFile() && $readResult->isReadable()) {
if ($mimeType && str_contains(strtolower($mimeType), 'text')) {
return [new TextResourceContents($uri, $mimeType, file_get_contents($readResult->getPathname()))];
}
return [BlobResourceContents::fromSplFileInfo($uri, $readResult, $mimeType)];
}
if (\is_array($readResult)) {
if ($mimeType && (str_contains(strtolower($mimeType), 'json')
|| 'application/json' === $mimeType)) {
try {
$jsonString = json_encode($readResult, \JSON_THROW_ON_ERROR | \JSON_PRETTY_PRINT);
return [new TextResourceContents($uri, $mimeType, $jsonString)];
} catch (\JsonException $e) {
throw new RuntimeException("Failed to encode array as JSON for URI '{$uri}': {$e->getMessage()}");
}
}
try {
$jsonString = json_encode($readResult, \JSON_THROW_ON_ERROR | \JSON_PRETTY_PRINT);
$mimeType = $mimeType ?? 'application/json';
return [new TextResourceContents($uri, $mimeType, $jsonString)];
} catch (\JsonException $e) {
throw new RuntimeException("Failed to encode array as JSON for URI '{$uri}': {$e->getMessage()}");
}
}
throw new RuntimeException("Cannot format resource read result for URI '{$uri}'. Handler method returned unhandled type: ".\gettype($readResult));
}
/** Guesses MIME type from string content (very basic) */
private function guessMimeTypeFromString(string $content): string
{
$trimmed = ltrim($content);
if (str_starts_with($trimmed, '<') && str_ends_with(rtrim($content), '>')) {
if (str_contains($trimmed, '<html')) {
return 'text/html';
}
if (str_contains($trimmed, '<?xml')) {
return 'application/xml';
}
return 'text/plain';
}
if (str_starts_with($trimmed, '{') && str_ends_with(rtrim($content), '}')) {
return 'application/json';
}
if (str_starts_with($trimmed, '[') && str_ends_with(rtrim($content), ']')) {
return 'application/json';
}
return 'text/plain';
}
}

View file

@ -0,0 +1,114 @@
<?php
/*
* This file is part of the official PHP MCP SDK.
*
* A collaboration between Symfony and the PHP Foundation.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mcp\Capability\Registry;
use Mcp\Schema\Content\Content;
use Mcp\Schema\Content\TextContent;
use Mcp\Schema\Tool;
/**
* @phpstan-import-type Handler from ElementReference
*
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
*/
class ToolReference extends ElementReference
{
/**
* @param Handler $handler
*/
public function __construct(
public readonly Tool $tool,
callable|array|string $handler,
bool $isManual = false,
) {
parent::__construct($handler, $isManual);
}
/**
* Formats the result of a tool execution into an array of MCP Content items.
*
* - If the result is already a Content object, it's wrapped in an array.
* - If the result is an array:
* - If all elements are Content objects, the array is returned as is.
* - If it's a mixed array (Content and non-Content items), non-Content items are
* individually formatted (scalars to TextContent, others to JSON TextContent).
* - If it's an array with no Content items, the entire array is JSON-encoded into a single TextContent.
* - Scalars (string, int, float, bool) are wrapped in TextContent.
* - null is represented as TextContent('(null)').
* - Other objects are JSON-encoded and wrapped in TextContent.
*
* @param mixed $toolExecutionResult the raw value returned by the tool's PHP method
*
* @return Content[] the content items for CallToolResult
*
* @throws \JsonException if JSON encoding fails for non-Content array/object results
*/
public function formatResult(mixed $toolExecutionResult): array
{
if ($toolExecutionResult instanceof Content) {
return [$toolExecutionResult];
}
if (\is_array($toolExecutionResult)) {
if (empty($toolExecutionResult)) {
return [new TextContent('[]')];
}
$allAreContent = true;
$hasContent = false;
foreach ($toolExecutionResult as $item) {
if ($item instanceof Content) {
$hasContent = true;
} else {
$allAreContent = false;
}
}
if ($allAreContent && $hasContent) {
return $toolExecutionResult;
}
if ($hasContent) {
$result = [];
foreach ($toolExecutionResult as $item) {
if ($item instanceof Content) {
$result[] = $item;
} else {
$result = array_merge($result, $this->formatResult($item));
}
}
return $result;
}
}
if (null === $toolExecutionResult) {
return [new TextContent('(null)')];
}
if (\is_bool($toolExecutionResult)) {
return [new TextContent($toolExecutionResult ? 'true' : 'false')];
}
if (\is_scalar($toolExecutionResult)) {
return [new TextContent($toolExecutionResult)];
}
$jsonResult = json_encode(
$toolExecutionResult,
\JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE | \JSON_THROW_ON_ERROR | \JSON_INVALID_UTF8_SUBSTITUTE
);
return [new TextContent($jsonResult)];
}
}

View file

@ -0,0 +1,18 @@
<?php
/*
* This file is part of the official PHP MCP SDK.
*
* A collaboration between Symfony and the PHP Foundation.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mcp\Exception;
use Psr\Container\ContainerExceptionInterface;
class ContainerException extends Exception implements ContainerExceptionInterface
{
}

View file

@ -0,0 +1,19 @@
<?php
/*
* This file is part of the official PHP MCP SDK.
*
* A collaboration between Symfony and the PHP Foundation.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mcp\Exception;
/**
* @author Christopher Hertel <mail@christopher-hertel.de>
*/
class Exception extends \Exception implements ExceptionInterface
{
}

View file

@ -0,0 +1,18 @@
<?php
/*
* This file is part of the official PHP MCP SDK.
*
* A collaboration between Symfony and the PHP Foundation.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mcp\Exception;
use Psr\Container\NotFoundExceptionInterface;
final class ServiceNotFoundException extends ContainerException implements NotFoundExceptionInterface
{
}

View file

@ -11,14 +11,18 @@
namespace Mcp\JsonRpc;
use Mcp\Capability\Registry;
use Mcp\Exception\ExceptionInterface;
use Mcp\Exception\HandlerNotFoundException;
use Mcp\Exception\InvalidInputMessageException;
use Mcp\Exception\NotFoundExceptionInterface;
use Mcp\Schema\Implementation;
use Mcp\Schema\JsonRpc\Error;
use Mcp\Schema\JsonRpc\HasMethodInterface;
use Mcp\Schema\JsonRpc\Response;
use Mcp\Server\MethodHandlerInterface;
use Mcp\Server\NotificationHandler;
use Mcp\Server\RequestHandler;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
@ -45,6 +49,28 @@ class Handler
$this->methodHandlers = $methodHandlers instanceof \Traversable ? iterator_to_array($methodHandlers) : $methodHandlers;
}
public static function make(
Registry $registry,
Implementation $implementation,
LoggerInterface $logger = new NullLogger(),
): self {
return new self(
MessageFactory::make(),
[
new NotificationHandler\InitializedHandler(),
new RequestHandler\InitializeHandler($registry->getCapabilities(), $implementation),
new RequestHandler\PingHandler(),
new RequestHandler\ListPromptsHandler($registry),
new RequestHandler\GetPromptHandler($registry),
new RequestHandler\ListResourcesHandler($registry),
new RequestHandler\ReadResourceHandler($registry),
new RequestHandler\CallToolHandler($registry, $logger),
new RequestHandler\ListToolsHandler($registry),
],
$logger,
);
}
/**
* @return iterable<string|null>
*
@ -53,12 +79,12 @@ class Handler
*/
public function process(string $input): iterable
{
$this->logger->info('Received message to process', ['message' => $input]);
$this->logger->info('Received message to process.', ['message' => $input]);
try {
$messages = $this->messageFactory->create($input);
} catch (\JsonException $e) {
$this->logger->warning('Failed to decode json message', ['exception' => $e]);
$this->logger->warning('Failed to decode json message.', ['exception' => $e]);
yield $this->encodeResponse(Error::forParseError($e->getMessage()));
@ -67,12 +93,14 @@ class Handler
foreach ($messages as $message) {
if ($message instanceof InvalidInputMessageException) {
$this->logger->warning('Failed to create message', ['exception' => $message]);
$this->logger->warning('Failed to create message.', ['exception' => $message]);
yield $this->encodeResponse(Error::forInvalidRequest($message->getMessage(), 0));
continue;
}
$this->logger->info('Decoded incoming message', ['message' => $message]);
$this->logger->debug(\sprintf('Decoded incoming message "%s".', $message::class), [
'method' => $message->getMethod(),
]);
try {
yield $this->encodeResponse($this->handle($message));
@ -105,7 +133,7 @@ class Handler
return null;
}
$this->logger->info('Encoding response', ['response' => $response]);
$this->logger->info('Encoding response.', ['response' => $response]);
if ($response instanceof Response && [] === $response->result) {
return json_encode($response, \JSON_THROW_ON_ERROR | \JSON_FORCE_OBJECT);
@ -122,12 +150,21 @@ class Handler
*/
private function handle(HasMethodInterface $message): Response|Error|null
{
$this->logger->info(\sprintf('Handling message for method "%s".', $message::getMethod()), [
'message' => $message,
]);
$handled = false;
foreach ($this->methodHandlers as $handler) {
if ($handler->supports($message)) {
$return = $handler->handle($message);
$handled = true;
$this->logger->debug(\sprintf('Message handled by "%s".', $handler::class), [
'method' => $message::getMethod(),
'response' => $return,
]);
if (null !== $return) {
return $return;
}

View file

@ -23,6 +23,7 @@ class Implementation implements \JsonSerializable
public function __construct(
public readonly string $name = 'app',
public readonly string $version = 'dev',
public readonly ?string $description = null,
) {
}
@ -41,7 +42,7 @@ class Implementation implements \JsonSerializable
throw new InvalidArgumentException('Invalid or missing "version" in Implementation data.');
}
return new self($data['name'], $data['version']);
return new self($data['name'], $data['version'], $data['description'] ?? null);
}
/**
@ -52,9 +53,15 @@ class Implementation implements \JsonSerializable
*/
public function jsonSerialize(): array
{
return [
$data = [
'name' => $this->name,
'version' => $this->version,
];
if (null !== $this->description) {
$data['description'] = $this->description;
}
return $data;
}
}

View file

@ -1,7 +1,5 @@
<?php
declare(strict_types=1);
/*
* This file is part of the official PHP MCP SDK.
*

View file

@ -19,4 +19,5 @@ namespace Mcp\Schema\JsonRpc;
interface MessageInterface extends \JsonSerializable
{
public const JSONRPC_VERSION = '2.0';
public const PROTOCOL_VERSION = '2025-06-18';
}

View file

@ -27,7 +27,7 @@ abstract class Notification implements HasMethodInterface, MessageInterface
/**
* @var array<string, mixed>|null
*/
protected ?array $meta;
protected ?array $meta = null;
abstract public static function getMethod(): string;

View file

@ -29,7 +29,7 @@ abstract class Request implements HasMethodInterface, MessageInterface
/**
* @var array<string, mixed>|null
*/
protected ?array $meta;
protected ?array $meta = null;
abstract public static function getMethod(): string;

View file

@ -11,6 +11,7 @@
namespace Mcp\Schema\Request;
use Mcp\Exception\InvalidArgumentException;
use Mcp\Schema\Content\SamplingMessage;
use Mcp\Schema\JsonRpc\Request;
use Mcp\Schema\ModelPreferences;
@ -61,11 +62,11 @@ class CreateSamplingMessageRequest extends Request
protected static function fromParams(?array $params): Request
{
if (!isset($params['messages']) || !\is_array($params['messages'])) {
throw new \InvalidArgumentException('Missing or invalid "messages" parameter for sampling/createMessage.');
throw new InvalidArgumentException('Missing or invalid "messages" parameter for sampling/createMessage.');
}
if (!isset($params['maxTokens']) || !\is_int($params['maxTokens'])) {
throw new \InvalidArgumentException('Missing or invalid "maxTokens" parameter for sampling/createMessage.');
throw new InvalidArgumentException('Missing or invalid "maxTokens" parameter for sampling/createMessage.');
}
$preferences = null;

View file

@ -35,8 +35,8 @@ class EmptyResult implements ResultInterface
/**
* @return array{}
*/
public function jsonSerialize(): array
public function jsonSerialize(): object
{
return [];
return new \stdClass();
}
}

View file

@ -82,7 +82,7 @@ class InitializeResult implements ResultInterface
public function jsonSerialize(): array
{
$data = [
'protocolVersion' => MessageInterface::JSONRPC_VERSION,
'protocolVersion' => MessageInterface::PROTOCOL_VERSION,
'capabilities' => $this->capabilities,
'serverInfo' => $this->serverInfo,
];

Some files were not shown because too many files have changed in this diff Show more