Introduce Capability Registry & Discovery
This commit is contained in:
parent
09707b4798
commit
da0d5a87a0
5 changed files with 7063 additions and 8 deletions
289
src/Capability/Registry/RegisteredElement.php
Normal file
289
src/Capability/Registry/RegisteredElement.php
Normal file
|
|
@ -0,0 +1,289 @@
|
|||
<?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;
|
||||
|
||||
/**
|
||||
* @phpstan-type CallableArray array{0: object|string, 1: string}
|
||||
*
|
||||
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
|
||||
*/
|
||||
class RegisteredElement implements \JsonSerializable
|
||||
{
|
||||
/**
|
||||
* @var callable|CallableArray|string
|
||||
*/
|
||||
public readonly mixed $handler;
|
||||
public readonly bool $isManual;
|
||||
|
||||
/**
|
||||
* @param callable|CallableArray|string $handler
|
||||
*/
|
||||
public function __construct(
|
||||
callable|array|string $handler,
|
||||
bool $isManual = false,
|
||||
) {
|
||||
$this->handler = $handler;
|
||||
$this->isManual = $isManual;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $arguments
|
||||
*/
|
||||
public function handle(ContainerInterface $container, array $arguments): mixed
|
||||
{
|
||||
if (\is_string($this->handler)) {
|
||||
if (class_exists($this->handler) && method_exists($this->handler, '__invoke')) {
|
||||
$reflection = new \ReflectionMethod($this->handler, '__invoke');
|
||||
$arguments = $this->prepareArguments($reflection, $arguments);
|
||||
$instance = $container->get($this->handler);
|
||||
|
||||
return \call_user_func($instance, ...$arguments);
|
||||
}
|
||||
|
||||
if (\function_exists($this->handler)) {
|
||||
$reflection = new \ReflectionFunction($this->handler);
|
||||
$arguments = $this->prepareArguments($reflection, $arguments);
|
||||
|
||||
return \call_user_func($this->handler, ...$arguments);
|
||||
}
|
||||
}
|
||||
|
||||
if (\is_callable($this->handler)) {
|
||||
$reflection = $this->getReflectionForCallable($this->handler);
|
||||
$arguments = $this->prepareArguments($reflection, $arguments);
|
||||
|
||||
return \call_user_func($this->handler, ...$arguments);
|
||||
}
|
||||
|
||||
if (\is_array($this->handler)) {
|
||||
[$className, $methodName] = $this->handler;
|
||||
$reflection = new \ReflectionMethod($className, $methodName);
|
||||
$arguments = $this->prepareArguments($reflection, $arguments);
|
||||
|
||||
$instance = $container->get($className);
|
||||
|
||||
return \call_user_func([$instance, $methodName], ...$arguments);
|
||||
}
|
||||
|
||||
throw new InvalidArgumentException('Invalid handler type');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $arguments
|
||||
*
|
||||
* @return array<int, mixed>
|
||||
*/
|
||||
protected 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.');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* handler: callable|CallableArray|string,
|
||||
* isManual: bool,
|
||||
* }
|
||||
*/
|
||||
public function jsonSerialize(): array
|
||||
{
|
||||
return [
|
||||
'handler' => $this->handler,
|
||||
'isManual' => $this->isManual,
|
||||
];
|
||||
}
|
||||
}
|
||||
368
src/Capability/Registry/RegisteredPrompt.php
Normal file
368
src/Capability/Registry/RegisteredPrompt.php
Normal file
|
|
@ -0,0 +1,368 @@
|
|||
<?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 CallableArray from RegisteredElement
|
||||
*
|
||||
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
|
||||
*/
|
||||
class RegisteredPrompt extends RegisteredElement
|
||||
{
|
||||
/**
|
||||
* @param callable|CallableArray|string $handler
|
||||
* @param array<string, class-string|object> $completionProviders
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly Prompt $prompt,
|
||||
callable|array|string $handler,
|
||||
bool $isManual = false,
|
||||
public readonly array $completionProviders = [],
|
||||
) {
|
||||
parent::__construct($handler, $isManual);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
public static function fromArray(array $data): self|false
|
||||
{
|
||||
try {
|
||||
if (!isset($data['schema']) || !isset($data['handler'])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$completionProviders = [];
|
||||
foreach ($data['completionProviders'] ?? [] as $argument => $provider) {
|
||||
$completionProviders[$argument] = unserialize($provider);
|
||||
}
|
||||
|
||||
return new self(
|
||||
Prompt::fromArray($data['schema']),
|
||||
$data['handler'],
|
||||
$data['isManual'] ?? false,
|
||||
$completionProviders,
|
||||
);
|
||||
} catch (\Throwable) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the prompt messages.
|
||||
*
|
||||
* @param array<string, mixed> $arguments
|
||||
*
|
||||
* @return PromptMessage[]
|
||||
*/
|
||||
public function get(ContainerInterface $container, array $arguments): array
|
||||
{
|
||||
$result = $this->handle($container, $arguments);
|
||||
|
||||
return $this->formatResult($result);
|
||||
}
|
||||
|
||||
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
|
||||
*/
|
||||
protected 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);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function jsonSerialize(): array
|
||||
{
|
||||
$completionProviders = [];
|
||||
foreach ($this->completionProviders as $argument => $provider) {
|
||||
$completionProviders[$argument] = serialize($provider);
|
||||
}
|
||||
|
||||
return [
|
||||
'schema' => $this->prompt,
|
||||
'completionProviders' => $completionProviders,
|
||||
...parent::jsonSerialize(),
|
||||
];
|
||||
}
|
||||
}
|
||||
248
src/Capability/Registry/RegisteredResource.php
Normal file
248
src/Capability/Registry/RegisteredResource.php
Normal file
|
|
@ -0,0 +1,248 @@
|
|||
<?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;
|
||||
use Psr\Container\ContainerInterface;
|
||||
|
||||
/**
|
||||
* @phpstan-import-type CallableArray from RegisteredElement
|
||||
*
|
||||
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
|
||||
*/
|
||||
class RegisteredResource extends RegisteredElement
|
||||
{
|
||||
/**
|
||||
* @param callable|CallableArray|string $handler
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly Resource $schema,
|
||||
callable|array|string $handler,
|
||||
bool $isManual = false,
|
||||
) {
|
||||
parent::__construct($handler, $isManual);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
public static function fromArray(array $data): self|false
|
||||
{
|
||||
try {
|
||||
if (!isset($data['schema']) || !isset($data['handler'])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return new self(
|
||||
Resource::fromArray($data['schema']),
|
||||
$data['handler'],
|
||||
$data['isManual'] ?? false,
|
||||
);
|
||||
} catch (\Throwable) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the resource content.
|
||||
*
|
||||
* @return ResourceContents[] array of ResourceContents objects
|
||||
*/
|
||||
public function read(ContainerInterface $container, string $uri): array
|
||||
{
|
||||
$result = $this->handle($container, ['uri' => $uri]);
|
||||
|
||||
return $this->formatResult($result, $uri, $this->schema->mimeType);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
protected function formatResult(mixed $readResult, string $uri, ?string $mimeType): 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';
|
||||
}
|
||||
|
||||
public function jsonSerialize(): array
|
||||
{
|
||||
return [
|
||||
'schema' => $this->schema,
|
||||
...parent::jsonSerialize(),
|
||||
];
|
||||
}
|
||||
}
|
||||
357
src/Capability/Registry/RegisteredResourceTemplate.php
Normal file
357
src/Capability/Registry/RegisteredResourceTemplate.php
Normal file
|
|
@ -0,0 +1,357 @@
|
|||
<?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 CallableArray from RegisteredElement
|
||||
*
|
||||
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
|
||||
*/
|
||||
class RegisteredResourceTemplate extends RegisteredElement
|
||||
{
|
||||
/**
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected array $variableNames;
|
||||
/**
|
||||
* @var array<string, string>
|
||||
*/
|
||||
protected array $uriVariables;
|
||||
protected string $uriTemplateRegex;
|
||||
|
||||
/**
|
||||
* @param callable|CallableArray|string $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();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
public static function fromArray(array $data): self|false
|
||||
{
|
||||
try {
|
||||
if (!isset($data['schema']) || !isset($data['handler'])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$completionProviders = [];
|
||||
foreach ($data['completionProviders'] ?? [] as $argument => $provider) {
|
||||
$completionProviders[$argument] = unserialize($provider);
|
||||
}
|
||||
|
||||
return new self(
|
||||
ResourceTemplate::fromArray($data['schema']),
|
||||
$data['handler'],
|
||||
$data['isManual'] ?? false,
|
||||
$completionProviders,
|
||||
);
|
||||
} catch (\Throwable) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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): 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';
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* schema: ResourceTemplate,
|
||||
* completionProviders: array<string, string>,
|
||||
* handler: callable|CallableArray|string,
|
||||
* isManual: bool,
|
||||
* }
|
||||
*/
|
||||
public function jsonSerialize(): array
|
||||
{
|
||||
$completionProviders = [];
|
||||
foreach ($this->completionProviders as $argument => $provider) {
|
||||
$completionProviders[$argument] = serialize($provider);
|
||||
}
|
||||
|
||||
return [
|
||||
'schema' => $this->resourceTemplate,
|
||||
'completionProviders' => $completionProviders,
|
||||
...parent::jsonSerialize(),
|
||||
];
|
||||
}
|
||||
}
|
||||
164
src/Capability/Registry/RegisteredTool.php
Normal file
164
src/Capability/Registry/RegisteredTool.php
Normal file
|
|
@ -0,0 +1,164 @@
|
|||
<?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;
|
||||
use Psr\Container\ContainerInterface;
|
||||
|
||||
/**
|
||||
* @phpstan-import-type CallableArray from RegisteredElement
|
||||
*
|
||||
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
|
||||
*/
|
||||
class RegisteredTool extends RegisteredElement
|
||||
{
|
||||
/**
|
||||
* @param callable|CallableArray|string $handler
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly Tool $tool,
|
||||
callable|array|string $handler,
|
||||
bool $isManual = false,
|
||||
) {
|
||||
parent::__construct($handler, $isManual);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
public static function fromArray(array $data): self|false
|
||||
{
|
||||
try {
|
||||
if (!isset($data['schema']) || !isset($data['handler'])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return new self(
|
||||
Tool::fromArray($data['schema']),
|
||||
$data['handler'],
|
||||
$data['isManual'] ?? false,
|
||||
);
|
||||
} catch (\Throwable) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls the underlying handler for this tool.
|
||||
*
|
||||
* @param array<string, mixed> $arguments
|
||||
*
|
||||
* @return Content[] the content items for CallToolResult
|
||||
*/
|
||||
public function call(ContainerInterface $container, array $arguments): array
|
||||
{
|
||||
$result = $this->handle($container, $arguments);
|
||||
|
||||
return $this->formatResult($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
private 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)];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* schema: Tool,
|
||||
* handler: callable|CallableArray|string,
|
||||
* isManual: bool,
|
||||
* }
|
||||
*/
|
||||
public function jsonSerialize(): array
|
||||
{
|
||||
return [
|
||||
'schema' => $this->tool,
|
||||
...parent::jsonSerialize(),
|
||||
];
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue