-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathClient.php
More file actions
1246 lines (1024 loc) · 46.4 KB
/
Client.php
File metadata and controls
1246 lines (1024 loc) · 46.4 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
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
namespace PhpMcp\Client;
use PhpMcp\Client\Cache\DefinitionCache;
use PhpMcp\Client\Contracts\MessageIdGeneratorInterface;
use PhpMcp\Client\Contracts\TransportInterface;
use PhpMcp\Client\Enum\ConnectionStatus;
use PhpMcp\Client\Exception\ConfigurationException;
use PhpMcp\Client\Exception\ConnectionException;
use PhpMcp\Client\Exception\McpClientException;
use PhpMcp\Client\Exception\ProtocolException;
use PhpMcp\Client\Exception\RequestException;
use PhpMcp\Client\Exception\TimeoutException;
use PhpMcp\Client\Exception\TransportException;
use PhpMcp\Client\Exception\UnsupportedCapabilityException;
use PhpMcp\Client\Factory\TransportFactory;
use PhpMcp\Client\JsonRpc\Message;
use PhpMcp\Client\JsonRpc\Notification;
use PhpMcp\Client\JsonRpc\Params\InitializeParams;
use PhpMcp\Client\JsonRpc\Request;
use PhpMcp\Client\JsonRpc\Response;
use PhpMcp\Client\JsonRpc\Results\CallToolResult;
use PhpMcp\Client\JsonRpc\Results\GetPromptResult;
use PhpMcp\Client\JsonRpc\Results\InitializeResult;
use PhpMcp\Client\JsonRpc\Results\ListPromptsResult;
use PhpMcp\Client\JsonRpc\Results\ListResourcesResult;
use PhpMcp\Client\JsonRpc\Results\ListResourceTemplatesResult;
use PhpMcp\Client\JsonRpc\Results\ListToolsResult;
use PhpMcp\Client\JsonRpc\Results\ReadResourceResult;
use PhpMcp\Client\Model\Capabilities;
use PhpMcp\Client\Model\Definitions\PromptDefinition;
use PhpMcp\Client\Model\Definitions\ResourceDefinition;
use PhpMcp\Client\Model\Definitions\ResourceTemplateDefinition;
use PhpMcp\Client\Model\Definitions\ToolDefinition;
use PhpMcp\Client\Transport\Stdio\StdioClientTransport;
use Psr\Log\LoggerInterface;
use React\EventLoop\LoopInterface;
use React\Promise\Deferred;
use React\Promise\PromiseInterface;
use Throwable;
use function React\Async\await;
use function React\Promise\reject;
use function React\Promise\resolve;
/**
* Main user-facing class for interacting with a single MCP server.
* Provides both synchronous-blocking and asynchronous-promise based methods.
*
* An explicit initialize() or initializeAsync() call is required before making requests.
*/
class Client
{
protected readonly LoggerInterface $logger;
protected readonly LoopInterface $loop;
protected readonly MessageIdGeneratorInterface $idGenerator;
protected readonly TransportFactory $transportFactory;
protected readonly ?DefinitionCache $definitionCache;
protected ConnectionStatus $status = ConnectionStatus::Disconnected;
protected ?TransportInterface $transport = null;
protected ?PromiseInterface $connectPromise = null;
protected ?Deferred $connectRequestDeferred = null;
/** @var array<string|int, Deferred> Request ID => Deferred mapping */
protected array $pendingRequests = [];
protected ?string $serverName = null;
protected ?string $serverVersion = null;
protected ?Capabilities $serverCapabilities = null;
protected ?string $negotiatedProtocolVersion = null;
protected string $preferredProtocolVersion = '2024-11-05';
/**
* @internal Use ClientBuilder::make()->...->build() instead.
*/
public function __construct(
public readonly ServerConfig $serverConfig,
public readonly ClientConfig $clientConfig,
?TransportFactory $transportFactory = null,
) {
$this->logger = $this->clientConfig->logger;
$this->loop = $this->clientConfig->loop;
$this->idGenerator = $this->clientConfig->idGenerator;
$this->transportFactory = $transportFactory ?? new TransportFactory($this->clientConfig);
$this->definitionCache = $this->clientConfig->cache
? new DefinitionCache($this->clientConfig->cache, $this->clientConfig->definitionCacheTtl, $this->logger)
: null;
}
public static function make(): ClientBuilder
{
return ClientBuilder::make();
}
// --- Getters for Connection State ---
public function getStatus(): ConnectionStatus
{
return $this->status;
}
public function getServerName(): ?string
{
return $this->serverName;
}
public function getServerVersion(): ?string
{
return $this->serverVersion;
}
public function getNegotiatedCapabilities(): ?Capabilities
{
return $this->serverCapabilities;
}
public function getNegotiatedProtocolVersion(): ?string
{
return $this->negotiatedProtocolVersion;
}
public function getConnectionStatus(): ConnectionStatus
{
return $this->status;
}
public function isReady(): bool
{
return $this->status === ConnectionStatus::Ready;
}
/** For advanced users needing async or event loop access */
public function getLoop(): LoopInterface
{
return $this->loop;
}
// --- Connection / Initialization Methods ---
/**
* Initiates the asynchronous connection and handshake process.
* Returns a promise that resolves with $this when ready, or rejects on error.
* This is the underlying async operation for initialize().
*/
public function initializeAsync(): PromiseInterface
{
if ($this->connectPromise !== null) {
return $this->connectPromise;
}
if ($this->status !== ConnectionStatus::Disconnected && $this->status !== ConnectionStatus::Closed && $this->status !== ConnectionStatus::Error) {
if ($this->status === ConnectionStatus::Ready) {
return resolve($this);
}
return reject(new ConnectionException("Cannot initialize, client is in unexpected status: {$this->status->value}"));
}
$this->logger->info("Initializing connection to server '{$this->getServerName()}'...", ['transport' => $this->serverConfig->transport->value]);
$this->connectRequestDeferred = new Deferred(function ($_, $reject) {
$this->logger->info("Initialization attempt for '{$this->getServerName()}' cancelled.");
$this->handleConnectionFailure(new ConnectionException('Initialization attempt cancelled.'), false);
if (isset($this->transport) && ($this->status === ConnectionStatus::Connecting || $this->status === ConnectionStatus::Handshaking)) {
$this->transport->close();
}
});
$this->status = ConnectionStatus::Connecting;
try {
$this->transport = $this->transportFactory->create($this->serverConfig);
} catch (Throwable $e) {
$this->handleConnectionFailure(new ConfigurationException("Failed to create transport: {$e->getMessage()}", 0, $e));
return reject($e);
}
$this->transport->on('message', $this->handleTransportMessage(...));
$this->transport->on('error', $this->handleTransportError(...));
$this->transport->on('close', $this->handleTransportClose(...));
if ($this->transport instanceof StdioClientTransport) {
$this->transport->on('stderr', function (string $data) {
$this->logger->warning("Server '{$this->getServerName()}' STDERR: ".trim($data));
});
}
// --- Define the connection and handshake sequence ---
$this->transport->connect()->then(
function () {
if ($this->status !== ConnectionStatus::Connecting) {
throw new ConnectionException("Internal state error: Status was {$this->status->value} after transport connect resolved.");
}
$this->logger->info("Transport connected for '{$this->getServerName()}', initiating handshake...");
$this->status = ConnectionStatus::Handshaking;
return $this->performHandshake();
}
)->then(
function () {
// Check status again in case of rapid failure during handshake
if ($this->status !== ConnectionStatus::Handshaking) {
throw new ConnectionException("Connection status changed unexpectedly ({$this->status->value}) during handshake.");
}
$this->status = ConnectionStatus::Ready;
$this->logger->info("Server '{$this->getServerName()}' connection ready.", [
'protocol' => $this->negotiatedProtocolVersion,
'server' => $this->serverName,
'version' => $this->serverVersion,
]);
return $this;
}
)->catch(
function (Throwable $error) {
$this->logger->error("Connection/Handshake failed for '{$this->getServerName()}': {$error->getMessage()}", ['exception' => $error]);
$this->handleConnectionFailure($error);
}
)->then(
fn ($connection) => $this->connectRequestDeferred?->resolve($connection),
fn (Throwable $error) => $this->connectRequestDeferred?->reject($error)
)->finally(function () {
$this->connectRequestDeferred = null;
});
$this->connectPromise = $this->connectRequestDeferred->promise();
return $this->connectPromise;
}
/**
* Connects and performs handshake, blocking until ready or failed.
*
* @throws ConnectionException|TimeoutException|ConfigurationException|Throwable
*/
public function initialize(): self
{
if ($this->status === ConnectionStatus::Ready) {
return $this;
}
if ($this->connectPromise !== null) {
$this->logger->debug("Waiting for existing async initialization to complete for '{$this->getServerName()}'...");
}
$promise = $this->connectPromise ?? $this->initializeAsync();
try {
await($promise);
if ($this->status !== ConnectionStatus::Ready) {
throw new ConnectionException("Initialization completed but client status is not Ready ({$this->status->value}).");
}
return $this;
} catch (Throwable $e) {
if ($this->status !== ConnectionStatus::Error && $this->status !== ConnectionStatus::Closed) {
$this->logger->warning("Forcing error status after initialize() await failed for '{$this->getServerName()}'.");
$this->handleConnectionFailure($e, false);
}
throw $e;
}
}
/**
* Disconnects the client asynchronously.
*/
public function disconnectAsync(): PromiseInterface
{
if (! isset($this->transport)) {
$this->status = ConnectionStatus::Closed;
return resolve(null);
}
if ($this->status === ConnectionStatus::Closing || $this->status === ConnectionStatus::Closed) {
return resolve(null);
}
if ($this->connectRequestDeferred) {
$this->connectRequestDeferred->reject(new ConnectionException('Disconnect called during initialization.'));
}
$this->logger->info("Disconnecting from server '{$this->getServerName()}'...");
$this->status = ConnectionStatus::Closing;
$deferred = new Deferred;
$this->rejectPendingRequests(new ConnectionException('Connection closing.'));
$listener = function ($reason = null) use ($deferred) {
$this->logger->info("Transport closed for server '{$this->getServerName()}'.", ['reason' => $reason]);
if ($this->status !== ConnectionStatus::Closed) {
$this->status = ConnectionStatus::Closed;
$this->cleanupTransport();
$deferred->resolve(null);
}
};
$this->transport->once('close', $listener);
$this->transport->close();
$closeTimeout = 5.0;
$operationName = "Disconnect from '{$this->getServerName()}'";
return Utils::timeout($deferred->promise(), $closeTimeout, $this->loop, $operationName)
->catch(function (Throwable $error) {
if ($this->status !== ConnectionStatus::Closed && $this->status !== ConnectionStatus::Error) {
$this->handleConnectionFailure($error, false);
}
throw $error;
});
}
/**
* Disconnects the client, blocking until complete or timeout.
*/
public function disconnect(): void
{
if ($this->status === ConnectionStatus::Disconnected || $this->status === ConnectionStatus::Closed) {
return;
}
$promise = $this->disconnectAsync();
try {
await($promise);
} catch (Throwable $e) {
$this->logger->error("Error during disconnect for '{$this->getServerName()}': {$e->getMessage()}", ['exception' => $e]);
if ($this->status !== ConnectionStatus::Closed && $this->status !== ConnectionStatus::Error) {
$this->handleConnectionFailure($e, false);
}
} finally {
if ($this->status !== ConnectionStatus::Closed && $this->status !== ConnectionStatus::Error) {
$this->status = ConnectionStatus::Closed;
$this->cleanupTransport();
}
}
}
// --- Synchronous Facade Methods ---
/**
* Synchronous ping method.
*
* @throws ConnectionException|TimeoutException|RequestException|ProtocolException|McpClientException|Throwable
*/
public function ping(): void
{
$this->ensureReady();
$request = new Request(
id: $this->idGenerator->generate(),
method: 'ping',
params: []
);
// Send and wait
$promise = $this->sendAsyncInternal($request);
$response = await($promise);
if ($response->isError()) {
throw RequestException::fromError('Ping failed: Server Error', $response->error);
}
// Success is lack of error
}
/**
* Synchronously lists all tools available on the server.
*
* @param bool $useCache Whether to use cached tool definitions.
* @return array<ToolDefinition>
*
* @throws ConnectionException|TimeoutException|RequestException|ProtocolException|McpClientException|Throwable
*/
public function listTools(bool $useCache = true): array
{
$this->ensureReady();
if ($useCache && $this->definitionCache && ($cached = $this->definitionCache->getTools($this->getServerName())) !== null) {
return $cached;
}
$request = new Request($this->idGenerator->generate(), 'tools/list');
$promise = $this->sendAsyncInternal($request);
$response = await($promise);
if ($response->isError()) {
throw RequestException::fromError('Failed to list tools', $response->error);
}
if (! is_array($response->result)) {
throw new ProtocolException('Invalid result format for tools/list.');
}
$listResult = ListToolsResult::fromArray($response->result);
if ($this->definitionCache && $listResult->nextCursor === null) {
$this->definitionCache->setTools($this->getServerName(), $listResult->tools);
}
return $listResult->tools;
}
/**
* Synchronously calls a tool on the server.
*
* @param string $toolName The name of the tool to call.
* @param array $arguments The arguments to pass to the tool.
*
* @throws ConnectionException|TimeoutException|RequestException|ProtocolException|McpClientException|Throwable
*/
public function callTool(string $toolName, array $arguments = []): CallToolResult
{
$this->ensureReady();
$request = new Request(
$this->idGenerator->generate(),
'tools/call',
['name' => $toolName, 'arguments' => empty($arguments) ? new \stdClass : $arguments]
);
$promise = $this->sendAsyncInternal($request);
$response = await($promise);
if ($response->isError()) {
throw RequestException::fromError("Failed to call tool '{$toolName}'", $response->error);
}
if (! is_array($response->result)) {
throw new ProtocolException('Invalid result format for tools/call.');
}
return CallToolResult::fromArray($response->result);
}
/**
* Synchronously lists all resources available on the server.
*
* @param bool $useCache Whether to use cached resource definitions.
* @return array<ResourceDefinition>
*
* @throws ConnectionException|TimeoutException|RequestException|ProtocolException|McpClientException|Throwable
*/
public function listResources(bool $useCache = true): array
{
$this->ensureReady();
if ($useCache && $this->definitionCache && ($cached = $this->definitionCache->getResources($this->getServerName())) !== null) {
$this->clientConfig->logger->debug("Cache hit for listResources on '{$this->getServerName()}'.");
return $cached;
}
$this->clientConfig->logger->debug("Cache miss for listResources on '{$this->getServerName()}'.");
$request = new Request($this->idGenerator->generate(), 'resources/list');
$promise = $this->sendAsyncInternal($request);
$response = await($promise);
if ($response->isError()) {
throw RequestException::fromError('Failed to list resources', $response->error);
}
if (! is_array($response->result)) {
throw new ProtocolException('Invalid result format for resources/list.');
}
$listResult = ListResourcesResult::fromArray($response->result);
if ($this->definitionCache && $listResult->nextCursor === null) {
$this->definitionCache->setResources($this->getServerName(), $listResult->resources);
}
return $listResult->resources;
}
/**
* Synchronously lists all resource templates available on the server.
*
* @param bool $useCache Whether to use cached resource template definitions.
* @return array<ResourceTemplateDefinition>
*
* @throws ConnectionException|TimeoutException|RequestException|ProtocolException|McpClientException|Throwable
*/
public function listResourceTemplates(bool $useCache = true): array
{
$this->ensureReady();
if ($useCache && $this->definitionCache && ($cached = $this->definitionCache->getResourceTemplates($this->getServerName())) !== null) {
$this->clientConfig->logger->debug("Cache hit for listResourceTemplates on '{$this->getServerName()}'.");
return $cached;
}
$this->clientConfig->logger->debug("Cache miss for listResourceTemplates on '{$this->getServerName()}'.");
$request = new Request($this->idGenerator->generate(), 'resources/templates/list');
$promise = $this->sendAsyncInternal($request);
$response = await($promise);
if ($response->isError()) {
throw RequestException::fromError('Failed to list resource templates', $response->error);
}
if (! is_array($response->result)) {
throw new ProtocolException('Invalid result format for resources/templates/list.');
}
$listResult = ListResourceTemplatesResult::fromArray($response->result);
if ($this->definitionCache && $listResult->nextCursor === null) {
$this->definitionCache->setResourceTemplates($this->getServerName(), $listResult->resourceTemplates);
}
return $listResult->resourceTemplates;
}
/**
* Synchronously lists all prompts available on the server.
*
* @param bool $useCache Whether to use cached prompt definitions.
* @return array<PromptDefinition>
*
* @throws ConnectionException|TimeoutException|RequestException|ProtocolException|McpClientException|Throwable
*/
public function listPrompts(bool $useCache = true): array
{
$this->ensureReady();
if ($useCache && $this->definitionCache && ($cached = $this->definitionCache->getPrompts($this->getServerName())) !== null) {
$this->clientConfig->logger->debug("Cache hit for listPrompts on '{$this->getServerName()}'.");
return $cached;
}
$this->clientConfig->logger->debug("Cache miss for listPrompts on '{$this->getServerName()}'.");
$request = new Request($this->idGenerator->generate(), 'prompts/list');
$promise = $this->sendAsyncInternal($request);
$response = await($promise);
if ($response->isError()) {
throw RequestException::fromError('Failed to list prompts', $response->error);
}
if (! is_array($response->result)) {
throw new ProtocolException('Invalid result format for prompts/list.');
}
$listResult = ListPromptsResult::fromArray($response->result);
if ($this->definitionCache && $listResult->nextCursor === null) {
$this->definitionCache->setPrompts($this->getServerName(), $listResult->prompts);
}
return $listResult->prompts;
}
/**
* Synchronously reads a resource from the server.
*
* @param string $uri The URI of the resource to read.
*
* @throws ConnectionException|TimeoutException|RequestException|ProtocolException|McpClientException|Throwable
*/
public function readResource(string $uri): ReadResourceResult
{
$this->ensureReady();
$request = new Request(
id: $this->idGenerator->generate(),
method: 'resources/read',
params: ['uri' => $uri]
);
$promise = $this->sendAsyncInternal($request);
$response = await($promise);
if ($response->isError()) {
throw RequestException::fromError("Failed to read resource '{$uri}'", $response->error);
}
if (! is_array($response->result)) {
throw new ProtocolException('Invalid result format for resources/read.');
}
return ReadResourceResult::fromArray($response->result);
}
/**
* Synchronously gets a prompt from the server.
*
* @param string $promptName The name of the prompt to get.
* @param array<string, mixed> $arguments The arguments to pass to the prompt.
*
* @throws ConnectionException|TimeoutException|RequestException|ProtocolException|McpClientException|Throwable
*/
public function getPrompt(string $promptName, array $arguments = []): GetPromptResult
{
$this->ensureReady();
$request = new Request(
id: $this->idGenerator->generate(),
method: 'prompts/get',
params: [
'name' => $promptName,
'arguments' => empty($arguments) ? new \stdClass : $arguments,
]
);
$promise = $this->sendAsyncInternal($request);
$response = await($promise);
if ($response->isError()) {
throw RequestException::fromError("Failed to get prompt '{$promptName}'", $response->error);
}
if (! is_array($response->result)) {
throw new ProtocolException('Invalid result format for prompts/get.');
}
return GetPromptResult::fromArray($response->result);
}
/**
* Synchronously subscribes to a resource on the server.
*
* @param string $uri The URI of the resource to subscribe to.
*
* @throws ConnectionException|TimeoutException|RequestException|UnsupportedCapabilityException|McpClientException|Throwable
*/
public function subscribeResource(string $uri): void
{
$this->ensureReady();
if (! $this->getNegotiatedCapabilities()?->serverSupportsResourceSubscription()) {
throw new UnsupportedCapabilityException("Server '{$this->getServerName()}' does not support resource subscription.");
}
$request = new Request(
id: $this->idGenerator->generate(),
method: 'resources/subscribe',
params: ['uri' => $uri]
);
$promise = $this->sendAsyncInternal($request);
$response = await($promise);
if ($response->isError()) {
throw RequestException::fromError("Failed to subscribe to resource '{$uri}'", $response->error);
}
// Success is empty result or specific ack? Assume empty for now.
}
/**
* Synchronously unsubscribes from a resource on the server.
*
* @param string $uri The URI of the resource to unsubscribe from.
*
* @throws ConnectionException|TimeoutException|RequestException|McpClientException|Throwable
*/
public function unsubscribeResource(string $uri): void
{
$this->ensureReady();
$request = new Request(
id: $this->idGenerator->generate(),
method: 'resources/unsubscribe',
params: ['uri' => $uri]
);
$promise = $this->sendAsyncInternal($request);
$response = await($promise);
if ($response->isError()) {
throw RequestException::fromError("Failed to unsubscribe from resource '{$uri}'", $response->error);
}
}
/**
* Synchronously sets the log level for the server.
*
* @param string $level The log level to set.
*
* @throws ConnectionException|TimeoutException|RequestException|UnsupportedCapabilityException|McpClientException|Throwable
*/
public function setLogLevel(string $level): void
{
$this->ensureReady();
if (! $this->getNegotiatedCapabilities()?->serverSupportsLogging()) {
throw new UnsupportedCapabilityException("Server '{$this->getServerName()}' does not support logging.");
}
$request = new Request(
id: $this->idGenerator->generate(),
method: 'logging/setLevel',
params: ['level' => strtolower($level)]
);
$promise = $this->sendAsyncInternal($request);
$response = await($promise);
if ($response->isError()) {
throw RequestException::fromError("Failed to set log level to '{$level}'", $response->error);
}
}
// --- Asynchronous API Methods ---
/**
* Asynchronously pings the server.
*
* @return PromiseInterface<void>
*/
public function pingAsync(): PromiseInterface
{
return $this->sendRequestAndParseResultAsync('ping', [], null);
}
/**
* Asynchronously lists all tools available on the server.
*
* @return PromiseInterface<array<ToolDefinition>>
*/
public function listToolsAsync(): PromiseInterface
{
return $this->sendRequestAndParseResultAsync('tools/list', [], ListToolsResult::class)
->then(fn (ListToolsResult $result) => $result->tools);
}
/**
* Asynchronously calls a tool on the server.
*
* @param string $toolName The name of the tool to call.
* @param array<string, mixed> $arguments The arguments to pass to the tool.
* @return PromiseInterface<CallToolResult>
*/
public function callToolAsync(string $toolName, array $arguments = []): PromiseInterface
{
$params = ['name' => $toolName, 'arguments' => empty($arguments) ? new \stdClass : $arguments];
return $this->sendRequestAndParseResultAsync('tools/call', $params, CallToolResult::class);
}
/**
* Asynchronously lists all resources available on the server.
*
* @return PromiseInterface<array<ResourceDefinition>>
*/
public function listResourcesAsync(): PromiseInterface
{
return $this->sendRequestAndParseResultAsync('resources/list', [], ListResourcesResult::class)
->then(fn (ListResourcesResult $result) => $result->resources);
}
/**
* Asynchronously lists all resource templates available on the server.
*
* @return PromiseInterface<array<ResourceTemplateDefinition>>
*/
public function listResourceTemplatesAsync(): PromiseInterface
{
return $this->sendRequestAndParseResultAsync('resources/templates/list', [], ListResourceTemplatesResult::class)
->then(fn (ListResourceTemplatesResult $result) => $result->resourceTemplates);
}
/**
* Asynchronously lists all prompts available on the server.
*
* @return PromiseInterface<array<PromptDefinition>>
*/
public function listPromptsAsync(): PromiseInterface
{
return $this->sendRequestAndParseResultAsync('prompts/list', [], ListPromptsResult::class)
->then(fn (ListPromptsResult $result) => $result->prompts);
}
/**
* Asynchronously reads a resource from the server.
*
* @param string $uri The URI of the resource to read.
* @return PromiseInterface<ReadResourceResult>
*/
public function readResourceAsync(string $uri): PromiseInterface
{
$params = ['uri' => $uri];
return $this->sendRequestAndParseResultAsync('resources/read', $params, ReadResourceResult::class);
}
/**
* Asynchronously gets a prompt from the server.
*
* @param string $promptName The name of the prompt to get.
* @param array<string, mixed> $arguments The arguments to pass to the prompt.
* @return PromiseInterface<GetPromptResult>
*/
public function getPromptAsync(string $promptName, array $arguments = []): PromiseInterface
{
$params = ['name' => $promptName, 'arguments' => empty($arguments) ? new \stdClass : $arguments];
return $this->sendRequestAndParseResultAsync('prompts/get', $params, GetPromptResult::class);
}
/**
* Asynchronously subscribes to a resource on the server.
*
* @param string $uri The URI of the resource to subscribe to.
* @return PromiseInterface<void>
*/
public function subscribeResourceAsync(string $uri): PromiseInterface
{
if (! $this->getNegotiatedCapabilities()?->serverSupportsResourceSubscription()) {
return reject(new UnsupportedCapabilityException("Server '{$this->getServerName()}' does not support resource subscription."));
}
return $this->sendRequestAndParseResultAsync('resources/subscribe', ['uri' => $uri], null);
}
/**
* Asynchronously unsubscribes from a resource on the server.
*
* @param string $uri The URI of the resource to unsubscribe from.
* @return PromiseInterface<void>
*/
public function unsubscribeResourceAsync(string $uri): PromiseInterface
{
return $this->sendRequestAndParseResultAsync('resources/unsubscribe', ['uri' => $uri], null);
}
/**
* Asynchronously sets the log level for the server.
*
* @param string $level The log level to set.
* @return PromiseInterface<void>
*/
public function setLogLevelAsync(string $level): PromiseInterface
{
if (! $this->getNegotiatedCapabilities()?->serverSupportsLogging()) {
return reject(new UnsupportedCapabilityException("Server '{$this->getServerName()}' does not support logging."));
}
return $this->sendRequestAndParseResultAsync('logging/setLevel', ['level' => strtolower($level)], null);
}
// --- Internal Helper Methods ---
/** Checks if client is ready, throws if not */
protected function ensureReady(): void
{
if ($this->status !== ConnectionStatus::Ready) {
// Attempt to initialize implicitly? Or just throw? Let's throw for clarity.
// Call $this->initialize() here if implicit connection is desired.
throw new ConnectionException('Client not initialized. Call initialize() first.');
}
}
/**
* Performs the MCP initialize handshake. Returns a promise.
*
* @return PromiseInterface<void>
*/
private function performHandshake(): PromiseInterface
{
$initParams = new InitializeParams(
clientName: $this->clientConfig->name,
clientVersion: $this->clientConfig->version,
protocolVersion: $this->preferredProtocolVersion,
capabilities: $this->clientConfig->capabilities,
);
$request = new Request(
id: $this->clientConfig->idGenerator->generate(),
method: 'initialize',
params: $initParams->toArray()
);
return $this->sendAsyncInternal($request)->then(
function (Response $response) {
if ($response->isError()) {
throw RequestException::fromError('Initialize failed', $response->error);
}
if (! is_array($response->result)) {
throw new ConnectionException('Invalid initialize result format.');
}
$initResult = InitializeResult::fromArray($response->result);
// Version Negotiation
$serverVersion = $initResult->protocolVersion;
if ($serverVersion !== $this->preferredProtocolVersion) {
$this->logger->warning("Version mismatch: Server returned {$serverVersion}, expected {$this->preferredProtocolVersion}.");
if (! is_string($serverVersion) || empty($serverVersion)) {
throw new ConnectionException('Server returned invalid protocol version.');
}
}
$this->negotiatedProtocolVersion = $serverVersion;
$this->serverName = $initResult->serverName;
$this->serverVersion = $initResult->serverVersion;
$this->serverCapabilities = $initResult->capabilities;
$this->logger->debug("Sending 'initialized' notification to '{$this->getServerName()}'.");
return $this->transport->send(new Notification('notifications/initialized'));
}
);
}
/**
* Internal async request sender
*
* Allows sending requests even if the client is not ready. Callers must check the status
* and ensure the client is ready before calling this method.
*
* @return PromiseInterface<Response>
*/
protected function sendAsyncInternal(Request $request): PromiseInterface
{
if ($this->status === ConnectionStatus::Closed || $this->status === ConnectionStatus::Closing || $this->status === ConnectionStatus::Error) {
return reject(new ConnectionException("Cannot send request, connection is closed or in error state ({$this->status->value})."));
}
if (! isset($this->transport)) {
return reject(new ConnectionException('Cannot send request, transport not available.'));
}
if (! isset($request->id)) {
return reject(new McpClientException('Cannot use sendAsyncInternal for notifications.'));
}
$deferred = new Deferred(function ($_, $reject) use ($request) {
if (isset($this->pendingRequests[$request->id])) {
unset($this->pendingRequests[$request->id]);
$reject(new McpClientException("Request '{$request->method}' (ID: {$request->id}) cancelled by user."));
}
});
$this->pendingRequests[$request->id] = $deferred;
$this->transport->send($request)
->catch(
function (Throwable $e) use ($deferred, $request) {
if (isset($this->pendingRequests[$request->id])) {
$sendFailMsg = "Failed to send request '{$request->method}' (ID: {$request->id}): {$e->getMessage()}";
$this->logger->error($sendFailMsg, ['exception' => $e]);
unset($this->pendingRequests[$request->id]);
$deferred->reject(new TransportException($sendFailMsg, 0, $e));
}
}
);
$timeout = $this->serverConfig->timeout;
$operationName = "Request '{$request->method}' (ID: {$request->id})";
return Utils::timeout($deferred->promise(), $timeout, $this->loop, $operationName)
->catch(function (Throwable $e) use ($request) {
if (isset($this->pendingRequests[$request->id])) {
unset($this->pendingRequests[$request->id]);
}
throw $e;
});
}
/**
* Helper for async methods that parses the result
*
* @param string $method The method to call.
* @param array<string, mixed> $params The parameters to pass to the method.
* @param string|null $resultClass The class of the result to parse.
* @return PromiseInterface<mixed>
*/
private function sendRequestAndParseResultAsync(string $method, array $params, ?string $resultClass): PromiseInterface
{
if ($this->status !== ConnectionStatus::Ready) {
return reject(new ConnectionException("Client not ready (Status: {$this->status->value})."));
}