Repository navigation
Expand file tree
/
Copy pathClient.php
More file actions
430 lines (360 loc) · 15.4 KB
/
Copy pathClient.php
File metadata and controls
430 lines (360 loc) · 15.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
<?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;
use Mcp\Client\Builder;
use Mcp\Client\CancellationTokenInterface;
use Mcp\Client\Configuration;
use Mcp\Client\Protocol;
use Mcp\Client\Transport\TransportInterface;
use Mcp\Exception\ConnectionException;
use Mcp\Exception\InvalidArgumentException;
use Mcp\Exception\RequestCancelledException;
use Mcp\Exception\RequestException;
use Mcp\Exception\RuntimeException;
use Mcp\Schema\Enum\LoggingLevel;
use Mcp\Schema\Enum\ProtocolVersion;
use Mcp\Schema\Implementation;
use Mcp\Schema\JsonRpc\Error;
use Mcp\Schema\JsonRpc\Request;
use Mcp\Schema\JsonRpc\Response;
use Mcp\Schema\Notification\RootsListChangedNotification;
use Mcp\Schema\PromptReference;
use Mcp\Schema\Request\CallToolRequest;
use Mcp\Schema\Request\CompletionCompleteRequest;
use Mcp\Schema\Request\DiscoverRequest;
use Mcp\Schema\Request\GetPromptRequest;
use Mcp\Schema\Request\ListPromptsRequest;
use Mcp\Schema\Request\ListResourcesRequest;
use Mcp\Schema\Request\ListResourceTemplatesRequest;
use Mcp\Schema\Request\ListToolsRequest;
use Mcp\Schema\Request\PingRequest;
use Mcp\Schema\Request\ReadResourceRequest;
use Mcp\Schema\Request\SetLogLevelRequest;
use Mcp\Schema\ResourceReference;
use Mcp\Schema\Result\CallToolResult;
use Mcp\Schema\Result\CompletionCompleteResult;
use Mcp\Schema\Result\GetPromptResult;
use Mcp\Schema\Result\ListPromptsResult;
use Mcp\Schema\Result\ListResourcesResult;
use Mcp\Schema\Result\ListResourceTemplatesResult;
use Mcp\Schema\Result\ListToolsResult;
use Mcp\Schema\Result\ReadResourceResult;
use Mcp\Schema\ServerCapabilities;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
/**
* Main MCP Client facade.
*
* Provides a synchronous API for communicating with MCP servers.
* All blocking operations are delegated to the transport.
*
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
*/
class Client
{
private const RETRY_BASE_DELAY_MS = 100;
private ?TransportInterface $transport = null;
public function __construct(
private readonly Protocol $protocol,
private readonly Configuration $config,
private readonly LoggerInterface $logger = new NullLogger(),
) {
}
/**
* Create a new client builder for fluent configuration.
*/
public static function builder(): Builder
{
return new Builder();
}
/**
* Connect to an MCP server using the provided transport.
*
* A failed attempt is closed and retried, see {@see Builder::setMaxRetries()}.
*
* @throws ConnectionException If connection or initialization fails on every attempt
*/
public function connect(TransportInterface $transport): void
{
$this->transport = $transport;
$this->protocol->connect($transport, $this->config);
$maxAttempts = $this->config->maxRetries + 1;
for ($attempt = 1; $attempt <= $maxAttempts; ++$attempt) {
try {
$transport->connect();
$this->logger->info('Client connected and initialized', ['attempt' => $attempt]);
return;
} catch (ConnectionException $e) {
// initialize() flags the session before sending the initialized
// notification, so a failure in between leaves the flag set.
$this->protocol->getState()->setInitialized(false);
$transport->close();
if ($attempt === $maxAttempts) {
throw $e;
}
$this->logger->warning('Connection attempt failed, retrying', [
'attempt' => $attempt,
'max_attempts' => $maxAttempts,
'exception' => $e,
]);
usleep($attempt * self::RETRY_BASE_DELAY_MS * 1000);
}
}
}
/**
* Check if connected and initialized.
*/
public function isConnected(): bool
{
return null !== $this->transport && $this->protocol->getState()->isInitialized();
}
/**
* Get server information from initialization.
*/
public function getServerInfo(): ?Implementation
{
return $this->protocol->getState()->getServerInfo();
}
/**
* Get server instructions.
*/
public function getInstructions(): ?string
{
return $this->protocol->getState()->getInstructions();
}
/**
* Capabilities the server declared: during the handshake, or in its
* `server/discover` result from 2026-07-28 on.
*
* Null until a server declared them, e.g. before connecting or when a
* 2026-07-28 server does not answer `server/discover`.
*/
public function getServerCapabilities(): ?ServerCapabilities
{
return $this->protocol->getState()->getServerCapabilities();
}
/**
* Protocol revision negotiated during the handshake.
*
* This is the version the server answered with, which is not necessarily the
* one configured on the builder: a server that cannot speak the requested
* revision counter-offers one it supports. Null until the handshake completed.
*/
public function getProtocolVersion(): ?ProtocolVersion
{
return $this->protocol->getState()->getProtocolVersion();
}
/**
* Check that the server is reachable: `ping`, or `server/discover` on the modern era, which removed it.
*/
public function ping(): void
{
$request = $this->protocol->isModern() ? new DiscoverRequest() : new PingRequest();
$this->sendRequest($request);
}
/**
* List available tools from the server.
*/
public function listTools(?string $cursor = null): ListToolsResult
{
$request = new ListToolsRequest($cursor);
$response = $this->sendRequest($request);
$result = $response->result;
// Filtered before parsing, because parsing is where a malformed
// `x-mcp-header` annotation throws. One broken definition must cost the
// caller that tool, not the whole listing (SEP-2243).
if (\is_array($result['tools'] ?? null)) {
$result['tools'] = $this->protocol->getToolCatalog()->record($result['tools']);
}
return ListToolsResult::fromArray($result);
}
/**
* Call a tool on the server.
*
* Cancellation and deadlines are cooperative: on HTTP, blocking I/O has to
* return before the transport can observe the interruption. An answer that
* arrived for an interrupted call is discarded rather than returned.
*
* @param string $name Tool name
* @param array<string, mixed> $arguments Tool arguments
* @param (callable(float $progress, ?float $total, ?string $message): void)|null $onProgress
* Optional callback for progress updates
* @param CancellationTokenInterface|null $cancellation Non-blocking cancellation signal
* @param float|null $timeoutSeconds Finite positive timeout replacing the default for this call
*
* @throws RequestCancelledException When cancellation is observed
* @throws Exception\TimeoutException When the per-call deadline is observed to have expired
* @throws RequestException|ConnectionException|InvalidArgumentException|RuntimeException
*/
public function callTool(string $name, array $arguments = [], ?callable $onProgress = null, ?CancellationTokenInterface $cancellation = null, ?float $timeoutSeconds = null): CallToolResult
{
if ($cancellation?->isCancellationRequested()) {
throw new RequestCancelledException('The client cancelled the request.');
}
if (null !== $timeoutSeconds && (!is_finite($timeoutSeconds) || $timeoutSeconds <= 0)) {
throw new InvalidArgumentException('The per-call timeout must be a finite positive number of seconds.');
}
$catalog = $this->protocol->getToolCatalog();
// A tool the listing showed to be malformed is refused here rather than
// sent: the client cannot produce the headers its annotations demand,
// so the call could only go out misdescribed (SEP-2243).
if ($catalog->isRejected($name)) {
throw new RuntimeException(\sprintf('Refusing to call tool "%s": its "x-mcp-header" annotations are invalid (%s).', $name, $catalog->reasonFor($name)));
}
$request = new CallToolRequest($name, $arguments);
$response = $this->sendRequest($request, $onProgress, $cancellation, $timeoutSeconds);
return CallToolResult::fromArray($response->result);
}
/**
* List available resources from the server.
*/
public function listResources(?string $cursor = null): ListResourcesResult
{
$request = new ListResourcesRequest($cursor);
$response = $this->sendRequest($request);
return ListResourcesResult::fromArray($response->result);
}
/**
* List available resource templates from the server.
*/
public function listResourceTemplates(?string $cursor = null): ListResourceTemplatesResult
{
$request = new ListResourceTemplatesRequest($cursor);
$response = $this->sendRequest($request);
return ListResourceTemplatesResult::fromArray($response->result);
}
/**
* Read a resource by URI.
*
* @param string $uri The resource URI
* @param (callable(float $progress, ?float $total, ?string $message): void)|null $onProgress
* Optional callback for progress updates
*/
public function readResource(string $uri, ?callable $onProgress = null): ReadResourceResult
{
if ('' === $uri) {
throw new InvalidArgumentException('Resource URI must not be empty.');
}
$request = new ReadResourceRequest($uri);
$response = $this->sendRequest($request, $onProgress);
return ReadResourceResult::fromArray($response->result);
}
/**
* List available prompts from the server.
*/
public function listPrompts(?string $cursor = null): ListPromptsResult
{
$request = new ListPromptsRequest($cursor);
$response = $this->sendRequest($request);
return ListPromptsResult::fromArray($response->result);
}
/**
* Get a prompt from the server.
*
* @param string $name Prompt name
* @param array<string, string> $arguments Prompt arguments
* @param (callable(float $progress, ?float $total, ?string $message): void)|null $onProgress
* Optional callback for progress updates
*/
public function getPrompt(string $name, array $arguments = [], ?callable $onProgress = null): GetPromptResult
{
$request = new GetPromptRequest($name, $arguments);
$response = $this->sendRequest($request, $onProgress);
return GetPromptResult::fromArray($response->result);
}
/**
* Request completion suggestions for a prompt or resource argument.
*
* @param PromptReference|ResourceReference $ref The prompt or resource reference
* @param array{name: string, value: string} $argument The argument to complete
*/
public function complete(PromptReference|ResourceReference $ref, array $argument): CompletionCompleteResult
{
$request = new CompletionCompleteRequest($ref, $argument);
$response = $this->sendRequest($request);
return CompletionCompleteResult::fromArray($response->result);
}
/**
* Set the minimum logging level for server log messages; on the modern era it rides on every following request.
*/
public function setLoggingLevel(LoggingLevel $level): void
{
if (!$this->isConnected()) {
throw new ConnectionException('Client is not connected. Call connect() first.');
}
if ($this->protocol->isModern()) {
$this->protocol->setLogLevel($level);
return;
}
$request = new SetLogLevelRequest($level);
$this->sendRequest($request);
}
/**
* Notify the server that the client's list of roots has changed.
*
* The server should react by requesting an updated list via roots/list.
*
* @throws RuntimeException if the client did not advertise the `roots.listChanged` capability
* @throws ConnectionException if the client is not connected
*/
public function sendRootsListChanged(): void
{
if (true !== $this->config->capabilities->rootsListChanged) {
throw new RuntimeException('Cannot send a "roots/list_changed" notification without advertising the "roots.listChanged" capability. Build the client with new ClientCapabilities(roots: true, rootsListChanged: true).');
}
if (!$this->isConnected()) {
throw new ConnectionException('Client is not connected. Call connect() first.');
}
if ($this->protocol->isModern()) {
$this->logger->debug('Not sending "notifications/roots/list_changed": the connection is on the modern era, which removed roots.');
return;
}
$this->protocol->sendNotification(new RootsListChangedNotification());
}
/**
* Send a request to the server and wait for response.
*
* @param (callable(float $progress, ?float $total, ?string $message): void)|null $onProgress
*
* @return Response<mixed>
*
* @throws RequestException|ConnectionException
*/
private function sendRequest(Request $request, ?callable $onProgress = null, ?CancellationTokenInterface $cancellation = null, ?float $timeoutSeconds = null): Response
{
$transport = $this->transport;
if (null === $transport || !$this->protocol->getState()->isInitialized()) {
throw new ConnectionException('Client is not connected. Call connect() first.');
}
$withProgress = null !== $onProgress;
$fiber = new \Fiber(fn () => $this->protocol->request($request, $this->config->requestTimeout, $withProgress, $cancellation, $timeoutSeconds));
$this->protocol->setProgressCallback($onProgress);
try {
$response = $transport->runRequest($fiber);
} finally {
$this->protocol->setProgressCallback(null);
}
if ($response instanceof Error) {
throw RequestException::fromError($response);
}
return $response;
}
/**
* Disconnect from the server.
*/
public function disconnect(): void
{
if (null !== $this->transport) {
$this->transport->close();
$this->transport = null;
$this->logger->info('Client disconnected');
}
}
}