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