|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | +/** |
| 5 | + * Copyright (c) The Magic , Distributed under the software license |
| 6 | + */ |
| 7 | + |
| 8 | +namespace Dtyq\PhpMcp\Server\Framework\Hyperf\Collector; |
| 9 | + |
| 10 | +use Dtyq\PhpMcp\Server\FastMcp\Tools\RegisteredTool; |
| 11 | +use Dtyq\PhpMcp\Server\Framework\Hyperf\Collector\Annotations\McpTool; |
| 12 | +use Dtyq\PhpMcp\Types\Tools\Tool; |
| 13 | +use Hyperf\Context\ApplicationContext; |
| 14 | +use Hyperf\Di\Annotation\AnnotationCollector; |
| 15 | +use RuntimeException; |
| 16 | + |
| 17 | +class McpCollector |
| 18 | +{ |
| 19 | + protected static bool $collect = false; |
| 20 | + |
| 21 | + /** |
| 22 | + * @var array<string, array<string, RegisteredTool>> |
| 23 | + */ |
| 24 | + protected static array $tools = []; |
| 25 | + |
| 26 | + /** |
| 27 | + * @return array<string, RegisteredTool> |
| 28 | + */ |
| 29 | + public static function getTools(string $group = ''): array |
| 30 | + { |
| 31 | + self::collect(); |
| 32 | + return self::$tools[$group] ?? []; |
| 33 | + } |
| 34 | + |
| 35 | + public static function collect(): void |
| 36 | + { |
| 37 | + if (self::$collect) { |
| 38 | + return; |
| 39 | + } |
| 40 | + |
| 41 | + self::collectTools(); |
| 42 | + |
| 43 | + self::$collect = true; |
| 44 | + } |
| 45 | + |
| 46 | + protected static function collectTools(): void |
| 47 | + { |
| 48 | + $mcpToolAnnotations = AnnotationCollector::getMethodsByAnnotation(McpTool::class); |
| 49 | + var_dump($mcpToolAnnotations); |
| 50 | + foreach ($mcpToolAnnotations as $data) { |
| 51 | + $class = $data['class'] ?? ''; |
| 52 | + $method = $data['method'] ?? ''; |
| 53 | + /** @var McpTool $mcpTool */ |
| 54 | + $mcpTool = $data['annotation'] ?? null; |
| 55 | + if (empty($class) || empty($method) || empty($mcpTool)) { |
| 56 | + continue; |
| 57 | + } |
| 58 | + if (! $mcpTool->isEnabled()) { |
| 59 | + continue; |
| 60 | + } |
| 61 | + $registeredTool = new RegisteredTool( |
| 62 | + new Tool( |
| 63 | + $mcpTool->getName(), |
| 64 | + $mcpTool->getInputSchema(), |
| 65 | + $mcpTool->getDescription() |
| 66 | + ), |
| 67 | + function (array $arguments) use ($class, $method) { |
| 68 | + $container = ApplicationContext::getContainer(); |
| 69 | + if (method_exists($container, 'make')) { |
| 70 | + $instance = $container->make($class); |
| 71 | + } |
| 72 | + if (! isset($instance) || ! method_exists($instance, $method)) { |
| 73 | + throw new RuntimeException("Method {$method} does not exist in class {$class}"); |
| 74 | + } |
| 75 | + return $instance->{$method}(...$arguments); |
| 76 | + } |
| 77 | + ); |
| 78 | + self::$tools[$mcpTool->getGroup()][$mcpTool->getName()] = $registeredTool; |
| 79 | + } |
| 80 | + } |
| 81 | +} |
0 commit comments