forked from EdouardCourty/mcp-server-bundle
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathResponseFactory.php
More file actions
54 lines (46 loc) · 1.53 KB
/
Copy pathResponseFactory.php
File metadata and controls
54 lines (46 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?php
declare(strict_types=1);
namespace Ecourty\McpServerBundle\Service;
use Ecourty\McpServerBundle\Enum\McpErrorCode;
use Ecourty\McpServerBundle\HttpFoundation\JsonRpcError;
use Ecourty\McpServerBundle\HttpFoundation\JsonRpcResponse;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
use Symfony\Component\Serializer\SerializerInterface;
/**
* Factory for creating JSON-RPC responses.
*/
class ResponseFactory
{
public function __construct(
private readonly SerializerInterface $serializer,
) {
}
public function success(int|string|null $id, mixed $result): JsonResponse
{
return $this->createResponse(new JsonRpcResponse(
id: $id,
result: $result,
error: null,
));
}
public function error(int|string|null $id, McpErrorCode $errorCode): JsonResponse
{
return $this->createResponse(new JsonRpcResponse(
id: $id,
result: null,
error: new JsonRpcError(
code: $errorCode,
message: $errorCode->getMessage(),
),
));
}
private function createResponse(JsonRpcResponse $response): JsonResponse
{
$json = $this->serializer->serialize($response, 'json', [
AbstractObjectNormalizer::SKIP_NULL_VALUES => true,
AbstractObjectNormalizer::PRESERVE_EMPTY_OBJECTS => true,
]);
return JsonResponse::fromJsonString($json, JsonResponse::HTTP_OK);
}
}