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\JsonRpc;
15:
16: use Nexus\Assert\Assert;
17: use Nexus\Mcp\Core\Schema\Arrayable;
18: use Nexus\Mcp\Core\Schema\Enum\ResultType;
19: use Nexus\Mcp\Core\Schema\RequestId;
20: use Nexus\Mcp\Core\Schema\Result;
21:
22: /**
23: * A successful (non-error) response to a request.
24: *
25: * @template-covariant TEnvelope of array<string, mixed> = array<string, mixed>
26: *
27: * @implements Arrayable<TEnvelope>
28: *
29: * @see https://modelcontextprotocol.io/specification/draft/schema#jsonrpcresultresponse
30: */
31: abstract readonly class JsonRpcResultResponse implements Arrayable, JsonRpcResponse
32: {
33: public function __construct(public RequestId $id, public Result $result)
34: {
35: }
36:
37: #[\Override]
38: public function jsonSerialize(): array
39: {
40: return [
41: 'jsonrpc' => self::JSONRPC_VERSION,
42: 'id' => $this->id->id,
43: 'result' => $this->result->jsonSerialize(),
44: ];
45: }
46:
47: /**
48: * @param array<string, mixed> $data
49: *
50: * @throws \InvalidArgumentException
51: */
52: protected static function parseId(array $data): RequestId
53: {
54: Assert::that($data)->hasOffset('id', 'missing the required "id" key.');
55: $id = $data['id'];
56: Assert::that($id)->isArrayKey('"id" must be an int or string, {type} given.');
57:
58: return new RequestId(id: $id);
59: }
60:
61: /**
62: * @param array<string, mixed> $data
63: *
64: * @return array<string, mixed>
65: *
66: * @throws \InvalidArgumentException
67: */
68: protected static function parseResult(array $data): array
69: {
70: Assert::that($data)->hasOffset('result', 'missing the required "result" key.');
71: $result = $data['result'];
72: Assert::that($result)
73: ->isArray('"result" must be an object, {type} given.')
74: ->isMap('"result" must be a string-keyed object.')
75: ;
76:
77: return $result;
78: }
79:
80: /**
81: * @param array<string, mixed> $payload
82: */
83: protected static function isInputRequired(array $payload): bool
84: {
85: return ($payload['resultType'] ?? null) === ResultType::InputRequired->value;
86: }
87:
88: /**
89: * @param array<string, mixed> $payload
90: *
91: * @throws \InvalidArgumentException
92: */
93: protected static function rejectInputRequired(array $payload): void
94: {
95: if (self::isInputRequired($payload)) {
96: throw new \InvalidArgumentException('"result" returned "input_required" for a method that does not support it.');
97: }
98: }
99: }
100: