| 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\Schema\Message; |
| 15: | |
| 16: | use Nexus\Mcp\Schema\Arrayable; |
| 17: | use Nexus\Mcp\Schema\Enum\ErrorCode; |
| 18: | |
| 19: | /** |
| 20: | * A response to a request that indicates an error occurred. |
| 21: | * |
| 22: | * @extends Message<array{ |
| 23: | * jsonrpc: '2.0', |
| 24: | * id: int|non-empty-string, |
| 25: | * error: template-type<Error, Arrayable, 'T'>, |
| 26: | * }> |
| 27: | */ |
| 28: | final readonly class JsonRpcError extends Message |
| 29: | { |
| 30: | /** |
| 31: | * @var non-empty-string |
| 32: | */ |
| 33: | public string $jsonrpc; |
| 34: | |
| 35: | public Error $error; |
| 36: | |
| 37: | /** |
| 38: | * @param RequestId $id The ID of the request that resulted in the error. |
| 39: | * @param ErrorCode $errorCode The error type that occurred. |
| 40: | * @param string $message A short description of the error. |
| 41: | * @param null|array<string, mixed> $data Additional information about the error. |
| 42: | */ |
| 43: | public function __construct( |
| 44: | public RequestId $id, |
| 45: | ErrorCode $errorCode, |
| 46: | string $message = '', |
| 47: | ?array $data = null, |
| 48: | ) { |
| 49: | if ('' === $message) { |
| 50: | $message = $errorCode->message(); |
| 51: | } |
| 52: | |
| 53: | $this->jsonrpc = self::JSON_RPC_VERSION; |
| 54: | $this->error = new Error($errorCode->value, $message, $data); |
| 55: | } |
| 56: | |
| 57: | #[\Override] |
| 58: | public function toArray(): array |
| 59: | { |
| 60: | return [ |
| 61: | 'jsonrpc' => $this->jsonrpc, |
| 62: | 'id' => $this->id->value, |
| 63: | 'error' => $this->error->toArray(), |
| 64: | ]; |
| 65: | } |
| 66: | |
| 67: | #[\Override] |
| 68: | public function jsonSerialize(): array |
| 69: | { |
| 70: | return $this->toArray(); |
| 71: | } |
| 72: | } |
| 73: |