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: * A JSON-RPC error indicating that the request is not a valid request object.
22: *
23: * This error is returned when the message structure does not conform to the JSON-RPC 2.0
24: * specification requirements for a request (e.g., missing required fields like `jsonrpc` or
25: * `method`, or using invalid types for these fields).
26: *
27: * @extends Error<array{code: -32600, message: non-empty-string, data?: mixed}>
28: *
29: * @see https://modelcontextprotocol.io/specification/draft/schema#invalidrequesterror
30: */
31: final readonly class InvalidRequestError extends Error
32: {
33: public const string DEFAULT_MESSAGE = 'Invalid request';
34:
35: public function __construct(string $message, mixed $data = null)
36: {
37: parent::__construct(code: ProtocolErrorCode::InvalidRequest, message: $message, data: $data);
38: }
39:
40: #[\Override]
41: public static function fromArray(array $data): static
42: {
43: $message = $data['message'] ?? self::DEFAULT_MESSAGE;
44: Assert::that($message)->isString('error "message" must be a string, {type} given.');
45:
46: return new self(message: $message, data: $data['data'] ?? null);
47: }
48:
49: #[\Override]
50: public function toArray(): array
51: {
52: $result = [
53: 'code' => ProtocolErrorCode::InvalidRequest->value,
54: 'message' => $this->message,
55: ];
56:
57: $data = $this->data ?? [];
58:
59: if ([] !== $data) {
60: $result['data'] = $data;
61: }
62:
63: return $result;
64: }
65: }
66: