Repository navigation
Expand file tree
/
Copy pathProtocol.php
More file actions
970 lines (800 loc) · 34.3 KB
/
Copy pathProtocol.php
File metadata and controls
970 lines (800 loc) · 34.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
<?php
/*
* This file is part of the official PHP MCP SDK.
*
* A collaboration between Symfony and the PHP Foundation.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mcp\Client;
use Mcp\Client\Exception\InvalidArgumentException;
use Mcp\Client\Exception\RequestCancelledException;
use Mcp\Client\Exception\TimeoutException;
use Mcp\Client\Handler\Notification\NotificationHandlerInterface;
use Mcp\Client\Handler\Notification\ProgressNotificationHandler;
use Mcp\Client\Handler\Request\RequestHandlerInterface;
use Mcp\Client\State\ClientState;
use Mcp\Client\State\ClientStateInterface;
use Mcp\Client\Stateless\HeaderFactory;
use Mcp\Client\Stateless\InputRequestResolver;
use Mcp\Client\Stateless\RequestEnvelope;
use Mcp\Client\Stateless\ToolCatalog;
use Mcp\Client\Transport\HeaderAwareTransportInterface;
use Mcp\Client\Transport\HttpTransport;
use Mcp\Client\Transport\TransportInterface;
use Mcp\Schema\Enum\LoggingLevel;
use Mcp\Schema\Enum\ProtocolVersion;
use Mcp\Schema\Exception\InvalidInputMessageException;
use Mcp\Schema\Implementation;
use Mcp\Schema\JsonRpc\Error;
use Mcp\Schema\JsonRpc\Notification;
use Mcp\Schema\JsonRpc\Request;
use Mcp\Schema\JsonRpc\Response;
use Mcp\Schema\MessageFactory;
use Mcp\Schema\Notification\CancelledNotification;
use Mcp\Schema\Notification\InitializedNotification;
use Mcp\Schema\Notification\ProgressNotification;
use Mcp\Schema\Request\DiscoverRequest;
use Mcp\Schema\Request\InitializeRequest;
use Mcp\Schema\RequestMeta;
use Mcp\Schema\Result\InitializeResult;
use Mcp\Schema\ServerCapabilities;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
/**
* Client protocol handler for MCP communication.
*
* Handles message routing, request/response correlation, and the initialization handshake.
* All blocking operations are delegated to the transport.
*
* @phpstan-import-type FiberSuspend from TransportInterface
*
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
*/
class Protocol
{
/**
* How many times a request may be re-sent before the client gives up.
*
* Both loops that re-send are bounded by it: a server that keeps asking for
* input, and one that keeps rejecting the offered revision. Neither is
* expected to run more than a round or two, so the cap is only there to
* stop a broken or hostile server from spinning the client forever.
*/
private const MAX_ROUND_TRIPS = 10;
private ?TransportInterface $transport = null;
private ClientStateInterface $state;
private MessageFactory $messageFactory;
private LoggerInterface $logger;
/** @var NotificationHandlerInterface[] */
private array $notificationHandlers;
/** Set only when the configured revision has no handshake. */
private ?RequestEnvelope $envelope = null;
private ?HeaderFactory $headers = null;
private ToolCatalog $tools;
private ?LoggingLevel $logLevel = null;
/** @var (callable(float, ?float, ?string): void)|null */
private $onProgress;
private readonly InputRequestResolver $inputRequests;
/**
* Progress tokens are only required to be unique within a connection, and
* a retry keeps the caller's one — the work being reported on is the same.
*/
private int $progressTokens = 0;
/** The token of the request in flight, the only one whose progress reaches the callback. */
private ?string $progressToken = null;
/**
* @param RequestHandlerInterface<mixed>[] $requestHandlers
* @param NotificationHandlerInterface[] $notificationHandlers
*/
public function __construct(
private readonly array $requestHandlers = [],
array $notificationHandlers = [],
?MessageFactory $messageFactory = null,
?LoggerInterface $logger = null,
) {
$this->state = new ClientState();
$this->messageFactory = $messageFactory ?? MessageFactory::make();
$this->logger = $logger ?? new NullLogger();
$this->notificationHandlers = [
new ProgressNotificationHandler($this->deliverProgress(...)),
...$notificationHandlers,
];
$this->tools = new ToolCatalog($this->logger);
$this->inputRequests = new InputRequestResolver($this->requestHandlers, $this->logger);
}
/**
* What the client knows about the server's tools, from `tools/list`.
*
* Kept on the protocol rather than the facade because it is what makes the
* SEP-2243 headers derivable at send time.
*/
public function getToolCatalog(): ToolCatalog
{
return $this->tools;
}
/**
* Connect this protocol to a transport.
*
* Sets up message handling callbacks.
*
* @param TransportInterface $transport The transport to connect
* @param Configuration $config The client configuration for initialization
*/
public function connect(TransportInterface $transport, Configuration $config): void
{
$this->transport = $transport;
// A fresh catalog per connection: it is what a server told this client
// about its tools, and a server reached by reconnecting — the same one
// or another — has said nothing yet.
$this->tools = new ToolCatalog($this->logger);
$this->logLevel = null;
// A connect can fail before the transport initializes.
$this->forgetServer();
$transport->setState($this->state);
$transport->onInitialize(fn () => $this->initialize($config));
$transport->onMessage($this->processMessage(...));
$transport->onError(fn (\Throwable $e) => $this->logger->error('Transport error', ['exception' => $e]));
if ($transport instanceof HeaderAwareTransportInterface) {
$transport->onHeaders($this->headersFor(...));
}
$this->logger->info('Protocol connected to transport', ['transport' => $transport::class]);
}
/**
* The headers belonging to an encoded message, for a transport that has any.
*
* @return array<string, string>
*/
private function headersFor(string $payload): array
{
if (null === $this->headers || null === $this->envelope) {
return [];
}
$decoded = json_decode($payload, true);
return \is_array($decoded)
? $this->headers->forMessage($decoded, $this->envelope->protocolVersion())
: [];
}
/**
* Ready the connection for use, settling which protocol era it speaks.
*
* @param Configuration $config The client configuration
*
* @return Response<array<string, mixed>>|Error
*/
public function initialize(Configuration $config): Response|Error
{
$this->envelope = null;
$this->headers = null;
$this->forgetServer();
if (!$config->protocolVersion->isModern()) {
return $this->handshake($config->protocolVersion, $config);
}
return $this->negotiate($config);
}
private function forgetServer(): void
{
$this->state->setInitialized(false);
$this->state->setProtocolVersion(null);
$this->state->setServerInfo(null);
$this->state->setInstructions(null);
$this->state->setServerCapabilities(null);
}
/**
* Probe for the modern era, falling back to the handshake unless the server proves to speak it.
*
* @see https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/stdio#backward-compatibility
* @see https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/streamable-http#backward-compatibility
*
* @return Response<array<string, mixed>>|Error
*/
private function negotiate(Configuration $config, ?ProtocolVersion $version = null, bool $reprobed = false): Response|Error
{
$this->enterModernEra($version ?? $config->protocolVersion, $config);
$probe = $this->request(new DiscoverRequest(), $config->initTimeout);
$adopted = $this->adopt($probe);
if ($adopted instanceof Response || $adopted instanceof Error) {
return $adopted;
}
if (null === $config->fallbackProtocolVersion) {
return Error::forInvalidRequest(\sprintf(
'Server does not speak protocol version %s and this client is configured without a handshake fallback: %s',
$config->protocolVersion->value,
self::describe($probe),
));
}
$this->logger->info('Server does not speak the modern era; falling back to the "initialize" handshake.', [
'probe' => self::describe($probe),
'offering' => $config->fallbackProtocolVersion->value,
]);
$this->envelope = null;
$this->headers = null;
$handshake = $this->handshake($config->fallbackProtocolVersion, $config);
// Once more: a timed-out probe may still have settled a slow server on the modern era.
if ($handshake instanceof Error && !$reprobed && null !== $modern = self::mutualModern($handshake)) {
$this->logger->info('Server settled on the modern era after all; probing again.', ['version' => $modern->value]);
return $this->negotiate($config, $modern, true);
}
return $handshake;
}
private function enterModernEra(ProtocolVersion $version, Configuration $config): void
{
$this->envelope = new RequestEnvelope($version, $config->capabilities, $config->clientInfo, $this->logLevel);
$this->headers = new HeaderFactory($this->tools);
}
/**
* Set the callback for progress on the request in flight, null to clear it.
*
* @param (callable(float $progress, ?float $total, ?string $message): void)|null $onProgress
*/
public function setProgressCallback(?callable $onProgress): void
{
$this->onProgress = $onProgress;
}
private function deliverProgress(ProgressNotification $notification): void
{
if (null === $this->onProgress || $notification->progressToken !== $this->progressToken) {
$this->logger->debug('Dropping progress for a request not in flight', ['progressToken' => $notification->progressToken]);
return;
}
try {
($this->onProgress)($notification->progress, $notification->total, $notification->message);
} catch (\Throwable $e) {
$this->logger->warning('Progress callback failed', ['exception' => $e]);
}
}
public function isModern(): bool
{
return null !== $this->envelope;
}
/**
* The modern era's stand-in for `logging/setLevel`.
*/
public function setLogLevel(LoggingLevel $level): void
{
$this->logLevel = $level;
$this->envelope = $this->envelope?->withLogLevel($level);
}
/**
* The modern connection, an error ending the attempt, or null to fall back.
*
* @param Response<array<string, mixed>>|Error $probe
*
* @return Response<array<string, mixed>>|Error|null
*/
private function adopt(Response|Error $probe): Response|Error|null
{
\assert(null !== $this->envelope);
if ($probe instanceof Error) {
if (\is_array($probe->data)) {
foreach ([TransportInterface::CONNECTION_LOST, TransportInterface::RESPONSE_TOO_LARGE, TransportInterface::REDIRECTED] as $marker) {
if (true === ($probe->data[$marker] ?? null)) {
return $probe;
}
}
}
if (Error::UNSUPPORTED_PROTOCOL_VERSION !== $probe->code) {
return null;
}
// Modern revisions it names were already retried by request().
$supported = self::supportedVersions($probe);
foreach ($supported as $version) {
if (!$version->isModern()) {
return null;
}
}
$named = self::namedVersions($probe);
return Error::forInvalidRequest(\sprintf('Server supports none of the protocol versions this client speaks (it advertises %s).', [] === $named ? 'none' : implode(', ', $named)), $probe->id);
}
$advertised = $probe->result['supportedVersions'] ?? null;
if (!\is_array($advertised)) {
return null;
}
$current = $this->envelope->protocolVersion();
$chosen = null;
foreach (ProtocolVersion::modernVersions() as $version) {
if (\in_array($version->value, $advertised, true) && (null === $chosen || $version->isAtLeast($chosen))) {
$chosen = $version;
}
}
if (\in_array($current->value, $advertised, true)) {
$chosen = $current;
}
if (null === $chosen) {
return null;
}
if ($chosen !== $current) {
$this->logger->warning('Server does not speak the configured revision; continuing on one it advertises.', [
'configured' => $current->value,
'using' => $chosen->value,
]);
$this->envelope = $this->envelope->withProtocolVersion($chosen);
}
$this->readDiscovery($probe->result);
return $this->settleModern($probe);
}
/**
* @param Response<array<string, mixed>> $probe
*
* @return Response<array<string, mixed>>
*/
private function settleModern(Response $probe): Response
{
\assert(null !== $this->envelope);
$this->state->setProtocolVersion($this->envelope->protocolVersion());
$this->state->setInitialized(true);
$this->logger->info('Connection settled on the modern era', [
'protocolVersion' => $this->envelope->protocolVersion()->value,
]);
return $probe;
}
/**
* @return Response<array<string, mixed>>|Error
*/
private function handshake(ProtocolVersion $offered, Configuration $config): Response|Error
{
$request = new InitializeRequest(
$offered->value,
$config->capabilities,
$config->clientInfo,
);
$response = $this->request($request, $config->initTimeout);
if ($response instanceof Error && Error::UNSUPPORTED_PROTOCOL_VERSION === $response->code) {
$named = self::namedVersions($response);
return new Error($response->id, $response->code, \sprintf(
'Server does not speak protocol version %s; it supports %s.',
$offered->value,
[] === $named ? 'none it named' : implode(', ', $named),
), $response->data);
}
if ($response instanceof Response) {
$initResult = InitializeResult::fromArray($response->result);
// A counter-offer this SDK cannot speak leaves nothing to fall back to,
// so the handshake fails rather than continuing on a revision neither
// side agrees on.
$negotiated = $initResult->protocolVersion;
if (null === $negotiated || $negotiated->isModern()) {
// fromArray() above already rejected a missing or non-string revision.
$counterOffer = (string) $response->result['protocolVersion'];
return Error::forInvalidParams(\sprintf(
'Server responded with unsupported protocol version "%s". Supported versions: %s.',
$counterOffer,
implode(', ', array_map(
static fn (ProtocolVersion $v): string => $v->value,
ProtocolVersion::handshakeVersions(),
)),
), $response->id);
}
$this->state->setProtocolVersion($negotiated);
$this->state->setServerInfo($initResult->serverInfo);
$this->state->setInstructions($initResult->instructions);
$this->state->setServerCapabilities($initResult->capabilities);
$this->state->setInitialized(true);
$this->sendNotification(new InitializedNotification());
$this->logger->info('Initialization complete', [
'server' => $initResult->serverInfo->name,
'protocolVersion' => $negotiated->value,
]);
}
return $response;
}
/**
* Read defensively: nothing beyond the revisions is load-bearing.
*
* @param array<string, mixed> $result
*/
private function readDiscovery(array $result): void
{
// Identity is wire vocabulary in this revision, so it rides in `_meta`
// rather than the result body. The top level is read as a fallback
// because that is where the handshake era put it.
$meta = \is_array($result['_meta'] ?? null) ? $result['_meta'] : [];
$serverInfo = $meta[RequestMeta::SERVER_INFO] ?? $result['serverInfo'] ?? null;
if (\is_array($serverInfo)) {
try {
$this->state->setServerInfo(Implementation::fromArray($serverInfo));
} catch (\Throwable $e) {
$this->logger->debug('Ignoring unreadable serverInfo from "server/discover".', ['exception' => $e]);
}
}
if (\is_string($result['instructions'] ?? null)) {
$this->state->setInstructions($result['instructions']);
}
if (\is_array($result['capabilities'] ?? null)) {
$this->state->setServerCapabilities(ServerCapabilities::fromArray($result['capabilities']));
}
}
/**
* The newest modern revision a refusal names that this client speaks.
*/
private static function mutualModern(Error $error): ?ProtocolVersion
{
if (Error::UNSUPPORTED_PROTOCOL_VERSION !== $error->code) {
return null;
}
$mutual = null;
foreach (self::supportedVersions($error) as $version) {
if ($version->isModern() && (null === $mutual || $version->isAtLeast($mutual))) {
$mutual = $version;
}
}
return $mutual;
}
/**
* @return list<ProtocolVersion>
*/
private static function supportedVersions(Error $error): array
{
return array_values(array_filter(array_map(ProtocolVersion::tryFrom(...), self::namedVersions($error))));
}
/**
* @return list<string>
*/
private static function namedVersions(Error $error): array
{
$supported = \is_array($error->data) && \is_array($error->data['supported'] ?? null) ? $error->data['supported'] : [];
return array_values(array_filter($supported, is_string(...)));
}
/**
* @param Response<array<string, mixed>>|Error $probe
*/
private static function describe(Response|Error $probe): string
{
return $probe instanceof Error
? \sprintf('"server/discover" was answered with error %d (%s)', $probe->code, $probe->message)
: '"server/discover" was answered without a modern revision';
}
/**
* Send a request to the server and wait for response.
*
* If a response is immediately available (sync HTTP), returns it.
* Otherwise, suspends the Fiber and waits for the transport to resume it.
*
* In the modern era this is also where the two loops that re-send live:
* answering a server's request for input (SEP-2322), and retrying under a
* revision the server accepts (SEP-2575). Both re-send the same call, so
* they belong together and above the single exchange.
*
* @param Request $request The request to send
* @param int $timeout The timeout in seconds
* @param bool $withProgress Whether to attach a progress token to the request
*
* @return Response<array<string, mixed>>|Error
*/
public function request(Request $request, int $timeout, bool $withProgress = false, ?CancellationTokenInterface $cancellation = null, ?float $callTimeout = null): Response|Error
{
$deadline = null !== $callTimeout ? microtime(true) + $callTimeout : null;
$payload = $request->withId(0)->jsonSerialize();
unset($payload['id']);
$this->progressToken = $withProgress ? 'prog-'.++$this->progressTokens : null;
if (null !== $this->progressToken) {
$payload = self::withMeta($payload, ['progressToken' => $this->progressToken]);
}
try {
if (null === $this->envelope) {
return $this->exchange($payload, $timeout, $cancellation, $deadline);
}
for ($attempt = 0; $attempt < self::MAX_ROUND_TRIPS; ++$attempt) {
$response = $this->exchange($payload, $timeout, $cancellation, $deadline);
if ($response instanceof Error) {
$retry = $this->withAcceptedVersion($response);
if (null === $retry) {
return $response;
}
continue;
}
$asked = InputRequestResolver::asked($response->result);
if (null === $asked) {
return $response;
}
// A fresh `inputResponses`/`requestState` pair every round, never
// merged with the last: the answers belong to the ask that just
// arrived, and carrying an old one forward is how state leaks
// between rounds.
//
// Cast to object: inputResponses is a JSON object keyed by the
// server's ids, but a PHP array with no entries or with sequential
// numeric-string keys encodes as a JSON array instead.
$payload['params'] = [
...($payload['params'] ?? []),
'inputResponses' => (object) $this->inputRequests->resolve($asked),
];
unset($payload['params']['requestState']);
// Echoed byte-for-byte, and only when the server sent one: the
// value is the server's to read, and inventing or reshaping it
// would break whatever it encodes.
if (\is_string($response->result['requestState'] ?? null)) {
$payload['params']['requestState'] = $response->result['requestState'];
}
$this->logger->debug('Retrying request with resolved input', [
'method' => $payload['method'] ?? null,
'round' => $attempt + 1,
]);
}
return Error::forInternalError(\sprintf('Server asked for input more than %d times without completing the request.', self::MAX_ROUND_TRIPS));
} finally {
$this->progressToken = null;
}
}
/**
* Switches the offered revision when the server refuses the current one,
* or null when there is nothing to retry with.
*
* @param Error $error the server's refusal
*/
private function withAcceptedVersion(Error $error): ?ProtocolVersion
{
if (Error::UNSUPPORTED_PROTOCOL_VERSION !== $error->code || null === $this->envelope) {
return null;
}
$data = \is_array($error->data) ? $error->data : [];
$supported = \is_array($data['supported'] ?? null) ? $data['supported'] : [];
$current = $this->envelope->protocolVersion();
foreach ($supported as $candidate) {
$version = \is_string($candidate) ? ProtocolVersion::tryFrom($candidate) : null;
// Only another modern revision is reachable from here: falling back
// to a handshake era one would mean opening a connection this
// transport already decided it was not going to open.
if (null === $version || !$version->isModern() || $version === $current) {
continue;
}
$this->logger->info('Server rejected the offered protocol revision, retrying with one it supports.', [
'offered' => $current->value,
'retrying' => $version->value,
]);
$this->envelope = $this->envelope->withProtocolVersion($version);
$this->state->setProtocolVersion($version);
return $version;
}
return null;
}
/**
* One request on the wire: assign an id, send, and wait for its answer.
*
* A retry gets a new id, because the previous one is spent — the server has
* already answered it, and reusing it would make the two indistinguishable.
*
* @param array<string, mixed> $payload
*
* @return Response<array<string, mixed>>|Error
*/
private function exchange(array $payload, int $timeout, ?CancellationTokenInterface $cancellation = null, ?float $deadline = null): Response|Error
{
if (null !== ($interruption = self::interruption($cancellation, $deadline))) {
throw $interruption;
}
$requestId = $this->state->nextRequestId();
$payload['id'] = $requestId;
$this->state->addPendingRequest($requestId, $timeout);
try {
$this->send($payload, 'request');
// send() can block and leave a JSON answer already buffered: drop it
// and report the interruption instead of a success nobody awaits.
if (null !== ($interruption = self::interruption($cancellation, $deadline))) {
throw $interruption;
}
$immediate = $this->state->consumeResponse($requestId);
if (null !== $immediate) {
$this->logger->debug('Received immediate response', ['id' => $requestId]);
return $immediate;
}
$this->logger->debug('Suspending fiber for response', ['id' => $requestId]);
$response = \Fiber::suspend([
'type' => 'await_response',
'request_id' => $requestId,
'timeout' => $timeout,
'cancellation' => $cancellation,
'deadline' => $deadline,
]);
// A transport may resume with a buffered reply before checking interruption.
if (null !== ($interruption = self::interruption($cancellation, $deadline))) {
throw $interruption;
}
return $response;
} catch (RequestCancelledException|TimeoutException $e) {
$this->state->consumeResponse($requestId);
$this->notifyCancellation($requestId, $e->getMessage());
throw $e;
} finally {
// Only the response path clears it, so a request that timed out or
// whose send() threw would stay pending and fail every later one.
$this->state->removePendingRequest($requestId);
}
}
/**
* The interruption an in-flight request is subject to, if any. Checked on
* both sides of a send and after the transport resumes a suspended request.
*
* @phpstan-impure
*/
private static function interruption(?CancellationTokenInterface $cancellation, ?float $deadline): RequestCancelledException|TimeoutException|null
{
if ($cancellation?->isCancellationRequested()) {
return new RequestCancelledException('The client cancelled the request.');
}
if (null !== $deadline && microtime(true) >= $deadline) {
return new TimeoutException('The request deadline expired.');
}
return null;
}
/**
* Tell the server an abandoned request's result will go unused. Only stdio and
* handshake-era HTTP need it: a modern connection signals by closing the
* response stream. Best effort — a send failure is logged, not raised.
*/
private function notifyCancellation(int $requestId, string $reason): void
{
if ($this->transport instanceof HttpTransport && true === $this->state->getProtocolVersion()?->isModern()) {
return;
}
try {
$this->sendNotification(new CancelledNotification($requestId, $reason));
} catch (\Throwable $notificationError) {
$this->logger->warning('Could not send request cancellation notification.', ['request_id' => $requestId, 'exception' => $notificationError]);
}
}
/**
* Send a notification to the server (fire and forget).
*/
public function sendNotification(Notification $notification): void
{
$this->send($notification->jsonSerialize(), 'notification');
}
/**
* Encode and hand a message to the transport, stamping the per-request
* envelope on the way out when the revision calls for one.
*
* @param array<string, mixed> $payload
*
* @throws InvalidArgumentException if the payload cannot be encoded as JSON, e.g. invalid UTF-8
*/
private function send(array $payload, string $kind): void
{
if (null !== $this->envelope) {
$payload = $this->envelope->stamp($payload);
}
$this->logger->debug('Sending '.$kind, [
'id' => $payload['id'] ?? null,
'method' => $payload['method'] ?? null,
]);
try {
$encoded = json_encode($payload, \JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
throw new InvalidArgumentException(\sprintf('Could not encode the "%s" %s as JSON: %s', $payload['method'] ?? 'unknown', $kind, $e->getMessage()), previous: $e);
}
$this->transport?->send($encoded);
}
/**
* @param array<string, mixed> $payload
* @param array<string, mixed> $meta
*
* @return array<string, mixed>
*/
private static function withMeta(array $payload, array $meta): array
{
$params = \is_array($payload['params'] ?? null) ? $payload['params'] : [];
$existing = \is_array($params['_meta'] ?? null) ? $params['_meta'] : [];
$params['_meta'] = [...$existing, ...$meta];
$payload['params'] = $params;
return $payload;
}
/**
* Send a response back to the server (for server-initiated requests).
*
* @param Response<mixed>|Error $response
*/
private function sendResponse(Response|Error $response): void
{
$this->logger->debug('Sending response', ['id' => $response->getId()]);
try {
$encoded = json_encode($response, \JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
// The server still awaits an answer, so it gets an error instead.
$this->logger->warning('Could not encode the response', ['id' => $response->getId(), 'exception' => $e]);
$encoded = json_encode(Error::forInternalError('Could not encode the response', $response->getId()), \JSON_THROW_ON_ERROR);
}
$this->transport?->send($encoded);
}
/**
* Process an incoming message from the server.
*
* Routes to appropriate handler based on message type.
*/
public function processMessage(string $input): void
{
$this->logger->debug('Received message', ['input' => $input]);
try {
$message = $this->messageFactory->create($input);
} catch (\JsonException|InvalidInputMessageException $e) {
$this->logger->warning('Failed to parse message', ['exception' => $e]);
return;
}
if ($message instanceof Response || $message instanceof Error) {
$this->handleResponse($message);
} elseif ($message instanceof Request) {
$this->handleRequest($message);
} elseif ($message instanceof Notification) {
$this->handleNotification($message);
}
}
/**
* Handle a response from the server.
*
* This stores it in session. The transport will pick it up and resume the Fiber.
*
* @param Response<mixed>|Error $response
*/
private function handleResponse(Response|Error $response): void
{
$requestId = $response->getId();
if (null === $requestId) {
$this->logger->warning('Received an id-less error response; cannot correlate it to a request.', ['response' => $response->jsonSerialize()]);
return;
}
if (!\array_key_exists($requestId, $this->state->getPendingRequests())) {
$this->logger->debug('Ignoring response for a request that is no longer pending.', ['id' => $requestId]);
return;
}
$this->logger->debug('Handling response', ['id' => $requestId]);
$this->state->storeResponse($requestId, $response->jsonSerialize());
}
/**
* Handle a request from the server (e.g., sampling request).
*/
private function handleRequest(Request $request): void
{
$method = $request::getMethod();
$this->logger->debug('Received server request', [
'method' => $method,
'id' => $request->getId(),
]);
foreach ($this->requestHandlers as $handler) {
if ($handler->supports($request)) {
try {
$response = $handler->handle($request);
} catch (\Throwable $e) {
$this->logger->error('Unexpected error while handling request', [
'method' => $method,
'exception' => $e,
]);
$response = Error::forInternalError(
\sprintf('Unexpected error while handling "%s" request', $method),
$request->getId()
);
}
$this->sendResponse($response);
return;
}
}
$error = Error::forMethodNotFound(
\sprintf('Client does not handle "%s" requests.', $method),
$request->getId()
);
$this->sendResponse($error);
}
/**
* Handle a notification from the server.
*/
private function handleNotification(Notification $notification): void
{
$method = $notification::getMethod();
$this->logger->debug('Received server notification', [
'method' => $method,
]);
foreach ($this->notificationHandlers as $handler) {
if ($handler->supports($notification)) {
try {
$handler->handle($notification);
} catch (\Throwable $e) {
$this->logger->warning('Notification handler failed', ['exception' => $e]);
}
return;
}
}
}
public function getState(): ClientStateInterface
{
return $this->state;
}
}