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\Mcp\Core\Schema\Arrayable;
17: use Nexus\Mcp\Core\Schema\Request;
18: use Nexus\Mcp\Core\Schema\RequestId;
19: use Nexus\Mcp\Core\Schema\RequestParams;
20: use Nexus\Mcp\Core\Schema\RequestParams\EmptyRequestParams;
21:
22: /**
23: * A request that expects a response.
24: *
25: * @template-covariant TMethod of non-empty-string
26: *
27: * @extends Request<TMethod>
28: * @implements Arrayable<array{
29: * jsonrpc: '2.0',
30: * id: int|non-empty-string,
31: * method: non-empty-string,
32: * params?: template-type<RequestParams, Arrayable, 'T'>,
33: * }>
34: *
35: * @see https://modelcontextprotocol.io/specification/2025-11-25/schema#jsonrpcrequest
36: */
37: abstract readonly class JsonRpcRequest extends Request implements Arrayable, JsonRpcMessage
38: {
39: public function __construct(public RequestId $id, RequestParams $params = new EmptyRequestParams())
40: {
41: parent::__construct($params);
42: }
43:
44: /**
45: * @param array<string, mixed> $data
46: */
47: #[\Override]
48: abstract public static function fromArray(array $data): static;
49:
50: #[\Override]
51: public function toArray(): array
52: {
53: $envelope = [
54: 'jsonrpc' => self::JSONRPC_VERSION,
55: 'id' => $this->id->id,
56: 'method' => static::getMethod(),
57: ];
58:
59: $params = $this->params->toArray();
60:
61: if ([] !== $params) {
62: $envelope['params'] = $params;
63: }
64:
65: return $envelope;
66: }
67:
68: #[\Override]
69: public function jsonSerialize(): array
70: {
71: $envelope = [
72: 'jsonrpc' => self::JSONRPC_VERSION,
73: 'id' => $this->id->id,
74: 'method' => static::getMethod(),
75: ];
76:
77: $params = $this->params->jsonSerialize();
78:
79: if ([] !== $params) {
80: $envelope['params'] = $params;
81: }
82:
83: return $envelope;
84: }
85: }
86: