| 1: | <?php |
| 2: | |
| 3: | declare(strict_types=1); |
| 4: | |
| 5: | |
| 6: | |
| 7: | |
| 8: | |
| 9: | |
| 10: | |
| 11: | |
| 12: | |
| 13: | |
| 14: | namespace Nexus\Mcp\Client; |
| 15: | |
| 16: | use Amp\CancelledException; |
| 17: | use Amp\DeferredFuture; |
| 18: | use Nexus\Mcp\Client\Dispatch\ProgressListenerRegistry; |
| 19: | use Nexus\Mcp\Client\Dispatch\RequestDeadline; |
| 20: | use Nexus\Mcp\Client\Exception\ClientAlreadyConnectedException; |
| 21: | use Nexus\Mcp\Client\Exception\ClientNotConnectedException; |
| 22: | use Nexus\Mcp\Client\Exception\ServerCapabilityNotSupportedException; |
| 23: | use Nexus\Mcp\Client\Subscription\OpenSubscription; |
| 24: | use Nexus\Mcp\Client\Subscription\SubscriptionRegistry; |
| 25: | use Nexus\Mcp\Client\Subscription\SubscriptionStream; |
| 26: | use Nexus\Mcp\Core\Dispatch\MessageDispatcherInterface; |
| 27: | use Nexus\Mcp\Core\Dispatch\PendingOutboundRequests; |
| 28: | use Nexus\Mcp\Core\Exception\OutboundRequestFailedException; |
| 29: | use Nexus\Mcp\Core\Exception\RemoteCallFailedException; |
| 30: | use Nexus\Mcp\Core\Exception\RequestTimeoutException; |
| 31: | use Nexus\Mcp\Core\Exception\SupervisionExhaustedException; |
| 32: | use Nexus\Mcp\Core\Exception\TransportAlreadyClosedException; |
| 33: | use Nexus\Mcp\Core\Http\ParameterHeaderBinding; |
| 34: | use Nexus\Mcp\Core\Http\ParameterHeaders; |
| 35: | use Nexus\Mcp\Core\Http\ParameterHeaderScanner; |
| 36: | use Nexus\Mcp\Core\Schema\ClientCapabilities; |
| 37: | use Nexus\Mcp\Core\Schema\Cursor; |
| 38: | use Nexus\Mcp\Core\Schema\Enum\ProtocolErrorCode; |
| 39: | use Nexus\Mcp\Core\Schema\Error\UnsupportedProtocolVersionError; |
| 40: | use Nexus\Mcp\Core\Schema\Implementation; |
| 41: | use Nexus\Mcp\Core\Schema\JsonRpc\JsonRpcNotification; |
| 42: | use Nexus\Mcp\Core\Schema\JsonRpc\JsonRpcRequest; |
| 43: | use Nexus\Mcp\Core\Schema\JsonRpc\JsonRpcResultResponse; |
| 44: | use Nexus\Mcp\Core\Schema\MetaObject\RequestMetaObject; |
| 45: | use Nexus\Mcp\Core\Schema\Notification\CancelledNotification; |
| 46: | use Nexus\Mcp\Core\Schema\NotificationParams\CancelledNotificationParams; |
| 47: | use Nexus\Mcp\Core\Schema\ProgressToken; |
| 48: | use Nexus\Mcp\Core\Schema\Prompt\PromptReference; |
| 49: | use Nexus\Mcp\Core\Schema\ProtocolVersion; |
| 50: | use Nexus\Mcp\Core\Schema\Request\CallToolRequest; |
| 51: | use Nexus\Mcp\Core\Schema\Request\CompleteRequest; |
| 52: | use Nexus\Mcp\Core\Schema\Request\DiscoverRequest; |
| 53: | use Nexus\Mcp\Core\Schema\Request\GetPromptRequest; |
| 54: | use Nexus\Mcp\Core\Schema\Request\ListPromptsRequest; |
| 55: | use Nexus\Mcp\Core\Schema\Request\ListResourcesRequest; |
| 56: | use Nexus\Mcp\Core\Schema\Request\ListResourceTemplatesRequest; |
| 57: | use Nexus\Mcp\Core\Schema\Request\ListToolsRequest; |
| 58: | use Nexus\Mcp\Core\Schema\Request\ReadResourceRequest; |
| 59: | use Nexus\Mcp\Core\Schema\Request\SubscriptionsListenRequest; |
| 60: | use Nexus\Mcp\Core\Schema\RequestId; |
| 61: | use Nexus\Mcp\Core\Schema\RequestParams; |
| 62: | use Nexus\Mcp\Core\Schema\RequestParams\CallToolRequestParams; |
| 63: | use Nexus\Mcp\Core\Schema\RequestParams\CompleteRequestParams; |
| 64: | use Nexus\Mcp\Core\Schema\RequestParams\EmptyRequestParams; |
| 65: | use Nexus\Mcp\Core\Schema\RequestParams\GetPromptRequestParams; |
| 66: | use Nexus\Mcp\Core\Schema\RequestParams\InputResponseRequestParams; |
| 67: | use Nexus\Mcp\Core\Schema\RequestParams\PaginatedRequestParams; |
| 68: | use Nexus\Mcp\Core\Schema\RequestParams\ReadResourceRequestParams; |
| 69: | use Nexus\Mcp\Core\Schema\RequestParams\SubscriptionsListenRequestParams; |
| 70: | use Nexus\Mcp\Core\Schema\RequestParamsInterface; |
| 71: | use Nexus\Mcp\Core\Schema\Resource\ResourceTemplateReference; |
| 72: | use Nexus\Mcp\Core\Schema\Result\CallToolResult; |
| 73: | use Nexus\Mcp\Core\Schema\Result\CompleteResult; |
| 74: | use Nexus\Mcp\Core\Schema\Result\DiscoverResult; |
| 75: | use Nexus\Mcp\Core\Schema\Result\GetPromptResult; |
| 76: | use Nexus\Mcp\Core\Schema\Result\InputRequiredResult; |
| 77: | use Nexus\Mcp\Core\Schema\Result\InputResponse; |
| 78: | use Nexus\Mcp\Core\Schema\Result\ListPromptsResult; |
| 79: | use Nexus\Mcp\Core\Schema\Result\ListResourcesResult; |
| 80: | use Nexus\Mcp\Core\Schema\Result\ListResourceTemplatesResult; |
| 81: | use Nexus\Mcp\Core\Schema\Result\ListToolsResult; |
| 82: | use Nexus\Mcp\Core\Schema\Result\ReadResourceResult; |
| 83: | use Nexus\Mcp\Core\Schema\Result\SubscriptionsListenResult; |
| 84: | use Nexus\Mcp\Core\Schema\ResultResponse\CallToolResultResponse; |
| 85: | use Nexus\Mcp\Core\Schema\ResultResponse\CompleteResultResponse; |
| 86: | use Nexus\Mcp\Core\Schema\ResultResponse\DiscoverResultResponse; |
| 87: | use Nexus\Mcp\Core\Schema\ResultResponse\GetPromptResultResponse; |
| 88: | use Nexus\Mcp\Core\Schema\ResultResponse\ListPromptsResultResponse; |
| 89: | use Nexus\Mcp\Core\Schema\ResultResponse\ListResourcesResultResponse; |
| 90: | use Nexus\Mcp\Core\Schema\ResultResponse\ListResourceTemplatesResultResponse; |
| 91: | use Nexus\Mcp\Core\Schema\ResultResponse\ListToolsResultResponse; |
| 92: | use Nexus\Mcp\Core\Schema\ResultResponse\ReadResourceResultResponse; |
| 93: | use Nexus\Mcp\Core\Schema\ResultResponse\SubscriptionsListenResultResponse; |
| 94: | use Nexus\Mcp\Core\Schema\ServerCapabilities; |
| 95: | use Nexus\Mcp\Core\Schema\SubscriptionFilter; |
| 96: | use Nexus\Mcp\Core\Transport\AbortableTransportInterface; |
| 97: | use Nexus\Mcp\Core\Transport\ParameterHeaderMirroringInterface; |
| 98: | use Nexus\Mcp\Core\Transport\ReceiveContext; |
| 99: | use Nexus\Mcp\Core\Transport\ReconnectingTransportInterface; |
| 100: | use Nexus\Mcp\Core\Transport\SendContext; |
| 101: | use Nexus\Mcp\Core\Transport\TransportInterface; |
| 102: | use Psr\Log\LoggerInterface; |
| 103: | use Psr\Log\NullLogger; |
| 104: | use Revolt\EventLoop; |
| 105: | |
| 106: | |
| 107: | |
| 108: | |
| 109: | |
| 110: | final class Client |
| 111: | { |
| 112: | |
| 113: | |
| 114: | |
| 115: | |
| 116: | public const float DEFAULT_REQUEST_TIMEOUT = 60.0; |
| 117: | |
| 118: | |
| 119: | |
| 120: | |
| 121: | public const float DEFAULT_MAX_REQUEST_TIMEOUT = 600.0; |
| 122: | |
| 123: | |
| 124: | |
| 125: | |
| 126: | |
| 127: | |
| 128: | |
| 129: | private const array RETRYABLE_REQUESTS = [ |
| 130: | CompleteRequest::class, |
| 131: | DiscoverRequest::class, |
| 132: | GetPromptRequest::class, |
| 133: | ListPromptsRequest::class, |
| 134: | ListResourcesRequest::class, |
| 135: | ListResourceTemplatesRequest::class, |
| 136: | ListToolsRequest::class, |
| 137: | ReadResourceRequest::class, |
| 138: | ]; |
| 139: | |
| 140: | private ?TransportInterface $transport = null; |
| 141: | private ?Implementation $serverInfo = null; |
| 142: | private ?ServerCapabilities $serverCapabilities = null; |
| 143: | |
| 144: | |
| 145: | |
| 146: | |
| 147: | |
| 148: | |
| 149: | |
| 150: | private array $toolHeaderBindings = []; |
| 151: | |
| 152: | |
| 153: | |
| 154: | |
| 155: | |
| 156: | |
| 157: | |
| 158: | public function __construct( |
| 159: | private readonly Implementation $clientInfo, |
| 160: | private readonly ClientCapabilities $clientCapabilities, |
| 161: | private readonly MessageDispatcherInterface $dispatcher, |
| 162: | private readonly PendingOutboundRequests $outboundRequests, |
| 163: | private readonly \Closure $requestIdFactory, |
| 164: | private readonly \Closure $progressTokenFactory, |
| 165: | private readonly ProtocolVersion $protocolVersion = new ProtocolVersion(version: ProtocolVersion::LATEST_VERSION), |
| 166: | private readonly ProgressListenerRegistry $progressListeners = new ProgressListenerRegistry(), |
| 167: | private readonly SubscriptionRegistry $subscriptions = new SubscriptionRegistry(), |
| 168: | private readonly LoggerInterface $logger = new NullLogger(), |
| 169: | private readonly ?float $requestTimeout = self::DEFAULT_REQUEST_TIMEOUT, |
| 170: | private readonly ?float $maxRequestTimeout = self::DEFAULT_MAX_REQUEST_TIMEOUT, |
| 171: | private readonly bool $retryLostRequests = false, |
| 172: | ) { |
| 173: | } |
| 174: | |
| 175: | |
| 176: | |
| 177: | |
| 178: | |
| 179: | |
| 180: | public function connect(TransportInterface $transport): void |
| 181: | { |
| 182: | if (null !== $this->transport) { |
| 183: | |
| 184: | throw new ClientAlreadyConnectedException(); |
| 185: | } |
| 186: | |
| 187: | $this->logger->info('Starting MCP client.'); |
| 188: | |
| 189: | $this->transport = $transport; |
| 190: | |
| 191: | $transport->onMessage(function (array $envelope, ReceiveContext $context) use ($transport): void { |
| 192: | $this->dispatcher->dispatch($envelope, $transport, $context); |
| 193: | }); |
| 194: | $transport->onError(function (\Throwable $e): void { |
| 195: | if ($e instanceof OutboundRequestFailedException) { |
| 196: | |
| 197: | |
| 198: | $this->outboundRequests->reject($e->requestId, $e); |
| 199: | } |
| 200: | |
| 201: | if ($e instanceof SupervisionExhaustedException) { |
| 202: | |
| 203: | |
| 204: | |
| 205: | $this->settleSubscriptions($e); |
| 206: | $this->outboundRequests->cancelAll($e); |
| 207: | } |
| 208: | |
| 209: | $this->logger->error('Transport error.', ['exception' => $e]); |
| 210: | }); |
| 211: | $transport->onDrain(function (): void { |
| 212: | $this->dispatcher->flushPending(); |
| 213: | }); |
| 214: | $transport->onClose(function () use ($transport): void { |
| 215: | $error = new TransportAlreadyClosedException(operation: 'await-response'); |
| 216: | |
| 217: | |
| 218: | $this->outboundRequests->cancelUnretained($error); |
| 219: | |
| 220: | |
| 221: | |
| 222: | EventLoop::queue(function () use ($transport, $error): void { |
| 223: | if ($transport !== $this->transport) { |
| 224: | |
| 225: | |
| 226: | return; |
| 227: | } |
| 228: | |
| 229: | if ($transport instanceof ReconnectingTransportInterface && $transport->isReconnecting()) { |
| 230: | return; |
| 231: | } |
| 232: | |
| 233: | |
| 234: | |
| 235: | |
| 236: | $this->outboundRequests->cancelAll($error); |
| 237: | }); |
| 238: | }); |
| 239: | |
| 240: | if ($transport instanceof ReconnectingTransportInterface) { |
| 241: | $transport->onReconnect(function () use ($transport): void { |
| 242: | foreach ($this->outboundRequests->collectRetained() as $retained) { |
| 243: | $request = $retained['request']; |
| 244: | |
| 245: | try { |
| 246: | $transport->send($request, $retained['context']); |
| 247: | } catch (\Throwable $e) { |
| 248: | if ($transport->isReconnecting()) { |
| 249: | |
| 250: | |
| 251: | $this->logger->warning( |
| 252: | 'Could not send request {id} again to the replacement peer.', |
| 253: | ['id' => $request->id->id, 'exception' => $e], |
| 254: | ); |
| 255: | |
| 256: | continue; |
| 257: | } |
| 258: | |
| 259: | |
| 260: | $this->outboundRequests->reject($request->id, $e); |
| 261: | } |
| 262: | } |
| 263: | |
| 264: | foreach ($this->subscriptions->all() as $subscription) { |
| 265: | try { |
| 266: | $this->openStream($subscription, $transport); |
| 267: | } catch (\Throwable $e) { |
| 268: | |
| 269: | $this->logger->error( |
| 270: | 'Could not re-open subscription {id} against the replacement peer.', |
| 271: | ['id' => $subscription->subscriptionId->id, 'exception' => $e], |
| 272: | ); |
| 273: | } |
| 274: | } |
| 275: | }); |
| 276: | } |
| 277: | |
| 278: | $transport->start(); |
| 279: | } |
| 280: | |
| 281: | |
| 282: | |
| 283: | |
| 284: | |
| 285: | public function disconnect(): void |
| 286: | { |
| 287: | $transport = $this->transport; |
| 288: | $this->transport = null; |
| 289: | |
| 290: | |
| 291: | |
| 292: | $this->toolHeaderBindings = []; |
| 293: | |
| 294: | |
| 295: | |
| 296: | $error = new TransportAlreadyClosedException(operation: 'await-response'); |
| 297: | $this->settleSubscriptions($error); |
| 298: | $this->outboundRequests->cancelAll($error); |
| 299: | |
| 300: | $transport?->close(); |
| 301: | } |
| 302: | |
| 303: | |
| 304: | |
| 305: | |
| 306: | |
| 307: | |
| 308: | public function getServerInfo(): ?Implementation |
| 309: | { |
| 310: | return $this->serverInfo; |
| 311: | } |
| 312: | |
| 313: | |
| 314: | |
| 315: | |
| 316: | |
| 317: | public function getServerCapabilities(): ?ServerCapabilities |
| 318: | { |
| 319: | return $this->serverCapabilities; |
| 320: | } |
| 321: | |
| 322: | |
| 323: | |
| 324: | |
| 325: | |
| 326: | |
| 327: | |
| 328: | |
| 329: | |
| 330: | public function discover(): DiscoverResult |
| 331: | { |
| 332: | $result = $this->sendRequest( |
| 333: | new DiscoverRequest(id: $this->mintRequestId(), params: new EmptyRequestParams(meta: $this->stampMeta())), |
| 334: | DiscoverResultResponse::class, |
| 335: | )->result; |
| 336: | |
| 337: | $this->serverInfo = $result->meta->serverInfo; |
| 338: | $this->serverCapabilities = $result->capabilities; |
| 339: | |
| 340: | return $result; |
| 341: | } |
| 342: | |
| 343: | |
| 344: | |
| 345: | |
| 346: | |
| 347: | |
| 348: | |
| 349: | |
| 350: | |
| 351: | |
| 352: | public function listen(SubscriptionFilter $notifications, \Closure $onNotification): SubscriptionStream |
| 353: | { |
| 354: | $transport = $this->transport ?? throw new ClientNotConnectedException(); |
| 355: | |
| 356: | $id = $this->mintRequestId(); |
| 357: | |
| 358: | |
| 359: | $outcome = new DeferredFuture(); |
| 360: | |
| 361: | |
| 362: | |
| 363: | $future = $outcome->getFuture(); |
| 364: | $future->ignore(); |
| 365: | |
| 366: | $subscription = new OpenSubscription($id, $notifications, $onNotification, $outcome); |
| 367: | |
| 368: | |
| 369: | |
| 370: | $this->openStream($subscription, $transport); |
| 371: | $this->subscriptions->register($subscription); |
| 372: | |
| 373: | return new SubscriptionStream($id, $future, function () use ($id, $transport): void { |
| 374: | $this->subscriptions->forget($id); |
| 375: | |
| 376: | if (! $this->outboundRequests->forget($id)) { |
| 377: | |
| 378: | return; |
| 379: | } |
| 380: | |
| 381: | self::abortExchange($transport, $id); |
| 382: | |
| 383: | try { |
| 384: | $transport->send(new CancelledNotification( |
| 385: | params: new CancelledNotificationParams(requestId: $id, reason: 'The subscription was closed.'), |
| 386: | )); |
| 387: | } catch (\Throwable $e) { |
| 388: | |
| 389: | $this->logger->debug( |
| 390: | 'Could not tell the server that subscription {id} was closed.', |
| 391: | ['id' => $id->id, 'exception' => $e], |
| 392: | ); |
| 393: | } |
| 394: | }); |
| 395: | } |
| 396: | |
| 397: | |
| 398: | |
| 399: | |
| 400: | |
| 401: | |
| 402: | |
| 403: | public function listTools(?Cursor $cursor = null): ListToolsResult |
| 404: | { |
| 405: | $result = $this->sendRequest( |
| 406: | new ListToolsRequest( |
| 407: | id: $this->mintRequestId(), |
| 408: | params: new PaginatedRequestParams(meta: $this->stampMeta(), cursor: $cursor), |
| 409: | ), |
| 410: | ListToolsResultResponse::class, |
| 411: | )->result; |
| 412: | |
| 413: | return $this->transport instanceof ParameterHeaderMirroringInterface |
| 414: | ? $this->admitMirrorableTools($result) |
| 415: | : $result; |
| 416: | } |
| 417: | |
| 418: | |
| 419: | |
| 420: | |
| 421: | |
| 422: | |
| 423: | |
| 424: | public function listResources(?Cursor $cursor = null): ListResourcesResult |
| 425: | { |
| 426: | return $this->sendRequest( |
| 427: | new ListResourcesRequest( |
| 428: | id: $this->mintRequestId(), |
| 429: | params: new PaginatedRequestParams(meta: $this->stampMeta(), cursor: $cursor), |
| 430: | ), |
| 431: | ListResourcesResultResponse::class, |
| 432: | )->result; |
| 433: | } |
| 434: | |
| 435: | |
| 436: | |
| 437: | |
| 438: | |
| 439: | |
| 440: | |
| 441: | public function listResourceTemplates(?Cursor $cursor = null): ListResourceTemplatesResult |
| 442: | { |
| 443: | return $this->sendRequest( |
| 444: | new ListResourceTemplatesRequest( |
| 445: | id: $this->mintRequestId(), |
| 446: | params: new PaginatedRequestParams(meta: $this->stampMeta(), cursor: $cursor), |
| 447: | ), |
| 448: | ListResourceTemplatesResultResponse::class, |
| 449: | )->result; |
| 450: | } |
| 451: | |
| 452: | |
| 453: | |
| 454: | |
| 455: | |
| 456: | |
| 457: | |
| 458: | public function listPrompts(?Cursor $cursor = null): ListPromptsResult |
| 459: | { |
| 460: | return $this->sendRequest( |
| 461: | new ListPromptsRequest( |
| 462: | id: $this->mintRequestId(), |
| 463: | params: new PaginatedRequestParams(meta: $this->stampMeta(), cursor: $cursor), |
| 464: | ), |
| 465: | ListPromptsResultResponse::class, |
| 466: | )->result; |
| 467: | } |
| 468: | |
| 469: | |
| 470: | |
| 471: | |
| 472: | |
| 473: | |
| 474: | |
| 475: | public function readResource(string $uri): InputRequiredResult|ReadResourceResult |
| 476: | { |
| 477: | return $this->sendRequest( |
| 478: | new ReadResourceRequest( |
| 479: | id: $this->mintRequestId(), |
| 480: | params: new ReadResourceRequestParams(uri: $uri, meta: $this->stampMeta()), |
| 481: | ), |
| 482: | ReadResourceResultResponse::class, |
| 483: | )->result; |
| 484: | } |
| 485: | |
| 486: | |
| 487: | |
| 488: | |
| 489: | |
| 490: | |
| 491: | |
| 492: | |
| 493: | |
| 494: | public function getPrompt(string $name, ?array $arguments = null): GetPromptResult|InputRequiredResult |
| 495: | { |
| 496: | return $this->sendRequest( |
| 497: | new GetPromptRequest( |
| 498: | id: $this->mintRequestId(), |
| 499: | params: new GetPromptRequestParams(name: $name, meta: $this->stampMeta(), arguments: $arguments), |
| 500: | ), |
| 501: | GetPromptResultResponse::class, |
| 502: | )->result; |
| 503: | } |
| 504: | |
| 505: | |
| 506: | |
| 507: | |
| 508: | |
| 509: | |
| 510: | |
| 511: | |
| 512: | |
| 513: | |
| 514: | public function complete( |
| 515: | PromptReference|ResourceTemplateReference $ref, |
| 516: | array $argument, |
| 517: | ?array $context = null, |
| 518: | ): CompleteResult { |
| 519: | return $this->sendRequest( |
| 520: | new CompleteRequest( |
| 521: | id: $this->mintRequestId(), |
| 522: | params: new CompleteRequestParams( |
| 523: | ref: $ref, |
| 524: | argument: $argument, |
| 525: | meta: $this->stampMeta(), |
| 526: | context: $context, |
| 527: | ), |
| 528: | ), |
| 529: | CompleteResultResponse::class, |
| 530: | )->result; |
| 531: | } |
| 532: | |
| 533: | |
| 534: | |
| 535: | |
| 536: | |
| 537: | |
| 538: | |
| 539: | |
| 540: | |
| 541: | |
| 542: | |
| 543: | |
| 544: | |
| 545: | |
| 546: | |
| 547: | |
| 548: | |
| 549: | |
| 550: | |
| 551: | |
| 552: | |
| 553: | public function callTool( |
| 554: | string $name, |
| 555: | ?array $arguments = null, |
| 556: | ?\Closure $onProgress = null, |
| 557: | ?array $inputResponses = null, |
| 558: | ?string $requestState = null, |
| 559: | ): CallToolResult|InputRequiredResult { |
| 560: | try { |
| 561: | return $this->attemptToolCall($name, $arguments, $onProgress, $inputResponses, $requestState); |
| 562: | } catch (RemoteCallFailedException $e) { |
| 563: | if ($e->getCode() !== ProtocolErrorCode::HeaderMismatch->value) { |
| 564: | throw $e; |
| 565: | } |
| 566: | } |
| 567: | |
| 568: | |
| 569: | |
| 570: | $this->refreshToolHeaderBindings($name); |
| 571: | |
| 572: | return $this->attemptToolCall($name, $arguments, $onProgress, $inputResponses, $requestState); |
| 573: | } |
| 574: | |
| 575: | |
| 576: | |
| 577: | |
| 578: | |
| 579: | |
| 580: | |
| 581: | |
| 582: | |
| 583: | |
| 584: | |
| 585: | |
| 586: | |
| 587: | |
| 588: | |
| 589: | |
| 590: | |
| 591: | public function sendRequest( |
| 592: | JsonRpcRequest $request, |
| 593: | string $response, |
| 594: | ?SendContext $context = null, |
| 595: | ?float $timeout = null, |
| 596: | ): JsonRpcResultResponse { |
| 597: | return $this->dispatch($request, $response, $context, $this->openDeadline($timeout)); |
| 598: | } |
| 599: | |
| 600: | |
| 601: | |
| 602: | |
| 603: | |
| 604: | |
| 605: | |
| 606: | private function openStream(OpenSubscription $subscription, TransportInterface $transport): void |
| 607: | { |
| 608: | $id = $subscription->subscriptionId; |
| 609: | |
| 610: | |
| 611: | $response = $this->outboundRequests->register($id, SubscriptionsListenResultResponse::class); |
| 612: | |
| 613: | $response |
| 614: | ->map(function (SubscriptionsListenResultResponse $response) use ($id): void { |
| 615: | |
| 616: | $this->subscriptions->forget($id)?->outcome->complete($response->result); |
| 617: | }) |
| 618: | ->catch(function (\Throwable $e) use ($id, $transport): void { |
| 619: | |
| 620: | |
| 621: | |
| 622: | if ($transport instanceof ReconnectingTransportInterface && $transport->isReconnecting()) { |
| 623: | return; |
| 624: | } |
| 625: | |
| 626: | $this->subscriptions->forget($id)?->outcome->error($e); |
| 627: | }) |
| 628: | ->ignore() |
| 629: | ; |
| 630: | |
| 631: | try { |
| 632: | $transport->send(new SubscriptionsListenRequest( |
| 633: | id: $id, |
| 634: | params: new SubscriptionsListenRequestParams( |
| 635: | notifications: $subscription->notifications, |
| 636: | meta: $this->stampMeta(), |
| 637: | ), |
| 638: | )); |
| 639: | } catch (\Throwable $e) { |
| 640: | $this->outboundRequests->forget($id); |
| 641: | |
| 642: | throw $e; |
| 643: | } |
| 644: | } |
| 645: | |
| 646: | |
| 647: | |
| 648: | |
| 649: | |
| 650: | |
| 651: | |
| 652: | private function retainsAcrossRestart(JsonRpcRequest $request): bool |
| 653: | { |
| 654: | if (! $this->retryLostRequests) { |
| 655: | return false; |
| 656: | } |
| 657: | |
| 658: | $method = $request::getMethod(); |
| 659: | |
| 660: | foreach (self::RETRYABLE_REQUESTS as $retryable) { |
| 661: | if ($retryable::getMethod() === $method) { |
| 662: | |
| 663: | |
| 664: | |
| 665: | return ! self::resumesAnEarlierRound($request->params); |
| 666: | } |
| 667: | } |
| 668: | |
| 669: | return false; |
| 670: | } |
| 671: | |
| 672: | |
| 673: | |
| 674: | |
| 675: | private static function resumesAnEarlierRound(?RequestParamsInterface $params): bool |
| 676: | { |
| 677: | [$inputResponses, $requestState] = match (true) { |
| 678: | $params instanceof InputResponseRequestParams => [$params->inputResponses, $params->requestState], |
| 679: | $params instanceof ReadResourceRequestParams => [$params->inputResponses, $params->requestState], |
| 680: | default => [null, null], |
| 681: | }; |
| 682: | |
| 683: | return null !== $inputResponses || null !== $requestState; |
| 684: | } |
| 685: | |
| 686: | |
| 687: | |
| 688: | |
| 689: | |
| 690: | private static function abortExchange(TransportInterface $transport, RequestId $id): void |
| 691: | { |
| 692: | if ($transport instanceof AbortableTransportInterface) { |
| 693: | $transport->abort($id); |
| 694: | } |
| 695: | } |
| 696: | |
| 697: | |
| 698: | |
| 699: | |
| 700: | private function settleSubscriptions(\Throwable $reason): void |
| 701: | { |
| 702: | foreach ($this->subscriptions->drain() as $subscription) { |
| 703: | $subscription->outcome->error($reason); |
| 704: | } |
| 705: | } |
| 706: | |
| 707: | |
| 708: | |
| 709: | |
| 710: | |
| 711: | private function refreshToolHeaderBindings(string $name): void |
| 712: | { |
| 713: | $cursor = null; |
| 714: | |
| 715: | do { |
| 716: | $page = $this->listTools($cursor); |
| 717: | |
| 718: | foreach ($page->tools as $tool) { |
| 719: | if ($tool->name === $name) { |
| 720: | return; |
| 721: | } |
| 722: | } |
| 723: | |
| 724: | $cursor = $page->nextCursor; |
| 725: | } while (null !== $cursor); |
| 726: | } |
| 727: | |
| 728: | |
| 729: | |
| 730: | |
| 731: | |
| 732: | |
| 733: | |
| 734: | |
| 735: | private function attemptToolCall( |
| 736: | string $name, |
| 737: | ?array $arguments, |
| 738: | ?\Closure $onProgress, |
| 739: | ?array $inputResponses = null, |
| 740: | ?string $requestState = null, |
| 741: | ): CallToolResult|InputRequiredResult { |
| 742: | $context = new SendContext(headers: $this->mirrorParameterHeaders($name, $arguments)); |
| 743: | |
| 744: | if (null === $onProgress) { |
| 745: | return $this->sendRequest( |
| 746: | new CallToolRequest( |
| 747: | id: $this->mintRequestId(), |
| 748: | params: new CallToolRequestParams( |
| 749: | name: $name, |
| 750: | meta: $this->stampMeta(), |
| 751: | arguments: $arguments, |
| 752: | inputResponses: $inputResponses, |
| 753: | requestState: $requestState, |
| 754: | ), |
| 755: | ), |
| 756: | CallToolResultResponse::class, |
| 757: | $context, |
| 758: | )->result; |
| 759: | } |
| 760: | |
| 761: | $progressToken = $this->mintProgressToken(); |
| 762: | |
| 763: | |
| 764: | |
| 765: | $deadline = $this->openDeadline(); |
| 766: | |
| 767: | try { |
| 768: | |
| 769: | $this->progressListeners->register( |
| 770: | $progressToken, |
| 771: | static function (float $progress, ?float $total, ?string $message) use ($onProgress, $deadline): void { |
| 772: | $deadline?->extend(); |
| 773: | $onProgress($progress, $total, $message); |
| 774: | }, |
| 775: | ); |
| 776: | |
| 777: | return $this->dispatch( |
| 778: | new CallToolRequest( |
| 779: | id: $this->mintRequestId(), |
| 780: | params: new CallToolRequestParams( |
| 781: | name: $name, |
| 782: | meta: $this->stampMeta($progressToken), |
| 783: | arguments: $arguments, |
| 784: | inputResponses: $inputResponses, |
| 785: | requestState: $requestState, |
| 786: | ), |
| 787: | ), |
| 788: | CallToolResultResponse::class, |
| 789: | $context, |
| 790: | $deadline, |
| 791: | )->result; |
| 792: | } finally { |
| 793: | $deadline?->release(); |
| 794: | $this->progressListeners->unregister($progressToken); |
| 795: | } |
| 796: | } |
| 797: | |
| 798: | |
| 799: | |
| 800: | |
| 801: | |
| 802: | |
| 803: | |
| 804: | |
| 805: | |
| 806: | |
| 807: | |
| 808: | |
| 809: | |
| 810: | private function dispatch( |
| 811: | JsonRpcRequest $request, |
| 812: | string $response, |
| 813: | ?SendContext $context, |
| 814: | ?RequestDeadline $deadline, |
| 815: | ): JsonRpcResultResponse { |
| 816: | try { |
| 817: | try { |
| 818: | return $this->exchange($request, $response, $context, $deadline); |
| 819: | } catch (RemoteCallFailedException $e) { |
| 820: | |
| 821: | |
| 822: | $retry = $this->renegotiateProtocolVersion($request, $e); |
| 823: | |
| 824: | if (null === $retry) { |
| 825: | throw $e; |
| 826: | } |
| 827: | |
| 828: | $this->logger->info( |
| 829: | 'Retrying request {id} as {retry}: the server does not support {requested}.', |
| 830: | ['id' => $request->id->id, 'retry' => $retry->id->id, 'requested' => $e->error->message], |
| 831: | ); |
| 832: | |
| 833: | return $this->exchange($retry, $response, $context, $deadline); |
| 834: | } |
| 835: | } finally { |
| 836: | $deadline?->release(); |
| 837: | } |
| 838: | } |
| 839: | |
| 840: | |
| 841: | |
| 842: | |
| 843: | |
| 844: | |
| 845: | |
| 846: | |
| 847: | |
| 848: | |
| 849: | |
| 850: | |
| 851: | |
| 852: | |
| 853: | |
| 854: | |
| 855: | private function exchange( |
| 856: | JsonRpcRequest $request, |
| 857: | string $response, |
| 858: | ?SendContext $context, |
| 859: | ?RequestDeadline $deadline, |
| 860: | ): JsonRpcResultResponse { |
| 861: | $transport = $this->transport ?? throw new ClientNotConnectedException(); |
| 862: | |
| 863: | $this->assertServerSupports($request::getMethod()); |
| 864: | |
| 865: | $retained = $this->retainsAcrossRestart($request); |
| 866: | $future = $this->outboundRequests->register( |
| 867: | $request->id, |
| 868: | $response, |
| 869: | $retained ? $request : null, |
| 870: | $retained ? $context : null, |
| 871: | ); |
| 872: | |
| 873: | try { |
| 874: | $transport->send($request, $context); |
| 875: | } catch (\Throwable $e) { |
| 876: | |
| 877: | |
| 878: | $this->outboundRequests->forget($request->id); |
| 879: | |
| 880: | throw $e; |
| 881: | } |
| 882: | |
| 883: | if (null === $deadline) { |
| 884: | return $future->await(); |
| 885: | } |
| 886: | |
| 887: | try { |
| 888: | return $future->await($deadline->getCancellation()); |
| 889: | } catch (CancelledException $e) { |
| 890: | throw $this->abandon($request, $transport, $deadline, $e); |
| 891: | } |
| 892: | } |
| 893: | |
| 894: | |
| 895: | |
| 896: | |
| 897: | |
| 898: | |
| 899: | |
| 900: | |
| 901: | |
| 902: | |
| 903: | |
| 904: | private function renegotiateProtocolVersion(JsonRpcRequest $request, RemoteCallFailedException $failure): ?JsonRpcRequest |
| 905: | { |
| 906: | $error = $failure->error; |
| 907: | |
| 908: | if (! $error instanceof UnsupportedProtocolVersionError) { |
| 909: | return null; |
| 910: | } |
| 911: | |
| 912: | $version = self::pickSupportedVersion($error->supported); |
| 913: | |
| 914: | if (null === $version) { |
| 915: | return null; |
| 916: | } |
| 917: | |
| 918: | $params = $request->params; |
| 919: | |
| 920: | if (! $params instanceof RequestParams) { |
| 921: | |
| 922: | return null; |
| 923: | } |
| 924: | |
| 925: | $meta = $params->meta->toArray(); |
| 926: | $meta[RequestMetaObject::PROTOCOL_VERSION_KEY] = $version; |
| 927: | |
| 928: | $fields = $params->toArray(); |
| 929: | $fields['_meta'] = $meta; |
| 930: | |
| 931: | $envelope = $request->toArray(); |
| 932: | $envelope['params'] = $fields; |
| 933: | |
| 934: | |
| 935: | $envelope['id'] = $this->mintRequestId()->id; |
| 936: | |
| 937: | return $request::fromArray($envelope); |
| 938: | } |
| 939: | |
| 940: | |
| 941: | |
| 942: | |
| 943: | |
| 944: | |
| 945: | private static function pickSupportedVersion(array $supported): ?string |
| 946: | { |
| 947: | foreach ($supported as $version) { |
| 948: | if (\in_array($version, ProtocolVersion::SUPPORTED_VERSIONS, true)) { |
| 949: | return $version; |
| 950: | } |
| 951: | } |
| 952: | |
| 953: | return null; |
| 954: | } |
| 955: | |
| 956: | |
| 957: | |
| 958: | |
| 959: | |
| 960: | |
| 961: | |
| 962: | private function abandon( |
| 963: | JsonRpcRequest $request, |
| 964: | TransportInterface $transport, |
| 965: | RequestDeadline $deadline, |
| 966: | CancelledException $cause, |
| 967: | ): RequestTimeoutException { |
| 968: | $this->outboundRequests->forget($request->id); |
| 969: | self::abortExchange($transport, $request->id); |
| 970: | |
| 971: | try { |
| 972: | $transport->send(new CancelledNotification( |
| 973: | params: new CancelledNotificationParams(requestId: $request->id, reason: 'The request timed out.'), |
| 974: | )); |
| 975: | } catch (\Throwable $e) { |
| 976: | |
| 977: | $this->logger->warning( |
| 978: | 'Could not tell the server that request {id} was abandoned.', |
| 979: | ['id' => $request->id->id, 'exception' => $e], |
| 980: | ); |
| 981: | } |
| 982: | |
| 983: | return new RequestTimeoutException($request->id, $deadline->elapsed, $cause); |
| 984: | } |
| 985: | |
| 986: | |
| 987: | |
| 988: | |
| 989: | private function openDeadline(?float $timeout = null): ?RequestDeadline |
| 990: | { |
| 991: | $timeout ??= $this->requestTimeout; |
| 992: | |
| 993: | return null === $timeout ? null : new RequestDeadline($timeout, $this->maxRequestTimeout); |
| 994: | } |
| 995: | |
| 996: | |
| 997: | |
| 998: | |
| 999: | |
| 1000: | private function admitMirrorableTools(ListToolsResult $result): ListToolsResult |
| 1001: | { |
| 1002: | $admitted = []; |
| 1003: | |
| 1004: | foreach ($result->tools as $tool) { |
| 1005: | $scan = ParameterHeaderScanner::scan($tool->inputSchema); |
| 1006: | |
| 1007: | if (! $scan->valid) { |
| 1008: | |
| 1009: | |
| 1010: | unset($this->toolHeaderBindings[$tool->name]); |
| 1011: | |
| 1012: | $this->logger->warning( |
| 1013: | 'Excluding tool {tool} from the listing: its "x-mcp-header" declarations are invalid.', |
| 1014: | ['tool' => $tool->name, 'reason' => $scan->reason], |
| 1015: | ); |
| 1016: | |
| 1017: | continue; |
| 1018: | } |
| 1019: | |
| 1020: | $this->toolHeaderBindings[$tool->name] = $scan->bindings; |
| 1021: | $admitted[] = $tool; |
| 1022: | } |
| 1023: | |
| 1024: | return $admitted === $result->tools ? $result : new ListToolsResult( |
| 1025: | tools: $admitted, |
| 1026: | ttlMs: $result->ttlMs, |
| 1027: | cacheScope: $result->cacheScope, |
| 1028: | nextCursor: $result->nextCursor, |
| 1029: | meta: $result->meta, |
| 1030: | ); |
| 1031: | } |
| 1032: | |
| 1033: | |
| 1034: | |
| 1035: | |
| 1036: | |
| 1037: | |
| 1038: | |
| 1039: | |
| 1040: | |
| 1041: | private function mirrorParameterHeaders(string $name, ?array $arguments): array |
| 1042: | { |
| 1043: | |
| 1044: | return ParameterHeaders::build($this->toolHeaderBindings[$name] ?? [], $arguments ?? []); |
| 1045: | } |
| 1046: | |
| 1047: | |
| 1048: | |
| 1049: | |
| 1050: | private function stampMeta(?ProgressToken $progressToken = null): RequestMetaObject |
| 1051: | { |
| 1052: | return new RequestMetaObject( |
| 1053: | protocolVersion: $this->protocolVersion, |
| 1054: | clientInfo: $this->clientInfo, |
| 1055: | clientCapabilities: $this->clientCapabilities, |
| 1056: | progressToken: $progressToken, |
| 1057: | ); |
| 1058: | } |
| 1059: | |
| 1060: | |
| 1061: | |
| 1062: | |
| 1063: | private function assertServerSupports(string $method): void |
| 1064: | { |
| 1065: | $capabilities = $this->serverCapabilities; |
| 1066: | |
| 1067: | if (null === $capabilities) { |
| 1068: | |
| 1069: | return; |
| 1070: | } |
| 1071: | |
| 1072: | $supported = match ($method) { |
| 1073: | ListToolsRequest::getMethod(), CallToolRequest::getMethod() => null !== $capabilities->tools, |
| 1074: | ListResourcesRequest::getMethod(), |
| 1075: | ListResourceTemplatesRequest::getMethod(), |
| 1076: | ReadResourceRequest::getMethod() => null !== $capabilities->resources, |
| 1077: | ListPromptsRequest::getMethod(), GetPromptRequest::getMethod() => null !== $capabilities->prompts, |
| 1078: | CompleteRequest::getMethod() => null !== $capabilities->completions, |
| 1079: | default => true, |
| 1080: | }; |
| 1081: | |
| 1082: | if (! $supported) { |
| 1083: | throw new ServerCapabilityNotSupportedException($method); |
| 1084: | } |
| 1085: | } |
| 1086: | |
| 1087: | private function mintRequestId(): RequestId |
| 1088: | { |
| 1089: | return new RequestId(id: ($this->requestIdFactory)()); |
| 1090: | } |
| 1091: | |
| 1092: | private function mintProgressToken(): ProgressToken |
| 1093: | { |
| 1094: | return new ProgressToken(token: ($this->progressTokenFactory)()); |
| 1095: | } |
| 1096: | } |
| 1097: | |