1: <?php
2:
3: declare(strict_types=1);
4:
5: /**
6: * This file is part of the Nexus MCP SDK package.
7: *
8: * (c) 2026 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\Core\Schema;
15:
16: use Nexus\Assert\Assert;
17: use Nexus\Mcp\Core\Schema\Enum\ProtocolErrorCode;
18:
19: /**
20: * @implements Arrayable<array{
21: * code: int,
22: * message: non-empty-string,
23: * data?: mixed
24: * }>
25: *
26: * @see https://modelcontextprotocol.io/specification/2025-11-25/schema#error
27: */
28: abstract readonly class Error implements Arrayable
29: {
30: public int $code;
31:
32: /**
33: * @var non-empty-string
34: */
35: public string $message;
36:
37: public function __construct(
38: int|ProtocolErrorCode $code,
39: string $message,
40: public mixed $data = null,
41: ) {
42: Assert::that($message)->isNonEmptyString('error "message" must be a non-empty string.');
43:
44: $this->code = $code instanceof ProtocolErrorCode ? $code->value : $code;
45: $this->message = $message;
46: }
47:
48: #[\Override]
49: public function toArray(): array
50: {
51: $result = [
52: 'code' => $this->code,
53: 'message' => $this->message,
54: ];
55:
56: $data = $this->data ?? [];
57:
58: if ([] !== $data) {
59: $result['data'] = $data;
60: }
61:
62: return $result;
63: }
64:
65: #[\Override]
66: public function jsonSerialize(): array
67: {
68: return $this->toArray();
69: }
70: }
71: