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:
18: /**
19: * The error object in a `JSONRPCError`.
20: *
21: * @implements Arrayable<array{
22: * code: int<-32768, -32000>,
23: * message: non-empty-string,
24: * data?: array<string, mixed>,
25: * }>
26: */
27: final readonly class Error implements \JsonSerializable, Arrayable
28: {
29: /**
30: * @var int<-32768, -32000>
31: */
32: public int $code;
33:
34: /**
35: * @param int $code The error type that occurred.
36: * @param non-empty-string $message A short description of the error.
37: * @param null|array<string, mixed> $data Additional information about the error.
38: */
39: public function __construct(
40: int $code,
41: public string $message,
42: public ?array $data = null,
43: ) {
44: if ($code < -32768 || $code > -32000) {
45: throw new \InvalidArgumentException('Error code must be between -32768 and -32000.');
46: }
47:
48: $this->code = $code;
49: }
50:
51: #[\Override]
52: public function toArray(): array
53: {
54: return array_filter([
55: 'code' => $this->code,
56: 'message' => $this->message,
57: 'data' => $this->data,
58: ], static fn(mixed $value): bool => null !== $value);
59: }
60:
61: /**
62: * @return template-type<self, Arrayable, 'T'>
63: */
64: #[\Override]
65: public function jsonSerialize(): array
66: {
67: return $this->toArray();
68: }
69: }
70: