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\Error;
15:
16: use Nexus\Assert\Assert;
17: use Nexus\Mcp\Core\Schema\Enum\ProtocolErrorCode;
18: use Nexus\Mcp\Core\Schema\Error;
19:
20: /**
21: * Error carrying a raw integer code that does not map to a known `ProtocolErrorCode` case.
22: *
23: * @extends Error<array{code: int, message: non-empty-string, data?: mixed}>
24: *
25: * @see https://www.jsonrpc.org/specification#error_object
26: */
27: final readonly class UnknownProtocolError extends Error
28: {
29: /**
30: * @param non-empty-string $message
31: */
32: public function __construct(int $code, string $message, mixed $data = null)
33: {
34: if (ProtocolErrorCode::tryFrom($code) !== null) {
35: throw new \InvalidArgumentException(\sprintf('code %d maps to a known protocol error code.', $code));
36: }
37:
38: parent::__construct(code: $code, message: $message, data: $data);
39: }
40:
41: #[\Override]
42: public static function fromArray(array $data): static
43: {
44: Assert::that($data)->hasOffset('code', '"error" is missing the required "code" key.');
45: Assert::that($data['code'])->isInt('"error.code" must be an integer, {type} given.');
46:
47: Assert::that($data)->hasOffset('message', '"error" is missing the required "message" key.');
48: Assert::that($data['message'])->isNonEmptyString('"error.message" must be a non-empty string, {type} given.');
49:
50: return new self(code: $data['code'], message: $data['message'], data: $data['data'] ?? null);
51: }
52:
53: #[\Override]
54: public function toArray(): array
55: {
56: $result = [
57: 'code' => $this->code,
58: 'message' => $this->message,
59: ];
60:
61: $data = $this->data ?? [];
62:
63: if ([] !== $data) {
64: $result['data'] = $data;
65: }
66:
67: return $result;
68: }
69: }
70: