1: | <?php |
2: | |
3: | declare(strict_types=1); |
4: | |
5: | /** |
6: | * This file is part of the Nexus MCP SDK package. |
7: | * |
8: | * (c) 2025 John Paul E. Balandan, CPA <paulbalandan@gmail.com> |
9: | * |
10: | * For the full copyright and license information, please view |
11: | * the LICENSE file that was distributed with this source code. |
12: | */ |
13: | |
14: | namespace Nexus\Mcp\Message; |
15: | |
16: | use Nexus\Mcp\Enum\ErrorCode; |
17: | |
18: | /** |
19: | * A response to a request that indicates an error occurred. |
20: | */ |
21: | final readonly class JsonRpcError extends Message |
22: | { |
23: | /** |
24: | * @var non-empty-string |
25: | */ |
26: | public string $message; |
27: | |
28: | /** |
29: | * @param non-empty-string $jsonrpc JSON-RPC version. Must be 2.0. |
30: | * @param RequestId $requestId The ID of the request that resulted in the error. |
31: | * @param ErrorCode $errorCode The error type that occurred. |
32: | * @param string $message A short description of the error. The message SHOULD be limited |
33: | * to a concise single sentence. |
34: | * @param null|array<string, mixed> $data Additional information about the error. The value of this member |
35: | * is defined by the sender (e.g. detailed error information, nested errors etc.). |
36: | */ |
37: | public function __construct( |
38: | string $jsonrpc, |
39: | public RequestId $requestId, |
40: | public ErrorCode $errorCode, |
41: | string $message = '', |
42: | public ?array $data = null, |
43: | ) { |
44: | parent::__construct($jsonrpc); |
45: | |
46: | if ('' === $message) { |
47: | $message = $this->errorCode->message(); |
48: | } |
49: | |
50: | $this->message = $message; |
51: | } |
52: | |
53: | /** |
54: | * @return array{ |
55: | * jsonrpc: non-empty-string, |
56: | * id: int|non-empty-string, |
57: | * error: array{ |
58: | * code: int, |
59: | * message: string, |
60: | * data?: array<string, mixed>, |
61: | * }, |
62: | * } |
63: | */ |
64: | #[\Override] |
65: | public function toArray(): array |
66: | { |
67: | return [ |
68: | 'jsonrpc' => $this->jsonrpc, |
69: | 'id' => $this->requestId->id, |
70: | 'error' => array_filter([ |
71: | 'code' => $this->errorCode->value, |
72: | 'message' => $this->message, |
73: | 'data' => $this->data, |
74: | ], static fn(mixed $value): bool => null !== $value), |
75: | ]; |
76: | } |
77: | } |
78: |