Repository navigation
Expand file tree
/
Copy pathBuilder.php
More file actions
1291 lines (1109 loc) · 47.1 KB
/
Copy pathBuilder.php
File metadata and controls
1291 lines (1109 loc) · 47.1 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
/*
* 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\Server;
use Mcp\Schema\Annotations;
use Mcp\Schema\Enum\ProtocolVersion;
use Mcp\Schema\Extension\AbstractExtension;
use Mcp\Schema\Extension\ExtensionInterface;
use Mcp\Schema\Icon;
use Mcp\Schema\Implementation;
use Mcp\Schema\MessageFactory;
use Mcp\Schema\Prompt;
use Mcp\Schema\Request\DiscoverRequest;
use Mcp\Schema\ResourceDefinition;
use Mcp\Schema\ResourceTemplate;
use Mcp\Schema\ServerCapabilities;
use Mcp\Schema\Tool;
use Mcp\Schema\ToolAnnotations;
use Mcp\Server\Capability\Completion\ProviderInterface;
use Mcp\Server\Capability\Discovery\CachedDiscoverer;
use Mcp\Server\Capability\Discovery\Discoverer;
use Mcp\Server\Capability\Discovery\DiscovererInterface;
use Mcp\Server\Capability\Discovery\SchemaGeneratorInterface;
use Mcp\Server\Capability\Discovery\SchemaValidator;
use Mcp\Server\Capability\Registry;
use Mcp\Server\Capability\Registry\Container;
use Mcp\Server\Capability\Registry\ElementReference;
use Mcp\Server\Capability\Registry\Loader\ChainLoader;
use Mcp\Server\Capability\Registry\Loader\DiscoveryLoader;
use Mcp\Server\Capability\Registry\Loader\ExplicitElementLoader;
use Mcp\Server\Capability\Registry\Loader\LoaderInterface;
use Mcp\Server\Capability\Registry\Loader\ReflectedElementLoader;
use Mcp\Server\Capability\Registry\ReferenceHandler;
use Mcp\Server\Capability\Registry\ReferenceHandlerInterface;
use Mcp\Server\Capability\RegistryInterface;
use Mcp\Server\Exception\InvalidArgumentException;
use Mcp\Server\Exception\LogicException;
use Mcp\Server\Extension\ServerExtensionInterface;
use Mcp\Server\Fiber\FiberContextInterface;
use Mcp\Server\Fiber\FiberSchedulerInterface;
use Mcp\Server\Handler\ElementHandlerInterface;
use Mcp\Server\Handler\Notification\NotificationHandlerInterface;
use Mcp\Server\Handler\PromptHandlerInterface;
use Mcp\Server\Handler\Request\RequestHandlerInterface;
use Mcp\Server\Handler\ResourceHandlerInterface;
use Mcp\Server\Handler\ResourceTemplateHandlerInterface;
use Mcp\Server\Handler\ToolHandlerInterface;
use Mcp\Server\Resource\SessionSubscriptionManager;
use Mcp\Server\Resource\SubscriptionManagerInterface;
use Mcp\Server\Session\InMemorySessionStore;
use Mcp\Server\Session\SessionLockInterface;
use Mcp\Server\Session\SessionManager;
use Mcp\Server\Session\SessionManagerInterface;
use Mcp\Server\Session\SessionStoreInterface;
use Mcp\Server\Stateless\RequestStateBinderInterface;
use Mcp\Server\Stateless\RequestStateCodec;
use Mcp\Server\Stateless\StandardHeaderValidator;
use Mcp\Server\Stateless\StatelessProtocol;
use Mcp\Server\Subscription\InMemoryNotificationBus;
use Mcp\Server\Subscription\NotificationBusInterface;
use Mcp\Server\Subscription\Psr16NotificationBus;
use Mcp\Server\Subscription\Psr6NotificationBus;
use Mcp\Server\Subscription\PublishingEventDispatcher;
use Mcp\Server\Wire\CachePolicy;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Container\ContainerInterface;
use Psr\EventDispatcher\EventDispatcherInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Psr\SimpleCache\CacheInterface;
/**
* @phpstan-import-type Handler from ElementReference
*
* @phpstan-type AssembledParts array{
* logger: LoggerInterface,
* eventDispatcher: ?EventDispatcherInterface,
* configuration: Configuration,
* messageFactory: MessageFactory,
* modernMessageFactory: MessageFactory,
* sessionManager: SessionManagerInterface,
* registry: RegistryInterface,
* requestHandlers: list<RequestHandlerInterface<mixed>>,
* notificationHandlers: list<NotificationHandlerInterface>,
* }
*
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
*/
final class Builder
{
private ?Implementation $serverInfo = null;
private RegistryInterface $registry;
private ?SubscriptionManagerInterface $subscriptionManager = null;
private ?LoggerInterface $logger = null;
private CacheInterface|CacheItemPoolInterface|null $discoveryCache = null;
private ?EventDispatcherInterface $eventDispatcher = null;
private ?ContainerInterface $container = null;
private ?SchemaGeneratorInterface $schemaGenerator = null;
private ?SchemaValidator $schemaValidator = null;
private ?ReferenceHandlerInterface $referenceHandler = null;
private ?DiscovererInterface $discoverer = null;
private ?SessionManagerInterface $sessionManager = null;
private ?SessionStoreInterface $sessionStore = null;
private ?SessionLockInterface $sessionLock = null;
private int $gcProbability = 1;
private int $gcDivisor = 100;
private int $paginationLimit = 50;
private ?string $instructions = null;
private ?ProtocolVersion $protocolVersion = null;
private ?CachePolicy $cachePolicy = null;
private ?NotificationBusInterface $notificationBus = null;
private float $subscriptionLifetime = 30.0;
private ?FiberSchedulerInterface $fiberScheduler = null;
private ?FiberContextInterface $fiberContext = null;
/** @var array<string, string> RPC method to the extension identifier defining it */
private array $extensionMethods = [];
/** @var list<class-string<\Mcp\Schema\JsonRpc\Request>|class-string<\Mcp\Schema\JsonRpc\Notification>> */
private array $extensionMessages = [];
/** @var string|list<string>|null */
private string|array|null $requestStateKey = null;
private int $requestStateTtl = 600;
private ?RequestStateBinderInterface $requestStateBinder = null;
/**
* @var array<int, RequestHandlerInterface<mixed>>
*/
private array $requestHandlers = [];
/**
* @var array<int, NotificationHandlerInterface>
*/
private array $notificationHandlers = [];
/**
* @var array{
* handler: Handler,
* name: ?string,
* title: ?string,
* description: ?string,
* annotations: ?ToolAnnotations,
* inputSchema: ?array<string, mixed>,
* icons: ?Icon[],
* meta: ?array<string, mixed>,
* outputSchema: ?array<string, mixed>,
* }[]
*/
private array $tools = [];
/**
* @var array{
* handler: Handler,
* uri: string,
* name: ?string,
* title: ?string,
* description: ?string,
* mimeType: ?string,
* size: int|null,
* annotations: ?Annotations,
* icons: ?Icon[],
* meta: ?array<string, mixed>
* }[]
*/
private array $resources = [];
/**
* @var array{
* handler: Handler,
* uriTemplate: string,
* name: ?string,
* title: ?string,
* description: ?string,
* mimeType: ?string,
* annotations: ?Annotations,
* meta: ?array<string, mixed>
* }[]
*/
private array $resourceTemplates = [];
/**
* @var array{
* handler: Handler,
* name: ?string,
* title: ?string,
* description: ?string,
* icons: ?Icon[],
* meta: ?array<string, mixed>
* }[]
*/
private array $prompts = [];
/**
* @var list<array{definition: Tool, handler: ToolHandlerInterface}>
*/
private array $explicitTools = [];
/**
* @var list<array{definition: ResourceDefinition, handler: ResourceHandlerInterface}>
*/
private array $explicitResources = [];
/**
* @var list<array{definition: ResourceTemplate, handler: ResourceTemplateHandlerInterface, completionProviders: array<string, ProviderInterface>}>
*/
private array $explicitResourceTemplates = [];
/**
* @var list<array{definition: Prompt, handler: PromptHandlerInterface, completionProviders: array<string, ProviderInterface>}>
*/
private array $explicitPrompts = [];
private ?string $discoveryBasePath = null;
/**
* @var string[]
*/
private array $discoveryScanDirs = [];
/**
* @var array|string[]
*/
private array $discoveryExcludeDirs = [];
/**
* @var string[]
*/
private array $discoveryNamePatterns = DiscovererInterface::DEFAULT_NAME_PATERNS;
private ?ServerCapabilities $serverCapabilities = null;
/**
* @var array<string, array<string, mixed>>
*/
private array $extensions = [];
/**
* @var LoaderInterface[]
*/
private array $loaders = [];
private bool $hasCustomRegistry = false;
private bool $lazyLoading = true;
private bool $headerValidation = true;
/** @var list<ProtocolVersion>|null null defaults to every modern revision, [] serves none */
private ?array $modernVersions = null;
private bool $inputRequiredShim = true;
private int $inputRequiredRounds = InputRequiredShim::DEFAULT_MAX_ROUNDS;
private int $inputRequiredTimeout = InputRequiredShim::DEFAULT_ROUND_TIMEOUT;
private bool $sessions = false;
/**
* @see self::assemble() for why this is memoized
*
* @var AssembledParts|null
*/
private ?array $parts = null;
/**
* Sets the server's identity. Required.
*
* @param ?Icon[] $icons
* @param ?string $title Display name for UI and end-user contexts. Falls back to $name when absent.
*/
public function setServerInfo(
string $name,
string $version,
?string $description = null,
?array $icons = null,
?string $websiteUrl = null,
?string $title = null,
): self {
$this->serverInfo = new Implementation(trim($name), trim($version), $description, $icons, $websiteUrl, $title);
return $this;
}
/**
* Sets the bus carrying server-initiated notifications to open
* `subscriptions/listen` streams (SEP-2575).
*
* Without one, a listen stream acknowledges and then carries nothing: there
* is no safe default, because the right implementation depends on whether
* the publisher and the stream share a process.
* {@see InMemoryNotificationBus} is correct for stdio and persistent
* runtimes; under PHP-FPM, where they are different workers, use
* {@see Psr6NotificationBus}, {@see Psr16NotificationBus} or an
* implementation over your own broker.
*
* With the built-in registry, registry changes are published automatically,
* with or without an event dispatcher, and `listChanged` is announced. A
* registry passed with setRegistry() is announced only if
* {@see RegistryInterface::publishesListChanges()} says so, as {@see Registry}
* does with a {@see PublishingEventDispatcher}.
* Anything else, `notifications/resources/updated` for example, is
* published by the application calling {@see NotificationBusInterface::publish()}.
*/
public function setNotificationBus(NotificationBusInterface $bus): self
{
$this->notificationBus = $bus;
return $this;
}
/**
* Sets how long a `subscriptions/listen` stream is held open before the
* server closes it gracefully.
*
* The real ceiling is the runtime's: under PHP-FPM a stream cannot outlive
* `request_terminate_timeout` once that is set, and a value above it buys a
* killed worker instead of a longer subscription. `max_execution_time`
* counts CPU time in a non-thread-safe build on Linux and does not end a
* waiting stream; a thread-safe build counts elapsed time, by default since
* PHP 8.3, and does. Pass `0` for "until the client or the runtime ends
* it", which is what a persistent runtime wants.
*/
public function setSubscriptionLifetime(float $seconds): self
{
$this->subscriptionLifetime = max(0.0, $seconds);
return $this;
}
/**
* Sets the runtime that may suspend a request handler's fiber besides the server: an event loop.
*
* The server runs every request handler in a fiber, to let it wait on the client. Under an event
* loop — Revolt (AMPHP), ReactPHP's async — a handler awaiting I/O suspends that fiber for the loop:
* the server then waits through this scheduler until the handler suspends for the server again or
* returns, instead of resuming the fiber itself. Without one, such a handler fails the request.
*/
public function setFiberScheduler(FiberSchedulerInterface $scheduler): self
{
$this->fiberScheduler = $scheduler;
return $this;
}
/**
* Carries execution context, e.g. the active OpenTelemetry context, into the fibers request handlers run in.
*/
public function setFiberContext(FiberContextInterface $context): self
{
$this->fiberContext = $context;
return $this;
}
/**
* Sets how long, and to whom, this server's answers may be cached (SEP-2549).
*
* The modern lifecycle must put `ttlMs` and `cacheScope` on every cacheable
* result; without a policy it says "private, immediately stale", which is
* conformant and forfeits the point. Build one with
* {@see CachePolicy::default()} and narrow it per method:
*
* ```php
* $builder->setCachePolicy(
* CachePolicy::default(60_000)
* ->withMethod('tools/list', 3_600_000, CacheScope::Public),
* );
* ```
*/
public function setCachePolicy(CachePolicy $policy): self
{
$this->cachePolicy = $policy;
return $this;
}
/**
* Sets the key signing the `requestState` carried across the rounds of a
* multi round-trip request (SEP-2322). Without one, every echoed state is
* refused.
*
* The same key must reach every instance that might serve the retry, so a
* per-process random value only works for a single-process deployment.
*
* A list of keys is a key ring: the first key signs, every key verifies.
* To rotate across several instances, first add the new key behind the
* current one everywhere, `[$current, $new]`, so every instance accepts it
* before any signs with it. Then move it to the front, `[$new, $current]`,
* and remove the old key one TTL after the last instance stopped signing
* with it. See docs/handlers/input-required.md, "Rotating the key".
*
* A binder ties every state the modern era mints to the request it was
* minted for, e.g. {@see Stateless\OriginatingRequestBinder} to the
* principal, method and arguments: a state echoed on a request that binds
* to another value fails verification like a forged one. States minted
* before a binder was configured no longer verify, so adding one fails the
* multi round-trip calls in flight for at most the TTL.
*
* @param string|list<string> $key the signing key or key ring, each key at least 32 bytes
* @param int $ttl how long a minted state stays valid, in seconds
* @param RequestStateBinderInterface|null $binder binds each state to its originating request
*/
public function setRequestState(string|array $key, int $ttl = 600, ?RequestStateBinderInterface $binder = null): self
{
$this->requestStateKey = $key;
$this->requestStateTtl = $ttl;
$this->requestStateBinder = $binder;
return $this;
}
/**
* Configures the server's pagination limit.
*/
public function setPaginationLimit(int $paginationLimit): self
{
$this->paginationLimit = $paginationLimit;
return $this;
}
/**
* Configures the instructions describing how to use the server and its features.
*
* This can be used by clients to improve the LLM's understanding of available tools, resources,
* etc. It can be thought of like a "hint" to the model. For example, this information MAY
* be added to the system prompt.
*/
public function setInstructions(?string $instructions): self
{
$this->instructions = $instructions;
return $this;
}
/**
* Explicitly set server capabilities. If set, this overrides automatic detection.
*
* A `listChanged` flag set here is announced on `server/discover` only; the
* `initialize` handshake has no way to deliver list changes.
*/
public function setCapabilities(ServerCapabilities $serverCapabilities): self
{
$this->serverCapabilities = $serverCapabilities;
return $this;
}
/**
* Enable one or more MCP protocol extensions, announced to clients under
* `capabilities.extensions` during the initialize handshake.
*
* An extension also contributes the message classes its methods decode
* into, and a {@see ServerExtensionInterface} the handlers serving them — see
* {@see AbstractExtension} for extensions that only announce a capability.
*
* @throws InvalidArgumentException if the identifier is not a valid `_meta` prefix
* @throws LogicException if the same extension is enabled more than once, or
* two enabled extensions define the same RPC method
*/
public function enableExtension(ExtensionInterface ...$extensions): self
{
foreach ($extensions as $extension) {
$id = (string) $extension->getId();
if (isset($this->extensions[$id])) {
throw new LogicException(\sprintf('Extension "%s" is already enabled.', $id));
}
$this->extensions[$id] = $extension->getCapabilities();
// Without this the method cannot be decoded at all, so nothing
// downstream ever sees it.
foreach ($extension->getMessages() as $message) {
$method = $message::getMethod();
// The message factory resolves a method to whichever class was
// registered first, so a second owner here would silently lose
// the dispatch race while still being named in error messages.
if (isset($this->extensionMethods[$method]) && $this->extensionMethods[$method] !== $id) {
throw new LogicException(\sprintf('Method "%s" is already claimed by extension "%s", so extension "%s" cannot also define it.', $method, $this->extensionMethods[$method], $id));
}
$this->extensionMessages[] = $message;
// Recorded even though the handler answers it, so a server with
// the extension *off* can say so instead of "no such method".
$this->extensionMethods[$method] = $id;
}
if ($extension instanceof ServerExtensionInterface) {
foreach ($extension->getRequestHandlers() as $handler) {
$this->requestHandlers[] = $handler;
}
}
}
return $this;
}
/**
* Register a single custom method handler.
*
* @param RequestHandlerInterface<mixed> $handler
*/
public function addRequestHandler(RequestHandlerInterface $handler): self
{
$this->requestHandlers[] = $handler;
return $this;
}
/**
* Register multiple custom method handlers.
*
* @param iterable<RequestHandlerInterface<mixed>> $handlers
*/
public function addRequestHandlers(iterable $handlers): self
{
foreach ($handlers as $handler) {
$this->requestHandlers[] = $handler;
}
return $this;
}
/**
* Register a single custom notification handler.
*/
public function addNotificationHandler(NotificationHandlerInterface $handler): self
{
$this->notificationHandlers[] = $handler;
return $this;
}
/**
* Register multiple custom notification handlers.
*
* @param iterable<int, NotificationHandlerInterface> $handlers
*/
public function addNotificationHandlers(iterable $handlers): self
{
foreach ($handlers as $handler) {
$this->notificationHandlers[] = $handler;
}
return $this;
}
public function setRegistry(RegistryInterface $registry): self
{
$this->registry = $registry;
$this->hasCustomRegistry = true;
return $this;
}
/**
* Controls when configured loaders (manual elements, discovery, custom loaders) run.
*
* Lazy (the default) defers loading to the first registry read so a persistent runtime does not
* freeze the registry to a source not yet ready at build time. Disable to load eagerly at build.
* A registry supplied via setRegistry() is always loaded eagerly; its own constructor loader,
* if it has one, still runs on the first read.
*/
public function setLazyLoading(bool $lazyLoading = true): self
{
$this->lazyLoading = $lazyLoading;
return $this;
}
/**
* Controls whether {@see self::buildStateless()} checks the standard MCP
* request headers (SEP-2243) against the JSON-RPC body. On by default.
*
* Disable for a `StatelessProtocol` served by a transport with no header
* layer — the validator would otherwise reject every request for
* carrying none of the standard headers.
*/
public function setHeaderValidator(bool $headerValidation = true): self
{
$this->headerValidation = $headerValidation;
return $this;
}
/**
* Provides a PSR-3 logger instance. Defaults to NullLogger.
*/
public function setLogger(LoggerInterface $logger): self
{
$this->logger = $logger;
return $this;
}
public function setEventDispatcher(EventDispatcherInterface $eventDispatcher): self
{
$this->eventDispatcher = $eventDispatcher;
return $this;
}
/**
* Provides a PSR-11 DI container, primarily for resolving user-defined handler classes.
* Defaults to a basic internal container.
*/
public function setContainer(ContainerInterface $container): self
{
$this->container = $container;
return $this;
}
public function setSchemaGenerator(SchemaGeneratorInterface $schemaGenerator): self
{
$this->schemaGenerator = $schemaGenerator;
return $this;
}
public function setSchemaValidator(SchemaValidator $schemaValidator): self
{
$this->schemaValidator = $schemaValidator;
return $this;
}
public function setReferenceHandler(ReferenceHandlerInterface $referenceHandler): self
{
$this->referenceHandler = $referenceHandler;
return $this;
}
public function setDiscoverer(DiscovererInterface $discoverer): self
{
$this->discoverer = $discoverer;
return $this;
}
public function setResourceSubscriptionManager(SubscriptionManagerInterface $subscriptionManager): self
{
$this->subscriptionManager = $subscriptionManager;
return $this;
}
/**
* Turns on sessions for handshake-era clients over Streamable HTTP and configures them.
*
* Without it, these clients are served without sessions: `initialize` gets no `Mcp-Session-Id`,
* every later request runs on an {@see Session\EphemeralSession}, `GET` and `DELETE` get `405`,
* and what needs a session fails loud (see `docs/run/sessions.md`). Stdio keeps its one session
* in memory either way.
*
* @param int $gcProbability The numerator of the GC probability fraction (like PHP's session.gc_probability). Set to 0 to disable GC.
* @param int $gcDivisor The denominator of the GC probability fraction (like PHP's session.gc_divisor). Probability = gcProbability/gcDivisor.
*/
public function setSession(
?SessionStoreInterface $sessionStore = null,
?SessionManagerInterface $sessionManager = null,
int $gcProbability = 1,
int $gcDivisor = 100,
): self {
$this->sessions = true;
$this->sessionStore = $sessionStore;
$this->sessionManager = $sessionManager;
$this->gcProbability = $gcProbability;
$this->gcDivisor = $gcDivisor;
if (null !== $sessionManager && null !== $sessionStore) {
throw new InvalidArgumentException('Cannot set both SessionStore and SessionManager. Set only one or the other.');
}
return $this;
}
/**
* Serializes the requests of one session, so two of them running at the same time
* cannot overwrite each other's changes to the session. Off by default.
*
* Pair the lock with the store: {@see Session\FileSessionLock} for {@see Session\FileSessionStore},
* {@see Session\SymfonyLockSessionLock} for a store shared across machines like {@see Session\Psr16SessionStore}.
*/
public function setSessionLock(SessionLockInterface $sessionLock): self
{
$this->sessionLock = $sessionLock;
return $this;
}
/**
* @param string[] $scanDirs
* @param string[] $excludeDirs
* @param string[] $namePatterns
*/
public function setDiscovery(
string $basePath,
array $scanDirs = ['.', 'src'],
array $excludeDirs = [],
CacheInterface|CacheItemPoolInterface|null $cache = null,
array $namePatterns = DiscovererInterface::DEFAULT_NAME_PATERNS,
): self {
$this->discoveryBasePath = $basePath;
$this->discoveryScanDirs = $scanDirs;
$this->discoveryExcludeDirs = $excludeDirs;
$this->discoveryCache = $cache;
$this->discoveryNamePatterns = $namePatterns;
return $this;
}
public function setProtocolVersion(ProtocolVersion $protocolVersion): self
{
$this->protocolVersion = $protocolVersion;
return $this;
}
/**
* Manually registers a tool handler.
*
* @param Handler $handler
* @param ?string $title Optional human-readable title for display in UI
* @param array<string, mixed>|null $inputSchema
* @param ?Icon[] $icons
* @param array<string, mixed>|null $meta
* @param array<string, mixed>|null $outputSchema
*/
public function addTool(
callable|array|string $handler,
?string $name = null,
?string $title = null,
?string $description = null,
?ToolAnnotations $annotations = null,
?array $inputSchema = null,
?array $icons = null,
?array $meta = null,
?array $outputSchema = null,
): self {
$this->tools[] = compact(
'handler',
'name',
'title',
'description',
'annotations',
'inputSchema',
'icons',
'meta',
'outputSchema',
);
return $this;
}
/**
* Manually registers a resource handler.
*
* @param Handler $handler
* @param ?string $title Optional human-readable title for display in UI
* @param ?Icon[] $icons
* @param array<string, mixed>|null $meta
*/
public function addResource(
\Closure|array|string $handler,
string $uri,
?string $name = null,
?string $title = null,
?string $description = null,
?string $mimeType = null,
?int $size = null,
?Annotations $annotations = null,
?array $icons = null,
?array $meta = null,
): self {
$this->resources[] = compact(
'handler',
'uri',
'name',
'title',
'description',
'mimeType',
'size',
'annotations',
'icons',
'meta',
);
return $this;
}
/**
* Manually registers a resource template handler.
*
* @param Handler $handler
* @param ?string $title Optional human-readable title for display in UI
* @param array<string, mixed>|null $meta
*/
public function addResourceTemplate(
\Closure|array|string $handler,
string $uriTemplate,
?string $name = null,
?string $title = null,
?string $description = null,
?string $mimeType = null,
?Annotations $annotations = null,
?array $meta = null,
): self {
$this->resourceTemplates[] = compact(
'handler',
'uriTemplate',
'name',
'title',
'description',
'mimeType',
'annotations',
'meta',
);
return $this;
}
/**
* Manually registers a prompt handler.
*
* @param Handler $handler
* @param ?Icon[] $icons
* @param array<string, mixed>|null $meta
*/
public function addPrompt(
\Closure|array|string $handler,
?string $name = null,
?string $title = null,
?string $description = null,
?array $icons = null,
?array $meta = null,
): self {
$this->prompts[] = compact('handler', 'name', 'title', 'description', 'icons', 'meta');
return $this;
}
/**
* Registers an element using an explicit schema value object paired with a handler interface.
*
* Use this entry point when an element's name, schema, or description is only known at
* runtime (e.g. config-driven integrations). For statically-known elements, prefer
* `addTool/addResource/addResourceTemplate/addPrompt`, which can derive metadata from
* reflection of the handler.
*
* Mismatched pairings (e.g. a `Tool` with a `PromptHandlerInterface`) raise
* `Mcp\Server\Exception\InvalidArgumentException`. Completion providers are only supported on
* `Prompt` and `ResourceTemplate` definitions; supplying them with `Tool` or
* `ResourceDefinition` raises the same exception.
*
* @param array<string, ProviderInterface> $completionProviders Keyed by argument/variable name
*/
public function add(
Tool|ResourceDefinition|ResourceTemplate|Prompt $definition,
ElementHandlerInterface $handler,
array $completionProviders = [],
): self {
if ([] !== $completionProviders && ($definition instanceof Tool || $definition instanceof ResourceDefinition)) {
throw new InvalidArgumentException(\sprintf('Completion providers are only supported on Prompt and ResourceTemplate definitions, got %s.', $definition::class));
}
match (true) {
$definition instanceof Tool && $handler instanceof ToolHandlerInterface => $this->explicitTools[] = ['definition' => $definition, 'handler' => $handler],
$definition instanceof ResourceDefinition && $handler instanceof ResourceHandlerInterface => $this->explicitResources[] = ['definition' => $definition, 'handler' => $handler],
$definition instanceof ResourceTemplate && $handler instanceof ResourceTemplateHandlerInterface => $this->explicitResourceTemplates[] = ['definition' => $definition, 'handler' => $handler, 'completionProviders' => $completionProviders],
$definition instanceof Prompt && $handler instanceof PromptHandlerInterface => $this->explicitPrompts[] = ['definition' => $definition, 'handler' => $handler, 'completionProviders' => $completionProviders],
default => throw new InvalidArgumentException(\sprintf('%s definition cannot be paired with %s; expected the matching handler interface.', $definition::class, $handler::class)),
};
return $this;
}
/**
* Register a single custom loader.
*/
public function addLoader(LoaderInterface $loader): self
{
$this->loaders[] = $loader;
return $this;
}
/**
* @param iterable<LoaderInterface> $loaders
*/
public function addLoaders(iterable $loaders): self
{
foreach ($loaders as $loader) {
$this->loaders[] = $loader;
}
return $this;
}
/**
* Stop serving multi round-trip handlers to handshake-era clients.
*
* A handler that returns an {@see \Mcp\Schema\Result\InputRequiredResult}
* is written for the modern era, where the client answers the embedded
* requests and retries the call. On a handshake-era connection the SDK
* fulfils it instead, by sending those requests over that connection's own
* channel and re-entering the handler with the answers — so one handler
* serves both eras. See {@see InputRequiredShim} for what re-entry costs.
*
* Turn it off to have such a handler fail on a handshake-era connection
* rather than be fulfilled behind your back.
*/
public function withoutInputRequiredShim(): self
{
$this->inputRequiredShim = false;
return $this;
}
/**
* Bounds on the shim's loop: how many times a handler may be re-entered for
* one request, and how long one answer is waited for.
*
* The wait holds the originating request open, so on a process-per-request
* runtime it holds a worker too. Size it against your pool, not against a
* user's patience.
*/
public function setInputRequiredLimits(int $maxRounds, int $roundTimeout): self
{
if ($maxRounds < 1) {
throw new InvalidArgumentException('maxRounds must be at least 1.');
}
if ($roundTimeout < 1) {
throw new InvalidArgumentException('roundTimeout must be at least 1 second.');
}
$this->inputRequiredRounds = $maxRounds;
$this->inputRequiredTimeout = $roundTimeout;
return $this;
}
private function requestStateCodec(): ?RequestStateCodec
{
return null !== $this->requestStateKey
? new RequestStateCodec($this->requestStateKey, $this->requestStateTtl)
: null;
}
/**
* Serve only the handshake era, refusing modern-era traffic.
*
* The default is to serve both from whatever the server is run on, because
* an endpoint that turns a client away for speaking the newer revision is
* almost never what anyone wants. Call this when it is: a deployment that
* has to stay on the handshake wire, or one whose tools call back into the
* client and would fail the modern half anyway.
*/
public function withoutModernEra(): self
{