Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
3.45% |
1 / 29 |
|
33.33% |
1 / 3 |
CRAP | |
0.00% |
0 / 1 |
ToolRunner | |
3.45% |
1 / 29 |
|
33.33% |
1 / 3 |
165.11 | |
0.00% |
0 / 1 |
__construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
run | |
0.00% |
0 / 11 |
|
0.00% |
0 / 1 |
6 | |||
actionResponseToToolResult | |
0.00% |
0 / 17 |
|
0.00% |
0 / 1 |
110 |
1 | <?php |
2 | namespace Apie\McpServer\Tool; |
3 | |
4 | use Apie\Common\ApieFacade; |
5 | use Apie\Core\Actions\ActionResponse; |
6 | use Apie\Core\Actions\ActionResponseStatus; |
7 | use Apie\Core\ContextBuilders\ContextBuilderFactory; |
8 | use Apie\Core\ContextConstants; |
9 | use Apie\Core\ValueObjects\Utils; |
10 | use Mcp\Types\CallToolResult; |
11 | use Mcp\Types\TextContent; |
12 | use Mcp\Types\Tool; |
13 | use Psr\Http\Message\ServerRequestInterface; |
14 | use ReflectionClass; |
15 | |
16 | class ToolRunner |
17 | { |
18 | public function __construct( |
19 | private readonly ContextBuilderFactory $contextBuilder, |
20 | private readonly ApieFacade $apieFacade, |
21 | ) { |
22 | } |
23 | public function run(Tool $tool, array $params, ?ServerRequestInterface $request = null): CallToolResult |
24 | { |
25 | $action = new ReflectionClass($tool->{"x-definition"}); |
26 | $fields = Utils::toArray($tool->{"x-fields"}); |
27 | $fields[ContextConstants::MCP_SERVER] = true; |
28 | $fields[Tool::class] = true; |
29 | $fields[ContextConstants::RAW_CONTENTS] = $params; |
30 | $context = $request |
31 | ? $this->contextBuilder->createFromRequest($request, $fields) |
32 | : $this->contextBuilder->createGeneralContext($fields); |
33 | $action = $this->apieFacade->createAction($context); |
34 | /** @var ActionResponse $data */ |
35 | $data = ($action)($context, $params); |
36 | return $this->actionResponseToToolResult($data); |
37 | } |
38 | |
39 | private function actionResponseToToolResult(ActionResponse $input): CallToolResult |
40 | { |
41 | switch ($input->status) { |
42 | case ActionResponseStatus::CREATED: |
43 | case ActionResponseStatus::AUTHORIZATION_ERROR: |
44 | case ActionResponseStatus::CLIENT_ERROR: |
45 | case ActionResponseStatus::DELETED: |
46 | case ActionResponseStatus::NOT_FOUND: |
47 | case ActionResponseStatus::OUTPUT_ERROR: |
48 | case ActionResponseStatus::PERISTENCE_ERROR: |
49 | case ActionResponseStatus::SERVER_ERROR: |
50 | case ActionResponseStatus::SUCCESS: |
51 | return new CallToolResult( |
52 | [ |
53 | new TextContent(json_encode($input->getResultAsNativeData())), |
54 | ], |
55 | false |
56 | ); |
57 | } |
58 | throw new \LogicException('Unknown status ' . $input->status->value); |
59 | } |
60 | } |